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