Merge "ApiSandbox: Indicate when login is suppressed"
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * User interface for page editing.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 use MediaWiki\Logger\LoggerFactory;
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\ScopedCallback;
26
27 /**
28 * The edit page/HTML interface (split from Article)
29 * The actual database and text munging is still in Article,
30 * but it should get easier to call those from alternate
31 * interfaces.
32 *
33 * EditPage cares about two distinct titles:
34 * $this->mContextTitle is the page that forms submit to, links point to,
35 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
36 * page in the database that is actually being edited. These are
37 * usually the same, but they are now allowed to be different.
38 *
39 * Surgeon General's Warning: prolonged exposure to this class is known to cause
40 * headaches, which may be fatal.
41 */
42 class EditPage {
43 /**
44 * Status: Article successfully updated
45 */
46 const AS_SUCCESS_UPDATE = 200;
47
48 /**
49 * Status: Article successfully created
50 */
51 const AS_SUCCESS_NEW_ARTICLE = 201;
52
53 /**
54 * Status: Article update aborted by a hook function
55 */
56 const AS_HOOK_ERROR = 210;
57
58 /**
59 * Status: A hook function returned an error
60 */
61 const AS_HOOK_ERROR_EXPECTED = 212;
62
63 /**
64 * Status: User is blocked from editing this page
65 */
66 const AS_BLOCKED_PAGE_FOR_USER = 215;
67
68 /**
69 * Status: Content too big (> $wgMaxArticleSize)
70 */
71 const AS_CONTENT_TOO_BIG = 216;
72
73 /**
74 * Status: this anonymous user is not allowed to edit this page
75 */
76 const AS_READ_ONLY_PAGE_ANON = 218;
77
78 /**
79 * Status: this logged in user is not allowed to edit this page
80 */
81 const AS_READ_ONLY_PAGE_LOGGED = 219;
82
83 /**
84 * Status: wiki is in readonly mode (wfReadOnly() == true)
85 */
86 const AS_READ_ONLY_PAGE = 220;
87
88 /**
89 * Status: rate limiter for action 'edit' was tripped
90 */
91 const AS_RATE_LIMITED = 221;
92
93 /**
94 * Status: article was deleted while editing and param wpRecreate == false or form
95 * was not posted
96 */
97 const AS_ARTICLE_WAS_DELETED = 222;
98
99 /**
100 * Status: user tried to create this page, but is not allowed to do that
101 * ( Title->userCan('create') == false )
102 */
103 const AS_NO_CREATE_PERMISSION = 223;
104
105 /**
106 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
107 */
108 const AS_BLANK_ARTICLE = 224;
109
110 /**
111 * Status: (non-resolvable) edit conflict
112 */
113 const AS_CONFLICT_DETECTED = 225;
114
115 /**
116 * Status: no edit summary given and the user has forceeditsummary set and the user is not
117 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
118 */
119 const AS_SUMMARY_NEEDED = 226;
120
121 /**
122 * Status: user tried to create a new section without content
123 */
124 const AS_TEXTBOX_EMPTY = 228;
125
126 /**
127 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
128 */
129 const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
130
131 /**
132 * Status: WikiPage::doEdit() was unsuccessful
133 */
134 const AS_END = 231;
135
136 /**
137 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
138 */
139 const AS_SPAM_ERROR = 232;
140
141 /**
142 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
143 */
144 const AS_IMAGE_REDIRECT_ANON = 233;
145
146 /**
147 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
148 */
149 const AS_IMAGE_REDIRECT_LOGGED = 234;
150
151 /**
152 * Status: user tried to modify the content model, but is not allowed to do that
153 * ( User::isAllowed('editcontentmodel') == false )
154 */
155 const AS_NO_CHANGE_CONTENT_MODEL = 235;
156
157 /**
158 * Status: user tried to create self-redirect (redirect to the same article) and
159 * wpIgnoreSelfRedirect == false
160 */
161 const AS_SELF_REDIRECT = 236;
162
163 /**
164 * Status: an error relating to change tagging. Look at the message key for
165 * more details
166 */
167 const AS_CHANGE_TAG_ERROR = 237;
168
169 /**
170 * Status: can't parse content
171 */
172 const AS_PARSE_ERROR = 240;
173
174 /**
175 * Status: when changing the content model is disallowed due to
176 * $wgContentHandlerUseDB being false
177 */
178 const AS_CANNOT_USE_CUSTOM_MODEL = 241;
179
180 /**
181 * HTML id and name for the beginning of the edit form.
182 */
183 const EDITFORM_ID = 'editform';
184
185 /**
186 * Prefix of key for cookie used to pass post-edit state.
187 * The revision id edited is added after this
188 */
189 const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
190
191 /**
192 * Duration of PostEdit cookie, in seconds.
193 * The cookie will be removed instantly if the JavaScript runs.
194 *
195 * Otherwise, though, we don't want the cookies to accumulate.
196 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
197 * limit of only 20 cookies per domain. This still applies at least to some
198 * versions of IE without full updates:
199 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
200 *
201 * A value of 20 minutes should be enough to take into account slow loads and minor
202 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
203 */
204 const POST_EDIT_COOKIE_DURATION = 1200;
205
206 /** @var Article */
207 public $mArticle;
208 /** @var WikiPage */
209 private $page;
210
211 /** @var Title */
212 public $mTitle;
213
214 /** @var null|Title */
215 private $mContextTitle = null;
216
217 /** @var string */
218 public $action = 'submit';
219
220 /** @var bool */
221 public $isConflict = false;
222
223 /** @var bool */
224 public $isCssJsSubpage = false;
225
226 /** @var bool */
227 public $isCssSubpage = false;
228
229 /** @var bool */
230 public $isJsSubpage = false;
231
232 /** @var bool */
233 public $isWrongCaseCssJsPage = false;
234
235 /** @var bool New page or new section */
236 public $isNew = false;
237
238 /** @var bool */
239 public $deletedSinceEdit;
240
241 /** @var string */
242 public $formtype;
243
244 /** @var bool */
245 public $firsttime;
246
247 /** @var bool|stdClass */
248 public $lastDelete;
249
250 /** @var bool */
251 public $mTokenOk = false;
252
253 /** @var bool */
254 public $mTokenOkExceptSuffix = false;
255
256 /** @var bool */
257 public $mTriedSave = false;
258
259 /** @var bool */
260 public $incompleteForm = false;
261
262 /** @var bool */
263 public $tooBig = false;
264
265 /** @var bool */
266 public $missingComment = false;
267
268 /** @var bool */
269 public $missingSummary = false;
270
271 /** @var bool */
272 public $allowBlankSummary = false;
273
274 /** @var bool */
275 protected $blankArticle = false;
276
277 /** @var bool */
278 protected $allowBlankArticle = false;
279
280 /** @var bool */
281 protected $selfRedirect = false;
282
283 /** @var bool */
284 protected $allowSelfRedirect = false;
285
286 /** @var string */
287 public $autoSumm = '';
288
289 /** @var string */
290 public $hookError = '';
291
292 /** @var ParserOutput */
293 public $mParserOutput;
294
295 /** @var bool Has a summary been preset using GET parameter &summary= ? */
296 public $hasPresetSummary = false;
297
298 /** @var Revision|bool */
299 public $mBaseRevision = false;
300
301 /** @var bool */
302 public $mShowSummaryField = true;
303
304 # Form values
305
306 /** @var bool */
307 public $save = false;
308
309 /** @var bool */
310 public $preview = false;
311
312 /** @var bool */
313 public $diff = false;
314
315 /** @var bool */
316 public $minoredit = false;
317
318 /** @var bool */
319 public $watchthis = false;
320
321 /** @var bool */
322 public $recreate = false;
323
324 /** @var string */
325 public $textbox1 = '';
326
327 /** @var string */
328 public $textbox2 = '';
329
330 /** @var string */
331 public $summary = '';
332
333 /** @var bool */
334 public $nosummary = false;
335
336 /** @var string */
337 public $edittime = '';
338
339 /** @var integer */
340 private $editRevId = null;
341
342 /** @var string */
343 public $section = '';
344
345 /** @var string */
346 public $sectiontitle = '';
347
348 /** @var string */
349 public $starttime = '';
350
351 /** @var int */
352 public $oldid = 0;
353
354 /** @var int */
355 public $parentRevId = 0;
356
357 /** @var string */
358 public $editintro = '';
359
360 /** @var null */
361 public $scrolltop = null;
362
363 /** @var bool */
364 public $bot = true;
365
366 /** @var string */
367 public $contentModel;
368
369 /** @var null|string */
370 public $contentFormat = null;
371
372 /** @var null|array */
373 private $changeTags = null;
374
375 # Placeholders for text injection by hooks (must be HTML)
376 # extensions should take care to _append_ to the present value
377
378 /** @var string Before even the preview */
379 public $editFormPageTop = '';
380 public $editFormTextTop = '';
381 public $editFormTextBeforeContent = '';
382 public $editFormTextAfterWarn = '';
383 public $editFormTextAfterTools = '';
384 public $editFormTextBottom = '';
385 public $editFormTextAfterContent = '';
386 public $previewTextAfterContent = '';
387 public $mPreloadContent = null;
388
389 /* $didSave should be set to true whenever an article was successfully altered. */
390 public $didSave = false;
391 public $undidRev = 0;
392
393 public $suppressIntro = false;
394
395 /** @var bool */
396 protected $edit;
397
398 /** @var bool|int */
399 protected $contentLength = false;
400
401 /**
402 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
403 */
404 private $enableApiEditOverride = false;
405
406 /**
407 * @var IContextSource
408 */
409 protected $context;
410
411 /**
412 * @var bool Whether an old revision is edited
413 */
414 private $isOldRev = false;
415
416 /**
417 * @var bool Whether OOUI should be enabled here
418 */
419 private $oouiEnabled = false;
420
421 /**
422 * @param Article $article
423 */
424 public function __construct( Article $article ) {
425 global $wgOOUIEditPage;
426
427 $this->mArticle = $article;
428 $this->page = $article->getPage(); // model object
429 $this->mTitle = $article->getTitle();
430 $this->context = $article->getContext();
431
432 $this->contentModel = $this->mTitle->getContentModel();
433
434 $handler = ContentHandler::getForModelID( $this->contentModel );
435 $this->contentFormat = $handler->getDefaultFormat();
436
437 $this->oouiEnabled = $wgOOUIEditPage;
438 }
439
440 /**
441 * @return Article
442 */
443 public function getArticle() {
444 return $this->mArticle;
445 }
446
447 /**
448 * @since 1.28
449 * @return IContextSource
450 */
451 public function getContext() {
452 return $this->context;
453 }
454
455 /**
456 * @since 1.19
457 * @return Title
458 */
459 public function getTitle() {
460 return $this->mTitle;
461 }
462
463 /**
464 * Set the context Title object
465 *
466 * @param Title|null $title Title object or null
467 */
468 public function setContextTitle( $title ) {
469 $this->mContextTitle = $title;
470 }
471
472 /**
473 * Get the context title object.
474 * If not set, $wgTitle will be returned. This behavior might change in
475 * the future to return $this->mTitle instead.
476 *
477 * @return Title
478 */
479 public function getContextTitle() {
480 if ( is_null( $this->mContextTitle ) ) {
481 global $wgTitle;
482 return $wgTitle;
483 } else {
484 return $this->mContextTitle;
485 }
486 }
487
488 /**
489 * Check if the edit page is using OOUI controls
490 * @return bool
491 */
492 public function isOouiEnabled() {
493 return $this->oouiEnabled;
494 }
495
496 /**
497 * Returns if the given content model is editable.
498 *
499 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
500 * @return bool
501 * @throws MWException If $modelId has no known handler
502 */
503 public function isSupportedContentModel( $modelId ) {
504 return $this->enableApiEditOverride === true ||
505 ContentHandler::getForModelID( $modelId )->supportsDirectEditing();
506 }
507
508 /**
509 * Allow editing of content that supports API direct editing, but not general
510 * direct editing. Set to false by default.
511 *
512 * @param bool $enableOverride
513 */
514 public function setApiEditOverride( $enableOverride ) {
515 $this->enableApiEditOverride = $enableOverride;
516 }
517
518 /**
519 * @deprecated since 1.29, call edit directly
520 */
521 public function submit() {
522 $this->edit();
523 }
524
525 /**
526 * This is the function that gets called for "action=edit". It
527 * sets up various member variables, then passes execution to
528 * another function, usually showEditForm()
529 *
530 * The edit form is self-submitting, so that when things like
531 * preview and edit conflicts occur, we get the same form back
532 * with the extra stuff added. Only when the final submission
533 * is made and all is well do we actually save and redirect to
534 * the newly-edited page.
535 */
536 public function edit() {
537 global $wgOut, $wgRequest, $wgUser;
538 // Allow extensions to modify/prevent this form or submission
539 if ( !Hooks::run( 'AlternateEdit', [ $this ] ) ) {
540 return;
541 }
542
543 wfDebug( __METHOD__ . ": enter\n" );
544
545 // If they used redlink=1 and the page exists, redirect to the main article
546 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
547 $wgOut->redirect( $this->mTitle->getFullURL() );
548 return;
549 }
550
551 $this->importFormData( $wgRequest );
552 $this->firsttime = false;
553
554 if ( wfReadOnly() && $this->save ) {
555 // Force preview
556 $this->save = false;
557 $this->preview = true;
558 }
559
560 if ( $this->save ) {
561 $this->formtype = 'save';
562 } elseif ( $this->preview ) {
563 $this->formtype = 'preview';
564 } elseif ( $this->diff ) {
565 $this->formtype = 'diff';
566 } else { # First time through
567 $this->firsttime = true;
568 if ( $this->previewOnOpen() ) {
569 $this->formtype = 'preview';
570 } else {
571 $this->formtype = 'initial';
572 }
573 }
574
575 $permErrors = $this->getEditPermissionErrors( $this->save ? 'secure' : 'full' );
576 if ( $permErrors ) {
577 wfDebug( __METHOD__ . ": User can't edit\n" );
578 // Auto-block user's IP if the account was "hard" blocked
579 if ( !wfReadOnly() ) {
580 $user = $wgUser;
581 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
582 $user->spreadAnyEditBlock();
583 } );
584 }
585 $this->displayPermissionsError( $permErrors );
586
587 return;
588 }
589
590 $revision = $this->mArticle->getRevisionFetched();
591 // Disallow editing revisions with content models different from the current one
592 // Undo edits being an exception in order to allow reverting content model changes.
593 if ( $revision
594 && $revision->getContentModel() !== $this->contentModel
595 ) {
596 $prevRev = null;
597 if ( $this->undidRev ) {
598 $undidRevObj = Revision::newFromId( $this->undidRev );
599 $prevRev = $undidRevObj ? $undidRevObj->getPrevious() : null;
600 }
601 if ( !$this->undidRev
602 || !$prevRev
603 || $prevRev->getContentModel() !== $this->contentModel
604 ) {
605 $this->displayViewSourcePage(
606 $this->getContentObject(),
607 $this->context->msg(
608 'contentmodelediterror',
609 $revision->getContentModel(),
610 $this->contentModel
611 )->plain()
612 );
613 return;
614 }
615 }
616
617 $this->isConflict = false;
618 // css / js subpages of user pages get a special treatment
619 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
620 $this->isCssSubpage = $this->mTitle->isCssSubpage();
621 $this->isJsSubpage = $this->mTitle->isJsSubpage();
622 // @todo FIXME: Silly assignment.
623 $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
624
625 # Show applicable editing introductions
626 if ( $this->formtype == 'initial' || $this->firsttime ) {
627 $this->showIntro();
628 }
629
630 # Attempt submission here. This will check for edit conflicts,
631 # and redundantly check for locked database, blocked IPs, etc.
632 # that edit() already checked just in case someone tries to sneak
633 # in the back door with a hand-edited submission URL.
634
635 if ( 'save' == $this->formtype ) {
636 $resultDetails = null;
637 $status = $this->attemptSave( $resultDetails );
638 if ( !$this->handleStatus( $status, $resultDetails ) ) {
639 return;
640 }
641 }
642
643 # First time through: get contents, set time for conflict
644 # checking, etc.
645 if ( 'initial' == $this->formtype || $this->firsttime ) {
646 if ( $this->initialiseForm() === false ) {
647 $this->noSuchSectionPage();
648 return;
649 }
650
651 if ( !$this->mTitle->getArticleID() ) {
652 Hooks::run( 'EditFormPreloadText', [ &$this->textbox1, &$this->mTitle ] );
653 } else {
654 Hooks::run( 'EditFormInitialText', [ $this ] );
655 }
656
657 }
658
659 $this->showEditForm();
660 }
661
662 /**
663 * @param string $rigor Same format as Title::getUserPermissionErrors()
664 * @return array
665 */
666 protected function getEditPermissionErrors( $rigor = 'secure' ) {
667 global $wgUser;
668
669 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
670 # Can this title be created?
671 if ( !$this->mTitle->exists() ) {
672 $permErrors = array_merge(
673 $permErrors,
674 wfArrayDiff2(
675 $this->mTitle->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
676 $permErrors
677 )
678 );
679 }
680 # Ignore some permissions errors when a user is just previewing/viewing diffs
681 $remove = [];
682 foreach ( $permErrors as $error ) {
683 if ( ( $this->preview || $this->diff )
684 && (
685 $error[0] == 'blockedtext' ||
686 $error[0] == 'autoblockedtext' ||
687 $error[0] == 'systemblockedtext'
688 )
689 ) {
690 $remove[] = $error;
691 }
692 }
693 $permErrors = wfArrayDiff2( $permErrors, $remove );
694
695 return $permErrors;
696 }
697
698 /**
699 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
700 * but with the following differences:
701 * - If redlink=1, the user will be redirected to the page
702 * - If there is content to display or the error occurs while either saving,
703 * previewing or showing the difference, it will be a
704 * "View source for ..." page displaying the source code after the error message.
705 *
706 * @since 1.19
707 * @param array $permErrors Array of permissions errors, as returned by
708 * Title::getUserPermissionsErrors().
709 * @throws PermissionsError
710 */
711 protected function displayPermissionsError( array $permErrors ) {
712 global $wgRequest, $wgOut;
713
714 if ( $wgRequest->getBool( 'redlink' ) ) {
715 // The edit page was reached via a red link.
716 // Redirect to the article page and let them click the edit tab if
717 // they really want a permission error.
718 $wgOut->redirect( $this->mTitle->getFullURL() );
719 return;
720 }
721
722 $content = $this->getContentObject();
723
724 # Use the normal message if there's nothing to display
725 if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
726 $action = $this->mTitle->exists() ? 'edit' :
727 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
728 throw new PermissionsError( $action, $permErrors );
729 }
730
731 $this->displayViewSourcePage(
732 $content,
733 $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' )
734 );
735 }
736
737 /**
738 * Display a read-only View Source page
739 * @param Content $content content object
740 * @param string $errorMessage additional wikitext error message to display
741 */
742 protected function displayViewSourcePage( Content $content, $errorMessage = '' ) {
743 global $wgOut;
744
745 Hooks::run( 'EditPage::showReadOnlyForm:initial', [ $this, &$wgOut ] );
746
747 $wgOut->setRobotPolicy( 'noindex,nofollow' );
748 $wgOut->setPageTitle( $this->context->msg(
749 'viewsource-title',
750 $this->getContextTitle()->getPrefixedText()
751 ) );
752 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
753 $wgOut->addHTML( $this->editFormPageTop );
754 $wgOut->addHTML( $this->editFormTextTop );
755
756 if ( $errorMessage !== '' ) {
757 $wgOut->addWikiText( $errorMessage );
758 $wgOut->addHTML( "<hr />\n" );
759 }
760
761 # If the user made changes, preserve them when showing the markup
762 # (This happens when a user is blocked during edit, for instance)
763 if ( !$this->firsttime ) {
764 $text = $this->textbox1;
765 $wgOut->addWikiMsg( 'viewyourtext' );
766 } else {
767 try {
768 $text = $this->toEditText( $content );
769 } catch ( MWException $e ) {
770 # Serialize using the default format if the content model is not supported
771 # (e.g. for an old revision with a different model)
772 $text = $content->serialize();
773 }
774 $wgOut->addWikiMsg( 'viewsourcetext' );
775 }
776
777 $wgOut->addHTML( $this->editFormTextBeforeContent );
778 $this->showTextbox( $text, 'wpTextbox1', [ 'readonly' ] );
779 $wgOut->addHTML( $this->editFormTextAfterContent );
780
781 $wgOut->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
782
783 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
784
785 $wgOut->addHTML( $this->editFormTextBottom );
786 if ( $this->mTitle->exists() ) {
787 $wgOut->returnToMain( null, $this->mTitle );
788 }
789 }
790
791 /**
792 * Should we show a preview when the edit form is first shown?
793 *
794 * @return bool
795 */
796 protected function previewOnOpen() {
797 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
798 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
799 // Explicit override from request
800 return true;
801 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
802 // Explicit override from request
803 return false;
804 } elseif ( $this->section == 'new' ) {
805 // Nothing *to* preview for new sections
806 return false;
807 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() )
808 && $wgUser->getOption( 'previewonfirst' )
809 ) {
810 // Standard preference behavior
811 return true;
812 } elseif ( !$this->mTitle->exists()
813 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
814 && $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]
815 ) {
816 // Categories are special
817 return true;
818 } else {
819 return false;
820 }
821 }
822
823 /**
824 * Checks whether the user entered a skin name in uppercase,
825 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
826 *
827 * @return bool
828 */
829 protected function isWrongCaseCssJsPage() {
830 if ( $this->mTitle->isCssJsSubpage() ) {
831 $name = $this->mTitle->getSkinFromCssJsSubpage();
832 $skins = array_merge(
833 array_keys( Skin::getSkinNames() ),
834 [ 'common' ]
835 );
836 return !in_array( $name, $skins )
837 && in_array( strtolower( $name ), $skins );
838 } else {
839 return false;
840 }
841 }
842
843 /**
844 * Returns whether section editing is supported for the current page.
845 * Subclasses may override this to replace the default behavior, which is
846 * to check ContentHandler::supportsSections.
847 *
848 * @return bool True if this edit page supports sections, false otherwise.
849 */
850 protected function isSectionEditSupported() {
851 $contentHandler = ContentHandler::getForTitle( $this->mTitle );
852 return $contentHandler->supportsSections();
853 }
854
855 /**
856 * This function collects the form data and uses it to populate various member variables.
857 * @param WebRequest $request
858 * @throws ErrorPageError
859 */
860 public function importFormData( &$request ) {
861 global $wgContLang, $wgUser;
862
863 # Allow users to change the mode for testing
864 $this->oouiEnabled = $request->getFuzzyBool( 'ooui', $this->oouiEnabled );
865
866 # Section edit can come from either the form or a link
867 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
868
869 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
870 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
871 }
872
873 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
874
875 if ( $request->wasPosted() ) {
876 # These fields need to be checked for encoding.
877 # Also remove trailing whitespace, but don't remove _initial_
878 # whitespace from the text boxes. This may be significant formatting.
879 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
880 if ( !$request->getCheck( 'wpTextbox2' ) ) {
881 // Skip this if wpTextbox2 has input, it indicates that we came
882 // from a conflict page with raw page text, not a custom form
883 // modified by subclasses
884 $textbox1 = $this->importContentFormData( $request );
885 if ( $textbox1 !== null ) {
886 $this->textbox1 = $textbox1;
887 }
888 }
889
890 # Truncate for whole multibyte characters
891 $this->summary = $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
892
893 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
894 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
895 # section titles.
896 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
897
898 # Treat sectiontitle the same way as summary.
899 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
900 # currently doing double duty as both edit summary and section title. Right now this
901 # is just to allow API edits to work around this limitation, but this should be
902 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
903 $this->sectiontitle = $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
904 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
905
906 $this->edittime = $request->getVal( 'wpEdittime' );
907 $this->editRevId = $request->getIntOrNull( 'editRevId' );
908 $this->starttime = $request->getVal( 'wpStarttime' );
909
910 $undidRev = $request->getInt( 'wpUndidRevision' );
911 if ( $undidRev ) {
912 $this->undidRev = $undidRev;
913 }
914
915 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
916
917 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
918 // wpTextbox1 field is missing, possibly due to being "too big"
919 // according to some filter rules such as Suhosin's setting for
920 // suhosin.request.max_value_length (d'oh)
921 $this->incompleteForm = true;
922 } else {
923 // If we receive the last parameter of the request, we can fairly
924 // claim the POST request has not been truncated.
925
926 // TODO: softened the check for cutover. Once we determine
927 // that it is safe, we should complete the transition by
928 // removing the "edittime" clause.
929 $this->incompleteForm = ( !$request->getVal( 'wpUltimateParam' )
930 && is_null( $this->edittime ) );
931 }
932 if ( $this->incompleteForm ) {
933 # If the form is incomplete, force to preview.
934 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
935 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
936 $this->preview = true;
937 } else {
938 $this->preview = $request->getCheck( 'wpPreview' );
939 $this->diff = $request->getCheck( 'wpDiff' );
940
941 // Remember whether a save was requested, so we can indicate
942 // if we forced preview due to session failure.
943 $this->mTriedSave = !$this->preview;
944
945 if ( $this->tokenOk( $request ) ) {
946 # Some browsers will not report any submit button
947 # if the user hits enter in the comment box.
948 # The unmarked state will be assumed to be a save,
949 # if the form seems otherwise complete.
950 wfDebug( __METHOD__ . ": Passed token check.\n" );
951 } elseif ( $this->diff ) {
952 # Failed token check, but only requested "Show Changes".
953 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
954 } else {
955 # Page might be a hack attempt posted from
956 # an external site. Preview instead of saving.
957 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
958 $this->preview = true;
959 }
960 }
961 $this->save = !$this->preview && !$this->diff;
962 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
963 $this->edittime = null;
964 }
965
966 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
967 $this->starttime = null;
968 }
969
970 $this->recreate = $request->getCheck( 'wpRecreate' );
971
972 $this->minoredit = $request->getCheck( 'wpMinoredit' );
973 $this->watchthis = $request->getCheck( 'wpWatchthis' );
974
975 # Don't force edit summaries when a user is editing their own user or talk page
976 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
977 && $this->mTitle->getText() == $wgUser->getName()
978 ) {
979 $this->allowBlankSummary = true;
980 } else {
981 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
982 || !$wgUser->getOption( 'forceeditsummary' );
983 }
984
985 $this->autoSumm = $request->getText( 'wpAutoSummary' );
986
987 $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
988 $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
989
990 $changeTags = $request->getVal( 'wpChangeTags' );
991 if ( is_null( $changeTags ) || $changeTags === '' ) {
992 $this->changeTags = [];
993 } else {
994 $this->changeTags = array_filter( array_map( 'trim', explode( ',',
995 $changeTags ) ) );
996 }
997 } else {
998 # Not a posted form? Start with nothing.
999 wfDebug( __METHOD__ . ": Not a posted form.\n" );
1000 $this->textbox1 = '';
1001 $this->summary = '';
1002 $this->sectiontitle = '';
1003 $this->edittime = '';
1004 $this->editRevId = null;
1005 $this->starttime = wfTimestampNow();
1006 $this->edit = false;
1007 $this->preview = false;
1008 $this->save = false;
1009 $this->diff = false;
1010 $this->minoredit = false;
1011 // Watch may be overridden by request parameters
1012 $this->watchthis = $request->getBool( 'watchthis', false );
1013 $this->recreate = false;
1014
1015 // When creating a new section, we can preload a section title by passing it as the
1016 // preloadtitle parameter in the URL (T15100)
1017 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
1018 $this->sectiontitle = $request->getVal( 'preloadtitle' );
1019 // Once wpSummary isn't being use for setting section titles, we should delete this.
1020 $this->summary = $request->getVal( 'preloadtitle' );
1021 } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
1022 $this->summary = $request->getText( 'summary' );
1023 if ( $this->summary !== '' ) {
1024 $this->hasPresetSummary = true;
1025 }
1026 }
1027
1028 if ( $request->getVal( 'minor' ) ) {
1029 $this->minoredit = true;
1030 }
1031 }
1032
1033 $this->oldid = $request->getInt( 'oldid' );
1034 $this->parentRevId = $request->getInt( 'parentRevId' );
1035
1036 $this->bot = $request->getBool( 'bot', true );
1037 $this->nosummary = $request->getBool( 'nosummary' );
1038
1039 // May be overridden by revision.
1040 $this->contentModel = $request->getText( 'model', $this->contentModel );
1041 // May be overridden by revision.
1042 $this->contentFormat = $request->getText( 'format', $this->contentFormat );
1043
1044 try {
1045 $handler = ContentHandler::getForModelID( $this->contentModel );
1046 } catch ( MWUnknownContentModelException $e ) {
1047 throw new ErrorPageError(
1048 'editpage-invalidcontentmodel-title',
1049 'editpage-invalidcontentmodel-text',
1050 [ wfEscapeWikiText( $this->contentModel ) ]
1051 );
1052 }
1053
1054 if ( !$handler->isSupportedFormat( $this->contentFormat ) ) {
1055 throw new ErrorPageError(
1056 'editpage-notsupportedcontentformat-title',
1057 'editpage-notsupportedcontentformat-text',
1058 [
1059 wfEscapeWikiText( $this->contentFormat ),
1060 wfEscapeWikiText( ContentHandler::getLocalizedName( $this->contentModel ) )
1061 ]
1062 );
1063 }
1064
1065 /**
1066 * @todo Check if the desired model is allowed in this namespace, and if
1067 * a transition from the page's current model to the new model is
1068 * allowed.
1069 */
1070
1071 $this->editintro = $request->getText( 'editintro',
1072 // Custom edit intro for new sections
1073 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
1074
1075 // Allow extensions to modify form data
1076 Hooks::run( 'EditPage::importFormData', [ $this, $request ] );
1077 }
1078
1079 /**
1080 * Subpage overridable method for extracting the page content data from the
1081 * posted form to be placed in $this->textbox1, if using customized input
1082 * this method should be overridden and return the page text that will be used
1083 * for saving, preview parsing and so on...
1084 *
1085 * @param WebRequest $request
1086 * @return string|null
1087 */
1088 protected function importContentFormData( &$request ) {
1089 return; // Don't do anything, EditPage already extracted wpTextbox1
1090 }
1091
1092 /**
1093 * Initialise form fields in the object
1094 * Called on the first invocation, e.g. when a user clicks an edit link
1095 * @return bool If the requested section is valid
1096 */
1097 public function initialiseForm() {
1098 global $wgUser;
1099 $this->edittime = $this->page->getTimestamp();
1100 $this->editRevId = $this->page->getLatest();
1101
1102 $content = $this->getContentObject( false ); # TODO: track content object?!
1103 if ( $content === false ) {
1104 return false;
1105 }
1106 $this->textbox1 = $this->toEditText( $content );
1107
1108 // activate checkboxes if user wants them to be always active
1109 # Sort out the "watch" checkbox
1110 if ( $wgUser->getOption( 'watchdefault' ) ) {
1111 # Watch all edits
1112 $this->watchthis = true;
1113 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1114 # Watch creations
1115 $this->watchthis = true;
1116 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
1117 # Already watched
1118 $this->watchthis = true;
1119 }
1120 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
1121 $this->minoredit = true;
1122 }
1123 if ( $this->textbox1 === false ) {
1124 return false;
1125 }
1126 return true;
1127 }
1128
1129 /**
1130 * @param Content|null $def_content The default value to return
1131 *
1132 * @return Content|null Content on success, $def_content for invalid sections
1133 *
1134 * @since 1.21
1135 */
1136 protected function getContentObject( $def_content = null ) {
1137 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1138
1139 $content = false;
1140
1141 // For message page not locally set, use the i18n message.
1142 // For other non-existent articles, use preload text if any.
1143 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
1144 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
1145 # If this is a system message, get the default text.
1146 $msg = $this->mTitle->getDefaultMessageText();
1147
1148 $content = $this->toEditContent( $msg );
1149 }
1150 if ( $content === false ) {
1151 # If requested, preload some text.
1152 $preload = $wgRequest->getVal( 'preload',
1153 // Custom preload text for new sections
1154 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
1155 $params = $wgRequest->getArray( 'preloadparams', [] );
1156
1157 $content = $this->getPreloadedContent( $preload, $params );
1158 }
1159 // For existing pages, get text based on "undo" or section parameters.
1160 } else {
1161 if ( $this->section != '' ) {
1162 // Get section edit text (returns $def_text for invalid sections)
1163 $orig = $this->getOriginalContent( $wgUser );
1164 $content = $orig ? $orig->getSection( $this->section ) : null;
1165
1166 if ( !$content ) {
1167 $content = $def_content;
1168 }
1169 } else {
1170 $undoafter = $wgRequest->getInt( 'undoafter' );
1171 $undo = $wgRequest->getInt( 'undo' );
1172
1173 if ( $undo > 0 && $undoafter > 0 ) {
1174 $undorev = Revision::newFromId( $undo );
1175 $oldrev = Revision::newFromId( $undoafter );
1176
1177 # Sanity check, make sure it's the right page,
1178 # the revisions exist and they were not deleted.
1179 # Otherwise, $content will be left as-is.
1180 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1181 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1182 !$oldrev->isDeleted( Revision::DELETED_TEXT )
1183 ) {
1184 $content = $this->page->getUndoContent( $undorev, $oldrev );
1185
1186 if ( $content === false ) {
1187 # Warn the user that something went wrong
1188 $undoMsg = 'failure';
1189 } else {
1190 $oldContent = $this->page->getContent( Revision::RAW );
1191 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
1192 $newContent = $content->preSaveTransform( $this->mTitle, $wgUser, $popts );
1193 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1194 // The undo may change content
1195 // model if its reverting the top
1196 // edit. This can result in
1197 // mismatched content model/format.
1198 $this->contentModel = $newContent->getModel();
1199 $this->contentFormat = $oldrev->getContentFormat();
1200 }
1201
1202 if ( $newContent->equals( $oldContent ) ) {
1203 # Tell the user that the undo results in no change,
1204 # i.e. the revisions were already undone.
1205 $undoMsg = 'nochange';
1206 $content = false;
1207 } else {
1208 # Inform the user of our success and set an automatic edit summary
1209 $undoMsg = 'success';
1210
1211 # If we just undid one rev, use an autosummary
1212 $firstrev = $oldrev->getNext();
1213 if ( $firstrev && $firstrev->getId() == $undo ) {
1214 $userText = $undorev->getUserText();
1215 if ( $userText === '' ) {
1216 $undoSummary = $this->context->msg(
1217 'undo-summary-username-hidden',
1218 $undo
1219 )->inContentLanguage()->text();
1220 } else {
1221 $undoSummary = $this->context->msg(
1222 'undo-summary',
1223 $undo,
1224 $userText
1225 )->inContentLanguage()->text();
1226 }
1227 if ( $this->summary === '' ) {
1228 $this->summary = $undoSummary;
1229 } else {
1230 $this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
1231 ->inContentLanguage()->text() . $this->summary;
1232 }
1233 $this->undidRev = $undo;
1234 }
1235 $this->formtype = 'diff';
1236 }
1237 }
1238 } else {
1239 // Failed basic sanity checks.
1240 // Older revisions may have been removed since the link
1241 // was created, or we may simply have got bogus input.
1242 $undoMsg = 'norev';
1243 }
1244
1245 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1246 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1247 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
1248 $this->context->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1249 }
1250
1251 if ( $content === false ) {
1252 $content = $this->getOriginalContent( $wgUser );
1253 }
1254 }
1255 }
1256
1257 return $content;
1258 }
1259
1260 /**
1261 * Get the content of the wanted revision, without section extraction.
1262 *
1263 * The result of this function can be used to compare user's input with
1264 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1265 * to the original text of the edit.
1266 *
1267 * This differs from Article::getContent() that when a missing revision is
1268 * encountered the result will be null and not the
1269 * 'missing-revision' message.
1270 *
1271 * @since 1.19
1272 * @param User $user The user to get the revision for
1273 * @return Content|null
1274 */
1275 private function getOriginalContent( User $user ) {
1276 if ( $this->section == 'new' ) {
1277 return $this->getCurrentContent();
1278 }
1279 $revision = $this->mArticle->getRevisionFetched();
1280 if ( $revision === null ) {
1281 $handler = ContentHandler::getForModelID( $this->contentModel );
1282 return $handler->makeEmptyContent();
1283 }
1284 $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1285 return $content;
1286 }
1287
1288 /**
1289 * Get the edit's parent revision ID
1290 *
1291 * The "parent" revision is the ancestor that should be recorded in this
1292 * page's revision history. It is either the revision ID of the in-memory
1293 * article content, or in the case of a 3-way merge in order to rebase
1294 * across a recoverable edit conflict, the ID of the newer revision to
1295 * which we have rebased this page.
1296 *
1297 * @since 1.27
1298 * @return int Revision ID
1299 */
1300 public function getParentRevId() {
1301 if ( $this->parentRevId ) {
1302 return $this->parentRevId;
1303 } else {
1304 return $this->mArticle->getRevIdFetched();
1305 }
1306 }
1307
1308 /**
1309 * Get the current content of the page. This is basically similar to
1310 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1311 * content object is returned instead of null.
1312 *
1313 * @since 1.21
1314 * @return Content
1315 */
1316 protected function getCurrentContent() {
1317 $rev = $this->page->getRevision();
1318 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1319
1320 if ( $content === false || $content === null ) {
1321 $handler = ContentHandler::getForModelID( $this->contentModel );
1322 return $handler->makeEmptyContent();
1323 } elseif ( !$this->undidRev ) {
1324 // Content models should always be the same since we error
1325 // out if they are different before this point (in ->edit()).
1326 // The exception being, during an undo, the current revision might
1327 // differ from the prior revision.
1328 $logger = LoggerFactory::getInstance( 'editpage' );
1329 if ( $this->contentModel !== $rev->getContentModel() ) {
1330 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1331 'prev' => $this->contentModel,
1332 'new' => $rev->getContentModel(),
1333 'title' => $this->getTitle()->getPrefixedDBkey(),
1334 'method' => __METHOD__
1335 ] );
1336 $this->contentModel = $rev->getContentModel();
1337 }
1338
1339 // Given that the content models should match, the current selected
1340 // format should be supported.
1341 if ( !$content->isSupportedFormat( $this->contentFormat ) ) {
1342 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1343
1344 'prev' => $this->contentFormat,
1345 'new' => $rev->getContentFormat(),
1346 'title' => $this->getTitle()->getPrefixedDBkey(),
1347 'method' => __METHOD__
1348 ] );
1349 $this->contentFormat = $rev->getContentFormat();
1350 }
1351 }
1352 return $content;
1353 }
1354
1355 /**
1356 * Use this method before edit() to preload some content into the edit box
1357 *
1358 * @param Content $content
1359 *
1360 * @since 1.21
1361 */
1362 public function setPreloadedContent( Content $content ) {
1363 $this->mPreloadContent = $content;
1364 }
1365
1366 /**
1367 * Get the contents to be preloaded into the box, either set by
1368 * an earlier setPreloadText() or by loading the given page.
1369 *
1370 * @param string $preload Representing the title to preload from.
1371 * @param array $params Parameters to use (interface-message style) in the preloaded text
1372 *
1373 * @return Content
1374 *
1375 * @since 1.21
1376 */
1377 protected function getPreloadedContent( $preload, $params = [] ) {
1378 global $wgUser;
1379
1380 if ( !empty( $this->mPreloadContent ) ) {
1381 return $this->mPreloadContent;
1382 }
1383
1384 $handler = ContentHandler::getForModelID( $this->contentModel );
1385
1386 if ( $preload === '' ) {
1387 return $handler->makeEmptyContent();
1388 }
1389
1390 $title = Title::newFromText( $preload );
1391 # Check for existence to avoid getting MediaWiki:Noarticletext
1392 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1393 // TODO: somehow show a warning to the user!
1394 return $handler->makeEmptyContent();
1395 }
1396
1397 $page = WikiPage::factory( $title );
1398 if ( $page->isRedirect() ) {
1399 $title = $page->getRedirectTarget();
1400 # Same as before
1401 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1402 // TODO: somehow show a warning to the user!
1403 return $handler->makeEmptyContent();
1404 }
1405 $page = WikiPage::factory( $title );
1406 }
1407
1408 $parserOptions = ParserOptions::newFromUser( $wgUser );
1409 $content = $page->getContent( Revision::RAW );
1410
1411 if ( !$content ) {
1412 // TODO: somehow show a warning to the user!
1413 return $handler->makeEmptyContent();
1414 }
1415
1416 if ( $content->getModel() !== $handler->getModelID() ) {
1417 $converted = $content->convert( $handler->getModelID() );
1418
1419 if ( !$converted ) {
1420 // TODO: somehow show a warning to the user!
1421 wfDebug( "Attempt to preload incompatible content: " .
1422 "can't convert " . $content->getModel() .
1423 " to " . $handler->getModelID() );
1424
1425 return $handler->makeEmptyContent();
1426 }
1427
1428 $content = $converted;
1429 }
1430
1431 return $content->preloadTransform( $title, $parserOptions, $params );
1432 }
1433
1434 /**
1435 * Make sure the form isn't faking a user's credentials.
1436 *
1437 * @param WebRequest $request
1438 * @return bool
1439 * @private
1440 */
1441 public function tokenOk( &$request ) {
1442 global $wgUser;
1443 $token = $request->getVal( 'wpEditToken' );
1444 $this->mTokenOk = $wgUser->matchEditToken( $token );
1445 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1446 return $this->mTokenOk;
1447 }
1448
1449 /**
1450 * Sets post-edit cookie indicating the user just saved a particular revision.
1451 *
1452 * This uses a temporary cookie for each revision ID so separate saves will never
1453 * interfere with each other.
1454 *
1455 * Article::view deletes the cookie on server-side after the redirect and
1456 * converts the value to the global JavaScript variable wgPostEdit.
1457 *
1458 * If the variable were set on the server, it would be cached, which is unwanted
1459 * since the post-edit state should only apply to the load right after the save.
1460 *
1461 * @param int $statusValue The status value (to check for new article status)
1462 */
1463 protected function setPostEditCookie( $statusValue ) {
1464 $revisionId = $this->page->getLatest();
1465 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1466
1467 $val = 'saved';
1468 if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1469 $val = 'created';
1470 } elseif ( $this->oldid ) {
1471 $val = 'restored';
1472 }
1473
1474 $response = RequestContext::getMain()->getRequest()->response();
1475 $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION );
1476 }
1477
1478 /**
1479 * Attempt submission
1480 * @param array|bool $resultDetails See docs for $result in internalAttemptSave
1481 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1482 * @return Status The resulting status object.
1483 */
1484 public function attemptSave( &$resultDetails = false ) {
1485 global $wgUser;
1486
1487 # Allow bots to exempt some edits from bot flagging
1488 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1489 $status = $this->internalAttemptSave( $resultDetails, $bot );
1490
1491 Hooks::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1492
1493 return $status;
1494 }
1495
1496 /**
1497 * Handle status, such as after attempt save
1498 *
1499 * @param Status $status
1500 * @param array|bool $resultDetails
1501 *
1502 * @throws ErrorPageError
1503 * @return bool False, if output is done, true if rest of the form should be displayed
1504 */
1505 private function handleStatus( Status $status, $resultDetails ) {
1506 global $wgUser, $wgOut;
1507
1508 /**
1509 * @todo FIXME: once the interface for internalAttemptSave() is made
1510 * nicer, this should use the message in $status
1511 */
1512 if ( $status->value == self::AS_SUCCESS_UPDATE
1513 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1514 ) {
1515 $this->didSave = true;
1516 if ( !$resultDetails['nullEdit'] ) {
1517 $this->setPostEditCookie( $status->value );
1518 }
1519 }
1520
1521 // "wpExtraQueryRedirect" is a hidden input to modify
1522 // after save URL and is not used by actual edit form
1523 $request = RequestContext::getMain()->getRequest();
1524 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1525
1526 switch ( $status->value ) {
1527 case self::AS_HOOK_ERROR_EXPECTED:
1528 case self::AS_CONTENT_TOO_BIG:
1529 case self::AS_ARTICLE_WAS_DELETED:
1530 case self::AS_CONFLICT_DETECTED:
1531 case self::AS_SUMMARY_NEEDED:
1532 case self::AS_TEXTBOX_EMPTY:
1533 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1534 case self::AS_END:
1535 case self::AS_BLANK_ARTICLE:
1536 case self::AS_SELF_REDIRECT:
1537 return true;
1538
1539 case self::AS_HOOK_ERROR:
1540 return false;
1541
1542 case self::AS_CANNOT_USE_CUSTOM_MODEL:
1543 case self::AS_PARSE_ERROR:
1544 $wgOut->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1545 return true;
1546
1547 case self::AS_SUCCESS_NEW_ARTICLE:
1548 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1549 if ( $extraQueryRedirect ) {
1550 if ( $query === '' ) {
1551 $query = $extraQueryRedirect;
1552 } else {
1553 $query = $query . '&' . $extraQueryRedirect;
1554 }
1555 }
1556 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1557 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1558 return false;
1559
1560 case self::AS_SUCCESS_UPDATE:
1561 $extraQuery = '';
1562 $sectionanchor = $resultDetails['sectionanchor'];
1563
1564 // Give extensions a chance to modify URL query on update
1565 Hooks::run(
1566 'ArticleUpdateBeforeRedirect',
1567 [ $this->mArticle, &$sectionanchor, &$extraQuery ]
1568 );
1569
1570 if ( $resultDetails['redirect'] ) {
1571 if ( $extraQuery == '' ) {
1572 $extraQuery = 'redirect=no';
1573 } else {
1574 $extraQuery = 'redirect=no&' . $extraQuery;
1575 }
1576 }
1577 if ( $extraQueryRedirect ) {
1578 if ( $extraQuery === '' ) {
1579 $extraQuery = $extraQueryRedirect;
1580 } else {
1581 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1582 }
1583 }
1584
1585 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1586 return false;
1587
1588 case self::AS_SPAM_ERROR:
1589 $this->spamPageWithContent( $resultDetails['spam'] );
1590 return false;
1591
1592 case self::AS_BLOCKED_PAGE_FOR_USER:
1593 throw new UserBlockedError( $wgUser->getBlock() );
1594
1595 case self::AS_IMAGE_REDIRECT_ANON:
1596 case self::AS_IMAGE_REDIRECT_LOGGED:
1597 throw new PermissionsError( 'upload' );
1598
1599 case self::AS_READ_ONLY_PAGE_ANON:
1600 case self::AS_READ_ONLY_PAGE_LOGGED:
1601 throw new PermissionsError( 'edit' );
1602
1603 case self::AS_READ_ONLY_PAGE:
1604 throw new ReadOnlyError;
1605
1606 case self::AS_RATE_LIMITED:
1607 throw new ThrottledError();
1608
1609 case self::AS_NO_CREATE_PERMISSION:
1610 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1611 throw new PermissionsError( $permission );
1612
1613 case self::AS_NO_CHANGE_CONTENT_MODEL:
1614 throw new PermissionsError( 'editcontentmodel' );
1615
1616 default:
1617 // We don't recognize $status->value. The only way that can happen
1618 // is if an extension hook aborted from inside ArticleSave.
1619 // Render the status object into $this->hookError
1620 // FIXME this sucks, we should just use the Status object throughout
1621 $this->hookError = '<div class="error">' ."\n" . $status->getWikiText() .
1622 '</div>';
1623 return true;
1624 }
1625 }
1626
1627 /**
1628 * Run hooks that can filter edits just before they get saved.
1629 *
1630 * @param Content $content The Content to filter.
1631 * @param Status $status For reporting the outcome to the caller
1632 * @param User $user The user performing the edit
1633 *
1634 * @return bool
1635 */
1636 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1637 // Run old style post-section-merge edit filter
1638 if ( $this->hookError != '' ) {
1639 # ...or the hook could be expecting us to produce an error
1640 $status->fatal( 'hookaborted' );
1641 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1642 return false;
1643 }
1644
1645 // Run new style post-section-merge edit filter
1646 if ( !Hooks::run( 'EditFilterMergedContent',
1647 [ $this->mArticle->getContext(), $content, $status, $this->summary,
1648 $user, $this->minoredit ] )
1649 ) {
1650 # Error messages etc. could be handled within the hook...
1651 if ( $status->isGood() ) {
1652 $status->fatal( 'hookaborted' );
1653 // Not setting $this->hookError here is a hack to allow the hook
1654 // to cause a return to the edit page without $this->hookError
1655 // being set. This is used by ConfirmEdit to display a captcha
1656 // without any error message cruft.
1657 } else {
1658 $this->hookError = $status->getWikiText();
1659 }
1660 // Use the existing $status->value if the hook set it
1661 if ( !$status->value ) {
1662 $status->value = self::AS_HOOK_ERROR;
1663 }
1664 return false;
1665 } elseif ( !$status->isOK() ) {
1666 # ...or the hook could be expecting us to produce an error
1667 // FIXME this sucks, we should just use the Status object throughout
1668 $this->hookError = $status->getWikiText();
1669 $status->fatal( 'hookaborted' );
1670 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1671 return false;
1672 }
1673
1674 return true;
1675 }
1676
1677 /**
1678 * Return the summary to be used for a new section.
1679 *
1680 * @param string $sectionanchor Set to the section anchor text
1681 * @return string
1682 */
1683 private function newSectionSummary( &$sectionanchor = null ) {
1684 global $wgParser;
1685
1686 if ( $this->sectiontitle !== '' ) {
1687 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1688 // If no edit summary was specified, create one automatically from the section
1689 // title and have it link to the new section. Otherwise, respect the summary as
1690 // passed.
1691 if ( $this->summary === '' ) {
1692 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1693 return $this->context->msg( 'newsectionsummary' )
1694 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1695 }
1696 } elseif ( $this->summary !== '' ) {
1697 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1698 # This is a new section, so create a link to the new section
1699 # in the revision summary.
1700 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1701 return $this->context->msg( 'newsectionsummary' )
1702 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1703 }
1704 return $this->summary;
1705 }
1706
1707 /**
1708 * Attempt submission (no UI)
1709 *
1710 * @param array $result Array to add statuses to, currently with the
1711 * possible keys:
1712 * - spam (string): Spam string from content if any spam is detected by
1713 * matchSpamRegex.
1714 * - sectionanchor (string): Section anchor for a section save.
1715 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1716 * false otherwise.
1717 * - redirect (bool): Set if doEditContent is OK. True if resulting
1718 * revision is a redirect.
1719 * @param bool $bot True if edit is being made under the bot right.
1720 *
1721 * @return Status Status object, possibly with a message, but always with
1722 * one of the AS_* constants in $status->value,
1723 *
1724 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1725 * various error display idiosyncrasies. There are also lots of cases
1726 * where error metadata is set in the object and retrieved later instead
1727 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1728 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1729 * time.
1730 */
1731 public function internalAttemptSave( &$result, $bot = false ) {
1732 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1733 global $wgContentHandlerUseDB;
1734
1735 $status = Status::newGood();
1736
1737 if ( !Hooks::run( 'EditPage::attemptSave', [ $this ] ) ) {
1738 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1739 $status->fatal( 'hookaborted' );
1740 $status->value = self::AS_HOOK_ERROR;
1741 return $status;
1742 }
1743
1744 $spam = $wgRequest->getText( 'wpAntispam' );
1745 if ( $spam !== '' ) {
1746 wfDebugLog(
1747 'SimpleAntiSpam',
1748 $wgUser->getName() .
1749 ' editing "' .
1750 $this->mTitle->getPrefixedText() .
1751 '" submitted bogus field "' .
1752 $spam .
1753 '"'
1754 );
1755 $status->fatal( 'spamprotectionmatch', false );
1756 $status->value = self::AS_SPAM_ERROR;
1757 return $status;
1758 }
1759
1760 try {
1761 # Construct Content object
1762 $textbox_content = $this->toEditContent( $this->textbox1 );
1763 } catch ( MWContentSerializationException $ex ) {
1764 $status->fatal(
1765 'content-failed-to-parse',
1766 $this->contentModel,
1767 $this->contentFormat,
1768 $ex->getMessage()
1769 );
1770 $status->value = self::AS_PARSE_ERROR;
1771 return $status;
1772 }
1773
1774 # Check image redirect
1775 if ( $this->mTitle->getNamespace() == NS_FILE &&
1776 $textbox_content->isRedirect() &&
1777 !$wgUser->isAllowed( 'upload' )
1778 ) {
1779 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1780 $status->setResult( false, $code );
1781
1782 return $status;
1783 }
1784
1785 # Check for spam
1786 $match = self::matchSummarySpamRegex( $this->summary );
1787 if ( $match === false && $this->section == 'new' ) {
1788 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1789 # regular summaries, it is added to the actual wikitext.
1790 if ( $this->sectiontitle !== '' ) {
1791 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1792 $match = self::matchSpamRegex( $this->sectiontitle );
1793 } else {
1794 # This branch is taken when the "Add Topic" user interface is used, or the API
1795 # is used with the 'summary' parameter.
1796 $match = self::matchSpamRegex( $this->summary );
1797 }
1798 }
1799 if ( $match === false ) {
1800 $match = self::matchSpamRegex( $this->textbox1 );
1801 }
1802 if ( $match !== false ) {
1803 $result['spam'] = $match;
1804 $ip = $wgRequest->getIP();
1805 $pdbk = $this->mTitle->getPrefixedDBkey();
1806 $match = str_replace( "\n", '', $match );
1807 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1808 $status->fatal( 'spamprotectionmatch', $match );
1809 $status->value = self::AS_SPAM_ERROR;
1810 return $status;
1811 }
1812 if ( !Hooks::run(
1813 'EditFilter',
1814 [ $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ] )
1815 ) {
1816 # Error messages etc. could be handled within the hook...
1817 $status->fatal( 'hookaborted' );
1818 $status->value = self::AS_HOOK_ERROR;
1819 return $status;
1820 } elseif ( $this->hookError != '' ) {
1821 # ...or the hook could be expecting us to produce an error
1822 $status->fatal( 'hookaborted' );
1823 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1824 return $status;
1825 }
1826
1827 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1828 // Auto-block user's IP if the account was "hard" blocked
1829 if ( !wfReadOnly() ) {
1830 $wgUser->spreadAnyEditBlock();
1831 }
1832 # Check block state against master, thus 'false'.
1833 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1834 return $status;
1835 }
1836
1837 $this->contentLength = strlen( $this->textbox1 );
1838 if ( $this->contentLength > $wgMaxArticleSize * 1024 ) {
1839 // Error will be displayed by showEditForm()
1840 $this->tooBig = true;
1841 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1842 return $status;
1843 }
1844
1845 if ( !$wgUser->isAllowed( 'edit' ) ) {
1846 if ( $wgUser->isAnon() ) {
1847 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1848 return $status;
1849 } else {
1850 $status->fatal( 'readonlytext' );
1851 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1852 return $status;
1853 }
1854 }
1855
1856 $changingContentModel = false;
1857 if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
1858 if ( !$wgContentHandlerUseDB ) {
1859 $status->fatal( 'editpage-cannot-use-custom-model' );
1860 $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
1861 return $status;
1862 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1863 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1864 return $status;
1865 }
1866 // Make sure the user can edit the page under the new content model too
1867 $titleWithNewContentModel = clone $this->mTitle;
1868 $titleWithNewContentModel->setContentModel( $this->contentModel );
1869 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $wgUser )
1870 || !$titleWithNewContentModel->userCan( 'edit', $wgUser )
1871 ) {
1872 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1873 return $status;
1874 }
1875
1876 $changingContentModel = true;
1877 $oldContentModel = $this->mTitle->getContentModel();
1878 }
1879
1880 if ( $this->changeTags ) {
1881 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
1882 $this->changeTags, $wgUser );
1883 if ( !$changeTagsStatus->isOK() ) {
1884 $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
1885 return $changeTagsStatus;
1886 }
1887 }
1888
1889 if ( wfReadOnly() ) {
1890 $status->fatal( 'readonlytext' );
1891 $status->value = self::AS_READ_ONLY_PAGE;
1892 return $status;
1893 }
1894 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 )
1895 || ( $changingContentModel && $wgUser->pingLimiter( 'editcontentmodel' ) )
1896 ) {
1897 $status->fatal( 'actionthrottledtext' );
1898 $status->value = self::AS_RATE_LIMITED;
1899 return $status;
1900 }
1901
1902 # If the article has been deleted while editing, don't save it without
1903 # confirmation
1904 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1905 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1906 return $status;
1907 }
1908
1909 # Load the page data from the master. If anything changes in the meantime,
1910 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1911 $this->page->loadPageData( 'fromdbmaster' );
1912 $new = !$this->page->exists();
1913
1914 if ( $new ) {
1915 // Late check for create permission, just in case *PARANOIA*
1916 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1917 $status->fatal( 'nocreatetext' );
1918 $status->value = self::AS_NO_CREATE_PERMISSION;
1919 wfDebug( __METHOD__ . ": no create permission\n" );
1920 return $status;
1921 }
1922
1923 // Don't save a new page if it's blank or if it's a MediaWiki:
1924 // message with content equivalent to default (allow empty pages
1925 // in this case to disable messages, see T52124)
1926 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1927 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1928 $defaultText = $defaultMessageText;
1929 } else {
1930 $defaultText = '';
1931 }
1932
1933 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1934 $this->blankArticle = true;
1935 $status->fatal( 'blankarticle' );
1936 $status->setResult( false, self::AS_BLANK_ARTICLE );
1937 return $status;
1938 }
1939
1940 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1941 return $status;
1942 }
1943
1944 $content = $textbox_content;
1945
1946 $result['sectionanchor'] = '';
1947 if ( $this->section == 'new' ) {
1948 if ( $this->sectiontitle !== '' ) {
1949 // Insert the section title above the content.
1950 $content = $content->addSectionHeader( $this->sectiontitle );
1951 } elseif ( $this->summary !== '' ) {
1952 // Insert the section title above the content.
1953 $content = $content->addSectionHeader( $this->summary );
1954 }
1955 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
1956 }
1957
1958 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1959
1960 } else { # not $new
1961
1962 # Article exists. Check for edit conflict.
1963
1964 $this->page->clear(); # Force reload of dates, etc.
1965 $timestamp = $this->page->getTimestamp();
1966 $latest = $this->page->getLatest();
1967
1968 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1969
1970 // Check editRevId if set, which handles same-second timestamp collisions
1971 if ( $timestamp != $this->edittime
1972 || ( $this->editRevId !== null && $this->editRevId != $latest )
1973 ) {
1974 $this->isConflict = true;
1975 if ( $this->section == 'new' ) {
1976 if ( $this->page->getUserText() == $wgUser->getName() &&
1977 $this->page->getComment() == $this->newSectionSummary()
1978 ) {
1979 // Probably a duplicate submission of a new comment.
1980 // This can happen when CDN resends a request after
1981 // a timeout but the first one actually went through.
1982 wfDebug( __METHOD__
1983 . ": duplicate new section submission; trigger edit conflict!\n" );
1984 } else {
1985 // New comment; suppress conflict.
1986 $this->isConflict = false;
1987 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1988 }
1989 } elseif ( $this->section == ''
1990 && Revision::userWasLastToEdit(
1991 DB_MASTER, $this->mTitle->getArticleID(),
1992 $wgUser->getId(), $this->edittime
1993 )
1994 ) {
1995 # Suppress edit conflict with self, except for section edits where merging is required.
1996 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1997 $this->isConflict = false;
1998 }
1999 }
2000
2001 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2002 if ( $this->sectiontitle !== '' ) {
2003 $sectionTitle = $this->sectiontitle;
2004 } else {
2005 $sectionTitle = $this->summary;
2006 }
2007
2008 $content = null;
2009
2010 if ( $this->isConflict ) {
2011 wfDebug( __METHOD__
2012 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2013 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2014 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2015 // ...or disable section editing for non-current revisions (not exposed anyway).
2016 if ( $this->editRevId !== null ) {
2017 $content = $this->page->replaceSectionAtRev(
2018 $this->section,
2019 $textbox_content,
2020 $sectionTitle,
2021 $this->editRevId
2022 );
2023 } else {
2024 $content = $this->page->replaceSectionContent(
2025 $this->section,
2026 $textbox_content,
2027 $sectionTitle,
2028 $this->edittime
2029 );
2030 }
2031 } else {
2032 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
2033 $content = $this->page->replaceSectionContent(
2034 $this->section,
2035 $textbox_content,
2036 $sectionTitle
2037 );
2038 }
2039
2040 if ( is_null( $content ) ) {
2041 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
2042 $this->isConflict = true;
2043 $content = $textbox_content; // do not try to merge here!
2044 } elseif ( $this->isConflict ) {
2045 # Attempt merge
2046 if ( $this->mergeChangesIntoContent( $content ) ) {
2047 // Successful merge! Maybe we should tell the user the good news?
2048 $this->isConflict = false;
2049 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
2050 } else {
2051 $this->section = '';
2052 $this->textbox1 = ContentHandler::getContentText( $content );
2053 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
2054 }
2055 }
2056
2057 if ( $this->isConflict ) {
2058 $status->setResult( false, self::AS_CONFLICT_DETECTED );
2059 return $status;
2060 }
2061
2062 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
2063 return $status;
2064 }
2065
2066 if ( $this->section == 'new' ) {
2067 // Handle the user preference to force summaries here
2068 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
2069 $this->missingSummary = true;
2070 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2071 $status->value = self::AS_SUMMARY_NEEDED;
2072 return $status;
2073 }
2074
2075 // Do not allow the user to post an empty comment
2076 if ( $this->textbox1 == '' ) {
2077 $this->missingComment = true;
2078 $status->fatal( 'missingcommenttext' );
2079 $status->value = self::AS_TEXTBOX_EMPTY;
2080 return $status;
2081 }
2082 } elseif ( !$this->allowBlankSummary
2083 && !$content->equals( $this->getOriginalContent( $wgUser ) )
2084 && !$content->isRedirect()
2085 && md5( $this->summary ) == $this->autoSumm
2086 ) {
2087 $this->missingSummary = true;
2088 $status->fatal( 'missingsummary' );
2089 $status->value = self::AS_SUMMARY_NEEDED;
2090 return $status;
2091 }
2092
2093 # All's well
2094 $sectionanchor = '';
2095 if ( $this->section == 'new' ) {
2096 $this->summary = $this->newSectionSummary( $sectionanchor );
2097 } elseif ( $this->section != '' ) {
2098 # Try to get a section anchor from the section source, redirect
2099 # to edited section if header found.
2100 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2101 # for duplicate heading checking and maybe parsing.
2102 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
2103 # We can't deal with anchors, includes, html etc in the header for now,
2104 # headline would need to be parsed to improve this.
2105 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2106 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
2107 }
2108 }
2109 $result['sectionanchor'] = $sectionanchor;
2110
2111 // Save errors may fall down to the edit form, but we've now
2112 // merged the section into full text. Clear the section field
2113 // so that later submission of conflict forms won't try to
2114 // replace that into a duplicated mess.
2115 $this->textbox1 = $this->toEditText( $content );
2116 $this->section = '';
2117
2118 $status->value = self::AS_SUCCESS_UPDATE;
2119 }
2120
2121 if ( !$this->allowSelfRedirect
2122 && $content->isRedirect()
2123 && $content->getRedirectTarget()->equals( $this->getTitle() )
2124 ) {
2125 // If the page already redirects to itself, don't warn.
2126 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2127 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
2128 $this->selfRedirect = true;
2129 $status->fatal( 'selfredirect' );
2130 $status->value = self::AS_SELF_REDIRECT;
2131 return $status;
2132 }
2133 }
2134
2135 // Check for length errors again now that the section is merged in
2136 $this->contentLength = strlen( $this->toEditText( $content ) );
2137 if ( $this->contentLength > $wgMaxArticleSize * 1024 ) {
2138 $this->tooBig = true;
2139 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
2140 return $status;
2141 }
2142
2143 $flags = EDIT_AUTOSUMMARY |
2144 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
2145 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
2146 ( $bot ? EDIT_FORCE_BOT : 0 );
2147
2148 $doEditStatus = $this->page->doEditContent(
2149 $content,
2150 $this->summary,
2151 $flags,
2152 false,
2153 $wgUser,
2154 $content->getDefaultFormat(),
2155 $this->changeTags,
2156 $this->undidRev
2157 );
2158
2159 if ( !$doEditStatus->isOK() ) {
2160 // Failure from doEdit()
2161 // Show the edit conflict page for certain recognized errors from doEdit(),
2162 // but don't show it for errors from extension hooks
2163 $errors = $doEditStatus->getErrorsArray();
2164 if ( in_array( $errors[0][0],
2165 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2166 ) {
2167 $this->isConflict = true;
2168 // Destroys data doEdit() put in $status->value but who cares
2169 $doEditStatus->value = self::AS_END;
2170 }
2171 return $doEditStatus;
2172 }
2173
2174 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2175 if ( $result['nullEdit'] ) {
2176 // We don't know if it was a null edit until now, so increment here
2177 $wgUser->pingLimiter( 'linkpurge' );
2178 }
2179 $result['redirect'] = $content->isRedirect();
2180
2181 $this->updateWatchlist();
2182
2183 // If the content model changed, add a log entry
2184 if ( $changingContentModel ) {
2185 $this->addContentModelChangeLogEntry(
2186 $wgUser,
2187 $new ? false : $oldContentModel,
2188 $this->contentModel,
2189 $this->summary
2190 );
2191 }
2192
2193 return $status;
2194 }
2195
2196 /**
2197 * @param User $user
2198 * @param string|false $oldModel false if the page is being newly created
2199 * @param string $newModel
2200 * @param string $reason
2201 */
2202 protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
2203 $new = $oldModel === false;
2204 $log = new ManualLogEntry( 'contentmodel', $new ? 'new' : 'change' );
2205 $log->setPerformer( $user );
2206 $log->setTarget( $this->mTitle );
2207 $log->setComment( $reason );
2208 $log->setParameters( [
2209 '4::oldmodel' => $oldModel,
2210 '5::newmodel' => $newModel
2211 ] );
2212 $logid = $log->insert();
2213 $log->publish( $logid );
2214 }
2215
2216 /**
2217 * Register the change of watch status
2218 */
2219 protected function updateWatchlist() {
2220 global $wgUser;
2221
2222 if ( !$wgUser->isLoggedIn() ) {
2223 return;
2224 }
2225
2226 $user = $wgUser;
2227 $title = $this->mTitle;
2228 $watch = $this->watchthis;
2229 // Do this in its own transaction to reduce contention...
2230 DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
2231 if ( $watch == $user->isWatched( $title, User::IGNORE_USER_RIGHTS ) ) {
2232 return; // nothing to change
2233 }
2234 WatchAction::doWatchOrUnwatch( $watch, $title, $user );
2235 } );
2236 }
2237
2238 /**
2239 * Attempts to do 3-way merge of edit content with a base revision
2240 * and current content, in case of edit conflict, in whichever way appropriate
2241 * for the content type.
2242 *
2243 * @since 1.21
2244 *
2245 * @param Content $editContent
2246 *
2247 * @return bool
2248 */
2249 private function mergeChangesIntoContent( &$editContent ) {
2250 $db = wfGetDB( DB_MASTER );
2251
2252 // This is the revision the editor started from
2253 $baseRevision = $this->getBaseRevision();
2254 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2255
2256 if ( is_null( $baseContent ) ) {
2257 return false;
2258 }
2259
2260 // The current state, we want to merge updates into it
2261 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2262 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2263
2264 if ( is_null( $currentContent ) ) {
2265 return false;
2266 }
2267
2268 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2269
2270 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2271
2272 if ( $result ) {
2273 $editContent = $result;
2274 // Update parentRevId to what we just merged.
2275 $this->parentRevId = $currentRevision->getId();
2276 return true;
2277 }
2278
2279 return false;
2280 }
2281
2282 /**
2283 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2284 * one might think of X as the "base revision", which is NOT what this returns.
2285 * @return Revision Current version when the edit was started
2286 */
2287 public function getBaseRevision() {
2288 if ( !$this->mBaseRevision ) {
2289 $db = wfGetDB( DB_MASTER );
2290 $this->mBaseRevision = $this->editRevId
2291 ? Revision::newFromId( $this->editRevId, Revision::READ_LATEST )
2292 : Revision::loadFromTimestamp( $db, $this->mTitle, $this->edittime );
2293 }
2294 return $this->mBaseRevision;
2295 }
2296
2297 /**
2298 * Check given input text against $wgSpamRegex, and return the text of the first match.
2299 *
2300 * @param string $text
2301 *
2302 * @return string|bool Matching string or false
2303 */
2304 public static function matchSpamRegex( $text ) {
2305 global $wgSpamRegex;
2306 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2307 $regexes = (array)$wgSpamRegex;
2308 return self::matchSpamRegexInternal( $text, $regexes );
2309 }
2310
2311 /**
2312 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2313 *
2314 * @param string $text
2315 *
2316 * @return string|bool Matching string or false
2317 */
2318 public static function matchSummarySpamRegex( $text ) {
2319 global $wgSummarySpamRegex;
2320 $regexes = (array)$wgSummarySpamRegex;
2321 return self::matchSpamRegexInternal( $text, $regexes );
2322 }
2323
2324 /**
2325 * @param string $text
2326 * @param array $regexes
2327 * @return bool|string
2328 */
2329 protected static function matchSpamRegexInternal( $text, $regexes ) {
2330 foreach ( $regexes as $regex ) {
2331 $matches = [];
2332 if ( preg_match( $regex, $text, $matches ) ) {
2333 return $matches[0];
2334 }
2335 }
2336 return false;
2337 }
2338
2339 public function setHeaders() {
2340 global $wgOut, $wgUser, $wgAjaxEditStash;
2341
2342 $wgOut->addModules( 'mediawiki.action.edit' );
2343 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2344
2345 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2346 // The addition of default buttons is handled by getEditToolbar() which
2347 // has its own dependency on this module. The call here ensures the module
2348 // is loaded in time (it has position "top") for other modules to register
2349 // buttons (e.g. extensions, gadgets, user scripts).
2350 $wgOut->addModules( 'mediawiki.toolbar' );
2351 }
2352
2353 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2354 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2355 }
2356
2357 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2358 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2359 }
2360
2361 # Enabled article-related sidebar, toplinks, etc.
2362 $wgOut->setArticleRelated( true );
2363
2364 $contextTitle = $this->getContextTitle();
2365 if ( $this->isConflict ) {
2366 $msg = 'editconflict';
2367 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2368 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2369 } else {
2370 $msg = $contextTitle->exists()
2371 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2372 && $contextTitle->getDefaultMessageText() !== false
2373 )
2374 ? 'editing'
2375 : 'creating';
2376 }
2377
2378 # Use the title defined by DISPLAYTITLE magic word when present
2379 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2380 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2381 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2382 if ( $displayTitle === false ) {
2383 $displayTitle = $contextTitle->getPrefixedText();
2384 }
2385 $wgOut->setPageTitle( $this->context->msg( $msg, $displayTitle ) );
2386 # Transmit the name of the message to JavaScript for live preview
2387 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2388 $wgOut->addJsConfigVars( [
2389 'wgEditMessage' => $msg,
2390 'wgAjaxEditStash' => $wgAjaxEditStash,
2391 ] );
2392 }
2393
2394 /**
2395 * Show all applicable editing introductions
2396 */
2397 protected function showIntro() {
2398 global $wgOut, $wgUser;
2399 if ( $this->suppressIntro ) {
2400 return;
2401 }
2402
2403 $namespace = $this->mTitle->getNamespace();
2404
2405 if ( $namespace == NS_MEDIAWIKI ) {
2406 # Show a warning if editing an interface message
2407 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2408 # If this is a default message (but not css or js),
2409 # show a hint that it is translatable on translatewiki.net
2410 if ( !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2411 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2412 ) {
2413 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2414 if ( $defaultMessageText !== false ) {
2415 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2416 'translateinterface' );
2417 }
2418 }
2419 } elseif ( $namespace == NS_FILE ) {
2420 # Show a hint to shared repo
2421 $file = wfFindFile( $this->mTitle );
2422 if ( $file && !$file->isLocal() ) {
2423 $descUrl = $file->getDescriptionUrl();
2424 # there must be a description url to show a hint to shared repo
2425 if ( $descUrl ) {
2426 if ( !$this->mTitle->exists() ) {
2427 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2428 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2429 ] );
2430 } else {
2431 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2432 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2433 ] );
2434 }
2435 }
2436 }
2437 }
2438
2439 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2440 # Show log extract when the user is currently blocked
2441 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2442 $username = explode( '/', $this->mTitle->getText(), 2 )[0];
2443 $user = User::newFromName( $username, false /* allow IP users */ );
2444 $ip = User::isIP( $username );
2445 $block = Block::newFromTarget( $user, $user );
2446 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2447 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2448 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2449 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2450 # Show log extract if the user is currently blocked
2451 LogEventsList::showLogExtract(
2452 $wgOut,
2453 'block',
2454 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2455 '',
2456 [
2457 'lim' => 1,
2458 'showIfEmpty' => false,
2459 'msgKey' => [
2460 'blocked-notice-logextract',
2461 $user->getName() # Support GENDER in notice
2462 ]
2463 ]
2464 );
2465 }
2466 }
2467 # Try to add a custom edit intro, or use the standard one if this is not possible.
2468 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2469 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2470 $this->context->msg( 'helppage' )->inContentLanguage()->text()
2471 ) );
2472 if ( $wgUser->isLoggedIn() ) {
2473 $wgOut->wrapWikiMsg(
2474 // Suppress the external link icon, consider the help url an internal one
2475 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2476 [
2477 'newarticletext',
2478 $helpLink
2479 ]
2480 );
2481 } else {
2482 $wgOut->wrapWikiMsg(
2483 // Suppress the external link icon, consider the help url an internal one
2484 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2485 [
2486 'newarticletextanon',
2487 $helpLink
2488 ]
2489 );
2490 }
2491 }
2492 # Give a notice if the user is editing a deleted/moved page...
2493 if ( !$this->mTitle->exists() ) {
2494 $dbr = wfGetDB( DB_REPLICA );
2495
2496 LogEventsList::showLogExtract( $wgOut, [ 'delete', 'move' ], $this->mTitle,
2497 '',
2498 [
2499 'lim' => 10,
2500 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2501 'showIfEmpty' => false,
2502 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2503 ]
2504 );
2505 }
2506 }
2507
2508 /**
2509 * Attempt to show a custom editing introduction, if supplied
2510 *
2511 * @return bool
2512 */
2513 protected function showCustomIntro() {
2514 if ( $this->editintro ) {
2515 $title = Title::newFromText( $this->editintro );
2516 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2517 global $wgOut;
2518 // Added using template syntax, to take <noinclude>'s into account.
2519 $wgOut->addWikiTextTitleTidy(
2520 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2521 $this->mTitle
2522 );
2523 return true;
2524 }
2525 }
2526 return false;
2527 }
2528
2529 /**
2530 * Gets an editable textual representation of $content.
2531 * The textual representation can be turned by into a Content object by the
2532 * toEditContent() method.
2533 *
2534 * If $content is null or false or a string, $content is returned unchanged.
2535 *
2536 * If the given Content object is not of a type that can be edited using
2537 * the text base EditPage, an exception will be raised. Set
2538 * $this->allowNonTextContent to true to allow editing of non-textual
2539 * content.
2540 *
2541 * @param Content|null|bool|string $content
2542 * @return string The editable text form of the content.
2543 *
2544 * @throws MWException If $content is not an instance of TextContent and
2545 * $this->allowNonTextContent is not true.
2546 */
2547 protected function toEditText( $content ) {
2548 if ( $content === null || $content === false || is_string( $content ) ) {
2549 return $content;
2550 }
2551
2552 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2553 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2554 }
2555
2556 return $content->serialize( $this->contentFormat );
2557 }
2558
2559 /**
2560 * Turns the given text into a Content object by unserializing it.
2561 *
2562 * If the resulting Content object is not of a type that can be edited using
2563 * the text base EditPage, an exception will be raised. Set
2564 * $this->allowNonTextContent to true to allow editing of non-textual
2565 * content.
2566 *
2567 * @param string|null|bool $text Text to unserialize
2568 * @return Content|bool|null The content object created from $text. If $text was false
2569 * or null, false resp. null will be returned instead.
2570 *
2571 * @throws MWException If unserializing the text results in a Content
2572 * object that is not an instance of TextContent and
2573 * $this->allowNonTextContent is not true.
2574 */
2575 protected function toEditContent( $text ) {
2576 if ( $text === false || $text === null ) {
2577 return $text;
2578 }
2579
2580 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2581 $this->contentModel, $this->contentFormat );
2582
2583 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2584 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2585 }
2586
2587 return $content;
2588 }
2589
2590 /**
2591 * Send the edit form and related headers to $wgOut
2592 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2593 * during form output near the top, for captchas and the like.
2594 *
2595 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2596 * use the EditPage::showEditForm:fields hook instead.
2597 */
2598 public function showEditForm( $formCallback = null ) {
2599 global $wgOut, $wgUser;
2600
2601 # need to parse the preview early so that we know which templates are used,
2602 # otherwise users with "show preview after edit box" will get a blank list
2603 # we parse this near the beginning so that setHeaders can do the title
2604 # setting work instead of leaving it in getPreviewText
2605 $previewOutput = '';
2606 if ( $this->formtype == 'preview' ) {
2607 $previewOutput = $this->getPreviewText();
2608 }
2609
2610 // Avoid PHP 7.1 warning of passing $this by reference
2611 $editPage = $this;
2612 Hooks::run( 'EditPage::showEditForm:initial', [ &$editPage, &$wgOut ] );
2613
2614 $this->setHeaders();
2615
2616 $this->addTalkPageText();
2617 $this->addEditNotices();
2618
2619 if ( !$this->isConflict &&
2620 $this->section != '' &&
2621 !$this->isSectionEditSupported() ) {
2622 // We use $this->section to much before this and getVal('wgSection') directly in other places
2623 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2624 // Someone is welcome to try refactoring though
2625 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2626 return;
2627 }
2628
2629 $this->showHeader();
2630
2631 $wgOut->addHTML( $this->editFormPageTop );
2632
2633 if ( $wgUser->getOption( 'previewontop' ) ) {
2634 $this->displayPreviewArea( $previewOutput, true );
2635 }
2636
2637 $wgOut->addHTML( $this->editFormTextTop );
2638
2639 $showToolbar = true;
2640 if ( $this->wasDeletedSinceLastEdit() ) {
2641 if ( $this->formtype == 'save' ) {
2642 // Hide the toolbar and edit area, user can click preview to get it back
2643 // Add an confirmation checkbox and explanation.
2644 $showToolbar = false;
2645 } else {
2646 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2647 'deletedwhileediting' );
2648 }
2649 }
2650
2651 // @todo add EditForm plugin interface and use it here!
2652 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2653 $wgOut->addHTML( Html::openElement(
2654 'form',
2655 [
2656 'class' => $this->oouiEnabled ? 'mw-editform-ooui' : 'mw-editform-legacy',
2657 'id' => self::EDITFORM_ID,
2658 'name' => self::EDITFORM_ID,
2659 'method' => 'post',
2660 'action' => $this->getActionURL( $this->getContextTitle() ),
2661 'enctype' => 'multipart/form-data'
2662 ]
2663 ) );
2664
2665 if ( is_callable( $formCallback ) ) {
2666 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2667 call_user_func_array( $formCallback, [ &$wgOut ] );
2668 }
2669
2670 // Add an empty field to trip up spambots
2671 $wgOut->addHTML(
2672 Xml::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2673 . Html::rawElement(
2674 'label',
2675 [ 'for' => 'wpAntispam' ],
2676 $this->context->msg( 'simpleantispam-label' )->parse()
2677 )
2678 . Xml::element(
2679 'input',
2680 [
2681 'type' => 'text',
2682 'name' => 'wpAntispam',
2683 'id' => 'wpAntispam',
2684 'value' => ''
2685 ]
2686 )
2687 . Xml::closeElement( 'div' )
2688 );
2689
2690 // Avoid PHP 7.1 warning of passing $this by reference
2691 $editPage = $this;
2692 Hooks::run( 'EditPage::showEditForm:fields', [ &$editPage, &$wgOut ] );
2693
2694 // Put these up at the top to ensure they aren't lost on early form submission
2695 $this->showFormBeforeText();
2696
2697 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2698 $username = $this->lastDelete->user_name;
2699 $comment = $this->lastDelete->log_comment;
2700
2701 // It is better to not parse the comment at all than to have templates expanded in the middle
2702 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2703 $key = $comment === ''
2704 ? 'confirmrecreate-noreason'
2705 : 'confirmrecreate';
2706 $wgOut->addHTML(
2707 '<div class="mw-confirm-recreate">' .
2708 $this->context->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2709 Xml::checkLabel( $this->context->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2710 [ 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2711 ) .
2712 '</div>'
2713 );
2714 }
2715
2716 # When the summary is hidden, also hide them on preview/show changes
2717 if ( $this->nosummary ) {
2718 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2719 }
2720
2721 # If a blank edit summary was previously provided, and the appropriate
2722 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2723 # user being bounced back more than once in the event that a summary
2724 # is not required.
2725 # ####
2726 # For a bit more sophisticated detection of blank summaries, hash the
2727 # automatic one and pass that in the hidden field wpAutoSummary.
2728 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2729 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2730 }
2731
2732 if ( $this->undidRev ) {
2733 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2734 }
2735
2736 if ( $this->selfRedirect ) {
2737 $wgOut->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2738 }
2739
2740 if ( $this->hasPresetSummary ) {
2741 // If a summary has been preset using &summary= we don't want to prompt for
2742 // a different summary. Only prompt for a summary if the summary is blanked.
2743 // (T19416)
2744 $this->autoSumm = md5( '' );
2745 }
2746
2747 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2748 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2749
2750 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2751 $wgOut->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
2752
2753 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2754 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2755
2756 // Preserve &ooui=1 / &ooui=0 from URL parameters after submitting the page for preview
2757 $wgOut->addHTML( Html::hidden( 'ooui', $this->oouiEnabled ? '1' : '0' ) );
2758
2759 // following functions will need OOUI, enable it only once; here.
2760 if ( $this->oouiEnabled ) {
2761 $wgOut->enableOOUI();
2762 }
2763
2764 if ( $this->section == 'new' ) {
2765 $this->showSummaryInput( true, $this->summary );
2766 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2767 }
2768
2769 $wgOut->addHTML( $this->editFormTextBeforeContent );
2770
2771 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2772 $wgOut->addHTML( EditPage::getEditToolbar( $this->mTitle ) );
2773 }
2774
2775 if ( $this->blankArticle ) {
2776 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2777 }
2778
2779 if ( $this->isConflict ) {
2780 // In an edit conflict bypass the overridable content form method
2781 // and fallback to the raw wpTextbox1 since editconflicts can't be
2782 // resolved between page source edits and custom ui edits using the
2783 // custom edit ui.
2784 $this->textbox2 = $this->textbox1;
2785
2786 $content = $this->getCurrentContent();
2787 $this->textbox1 = $this->toEditText( $content );
2788
2789 $this->showTextbox1();
2790 } else {
2791 $this->showContentForm();
2792 }
2793
2794 $wgOut->addHTML( $this->editFormTextAfterContent );
2795
2796 $this->showStandardInputs();
2797
2798 $this->showFormAfterText();
2799
2800 $this->showTosSummary();
2801
2802 $this->showEditTools();
2803
2804 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2805
2806 $wgOut->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2807
2808 $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'hiddencats' ],
2809 Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
2810
2811 $wgOut->addHTML( Html::rawElement( 'div', [ 'class' => 'limitreport' ],
2812 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2813
2814 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2815
2816 if ( $this->isConflict ) {
2817 try {
2818 $this->showConflict();
2819 } catch ( MWContentSerializationException $ex ) {
2820 // this can't really happen, but be nice if it does.
2821 $msg = $this->context->msg(
2822 'content-failed-to-parse',
2823 $this->contentModel,
2824 $this->contentFormat,
2825 $ex->getMessage()
2826 );
2827 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2828 }
2829 }
2830
2831 // Set a hidden field so JS knows what edit form mode we are in
2832 if ( $this->isConflict ) {
2833 $mode = 'conflict';
2834 } elseif ( $this->preview ) {
2835 $mode = 'preview';
2836 } elseif ( $this->diff ) {
2837 $mode = 'diff';
2838 } else {
2839 $mode = 'text';
2840 }
2841 $wgOut->addHTML( Html::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2842
2843 // Marker for detecting truncated form data. This must be the last
2844 // parameter sent in order to be of use, so do not move me.
2845 $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2846 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2847
2848 if ( !$wgUser->getOption( 'previewontop' ) ) {
2849 $this->displayPreviewArea( $previewOutput, false );
2850 }
2851 }
2852
2853 /**
2854 * Wrapper around TemplatesOnThisPageFormatter to make
2855 * a "templates on this page" list.
2856 *
2857 * @param Title[] $templates
2858 * @return string HTML
2859 */
2860 public function makeTemplatesOnThisPageList( array $templates ) {
2861 $templateListFormatter = new TemplatesOnThisPageFormatter(
2862 $this->context, MediaWikiServices::getInstance()->getLinkRenderer()
2863 );
2864
2865 // preview if preview, else section if section, else false
2866 $type = false;
2867 if ( $this->preview ) {
2868 $type = 'preview';
2869 } elseif ( $this->section != '' ) {
2870 $type = 'section';
2871 }
2872
2873 return Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2874 $templateListFormatter->format( $templates, $type )
2875 );
2876 }
2877
2878 /**
2879 * Extract the section title from current section text, if any.
2880 *
2881 * @param string $text
2882 * @return string|bool String or false
2883 */
2884 public static function extractSectionTitle( $text ) {
2885 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2886 if ( !empty( $matches[2] ) ) {
2887 global $wgParser;
2888 return $wgParser->stripSectionName( trim( $matches[2] ) );
2889 } else {
2890 return false;
2891 }
2892 }
2893
2894 protected function showHeader() {
2895 global $wgOut, $wgUser;
2896 global $wgAllowUserCss, $wgAllowUserJs;
2897
2898 if ( $this->isConflict ) {
2899 $this->addExplainConflictHeader( $wgOut );
2900 $this->editRevId = $this->page->getLatest();
2901 } else {
2902 if ( $this->section != '' && $this->section != 'new' ) {
2903 if ( !$this->summary && !$this->preview && !$this->diff ) {
2904 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
2905 if ( $sectionTitle !== false ) {
2906 $this->summary = "/* $sectionTitle */ ";
2907 }
2908 }
2909 }
2910
2911 $buttonLabel = $this->context->msg( $this->getSaveButtonLabel() )->text();
2912
2913 if ( $this->missingComment ) {
2914 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2915 }
2916
2917 if ( $this->missingSummary && $this->section != 'new' ) {
2918 $wgOut->wrapWikiMsg(
2919 "<div id='mw-missingsummary'>\n$1\n</div>",
2920 [ 'missingsummary', $buttonLabel ]
2921 );
2922 }
2923
2924 if ( $this->missingSummary && $this->section == 'new' ) {
2925 $wgOut->wrapWikiMsg(
2926 "<div id='mw-missingcommentheader'>\n$1\n</div>",
2927 [ 'missingcommentheader', $buttonLabel ]
2928 );
2929 }
2930
2931 if ( $this->blankArticle ) {
2932 $wgOut->wrapWikiMsg(
2933 "<div id='mw-blankarticle'>\n$1\n</div>",
2934 [ 'blankarticle', $buttonLabel ]
2935 );
2936 }
2937
2938 if ( $this->selfRedirect ) {
2939 $wgOut->wrapWikiMsg(
2940 "<div id='mw-selfredirect'>\n$1\n</div>",
2941 [ 'selfredirect', $buttonLabel ]
2942 );
2943 }
2944
2945 if ( $this->hookError !== '' ) {
2946 $wgOut->addWikiText( $this->hookError );
2947 }
2948
2949 if ( !$this->checkUnicodeCompliantBrowser() ) {
2950 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2951 }
2952
2953 if ( $this->section != 'new' ) {
2954 $revision = $this->mArticle->getRevisionFetched();
2955 if ( $revision ) {
2956 // Let sysop know that this will make private content public if saved
2957
2958 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2959 $wgOut->wrapWikiMsg(
2960 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2961 'rev-deleted-text-permission'
2962 );
2963 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2964 $wgOut->wrapWikiMsg(
2965 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2966 'rev-deleted-text-view'
2967 );
2968 }
2969
2970 if ( !$revision->isCurrent() ) {
2971 $this->mArticle->setOldSubtitle( $revision->getId() );
2972 $wgOut->addWikiMsg( 'editingold' );
2973 $this->isOldRev = true;
2974 }
2975 } elseif ( $this->mTitle->exists() ) {
2976 // Something went wrong
2977
2978 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2979 [ 'missing-revision', $this->oldid ] );
2980 }
2981 }
2982 }
2983
2984 if ( wfReadOnly() ) {
2985 $wgOut->wrapWikiMsg(
2986 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2987 [ 'readonlywarning', wfReadOnlyReason() ]
2988 );
2989 } elseif ( $wgUser->isAnon() ) {
2990 if ( $this->formtype != 'preview' ) {
2991 $wgOut->wrapWikiMsg(
2992 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
2993 [ 'anoneditwarning',
2994 // Log-in link
2995 SpecialPage::getTitleFor( 'Userlogin' )->getFullURL( [
2996 'returnto' => $this->getTitle()->getPrefixedDBkey()
2997 ] ),
2998 // Sign-up link
2999 SpecialPage::getTitleFor( 'CreateAccount' )->getFullURL( [
3000 'returnto' => $this->getTitle()->getPrefixedDBkey()
3001 ] )
3002 ]
3003 );
3004 } else {
3005 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3006 'anonpreviewwarning'
3007 );
3008 }
3009 } else {
3010 if ( $this->isCssJsSubpage ) {
3011 # Check the skin exists
3012 if ( $this->isWrongCaseCssJsPage ) {
3013 $wgOut->wrapWikiMsg(
3014 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
3015 [ 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ]
3016 );
3017 }
3018 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
3019 $wgOut->wrapWikiMsg( '<div class="mw-usercssjspublic">$1</div>',
3020 $this->isCssSubpage ? 'usercssispublic' : 'userjsispublic'
3021 );
3022 if ( $this->formtype !== 'preview' ) {
3023 if ( $this->isCssSubpage && $wgAllowUserCss ) {
3024 $wgOut->wrapWikiMsg(
3025 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3026 [ 'usercssyoucanpreview' ]
3027 );
3028 }
3029
3030 if ( $this->isJsSubpage && $wgAllowUserJs ) {
3031 $wgOut->wrapWikiMsg(
3032 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3033 [ 'userjsyoucanpreview' ]
3034 );
3035 }
3036 }
3037 }
3038 }
3039 }
3040
3041 $this->addPageProtectionWarningHeaders();
3042
3043 $this->addLongPageWarningHeader();
3044
3045 # Add header copyright warning
3046 $this->showHeaderCopyrightWarning();
3047 }
3048
3049 /**
3050 * Helper function for summary input functions, which returns the neccessary
3051 * attributes for the input.
3052 *
3053 * @param array|null $inputAttrs Array of attrs to use on the input
3054 * @return array
3055 */
3056 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3057 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
3058 return ( is_array( $inputAttrs ) ? $inputAttrs : [] ) + [
3059 'id' => 'wpSummary',
3060 'name' => 'wpSummary',
3061 'maxlength' => '200',
3062 'tabindex' => 1,
3063 'size' => 60,
3064 'spellcheck' => 'true',
3065 ] + Linker::tooltipAndAccesskeyAttribs( 'summary' );
3066 }
3067
3068 /**
3069 * Standard summary input and label (wgSummary), abstracted so EditPage
3070 * subclasses may reorganize the form.
3071 * Note that you do not need to worry about the label's for=, it will be
3072 * inferred by the id given to the input. You can remove them both by
3073 * passing [ 'id' => false ] to $userInputAttrs.
3074 *
3075 * @param string $summary The value of the summary input
3076 * @param string $labelText The html to place inside the label
3077 * @param array $inputAttrs Array of attrs to use on the input
3078 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
3079 *
3080 * @return array An array in the format [ $label, $input ]
3081 */
3082 public function getSummaryInput( $summary = "", $labelText = null,
3083 $inputAttrs = null, $spanLabelAttrs = null
3084 ) {
3085 $inputAttrs = $this->getSummaryInputAttributes( $inputAttrs );
3086
3087 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : [] ) + [
3088 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
3089 'id' => "wpSummaryLabel"
3090 ];
3091
3092 $label = null;
3093 if ( $labelText ) {
3094 $label = Xml::tags(
3095 'label',
3096 $inputAttrs['id'] ? [ 'for' => $inputAttrs['id'] ] : null,
3097 $labelText
3098 );
3099 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
3100 }
3101
3102 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
3103
3104 return [ $label, $input ];
3105 }
3106
3107 /**
3108 * Same as self::getSummaryInput, but uses OOUI, instead of plain HTML.
3109 * Builds a standard summary input with a label.
3110 *
3111 * @param string $summary The value of the summary input
3112 * @param string $labelText The html to place inside the label
3113 * @param array $inputAttrs Array of attrs to use on the input
3114 *
3115 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3116 */
3117 function getSummaryInputOOUI( $summary = "", $labelText = null, $inputAttrs = null ) {
3118 $inputAttrs = OOUI\Element::configFromHtmlAttributes(
3119 $this->getSummaryInputAttributes( $inputAttrs )
3120 );
3121
3122 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3123 $inputAttrs['inputId'] = $inputAttrs['id'];
3124 $inputAttrs['id'] = 'wpSummaryWidget';
3125
3126 return new OOUI\FieldLayout(
3127 new OOUI\TextInputWidget( [
3128 'value' => $summary,
3129 'infusable' => true,
3130 ] + $inputAttrs ),
3131 [
3132 'label' => new OOUI\HtmlSnippet( $labelText ),
3133 'align' => 'top',
3134 'id' => 'wpSummaryLabel',
3135 'classes' => [ $this->missingSummary ? 'mw-summarymissed' : 'mw-summary' ],
3136 ]
3137 );
3138 }
3139
3140 /**
3141 * @param bool $isSubjectPreview True if this is the section subject/title
3142 * up top, or false if this is the comment summary
3143 * down below the textarea
3144 * @param string $summary The text of the summary to display
3145 */
3146 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3147 global $wgOut;
3148
3149 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3150 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
3151 if ( $isSubjectPreview ) {
3152 if ( $this->nosummary ) {
3153 return;
3154 }
3155 } else {
3156 if ( !$this->mShowSummaryField ) {
3157 return;
3158 }
3159 }
3160
3161 $labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse();
3162 if ( $this->oouiEnabled ) {
3163 $wgOut->addHTML( $this->getSummaryInputOOUI(
3164 $summary,
3165 $labelText,
3166 [ 'class' => $summaryClass ]
3167 ) );
3168 } else {
3169 list( $label, $input ) = $this->getSummaryInput(
3170 $summary,
3171 $labelText,
3172 [ 'class' => $summaryClass ]
3173 );
3174 $wgOut->addHTML( "{$label} {$input}" );
3175 }
3176 }
3177
3178 /**
3179 * @param bool $isSubjectPreview True if this is the section subject/title
3180 * up top, or false if this is the comment summary
3181 * down below the textarea
3182 * @param string $summary The text of the summary to display
3183 * @return string
3184 */
3185 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3186 // avoid spaces in preview, gets always trimmed on save
3187 $summary = trim( $summary );
3188 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
3189 return "";
3190 }
3191
3192 global $wgParser;
3193
3194 if ( $isSubjectPreview ) {
3195 $summary = $this->context->msg( 'newsectionsummary' )
3196 ->rawParams( $wgParser->stripSectionName( $summary ) )
3197 ->inContentLanguage()->text();
3198 }
3199
3200 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
3201
3202 $summary = $this->context->msg( $message )->parse()
3203 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
3204 return Xml::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3205 }
3206
3207 protected function showFormBeforeText() {
3208 global $wgOut;
3209 $section = htmlspecialchars( $this->section );
3210 $wgOut->addHTML( <<<HTML
3211 <input type='hidden' value="{$section}" name="wpSection"/>
3212 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
3213 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
3214 <input type='hidden' value="{$this->editRevId}" name="editRevId" />
3215 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
3216
3217 HTML
3218 );
3219 if ( !$this->checkUnicodeCompliantBrowser() ) {
3220 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
3221 }
3222 }
3223
3224 protected function showFormAfterText() {
3225 global $wgOut, $wgUser;
3226 /**
3227 * To make it harder for someone to slip a user a page
3228 * which submits an edit form to the wiki without their
3229 * knowledge, a random token is associated with the login
3230 * session. If it's not passed back with the submission,
3231 * we won't save the page, or render user JavaScript and
3232 * CSS previews.
3233 *
3234 * For anon editors, who may not have a session, we just
3235 * include the constant suffix to prevent editing from
3236 * broken text-mangling proxies.
3237 */
3238 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
3239 }
3240
3241 /**
3242 * Subpage overridable method for printing the form for page content editing
3243 * By default this simply outputs wpTextbox1
3244 * Subclasses can override this to provide a custom UI for editing;
3245 * be it a form, or simply wpTextbox1 with a modified content that will be
3246 * reverse modified when extracted from the post data.
3247 * Note that this is basically the inverse for importContentFormData
3248 */
3249 protected function showContentForm() {
3250 $this->showTextbox1();
3251 }
3252
3253 /**
3254 * Method to output wpTextbox1
3255 * The $textoverride method can be used by subclasses overriding showContentForm
3256 * to pass back to this method.
3257 *
3258 * @param array $customAttribs Array of html attributes to use in the textarea
3259 * @param string $textoverride Optional text to override $this->textarea1 with
3260 */
3261 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3262 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
3263 $attribs = [ 'style' => 'display:none;' ];
3264 } else {
3265 $classes = []; // Textarea CSS
3266 if ( $this->mTitle->isProtected( 'edit' ) &&
3267 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
3268 ) {
3269 # Is the title semi-protected?
3270 if ( $this->mTitle->isSemiProtected() ) {
3271 $classes[] = 'mw-textarea-sprotected';
3272 } else {
3273 # Then it must be protected based on static groups (regular)
3274 $classes[] = 'mw-textarea-protected';
3275 }
3276 # Is the title cascade-protected?
3277 if ( $this->mTitle->isCascadeProtected() ) {
3278 $classes[] = 'mw-textarea-cprotected';
3279 }
3280 }
3281 # Is an old revision being edited?
3282 if ( $this->isOldRev ) {
3283 $classes[] = 'mw-textarea-oldrev';
3284 }
3285
3286 $attribs = [ 'tabindex' => 1 ];
3287
3288 if ( is_array( $customAttribs ) ) {
3289 $attribs += $customAttribs;
3290 }
3291
3292 if ( count( $classes ) ) {
3293 if ( isset( $attribs['class'] ) ) {
3294 $classes[] = $attribs['class'];
3295 }
3296 $attribs['class'] = implode( ' ', $classes );
3297 }
3298 }
3299
3300 $this->showTextbox(
3301 $textoverride !== null ? $textoverride : $this->textbox1,
3302 'wpTextbox1',
3303 $attribs
3304 );
3305 }
3306
3307 protected function showTextbox2() {
3308 $this->showTextbox( $this->textbox2, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3309 }
3310
3311 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3312 global $wgOut, $wgUser;
3313
3314 $wikitext = $this->safeUnicodeOutput( $text );
3315 $wikitext = $this->addNewLineAtEnd( $wikitext );
3316
3317 $attribs = $this->buildTextboxAttribs( $name, $customAttribs, $wgUser );
3318
3319 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
3320 }
3321
3322 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3323 global $wgOut;
3324 $classes = [];
3325 if ( $isOnTop ) {
3326 $classes[] = 'ontop';
3327 }
3328
3329 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3330
3331 if ( $this->formtype != 'preview' ) {
3332 $attribs['style'] = 'display: none;';
3333 }
3334
3335 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
3336
3337 if ( $this->formtype == 'preview' ) {
3338 $this->showPreview( $previewOutput );
3339 } else {
3340 // Empty content container for LivePreview
3341 $pageViewLang = $this->mTitle->getPageViewLanguage();
3342 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3343 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3344 $wgOut->addHTML( Html::rawElement( 'div', $attribs ) );
3345 }
3346
3347 $wgOut->addHTML( '</div>' );
3348
3349 if ( $this->formtype == 'diff' ) {
3350 try {
3351 $this->showDiff();
3352 } catch ( MWContentSerializationException $ex ) {
3353 $msg = $this->context->msg(
3354 'content-failed-to-parse',
3355 $this->contentModel,
3356 $this->contentFormat,
3357 $ex->getMessage()
3358 );
3359 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3360 }
3361 }
3362 }
3363
3364 /**
3365 * Append preview output to $wgOut.
3366 * Includes category rendering if this is a category page.
3367 *
3368 * @param string $text The HTML to be output for the preview.
3369 */
3370 protected function showPreview( $text ) {
3371 global $wgOut;
3372 if ( $this->mArticle instanceof CategoryPage ) {
3373 $this->mArticle->openShowCategory();
3374 }
3375 # This hook seems slightly odd here, but makes things more
3376 # consistent for extensions.
3377 Hooks::run( 'OutputPageBeforeHTML', [ &$wgOut, &$text ] );
3378 $wgOut->addHTML( $text );
3379 if ( $this->mArticle instanceof CategoryPage ) {
3380 $this->mArticle->closeShowCategory();
3381 }
3382 }
3383
3384 /**
3385 * Get a diff between the current contents of the edit box and the
3386 * version of the page we're editing from.
3387 *
3388 * If this is a section edit, we'll replace the section as for final
3389 * save and then make a comparison.
3390 */
3391 public function showDiff() {
3392 global $wgUser, $wgContLang, $wgOut;
3393
3394 $oldtitlemsg = 'currentrev';
3395 # if message does not exist, show diff against the preloaded default
3396 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3397 $oldtext = $this->mTitle->getDefaultMessageText();
3398 if ( $oldtext !== false ) {
3399 $oldtitlemsg = 'defaultmessagetext';
3400 $oldContent = $this->toEditContent( $oldtext );
3401 } else {
3402 $oldContent = null;
3403 }
3404 } else {
3405 $oldContent = $this->getCurrentContent();
3406 }
3407
3408 $textboxContent = $this->toEditContent( $this->textbox1 );
3409 if ( $this->editRevId !== null ) {
3410 $newContent = $this->page->replaceSectionAtRev(
3411 $this->section, $textboxContent, $this->summary, $this->editRevId
3412 );
3413 } else {
3414 $newContent = $this->page->replaceSectionContent(
3415 $this->section, $textboxContent, $this->summary, $this->edittime
3416 );
3417 }
3418
3419 if ( $newContent ) {
3420 Hooks::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3421
3422 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
3423 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
3424 }
3425
3426 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3427 $oldtitle = $this->context->msg( $oldtitlemsg )->parse();
3428 $newtitle = $this->context->msg( 'yourtext' )->parse();
3429
3430 if ( !$oldContent ) {
3431 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3432 }
3433
3434 if ( !$newContent ) {
3435 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3436 }
3437
3438 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
3439 $de->setContent( $oldContent, $newContent );
3440
3441 $difftext = $de->getDiff( $oldtitle, $newtitle );
3442 $de->showDiffStyle();
3443 } else {
3444 $difftext = '';
3445 }
3446
3447 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3448 }
3449
3450 /**
3451 * Show the header copyright warning.
3452 */
3453 protected function showHeaderCopyrightWarning() {
3454 $msg = 'editpage-head-copy-warn';
3455 if ( !$this->context->msg( $msg )->isDisabled() ) {
3456 global $wgOut;
3457 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3458 'editpage-head-copy-warn' );
3459 }
3460 }
3461
3462 /**
3463 * Give a chance for site and per-namespace customizations of
3464 * terms of service summary link that might exist separately
3465 * from the copyright notice.
3466 *
3467 * This will display between the save button and the edit tools,
3468 * so should remain short!
3469 */
3470 protected function showTosSummary() {
3471 $msg = 'editpage-tos-summary';
3472 Hooks::run( 'EditPageTosSummary', [ $this->mTitle, &$msg ] );
3473 if ( !$this->context->msg( $msg )->isDisabled() ) {
3474 global $wgOut;
3475 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3476 $wgOut->addWikiMsg( $msg );
3477 $wgOut->addHTML( '</div>' );
3478 }
3479 }
3480
3481 protected function showEditTools() {
3482 global $wgOut;
3483 $wgOut->addHTML( '<div class="mw-editTools">' .
3484 $this->context->msg( 'edittools' )->inContentLanguage()->parse() .
3485 '</div>' );
3486 }
3487
3488 /**
3489 * Get the copyright warning
3490 *
3491 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3492 * @return string
3493 */
3494 protected function getCopywarn() {
3495 return self::getCopyrightWarning( $this->mTitle );
3496 }
3497
3498 /**
3499 * Get the copyright warning, by default returns wikitext
3500 *
3501 * @param Title $title
3502 * @param string $format Output format, valid values are any function of a Message object
3503 * @param Language|string|null $langcode Language code or Language object.
3504 * @return string
3505 */
3506 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3507 global $wgRightsText;
3508 if ( $wgRightsText ) {
3509 $copywarnMsg = [ 'copyrightwarning',
3510 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3511 $wgRightsText ];
3512 } else {
3513 $copywarnMsg = [ 'copyrightwarning2',
3514 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3515 }
3516 // Allow for site and per-namespace customization of contribution/copyright notice.
3517 Hooks::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3518
3519 $msg = call_user_func_array( 'wfMessage', $copywarnMsg )->title( $title );
3520 if ( $langcode ) {
3521 $msg->inLanguage( $langcode );
3522 }
3523 return "<div id=\"editpage-copywarn\">\n" .
3524 $msg->$format() . "\n</div>";
3525 }
3526
3527 /**
3528 * Get the Limit report for page previews
3529 *
3530 * @since 1.22
3531 * @param ParserOutput $output ParserOutput object from the parse
3532 * @return string HTML
3533 */
3534 public static function getPreviewLimitReport( $output ) {
3535 if ( !$output || !$output->getLimitReportData() ) {
3536 return '';
3537 }
3538
3539 $limitReport = Html::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3540 wfMessage( 'limitreport-title' )->parseAsBlock()
3541 );
3542
3543 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3544 $limitReport .= Html::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3545
3546 $limitReport .= Html::openElement( 'table', [
3547 'class' => 'preview-limit-report wikitable'
3548 ] ) .
3549 Html::openElement( 'tbody' );
3550
3551 foreach ( $output->getLimitReportData() as $key => $value ) {
3552 if ( Hooks::run( 'ParserLimitReportFormat',
3553 [ $key, &$value, &$limitReport, true, true ]
3554 ) ) {
3555 $keyMsg = wfMessage( $key );
3556 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3557 if ( !$valueMsg->exists() ) {
3558 $valueMsg = new RawMessage( '$1' );
3559 }
3560 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3561 $limitReport .= Html::openElement( 'tr' ) .
3562 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3563 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3564 Html::closeElement( 'tr' );
3565 }
3566 }
3567 }
3568
3569 $limitReport .= Html::closeElement( 'tbody' ) .
3570 Html::closeElement( 'table' ) .
3571 Html::closeElement( 'div' );
3572
3573 return $limitReport;
3574 }
3575
3576 protected function showStandardInputs( &$tabindex = 2 ) {
3577 global $wgOut;
3578 $wgOut->addHTML( "<div class='editOptions'>\n" );
3579
3580 if ( $this->section != 'new' ) {
3581 $this->showSummaryInput( false, $this->summary );
3582 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3583 }
3584
3585 if ( $this->oouiEnabled ) {
3586 $checkboxes = $this->getCheckboxesOOUI(
3587 $tabindex,
3588 [ 'minor' => $this->minoredit, 'watch' => $this->watchthis ]
3589 );
3590 $checkboxesHTML = new OOUI\HorizontalLayout( [ 'items' => $checkboxes ] );
3591 } else {
3592 $checkboxes = $this->getCheckboxes(
3593 $tabindex,
3594 [ 'minor' => $this->minoredit, 'watch' => $this->watchthis ]
3595 );
3596 $checkboxesHTML = implode( $checkboxes, "\n" );
3597 }
3598
3599 $wgOut->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3600
3601 // Show copyright warning.
3602 $wgOut->addWikiText( $this->getCopywarn() );
3603 $wgOut->addHTML( $this->editFormTextAfterWarn );
3604
3605 $wgOut->addHTML( "<div class='editButtons'>\n" );
3606 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3607
3608 $cancel = $this->getCancelLink();
3609 if ( $cancel !== '' ) {
3610 $cancel .= Html::element( 'span',
3611 [ 'class' => 'mw-editButtons-pipe-separator' ],
3612 $this->context->msg( 'pipe-separator' )->text() );
3613 }
3614
3615 $message = $this->context->msg( 'edithelppage' )->inContentLanguage()->text();
3616 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3617 $edithelp =
3618 Html::linkButton(
3619 $this->context->msg( 'edithelp' )->text(),
3620 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3621 [ 'mw-ui-quiet' ]
3622 ) .
3623 $this->context->msg( 'word-separator' )->escaped() .
3624 $this->context->msg( 'newwindow' )->parse();
3625
3626 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3627 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3628 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3629
3630 Hooks::run( 'EditPage::showStandardInputs:options', [ $this, $wgOut, &$tabindex ] );
3631
3632 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3633 }
3634
3635 /**
3636 * Show an edit conflict. textbox1 is already shown in showEditForm().
3637 * If you want to use another entry point to this function, be careful.
3638 */
3639 protected function showConflict() {
3640 global $wgOut;
3641
3642 // Avoid PHP 7.1 warning of passing $this by reference
3643 $editPage = $this;
3644 if ( Hooks::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$wgOut ] ) ) {
3645 $this->incrementConflictStats();
3646
3647 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3648
3649 $content1 = $this->toEditContent( $this->textbox1 );
3650 $content2 = $this->toEditContent( $this->textbox2 );
3651
3652 $handler = ContentHandler::getForModelID( $this->contentModel );
3653 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3654 $de->setContent( $content2, $content1 );
3655 $de->showDiff(
3656 $this->context->msg( 'yourtext' )->parse(),
3657 $this->context->msg( 'storedversion' )->text()
3658 );
3659
3660 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3661 $this->showTextbox2();
3662 }
3663 }
3664
3665 protected function incrementConflictStats() {
3666 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
3667 $stats->increment( 'edit.failures.conflict' );
3668 // Only include 'standard' namespaces to avoid creating unknown numbers of statsd metrics
3669 if (
3670 $this->mTitle->getNamespace() >= NS_MAIN &&
3671 $this->mTitle->getNamespace() <= NS_CATEGORY_TALK
3672 ) {
3673 $stats->increment( 'edit.failures.conflict.byNamespaceId.' . $this->mTitle->getNamespace() );
3674 }
3675 }
3676
3677 /**
3678 * @return string
3679 */
3680 public function getCancelLink() {
3681 $cancelParams = [];
3682 if ( !$this->isConflict && $this->oldid > 0 ) {
3683 $cancelParams['oldid'] = $this->oldid;
3684 } elseif ( $this->getContextTitle()->isRedirect() ) {
3685 $cancelParams['redirect'] = 'no';
3686 }
3687 if ( $this->oouiEnabled ) {
3688 return new OOUI\ButtonWidget( [
3689 'id' => 'mw-editform-cancel',
3690 'href' => $this->getContextTitle()->getLinkUrl( $cancelParams ),
3691 'label' => new OOUI\HtmlSnippet( $this->context->msg( 'cancel' )->parse() ),
3692 'framed' => false,
3693 'infusable' => true,
3694 'flags' => 'destructive',
3695 ] );
3696 } else {
3697 return MediaWikiServices::getInstance()->getLinkRenderer()->makeKnownLink(
3698 $this->getContextTitle(),
3699 new HtmlArmor( $this->context->msg( 'cancel' )->parse() ),
3700 Html::buttonAttributes( [ 'id' => 'mw-editform-cancel' ], [ 'mw-ui-quiet' ] ),
3701 $cancelParams
3702 );
3703 }
3704 }
3705
3706 /**
3707 * Returns the URL to use in the form's action attribute.
3708 * This is used by EditPage subclasses when simply customizing the action
3709 * variable in the constructor is not enough. This can be used when the
3710 * EditPage lives inside of a Special page rather than a custom page action.
3711 *
3712 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3713 * @return string
3714 */
3715 protected function getActionURL( Title $title ) {
3716 return $title->getLocalURL( [ 'action' => $this->action ] );
3717 }
3718
3719 /**
3720 * Check if a page was deleted while the user was editing it, before submit.
3721 * Note that we rely on the logging table, which hasn't been always there,
3722 * but that doesn't matter, because this only applies to brand new
3723 * deletes.
3724 * @return bool
3725 */
3726 protected function wasDeletedSinceLastEdit() {
3727 if ( $this->deletedSinceEdit !== null ) {
3728 return $this->deletedSinceEdit;
3729 }
3730
3731 $this->deletedSinceEdit = false;
3732
3733 if ( !$this->mTitle->exists() && $this->mTitle->isDeletedQuick() ) {
3734 $this->lastDelete = $this->getLastDelete();
3735 if ( $this->lastDelete ) {
3736 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3737 if ( $deleteTime > $this->starttime ) {
3738 $this->deletedSinceEdit = true;
3739 }
3740 }
3741 }
3742
3743 return $this->deletedSinceEdit;
3744 }
3745
3746 /**
3747 * @return bool|stdClass
3748 */
3749 protected function getLastDelete() {
3750 $dbr = wfGetDB( DB_REPLICA );
3751 $data = $dbr->selectRow(
3752 [ 'logging', 'user' ],
3753 [
3754 'log_type',
3755 'log_action',
3756 'log_timestamp',
3757 'log_user',
3758 'log_namespace',
3759 'log_title',
3760 'log_comment',
3761 'log_params',
3762 'log_deleted',
3763 'user_name'
3764 ], [
3765 'log_namespace' => $this->mTitle->getNamespace(),
3766 'log_title' => $this->mTitle->getDBkey(),
3767 'log_type' => 'delete',
3768 'log_action' => 'delete',
3769 'user_id=log_user'
3770 ],
3771 __METHOD__,
3772 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ]
3773 );
3774 // Quick paranoid permission checks...
3775 if ( is_object( $data ) ) {
3776 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3777 $data->user_name = $this->context->msg( 'rev-deleted-user' )->escaped();
3778 }
3779
3780 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3781 $data->log_comment = $this->context->msg( 'rev-deleted-comment' )->escaped();
3782 }
3783 }
3784
3785 return $data;
3786 }
3787
3788 /**
3789 * Get the rendered text for previewing.
3790 * @throws MWException
3791 * @return string
3792 */
3793 public function getPreviewText() {
3794 global $wgOut, $wgRawHtml, $wgLang;
3795 global $wgAllowUserCss, $wgAllowUserJs;
3796
3797 if ( $wgRawHtml && !$this->mTokenOk ) {
3798 // Could be an offsite preview attempt. This is very unsafe if
3799 // HTML is enabled, as it could be an attack.
3800 $parsedNote = '';
3801 if ( $this->textbox1 !== '' ) {
3802 // Do not put big scary notice, if previewing the empty
3803 // string, which happens when you initially edit
3804 // a category page, due to automatic preview-on-open.
3805 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3806 $this->context->msg( 'session_fail_preview_html' )->text() . "</div>",
3807 true, /* interface */true );
3808 }
3809 $this->incrementEditFailureStats( 'session_loss' );
3810 return $parsedNote;
3811 }
3812
3813 $note = '';
3814
3815 try {
3816 $content = $this->toEditContent( $this->textbox1 );
3817
3818 $previewHTML = '';
3819 if ( !Hooks::run(
3820 'AlternateEditPreview',
3821 [ $this, &$content, &$previewHTML, &$this->mParserOutput ] )
3822 ) {
3823 return $previewHTML;
3824 }
3825
3826 # provide a anchor link to the editform
3827 $continueEditing = '<span class="mw-continue-editing">' .
3828 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3829 $this->context->msg( 'continue-editing' )->text() . ']]</span>';
3830 if ( $this->mTriedSave && !$this->mTokenOk ) {
3831 if ( $this->mTokenOkExceptSuffix ) {
3832 $note = $this->context->msg( 'token_suffix_mismatch' )->plain();
3833 $this->incrementEditFailureStats( 'bad_token' );
3834 } else {
3835 $note = $this->context->msg( 'session_fail_preview' )->plain();
3836 $this->incrementEditFailureStats( 'session_loss' );
3837 }
3838 } elseif ( $this->incompleteForm ) {
3839 $note = $this->context->msg( 'edit_form_incomplete' )->plain();
3840 if ( $this->mTriedSave ) {
3841 $this->incrementEditFailureStats( 'incomplete_form' );
3842 }
3843 } else {
3844 $note = $this->context->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3845 }
3846
3847 # don't parse non-wikitext pages, show message about preview
3848 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3849 if ( $this->mTitle->isCssJsSubpage() ) {
3850 $level = 'user';
3851 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3852 $level = 'site';
3853 } else {
3854 $level = false;
3855 }
3856
3857 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3858 $format = 'css';
3859 if ( $level === 'user' && !$wgAllowUserCss ) {
3860 $format = false;
3861 }
3862 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3863 $format = 'js';
3864 if ( $level === 'user' && !$wgAllowUserJs ) {
3865 $format = false;
3866 }
3867 } else {
3868 $format = false;
3869 }
3870
3871 # Used messages to make sure grep find them:
3872 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3873 if ( $level && $format ) {
3874 $note = "<div id='mw-{$level}{$format}preview'>" .
3875 $this->context->msg( "{$level}{$format}preview" )->text() .
3876 ' ' . $continueEditing . "</div>";
3877 }
3878 }
3879
3880 # If we're adding a comment, we need to show the
3881 # summary as the headline
3882 if ( $this->section === "new" && $this->summary !== "" ) {
3883 $content = $content->addSectionHeader( $this->summary );
3884 }
3885
3886 $hook_args = [ $this, &$content ];
3887 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3888
3889 $parserResult = $this->doPreviewParse( $content );
3890 $parserOutput = $parserResult['parserOutput'];
3891 $previewHTML = $parserResult['html'];
3892 $this->mParserOutput = $parserOutput;
3893 $wgOut->addParserOutputMetadata( $parserOutput );
3894
3895 if ( count( $parserOutput->getWarnings() ) ) {
3896 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3897 }
3898
3899 } catch ( MWContentSerializationException $ex ) {
3900 $m = $this->context->msg(
3901 'content-failed-to-parse',
3902 $this->contentModel,
3903 $this->contentFormat,
3904 $ex->getMessage()
3905 );
3906 $note .= "\n\n" . $m->parse();
3907 $previewHTML = '';
3908 }
3909
3910 if ( $this->isConflict ) {
3911 $conflict = '<h2 id="mw-previewconflict">'
3912 . $this->context->msg( 'previewconflict' )->escaped() . "</h2>\n";
3913 } else {
3914 $conflict = '<hr />';
3915 }
3916
3917 $previewhead = "<div class='previewnote'>\n" .
3918 '<h2 id="mw-previewheader">' . $this->context->msg( 'preview' )->escaped() . "</h2>" .
3919 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3920
3921 $pageViewLang = $this->mTitle->getPageViewLanguage();
3922 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3923 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3924 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3925
3926 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3927 }
3928
3929 private function incrementEditFailureStats( $failureType ) {
3930 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
3931 $stats->increment( 'edit.failures.' . $failureType );
3932 }
3933
3934 /**
3935 * Get parser options for a preview
3936 * @return ParserOptions
3937 */
3938 protected function getPreviewParserOptions() {
3939 $parserOptions = $this->page->makeParserOptions( $this->mArticle->getContext() );
3940 $parserOptions->setIsPreview( true );
3941 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3942 $parserOptions->enableLimitReport();
3943 return $parserOptions;
3944 }
3945
3946 /**
3947 * Parse the page for a preview. Subclasses may override this class, in order
3948 * to parse with different options, or to otherwise modify the preview HTML.
3949 *
3950 * @param Content $content The page content
3951 * @return array with keys:
3952 * - parserOutput: The ParserOutput object
3953 * - html: The HTML to be displayed
3954 */
3955 protected function doPreviewParse( Content $content ) {
3956 global $wgUser;
3957 $parserOptions = $this->getPreviewParserOptions();
3958 $pstContent = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3959 $scopedCallback = $parserOptions->setupFakeRevision(
3960 $this->mTitle, $pstContent, $wgUser );
3961 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
3962 ScopedCallback::consume( $scopedCallback );
3963 $parserOutput->setEditSectionTokens( false ); // no section edit links
3964 return [
3965 'parserOutput' => $parserOutput,
3966 'html' => $parserOutput->getText() ];
3967 }
3968
3969 /**
3970 * @return array
3971 */
3972 public function getTemplates() {
3973 if ( $this->preview || $this->section != '' ) {
3974 $templates = [];
3975 if ( !isset( $this->mParserOutput ) ) {
3976 return $templates;
3977 }
3978 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3979 foreach ( array_keys( $template ) as $dbk ) {
3980 $templates[] = Title::makeTitle( $ns, $dbk );
3981 }
3982 }
3983 return $templates;
3984 } else {
3985 return $this->mTitle->getTemplateLinksFrom();
3986 }
3987 }
3988
3989 /**
3990 * Shows a bulletin board style toolbar for common editing functions.
3991 * It can be disabled in the user preferences.
3992 *
3993 * @param Title $title Title object for the page being edited (optional)
3994 * @return string
3995 */
3996 public static function getEditToolbar( $title = null ) {
3997 global $wgContLang, $wgOut;
3998 global $wgEnableUploads, $wgForeignFileRepos;
3999
4000 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
4001 $showSignature = true;
4002 if ( $title ) {
4003 $showSignature = MWNamespace::wantSignatures( $title->getNamespace() );
4004 }
4005
4006 /**
4007 * $toolarray is an array of arrays each of which includes the
4008 * opening tag, the closing tag, optionally a sample text that is
4009 * inserted between the two when no selection is highlighted
4010 * and. The tip text is shown when the user moves the mouse
4011 * over the button.
4012 *
4013 * Images are defined in ResourceLoaderEditToolbarModule.
4014 */
4015 $toolarray = [
4016 [
4017 'id' => 'mw-editbutton-bold',
4018 'open' => '\'\'\'',
4019 'close' => '\'\'\'',
4020 'sample' => wfMessage( 'bold_sample' )->text(),
4021 'tip' => wfMessage( 'bold_tip' )->text(),
4022 ],
4023 [
4024 'id' => 'mw-editbutton-italic',
4025 'open' => '\'\'',
4026 'close' => '\'\'',
4027 'sample' => wfMessage( 'italic_sample' )->text(),
4028 'tip' => wfMessage( 'italic_tip' )->text(),
4029 ],
4030 [
4031 'id' => 'mw-editbutton-link',
4032 'open' => '[[',
4033 'close' => ']]',
4034 'sample' => wfMessage( 'link_sample' )->text(),
4035 'tip' => wfMessage( 'link_tip' )->text(),
4036 ],
4037 [
4038 'id' => 'mw-editbutton-extlink',
4039 'open' => '[',
4040 'close' => ']',
4041 'sample' => wfMessage( 'extlink_sample' )->text(),
4042 'tip' => wfMessage( 'extlink_tip' )->text(),
4043 ],
4044 [
4045 'id' => 'mw-editbutton-headline',
4046 'open' => "\n== ",
4047 'close' => " ==\n",
4048 'sample' => wfMessage( 'headline_sample' )->text(),
4049 'tip' => wfMessage( 'headline_tip' )->text(),
4050 ],
4051 $imagesAvailable ? [
4052 'id' => 'mw-editbutton-image',
4053 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
4054 'close' => ']]',
4055 'sample' => wfMessage( 'image_sample' )->text(),
4056 'tip' => wfMessage( 'image_tip' )->text(),
4057 ] : false,
4058 $imagesAvailable ? [
4059 'id' => 'mw-editbutton-media',
4060 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
4061 'close' => ']]',
4062 'sample' => wfMessage( 'media_sample' )->text(),
4063 'tip' => wfMessage( 'media_tip' )->text(),
4064 ] : false,
4065 [
4066 'id' => 'mw-editbutton-nowiki',
4067 'open' => "<nowiki>",
4068 'close' => "</nowiki>",
4069 'sample' => wfMessage( 'nowiki_sample' )->text(),
4070 'tip' => wfMessage( 'nowiki_tip' )->text(),
4071 ],
4072 $showSignature ? [
4073 'id' => 'mw-editbutton-signature',
4074 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4075 'close' => '',
4076 'sample' => '',
4077 'tip' => wfMessage( 'sig_tip' )->text(),
4078 ] : false,
4079 [
4080 'id' => 'mw-editbutton-hr',
4081 'open' => "\n----\n",
4082 'close' => '',
4083 'sample' => '',
4084 'tip' => wfMessage( 'hr_tip' )->text(),
4085 ]
4086 ];
4087
4088 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4089 foreach ( $toolarray as $tool ) {
4090 if ( !$tool ) {
4091 continue;
4092 }
4093
4094 $params = [
4095 // Images are defined in ResourceLoaderEditToolbarModule
4096 false,
4097 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4098 // Older browsers show a "speedtip" type message only for ALT.
4099 // Ideally these should be different, realistically they
4100 // probably don't need to be.
4101 $tool['tip'],
4102 $tool['open'],
4103 $tool['close'],
4104 $tool['sample'],
4105 $tool['id'],
4106 ];
4107
4108 $script .= Xml::encodeJsCall(
4109 'mw.toolbar.addButton',
4110 $params,
4111 ResourceLoader::inDebugMode()
4112 );
4113 }
4114
4115 $script .= '});';
4116
4117 $toolbar = '<div id="toolbar"></div>';
4118
4119 if ( Hooks::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4120 // Only add the old toolbar cruft to the page payload if the toolbar has not
4121 // been over-written by a hook caller
4122 $wgOut->addScript( ResourceLoader::makeInlineScript( $script ) );
4123 };
4124
4125 return $toolbar;
4126 }
4127
4128 /**
4129 * Return an array of checkbox definitions.
4130 *
4131 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4132 *
4133 * Array values are associative arrays with the following keys:
4134 * - 'label-message' (required): message for label text
4135 * - 'id' (required): 'id' attribute for the `<input>`
4136 * - 'default' (required): default checkedness (true or false)
4137 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4138 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4139 * from messages like 'tooltip-foo', 'accesskey-foo'
4140 * - 'label-id' (optional): 'id' attribute for the `<label>`
4141 * - 'legacy-name' (optional): short name for backwards-compatibility
4142 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4143 * where bool indicates the checked status of the checkbox
4144 * @return array
4145 */
4146 protected function getCheckboxesDefinition( $checked ) {
4147 global $wgUser;
4148 $checkboxes = [];
4149
4150 // don't show the minor edit checkbox if it's a new page or section
4151 if ( !$this->isNew && $wgUser->isAllowed( 'minoredit' ) ) {
4152 $checkboxes['wpMinoredit'] = [
4153 'id' => 'wpMinoredit',
4154 'label-message' => 'minoredit',
4155 // Uses messages: tooltip-minoredit, accesskey-minoredit
4156 'tooltip' => 'minoredit',
4157 'label-id' => 'mw-editpage-minoredit',
4158 'legacy-name' => 'minor',
4159 'default' => $checked['minor'],
4160 ];
4161 }
4162
4163 if ( $wgUser->isLoggedIn() ) {
4164 $checkboxes['wpWatchthis'] = [
4165 'id' => 'wpWatchthis',
4166 'label-message' => 'watchthis',
4167 // Uses messages: tooltip-watch, accesskey-watch
4168 'tooltip' => 'watch',
4169 'label-id' => 'mw-editpage-watch',
4170 'legacy-name' => 'watch',
4171 'default' => $checked['watch'],
4172 ];
4173 }
4174
4175 $editPage = $this;
4176 Hooks::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4177
4178 return $checkboxes;
4179 }
4180
4181 /**
4182 * Returns an array of html code of the following checkboxes old style:
4183 * minor and watch
4184 *
4185 * @param int $tabindex Current tabindex
4186 * @param array $checked See getCheckboxesDefinition()
4187 * @return array
4188 */
4189 public function getCheckboxes( &$tabindex, $checked ) {
4190 global $wgUseMediaWikiUIEverywhere;
4191
4192 $checkboxes = [];
4193 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4194
4195 // Backwards-compatibility for the EditPageBeforeEditChecks hook
4196 if ( !$this->isNew ) {
4197 $checkboxes['minor'] = '';
4198 }
4199 $checkboxes['watch'] = '';
4200
4201 foreach ( $checkboxesDef as $name => $options ) {
4202 $legacyName = isset( $options['legacy-name'] ) ? $options['legacy-name'] : $name;
4203 $label = $this->context->msg( $options['label-message'] )->parse();
4204 $attribs = [
4205 'tabindex' => ++$tabindex,
4206 'id' => $options['id'],
4207 ];
4208 $labelAttribs = [
4209 'for' => $options['id'],
4210 ];
4211 if ( isset( $options['tooltip'] ) ) {
4212 $attribs['accesskey'] = $this->context->msg( "accesskey-{$options['tooltip']}" )->text();
4213 $labelAttribs['title'] = Linker::titleAttrib( $options['tooltip'], 'withaccess' );
4214 }
4215 if ( isset( $options['title-message'] ) ) {
4216 $labelAttribs['title'] = $this->context->msg( $options['title-message'] )->text();
4217 }
4218 if ( isset( $options['label-id'] ) ) {
4219 $labelAttribs['id'] = $options['label-id'];
4220 }
4221 $checkboxHtml =
4222 Xml::check( $name, $options['default'], $attribs ) .
4223 '&#160;' .
4224 Xml::tags( 'label', $labelAttribs, $label );
4225
4226 if ( $wgUseMediaWikiUIEverywhere ) {
4227 $checkboxHtml = Html::rawElement( 'div', [ 'class' => 'mw-ui-checkbox' ], $checkboxHtml );
4228 }
4229
4230 $checkboxes[ $legacyName ] = $checkboxHtml;
4231 }
4232
4233 // Avoid PHP 7.1 warning of passing $this by reference
4234 $editPage = $this;
4235 Hooks::run( 'EditPageBeforeEditChecks', [ &$editPage, &$checkboxes, &$tabindex ], '1.29' );
4236 return $checkboxes;
4237 }
4238
4239 /**
4240 * Returns an array of html code of the following checkboxes:
4241 * minor and watch
4242 *
4243 * @param int $tabindex Current tabindex
4244 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4245 * status of the checkbox
4246 *
4247 * @return array
4248 */
4249 public function getCheckboxesOOUI( &$tabindex, $checked ) {
4250 $checkboxes = [];
4251 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4252
4253 $origTabindex = $tabindex;
4254
4255 foreach ( $checkboxesDef as $name => $options ) {
4256 $legacyName = isset( $options['legacy-name'] ) ? $options['legacy-name'] : $name;
4257
4258 $title = null;
4259 $accesskey = null;
4260 if ( isset( $options['tooltip'] ) ) {
4261 $accesskey = $this->context->msg( "accesskey-{$options['tooltip']}" )->text();
4262 $title = Linker::titleAttrib( $options['tooltip'], 'withaccess' );
4263 }
4264 if ( isset( $options['title-message'] ) ) {
4265 $title = $this->context->msg( $options['title-message'] )->text();
4266 }
4267 if ( isset( $options['label-id'] ) ) {
4268 $labelAttribs['id'] = $options['label-id'];
4269 }
4270
4271 $checkboxes[ $legacyName ] = new OOUI\FieldLayout(
4272 new OOUI\CheckboxInputWidget( [
4273 'tabIndex' => ++$tabindex,
4274 'accessKey' => $accesskey,
4275 'id' => $options['id'] . 'Widget',
4276 'inputId' => $options['id'],
4277 'name' => $name,
4278 'selected' => $options['default'],
4279 'infusable' => true,
4280 ] ),
4281 [
4282 'align' => 'inline',
4283 'label' => new OOUI\HtmlSnippet( $this->context->msg( $options['label-message'] )->parse() ),
4284 'title' => $title,
4285 'id' => isset( $options['label-id'] ) ? $options['label-id'] : null,
4286 ]
4287 );
4288 }
4289
4290 // Backwards-compatibility hack to run the EditPageBeforeEditChecks hook. It's important,
4291 // people have used it for the weirdest things completely unrelated to checkboxes...
4292 // And if we're gonna run it, might as well allow its legacy checkboxes to be shown.
4293 $legacyCheckboxes = $this->getCheckboxes( $origTabindex, $checked );
4294 foreach ( $legacyCheckboxes as $name => $html ) {
4295 if ( $html && !isset( $checkboxes[$name] ) ) {
4296 $checkboxes[$name] = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $html ) ] );
4297 }
4298 }
4299
4300 return $checkboxes;
4301 }
4302
4303 /**
4304 * Get the message key of the label for the button to save the page
4305 *
4306 * @return string
4307 */
4308 private function getSaveButtonLabel() {
4309 $labelAsPublish =
4310 $this->mArticle->getContext()->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4311
4312 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4313 $newPage = !$this->mTitle->exists();
4314
4315 if ( $labelAsPublish ) {
4316 $buttonLabelKey = $newPage ? 'publishpage' : 'publishchanges';
4317 } else {
4318 $buttonLabelKey = $newPage ? 'savearticle' : 'savechanges';
4319 }
4320
4321 return $buttonLabelKey;
4322 }
4323
4324 /**
4325 * Returns an array of html code of the following buttons:
4326 * save, diff and preview
4327 *
4328 * @param int $tabindex Current tabindex
4329 *
4330 * @return array
4331 */
4332 public function getEditButtons( &$tabindex ) {
4333 $buttons = [];
4334
4335 $buttonLabel = $this->context->msg( $this->getSaveButtonLabel() )->text();
4336
4337 $attribs = [
4338 'name' => 'wpSave',
4339 'tabindex' => ++$tabindex,
4340 ] + Linker::tooltipAndAccesskeyAttribs( 'save' );
4341
4342 if ( $this->oouiEnabled ) {
4343 $saveConfig = OOUI\Element::configFromHtmlAttributes( $attribs );
4344 $buttons['save'] = new OOUI\ButtonInputWidget( [
4345 'id' => 'wpSaveWidget',
4346 'inputId' => 'wpSave',
4347 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4348 'useInputTag' => true,
4349 'flags' => [ 'constructive', 'primary' ],
4350 'label' => $buttonLabel,
4351 'infusable' => true,
4352 'type' => 'submit',
4353 ] + $saveConfig );
4354 } else {
4355 $buttons['save'] = Html::submitButton(
4356 $buttonLabel,
4357 $attribs + [ 'id' => 'wpSave' ],
4358 [ 'mw-ui-progressive' ]
4359 );
4360 }
4361
4362 $attribs = [
4363 'name' => 'wpPreview',
4364 'tabindex' => ++$tabindex,
4365 ] + Linker::tooltipAndAccesskeyAttribs( 'preview' );
4366 if ( $this->oouiEnabled ) {
4367 $previewConfig = OOUI\Element::configFromHtmlAttributes( $attribs );
4368 $buttons['preview'] = new OOUI\ButtonInputWidget( [
4369 'id' => 'wpPreviewWidget',
4370 'inputId' => 'wpPreview',
4371 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4372 'useInputTag' => true,
4373 'label' => $this->context->msg( 'showpreview' )->text(),
4374 'infusable' => true,
4375 'type' => 'submit'
4376 ] + $previewConfig );
4377 } else {
4378 $buttons['preview'] = Html::submitButton(
4379 $this->context->msg( 'showpreview' )->text(),
4380 $attribs + [ 'id' => 'wpPreview' ]
4381 );
4382 }
4383 $attribs = [
4384 'name' => 'wpDiff',
4385 'tabindex' => ++$tabindex,
4386 ] + Linker::tooltipAndAccesskeyAttribs( 'diff' );
4387 if ( $this->oouiEnabled ) {
4388 $diffConfig = OOUI\Element::configFromHtmlAttributes( $attribs );
4389 $buttons['diff'] = new OOUI\ButtonInputWidget( [
4390 'id' => 'wpDiffWidget',
4391 'inputId' => 'wpDiff',
4392 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4393 'useInputTag' => true,
4394 'label' => $this->context->msg( 'showdiff' )->text(),
4395 'infusable' => true,
4396 'type' => 'submit',
4397 ] + $diffConfig );
4398 } else {
4399 $buttons['diff'] = Html::submitButton(
4400 $this->context->msg( 'showdiff' )->text(),
4401 $attribs + [ 'id' => 'wpDiff' ]
4402 );
4403 }
4404
4405 // Avoid PHP 7.1 warning of passing $this by reference
4406 $editPage = $this;
4407 Hooks::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4408
4409 return $buttons;
4410 }
4411
4412 /**
4413 * Creates a basic error page which informs the user that
4414 * they have attempted to edit a nonexistent section.
4415 */
4416 public function noSuchSectionPage() {
4417 global $wgOut;
4418
4419 $wgOut->prepareErrorPage( $this->context->msg( 'nosuchsectiontitle' ) );
4420
4421 $res = $this->context->msg( 'nosuchsectiontext', $this->section )->parseAsBlock();
4422
4423 // Avoid PHP 7.1 warning of passing $this by reference
4424 $editPage = $this;
4425 Hooks::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4426 $wgOut->addHTML( $res );
4427
4428 $wgOut->returnToMain( false, $this->mTitle );
4429 }
4430
4431 /**
4432 * Show "your edit contains spam" page with your diff and text
4433 *
4434 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4435 */
4436 public function spamPageWithContent( $match = false ) {
4437 global $wgOut, $wgLang;
4438 $this->textbox2 = $this->textbox1;
4439
4440 if ( is_array( $match ) ) {
4441 $match = $wgLang->listToText( $match );
4442 }
4443 $wgOut->prepareErrorPage( $this->context->msg( 'spamprotectiontitle' ) );
4444
4445 $wgOut->addHTML( '<div id="spamprotected">' );
4446 $wgOut->addWikiMsg( 'spamprotectiontext' );
4447 if ( $match ) {
4448 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4449 }
4450 $wgOut->addHTML( '</div>' );
4451
4452 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4453 $this->showDiff();
4454
4455 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4456 $this->showTextbox2();
4457
4458 $wgOut->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4459 }
4460
4461 /**
4462 * Check if the browser is on a blacklist of user-agents known to
4463 * mangle UTF-8 data on form submission. Returns true if Unicode
4464 * should make it through, false if it's known to be a problem.
4465 * @return bool
4466 */
4467 private function checkUnicodeCompliantBrowser() {
4468 global $wgBrowserBlackList, $wgRequest;
4469
4470 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4471 if ( $currentbrowser === false ) {
4472 // No User-Agent header sent? Trust it by default...
4473 return true;
4474 }
4475
4476 foreach ( $wgBrowserBlackList as $browser ) {
4477 if ( preg_match( $browser, $currentbrowser ) ) {
4478 return false;
4479 }
4480 }
4481 return true;
4482 }
4483
4484 /**
4485 * Filter an input field through a Unicode de-armoring process if it
4486 * came from an old browser with known broken Unicode editing issues.
4487 *
4488 * @param WebRequest $request
4489 * @param string $field
4490 * @return string
4491 */
4492 protected function safeUnicodeInput( $request, $field ) {
4493 $text = rtrim( $request->getText( $field ) );
4494 return $request->getBool( 'safemode' )
4495 ? $this->unmakeSafe( $text )
4496 : $text;
4497 }
4498
4499 /**
4500 * Filter an output field through a Unicode armoring process if it is
4501 * going to an old browser with known broken Unicode editing issues.
4502 *
4503 * @param string $text
4504 * @return string
4505 */
4506 protected function safeUnicodeOutput( $text ) {
4507 return $this->checkUnicodeCompliantBrowser()
4508 ? $text
4509 : $this->makeSafe( $text );
4510 }
4511
4512 /**
4513 * A number of web browsers are known to corrupt non-ASCII characters
4514 * in a UTF-8 text editing environment. To protect against this,
4515 * detected browsers will be served an armored version of the text,
4516 * with non-ASCII chars converted to numeric HTML character references.
4517 *
4518 * Preexisting such character references will have a 0 added to them
4519 * to ensure that round-trips do not alter the original data.
4520 *
4521 * @param string $invalue
4522 * @return string
4523 */
4524 private function makeSafe( $invalue ) {
4525 // Armor existing references for reversibility.
4526 $invalue = strtr( $invalue, [ "&#x" => "&#x0" ] );
4527
4528 $bytesleft = 0;
4529 $result = "";
4530 $working = 0;
4531 $valueLength = strlen( $invalue );
4532 for ( $i = 0; $i < $valueLength; $i++ ) {
4533 $bytevalue = ord( $invalue[$i] );
4534 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4535 $result .= chr( $bytevalue );
4536 $bytesleft = 0;
4537 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4538 $working = $working << 6;
4539 $working += ( $bytevalue & 0x3F );
4540 $bytesleft--;
4541 if ( $bytesleft <= 0 ) {
4542 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4543 }
4544 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4545 $working = $bytevalue & 0x1F;
4546 $bytesleft = 1;
4547 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4548 $working = $bytevalue & 0x0F;
4549 $bytesleft = 2;
4550 } else { // 1111 0xxx
4551 $working = $bytevalue & 0x07;
4552 $bytesleft = 3;
4553 }
4554 }
4555 return $result;
4556 }
4557
4558 /**
4559 * Reverse the previously applied transliteration of non-ASCII characters
4560 * back to UTF-8. Used to protect data from corruption by broken web browsers
4561 * as listed in $wgBrowserBlackList.
4562 *
4563 * @param string $invalue
4564 * @return string
4565 */
4566 private function unmakeSafe( $invalue ) {
4567 $result = "";
4568 $valueLength = strlen( $invalue );
4569 for ( $i = 0; $i < $valueLength; $i++ ) {
4570 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
4571 $i += 3;
4572 $hexstring = "";
4573 do {
4574 $hexstring .= $invalue[$i];
4575 $i++;
4576 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4577
4578 // Do some sanity checks. These aren't needed for reversibility,
4579 // but should help keep the breakage down if the editor
4580 // breaks one of the entities whilst editing.
4581 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4582 $codepoint = hexdec( $hexstring );
4583 $result .= UtfNormal\Utils::codepointToUtf8( $codepoint );
4584 } else {
4585 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4586 }
4587 } else {
4588 $result .= substr( $invalue, $i, 1 );
4589 }
4590 }
4591 // reverse the transform that we made for reversibility reasons.
4592 return strtr( $result, [ "&#x0" => "&#x" ] );
4593 }
4594
4595 /**
4596 * @since 1.29
4597 */
4598 protected function addEditNotices() {
4599 global $wgOut;
4600
4601 $editNotices = $this->mTitle->getEditNotices( $this->oldid );
4602 if ( count( $editNotices ) ) {
4603 $wgOut->addHTML( implode( "\n", $editNotices ) );
4604 } else {
4605 $msg = $this->context->msg( 'editnotice-notext' );
4606 if ( !$msg->isDisabled() ) {
4607 $wgOut->addHTML(
4608 '<div class="mw-editnotice-notext">'
4609 . $msg->parseAsBlock()
4610 . '</div>'
4611 );
4612 }
4613 }
4614 }
4615
4616 /**
4617 * @since 1.29
4618 */
4619 protected function addTalkPageText() {
4620 global $wgOut;
4621
4622 if ( $this->mTitle->isTalkPage() ) {
4623 $wgOut->addWikiMsg( 'talkpagetext' );
4624 }
4625 }
4626
4627 /**
4628 * @since 1.29
4629 */
4630 protected function addLongPageWarningHeader() {
4631 global $wgMaxArticleSize, $wgOut, $wgLang;
4632
4633 if ( $this->contentLength === false ) {
4634 $this->contentLength = strlen( $this->textbox1 );
4635 }
4636
4637 if ( $this->tooBig || $this->contentLength > $wgMaxArticleSize * 1024 ) {
4638 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4639 [
4640 'longpageerror',
4641 $wgLang->formatNum( round( $this->contentLength / 1024, 3 ) ),
4642 $wgLang->formatNum( $wgMaxArticleSize )
4643 ]
4644 );
4645 } else {
4646 if ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) {
4647 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4648 [
4649 'longpage-hint',
4650 $wgLang->formatSize( strlen( $this->textbox1 ) ),
4651 strlen( $this->textbox1 )
4652 ]
4653 );
4654 }
4655 }
4656 }
4657
4658 /**
4659 * @since 1.29
4660 */
4661 protected function addPageProtectionWarningHeaders() {
4662 global $wgOut;
4663
4664 if ( $this->mTitle->isProtected( 'edit' ) &&
4665 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
4666 ) {
4667 # Is the title semi-protected?
4668 if ( $this->mTitle->isSemiProtected() ) {
4669 $noticeMsg = 'semiprotectedpagewarning';
4670 } else {
4671 # Then it must be protected based on static groups (regular)
4672 $noticeMsg = 'protectedpagewarning';
4673 }
4674 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
4675 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4676 }
4677 if ( $this->mTitle->isCascadeProtected() ) {
4678 # Is this page under cascading protection from some source pages?
4679 /** @var Title[] $cascadeSources */
4680 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
4681 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4682 $cascadeSourcesCount = count( $cascadeSources );
4683 if ( $cascadeSourcesCount > 0 ) {
4684 # Explain, and list the titles responsible
4685 foreach ( $cascadeSources as $page ) {
4686 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4687 }
4688 }
4689 $notice .= '</div>';
4690 $wgOut->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4691 }
4692 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
4693 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
4694 [ 'lim' => 1,
4695 'showIfEmpty' => false,
4696 'msgKey' => [ 'titleprotectedwarning' ],
4697 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4698 }
4699 }
4700
4701 /**
4702 * @param OutputPage $out
4703 * @since 1.29
4704 */
4705 protected function addExplainConflictHeader( OutputPage $out ) {
4706 $out->wrapWikiMsg(
4707 "<div class='mw-explainconflict'>\n$1\n</div>",
4708 [ 'explainconflict', $this->context->msg( $this->getSaveButtonLabel() )->text() ]
4709 );
4710 }
4711
4712 /**
4713 * @param string $name
4714 * @param mixed[] $customAttribs
4715 * @param User $user
4716 * @return mixed[]
4717 * @since 1.29
4718 */
4719 protected function buildTextboxAttribs( $name, array $customAttribs, User $user ) {
4720 $attribs = $customAttribs + [
4721 'accesskey' => ',',
4722 'id' => $name,
4723 'cols' => 80,
4724 'rows' => 25,
4725 // Avoid PHP notices when appending preferences
4726 // (appending allows customAttribs['style'] to still work).
4727 'style' => ''
4728 ];
4729
4730 // The following classes can be used here:
4731 // * mw-editfont-default
4732 // * mw-editfont-monospace
4733 // * mw-editfont-sans-serif
4734 // * mw-editfont-serif
4735 $class = 'mw-editfont-' . $user->getOption( 'editfont' );
4736
4737 if ( isset( $attribs['class'] ) ) {
4738 if ( is_string( $attribs['class'] ) ) {
4739 $attribs['class'] .= ' ' . $class;
4740 } elseif ( is_array( $attribs['class'] ) ) {
4741 $attribs['class'][] = $class;
4742 }
4743 } else {
4744 $attribs['class'] = $class;
4745 }
4746
4747 $pageLang = $this->mTitle->getPageLanguage();
4748 $attribs['lang'] = $pageLang->getHtmlCode();
4749 $attribs['dir'] = $pageLang->getDir();
4750
4751 return $attribs;
4752 }
4753
4754 /**
4755 * @param string $wikitext
4756 * @return string
4757 * @since 1.29
4758 */
4759 protected function addNewLineAtEnd( $wikitext ) {
4760 if ( strval( $wikitext ) !== '' ) {
4761 // Ensure there's a newline at the end, otherwise adding lines
4762 // is awkward.
4763 // But don't add a newline if the text is empty, or Firefox in XHTML
4764 // mode will show an extra newline. A bit annoying.
4765 $wikitext .= "\n";
4766 return $wikitext;
4767 }
4768 return $wikitext;
4769 }
4770 }