Merge "Remove not used private member variable mParserWarnings from OutputPage"
[mediawiki.git] / includes / EditPage.php
blob47912cb8c2c3f09b07184b777dcdcf0e3b998e62
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: an error relating to change tagging. Look at the message key for
161 * more details
163 const AS_CHANGE_TAG_ERROR = 237;
166 * Status: can't parse content
168 const AS_PARSE_ERROR = 240;
171 * Status: when changing the content model is disallowed due to
172 * $wgContentHandlerUseDB being false
174 const AS_CANNOT_USE_CUSTOM_MODEL = 241;
177 * HTML id and name for the beginning of the edit form.
179 const EDITFORM_ID = 'editform';
182 * Prefix of key for cookie used to pass post-edit state.
183 * The revision id edited is added after this
185 const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
188 * Duration of PostEdit cookie, in seconds.
189 * The cookie will be removed instantly if the JavaScript runs.
191 * Otherwise, though, we don't want the cookies to accumulate.
192 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
193 * limit of only 20 cookies per domain. This still applies at least to some
194 * versions of IE without full updates:
195 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
197 * A value of 20 minutes should be enough to take into account slow loads and minor
198 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
200 const POST_EDIT_COOKIE_DURATION = 1200;
202 /** @var Article */
203 public $mArticle;
204 /** @var WikiPage */
205 private $page;
207 /** @var Title */
208 public $mTitle;
210 /** @var null|Title */
211 private $mContextTitle = null;
213 /** @var string */
214 public $action = 'submit';
216 /** @var bool */
217 public $isConflict = false;
219 /** @var bool */
220 public $isCssJsSubpage = false;
222 /** @var bool */
223 public $isCssSubpage = false;
225 /** @var bool */
226 public $isJsSubpage = false;
228 /** @var bool */
229 public $isWrongCaseCssJsPage = false;
231 /** @var bool New page or new section */
232 public $isNew = false;
234 /** @var bool */
235 public $deletedSinceEdit;
237 /** @var string */
238 public $formtype;
240 /** @var bool */
241 public $firsttime;
243 /** @var bool|stdClass */
244 public $lastDelete;
246 /** @var bool */
247 public $mTokenOk = false;
249 /** @var bool */
250 public $mTokenOkExceptSuffix = false;
252 /** @var bool */
253 public $mTriedSave = false;
255 /** @var bool */
256 public $incompleteForm = false;
258 /** @var bool */
259 public $tooBig = false;
261 /** @var bool */
262 public $kblength = false;
264 /** @var bool */
265 public $missingComment = false;
267 /** @var bool */
268 public $missingSummary = false;
270 /** @var bool */
271 public $allowBlankSummary = false;
273 /** @var bool */
274 protected $blankArticle = false;
276 /** @var bool */
277 protected $allowBlankArticle = false;
279 /** @var bool */
280 protected $selfRedirect = false;
282 /** @var bool */
283 protected $allowSelfRedirect = false;
285 /** @var string */
286 public $autoSumm = '';
288 /** @var string */
289 public $hookError = '';
291 /** @var ParserOutput */
292 public $mParserOutput;
294 /** @var bool Has a summary been preset using GET parameter &summary= ? */
295 public $hasPresetSummary = false;
297 /** @var bool */
298 public $mBaseRevision = false;
300 /** @var bool */
301 public $mShowSummaryField = true;
303 # Form values
305 /** @var bool */
306 public $save = false;
308 /** @var bool */
309 public $preview = false;
311 /** @var bool */
312 public $diff = false;
314 /** @var bool */
315 public $minoredit = false;
317 /** @var bool */
318 public $watchthis = false;
320 /** @var bool */
321 public $recreate = false;
323 /** @var string */
324 public $textbox1 = '';
326 /** @var string */
327 public $textbox2 = '';
329 /** @var string */
330 public $summary = '';
332 /** @var bool */
333 public $nosummary = false;
335 /** @var string */
336 public $edittime = '';
338 /** @var string */
339 public $section = '';
341 /** @var string */
342 public $sectiontitle = '';
344 /** @var string */
345 public $starttime = '';
347 /** @var int */
348 public $oldid = 0;
350 /** @var int */
351 public $parentRevId = 0;
353 /** @var string */
354 public $editintro = '';
356 /** @var null */
357 public $scrolltop = null;
359 /** @var bool */
360 public $bot = true;
362 /** @var null|string */
363 public $contentModel = null;
365 /** @var null|string */
366 public $contentFormat = null;
368 /** @var null|array */
369 public $changeTags = null;
371 # Placeholders for text injection by hooks (must be HTML)
372 # extensions should take care to _append_ to the present value
374 /** @var string Before even the preview */
375 public $editFormPageTop = '';
376 public $editFormTextTop = '';
377 public $editFormTextBeforeContent = '';
378 public $editFormTextAfterWarn = '';
379 public $editFormTextAfterTools = '';
380 public $editFormTextBottom = '';
381 public $editFormTextAfterContent = '';
382 public $previewTextAfterContent = '';
383 public $mPreloadContent = null;
385 /* $didSave should be set to true whenever an article was successfully altered. */
386 public $didSave = false;
387 public $undidRev = 0;
389 public $suppressIntro = false;
391 /** @var bool */
392 protected $edit;
395 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
397 private $enableApiEditOverride = false;
400 * @param Article $article
402 public function __construct( Article $article ) {
403 $this->mArticle = $article;
404 $this->page = $article->getPage(); // model object
405 $this->mTitle = $article->getTitle();
407 $this->contentModel = $this->mTitle->getContentModel();
409 $handler = ContentHandler::getForModelID( $this->contentModel );
410 $this->contentFormat = $handler->getDefaultFormat();
414 * @return Article
416 public function getArticle() {
417 return $this->mArticle;
421 * @since 1.19
422 * @return Title
424 public function getTitle() {
425 return $this->mTitle;
429 * Set the context Title object
431 * @param Title|null $title Title object or null
433 public function setContextTitle( $title ) {
434 $this->mContextTitle = $title;
438 * Get the context title object.
439 * If not set, $wgTitle will be returned. This behavior might change in
440 * the future to return $this->mTitle instead.
442 * @return Title
444 public function getContextTitle() {
445 if ( is_null( $this->mContextTitle ) ) {
446 global $wgTitle;
447 return $wgTitle;
448 } else {
449 return $this->mContextTitle;
454 * Returns if the given content model is editable.
456 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
457 * @return bool
458 * @throws MWException If $modelId has no known handler
460 public function isSupportedContentModel( $modelId ) {
461 return $this->enableApiEditOverride === true ||
462 ContentHandler::getForModelID( $modelId )->supportsDirectEditing();
466 * Allow editing of content that supports API direct editing, but not general
467 * direct editing. Set to false by default.
469 * @param bool $enableOverride
471 public function setApiEditOverride( $enableOverride ) {
472 $this->enableApiEditOverride = $enableOverride;
475 function submit() {
476 $this->edit();
480 * This is the function that gets called for "action=edit". It
481 * sets up various member variables, then passes execution to
482 * another function, usually showEditForm()
484 * The edit form is self-submitting, so that when things like
485 * preview and edit conflicts occur, we get the same form back
486 * with the extra stuff added. Only when the final submission
487 * is made and all is well do we actually save and redirect to
488 * the newly-edited page.
490 function edit() {
491 global $wgOut, $wgRequest, $wgUser;
492 // Allow extensions to modify/prevent this form or submission
493 if ( !Hooks::run( 'AlternateEdit', array( $this ) ) ) {
494 return;
497 wfDebug( __METHOD__ . ": enter\n" );
499 // If they used redlink=1 and the page exists, redirect to the main article
500 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
501 $wgOut->redirect( $this->mTitle->getFullURL() );
502 return;
505 $this->importFormData( $wgRequest );
506 $this->firsttime = false;
508 if ( wfReadOnly() && $this->save ) {
509 // Force preview
510 $this->save = false;
511 $this->preview = true;
514 if ( $this->save ) {
515 $this->formtype = 'save';
516 } elseif ( $this->preview ) {
517 $this->formtype = 'preview';
518 } elseif ( $this->diff ) {
519 $this->formtype = 'diff';
520 } else { # First time through
521 $this->firsttime = true;
522 if ( $this->previewOnOpen() ) {
523 $this->formtype = 'preview';
524 } else {
525 $this->formtype = 'initial';
529 $permErrors = $this->getEditPermissionErrors( $this->save ? 'secure' : 'full' );
530 if ( $permErrors ) {
531 wfDebug( __METHOD__ . ": User can't edit\n" );
532 // Auto-block user's IP if the account was "hard" blocked
533 $user = $wgUser;
534 DeferredUpdates::addCallableUpdate( function() use ( $user ) {
535 $user->spreadAnyEditBlock();
536 } );
538 $this->displayPermissionsError( $permErrors );
540 return;
543 $revision = $this->mArticle->getRevisionFetched();
544 // Disallow editing revisions with content models different from the current one
545 if ( $revision && $revision->getContentModel() !== $this->contentModel ) {
546 $this->displayViewSourcePage(
547 $this->getContentObject(),
548 wfMessage(
549 'contentmodelediterror',
550 $revision->getContentModel(),
551 $this->contentModel
552 )->plain()
554 return;
557 $this->isConflict = false;
558 // css / js subpages of user pages get a special treatment
559 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
560 $this->isCssSubpage = $this->mTitle->isCssSubpage();
561 $this->isJsSubpage = $this->mTitle->isJsSubpage();
562 // @todo FIXME: Silly assignment.
563 $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
565 # Show applicable editing introductions
566 if ( $this->formtype == 'initial' || $this->firsttime ) {
567 $this->showIntro();
570 # Attempt submission here. This will check for edit conflicts,
571 # and redundantly check for locked database, blocked IPs, etc.
572 # that edit() already checked just in case someone tries to sneak
573 # in the back door with a hand-edited submission URL.
575 if ( 'save' == $this->formtype ) {
576 $resultDetails = null;
577 $status = $this->attemptSave( $resultDetails );
578 if ( !$this->handleStatus( $status, $resultDetails ) ) {
579 return;
583 # First time through: get contents, set time for conflict
584 # checking, etc.
585 if ( 'initial' == $this->formtype || $this->firsttime ) {
586 if ( $this->initialiseForm() === false ) {
587 $this->noSuchSectionPage();
588 return;
591 if ( !$this->mTitle->getArticleID() ) {
592 Hooks::run( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
593 } else {
594 Hooks::run( 'EditFormInitialText', array( $this ) );
599 $this->showEditForm();
603 * @param string $rigor Same format as Title::getUserPermissionErrors()
604 * @return array
606 protected function getEditPermissionErrors( $rigor = 'secure' ) {
607 global $wgUser;
609 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
610 # Can this title be created?
611 if ( !$this->mTitle->exists() ) {
612 $permErrors = array_merge(
613 $permErrors,
614 wfArrayDiff2(
615 $this->mTitle->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
616 $permErrors
620 # Ignore some permissions errors when a user is just previewing/viewing diffs
621 $remove = array();
622 foreach ( $permErrors as $error ) {
623 if ( ( $this->preview || $this->diff )
624 && ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' )
626 $remove[] = $error;
629 $permErrors = wfArrayDiff2( $permErrors, $remove );
631 return $permErrors;
635 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
636 * but with the following differences:
637 * - If redlink=1, the user will be redirected to the page
638 * - If there is content to display or the error occurs while either saving,
639 * previewing or showing the difference, it will be a
640 * "View source for ..." page displaying the source code after the error message.
642 * @since 1.19
643 * @param array $permErrors Array of permissions errors, as returned by
644 * Title::getUserPermissionsErrors().
645 * @throws PermissionsError
647 protected function displayPermissionsError( array $permErrors ) {
648 global $wgRequest, $wgOut;
650 if ( $wgRequest->getBool( 'redlink' ) ) {
651 // The edit page was reached via a red link.
652 // Redirect to the article page and let them click the edit tab if
653 // they really want a permission error.
654 $wgOut->redirect( $this->mTitle->getFullURL() );
655 return;
658 $content = $this->getContentObject();
660 # Use the normal message if there's nothing to display
661 if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
662 $action = $this->mTitle->exists() ? 'edit' :
663 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
664 throw new PermissionsError( $action, $permErrors );
667 $this->displayViewSourcePage(
668 $content,
669 $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' )
674 * Display a read-only View Source page
675 * @param Content $content content object
676 * @param string $errorMessage additional wikitext error message to display
678 protected function displayViewSourcePage( Content $content, $errorMessage = '' ) {
679 global $wgOut;
681 Hooks::run( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
683 $wgOut->setRobotPolicy( 'noindex,nofollow' );
684 $wgOut->setPageTitle( wfMessage(
685 'viewsource-title',
686 $this->getContextTitle()->getPrefixedText()
687 ) );
688 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
689 $wgOut->addHTML( $this->editFormPageTop );
690 $wgOut->addHTML( $this->editFormTextTop );
692 if ( $errorMessage !== '' ) {
693 $wgOut->addWikiText( $errorMessage );
694 $wgOut->addHTML( "<hr />\n" );
697 # If the user made changes, preserve them when showing the markup
698 # (This happens when a user is blocked during edit, for instance)
699 if ( !$this->firsttime ) {
700 $text = $this->textbox1;
701 $wgOut->addWikiMsg( 'viewyourtext' );
702 } else {
703 try {
704 $text = $this->toEditText( $content );
705 } catch ( MWException $e ) {
706 # Serialize using the default format if the content model is not supported
707 # (e.g. for an old revision with a different model)
708 $text = $content->serialize();
710 $wgOut->addWikiMsg( 'viewsourcetext' );
713 $wgOut->addHTML( $this->editFormTextBeforeContent );
714 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
715 $wgOut->addHTML( $this->editFormTextAfterContent );
717 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
718 Linker::formatTemplates( $this->getTemplates() ) ) );
720 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
722 $wgOut->addHTML( $this->editFormTextBottom );
723 if ( $this->mTitle->exists() ) {
724 $wgOut->returnToMain( null, $this->mTitle );
729 * Should we show a preview when the edit form is first shown?
731 * @return bool
733 protected function previewOnOpen() {
734 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
735 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
736 // Explicit override from request
737 return true;
738 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
739 // Explicit override from request
740 return false;
741 } elseif ( $this->section == 'new' ) {
742 // Nothing *to* preview for new sections
743 return false;
744 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() )
745 && $wgUser->getOption( 'previewonfirst' )
747 // Standard preference behavior
748 return true;
749 } elseif ( !$this->mTitle->exists()
750 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
751 && $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]
753 // Categories are special
754 return true;
755 } else {
756 return false;
761 * Checks whether the user entered a skin name in uppercase,
762 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
764 * @return bool
766 protected function isWrongCaseCssJsPage() {
767 if ( $this->mTitle->isCssJsSubpage() ) {
768 $name = $this->mTitle->getSkinFromCssJsSubpage();
769 $skins = array_merge(
770 array_keys( Skin::getSkinNames() ),
771 array( 'common' )
773 return !in_array( $name, $skins )
774 && in_array( strtolower( $name ), $skins );
775 } else {
776 return false;
781 * Returns whether section editing is supported for the current page.
782 * Subclasses may override this to replace the default behavior, which is
783 * to check ContentHandler::supportsSections.
785 * @return bool True if this edit page supports sections, false otherwise.
787 protected function isSectionEditSupported() {
788 $contentHandler = ContentHandler::getForTitle( $this->mTitle );
789 return $contentHandler->supportsSections();
793 * This function collects the form data and uses it to populate various member variables.
794 * @param WebRequest $request
795 * @throws ErrorPageError
797 function importFormData( &$request ) {
798 global $wgContLang, $wgUser;
800 # Section edit can come from either the form or a link
801 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
803 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
804 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
807 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
809 if ( $request->wasPosted() ) {
810 # These fields need to be checked for encoding.
811 # Also remove trailing whitespace, but don't remove _initial_
812 # whitespace from the text boxes. This may be significant formatting.
813 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
814 if ( !$request->getCheck( 'wpTextbox2' ) ) {
815 // Skip this if wpTextbox2 has input, it indicates that we came
816 // from a conflict page with raw page text, not a custom form
817 // modified by subclasses
818 $textbox1 = $this->importContentFormData( $request );
819 if ( $textbox1 !== null ) {
820 $this->textbox1 = $textbox1;
824 # Truncate for whole multibyte characters
825 $this->summary = $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
827 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
828 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
829 # section titles.
830 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
832 # Treat sectiontitle the same way as summary.
833 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
834 # currently doing double duty as both edit summary and section title. Right now this
835 # is just to allow API edits to work around this limitation, but this should be
836 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
837 $this->sectiontitle = $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
838 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
840 $this->edittime = $request->getVal( 'wpEdittime' );
841 $this->starttime = $request->getVal( 'wpStarttime' );
843 $undidRev = $request->getInt( 'wpUndidRevision' );
844 if ( $undidRev ) {
845 $this->undidRev = $undidRev;
848 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
850 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
851 // wpTextbox1 field is missing, possibly due to being "too big"
852 // according to some filter rules such as Suhosin's setting for
853 // suhosin.request.max_value_length (d'oh)
854 $this->incompleteForm = true;
855 } else {
856 // If we receive the last parameter of the request, we can fairly
857 // claim the POST request has not been truncated.
859 // TODO: softened the check for cutover. Once we determine
860 // that it is safe, we should complete the transition by
861 // removing the "edittime" clause.
862 $this->incompleteForm = ( !$request->getVal( 'wpUltimateParam' )
863 && is_null( $this->edittime ) );
865 if ( $this->incompleteForm ) {
866 # If the form is incomplete, force to preview.
867 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
868 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
869 $this->preview = true;
870 } else {
871 $this->preview = $request->getCheck( 'wpPreview' );
872 $this->diff = $request->getCheck( 'wpDiff' );
874 // Remember whether a save was requested, so we can indicate
875 // if we forced preview due to session failure.
876 $this->mTriedSave = !$this->preview;
878 if ( $this->tokenOk( $request ) ) {
879 # Some browsers will not report any submit button
880 # if the user hits enter in the comment box.
881 # The unmarked state will be assumed to be a save,
882 # if the form seems otherwise complete.
883 wfDebug( __METHOD__ . ": Passed token check.\n" );
884 } elseif ( $this->diff ) {
885 # Failed token check, but only requested "Show Changes".
886 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
887 } else {
888 # Page might be a hack attempt posted from
889 # an external site. Preview instead of saving.
890 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
891 $this->preview = true;
894 $this->save = !$this->preview && !$this->diff;
895 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
896 $this->edittime = null;
899 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
900 $this->starttime = null;
903 $this->recreate = $request->getCheck( 'wpRecreate' );
905 $this->minoredit = $request->getCheck( 'wpMinoredit' );
906 $this->watchthis = $request->getCheck( 'wpWatchthis' );
908 # Don't force edit summaries when a user is editing their own user or talk page
909 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
910 && $this->mTitle->getText() == $wgUser->getName()
912 $this->allowBlankSummary = true;
913 } else {
914 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
915 || !$wgUser->getOption( 'forceeditsummary' );
918 $this->autoSumm = $request->getText( 'wpAutoSummary' );
920 $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
921 $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
923 $changeTags = $request->getVal( 'wpChangeTags' );
924 if ( is_null( $changeTags ) || $changeTags === '' ) {
925 $this->changeTags = array();
926 } else {
927 $this->changeTags = array_filter( array_map( 'trim', explode( ',',
928 $changeTags ) ) );
930 } else {
931 # Not a posted form? Start with nothing.
932 wfDebug( __METHOD__ . ": Not a posted form.\n" );
933 $this->textbox1 = '';
934 $this->summary = '';
935 $this->sectiontitle = '';
936 $this->edittime = '';
937 $this->starttime = wfTimestampNow();
938 $this->edit = false;
939 $this->preview = false;
940 $this->save = false;
941 $this->diff = false;
942 $this->minoredit = false;
943 // Watch may be overridden by request parameters
944 $this->watchthis = $request->getBool( 'watchthis', false );
945 $this->recreate = false;
947 // When creating a new section, we can preload a section title by passing it as the
948 // preloadtitle parameter in the URL (Bug 13100)
949 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
950 $this->sectiontitle = $request->getVal( 'preloadtitle' );
951 // Once wpSummary isn't being use for setting section titles, we should delete this.
952 $this->summary = $request->getVal( 'preloadtitle' );
953 } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
954 $this->summary = $request->getText( 'summary' );
955 if ( $this->summary !== '' ) {
956 $this->hasPresetSummary = true;
960 if ( $request->getVal( 'minor' ) ) {
961 $this->minoredit = true;
965 $this->oldid = $request->getInt( 'oldid' );
966 $this->parentRevId = $request->getInt( 'parentRevId' );
968 $this->bot = $request->getBool( 'bot', true );
969 $this->nosummary = $request->getBool( 'nosummary' );
971 // May be overridden by revision.
972 $this->contentModel = $request->getText( 'model', $this->contentModel );
973 // May be overridden by revision.
974 $this->contentFormat = $request->getText( 'format', $this->contentFormat );
976 if ( !ContentHandler::getForModelID( $this->contentModel )
977 ->isSupportedFormat( $this->contentFormat )
979 throw new ErrorPageError(
980 'editpage-notsupportedcontentformat-title',
981 'editpage-notsupportedcontentformat-text',
982 array( $this->contentFormat, ContentHandler::getLocalizedName( $this->contentModel ) )
987 * @todo Check if the desired model is allowed in this namespace, and if
988 * a transition from the page's current model to the new model is
989 * allowed.
992 $this->editintro = $request->getText( 'editintro',
993 // Custom edit intro for new sections
994 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
996 // Allow extensions to modify form data
997 Hooks::run( 'EditPage::importFormData', array( $this, $request ) );
1002 * Subpage overridable method for extracting the page content data from the
1003 * posted form to be placed in $this->textbox1, if using customized input
1004 * this method should be overridden and return the page text that will be used
1005 * for saving, preview parsing and so on...
1007 * @param WebRequest $request
1008 * @return string|null
1010 protected function importContentFormData( &$request ) {
1011 return; // Don't do anything, EditPage already extracted wpTextbox1
1015 * Initialise form fields in the object
1016 * Called on the first invocation, e.g. when a user clicks an edit link
1017 * @return bool If the requested section is valid
1019 function initialiseForm() {
1020 global $wgUser;
1021 $this->edittime = $this->page->getTimestamp();
1023 $content = $this->getContentObject( false ); # TODO: track content object?!
1024 if ( $content === false ) {
1025 return false;
1027 $this->textbox1 = $this->toEditText( $content );
1029 // activate checkboxes if user wants them to be always active
1030 # Sort out the "watch" checkbox
1031 if ( $wgUser->getOption( 'watchdefault' ) ) {
1032 # Watch all edits
1033 $this->watchthis = true;
1034 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1035 # Watch creations
1036 $this->watchthis = true;
1037 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
1038 # Already watched
1039 $this->watchthis = true;
1041 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
1042 $this->minoredit = true;
1044 if ( $this->textbox1 === false ) {
1045 return false;
1047 return true;
1051 * @param Content|null $def_content The default value to return
1053 * @return Content|null Content on success, $def_content for invalid sections
1055 * @since 1.21
1057 protected function getContentObject( $def_content = null ) {
1058 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1060 $content = false;
1062 // For message page not locally set, use the i18n message.
1063 // For other non-existent articles, use preload text if any.
1064 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
1065 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
1066 # If this is a system message, get the default text.
1067 $msg = $this->mTitle->getDefaultMessageText();
1069 $content = $this->toEditContent( $msg );
1071 if ( $content === false ) {
1072 # If requested, preload some text.
1073 $preload = $wgRequest->getVal( 'preload',
1074 // Custom preload text for new sections
1075 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
1076 $params = $wgRequest->getArray( 'preloadparams', array() );
1078 $content = $this->getPreloadedContent( $preload, $params );
1080 // For existing pages, get text based on "undo" or section parameters.
1081 } else {
1082 if ( $this->section != '' ) {
1083 // Get section edit text (returns $def_text for invalid sections)
1084 $orig = $this->getOriginalContent( $wgUser );
1085 $content = $orig ? $orig->getSection( $this->section ) : null;
1087 if ( !$content ) {
1088 $content = $def_content;
1090 } else {
1091 $undoafter = $wgRequest->getInt( 'undoafter' );
1092 $undo = $wgRequest->getInt( 'undo' );
1094 if ( $undo > 0 && $undoafter > 0 ) {
1095 $undorev = Revision::newFromId( $undo );
1096 $oldrev = Revision::newFromId( $undoafter );
1098 # Sanity check, make sure it's the right page,
1099 # the revisions exist and they were not deleted.
1100 # Otherwise, $content will be left as-is.
1101 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1102 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1103 !$oldrev->isDeleted( Revision::DELETED_TEXT )
1105 $content = $this->page->getUndoContent( $undorev, $oldrev );
1107 if ( $content === false ) {
1108 # Warn the user that something went wrong
1109 $undoMsg = 'failure';
1110 } else {
1111 $oldContent = $this->page->getContent( Revision::RAW );
1112 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
1113 $newContent = $content->preSaveTransform( $this->mTitle, $wgUser, $popts );
1115 if ( $newContent->equals( $oldContent ) ) {
1116 # Tell the user that the undo results in no change,
1117 # i.e. the revisions were already undone.
1118 $undoMsg = 'nochange';
1119 $content = false;
1120 } else {
1121 # Inform the user of our success and set an automatic edit summary
1122 $undoMsg = 'success';
1124 # If we just undid one rev, use an autosummary
1125 $firstrev = $oldrev->getNext();
1126 if ( $firstrev && $firstrev->getId() == $undo ) {
1127 $userText = $undorev->getUserText();
1128 if ( $userText === '' ) {
1129 $undoSummary = wfMessage(
1130 'undo-summary-username-hidden',
1131 $undo
1132 )->inContentLanguage()->text();
1133 } else {
1134 $undoSummary = wfMessage(
1135 'undo-summary',
1136 $undo,
1137 $userText
1138 )->inContentLanguage()->text();
1140 if ( $this->summary === '' ) {
1141 $this->summary = $undoSummary;
1142 } else {
1143 $this->summary = $undoSummary . wfMessage( 'colon-separator' )
1144 ->inContentLanguage()->text() . $this->summary;
1146 $this->undidRev = $undo;
1148 $this->formtype = 'diff';
1151 } else {
1152 // Failed basic sanity checks.
1153 // Older revisions may have been removed since the link
1154 // was created, or we may simply have got bogus input.
1155 $undoMsg = 'norev';
1158 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1159 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1160 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
1161 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1164 if ( $content === false ) {
1165 $content = $this->getOriginalContent( $wgUser );
1170 return $content;
1174 * Get the content of the wanted revision, without section extraction.
1176 * The result of this function can be used to compare user's input with
1177 * section replaced in its context (using WikiPage::replaceSection())
1178 * to the original text of the edit.
1180 * This differs from Article::getContent() that when a missing revision is
1181 * encountered the result will be null and not the
1182 * 'missing-revision' message.
1184 * @since 1.19
1185 * @param User $user The user to get the revision for
1186 * @return Content|null
1188 private function getOriginalContent( User $user ) {
1189 if ( $this->section == 'new' ) {
1190 return $this->getCurrentContent();
1192 $revision = $this->mArticle->getRevisionFetched();
1193 if ( $revision === null ) {
1194 if ( !$this->contentModel ) {
1195 $this->contentModel = $this->getTitle()->getContentModel();
1197 $handler = ContentHandler::getForModelID( $this->contentModel );
1199 return $handler->makeEmptyContent();
1201 $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1202 return $content;
1206 * Get the edit's parent revision ID
1208 * The "parent" revision is the ancestor that should be recorded in this
1209 * page's revision history. It is either the revision ID of the in-memory
1210 * article content, or in the case of a 3-way merge in order to rebase
1211 * across a recoverable edit conflict, the ID of the newer revision to
1212 * which we have rebased this page.
1214 * @since 1.27
1215 * @return int Revision ID
1217 public function getParentRevId() {
1218 if ( $this->parentRevId ) {
1219 return $this->parentRevId;
1220 } else {
1221 return $this->mArticle->getRevIdFetched();
1226 * Get the current content of the page. This is basically similar to
1227 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1228 * content object is returned instead of null.
1230 * @since 1.21
1231 * @return Content
1233 protected function getCurrentContent() {
1234 $rev = $this->page->getRevision();
1235 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1237 if ( $content === false || $content === null ) {
1238 if ( !$this->contentModel ) {
1239 $this->contentModel = $this->getTitle()->getContentModel();
1241 $handler = ContentHandler::getForModelID( $this->contentModel );
1243 return $handler->makeEmptyContent();
1244 } else {
1245 # nasty side-effect, but needed for consistency
1246 $this->contentModel = $rev->getContentModel();
1247 $this->contentFormat = $rev->getContentFormat();
1249 return $content;
1254 * Use this method before edit() to preload some content into the edit box
1256 * @param Content $content
1258 * @since 1.21
1260 public function setPreloadedContent( Content $content ) {
1261 $this->mPreloadContent = $content;
1265 * Get the contents to be preloaded into the box, either set by
1266 * an earlier setPreloadText() or by loading the given page.
1268 * @param string $preload Representing the title to preload from.
1269 * @param array $params Parameters to use (interface-message style) in the preloaded text
1271 * @return Content
1273 * @since 1.21
1275 protected function getPreloadedContent( $preload, $params = array() ) {
1276 global $wgUser;
1278 if ( !empty( $this->mPreloadContent ) ) {
1279 return $this->mPreloadContent;
1282 $handler = ContentHandler::getForTitle( $this->getTitle() );
1284 if ( $preload === '' ) {
1285 return $handler->makeEmptyContent();
1288 $title = Title::newFromText( $preload );
1289 # Check for existence to avoid getting MediaWiki:Noarticletext
1290 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1291 // TODO: somehow show a warning to the user!
1292 return $handler->makeEmptyContent();
1295 $page = WikiPage::factory( $title );
1296 if ( $page->isRedirect() ) {
1297 $title = $page->getRedirectTarget();
1298 # Same as before
1299 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1300 // TODO: somehow show a warning to the user!
1301 return $handler->makeEmptyContent();
1303 $page = WikiPage::factory( $title );
1306 $parserOptions = ParserOptions::newFromUser( $wgUser );
1307 $content = $page->getContent( Revision::RAW );
1309 if ( !$content ) {
1310 // TODO: somehow show a warning to the user!
1311 return $handler->makeEmptyContent();
1314 if ( $content->getModel() !== $handler->getModelID() ) {
1315 $converted = $content->convert( $handler->getModelID() );
1317 if ( !$converted ) {
1318 // TODO: somehow show a warning to the user!
1319 wfDebug( "Attempt to preload incompatible content: " .
1320 "can't convert " . $content->getModel() .
1321 " to " . $handler->getModelID() );
1323 return $handler->makeEmptyContent();
1326 $content = $converted;
1329 return $content->preloadTransform( $title, $parserOptions, $params );
1333 * Make sure the form isn't faking a user's credentials.
1335 * @param WebRequest $request
1336 * @return bool
1337 * @private
1339 function tokenOk( &$request ) {
1340 global $wgUser;
1341 $token = $request->getVal( 'wpEditToken' );
1342 $this->mTokenOk = $wgUser->matchEditToken( $token );
1343 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1344 return $this->mTokenOk;
1348 * Sets post-edit cookie indicating the user just saved a particular revision.
1350 * This uses a temporary cookie for each revision ID so separate saves will never
1351 * interfere with each other.
1353 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1354 * the redirect. It must be clearable by JavaScript code, so it must not be
1355 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1356 * variable.
1358 * If the variable were set on the server, it would be cached, which is unwanted
1359 * since the post-edit state should only apply to the load right after the save.
1361 * @param int $statusValue The status value (to check for new article status)
1363 protected function setPostEditCookie( $statusValue ) {
1364 $revisionId = $this->page->getLatest();
1365 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1367 $val = 'saved';
1368 if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1369 $val = 'created';
1370 } elseif ( $this->oldid ) {
1371 $val = 'restored';
1374 $response = RequestContext::getMain()->getRequest()->response();
1375 $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION, array(
1376 'httpOnly' => false,
1377 ) );
1381 * Attempt submission
1382 * @param array $resultDetails See docs for $result in internalAttemptSave
1383 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1384 * @return Status The resulting status object.
1386 public function attemptSave( &$resultDetails = false ) {
1387 global $wgUser;
1389 # Allow bots to exempt some edits from bot flagging
1390 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1391 $status = $this->internalAttemptSave( $resultDetails, $bot );
1393 Hooks::run( 'EditPage::attemptSave:after', array( $this, $status, $resultDetails ) );
1395 return $status;
1399 * Handle status, such as after attempt save
1401 * @param Status $status
1402 * @param array|bool $resultDetails
1404 * @throws ErrorPageError
1405 * @return bool False, if output is done, true if rest of the form should be displayed
1407 private function handleStatus( Status $status, $resultDetails ) {
1408 global $wgUser, $wgOut;
1411 * @todo FIXME: once the interface for internalAttemptSave() is made
1412 * nicer, this should use the message in $status
1414 if ( $status->value == self::AS_SUCCESS_UPDATE
1415 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1417 $this->didSave = true;
1418 if ( !$resultDetails['nullEdit'] ) {
1419 $this->setPostEditCookie( $status->value );
1423 switch ( $status->value ) {
1424 case self::AS_HOOK_ERROR_EXPECTED:
1425 case self::AS_CONTENT_TOO_BIG:
1426 case self::AS_ARTICLE_WAS_DELETED:
1427 case self::AS_CONFLICT_DETECTED:
1428 case self::AS_SUMMARY_NEEDED:
1429 case self::AS_TEXTBOX_EMPTY:
1430 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1431 case self::AS_END:
1432 case self::AS_BLANK_ARTICLE:
1433 case self::AS_SELF_REDIRECT:
1434 return true;
1436 case self::AS_HOOK_ERROR:
1437 return false;
1439 case self::AS_CANNOT_USE_CUSTOM_MODEL:
1440 case self::AS_PARSE_ERROR:
1441 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1442 return true;
1444 case self::AS_SUCCESS_NEW_ARTICLE:
1445 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1446 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1447 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1448 return false;
1450 case self::AS_SUCCESS_UPDATE:
1451 $extraQuery = '';
1452 $sectionanchor = $resultDetails['sectionanchor'];
1454 // Give extensions a chance to modify URL query on update
1455 Hooks::run(
1456 'ArticleUpdateBeforeRedirect',
1457 array( $this->mArticle, &$sectionanchor, &$extraQuery )
1460 if ( $resultDetails['redirect'] ) {
1461 if ( $extraQuery == '' ) {
1462 $extraQuery = 'redirect=no';
1463 } else {
1464 $extraQuery = 'redirect=no&' . $extraQuery;
1467 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1468 return false;
1470 case self::AS_SPAM_ERROR:
1471 $this->spamPageWithContent( $resultDetails['spam'] );
1472 return false;
1474 case self::AS_BLOCKED_PAGE_FOR_USER:
1475 throw new UserBlockedError( $wgUser->getBlock() );
1477 case self::AS_IMAGE_REDIRECT_ANON:
1478 case self::AS_IMAGE_REDIRECT_LOGGED:
1479 throw new PermissionsError( 'upload' );
1481 case self::AS_READ_ONLY_PAGE_ANON:
1482 case self::AS_READ_ONLY_PAGE_LOGGED:
1483 throw new PermissionsError( 'edit' );
1485 case self::AS_READ_ONLY_PAGE:
1486 throw new ReadOnlyError;
1488 case self::AS_RATE_LIMITED:
1489 throw new ThrottledError();
1491 case self::AS_NO_CREATE_PERMISSION:
1492 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1493 throw new PermissionsError( $permission );
1495 case self::AS_NO_CHANGE_CONTENT_MODEL:
1496 throw new PermissionsError( 'editcontentmodel' );
1498 default:
1499 // We don't recognize $status->value. The only way that can happen
1500 // is if an extension hook aborted from inside ArticleSave.
1501 // Render the status object into $this->hookError
1502 // FIXME this sucks, we should just use the Status object throughout
1503 $this->hookError = '<div class="error">' . $status->getWikitext() .
1504 '</div>';
1505 return true;
1510 * Run hooks that can filter edits just before they get saved.
1512 * @param Content $content The Content to filter.
1513 * @param Status $status For reporting the outcome to the caller
1514 * @param User $user The user performing the edit
1516 * @return bool
1518 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1519 // Run old style post-section-merge edit filter
1520 if ( !ContentHandler::runLegacyHooks( 'EditFilterMerged',
1521 array( $this, $content, &$this->hookError, $this->summary ) )
1523 # Error messages etc. could be handled within the hook...
1524 $status->fatal( 'hookaborted' );
1525 $status->value = self::AS_HOOK_ERROR;
1526 return false;
1527 } elseif ( $this->hookError != '' ) {
1528 # ...or the hook could be expecting us to produce an error
1529 $status->fatal( 'hookaborted' );
1530 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1531 return false;
1534 // Run new style post-section-merge edit filter
1535 if ( !Hooks::run( 'EditFilterMergedContent',
1536 array( $this->mArticle->getContext(), $content, $status, $this->summary,
1537 $user, $this->minoredit ) )
1539 # Error messages etc. could be handled within the hook...
1540 if ( $status->isGood() ) {
1541 $status->fatal( 'hookaborted' );
1542 // Not setting $this->hookError here is a hack to allow the hook
1543 // to cause a return to the edit page without $this->hookError
1544 // being set. This is used by ConfirmEdit to display a captcha
1545 // without any error message cruft.
1546 } else {
1547 $this->hookError = $status->getWikiText();
1549 // Use the existing $status->value if the hook set it
1550 if ( !$status->value ) {
1551 $status->value = self::AS_HOOK_ERROR;
1553 return false;
1554 } elseif ( !$status->isOK() ) {
1555 # ...or the hook could be expecting us to produce an error
1556 // FIXME this sucks, we should just use the Status object throughout
1557 $this->hookError = $status->getWikiText();
1558 $status->fatal( 'hookaborted' );
1559 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1560 return false;
1563 return true;
1567 * Return the summary to be used for a new section.
1569 * @param string $sectionanchor Set to the section anchor text
1570 * @return string
1572 private function newSectionSummary( &$sectionanchor = null ) {
1573 global $wgParser;
1575 if ( $this->sectiontitle !== '' ) {
1576 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1577 // If no edit summary was specified, create one automatically from the section
1578 // title and have it link to the new section. Otherwise, respect the summary as
1579 // passed.
1580 if ( $this->summary === '' ) {
1581 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1582 return wfMessage( 'newsectionsummary' )
1583 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1585 } elseif ( $this->summary !== '' ) {
1586 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1587 # This is a new section, so create a link to the new section
1588 # in the revision summary.
1589 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1590 return wfMessage( 'newsectionsummary' )
1591 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1593 return $this->summary;
1597 * Attempt submission (no UI)
1599 * @param array $result Array to add statuses to, currently with the
1600 * possible keys:
1601 * - spam (string): Spam string from content if any spam is detected by
1602 * matchSpamRegex.
1603 * - sectionanchor (string): Section anchor for a section save.
1604 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1605 * false otherwise.
1606 * - redirect (bool): Set if doEditContent is OK. True if resulting
1607 * revision is a redirect.
1608 * @param bool $bot True if edit is being made under the bot right.
1610 * @return Status Status object, possibly with a message, but always with
1611 * one of the AS_* constants in $status->value,
1613 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1614 * various error display idiosyncrasies. There are also lots of cases
1615 * where error metadata is set in the object and retrieved later instead
1616 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1617 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1618 * time.
1620 function internalAttemptSave( &$result, $bot = false ) {
1621 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1622 global $wgContentHandlerUseDB;
1624 $status = Status::newGood();
1626 if ( !Hooks::run( 'EditPage::attemptSave', array( $this ) ) ) {
1627 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1628 $status->fatal( 'hookaborted' );
1629 $status->value = self::AS_HOOK_ERROR;
1630 return $status;
1633 $spam = $wgRequest->getText( 'wpAntispam' );
1634 if ( $spam !== '' ) {
1635 wfDebugLog(
1636 'SimpleAntiSpam',
1637 $wgUser->getName() .
1638 ' editing "' .
1639 $this->mTitle->getPrefixedText() .
1640 '" submitted bogus field "' .
1641 $spam .
1644 $status->fatal( 'spamprotectionmatch', false );
1645 $status->value = self::AS_SPAM_ERROR;
1646 return $status;
1649 try {
1650 # Construct Content object
1651 $textbox_content = $this->toEditContent( $this->textbox1 );
1652 } catch ( MWContentSerializationException $ex ) {
1653 $status->fatal(
1654 'content-failed-to-parse',
1655 $this->contentModel,
1656 $this->contentFormat,
1657 $ex->getMessage()
1659 $status->value = self::AS_PARSE_ERROR;
1660 return $status;
1663 # Check image redirect
1664 if ( $this->mTitle->getNamespace() == NS_FILE &&
1665 $textbox_content->isRedirect() &&
1666 !$wgUser->isAllowed( 'upload' )
1668 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1669 $status->setResult( false, $code );
1671 return $status;
1674 # Check for spam
1675 $match = self::matchSummarySpamRegex( $this->summary );
1676 if ( $match === false && $this->section == 'new' ) {
1677 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1678 # regular summaries, it is added to the actual wikitext.
1679 if ( $this->sectiontitle !== '' ) {
1680 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1681 $match = self::matchSpamRegex( $this->sectiontitle );
1682 } else {
1683 # This branch is taken when the "Add Topic" user interface is used, or the API
1684 # is used with the 'summary' parameter.
1685 $match = self::matchSpamRegex( $this->summary );
1688 if ( $match === false ) {
1689 $match = self::matchSpamRegex( $this->textbox1 );
1691 if ( $match !== false ) {
1692 $result['spam'] = $match;
1693 $ip = $wgRequest->getIP();
1694 $pdbk = $this->mTitle->getPrefixedDBkey();
1695 $match = str_replace( "\n", '', $match );
1696 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1697 $status->fatal( 'spamprotectionmatch', $match );
1698 $status->value = self::AS_SPAM_ERROR;
1699 return $status;
1701 if ( !Hooks::run(
1702 'EditFilter',
1703 array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) )
1705 # Error messages etc. could be handled within the hook...
1706 $status->fatal( 'hookaborted' );
1707 $status->value = self::AS_HOOK_ERROR;
1708 return $status;
1709 } elseif ( $this->hookError != '' ) {
1710 # ...or the hook could be expecting us to produce an error
1711 $status->fatal( 'hookaborted' );
1712 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1713 return $status;
1716 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1717 // Auto-block user's IP if the account was "hard" blocked
1718 $wgUser->spreadAnyEditBlock();
1719 # Check block state against master, thus 'false'.
1720 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1721 return $status;
1724 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1725 if ( $this->kblength > $wgMaxArticleSize ) {
1726 // Error will be displayed by showEditForm()
1727 $this->tooBig = true;
1728 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1729 return $status;
1732 if ( !$wgUser->isAllowed( 'edit' ) ) {
1733 if ( $wgUser->isAnon() ) {
1734 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1735 return $status;
1736 } else {
1737 $status->fatal( 'readonlytext' );
1738 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1739 return $status;
1743 $changingContentModel = false;
1744 if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
1745 if ( !$wgContentHandlerUseDB ) {
1746 $status->fatal( 'editpage-cannot-use-custom-model' );
1747 $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
1748 return $status;
1749 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1750 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1751 return $status;
1754 $changingContentModel = true;
1755 $oldContentModel = $this->mTitle->getContentModel();
1758 if ( $this->changeTags ) {
1759 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
1760 $this->changeTags, $wgUser );
1761 if ( !$changeTagsStatus->isOK() ) {
1762 $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
1763 return $changeTagsStatus;
1767 if ( wfReadOnly() ) {
1768 $status->fatal( 'readonlytext' );
1769 $status->value = self::AS_READ_ONLY_PAGE;
1770 return $status;
1772 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1773 $status->fatal( 'actionthrottledtext' );
1774 $status->value = self::AS_RATE_LIMITED;
1775 return $status;
1778 # If the article has been deleted while editing, don't save it without
1779 # confirmation
1780 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1781 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1782 return $status;
1785 # Load the page data from the master. If anything changes in the meantime,
1786 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1787 $this->page->loadPageData( 'fromdbmaster' );
1788 $new = !$this->page->exists();
1790 if ( $new ) {
1791 // Late check for create permission, just in case *PARANOIA*
1792 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1793 $status->fatal( 'nocreatetext' );
1794 $status->value = self::AS_NO_CREATE_PERMISSION;
1795 wfDebug( __METHOD__ . ": no create permission\n" );
1796 return $status;
1799 // Don't save a new page if it's blank or if it's a MediaWiki:
1800 // message with content equivalent to default (allow empty pages
1801 // in this case to disable messages, see bug 50124)
1802 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1803 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1804 $defaultText = $defaultMessageText;
1805 } else {
1806 $defaultText = '';
1809 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1810 $this->blankArticle = true;
1811 $status->fatal( 'blankarticle' );
1812 $status->setResult( false, self::AS_BLANK_ARTICLE );
1813 return $status;
1816 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1817 return $status;
1820 $content = $textbox_content;
1822 $result['sectionanchor'] = '';
1823 if ( $this->section == 'new' ) {
1824 if ( $this->sectiontitle !== '' ) {
1825 // Insert the section title above the content.
1826 $content = $content->addSectionHeader( $this->sectiontitle );
1827 } elseif ( $this->summary !== '' ) {
1828 // Insert the section title above the content.
1829 $content = $content->addSectionHeader( $this->summary );
1831 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
1834 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1836 } else { # not $new
1838 # Article exists. Check for edit conflict.
1840 $this->page->clear(); # Force reload of dates, etc.
1841 $timestamp = $this->page->getTimestamp();
1843 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1845 if ( $timestamp != $this->edittime ) {
1846 $this->isConflict = true;
1847 if ( $this->section == 'new' ) {
1848 if ( $this->page->getUserText() == $wgUser->getName() &&
1849 $this->page->getComment() == $this->newSectionSummary()
1851 // Probably a duplicate submission of a new comment.
1852 // This can happen when CDN resends a request after
1853 // a timeout but the first one actually went through.
1854 wfDebug( __METHOD__
1855 . ": duplicate new section submission; trigger edit conflict!\n" );
1856 } else {
1857 // New comment; suppress conflict.
1858 $this->isConflict = false;
1859 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1861 } elseif ( $this->section == ''
1862 && Revision::userWasLastToEdit(
1863 DB_MASTER, $this->mTitle->getArticleID(),
1864 $wgUser->getId(), $this->edittime
1867 # Suppress edit conflict with self, except for section edits where merging is required.
1868 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1869 $this->isConflict = false;
1873 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1874 if ( $this->sectiontitle !== '' ) {
1875 $sectionTitle = $this->sectiontitle;
1876 } else {
1877 $sectionTitle = $this->summary;
1880 $content = null;
1882 if ( $this->isConflict ) {
1883 wfDebug( __METHOD__
1884 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1885 . " (article time '{$timestamp}')\n" );
1887 $content = $this->page->replaceSectionContent(
1888 $this->section,
1889 $textbox_content,
1890 $sectionTitle,
1891 $this->edittime
1893 } else {
1894 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
1895 $content = $this->page->replaceSectionContent(
1896 $this->section,
1897 $textbox_content,
1898 $sectionTitle
1902 if ( is_null( $content ) ) {
1903 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1904 $this->isConflict = true;
1905 $content = $textbox_content; // do not try to merge here!
1906 } elseif ( $this->isConflict ) {
1907 # Attempt merge
1908 if ( $this->mergeChangesIntoContent( $content ) ) {
1909 // Successful merge! Maybe we should tell the user the good news?
1910 $this->isConflict = false;
1911 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1912 } else {
1913 $this->section = '';
1914 $this->textbox1 = ContentHandler::getContentText( $content );
1915 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1919 if ( $this->isConflict ) {
1920 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1921 return $status;
1924 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1925 return $status;
1928 if ( $this->section == 'new' ) {
1929 // Handle the user preference to force summaries here
1930 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
1931 $this->missingSummary = true;
1932 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1933 $status->value = self::AS_SUMMARY_NEEDED;
1934 return $status;
1937 // Do not allow the user to post an empty comment
1938 if ( $this->textbox1 == '' ) {
1939 $this->missingComment = true;
1940 $status->fatal( 'missingcommenttext' );
1941 $status->value = self::AS_TEXTBOX_EMPTY;
1942 return $status;
1944 } elseif ( !$this->allowBlankSummary
1945 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1946 && !$content->isRedirect()
1947 && md5( $this->summary ) == $this->autoSumm
1949 $this->missingSummary = true;
1950 $status->fatal( 'missingsummary' );
1951 $status->value = self::AS_SUMMARY_NEEDED;
1952 return $status;
1955 # All's well
1956 $sectionanchor = '';
1957 if ( $this->section == 'new' ) {
1958 $this->summary = $this->newSectionSummary( $sectionanchor );
1959 } elseif ( $this->section != '' ) {
1960 # Try to get a section anchor from the section source, redirect
1961 # to edited section if header found.
1962 # XXX: Might be better to integrate this into Article::replaceSection
1963 # for duplicate heading checking and maybe parsing.
1964 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1965 # We can't deal with anchors, includes, html etc in the header for now,
1966 # headline would need to be parsed to improve this.
1967 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1968 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1971 $result['sectionanchor'] = $sectionanchor;
1973 // Save errors may fall down to the edit form, but we've now
1974 // merged the section into full text. Clear the section field
1975 // so that later submission of conflict forms won't try to
1976 // replace that into a duplicated mess.
1977 $this->textbox1 = $this->toEditText( $content );
1978 $this->section = '';
1980 $status->value = self::AS_SUCCESS_UPDATE;
1983 if ( !$this->allowSelfRedirect
1984 && $content->isRedirect()
1985 && $content->getRedirectTarget()->equals( $this->getTitle() )
1987 // If the page already redirects to itself, don't warn.
1988 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
1989 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
1990 $this->selfRedirect = true;
1991 $status->fatal( 'selfredirect' );
1992 $status->value = self::AS_SELF_REDIRECT;
1993 return $status;
1997 // Check for length errors again now that the section is merged in
1998 $this->kblength = (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1999 if ( $this->kblength > $wgMaxArticleSize ) {
2000 $this->tooBig = true;
2001 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
2002 return $status;
2005 $flags = EDIT_AUTOSUMMARY |
2006 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
2007 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
2008 ( $bot ? EDIT_FORCE_BOT : 0 );
2010 $doEditStatus = $this->page->doEditContent(
2011 $content,
2012 $this->summary,
2013 $flags,
2014 false,
2015 $wgUser,
2016 $content->getDefaultFormat()
2019 if ( !$doEditStatus->isOK() ) {
2020 // Failure from doEdit()
2021 // Show the edit conflict page for certain recognized errors from doEdit(),
2022 // but don't show it for errors from extension hooks
2023 $errors = $doEditStatus->getErrorsArray();
2024 if ( in_array( $errors[0][0],
2025 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
2027 $this->isConflict = true;
2028 // Destroys data doEdit() put in $status->value but who cares
2029 $doEditStatus->value = self::AS_END;
2031 return $doEditStatus;
2034 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2035 if ( $result['nullEdit'] ) {
2036 // We don't know if it was a null edit until now, so increment here
2037 $wgUser->pingLimiter( 'linkpurge' );
2039 $result['redirect'] = $content->isRedirect();
2041 $this->updateWatchlist();
2043 if ( $this->changeTags && isset( $doEditStatus->value['revision'] ) ) {
2044 // If a revision was created, apply any change tags that were requested
2045 $addTags = $this->changeTags;
2046 $revId = $doEditStatus->value['revision']->getId();
2047 // Defer this both for performance and so that addTags() sees the rc_id
2048 // since the recentchange entry addition is deferred first (bug T100248)
2049 DeferredUpdates::addCallableUpdate( function() use ( $addTags, $revId ) {
2050 ChangeTags::addTags( $addTags, null, $revId );
2051 } );
2054 // If the content model changed, add a log entry
2055 if ( $changingContentModel ) {
2056 $this->addContentModelChangeLogEntry(
2057 $wgUser,
2058 $oldContentModel,
2059 $this->contentModel,
2060 $this->summary
2064 return $status;
2068 * @param User $user
2069 * @param string $oldModel
2070 * @param string $newModel
2071 * @param string $reason
2073 protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
2074 $log = new ManualLogEntry( 'contentmodel', 'change' );
2075 $log->setPerformer( $user );
2076 $log->setTarget( $this->mTitle );
2077 $log->setComment( $reason );
2078 $log->setParameters( array(
2079 '4::oldmodel' => $oldModel,
2080 '5::newmodel' => $newModel
2081 ) );
2082 $logid = $log->insert();
2083 $log->publish( $logid );
2087 * Register the change of watch status
2089 protected function updateWatchlist() {
2090 global $wgUser;
2092 if ( !$wgUser->isLoggedIn() ) {
2093 return;
2096 $user = $wgUser;
2097 $title = $this->mTitle;
2098 $watch = $this->watchthis;
2099 // Do this in its own transaction to reduce contention...
2100 DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
2101 if ( $watch == $user->isWatched( $title, WatchedItem::IGNORE_USER_RIGHTS ) ) {
2102 return; // nothing to change
2104 WatchAction::doWatchOrUnwatch( $watch, $title, $user );
2105 } );
2109 * Attempts to do 3-way merge of edit content with a base revision
2110 * and current content, in case of edit conflict, in whichever way appropriate
2111 * for the content type.
2113 * @since 1.21
2115 * @param Content $editContent
2117 * @return bool
2119 private function mergeChangesIntoContent( &$editContent ) {
2121 $db = wfGetDB( DB_MASTER );
2123 // This is the revision the editor started from
2124 $baseRevision = $this->getBaseRevision();
2125 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2127 if ( is_null( $baseContent ) ) {
2128 return false;
2131 // The current state, we want to merge updates into it
2132 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2133 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2135 if ( is_null( $currentContent ) ) {
2136 return false;
2139 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2141 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2143 if ( $result ) {
2144 $editContent = $result;
2145 // Update parentRevId to what we just merged.
2146 $this->parentRevId = $currentRevision->getId();
2147 return true;
2150 return false;
2154 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2155 * one might think of X as the "base revision", which is NOT what this returns.
2156 * @return Revision Current version when the edit was started
2158 function getBaseRevision() {
2159 if ( !$this->mBaseRevision ) {
2160 $db = wfGetDB( DB_MASTER );
2161 $this->mBaseRevision = Revision::loadFromTimestamp(
2162 $db, $this->mTitle, $this->edittime );
2164 return $this->mBaseRevision;
2168 * Check given input text against $wgSpamRegex, and return the text of the first match.
2170 * @param string $text
2172 * @return string|bool Matching string or false
2174 public static function matchSpamRegex( $text ) {
2175 global $wgSpamRegex;
2176 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2177 $regexes = (array)$wgSpamRegex;
2178 return self::matchSpamRegexInternal( $text, $regexes );
2182 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2184 * @param string $text
2186 * @return string|bool Matching string or false
2188 public static function matchSummarySpamRegex( $text ) {
2189 global $wgSummarySpamRegex;
2190 $regexes = (array)$wgSummarySpamRegex;
2191 return self::matchSpamRegexInternal( $text, $regexes );
2195 * @param string $text
2196 * @param array $regexes
2197 * @return bool|string
2199 protected static function matchSpamRegexInternal( $text, $regexes ) {
2200 foreach ( $regexes as $regex ) {
2201 $matches = array();
2202 if ( preg_match( $regex, $text, $matches ) ) {
2203 return $matches[0];
2206 return false;
2209 function setHeaders() {
2210 global $wgOut, $wgUser, $wgAjaxEditStash;
2212 $wgOut->addModules( 'mediawiki.action.edit' );
2213 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2215 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2216 // The addition of default buttons is handled by getEditToolbar() which
2217 // has its own dependency on this module. The call here ensures the module
2218 // is loaded in time (it has position "top") for other modules to register
2219 // buttons (e.g. extensions, gadgets, user scripts).
2220 $wgOut->addModules( 'mediawiki.toolbar' );
2223 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2224 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2227 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2228 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2231 if ( $wgAjaxEditStash ) {
2232 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2235 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2237 # Enabled article-related sidebar, toplinks, etc.
2238 $wgOut->setArticleRelated( true );
2240 $contextTitle = $this->getContextTitle();
2241 if ( $this->isConflict ) {
2242 $msg = 'editconflict';
2243 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2244 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2245 } else {
2246 $msg = $contextTitle->exists()
2247 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2248 && $contextTitle->getDefaultMessageText() !== false
2250 ? 'editing'
2251 : 'creating';
2254 # Use the title defined by DISPLAYTITLE magic word when present
2255 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2256 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2257 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2258 if ( $displayTitle === false ) {
2259 $displayTitle = $contextTitle->getPrefixedText();
2261 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2262 # Transmit the name of the message to JavaScript for live preview
2263 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2264 $wgOut->addJsConfigVars( 'wgEditMessage', $msg );
2268 * Show all applicable editing introductions
2270 protected function showIntro() {
2271 global $wgOut, $wgUser;
2272 if ( $this->suppressIntro ) {
2273 return;
2276 $namespace = $this->mTitle->getNamespace();
2278 if ( $namespace == NS_MEDIAWIKI ) {
2279 # Show a warning if editing an interface message
2280 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2281 # If this is a default message (but not css or js),
2282 # show a hint that it is translatable on translatewiki.net
2283 if ( !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2284 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2286 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2287 if ( $defaultMessageText !== false ) {
2288 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2289 'translateinterface' );
2292 } elseif ( $namespace == NS_FILE ) {
2293 # Show a hint to shared repo
2294 $file = wfFindFile( $this->mTitle );
2295 if ( $file && !$file->isLocal() ) {
2296 $descUrl = $file->getDescriptionUrl();
2297 # there must be a description url to show a hint to shared repo
2298 if ( $descUrl ) {
2299 if ( !$this->mTitle->exists() ) {
2300 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2301 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2302 ) );
2303 } else {
2304 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2305 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2306 ) );
2312 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2313 # Show log extract when the user is currently blocked
2314 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2315 $parts = explode( '/', $this->mTitle->getText(), 2 );
2316 $username = $parts[0];
2317 $user = User::newFromName( $username, false /* allow IP users*/ );
2318 $ip = User::isIP( $username );
2319 $block = Block::newFromTarget( $user, $user );
2320 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2321 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2322 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2323 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2324 # Show log extract if the user is currently blocked
2325 LogEventsList::showLogExtract(
2326 $wgOut,
2327 'block',
2328 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2330 array(
2331 'lim' => 1,
2332 'showIfEmpty' => false,
2333 'msgKey' => array(
2334 'blocked-notice-logextract',
2335 $user->getName() # Support GENDER in notice
2341 # Try to add a custom edit intro, or use the standard one if this is not possible.
2342 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2343 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2344 wfMessage( 'helppage' )->inContentLanguage()->text()
2345 ) );
2346 if ( $wgUser->isLoggedIn() ) {
2347 $wgOut->wrapWikiMsg(
2348 // Suppress the external link icon, consider the help url an internal one
2349 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2350 array(
2351 'newarticletext',
2352 $helpLink
2355 } else {
2356 $wgOut->wrapWikiMsg(
2357 // Suppress the external link icon, consider the help url an internal one
2358 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2359 array(
2360 'newarticletextanon',
2361 $helpLink
2366 # Give a notice if the user is editing a deleted/moved page...
2367 if ( !$this->mTitle->exists() ) {
2368 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
2370 array(
2371 'lim' => 10,
2372 'conds' => array( "log_action != 'revision'" ),
2373 'showIfEmpty' => false,
2374 'msgKey' => array( 'recreate-moveddeleted-warn' )
2381 * Attempt to show a custom editing introduction, if supplied
2383 * @return bool
2385 protected function showCustomIntro() {
2386 if ( $this->editintro ) {
2387 $title = Title::newFromText( $this->editintro );
2388 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2389 global $wgOut;
2390 // Added using template syntax, to take <noinclude>'s into account.
2391 $wgOut->addWikiTextTitleTidy(
2392 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2393 $this->mTitle
2395 return true;
2398 return false;
2402 * Gets an editable textual representation of $content.
2403 * The textual representation can be turned by into a Content object by the
2404 * toEditContent() method.
2406 * If $content is null or false or a string, $content is returned unchanged.
2408 * If the given Content object is not of a type that can be edited using
2409 * the text base EditPage, an exception will be raised. Set
2410 * $this->allowNonTextContent to true to allow editing of non-textual
2411 * content.
2413 * @param Content|null|bool|string $content
2414 * @return string The editable text form of the content.
2416 * @throws MWException If $content is not an instance of TextContent and
2417 * $this->allowNonTextContent is not true.
2419 protected function toEditText( $content ) {
2420 if ( $content === null || $content === false || is_string( $content ) ) {
2421 return $content;
2424 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2425 throw new MWException( 'This content model is not supported: '
2426 . ContentHandler::getLocalizedName( $content->getModel() ) );
2429 return $content->serialize( $this->contentFormat );
2433 * Turns the given text into a Content object by unserializing it.
2435 * If the resulting Content object is not of a type that can be edited using
2436 * the text base EditPage, an exception will be raised. Set
2437 * $this->allowNonTextContent to true to allow editing of non-textual
2438 * content.
2440 * @param string|null|bool $text Text to unserialize
2441 * @return Content The content object created from $text. If $text was false
2442 * or null, false resp. null will be returned instead.
2444 * @throws MWException If unserializing the text results in a Content
2445 * object that is not an instance of TextContent and
2446 * $this->allowNonTextContent is not true.
2448 protected function toEditContent( $text ) {
2449 if ( $text === false || $text === null ) {
2450 return $text;
2453 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2454 $this->contentModel, $this->contentFormat );
2456 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2457 throw new MWException( 'This content model is not supported: '
2458 . ContentHandler::getLocalizedName( $content->getModel() ) );
2461 return $content;
2465 * Send the edit form and related headers to $wgOut
2466 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2467 * during form output near the top, for captchas and the like.
2469 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2470 * use the EditPage::showEditForm:fields hook instead.
2472 function showEditForm( $formCallback = null ) {
2473 global $wgOut, $wgUser;
2475 # need to parse the preview early so that we know which templates are used,
2476 # otherwise users with "show preview after edit box" will get a blank list
2477 # we parse this near the beginning so that setHeaders can do the title
2478 # setting work instead of leaving it in getPreviewText
2479 $previewOutput = '';
2480 if ( $this->formtype == 'preview' ) {
2481 $previewOutput = $this->getPreviewText();
2484 Hooks::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2486 $this->setHeaders();
2488 if ( $this->showHeader() === false ) {
2489 return;
2492 $wgOut->addHTML( $this->editFormPageTop );
2494 if ( $wgUser->getOption( 'previewontop' ) ) {
2495 $this->displayPreviewArea( $previewOutput, true );
2498 $wgOut->addHTML( $this->editFormTextTop );
2500 $showToolbar = true;
2501 if ( $this->wasDeletedSinceLastEdit() ) {
2502 if ( $this->formtype == 'save' ) {
2503 // Hide the toolbar and edit area, user can click preview to get it back
2504 // Add an confirmation checkbox and explanation.
2505 $showToolbar = false;
2506 } else {
2507 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2508 'deletedwhileediting' );
2512 // @todo add EditForm plugin interface and use it here!
2513 // search for textarea1 and textares2, and allow EditForm to override all uses.
2514 $wgOut->addHTML( Html::openElement(
2515 'form',
2516 array(
2517 'id' => self::EDITFORM_ID,
2518 'name' => self::EDITFORM_ID,
2519 'method' => 'post',
2520 'action' => $this->getActionURL( $this->getContextTitle() ),
2521 'enctype' => 'multipart/form-data'
2523 ) );
2525 if ( is_callable( $formCallback ) ) {
2526 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2527 call_user_func_array( $formCallback, array( &$wgOut ) );
2530 // Add an empty field to trip up spambots
2531 $wgOut->addHTML(
2532 Xml::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2533 . Html::rawElement(
2534 'label',
2535 array( 'for' => 'wpAntiSpam' ),
2536 wfMessage( 'simpleantispam-label' )->parse()
2538 . Xml::element(
2539 'input',
2540 array(
2541 'type' => 'text',
2542 'name' => 'wpAntispam',
2543 'id' => 'wpAntispam',
2544 'value' => ''
2547 . Xml::closeElement( 'div' )
2550 Hooks::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2552 // Put these up at the top to ensure they aren't lost on early form submission
2553 $this->showFormBeforeText();
2555 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2556 $username = $this->lastDelete->user_name;
2557 $comment = $this->lastDelete->log_comment;
2559 // It is better to not parse the comment at all than to have templates expanded in the middle
2560 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2561 $key = $comment === ''
2562 ? 'confirmrecreate-noreason'
2563 : 'confirmrecreate';
2564 $wgOut->addHTML(
2565 '<div class="mw-confirm-recreate">' .
2566 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2567 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2568 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2570 '</div>'
2574 # When the summary is hidden, also hide them on preview/show changes
2575 if ( $this->nosummary ) {
2576 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2579 # If a blank edit summary was previously provided, and the appropriate
2580 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2581 # user being bounced back more than once in the event that a summary
2582 # is not required.
2583 # ####
2584 # For a bit more sophisticated detection of blank summaries, hash the
2585 # automatic one and pass that in the hidden field wpAutoSummary.
2586 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2587 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2590 if ( $this->undidRev ) {
2591 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2594 if ( $this->selfRedirect ) {
2595 $wgOut->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2598 if ( $this->hasPresetSummary ) {
2599 // If a summary has been preset using &summary= we don't want to prompt for
2600 // a different summary. Only prompt for a summary if the summary is blanked.
2601 // (Bug 17416)
2602 $this->autoSumm = md5( '' );
2605 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2606 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2608 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2609 $wgOut->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
2611 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2612 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2614 if ( $this->section == 'new' ) {
2615 $this->showSummaryInput( true, $this->summary );
2616 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2619 $wgOut->addHTML( $this->editFormTextBeforeContent );
2621 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2622 $wgOut->addHTML( EditPage::getEditToolbar( $this->mTitle ) );
2625 if ( $this->blankArticle ) {
2626 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2629 if ( $this->isConflict ) {
2630 // In an edit conflict bypass the overridable content form method
2631 // and fallback to the raw wpTextbox1 since editconflicts can't be
2632 // resolved between page source edits and custom ui edits using the
2633 // custom edit ui.
2634 $this->textbox2 = $this->textbox1;
2636 $content = $this->getCurrentContent();
2637 $this->textbox1 = $this->toEditText( $content );
2639 $this->showTextbox1();
2640 } else {
2641 $this->showContentForm();
2644 $wgOut->addHTML( $this->editFormTextAfterContent );
2646 $this->showStandardInputs();
2648 $this->showFormAfterText();
2650 $this->showTosSummary();
2652 $this->showEditTools();
2654 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2656 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2657 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2659 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2660 Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
2662 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'limitreport' ),
2663 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2665 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2667 if ( $this->isConflict ) {
2668 try {
2669 $this->showConflict();
2670 } catch ( MWContentSerializationException $ex ) {
2671 // this can't really happen, but be nice if it does.
2672 $msg = wfMessage(
2673 'content-failed-to-parse',
2674 $this->contentModel,
2675 $this->contentFormat,
2676 $ex->getMessage()
2678 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2682 // Marker for detecting truncated form data. This must be the last
2683 // parameter sent in order to be of use, so do not move me.
2684 $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2685 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2687 if ( !$wgUser->getOption( 'previewontop' ) ) {
2688 $this->displayPreviewArea( $previewOutput, false );
2694 * Extract the section title from current section text, if any.
2696 * @param string $text
2697 * @return string|bool String or false
2699 public static function extractSectionTitle( $text ) {
2700 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2701 if ( !empty( $matches[2] ) ) {
2702 global $wgParser;
2703 return $wgParser->stripSectionName( trim( $matches[2] ) );
2704 } else {
2705 return false;
2710 * @return bool
2712 protected function showHeader() {
2713 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2714 global $wgAllowUserCss, $wgAllowUserJs;
2716 if ( $this->mTitle->isTalkPage() ) {
2717 $wgOut->addWikiMsg( 'talkpagetext' );
2720 // Add edit notices
2721 $editNotices = $this->mTitle->getEditNotices( $this->oldid );
2722 if ( count( $editNotices ) ) {
2723 $wgOut->addHTML( implode( "\n", $editNotices ) );
2724 } else {
2725 $msg = wfMessage( 'editnotice-notext' );
2726 if ( !$msg->isDisabled() ) {
2727 $wgOut->addHTML(
2728 '<div class="mw-editnotice-notext">'
2729 . $msg->parseAsBlock()
2730 . '</div>'
2735 if ( $this->isConflict ) {
2736 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2737 $this->edittime = $this->page->getTimestamp();
2738 } else {
2739 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2740 // We use $this->section to much before this and getVal('wgSection') directly in other places
2741 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2742 // Someone is welcome to try refactoring though
2743 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2744 return false;
2747 if ( $this->section != '' && $this->section != 'new' ) {
2748 if ( !$this->summary && !$this->preview && !$this->diff ) {
2749 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
2750 if ( $sectionTitle !== false ) {
2751 $this->summary = "/* $sectionTitle */ ";
2756 if ( $this->missingComment ) {
2757 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2760 if ( $this->missingSummary && $this->section != 'new' ) {
2761 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2764 if ( $this->missingSummary && $this->section == 'new' ) {
2765 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2768 if ( $this->blankArticle ) {
2769 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2772 if ( $this->selfRedirect ) {
2773 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2776 if ( $this->hookError !== '' ) {
2777 $wgOut->addWikiText( $this->hookError );
2780 if ( !$this->checkUnicodeCompliantBrowser() ) {
2781 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2784 if ( $this->section != 'new' ) {
2785 $revision = $this->mArticle->getRevisionFetched();
2786 if ( $revision ) {
2787 // Let sysop know that this will make private content public if saved
2789 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2790 $wgOut->wrapWikiMsg(
2791 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2792 'rev-deleted-text-permission'
2794 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2795 $wgOut->wrapWikiMsg(
2796 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2797 'rev-deleted-text-view'
2801 if ( !$revision->isCurrent() ) {
2802 $this->mArticle->setOldSubtitle( $revision->getId() );
2803 $wgOut->addWikiMsg( 'editingold' );
2805 } elseif ( $this->mTitle->exists() ) {
2806 // Something went wrong
2808 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2809 array( 'missing-revision', $this->oldid ) );
2814 if ( wfReadOnly() ) {
2815 $wgOut->wrapWikiMsg(
2816 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2817 array( 'readonlywarning', wfReadOnlyReason() )
2819 } elseif ( $wgUser->isAnon() ) {
2820 if ( $this->formtype != 'preview' ) {
2821 $wgOut->wrapWikiMsg(
2822 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2823 array( 'anoneditwarning',
2824 // Log-in link
2825 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2826 // Sign-up link
2827 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2829 } else {
2830 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2831 'anonpreviewwarning'
2834 } else {
2835 if ( $this->isCssJsSubpage ) {
2836 # Check the skin exists
2837 if ( $this->isWrongCaseCssJsPage ) {
2838 $wgOut->wrapWikiMsg(
2839 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2840 array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() )
2843 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2844 if ( $this->formtype !== 'preview' ) {
2845 if ( $this->isCssSubpage && $wgAllowUserCss ) {
2846 $wgOut->wrapWikiMsg(
2847 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2848 array( 'usercssyoucanpreview' )
2852 if ( $this->isJsSubpage && $wgAllowUserJs ) {
2853 $wgOut->wrapWikiMsg(
2854 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2855 array( 'userjsyoucanpreview' )
2863 if ( $this->mTitle->isProtected( 'edit' ) &&
2864 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2866 # Is the title semi-protected?
2867 if ( $this->mTitle->isSemiProtected() ) {
2868 $noticeMsg = 'semiprotectedpagewarning';
2869 } else {
2870 # Then it must be protected based on static groups (regular)
2871 $noticeMsg = 'protectedpagewarning';
2873 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2874 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2876 if ( $this->mTitle->isCascadeProtected() ) {
2877 # Is this page under cascading protection from some source pages?
2878 /** @var Title[] $cascadeSources */
2879 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2880 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2881 $cascadeSourcesCount = count( $cascadeSources );
2882 if ( $cascadeSourcesCount > 0 ) {
2883 # Explain, and list the titles responsible
2884 foreach ( $cascadeSources as $page ) {
2885 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2888 $notice .= '</div>';
2889 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2891 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2892 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2893 array( 'lim' => 1,
2894 'showIfEmpty' => false,
2895 'msgKey' => array( 'titleprotectedwarning' ),
2896 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2899 if ( $this->kblength === false ) {
2900 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2903 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2904 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2905 array(
2906 'longpageerror',
2907 $wgLang->formatNum( $this->kblength ),
2908 $wgLang->formatNum( $wgMaxArticleSize )
2911 } else {
2912 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2913 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2914 array(
2915 'longpage-hint',
2916 $wgLang->formatSize( strlen( $this->textbox1 ) ),
2917 strlen( $this->textbox1 )
2922 # Add header copyright warning
2923 $this->showHeaderCopyrightWarning();
2925 return true;
2929 * Standard summary input and label (wgSummary), abstracted so EditPage
2930 * subclasses may reorganize the form.
2931 * Note that you do not need to worry about the label's for=, it will be
2932 * inferred by the id given to the input. You can remove them both by
2933 * passing array( 'id' => false ) to $userInputAttrs.
2935 * @param string $summary The value of the summary input
2936 * @param string $labelText The html to place inside the label
2937 * @param array $inputAttrs Array of attrs to use on the input
2938 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2940 * @return array An array in the format array( $label, $input )
2942 function getSummaryInput( $summary = "", $labelText = null,
2943 $inputAttrs = null, $spanLabelAttrs = null
2945 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2946 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2947 'id' => 'wpSummary',
2948 'maxlength' => '200',
2949 'tabindex' => '1',
2950 'size' => 60,
2951 'spellcheck' => 'true',
2952 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2954 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2955 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2956 'id' => "wpSummaryLabel"
2959 $label = null;
2960 if ( $labelText ) {
2961 $label = Xml::tags(
2962 'label',
2963 $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null,
2964 $labelText
2966 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2969 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2971 return array( $label, $input );
2975 * @param bool $isSubjectPreview True if this is the section subject/title
2976 * up top, or false if this is the comment summary
2977 * down below the textarea
2978 * @param string $summary The text of the summary to display
2980 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2981 global $wgOut, $wgContLang;
2982 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2983 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2984 if ( $isSubjectPreview ) {
2985 if ( $this->nosummary ) {
2986 return;
2988 } else {
2989 if ( !$this->mShowSummaryField ) {
2990 return;
2993 $summary = $wgContLang->recodeForEdit( $summary );
2994 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2995 list( $label, $input ) = $this->getSummaryInput(
2996 $summary,
2997 $labelText,
2998 array( 'class' => $summaryClass ),
2999 array()
3001 $wgOut->addHTML( "{$label} {$input}" );
3005 * @param bool $isSubjectPreview True if this is the section subject/title
3006 * up top, or false if this is the comment summary
3007 * down below the textarea
3008 * @param string $summary The text of the summary to display
3009 * @return string
3011 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3012 // avoid spaces in preview, gets always trimmed on save
3013 $summary = trim( $summary );
3014 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
3015 return "";
3018 global $wgParser;
3020 if ( $isSubjectPreview ) {
3021 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
3022 ->inContentLanguage()->text();
3025 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
3027 $summary = wfMessage( $message )->parse()
3028 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
3029 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
3032 protected function showFormBeforeText() {
3033 global $wgOut;
3034 $section = htmlspecialchars( $this->section );
3035 $wgOut->addHTML( <<<HTML
3036 <input type='hidden' value="{$section}" name="wpSection"/>
3037 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
3038 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
3039 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
3041 HTML
3043 if ( !$this->checkUnicodeCompliantBrowser() ) {
3044 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
3048 protected function showFormAfterText() {
3049 global $wgOut, $wgUser;
3051 * To make it harder for someone to slip a user a page
3052 * which submits an edit form to the wiki without their
3053 * knowledge, a random token is associated with the login
3054 * session. If it's not passed back with the submission,
3055 * we won't save the page, or render user JavaScript and
3056 * CSS previews.
3058 * For anon editors, who may not have a session, we just
3059 * include the constant suffix to prevent editing from
3060 * broken text-mangling proxies.
3062 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
3066 * Subpage overridable method for printing the form for page content editing
3067 * By default this simply outputs wpTextbox1
3068 * Subclasses can override this to provide a custom UI for editing;
3069 * be it a form, or simply wpTextbox1 with a modified content that will be
3070 * reverse modified when extracted from the post data.
3071 * Note that this is basically the inverse for importContentFormData
3073 protected function showContentForm() {
3074 $this->showTextbox1();
3078 * Method to output wpTextbox1
3079 * The $textoverride method can be used by subclasses overriding showContentForm
3080 * to pass back to this method.
3082 * @param array $customAttribs Array of html attributes to use in the textarea
3083 * @param string $textoverride Optional text to override $this->textarea1 with
3085 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3086 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
3087 $attribs = array( 'style' => 'display:none;' );
3088 } else {
3089 $classes = array(); // Textarea CSS
3090 if ( $this->mTitle->isProtected( 'edit' ) &&
3091 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
3093 # Is the title semi-protected?
3094 if ( $this->mTitle->isSemiProtected() ) {
3095 $classes[] = 'mw-textarea-sprotected';
3096 } else {
3097 # Then it must be protected based on static groups (regular)
3098 $classes[] = 'mw-textarea-protected';
3100 # Is the title cascade-protected?
3101 if ( $this->mTitle->isCascadeProtected() ) {
3102 $classes[] = 'mw-textarea-cprotected';
3106 $attribs = array( 'tabindex' => 1 );
3108 if ( is_array( $customAttribs ) ) {
3109 $attribs += $customAttribs;
3112 if ( count( $classes ) ) {
3113 if ( isset( $attribs['class'] ) ) {
3114 $classes[] = $attribs['class'];
3116 $attribs['class'] = implode( ' ', $classes );
3120 $this->showTextbox(
3121 $textoverride !== null ? $textoverride : $this->textbox1,
3122 'wpTextbox1',
3123 $attribs
3127 protected function showTextbox2() {
3128 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
3131 protected function showTextbox( $text, $name, $customAttribs = array() ) {
3132 global $wgOut, $wgUser;
3134 $wikitext = $this->safeUnicodeOutput( $text );
3135 if ( strval( $wikitext ) !== '' ) {
3136 // Ensure there's a newline at the end, otherwise adding lines
3137 // is awkward.
3138 // But don't add a newline if the ext is empty, or Firefox in XHTML
3139 // mode will show an extra newline. A bit annoying.
3140 $wikitext .= "\n";
3143 $attribs = $customAttribs + array(
3144 'accesskey' => ',',
3145 'id' => $name,
3146 'cols' => $wgUser->getIntOption( 'cols' ),
3147 'rows' => $wgUser->getIntOption( 'rows' ),
3148 // Avoid PHP notices when appending preferences
3149 // (appending allows customAttribs['style'] to still work).
3150 'style' => ''
3153 $pageLang = $this->mTitle->getPageLanguage();
3154 $attribs['lang'] = $pageLang->getHtmlCode();
3155 $attribs['dir'] = $pageLang->getDir();
3157 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
3160 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3161 global $wgOut;
3162 $classes = array();
3163 if ( $isOnTop ) {
3164 $classes[] = 'ontop';
3167 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3169 if ( $this->formtype != 'preview' ) {
3170 $attribs['style'] = 'display: none;';
3173 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
3175 if ( $this->formtype == 'preview' ) {
3176 $this->showPreview( $previewOutput );
3177 } else {
3178 // Empty content container for LivePreview
3179 $pageViewLang = $this->mTitle->getPageViewLanguage();
3180 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3181 'class' => 'mw-content-' . $pageViewLang->getDir() );
3182 $wgOut->addHTML( Html::rawElement( 'div', $attribs ) );
3185 $wgOut->addHTML( '</div>' );
3187 if ( $this->formtype == 'diff' ) {
3188 try {
3189 $this->showDiff();
3190 } catch ( MWContentSerializationException $ex ) {
3191 $msg = wfMessage(
3192 'content-failed-to-parse',
3193 $this->contentModel,
3194 $this->contentFormat,
3195 $ex->getMessage()
3197 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3203 * Append preview output to $wgOut.
3204 * Includes category rendering if this is a category page.
3206 * @param string $text The HTML to be output for the preview.
3208 protected function showPreview( $text ) {
3209 global $wgOut;
3210 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3211 $this->mArticle->openShowCategory();
3213 # This hook seems slightly odd here, but makes things more
3214 # consistent for extensions.
3215 Hooks::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3216 $wgOut->addHTML( $text );
3217 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3218 $this->mArticle->closeShowCategory();
3223 * Get a diff between the current contents of the edit box and the
3224 * version of the page we're editing from.
3226 * If this is a section edit, we'll replace the section as for final
3227 * save and then make a comparison.
3229 function showDiff() {
3230 global $wgUser, $wgContLang, $wgOut;
3232 $oldtitlemsg = 'currentrev';
3233 # if message does not exist, show diff against the preloaded default
3234 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3235 $oldtext = $this->mTitle->getDefaultMessageText();
3236 if ( $oldtext !== false ) {
3237 $oldtitlemsg = 'defaultmessagetext';
3238 $oldContent = $this->toEditContent( $oldtext );
3239 } else {
3240 $oldContent = null;
3242 } else {
3243 $oldContent = $this->getCurrentContent();
3246 $textboxContent = $this->toEditContent( $this->textbox1 );
3248 $newContent = $this->page->replaceSectionContent(
3249 $this->section, $textboxContent,
3250 $this->summary, $this->edittime );
3252 if ( $newContent ) {
3253 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3254 Hooks::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3256 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
3257 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
3260 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3261 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3262 $newtitle = wfMessage( 'yourtext' )->parse();
3264 if ( !$oldContent ) {
3265 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3268 if ( !$newContent ) {
3269 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3272 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
3273 $de->setContent( $oldContent, $newContent );
3275 $difftext = $de->getDiff( $oldtitle, $newtitle );
3276 $de->showDiffStyle();
3277 } else {
3278 $difftext = '';
3281 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3285 * Show the header copyright warning.
3287 protected function showHeaderCopyrightWarning() {
3288 $msg = 'editpage-head-copy-warn';
3289 if ( !wfMessage( $msg )->isDisabled() ) {
3290 global $wgOut;
3291 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3292 'editpage-head-copy-warn' );
3297 * Give a chance for site and per-namespace customizations of
3298 * terms of service summary link that might exist separately
3299 * from the copyright notice.
3301 * This will display between the save button and the edit tools,
3302 * so should remain short!
3304 protected function showTosSummary() {
3305 $msg = 'editpage-tos-summary';
3306 Hooks::run( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
3307 if ( !wfMessage( $msg )->isDisabled() ) {
3308 global $wgOut;
3309 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3310 $wgOut->addWikiMsg( $msg );
3311 $wgOut->addHTML( '</div>' );
3315 protected function showEditTools() {
3316 global $wgOut;
3317 $wgOut->addHTML( '<div class="mw-editTools">' .
3318 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3319 '</div>' );
3323 * Get the copyright warning
3325 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3326 * @return string
3328 protected function getCopywarn() {
3329 return self::getCopyrightWarning( $this->mTitle );
3333 * Get the copyright warning, by default returns wikitext
3335 * @param Title $title
3336 * @param string $format Output format, valid values are any function of a Message object
3337 * @return string
3339 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3340 global $wgRightsText;
3341 if ( $wgRightsText ) {
3342 $copywarnMsg = array( 'copyrightwarning',
3343 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3344 $wgRightsText );
3345 } else {
3346 $copywarnMsg = array( 'copyrightwarning2',
3347 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3349 // Allow for site and per-namespace customization of contribution/copyright notice.
3350 Hooks::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3352 return "<div id=\"editpage-copywarn\">\n" .
3353 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3357 * Get the Limit report for page previews
3359 * @since 1.22
3360 * @param ParserOutput $output ParserOutput object from the parse
3361 * @return string HTML
3363 public static function getPreviewLimitReport( $output ) {
3364 if ( !$output || !$output->getLimitReportData() ) {
3365 return '';
3368 $limitReport = Html::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3369 wfMessage( 'limitreport-title' )->parseAsBlock()
3372 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3373 $limitReport .= Html::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3375 $limitReport .= Html::openElement( 'table', array(
3376 'class' => 'preview-limit-report wikitable'
3377 ) ) .
3378 Html::openElement( 'tbody' );
3380 foreach ( $output->getLimitReportData() as $key => $value ) {
3381 if ( Hooks::run( 'ParserLimitReportFormat',
3382 array( $key, &$value, &$limitReport, true, true )
3383 ) ) {
3384 $keyMsg = wfMessage( $key );
3385 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3386 if ( !$valueMsg->exists() ) {
3387 $valueMsg = new RawMessage( '$1' );
3389 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3390 $limitReport .= Html::openElement( 'tr' ) .
3391 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3392 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3393 Html::closeElement( 'tr' );
3398 $limitReport .= Html::closeElement( 'tbody' ) .
3399 Html::closeElement( 'table' ) .
3400 Html::closeElement( 'div' );
3402 return $limitReport;
3405 protected function showStandardInputs( &$tabindex = 2 ) {
3406 global $wgOut;
3407 $wgOut->addHTML( "<div class='editOptions'>\n" );
3409 if ( $this->section != 'new' ) {
3410 $this->showSummaryInput( false, $this->summary );
3411 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3414 $checkboxes = $this->getCheckboxes( $tabindex,
3415 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
3416 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3418 // Show copyright warning.
3419 $wgOut->addWikiText( $this->getCopywarn() );
3420 $wgOut->addHTML( $this->editFormTextAfterWarn );
3422 $wgOut->addHTML( "<div class='editButtons'>\n" );
3423 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3425 $cancel = $this->getCancelLink();
3426 if ( $cancel !== '' ) {
3427 $cancel .= Html::element( 'span',
3428 array( 'class' => 'mw-editButtons-pipe-separator' ),
3429 wfMessage( 'pipe-separator' )->text() );
3432 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3433 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3434 $attrs = array(
3435 'target' => 'helpwindow',
3436 'href' => $edithelpurl,
3438 $edithelp = Html::linkButton( wfMessage( 'edithelp' )->text(),
3439 $attrs, array( 'mw-ui-quiet' ) ) .
3440 wfMessage( 'word-separator' )->escaped() .
3441 wfMessage( 'newwindow' )->parse();
3443 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3444 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3445 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3447 Hooks::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3449 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3453 * Show an edit conflict. textbox1 is already shown in showEditForm().
3454 * If you want to use another entry point to this function, be careful.
3456 protected function showConflict() {
3457 global $wgOut;
3459 if ( Hooks::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3460 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3462 $content1 = $this->toEditContent( $this->textbox1 );
3463 $content2 = $this->toEditContent( $this->textbox2 );
3465 $handler = ContentHandler::getForModelID( $this->contentModel );
3466 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3467 $de->setContent( $content2, $content1 );
3468 $de->showDiff(
3469 wfMessage( 'yourtext' )->parse(),
3470 wfMessage( 'storedversion' )->text()
3473 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3474 $this->showTextbox2();
3479 * @return string
3481 public function getCancelLink() {
3482 $cancelParams = array();
3483 if ( !$this->isConflict && $this->oldid > 0 ) {
3484 $cancelParams['oldid'] = $this->oldid;
3486 $attrs = array( 'id' => 'mw-editform-cancel' );
3488 return Linker::linkKnown(
3489 $this->getContextTitle(),
3490 wfMessage( 'cancel' )->parse(),
3491 Html::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3492 $cancelParams
3497 * Returns the URL to use in the form's action attribute.
3498 * This is used by EditPage subclasses when simply customizing the action
3499 * variable in the constructor is not enough. This can be used when the
3500 * EditPage lives inside of a Special page rather than a custom page action.
3502 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3503 * @return string
3505 protected function getActionURL( Title $title ) {
3506 return $title->getLocalURL( array( 'action' => $this->action ) );
3510 * Check if a page was deleted while the user was editing it, before submit.
3511 * Note that we rely on the logging table, which hasn't been always there,
3512 * but that doesn't matter, because this only applies to brand new
3513 * deletes.
3514 * @return bool
3516 protected function wasDeletedSinceLastEdit() {
3517 if ( $this->deletedSinceEdit !== null ) {
3518 return $this->deletedSinceEdit;
3521 $this->deletedSinceEdit = false;
3523 if ( !$this->mTitle->exists() && $this->mTitle->isDeletedQuick() ) {
3524 $this->lastDelete = $this->getLastDelete();
3525 if ( $this->lastDelete ) {
3526 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3527 if ( $deleteTime > $this->starttime ) {
3528 $this->deletedSinceEdit = true;
3533 return $this->deletedSinceEdit;
3537 * @return bool|stdClass
3539 protected function getLastDelete() {
3540 $dbr = wfGetDB( DB_SLAVE );
3541 $data = $dbr->selectRow(
3542 array( 'logging', 'user' ),
3543 array(
3544 'log_type',
3545 'log_action',
3546 'log_timestamp',
3547 'log_user',
3548 'log_namespace',
3549 'log_title',
3550 'log_comment',
3551 'log_params',
3552 'log_deleted',
3553 'user_name'
3554 ), array(
3555 'log_namespace' => $this->mTitle->getNamespace(),
3556 'log_title' => $this->mTitle->getDBkey(),
3557 'log_type' => 'delete',
3558 'log_action' => 'delete',
3559 'user_id=log_user'
3561 __METHOD__,
3562 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3564 // Quick paranoid permission checks...
3565 if ( is_object( $data ) ) {
3566 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3567 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3570 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3571 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3575 return $data;
3579 * Get the rendered text for previewing.
3580 * @throws MWException
3581 * @return string
3583 function getPreviewText() {
3584 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3585 global $wgAllowUserCss, $wgAllowUserJs;
3587 $stats = $wgOut->getContext()->getStats();
3589 if ( $wgRawHtml && !$this->mTokenOk ) {
3590 // Could be an offsite preview attempt. This is very unsafe if
3591 // HTML is enabled, as it could be an attack.
3592 $parsedNote = '';
3593 if ( $this->textbox1 !== '' ) {
3594 // Do not put big scary notice, if previewing the empty
3595 // string, which happens when you initially edit
3596 // a category page, due to automatic preview-on-open.
3597 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3598 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3600 $stats->increment( 'edit.failures.session_loss' );
3601 return $parsedNote;
3604 $note = '';
3606 try {
3607 $content = $this->toEditContent( $this->textbox1 );
3609 $previewHTML = '';
3610 if ( !Hooks::run(
3611 'AlternateEditPreview',
3612 array( $this, &$content, &$previewHTML, &$this->mParserOutput ) )
3614 return $previewHTML;
3617 # provide a anchor link to the editform
3618 $continueEditing = '<span class="mw-continue-editing">' .
3619 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3620 wfMessage( 'continue-editing' )->text() . ']]</span>';
3621 if ( $this->mTriedSave && !$this->mTokenOk ) {
3622 if ( $this->mTokenOkExceptSuffix ) {
3623 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3624 $stats->increment( 'edit.failures.bad_token' );
3625 } else {
3626 $note = wfMessage( 'session_fail_preview' )->plain();
3627 $stats->increment( 'edit.failures.session_loss' );
3629 } elseif ( $this->incompleteForm ) {
3630 $note = wfMessage( 'edit_form_incomplete' )->plain();
3631 if ( $this->mTriedSave ) {
3632 $stats->increment( 'edit.failures.incomplete_form' );
3634 } else {
3635 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3638 $parserOptions = $this->page->makeParserOptions( $this->mArticle->getContext() );
3639 $parserOptions->setIsPreview( true );
3640 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3642 # don't parse non-wikitext pages, show message about preview
3643 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3644 if ( $this->mTitle->isCssJsSubpage() ) {
3645 $level = 'user';
3646 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3647 $level = 'site';
3648 } else {
3649 $level = false;
3652 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3653 $format = 'css';
3654 if ( $level === 'user' && !$wgAllowUserCss ) {
3655 $format = false;
3657 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3658 $format = 'js';
3659 if ( $level === 'user' && !$wgAllowUserJs ) {
3660 $format = false;
3662 } else {
3663 $format = false;
3666 # Used messages to make sure grep find them:
3667 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3668 if ( $level && $format ) {
3669 $note = "<div id='mw-{$level}{$format}preview'>" .
3670 wfMessage( "{$level}{$format}preview" )->text() .
3671 ' ' . $continueEditing . "</div>";
3675 # If we're adding a comment, we need to show the
3676 # summary as the headline
3677 if ( $this->section === "new" && $this->summary !== "" ) {
3678 $content = $content->addSectionHeader( $this->summary );
3681 $hook_args = array( $this, &$content );
3682 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3683 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3685 $parserOptions->enableLimitReport();
3687 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3688 # But it's now deprecated, so never mind
3690 $pstContent = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3691 $scopedCallback = $parserOptions->setupFakeRevision(
3692 $this->mTitle, $pstContent, $wgUser );
3693 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
3695 # Try to stash the edit for the final submission step
3696 # @todo: different date format preferences cause cache misses
3697 ApiStashEdit::stashEditFromPreview(
3698 $this->getArticle(), $content, $pstContent,
3699 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3702 $parserOutput->setEditSectionTokens( false ); // no section edit links
3703 $previewHTML = $parserOutput->getText();
3704 $this->mParserOutput = $parserOutput;
3705 $wgOut->addParserOutputMetadata( $parserOutput );
3707 if ( count( $parserOutput->getWarnings() ) ) {
3708 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3711 ScopedCallback::consume( $scopedCallback );
3712 } catch ( MWContentSerializationException $ex ) {
3713 $m = wfMessage(
3714 'content-failed-to-parse',
3715 $this->contentModel,
3716 $this->contentFormat,
3717 $ex->getMessage()
3719 $note .= "\n\n" . $m->parse();
3720 $previewHTML = '';
3723 if ( $this->isConflict ) {
3724 $conflict = '<h2 id="mw-previewconflict">'
3725 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3726 } else {
3727 $conflict = '<hr />';
3730 $previewhead = "<div class='previewnote'>\n" .
3731 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3732 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3734 $pageViewLang = $this->mTitle->getPageViewLanguage();
3735 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3736 'class' => 'mw-content-' . $pageViewLang->getDir() );
3737 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3739 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3743 * @return array
3745 function getTemplates() {
3746 if ( $this->preview || $this->section != '' ) {
3747 $templates = array();
3748 if ( !isset( $this->mParserOutput ) ) {
3749 return $templates;
3751 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3752 foreach ( array_keys( $template ) as $dbk ) {
3753 $templates[] = Title::makeTitle( $ns, $dbk );
3756 return $templates;
3757 } else {
3758 return $this->mTitle->getTemplateLinksFrom();
3763 * Shows a bulletin board style toolbar for common editing functions.
3764 * It can be disabled in the user preferences.
3766 * @param $title Title object for the page being edited (optional)
3767 * @return string
3769 static function getEditToolbar( $title = null ) {
3770 global $wgContLang, $wgOut;
3771 global $wgEnableUploads, $wgForeignFileRepos;
3773 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3774 $showSignature = true;
3775 if ( $title ) {
3776 $showSignature = MWNamespace::wantSignatures( $title->getNamespace() );
3780 * $toolarray is an array of arrays each of which includes the
3781 * opening tag, the closing tag, optionally a sample text that is
3782 * inserted between the two when no selection is highlighted
3783 * and. The tip text is shown when the user moves the mouse
3784 * over the button.
3786 * Images are defined in ResourceLoaderEditToolbarModule.
3788 $toolarray = array(
3789 array(
3790 'id' => 'mw-editbutton-bold',
3791 'open' => '\'\'\'',
3792 'close' => '\'\'\'',
3793 'sample' => wfMessage( 'bold_sample' )->text(),
3794 'tip' => wfMessage( 'bold_tip' )->text(),
3796 array(
3797 'id' => 'mw-editbutton-italic',
3798 'open' => '\'\'',
3799 'close' => '\'\'',
3800 'sample' => wfMessage( 'italic_sample' )->text(),
3801 'tip' => wfMessage( 'italic_tip' )->text(),
3803 array(
3804 'id' => 'mw-editbutton-link',
3805 'open' => '[[',
3806 'close' => ']]',
3807 'sample' => wfMessage( 'link_sample' )->text(),
3808 'tip' => wfMessage( 'link_tip' )->text(),
3810 array(
3811 'id' => 'mw-editbutton-extlink',
3812 'open' => '[',
3813 'close' => ']',
3814 'sample' => wfMessage( 'extlink_sample' )->text(),
3815 'tip' => wfMessage( 'extlink_tip' )->text(),
3817 array(
3818 'id' => 'mw-editbutton-headline',
3819 'open' => "\n== ",
3820 'close' => " ==\n",
3821 'sample' => wfMessage( 'headline_sample' )->text(),
3822 'tip' => wfMessage( 'headline_tip' )->text(),
3824 $imagesAvailable ? array(
3825 'id' => 'mw-editbutton-image',
3826 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3827 'close' => ']]',
3828 'sample' => wfMessage( 'image_sample' )->text(),
3829 'tip' => wfMessage( 'image_tip' )->text(),
3830 ) : false,
3831 $imagesAvailable ? array(
3832 'id' => 'mw-editbutton-media',
3833 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3834 'close' => ']]',
3835 'sample' => wfMessage( 'media_sample' )->text(),
3836 'tip' => wfMessage( 'media_tip' )->text(),
3837 ) : false,
3838 array(
3839 'id' => 'mw-editbutton-nowiki',
3840 'open' => "<nowiki>",
3841 'close' => "</nowiki>",
3842 'sample' => wfMessage( 'nowiki_sample' )->text(),
3843 'tip' => wfMessage( 'nowiki_tip' )->text(),
3845 $showSignature ? array(
3846 'id' => 'mw-editbutton-signature',
3847 'open' => '--~~~~',
3848 'close' => '',
3849 'sample' => '',
3850 'tip' => wfMessage( 'sig_tip' )->text(),
3851 ) : false,
3852 array(
3853 'id' => 'mw-editbutton-hr',
3854 'open' => "\n----\n",
3855 'close' => '',
3856 'sample' => '',
3857 'tip' => wfMessage( 'hr_tip' )->text(),
3861 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3862 foreach ( $toolarray as $tool ) {
3863 if ( !$tool ) {
3864 continue;
3867 $params = array(
3868 // Images are defined in ResourceLoaderEditToolbarModule
3869 false,
3870 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3871 // Older browsers show a "speedtip" type message only for ALT.
3872 // Ideally these should be different, realistically they
3873 // probably don't need to be.
3874 $tool['tip'],
3875 $tool['open'],
3876 $tool['close'],
3877 $tool['sample'],
3878 $tool['id'],
3881 $script .= Xml::encodeJsCall(
3882 'mw.toolbar.addButton',
3883 $params,
3884 ResourceLoader::inDebugMode()
3888 $script .= '});';
3889 $wgOut->addScript( ResourceLoader::makeInlineScript( $script ) );
3891 $toolbar = '<div id="toolbar"></div>';
3893 Hooks::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3895 return $toolbar;
3899 * Returns an array of html code of the following checkboxes:
3900 * minor and watch
3902 * @param int $tabindex Current tabindex
3903 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3904 * status of the checkbox
3906 * @return array
3908 public function getCheckboxes( &$tabindex, $checked ) {
3909 global $wgUser, $wgUseMediaWikiUIEverywhere;
3911 $checkboxes = array();
3913 // don't show the minor edit checkbox if it's a new page or section
3914 if ( !$this->isNew ) {
3915 $checkboxes['minor'] = '';
3916 $minorLabel = wfMessage( 'minoredit' )->parse();
3917 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3918 $attribs = array(
3919 'tabindex' => ++$tabindex,
3920 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3921 'id' => 'wpMinoredit',
3923 $minorEditHtml =
3924 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3925 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3926 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3927 ">{$minorLabel}</label>";
3929 if ( $wgUseMediaWikiUIEverywhere ) {
3930 $checkboxes['minor'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3931 $minorEditHtml .
3932 Html::closeElement( 'div' );
3933 } else {
3934 $checkboxes['minor'] = $minorEditHtml;
3939 $watchLabel = wfMessage( 'watchthis' )->parse();
3940 $checkboxes['watch'] = '';
3941 if ( $wgUser->isLoggedIn() ) {
3942 $attribs = array(
3943 'tabindex' => ++$tabindex,
3944 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3945 'id' => 'wpWatchthis',
3947 $watchThisHtml =
3948 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3949 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3950 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3951 ">{$watchLabel}</label>";
3952 if ( $wgUseMediaWikiUIEverywhere ) {
3953 $checkboxes['watch'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3954 $watchThisHtml .
3955 Html::closeElement( 'div' );
3956 } else {
3957 $checkboxes['watch'] = $watchThisHtml;
3960 Hooks::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3961 return $checkboxes;
3965 * Returns an array of html code of the following buttons:
3966 * save, diff, preview and live
3968 * @param int $tabindex Current tabindex
3970 * @return array
3972 public function getEditButtons( &$tabindex ) {
3973 $buttons = array();
3975 $attribs = array(
3976 'id' => 'wpSave',
3977 'name' => 'wpSave',
3978 'tabindex' => ++$tabindex,
3979 ) + Linker::tooltipAndAccesskeyAttribs( 'save' );
3980 $buttons['save'] = Html::submitButton( wfMessage( 'savearticle' )->text(),
3981 $attribs, array( 'mw-ui-constructive' ) );
3983 ++$tabindex; // use the same for preview and live preview
3984 $attribs = array(
3985 'id' => 'wpPreview',
3986 'name' => 'wpPreview',
3987 'tabindex' => $tabindex,
3988 ) + Linker::tooltipAndAccesskeyAttribs( 'preview' );
3989 $buttons['preview'] = Html::submitButton( wfMessage( 'showpreview' )->text(),
3990 $attribs );
3991 $buttons['live'] = '';
3993 $attribs = array(
3994 'id' => 'wpDiff',
3995 'name' => 'wpDiff',
3996 'tabindex' => ++$tabindex,
3997 ) + Linker::tooltipAndAccesskeyAttribs( 'diff' );
3998 $buttons['diff'] = Html::submitButton( wfMessage( 'showdiff' )->text(),
3999 $attribs );
4001 Hooks::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
4002 return $buttons;
4006 * Creates a basic error page which informs the user that
4007 * they have attempted to edit a nonexistent section.
4009 function noSuchSectionPage() {
4010 global $wgOut;
4012 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
4014 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
4015 Hooks::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
4016 $wgOut->addHTML( $res );
4018 $wgOut->returnToMain( false, $this->mTitle );
4022 * Show "your edit contains spam" page with your diff and text
4024 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4026 public function spamPageWithContent( $match = false ) {
4027 global $wgOut, $wgLang;
4028 $this->textbox2 = $this->textbox1;
4030 if ( is_array( $match ) ) {
4031 $match = $wgLang->listToText( $match );
4033 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
4035 $wgOut->addHTML( '<div id="spamprotected">' );
4036 $wgOut->addWikiMsg( 'spamprotectiontext' );
4037 if ( $match ) {
4038 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4040 $wgOut->addHTML( '</div>' );
4042 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4043 $this->showDiff();
4045 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4046 $this->showTextbox2();
4048 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
4052 * Check if the browser is on a blacklist of user-agents known to
4053 * mangle UTF-8 data on form submission. Returns true if Unicode
4054 * should make it through, false if it's known to be a problem.
4055 * @return bool
4057 private function checkUnicodeCompliantBrowser() {
4058 global $wgBrowserBlackList, $wgRequest;
4060 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4061 if ( $currentbrowser === false ) {
4062 // No User-Agent header sent? Trust it by default...
4063 return true;
4066 foreach ( $wgBrowserBlackList as $browser ) {
4067 if ( preg_match( $browser, $currentbrowser ) ) {
4068 return false;
4071 return true;
4075 * Filter an input field through a Unicode de-armoring process if it
4076 * came from an old browser with known broken Unicode editing issues.
4078 * @param WebRequest $request
4079 * @param string $field
4080 * @return string
4082 protected function safeUnicodeInput( $request, $field ) {
4083 $text = rtrim( $request->getText( $field ) );
4084 return $request->getBool( 'safemode' )
4085 ? $this->unmakeSafe( $text )
4086 : $text;
4090 * Filter an output field through a Unicode armoring process if it is
4091 * going to an old browser with known broken Unicode editing issues.
4093 * @param string $text
4094 * @return string
4096 protected function safeUnicodeOutput( $text ) {
4097 global $wgContLang;
4098 $codedText = $wgContLang->recodeForEdit( $text );
4099 return $this->checkUnicodeCompliantBrowser()
4100 ? $codedText
4101 : $this->makeSafe( $codedText );
4105 * A number of web browsers are known to corrupt non-ASCII characters
4106 * in a UTF-8 text editing environment. To protect against this,
4107 * detected browsers will be served an armored version of the text,
4108 * with non-ASCII chars converted to numeric HTML character references.
4110 * Preexisting such character references will have a 0 added to them
4111 * to ensure that round-trips do not alter the original data.
4113 * @param string $invalue
4114 * @return string
4116 private function makeSafe( $invalue ) {
4117 // Armor existing references for reversibility.
4118 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
4120 $bytesleft = 0;
4121 $result = "";
4122 $working = 0;
4123 $valueLength = strlen( $invalue );
4124 for ( $i = 0; $i < $valueLength; $i++ ) {
4125 $bytevalue = ord( $invalue[$i] );
4126 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4127 $result .= chr( $bytevalue );
4128 $bytesleft = 0;
4129 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4130 $working = $working << 6;
4131 $working += ( $bytevalue & 0x3F );
4132 $bytesleft--;
4133 if ( $bytesleft <= 0 ) {
4134 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4136 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4137 $working = $bytevalue & 0x1F;
4138 $bytesleft = 1;
4139 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4140 $working = $bytevalue & 0x0F;
4141 $bytesleft = 2;
4142 } else { // 1111 0xxx
4143 $working = $bytevalue & 0x07;
4144 $bytesleft = 3;
4147 return $result;
4151 * Reverse the previously applied transliteration of non-ASCII characters
4152 * back to UTF-8. Used to protect data from corruption by broken web browsers
4153 * as listed in $wgBrowserBlackList.
4155 * @param string $invalue
4156 * @return string
4158 private function unmakeSafe( $invalue ) {
4159 $result = "";
4160 $valueLength = strlen( $invalue );
4161 for ( $i = 0; $i < $valueLength; $i++ ) {
4162 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
4163 $i += 3;
4164 $hexstring = "";
4165 do {
4166 $hexstring .= $invalue[$i];
4167 $i++;
4168 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4170 // Do some sanity checks. These aren't needed for reversibility,
4171 // but should help keep the breakage down if the editor
4172 // breaks one of the entities whilst editing.
4173 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4174 $codepoint = hexdec( $hexstring );
4175 $result .= UtfNormal\Utils::codepointToUtf8( $codepoint );
4176 } else {
4177 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4179 } else {
4180 $result .= substr( $invalue, $i, 1 );
4183 // reverse the transform that we made for reversibility reasons.
4184 return strtr( $result, array( "&#x0" => "&#x" ) );