Make undo fail if more than just the main slot is affected.
[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 $undoMsg = null;
1188
1189 # Sanity check, make sure it's the right page,
1190 # the revisions exist and they were not deleted.
1191 # Otherwise, $content will be left as-is.
1192 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1193 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1194 !$oldrev->isDeleted( Revision::DELETED_TEXT )
1195 ) {
1196 if ( WikiPage::hasDifferencesOutsideMainSlot( $undorev, $oldrev ) ) {
1197 // Cannot yet undo edits that involve anything other the main slot.
1198 $undoMsg = 'main-slot-only';
1199 } else {
1200 $content = $this->page->getUndoContent( $undorev, $oldrev );
1201
1202 if ( $content === false ) {
1203 # Warn the user that something went wrong
1204 $undoMsg = 'failure';
1205 }
1206 }
1207
1208 if ( $undoMsg === null ) {
1209 $oldContent = $this->page->getContent( Revision::RAW );
1210 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
1211 $newContent = $content->preSaveTransform( $this->mTitle, $user, $popts );
1212 if ( $newContent->getModel() !== $oldContent->getModel() ) {
1213 // The undo may change content
1214 // model if its reverting the top
1215 // edit. This can result in
1216 // mismatched content model/format.
1217 $this->contentModel = $newContent->getModel();
1218 $this->contentFormat = $oldrev->getContentFormat();
1219 }
1220
1221 if ( $newContent->equals( $oldContent ) ) {
1222 # Tell the user that the undo results in no change,
1223 # i.e. the revisions were already undone.
1224 $undoMsg = 'nochange';
1225 $content = false;
1226 } else {
1227 # Inform the user of our success and set an automatic edit summary
1228 $undoMsg = 'success';
1229
1230 # If we just undid one rev, use an autosummary
1231 $firstrev = $oldrev->getNext();
1232 if ( $firstrev && $firstrev->getId() == $undo ) {
1233 $userText = $undorev->getUserText();
1234 if ( $userText === '' ) {
1235 $undoSummary = $this->context->msg(
1236 'undo-summary-username-hidden',
1237 $undo
1238 )->inContentLanguage()->text();
1239 } else {
1240 $undoSummary = $this->context->msg(
1241 'undo-summary',
1242 $undo,
1243 $userText
1244 )->inContentLanguage()->text();
1245 }
1246 if ( $this->summary === '' ) {
1247 $this->summary = $undoSummary;
1248 } else {
1249 $this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
1250 ->inContentLanguage()->text() . $this->summary;
1251 }
1252 $this->undidRev = $undo;
1253 }
1254 $this->formtype = 'diff';
1255 }
1256 }
1257 } else {
1258 // Failed basic sanity checks.
1259 // Older revisions may have been removed since the link
1260 // was created, or we may simply have got bogus input.
1261 $undoMsg = 'norev';
1262 }
1263
1264 $out = $this->context->getOutput();
1265 // Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
1266 // undo-nochange.
1267 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1268 $this->editFormPageTop .= $out->parse( "<div class=\"{$class}\">" .
1269 $this->context->msg( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1270 }
1271
1272 if ( $content === false ) {
1273 $content = $this->getOriginalContent( $user );
1274 }
1275 }
1276 }
1277
1278 return $content;
1279 }
1280
1281 /**
1282 * Get the content of the wanted revision, without section extraction.
1283 *
1284 * The result of this function can be used to compare user's input with
1285 * section replaced in its context (using WikiPage::replaceSectionAtRev())
1286 * to the original text of the edit.
1287 *
1288 * This differs from Article::getContent() that when a missing revision is
1289 * encountered the result will be null and not the
1290 * 'missing-revision' message.
1291 *
1292 * @since 1.19
1293 * @param User $user The user to get the revision for
1294 * @return Content|null
1295 */
1296 private function getOriginalContent( User $user ) {
1297 if ( $this->section == 'new' ) {
1298 return $this->getCurrentContent();
1299 }
1300 $revision = $this->mArticle->getRevisionFetched();
1301 if ( $revision === null ) {
1302 $handler = ContentHandler::getForModelID( $this->contentModel );
1303 return $handler->makeEmptyContent();
1304 }
1305 $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1306 return $content;
1307 }
1308
1309 /**
1310 * Get the edit's parent revision ID
1311 *
1312 * The "parent" revision is the ancestor that should be recorded in this
1313 * page's revision history. It is either the revision ID of the in-memory
1314 * article content, or in the case of a 3-way merge in order to rebase
1315 * across a recoverable edit conflict, the ID of the newer revision to
1316 * which we have rebased this page.
1317 *
1318 * @since 1.27
1319 * @return int Revision ID
1320 */
1321 public function getParentRevId() {
1322 if ( $this->parentRevId ) {
1323 return $this->parentRevId;
1324 } else {
1325 return $this->mArticle->getRevIdFetched();
1326 }
1327 }
1328
1329 /**
1330 * Get the current content of the page. This is basically similar to
1331 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1332 * content object is returned instead of null.
1333 *
1334 * @since 1.21
1335 * @return Content
1336 */
1337 protected function getCurrentContent() {
1338 $rev = $this->page->getRevision();
1339 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1340
1341 if ( $content === false || $content === null ) {
1342 $handler = ContentHandler::getForModelID( $this->contentModel );
1343 return $handler->makeEmptyContent();
1344 } elseif ( !$this->undidRev ) {
1345 // Content models should always be the same since we error
1346 // out if they are different before this point (in ->edit()).
1347 // The exception being, during an undo, the current revision might
1348 // differ from the prior revision.
1349 $logger = LoggerFactory::getInstance( 'editpage' );
1350 if ( $this->contentModel !== $rev->getContentModel() ) {
1351 $logger->warning( "Overriding content model from current edit {prev} to {new}", [
1352 'prev' => $this->contentModel,
1353 'new' => $rev->getContentModel(),
1354 'title' => $this->getTitle()->getPrefixedDBkey(),
1355 'method' => __METHOD__
1356 ] );
1357 $this->contentModel = $rev->getContentModel();
1358 }
1359
1360 // Given that the content models should match, the current selected
1361 // format should be supported.
1362 if ( !$content->isSupportedFormat( $this->contentFormat ) ) {
1363 $logger->warning( "Current revision content format unsupported. Overriding {prev} to {new}", [
1364
1365 'prev' => $this->contentFormat,
1366 'new' => $rev->getContentFormat(),
1367 'title' => $this->getTitle()->getPrefixedDBkey(),
1368 'method' => __METHOD__
1369 ] );
1370 $this->contentFormat = $rev->getContentFormat();
1371 }
1372 }
1373 return $content;
1374 }
1375
1376 /**
1377 * Use this method before edit() to preload some content into the edit box
1378 *
1379 * @param Content $content
1380 *
1381 * @since 1.21
1382 */
1383 public function setPreloadedContent( Content $content ) {
1384 $this->mPreloadContent = $content;
1385 }
1386
1387 /**
1388 * Get the contents to be preloaded into the box, either set by
1389 * an earlier setPreloadText() or by loading the given page.
1390 *
1391 * @param string $preload Representing the title to preload from.
1392 * @param array $params Parameters to use (interface-message style) in the preloaded text
1393 *
1394 * @return Content
1395 *
1396 * @since 1.21
1397 */
1398 protected function getPreloadedContent( $preload, $params = [] ) {
1399 if ( !empty( $this->mPreloadContent ) ) {
1400 return $this->mPreloadContent;
1401 }
1402
1403 $handler = ContentHandler::getForModelID( $this->contentModel );
1404
1405 if ( $preload === '' ) {
1406 return $handler->makeEmptyContent();
1407 }
1408
1409 $user = $this->context->getUser();
1410 $title = Title::newFromText( $preload );
1411 # Check for existence to avoid getting MediaWiki:Noarticletext
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
1417 $page = WikiPage::factory( $title );
1418 if ( $page->isRedirect() ) {
1419 $title = $page->getRedirectTarget();
1420 # Same as before
1421 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $user ) ) {
1422 // TODO: somehow show a warning to the user!
1423 return $handler->makeEmptyContent();
1424 }
1425 $page = WikiPage::factory( $title );
1426 }
1427
1428 $parserOptions = ParserOptions::newFromUser( $user );
1429 $content = $page->getContent( Revision::RAW );
1430
1431 if ( !$content ) {
1432 // TODO: somehow show a warning to the user!
1433 return $handler->makeEmptyContent();
1434 }
1435
1436 if ( $content->getModel() !== $handler->getModelID() ) {
1437 $converted = $content->convert( $handler->getModelID() );
1438
1439 if ( !$converted ) {
1440 // TODO: somehow show a warning to the user!
1441 wfDebug( "Attempt to preload incompatible content: " .
1442 "can't convert " . $content->getModel() .
1443 " to " . $handler->getModelID() );
1444
1445 return $handler->makeEmptyContent();
1446 }
1447
1448 $content = $converted;
1449 }
1450
1451 return $content->preloadTransform( $title, $parserOptions, $params );
1452 }
1453
1454 /**
1455 * Make sure the form isn't faking a user's credentials.
1456 *
1457 * @param WebRequest &$request
1458 * @return bool
1459 * @private
1460 */
1461 public function tokenOk( &$request ) {
1462 $token = $request->getVal( 'wpEditToken' );
1463 $user = $this->context->getUser();
1464 $this->mTokenOk = $user->matchEditToken( $token );
1465 $this->mTokenOkExceptSuffix = $user->matchEditTokenNoSuffix( $token );
1466 return $this->mTokenOk;
1467 }
1468
1469 /**
1470 * Sets post-edit cookie indicating the user just saved a particular revision.
1471 *
1472 * This uses a temporary cookie for each revision ID so separate saves will never
1473 * interfere with each other.
1474 *
1475 * Article::view deletes the cookie on server-side after the redirect and
1476 * converts the value to the global JavaScript variable wgPostEdit.
1477 *
1478 * If the variable were set on the server, it would be cached, which is unwanted
1479 * since the post-edit state should only apply to the load right after the save.
1480 *
1481 * @param int $statusValue The status value (to check for new article status)
1482 */
1483 protected function setPostEditCookie( $statusValue ) {
1484 $revisionId = $this->page->getLatest();
1485 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1486
1487 $val = 'saved';
1488 if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1489 $val = 'created';
1490 } elseif ( $this->oldid ) {
1491 $val = 'restored';
1492 }
1493
1494 $response = $this->context->getRequest()->response();
1495 $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION );
1496 }
1497
1498 /**
1499 * Attempt submission
1500 * @param array|bool &$resultDetails See docs for $result in internalAttemptSave
1501 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1502 * @return Status The resulting status object.
1503 */
1504 public function attemptSave( &$resultDetails = false ) {
1505 // TODO: MCR: treat $this->minoredit like $this->bot and check isAllowed( 'minoredit' )!
1506 // Also, add $this->autopatrol like $this->bot and check isAllowed( 'autopatrol' )!
1507 // This is needed since PageUpdater no longer checks these rights!
1508
1509 // Allow bots to exempt some edits from bot flagging
1510 $bot = $this->context->getUser()->isAllowed( 'bot' ) && $this->bot;
1511 $status = $this->internalAttemptSave( $resultDetails, $bot );
1512
1513 Hooks::run( 'EditPage::attemptSave:after', [ $this, $status, $resultDetails ] );
1514
1515 return $status;
1516 }
1517
1518 /**
1519 * Log when a page was successfully saved after the edit conflict view
1520 */
1521 private function incrementResolvedConflicts() {
1522 if ( $this->context->getRequest()->getText( 'mode' ) !== 'conflict' ) {
1523 return;
1524 }
1525
1526 $this->getEditConflictHelper()->incrementResolvedStats();
1527 }
1528
1529 /**
1530 * Handle status, such as after attempt save
1531 *
1532 * @param Status $status
1533 * @param array|bool $resultDetails
1534 *
1535 * @throws ErrorPageError
1536 * @return bool False, if output is done, true if rest of the form should be displayed
1537 */
1538 private function handleStatus( Status $status, $resultDetails ) {
1539 /**
1540 * @todo FIXME: once the interface for internalAttemptSave() is made
1541 * nicer, this should use the message in $status
1542 */
1543 if ( $status->value == self::AS_SUCCESS_UPDATE
1544 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1545 ) {
1546 $this->incrementResolvedConflicts();
1547
1548 $this->didSave = true;
1549 if ( !$resultDetails['nullEdit'] ) {
1550 $this->setPostEditCookie( $status->value );
1551 }
1552 }
1553
1554 $out = $this->context->getOutput();
1555
1556 // "wpExtraQueryRedirect" is a hidden input to modify
1557 // after save URL and is not used by actual edit form
1558 $request = $this->context->getRequest();
1559 $extraQueryRedirect = $request->getVal( 'wpExtraQueryRedirect' );
1560
1561 switch ( $status->value ) {
1562 case self::AS_HOOK_ERROR_EXPECTED:
1563 case self::AS_CONTENT_TOO_BIG:
1564 case self::AS_ARTICLE_WAS_DELETED:
1565 case self::AS_CONFLICT_DETECTED:
1566 case self::AS_SUMMARY_NEEDED:
1567 case self::AS_TEXTBOX_EMPTY:
1568 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1569 case self::AS_END:
1570 case self::AS_BLANK_ARTICLE:
1571 case self::AS_SELF_REDIRECT:
1572 return true;
1573
1574 case self::AS_HOOK_ERROR:
1575 return false;
1576
1577 case self::AS_CANNOT_USE_CUSTOM_MODEL:
1578 case self::AS_PARSE_ERROR:
1579 case self::AS_UNICODE_NOT_SUPPORTED:
1580 $out->addWikiText( '<div class="error">' . "\n" . $status->getWikiText() . '</div>' );
1581 return true;
1582
1583 case self::AS_SUCCESS_NEW_ARTICLE:
1584 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1585 if ( $extraQueryRedirect ) {
1586 if ( $query === '' ) {
1587 $query = $extraQueryRedirect;
1588 } else {
1589 $query = $query . '&' . $extraQueryRedirect;
1590 }
1591 }
1592 $anchor = $resultDetails['sectionanchor'] ?? '';
1593 $out->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1594 return false;
1595
1596 case self::AS_SUCCESS_UPDATE:
1597 $extraQuery = '';
1598 $sectionanchor = $resultDetails['sectionanchor'];
1599
1600 // Give extensions a chance to modify URL query on update
1601 Hooks::run(
1602 'ArticleUpdateBeforeRedirect',
1603 [ $this->mArticle, &$sectionanchor, &$extraQuery ]
1604 );
1605
1606 if ( $resultDetails['redirect'] ) {
1607 if ( $extraQuery == '' ) {
1608 $extraQuery = 'redirect=no';
1609 } else {
1610 $extraQuery = 'redirect=no&' . $extraQuery;
1611 }
1612 }
1613 if ( $extraQueryRedirect ) {
1614 if ( $extraQuery === '' ) {
1615 $extraQuery = $extraQueryRedirect;
1616 } else {
1617 $extraQuery = $extraQuery . '&' . $extraQueryRedirect;
1618 }
1619 }
1620
1621 $out->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1622 return false;
1623
1624 case self::AS_SPAM_ERROR:
1625 $this->spamPageWithContent( $resultDetails['spam'] );
1626 return false;
1627
1628 case self::AS_BLOCKED_PAGE_FOR_USER:
1629 throw new UserBlockedError( $this->context->getUser()->getBlock() );
1630
1631 case self::AS_IMAGE_REDIRECT_ANON:
1632 case self::AS_IMAGE_REDIRECT_LOGGED:
1633 throw new PermissionsError( 'upload' );
1634
1635 case self::AS_READ_ONLY_PAGE_ANON:
1636 case self::AS_READ_ONLY_PAGE_LOGGED:
1637 throw new PermissionsError( 'edit' );
1638
1639 case self::AS_READ_ONLY_PAGE:
1640 throw new ReadOnlyError;
1641
1642 case self::AS_RATE_LIMITED:
1643 throw new ThrottledError();
1644
1645 case self::AS_NO_CREATE_PERMISSION:
1646 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1647 throw new PermissionsError( $permission );
1648
1649 case self::AS_NO_CHANGE_CONTENT_MODEL:
1650 throw new PermissionsError( 'editcontentmodel' );
1651
1652 default:
1653 // We don't recognize $status->value. The only way that can happen
1654 // is if an extension hook aborted from inside ArticleSave.
1655 // Render the status object into $this->hookError
1656 // FIXME this sucks, we should just use the Status object throughout
1657 $this->hookError = '<div class="error">' ."\n" . $status->getWikiText() .
1658 '</div>';
1659 return true;
1660 }
1661 }
1662
1663 /**
1664 * Run hooks that can filter edits just before they get saved.
1665 *
1666 * @param Content $content The Content to filter.
1667 * @param Status $status For reporting the outcome to the caller
1668 * @param User $user The user performing the edit
1669 *
1670 * @return bool
1671 */
1672 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1673 // Run old style post-section-merge edit filter
1674 if ( $this->hookError != '' ) {
1675 # ...or the hook could be expecting us to produce an error
1676 $status->fatal( 'hookaborted' );
1677 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1678 return false;
1679 }
1680
1681 // Run new style post-section-merge edit filter
1682 if ( !Hooks::run( 'EditFilterMergedContent',
1683 [ $this->context, $content, $status, $this->summary,
1684 $user, $this->minoredit ] )
1685 ) {
1686 # Error messages etc. could be handled within the hook...
1687 if ( $status->isGood() ) {
1688 $status->fatal( 'hookaborted' );
1689 // Not setting $this->hookError here is a hack to allow the hook
1690 // to cause a return to the edit page without $this->hookError
1691 // being set. This is used by ConfirmEdit to display a captcha
1692 // without any error message cruft.
1693 } else {
1694 $this->hookError = $this->formatStatusErrors( $status );
1695 }
1696 // Use the existing $status->value if the hook set it
1697 if ( !$status->value ) {
1698 $status->value = self::AS_HOOK_ERROR;
1699 }
1700 return false;
1701 } elseif ( !$status->isOK() ) {
1702 # ...or the hook could be expecting us to produce an error
1703 // FIXME this sucks, we should just use the Status object throughout
1704 $this->hookError = $this->formatStatusErrors( $status );
1705 $status->fatal( 'hookaborted' );
1706 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1707 return false;
1708 }
1709
1710 return true;
1711 }
1712
1713 /**
1714 * Wrap status errors in an errorbox for increased visibility
1715 *
1716 * @param Status $status
1717 * @return string Wikitext
1718 */
1719 private function formatStatusErrors( Status $status ) {
1720 $errmsg = $status->getWikiText(
1721 'edit-error-short',
1722 'edit-error-long',
1723 $this->context->getLanguage()
1724 );
1725 return <<<ERROR
1726 <div class="errorbox">
1727 {$errmsg}
1728 </div>
1729 <br clear="all" />
1730 ERROR;
1731 }
1732
1733 /**
1734 * Return the summary to be used for a new section.
1735 *
1736 * @param string $sectionanchor Set to the section anchor text
1737 * @return string
1738 */
1739 private function newSectionSummary( &$sectionanchor = null ) {
1740 global $wgParser;
1741
1742 if ( $this->sectiontitle !== '' ) {
1743 $sectionanchor = $this->guessSectionName( $this->sectiontitle );
1744 // If no edit summary was specified, create one automatically from the section
1745 // title and have it link to the new section. Otherwise, respect the summary as
1746 // passed.
1747 if ( $this->summary === '' ) {
1748 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1749 return $this->context->msg( 'newsectionsummary' )
1750 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1751 }
1752 } elseif ( $this->summary !== '' ) {
1753 $sectionanchor = $this->guessSectionName( $this->summary );
1754 # This is a new section, so create a link to the new section
1755 # in the revision summary.
1756 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1757 return $this->context->msg( 'newsectionsummary' )
1758 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1759 }
1760 return $this->summary;
1761 }
1762
1763 /**
1764 * Attempt submission (no UI)
1765 *
1766 * @param array &$result Array to add statuses to, currently with the
1767 * possible keys:
1768 * - spam (string): Spam string from content if any spam is detected by
1769 * matchSpamRegex.
1770 * - sectionanchor (string): Section anchor for a section save.
1771 * - nullEdit (bool): Set if doEditContent is OK. True if null edit,
1772 * false otherwise.
1773 * - redirect (bool): Set if doEditContent is OK. True if resulting
1774 * revision is a redirect.
1775 * @param bool $bot True if edit is being made under the bot right.
1776 *
1777 * @return Status Status object, possibly with a message, but always with
1778 * one of the AS_* constants in $status->value,
1779 *
1780 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1781 * various error display idiosyncrasies. There are also lots of cases
1782 * where error metadata is set in the object and retrieved later instead
1783 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1784 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1785 * time.
1786 */
1787 public function internalAttemptSave( &$result, $bot = false ) {
1788 $status = Status::newGood();
1789 $user = $this->context->getUser();
1790
1791 if ( !Hooks::run( 'EditPage::attemptSave', [ $this ] ) ) {
1792 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1793 $status->fatal( 'hookaborted' );
1794 $status->value = self::AS_HOOK_ERROR;
1795 return $status;
1796 }
1797
1798 if ( $this->unicodeCheck !== self::UNICODE_CHECK ) {
1799 $status->fatal( 'unicode-support-fail' );
1800 $status->value = self::AS_UNICODE_NOT_SUPPORTED;
1801 return $status;
1802 }
1803
1804 $request = $this->context->getRequest();
1805 $spam = $request->getText( 'wpAntispam' );
1806 if ( $spam !== '' ) {
1807 wfDebugLog(
1808 'SimpleAntiSpam',
1809 $user->getName() .
1810 ' editing "' .
1811 $this->mTitle->getPrefixedText() .
1812 '" submitted bogus field "' .
1813 $spam .
1814 '"'
1815 );
1816 $status->fatal( 'spamprotectionmatch', false );
1817 $status->value = self::AS_SPAM_ERROR;
1818 return $status;
1819 }
1820
1821 try {
1822 # Construct Content object
1823 $textbox_content = $this->toEditContent( $this->textbox1 );
1824 } catch ( MWContentSerializationException $ex ) {
1825 $status->fatal(
1826 'content-failed-to-parse',
1827 $this->contentModel,
1828 $this->contentFormat,
1829 $ex->getMessage()
1830 );
1831 $status->value = self::AS_PARSE_ERROR;
1832 return $status;
1833 }
1834
1835 # Check image redirect
1836 if ( $this->mTitle->getNamespace() == NS_FILE &&
1837 $textbox_content->isRedirect() &&
1838 !$user->isAllowed( 'upload' )
1839 ) {
1840 $code = $user->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1841 $status->setResult( false, $code );
1842
1843 return $status;
1844 }
1845
1846 # Check for spam
1847 $match = self::matchSummarySpamRegex( $this->summary );
1848 if ( $match === false && $this->section == 'new' ) {
1849 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1850 # regular summaries, it is added to the actual wikitext.
1851 if ( $this->sectiontitle !== '' ) {
1852 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1853 $match = self::matchSpamRegex( $this->sectiontitle );
1854 } else {
1855 # This branch is taken when the "Add Topic" user interface is used, or the API
1856 # is used with the 'summary' parameter.
1857 $match = self::matchSpamRegex( $this->summary );
1858 }
1859 }
1860 if ( $match === false ) {
1861 $match = self::matchSpamRegex( $this->textbox1 );
1862 }
1863 if ( $match !== false ) {
1864 $result['spam'] = $match;
1865 $ip = $request->getIP();
1866 $pdbk = $this->mTitle->getPrefixedDBkey();
1867 $match = str_replace( "\n", '', $match );
1868 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1869 $status->fatal( 'spamprotectionmatch', $match );
1870 $status->value = self::AS_SPAM_ERROR;
1871 return $status;
1872 }
1873 if ( !Hooks::run(
1874 'EditFilter',
1875 [ $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ] )
1876 ) {
1877 # Error messages etc. could be handled within the hook...
1878 $status->fatal( 'hookaborted' );
1879 $status->value = self::AS_HOOK_ERROR;
1880 return $status;
1881 } elseif ( $this->hookError != '' ) {
1882 # ...or the hook could be expecting us to produce an error
1883 $status->fatal( 'hookaborted' );
1884 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1885 return $status;
1886 }
1887
1888 if ( $user->isBlockedFrom( $this->mTitle, false ) ) {
1889 // Auto-block user's IP if the account was "hard" blocked
1890 if ( !wfReadOnly() ) {
1891 $user->spreadAnyEditBlock();
1892 }
1893 # Check block state against master, thus 'false'.
1894 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1895 return $status;
1896 }
1897
1898 $this->contentLength = strlen( $this->textbox1 );
1899 $config = $this->context->getConfig();
1900 $maxArticleSize = $config->get( 'MaxArticleSize' );
1901 if ( $this->contentLength > $maxArticleSize * 1024 ) {
1902 // Error will be displayed by showEditForm()
1903 $this->tooBig = true;
1904 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1905 return $status;
1906 }
1907
1908 if ( !$user->isAllowed( 'edit' ) ) {
1909 if ( $user->isAnon() ) {
1910 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1911 return $status;
1912 } else {
1913 $status->fatal( 'readonlytext' );
1914 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1915 return $status;
1916 }
1917 }
1918
1919 $changingContentModel = false;
1920 if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
1921 if ( !$config->get( 'ContentHandlerUseDB' ) ) {
1922 $status->fatal( 'editpage-cannot-use-custom-model' );
1923 $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
1924 return $status;
1925 } elseif ( !$user->isAllowed( 'editcontentmodel' ) ) {
1926 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1927 return $status;
1928 }
1929 // Make sure the user can edit the page under the new content model too
1930 $titleWithNewContentModel = clone $this->mTitle;
1931 $titleWithNewContentModel->setContentModel( $this->contentModel );
1932 if ( !$titleWithNewContentModel->userCan( 'editcontentmodel', $user )
1933 || !$titleWithNewContentModel->userCan( 'edit', $user )
1934 ) {
1935 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1936 return $status;
1937 }
1938
1939 $changingContentModel = true;
1940 $oldContentModel = $this->mTitle->getContentModel();
1941 }
1942
1943 if ( $this->changeTags ) {
1944 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
1945 $this->changeTags, $user );
1946 if ( !$changeTagsStatus->isOK() ) {
1947 $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
1948 return $changeTagsStatus;
1949 }
1950 }
1951
1952 if ( wfReadOnly() ) {
1953 $status->fatal( 'readonlytext' );
1954 $status->value = self::AS_READ_ONLY_PAGE;
1955 return $status;
1956 }
1957 if ( $user->pingLimiter() || $user->pingLimiter( 'linkpurge', 0 )
1958 || ( $changingContentModel && $user->pingLimiter( 'editcontentmodel' ) )
1959 ) {
1960 $status->fatal( 'actionthrottledtext' );
1961 $status->value = self::AS_RATE_LIMITED;
1962 return $status;
1963 }
1964
1965 # If the article has been deleted while editing, don't save it without
1966 # confirmation
1967 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1968 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1969 return $status;
1970 }
1971
1972 # Load the page data from the master. If anything changes in the meantime,
1973 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1974 $this->page->loadPageData( 'fromdbmaster' );
1975 $new = !$this->page->exists();
1976
1977 if ( $new ) {
1978 // Late check for create permission, just in case *PARANOIA*
1979 if ( !$this->mTitle->userCan( 'create', $user ) ) {
1980 $status->fatal( 'nocreatetext' );
1981 $status->value = self::AS_NO_CREATE_PERMISSION;
1982 wfDebug( __METHOD__ . ": no create permission\n" );
1983 return $status;
1984 }
1985
1986 // Don't save a new page if it's blank or if it's a MediaWiki:
1987 // message with content equivalent to default (allow empty pages
1988 // in this case to disable messages, see T52124)
1989 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1990 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1991 $defaultText = $defaultMessageText;
1992 } else {
1993 $defaultText = '';
1994 }
1995
1996 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1997 $this->blankArticle = true;
1998 $status->fatal( 'blankarticle' );
1999 $status->setResult( false, self::AS_BLANK_ARTICLE );
2000 return $status;
2001 }
2002
2003 if ( !$this->runPostMergeFilters( $textbox_content, $status, $user ) ) {
2004 return $status;
2005 }
2006
2007 $content = $textbox_content;
2008
2009 $result['sectionanchor'] = '';
2010 if ( $this->section == 'new' ) {
2011 if ( $this->sectiontitle !== '' ) {
2012 // Insert the section title above the content.
2013 $content = $content->addSectionHeader( $this->sectiontitle );
2014 } elseif ( $this->summary !== '' ) {
2015 // Insert the section title above the content.
2016 $content = $content->addSectionHeader( $this->summary );
2017 }
2018 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
2019 }
2020
2021 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
2022
2023 } else { # not $new
2024
2025 # Article exists. Check for edit conflict.
2026
2027 $this->page->clear(); # Force reload of dates, etc.
2028 $timestamp = $this->page->getTimestamp();
2029 $latest = $this->page->getLatest();
2030
2031 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
2032
2033 // Check editRevId if set, which handles same-second timestamp collisions
2034 if ( $timestamp != $this->edittime
2035 || ( $this->editRevId !== null && $this->editRevId != $latest )
2036 ) {
2037 $this->isConflict = true;
2038 if ( $this->section == 'new' ) {
2039 if ( $this->page->getUserText() == $user->getName() &&
2040 $this->page->getComment() == $this->newSectionSummary()
2041 ) {
2042 // Probably a duplicate submission of a new comment.
2043 // This can happen when CDN resends a request after
2044 // a timeout but the first one actually went through.
2045 wfDebug( __METHOD__
2046 . ": duplicate new section submission; trigger edit conflict!\n" );
2047 } else {
2048 // New comment; suppress conflict.
2049 $this->isConflict = false;
2050 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
2051 }
2052 } elseif ( $this->section == ''
2053 && Revision::userWasLastToEdit(
2054 DB_MASTER, $this->mTitle->getArticleID(),
2055 $user->getId(), $this->edittime
2056 )
2057 ) {
2058 # Suppress edit conflict with self, except for section edits where merging is required.
2059 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
2060 $this->isConflict = false;
2061 }
2062 }
2063
2064 // If sectiontitle is set, use it, otherwise use the summary as the section title.
2065 if ( $this->sectiontitle !== '' ) {
2066 $sectionTitle = $this->sectiontitle;
2067 } else {
2068 $sectionTitle = $this->summary;
2069 }
2070
2071 $content = null;
2072
2073 if ( $this->isConflict ) {
2074 wfDebug( __METHOD__
2075 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
2076 . " (id '{$this->editRevId}') (article time '{$timestamp}')\n" );
2077 // @TODO: replaceSectionAtRev() with base ID (not prior current) for ?oldid=X case
2078 // ...or disable section editing for non-current revisions (not exposed anyway).
2079 if ( $this->editRevId !== null ) {
2080 $content = $this->page->replaceSectionAtRev(
2081 $this->section,
2082 $textbox_content,
2083 $sectionTitle,
2084 $this->editRevId
2085 );
2086 } else {
2087 $content = $this->page->replaceSectionContent(
2088 $this->section,
2089 $textbox_content,
2090 $sectionTitle,
2091 $this->edittime
2092 );
2093 }
2094 } else {
2095 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
2096 $content = $this->page->replaceSectionContent(
2097 $this->section,
2098 $textbox_content,
2099 $sectionTitle
2100 );
2101 }
2102
2103 if ( is_null( $content ) ) {
2104 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
2105 $this->isConflict = true;
2106 $content = $textbox_content; // do not try to merge here!
2107 } elseif ( $this->isConflict ) {
2108 # Attempt merge
2109 if ( $this->mergeChangesIntoContent( $content ) ) {
2110 // Successful merge! Maybe we should tell the user the good news?
2111 $this->isConflict = false;
2112 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
2113 } else {
2114 $this->section = '';
2115 $this->textbox1 = ContentHandler::getContentText( $content );
2116 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
2117 }
2118 }
2119
2120 if ( $this->isConflict ) {
2121 $status->setResult( false, self::AS_CONFLICT_DETECTED );
2122 return $status;
2123 }
2124
2125 if ( !$this->runPostMergeFilters( $content, $status, $user ) ) {
2126 return $status;
2127 }
2128
2129 if ( $this->section == 'new' ) {
2130 // Handle the user preference to force summaries here
2131 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
2132 $this->missingSummary = true;
2133 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
2134 $status->value = self::AS_SUMMARY_NEEDED;
2135 return $status;
2136 }
2137
2138 // Do not allow the user to post an empty comment
2139 if ( $this->textbox1 == '' ) {
2140 $this->missingComment = true;
2141 $status->fatal( 'missingcommenttext' );
2142 $status->value = self::AS_TEXTBOX_EMPTY;
2143 return $status;
2144 }
2145 } elseif ( !$this->allowBlankSummary
2146 && !$content->equals( $this->getOriginalContent( $user ) )
2147 && !$content->isRedirect()
2148 && md5( $this->summary ) == $this->autoSumm
2149 ) {
2150 $this->missingSummary = true;
2151 $status->fatal( 'missingsummary' );
2152 $status->value = self::AS_SUMMARY_NEEDED;
2153 return $status;
2154 }
2155
2156 # All's well
2157 $sectionanchor = '';
2158 if ( $this->section == 'new' ) {
2159 $this->summary = $this->newSectionSummary( $sectionanchor );
2160 } elseif ( $this->section != '' ) {
2161 # Try to get a section anchor from the section source, redirect
2162 # to edited section if header found.
2163 # XXX: Might be better to integrate this into Article::replaceSectionAtRev
2164 # for duplicate heading checking and maybe parsing.
2165 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
2166 # We can't deal with anchors, includes, html etc in the header for now,
2167 # headline would need to be parsed to improve this.
2168 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
2169 $sectionanchor = $this->guessSectionName( $matches[2] );
2170 }
2171 }
2172 $result['sectionanchor'] = $sectionanchor;
2173
2174 // Save errors may fall down to the edit form, but we've now
2175 // merged the section into full text. Clear the section field
2176 // so that later submission of conflict forms won't try to
2177 // replace that into a duplicated mess.
2178 $this->textbox1 = $this->toEditText( $content );
2179 $this->section = '';
2180
2181 $status->value = self::AS_SUCCESS_UPDATE;
2182 }
2183
2184 if ( !$this->allowSelfRedirect
2185 && $content->isRedirect()
2186 && $content->getRedirectTarget()->equals( $this->getTitle() )
2187 ) {
2188 // If the page already redirects to itself, don't warn.
2189 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
2190 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
2191 $this->selfRedirect = true;
2192 $status->fatal( 'selfredirect' );
2193 $status->value = self::AS_SELF_REDIRECT;
2194 return $status;
2195 }
2196 }
2197
2198 // Check for length errors again now that the section is merged in
2199 $this->contentLength = strlen( $this->toEditText( $content ) );
2200 if ( $this->contentLength > $maxArticleSize * 1024 ) {
2201 $this->tooBig = true;
2202 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
2203 return $status;
2204 }
2205
2206 $flags = EDIT_AUTOSUMMARY |
2207 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
2208 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
2209 ( $bot ? EDIT_FORCE_BOT : 0 );
2210
2211 $doEditStatus = $this->page->doEditContent(
2212 $content,
2213 $this->summary,
2214 $flags,
2215 false,
2216 $user,
2217 $content->getDefaultFormat(),
2218 $this->changeTags,
2219 $this->undidRev
2220 );
2221
2222 if ( !$doEditStatus->isOK() ) {
2223 // Failure from doEdit()
2224 // Show the edit conflict page for certain recognized errors from doEdit(),
2225 // but don't show it for errors from extension hooks
2226 $errors = $doEditStatus->getErrorsArray();
2227 if ( in_array( $errors[0][0],
2228 [ 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ] )
2229 ) {
2230 $this->isConflict = true;
2231 // Destroys data doEdit() put in $status->value but who cares
2232 $doEditStatus->value = self::AS_END;
2233 }
2234 return $doEditStatus;
2235 }
2236
2237 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2238 if ( $result['nullEdit'] ) {
2239 // We don't know if it was a null edit until now, so increment here
2240 $user->pingLimiter( 'linkpurge' );
2241 }
2242 $result['redirect'] = $content->isRedirect();
2243
2244 $this->updateWatchlist();
2245
2246 // If the content model changed, add a log entry
2247 if ( $changingContentModel ) {
2248 $this->addContentModelChangeLogEntry(
2249 $user,
2250 $new ? false : $oldContentModel,
2251 $this->contentModel,
2252 $this->summary
2253 );
2254 }
2255
2256 return $status;
2257 }
2258
2259 /**
2260 * @param User $user
2261 * @param string|false $oldModel false if the page is being newly created
2262 * @param string $newModel
2263 * @param string $reason
2264 */
2265 protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
2266 $new = $oldModel === false;
2267 $log = new ManualLogEntry( 'contentmodel', $new ? 'new' : 'change' );
2268 $log->setPerformer( $user );
2269 $log->setTarget( $this->mTitle );
2270 $log->setComment( $reason );
2271 $log->setParameters( [
2272 '4::oldmodel' => $oldModel,
2273 '5::newmodel' => $newModel
2274 ] );
2275 $logid = $log->insert();
2276 $log->publish( $logid );
2277 }
2278
2279 /**
2280 * Register the change of watch status
2281 */
2282 protected function updateWatchlist() {
2283 $user = $this->context->getUser();
2284 if ( !$user->isLoggedIn() ) {
2285 return;
2286 }
2287
2288 $title = $this->mTitle;
2289 $watch = $this->watchthis;
2290 // Do this in its own transaction to reduce contention...
2291 DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
2292 if ( $watch == $user->isWatched( $title, User::IGNORE_USER_RIGHTS ) ) {
2293 return; // nothing to change
2294 }
2295 WatchAction::doWatchOrUnwatch( $watch, $title, $user );
2296 } );
2297 }
2298
2299 /**
2300 * Attempts to do 3-way merge of edit content with a base revision
2301 * and current content, in case of edit conflict, in whichever way appropriate
2302 * for the content type.
2303 *
2304 * @since 1.21
2305 *
2306 * @param Content $editContent
2307 *
2308 * @return bool
2309 */
2310 private function mergeChangesIntoContent( &$editContent ) {
2311 $db = wfGetDB( DB_MASTER );
2312
2313 // This is the revision the editor started from
2314 $baseRevision = $this->getBaseRevision();
2315 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2316
2317 if ( is_null( $baseContent ) ) {
2318 return false;
2319 }
2320
2321 // The current state, we want to merge updates into it
2322 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2323 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2324
2325 if ( is_null( $currentContent ) ) {
2326 return false;
2327 }
2328
2329 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2330
2331 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2332
2333 if ( $result ) {
2334 $editContent = $result;
2335 // Update parentRevId to what we just merged.
2336 $this->parentRevId = $currentRevision->getId();
2337 return true;
2338 }
2339
2340 return false;
2341 }
2342
2343 /**
2344 * @note: this method is very poorly named. If the user opened the form with ?oldid=X,
2345 * one might think of X as the "base revision", which is NOT what this returns.
2346 * @return Revision|null Current version when the edit was started
2347 */
2348 public function getBaseRevision() {
2349 if ( !$this->mBaseRevision ) {
2350 $db = wfGetDB( DB_MASTER );
2351 $this->mBaseRevision = $this->editRevId
2352 ? Revision::newFromId( $this->editRevId, Revision::READ_LATEST )
2353 : Revision::loadFromTimestamp( $db, $this->mTitle, $this->edittime );
2354 }
2355 return $this->mBaseRevision;
2356 }
2357
2358 /**
2359 * Check given input text against $wgSpamRegex, and return the text of the first match.
2360 *
2361 * @param string $text
2362 *
2363 * @return string|bool Matching string or false
2364 */
2365 public static function matchSpamRegex( $text ) {
2366 global $wgSpamRegex;
2367 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2368 $regexes = (array)$wgSpamRegex;
2369 return self::matchSpamRegexInternal( $text, $regexes );
2370 }
2371
2372 /**
2373 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2374 *
2375 * @param string $text
2376 *
2377 * @return string|bool Matching string or false
2378 */
2379 public static function matchSummarySpamRegex( $text ) {
2380 global $wgSummarySpamRegex;
2381 $regexes = (array)$wgSummarySpamRegex;
2382 return self::matchSpamRegexInternal( $text, $regexes );
2383 }
2384
2385 /**
2386 * @param string $text
2387 * @param array $regexes
2388 * @return bool|string
2389 */
2390 protected static function matchSpamRegexInternal( $text, $regexes ) {
2391 foreach ( $regexes as $regex ) {
2392 $matches = [];
2393 if ( preg_match( $regex, $text, $matches ) ) {
2394 return $matches[0];
2395 }
2396 }
2397 return false;
2398 }
2399
2400 public function setHeaders() {
2401 $out = $this->context->getOutput();
2402
2403 $out->addModules( 'mediawiki.action.edit' );
2404 $out->addModuleStyles( 'mediawiki.action.edit.styles' );
2405 $out->addModuleStyles( 'mediawiki.editfont.styles' );
2406
2407 $user = $this->context->getUser();
2408 if ( $user->getOption( 'showtoolbar' ) ) {
2409 // The addition of default buttons is handled by getEditToolbar() which
2410 // has its own dependency on this module. The call here ensures the module
2411 // is loaded in time (it has position "top") for other modules to register
2412 // buttons (e.g. extensions, gadgets, user scripts).
2413 $out->addModules( 'mediawiki.toolbar' );
2414 }
2415
2416 if ( $user->getOption( 'uselivepreview' ) ) {
2417 $out->addModules( 'mediawiki.action.edit.preview' );
2418 }
2419
2420 if ( $user->getOption( 'useeditwarning' ) ) {
2421 $out->addModules( 'mediawiki.action.edit.editWarning' );
2422 }
2423
2424 # Enabled article-related sidebar, toplinks, etc.
2425 $out->setArticleRelated( true );
2426
2427 $contextTitle = $this->getContextTitle();
2428 if ( $this->isConflict ) {
2429 $msg = 'editconflict';
2430 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2431 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2432 } else {
2433 $msg = $contextTitle->exists()
2434 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2435 && $contextTitle->getDefaultMessageText() !== false
2436 )
2437 ? 'editing'
2438 : 'creating';
2439 }
2440
2441 # Use the title defined by DISPLAYTITLE magic word when present
2442 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2443 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2444 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2445 if ( $displayTitle === false ) {
2446 $displayTitle = $contextTitle->getPrefixedText();
2447 }
2448 $out->setPageTitle( $this->context->msg( $msg, $displayTitle ) );
2449
2450 $config = $this->context->getConfig();
2451
2452 # Transmit the name of the message to JavaScript for live preview
2453 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2454 $out->addJsConfigVars( [
2455 'wgEditMessage' => $msg,
2456 'wgAjaxEditStash' => $config->get( 'AjaxEditStash' ),
2457 ] );
2458
2459 // Add whether to use 'save' or 'publish' messages to JavaScript for post-edit, other
2460 // editors, etc.
2461 $out->addJsConfigVars(
2462 'wgEditSubmitButtonLabelPublish',
2463 $config->get( 'EditSubmitButtonLabelPublish' )
2464 );
2465 }
2466
2467 /**
2468 * Show all applicable editing introductions
2469 */
2470 protected function showIntro() {
2471 if ( $this->suppressIntro ) {
2472 return;
2473 }
2474
2475 $out = $this->context->getOutput();
2476 $namespace = $this->mTitle->getNamespace();
2477
2478 if ( $namespace == NS_MEDIAWIKI ) {
2479 # Show a warning if editing an interface message
2480 $out->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2481 # If this is a default message (but not css, json, or js),
2482 # show a hint that it is translatable on translatewiki.net
2483 if (
2484 !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2485 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JSON )
2486 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2487 ) {
2488 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2489 if ( $defaultMessageText !== false ) {
2490 $out->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2491 'translateinterface' );
2492 }
2493 }
2494 } elseif ( $namespace == NS_FILE ) {
2495 # Show a hint to shared repo
2496 $file = wfFindFile( $this->mTitle );
2497 if ( $file && !$file->isLocal() ) {
2498 $descUrl = $file->getDescriptionUrl();
2499 # there must be a description url to show a hint to shared repo
2500 if ( $descUrl ) {
2501 if ( !$this->mTitle->exists() ) {
2502 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", [
2503 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2504 ] );
2505 } else {
2506 $out->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", [
2507 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2508 ] );
2509 }
2510 }
2511 }
2512 }
2513
2514 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2515 # Show log extract when the user is currently blocked
2516 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2517 $username = explode( '/', $this->mTitle->getText(), 2 )[0];
2518 $user = User::newFromName( $username, false /* allow IP users */ );
2519 $ip = User::isIP( $username );
2520 $block = Block::newFromTarget( $user, $user );
2521 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2522 $out->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2523 [ 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ] );
2524 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2525 # Show log extract if the user is currently blocked
2526 LogEventsList::showLogExtract(
2527 $out,
2528 'block',
2529 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2530 '',
2531 [
2532 'lim' => 1,
2533 'showIfEmpty' => false,
2534 'msgKey' => [
2535 'blocked-notice-logextract',
2536 $user->getName() # Support GENDER in notice
2537 ]
2538 ]
2539 );
2540 }
2541 }
2542 # Try to add a custom edit intro, or use the standard one if this is not possible.
2543 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2544 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2545 $this->context->msg( 'helppage' )->inContentLanguage()->text()
2546 ) );
2547 if ( $this->context->getUser()->isLoggedIn() ) {
2548 $out->wrapWikiMsg(
2549 // Suppress the external link icon, consider the help url an internal one
2550 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2551 [
2552 'newarticletext',
2553 $helpLink
2554 ]
2555 );
2556 } else {
2557 $out->wrapWikiMsg(
2558 // Suppress the external link icon, consider the help url an internal one
2559 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2560 [
2561 'newarticletextanon',
2562 $helpLink
2563 ]
2564 );
2565 }
2566 }
2567 # Give a notice if the user is editing a deleted/moved page...
2568 if ( !$this->mTitle->exists() ) {
2569 $dbr = wfGetDB( DB_REPLICA );
2570
2571 LogEventsList::showLogExtract( $out, [ 'delete', 'move' ], $this->mTitle,
2572 '',
2573 [
2574 'lim' => 10,
2575 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
2576 'showIfEmpty' => false,
2577 'msgKey' => [ 'recreate-moveddeleted-warn' ]
2578 ]
2579 );
2580 }
2581 }
2582
2583 /**
2584 * Attempt to show a custom editing introduction, if supplied
2585 *
2586 * @return bool
2587 */
2588 protected function showCustomIntro() {
2589 if ( $this->editintro ) {
2590 $title = Title::newFromText( $this->editintro );
2591 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2592 // Added using template syntax, to take <noinclude>'s into account.
2593 $this->context->getOutput()->addWikiTextTitleTidy(
2594 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2595 $this->mTitle
2596 );
2597 return true;
2598 }
2599 }
2600 return false;
2601 }
2602
2603 /**
2604 * Gets an editable textual representation of $content.
2605 * The textual representation can be turned by into a Content object by the
2606 * toEditContent() method.
2607 *
2608 * If $content is null or false or a string, $content is returned unchanged.
2609 *
2610 * If the given Content object is not of a type that can be edited using
2611 * the text base EditPage, an exception will be raised. Set
2612 * $this->allowNonTextContent to true to allow editing of non-textual
2613 * content.
2614 *
2615 * @param Content|null|bool|string $content
2616 * @return string The editable text form of the content.
2617 *
2618 * @throws MWException If $content is not an instance of TextContent and
2619 * $this->allowNonTextContent is not true.
2620 */
2621 protected function toEditText( $content ) {
2622 if ( $content === null || $content === false || is_string( $content ) ) {
2623 return $content;
2624 }
2625
2626 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2627 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2628 }
2629
2630 return $content->serialize( $this->contentFormat );
2631 }
2632
2633 /**
2634 * Turns the given text into a Content object by unserializing it.
2635 *
2636 * If the resulting Content object is not of a type that can be edited using
2637 * the text base EditPage, an exception will be raised. Set
2638 * $this->allowNonTextContent to true to allow editing of non-textual
2639 * content.
2640 *
2641 * @param string|null|bool $text Text to unserialize
2642 * @return Content|bool|null The content object created from $text. If $text was false
2643 * or null, false resp. null will be returned instead.
2644 *
2645 * @throws MWException If unserializing the text results in a Content
2646 * object that is not an instance of TextContent and
2647 * $this->allowNonTextContent is not true.
2648 */
2649 protected function toEditContent( $text ) {
2650 if ( $text === false || $text === null ) {
2651 return $text;
2652 }
2653
2654 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2655 $this->contentModel, $this->contentFormat );
2656
2657 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2658 throw new MWException( 'This content model is not supported: ' . $content->getModel() );
2659 }
2660
2661 return $content;
2662 }
2663
2664 /**
2665 * Send the edit form and related headers to OutputPage
2666 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2667 * during form output near the top, for captchas and the like.
2668 *
2669 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2670 * use the EditPage::showEditForm:fields hook instead.
2671 */
2672 public function showEditForm( $formCallback = null ) {
2673 # need to parse the preview early so that we know which templates are used,
2674 # otherwise users with "show preview after edit box" will get a blank list
2675 # we parse this near the beginning so that setHeaders can do the title
2676 # setting work instead of leaving it in getPreviewText
2677 $previewOutput = '';
2678 if ( $this->formtype == 'preview' ) {
2679 $previewOutput = $this->getPreviewText();
2680 }
2681
2682 $out = $this->context->getOutput();
2683
2684 // Avoid PHP 7.1 warning of passing $this by reference
2685 $editPage = $this;
2686 Hooks::run( 'EditPage::showEditForm:initial', [ &$editPage, &$out ] );
2687
2688 $this->setHeaders();
2689
2690 $this->addTalkPageText();
2691 $this->addEditNotices();
2692
2693 if ( !$this->isConflict &&
2694 $this->section != '' &&
2695 !$this->isSectionEditSupported() ) {
2696 // We use $this->section to much before this and getVal('wgSection') directly in other places
2697 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2698 // Someone is welcome to try refactoring though
2699 $out->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2700 return;
2701 }
2702
2703 $this->showHeader();
2704
2705 $out->addHTML( $this->editFormPageTop );
2706
2707 $user = $this->context->getUser();
2708 if ( $user->getOption( 'previewontop' ) ) {
2709 $this->displayPreviewArea( $previewOutput, true );
2710 }
2711
2712 $out->addHTML( $this->editFormTextTop );
2713
2714 $showToolbar = true;
2715 if ( $this->wasDeletedSinceLastEdit() ) {
2716 if ( $this->formtype == 'save' ) {
2717 // Hide the toolbar and edit area, user can click preview to get it back
2718 // Add an confirmation checkbox and explanation.
2719 $showToolbar = false;
2720 } else {
2721 $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2722 'deletedwhileediting' );
2723 }
2724 }
2725
2726 // @todo add EditForm plugin interface and use it here!
2727 // search for textarea1 and textarea2, and allow EditForm to override all uses.
2728 $out->addHTML( Html::openElement(
2729 'form',
2730 [
2731 'class' => 'mw-editform',
2732 'id' => self::EDITFORM_ID,
2733 'name' => self::EDITFORM_ID,
2734 'method' => 'post',
2735 'action' => $this->getActionURL( $this->getContextTitle() ),
2736 'enctype' => 'multipart/form-data'
2737 ]
2738 ) );
2739
2740 if ( is_callable( $formCallback ) ) {
2741 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2742 call_user_func_array( $formCallback, [ &$out ] );
2743 }
2744
2745 // Add a check for Unicode support
2746 $out->addHTML( Html::hidden( 'wpUnicodeCheck', self::UNICODE_CHECK ) );
2747
2748 // Add an empty field to trip up spambots
2749 $out->addHTML(
2750 Xml::openElement( 'div', [ 'id' => 'antispam-container', 'style' => 'display: none;' ] )
2751 . Html::rawElement(
2752 'label',
2753 [ 'for' => 'wpAntispam' ],
2754 $this->context->msg( 'simpleantispam-label' )->parse()
2755 )
2756 . Xml::element(
2757 'input',
2758 [
2759 'type' => 'text',
2760 'name' => 'wpAntispam',
2761 'id' => 'wpAntispam',
2762 'value' => ''
2763 ]
2764 )
2765 . Xml::closeElement( 'div' )
2766 );
2767
2768 // Avoid PHP 7.1 warning of passing $this by reference
2769 $editPage = $this;
2770 Hooks::run( 'EditPage::showEditForm:fields', [ &$editPage, &$out ] );
2771
2772 // Put these up at the top to ensure they aren't lost on early form submission
2773 $this->showFormBeforeText();
2774
2775 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2776 $username = $this->lastDelete->user_name;
2777 $comment = CommentStore::getStore()
2778 ->getComment( 'log_comment', $this->lastDelete )->text;
2779
2780 // It is better to not parse the comment at all than to have templates expanded in the middle
2781 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2782 $key = $comment === ''
2783 ? 'confirmrecreate-noreason'
2784 : 'confirmrecreate';
2785 $out->addHTML(
2786 '<div class="mw-confirm-recreate">' .
2787 $this->context->msg( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2788 Xml::checkLabel( $this->context->msg( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2789 [ 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' ]
2790 ) .
2791 '</div>'
2792 );
2793 }
2794
2795 # When the summary is hidden, also hide them on preview/show changes
2796 if ( $this->nosummary ) {
2797 $out->addHTML( Html::hidden( 'nosummary', true ) );
2798 }
2799
2800 # If a blank edit summary was previously provided, and the appropriate
2801 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2802 # user being bounced back more than once in the event that a summary
2803 # is not required.
2804 # ####
2805 # For a bit more sophisticated detection of blank summaries, hash the
2806 # automatic one and pass that in the hidden field wpAutoSummary.
2807 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2808 $out->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2809 }
2810
2811 if ( $this->undidRev ) {
2812 $out->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2813 }
2814
2815 if ( $this->selfRedirect ) {
2816 $out->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2817 }
2818
2819 if ( $this->hasPresetSummary ) {
2820 // If a summary has been preset using &summary= we don't want to prompt for
2821 // a different summary. Only prompt for a summary if the summary is blanked.
2822 // (T19416)
2823 $this->autoSumm = md5( '' );
2824 }
2825
2826 $autosumm = $this->autoSumm ?: md5( $this->summary );
2827 $out->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2828
2829 $out->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2830 $out->addHTML( Html::hidden( 'parentRevId', $this->getParentRevId() ) );
2831
2832 $out->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2833 $out->addHTML( Html::hidden( 'model', $this->contentModel ) );
2834
2835 $out->enableOOUI();
2836
2837 if ( $this->section == 'new' ) {
2838 $this->showSummaryInput( true, $this->summary );
2839 $out->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2840 }
2841
2842 $out->addHTML( $this->editFormTextBeforeContent );
2843 if ( $this->isConflict ) {
2844 // In an edit conflict, we turn textbox2 into the user's text,
2845 // and textbox1 into the stored version
2846 $this->textbox2 = $this->textbox1;
2847
2848 $content = $this->getCurrentContent();
2849 $this->textbox1 = $this->toEditText( $content );
2850
2851 $editConflictHelper = $this->getEditConflictHelper();
2852 $editConflictHelper->setTextboxes( $this->textbox2, $this->textbox1 );
2853 $editConflictHelper->setContentModel( $this->contentModel );
2854 $editConflictHelper->setContentFormat( $this->contentFormat );
2855 $out->addHTML( $editConflictHelper->getEditFormHtmlBeforeContent() );
2856 }
2857
2858 if ( !$this->mTitle->isUserConfigPage() && $showToolbar && $user->getOption( 'showtoolbar' ) ) {
2859 $out->addHTML( self::getEditToolbar( $this->mTitle ) );
2860 }
2861
2862 if ( $this->blankArticle ) {
2863 $out->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2864 }
2865
2866 if ( $this->isConflict ) {
2867 // In an edit conflict bypass the overridable content form method
2868 // and fallback to the raw wpTextbox1 since editconflicts can't be
2869 // resolved between page source edits and custom ui edits using the
2870 // custom edit ui.
2871 $conflictTextBoxAttribs = [];
2872 if ( $this->wasDeletedSinceLastEdit() ) {
2873 $conflictTextBoxAttribs['style'] = 'display:none;';
2874 } elseif ( $this->isOldRev ) {
2875 $conflictTextBoxAttribs['class'] = 'mw-textarea-oldrev';
2876 }
2877
2878 $out->addHTML( $editConflictHelper->getEditConflictMainTextBox( $conflictTextBoxAttribs ) );
2879 $out->addHTML( $editConflictHelper->getEditFormHtmlAfterContent() );
2880 } else {
2881 $this->showContentForm();
2882 }
2883
2884 $out->addHTML( $this->editFormTextAfterContent );
2885
2886 $this->showStandardInputs();
2887
2888 $this->showFormAfterText();
2889
2890 $this->showTosSummary();
2891
2892 $this->showEditTools();
2893
2894 $out->addHTML( $this->editFormTextAfterTools . "\n" );
2895
2896 $out->addHTML( $this->makeTemplatesOnThisPageList( $this->getTemplates() ) );
2897
2898 $out->addHTML( Html::rawElement( 'div', [ 'class' => 'hiddencats' ],
2899 Linker::formatHiddenCategories( $this->page->getHiddenCategories() ) ) );
2900
2901 $out->addHTML( Html::rawElement( 'div', [ 'class' => 'limitreport' ],
2902 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2903
2904 $out->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2905
2906 if ( $this->isConflict ) {
2907 try {
2908 $this->showConflict();
2909 } catch ( MWContentSerializationException $ex ) {
2910 // this can't really happen, but be nice if it does.
2911 $msg = $this->context->msg(
2912 'content-failed-to-parse',
2913 $this->contentModel,
2914 $this->contentFormat,
2915 $ex->getMessage()
2916 );
2917 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2918 }
2919 }
2920
2921 // Set a hidden field so JS knows what edit form mode we are in
2922 if ( $this->isConflict ) {
2923 $mode = 'conflict';
2924 } elseif ( $this->preview ) {
2925 $mode = 'preview';
2926 } elseif ( $this->diff ) {
2927 $mode = 'diff';
2928 } else {
2929 $mode = 'text';
2930 }
2931 $out->addHTML( Html::hidden( 'mode', $mode, [ 'id' => 'mw-edit-mode' ] ) );
2932
2933 // Marker for detecting truncated form data. This must be the last
2934 // parameter sent in order to be of use, so do not move me.
2935 $out->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2936 $out->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2937
2938 if ( !$user->getOption( 'previewontop' ) ) {
2939 $this->displayPreviewArea( $previewOutput, false );
2940 }
2941 }
2942
2943 /**
2944 * Wrapper around TemplatesOnThisPageFormatter to make
2945 * a "templates on this page" list.
2946 *
2947 * @param Title[] $templates
2948 * @return string HTML
2949 */
2950 public function makeTemplatesOnThisPageList( array $templates ) {
2951 $templateListFormatter = new TemplatesOnThisPageFormatter(
2952 $this->context, MediaWikiServices::getInstance()->getLinkRenderer()
2953 );
2954
2955 // preview if preview, else section if section, else false
2956 $type = false;
2957 if ( $this->preview ) {
2958 $type = 'preview';
2959 } elseif ( $this->section != '' ) {
2960 $type = 'section';
2961 }
2962
2963 return Html::rawElement( 'div', [ 'class' => 'templatesUsed' ],
2964 $templateListFormatter->format( $templates, $type )
2965 );
2966 }
2967
2968 /**
2969 * Extract the section title from current section text, if any.
2970 *
2971 * @param string $text
2972 * @return string|bool String or false
2973 */
2974 public static function extractSectionTitle( $text ) {
2975 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2976 if ( !empty( $matches[2] ) ) {
2977 global $wgParser;
2978 return $wgParser->stripSectionName( trim( $matches[2] ) );
2979 } else {
2980 return false;
2981 }
2982 }
2983
2984 protected function showHeader() {
2985 $out = $this->context->getOutput();
2986 $user = $this->context->getUser();
2987 if ( $this->isConflict ) {
2988 $this->addExplainConflictHeader( $out );
2989 $this->editRevId = $this->page->getLatest();
2990 } else {
2991 if ( $this->section != '' && $this->section != 'new' ) {
2992 if ( !$this->summary && !$this->preview && !$this->diff ) {
2993 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
2994 if ( $sectionTitle !== false ) {
2995 $this->summary = "/* $sectionTitle */ ";
2996 }
2997 }
2998 }
2999
3000 $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
3001
3002 if ( $this->missingComment ) {
3003 $out->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
3004 }
3005
3006 if ( $this->missingSummary && $this->section != 'new' ) {
3007 $out->wrapWikiMsg(
3008 "<div id='mw-missingsummary'>\n$1\n</div>",
3009 [ 'missingsummary', $buttonLabel ]
3010 );
3011 }
3012
3013 if ( $this->missingSummary && $this->section == 'new' ) {
3014 $out->wrapWikiMsg(
3015 "<div id='mw-missingcommentheader'>\n$1\n</div>",
3016 [ 'missingcommentheader', $buttonLabel ]
3017 );
3018 }
3019
3020 if ( $this->blankArticle ) {
3021 $out->wrapWikiMsg(
3022 "<div id='mw-blankarticle'>\n$1\n</div>",
3023 [ 'blankarticle', $buttonLabel ]
3024 );
3025 }
3026
3027 if ( $this->selfRedirect ) {
3028 $out->wrapWikiMsg(
3029 "<div id='mw-selfredirect'>\n$1\n</div>",
3030 [ 'selfredirect', $buttonLabel ]
3031 );
3032 }
3033
3034 if ( $this->hookError !== '' ) {
3035 $out->addWikiText( $this->hookError );
3036 }
3037
3038 if ( $this->section != 'new' ) {
3039 $revision = $this->mArticle->getRevisionFetched();
3040 if ( $revision ) {
3041 // Let sysop know that this will make private content public if saved
3042
3043 if ( !$revision->userCan( Revision::DELETED_TEXT, $user ) ) {
3044 $out->wrapWikiMsg(
3045 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3046 'rev-deleted-text-permission'
3047 );
3048 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
3049 $out->wrapWikiMsg(
3050 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
3051 'rev-deleted-text-view'
3052 );
3053 }
3054
3055 if ( !$revision->isCurrent() ) {
3056 $this->mArticle->setOldSubtitle( $revision->getId() );
3057 $out->addWikiMsg( 'editingold' );
3058 $this->isOldRev = true;
3059 }
3060 } elseif ( $this->mTitle->exists() ) {
3061 // Something went wrong
3062
3063 $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
3064 [ 'missing-revision', $this->oldid ] );
3065 }
3066 }
3067 }
3068
3069 if ( wfReadOnly() ) {
3070 $out->wrapWikiMsg(
3071 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
3072 [ 'readonlywarning', wfReadOnlyReason() ]
3073 );
3074 } elseif ( $user->isAnon() ) {
3075 if ( $this->formtype != 'preview' ) {
3076 $out->wrapWikiMsg(
3077 "<div id='mw-anon-edit-warning' class='warningbox'>\n$1\n</div>",
3078 [ 'anoneditwarning',
3079 // Log-in link
3080 SpecialPage::getTitleFor( 'Userlogin' )->getFullURL( [
3081 'returnto' => $this->getTitle()->getPrefixedDBkey()
3082 ] ),
3083 // Sign-up link
3084 SpecialPage::getTitleFor( 'CreateAccount' )->getFullURL( [
3085 'returnto' => $this->getTitle()->getPrefixedDBkey()
3086 ] )
3087 ]
3088 );
3089 } else {
3090 $out->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\" class=\"warningbox\">\n$1</div>",
3091 'anonpreviewwarning'
3092 );
3093 }
3094 } else {
3095 if ( $this->mTitle->isUserConfigPage() ) {
3096 # Check the skin exists
3097 if ( $this->isWrongCaseUserConfigPage() ) {
3098 $out->wrapWikiMsg(
3099 "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
3100 [ 'userinvalidconfigtitle', $this->mTitle->getSkinFromConfigSubpage() ]
3101 );
3102 }
3103 if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
3104 $isUserCssConfig = $this->mTitle->isUserCssConfigPage();
3105 $isUserJsonConfig = $this->mTitle->isUserJsonConfigPage();
3106 $isUserJsConfig = $this->mTitle->isUserJsConfigPage();
3107
3108 $warning = $isUserCssConfig
3109 ? 'usercssispublic'
3110 : ( $isUserJsonConfig ? 'userjsonispublic' : 'userjsispublic' );
3111
3112 $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
3113
3114 if ( $this->formtype !== 'preview' ) {
3115 $config = $this->context->getConfig();
3116 if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
3117 $out->wrapWikiMsg(
3118 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
3119 [ 'usercssyoucanpreview' ]
3120 );
3121 } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
3122 $out->wrapWikiMsg(
3123 "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
3124 [ 'userjsonyoucanpreview' ]
3125 );
3126 } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
3127 $out->wrapWikiMsg(
3128 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
3129 [ 'userjsyoucanpreview' ]
3130 );
3131 }
3132 }
3133 }
3134 }
3135 }
3136
3137 $this->addPageProtectionWarningHeaders();
3138
3139 $this->addLongPageWarningHeader();
3140
3141 # Add header copyright warning
3142 $this->showHeaderCopyrightWarning();
3143 }
3144
3145 /**
3146 * Helper function for summary input functions, which returns the neccessary
3147 * attributes for the input.
3148 *
3149 * @param array|null $inputAttrs Array of attrs to use on the input
3150 * @return array
3151 */
3152 private function getSummaryInputAttributes( array $inputAttrs = null ) {
3153 $conf = $this->context->getConfig();
3154 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD;
3155 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
3156 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
3157 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
3158 return ( is_array( $inputAttrs ) ? $inputAttrs : [] ) + [
3159 'id' => 'wpSummary',
3160 'name' => 'wpSummary',
3161 'maxlength' => $oldCommentSchema ? 200 : CommentStore::COMMENT_CHARACTER_LIMIT,
3162 'tabindex' => 1,
3163 'size' => 60,
3164 'spellcheck' => 'true',
3165 ];
3166 }
3167
3168 /**
3169 * Builds a standard summary input with a label.
3170 *
3171 * @param string $summary The value of the summary input
3172 * @param string $labelText The html to place inside the label
3173 * @param array $inputAttrs Array of attrs to use on the input
3174 *
3175 * @return OOUI\FieldLayout OOUI FieldLayout with Label and Input
3176 */
3177 function getSummaryInputWidget( $summary = "", $labelText = null, $inputAttrs = null ) {
3178 $inputAttrs = OOUI\Element::configFromHtmlAttributes(
3179 $this->getSummaryInputAttributes( $inputAttrs )
3180 );
3181 $inputAttrs += [
3182 'title' => Linker::titleAttrib( 'summary' ),
3183 'accessKey' => Linker::accesskey( 'summary' ),
3184 ];
3185
3186 // For compatibility with old scripts and extensions, we want the legacy 'id' on the `<input>`
3187 $inputAttrs['inputId'] = $inputAttrs['id'];
3188 $inputAttrs['id'] = 'wpSummaryWidget';
3189
3190 return new OOUI\FieldLayout(
3191 new OOUI\TextInputWidget( [
3192 'value' => $summary,
3193 'infusable' => true,
3194 ] + $inputAttrs ),
3195 [
3196 'label' => new OOUI\HtmlSnippet( $labelText ),
3197 'align' => 'top',
3198 'id' => 'wpSummaryLabel',
3199 'classes' => [ $this->missingSummary ? 'mw-summarymissed' : 'mw-summary' ],
3200 ]
3201 );
3202 }
3203
3204 /**
3205 * @param bool $isSubjectPreview True if this is the section subject/title
3206 * up top, or false if this is the comment summary
3207 * down below the textarea
3208 * @param string $summary The text of the summary to display
3209 */
3210 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
3211 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
3212 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
3213 if ( $isSubjectPreview ) {
3214 if ( $this->nosummary ) {
3215 return;
3216 }
3217 } else {
3218 if ( !$this->mShowSummaryField ) {
3219 return;
3220 }
3221 }
3222
3223 $labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse();
3224 $this->context->getOutput()->addHTML( $this->getSummaryInputWidget(
3225 $summary,
3226 $labelText,
3227 [ 'class' => $summaryClass ]
3228 ) );
3229 }
3230
3231 /**
3232 * @param bool $isSubjectPreview True if this is the section subject/title
3233 * up top, or false if this is the comment summary
3234 * down below the textarea
3235 * @param string $summary The text of the summary to display
3236 * @return string
3237 */
3238 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
3239 // avoid spaces in preview, gets always trimmed on save
3240 $summary = trim( $summary );
3241 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
3242 return "";
3243 }
3244
3245 global $wgParser;
3246
3247 if ( $isSubjectPreview ) {
3248 $summary = $this->context->msg( 'newsectionsummary' )
3249 ->rawParams( $wgParser->stripSectionName( $summary ) )
3250 ->inContentLanguage()->text();
3251 }
3252
3253 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
3254
3255 $summary = $this->context->msg( $message )->parse()
3256 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
3257 return Xml::tags( 'div', [ 'class' => 'mw-summary-preview' ], $summary );
3258 }
3259
3260 protected function showFormBeforeText() {
3261 $out = $this->context->getOutput();
3262 $out->addHTML( Html::hidden( 'wpSection', $this->section ) );
3263 $out->addHTML( Html::hidden( 'wpStarttime', $this->starttime ) );
3264 $out->addHTML( Html::hidden( 'wpEdittime', $this->edittime ) );
3265 $out->addHTML( Html::hidden( 'editRevId', $this->editRevId ) );
3266 $out->addHTML( Html::hidden( 'wpScrolltop', $this->scrolltop, [ 'id' => 'wpScrolltop' ] ) );
3267 }
3268
3269 protected function showFormAfterText() {
3270 /**
3271 * To make it harder for someone to slip a user a page
3272 * which submits an edit form to the wiki without their
3273 * knowledge, a random token is associated with the login
3274 * session. If it's not passed back with the submission,
3275 * we won't save the page, or render user JavaScript and
3276 * CSS previews.
3277 *
3278 * For anon editors, who may not have a session, we just
3279 * include the constant suffix to prevent editing from
3280 * broken text-mangling proxies.
3281 */
3282 $this->context->getOutput()->addHTML(
3283 "\n" .
3284 Html::hidden( "wpEditToken", $this->context->getUser()->getEditToken() ) .
3285 "\n"
3286 );
3287 }
3288
3289 /**
3290 * Subpage overridable method for printing the form for page content editing
3291 * By default this simply outputs wpTextbox1
3292 * Subclasses can override this to provide a custom UI for editing;
3293 * be it a form, or simply wpTextbox1 with a modified content that will be
3294 * reverse modified when extracted from the post data.
3295 * Note that this is basically the inverse for importContentFormData
3296 */
3297 protected function showContentForm() {
3298 $this->showTextbox1();
3299 }
3300
3301 /**
3302 * Method to output wpTextbox1
3303 * The $textoverride method can be used by subclasses overriding showContentForm
3304 * to pass back to this method.
3305 *
3306 * @param array $customAttribs Array of html attributes to use in the textarea
3307 * @param string $textoverride Optional text to override $this->textarea1 with
3308 */
3309 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3310 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
3311 $attribs = [ 'style' => 'display:none;' ];
3312 } else {
3313 $builder = new TextboxBuilder();
3314 $classes = $builder->getTextboxProtectionCSSClasses( $this->getTitle() );
3315
3316 # Is an old revision being edited?
3317 if ( $this->isOldRev ) {
3318 $classes[] = 'mw-textarea-oldrev';
3319 }
3320
3321 $attribs = [ 'tabindex' => 1 ];
3322
3323 if ( is_array( $customAttribs ) ) {
3324 $attribs += $customAttribs;
3325 }
3326
3327 $attribs = $builder->mergeClassesIntoAttributes( $classes, $attribs );
3328 }
3329
3330 $this->showTextbox(
3331 $textoverride !== null ? $textoverride : $this->textbox1,
3332 'wpTextbox1',
3333 $attribs
3334 );
3335 }
3336
3337 protected function showTextbox2() {
3338 $this->showTextbox( $this->textbox2, 'wpTextbox2', [ 'tabindex' => 6, 'readonly' ] );
3339 }
3340
3341 protected function showTextbox( $text, $name, $customAttribs = [] ) {
3342 $builder = new TextboxBuilder();
3343 $attribs = $builder->buildTextboxAttribs(
3344 $name,
3345 $customAttribs,
3346 $this->context->getUser(),
3347 $this->mTitle
3348 );
3349
3350 $this->context->getOutput()->addHTML(
3351 Html::textarea( $name, $builder->addNewLineAtEnd( $text ), $attribs )
3352 );
3353 }
3354
3355 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3356 $classes = [];
3357 if ( $isOnTop ) {
3358 $classes[] = 'ontop';
3359 }
3360
3361 $attribs = [ 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) ];
3362
3363 if ( $this->formtype != 'preview' ) {
3364 $attribs['style'] = 'display: none;';
3365 }
3366
3367 $out = $this->context->getOutput();
3368 $out->addHTML( Xml::openElement( 'div', $attribs ) );
3369
3370 if ( $this->formtype == 'preview' ) {
3371 $this->showPreview( $previewOutput );
3372 } else {
3373 // Empty content container for LivePreview
3374 $pageViewLang = $this->mTitle->getPageViewLanguage();
3375 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3376 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3377 $out->addHTML( Html::rawElement( 'div', $attribs ) );
3378 }
3379
3380 $out->addHTML( '</div>' );
3381
3382 if ( $this->formtype == 'diff' ) {
3383 try {
3384 $this->showDiff();
3385 } catch ( MWContentSerializationException $ex ) {
3386 $msg = $this->context->msg(
3387 'content-failed-to-parse',
3388 $this->contentModel,
3389 $this->contentFormat,
3390 $ex->getMessage()
3391 );
3392 $out->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3393 }
3394 }
3395 }
3396
3397 /**
3398 * Append preview output to OutputPage.
3399 * Includes category rendering if this is a category page.
3400 *
3401 * @param string $text The HTML to be output for the preview.
3402 */
3403 protected function showPreview( $text ) {
3404 if ( $this->mArticle instanceof CategoryPage ) {
3405 $this->mArticle->openShowCategory();
3406 }
3407 # This hook seems slightly odd here, but makes things more
3408 # consistent for extensions.
3409 $out = $this->context->getOutput();
3410 Hooks::run( 'OutputPageBeforeHTML', [ &$out, &$text ] );
3411 $out->addHTML( $text );
3412 if ( $this->mArticle instanceof CategoryPage ) {
3413 $this->mArticle->closeShowCategory();
3414 }
3415 }
3416
3417 /**
3418 * Get a diff between the current contents of the edit box and the
3419 * version of the page we're editing from.
3420 *
3421 * If this is a section edit, we'll replace the section as for final
3422 * save and then make a comparison.
3423 */
3424 public function showDiff() {
3425 global $wgContLang;
3426
3427 $oldtitlemsg = 'currentrev';
3428 # if message does not exist, show diff against the preloaded default
3429 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3430 $oldtext = $this->mTitle->getDefaultMessageText();
3431 if ( $oldtext !== false ) {
3432 $oldtitlemsg = 'defaultmessagetext';
3433 $oldContent = $this->toEditContent( $oldtext );
3434 } else {
3435 $oldContent = null;
3436 }
3437 } else {
3438 $oldContent = $this->getCurrentContent();
3439 }
3440
3441 $textboxContent = $this->toEditContent( $this->textbox1 );
3442 if ( $this->editRevId !== null ) {
3443 $newContent = $this->page->replaceSectionAtRev(
3444 $this->section, $textboxContent, $this->summary, $this->editRevId
3445 );
3446 } else {
3447 $newContent = $this->page->replaceSectionContent(
3448 $this->section, $textboxContent, $this->summary, $this->edittime
3449 );
3450 }
3451
3452 if ( $newContent ) {
3453 Hooks::run( 'EditPageGetDiffContent', [ $this, &$newContent ] );
3454
3455 $user = $this->context->getUser();
3456 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
3457 $newContent = $newContent->preSaveTransform( $this->mTitle, $user, $popts );
3458 }
3459
3460 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3461 $oldtitle = $this->context->msg( $oldtitlemsg )->parse();
3462 $newtitle = $this->context->msg( 'yourtext' )->parse();
3463
3464 if ( !$oldContent ) {
3465 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3466 }
3467
3468 if ( !$newContent ) {
3469 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3470 }
3471
3472 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->context );
3473 $de->setContent( $oldContent, $newContent );
3474
3475 $difftext = $de->getDiff( $oldtitle, $newtitle );
3476 $de->showDiffStyle();
3477 } else {
3478 $difftext = '';
3479 }
3480
3481 $this->context->getOutput()->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3482 }
3483
3484 /**
3485 * Show the header copyright warning.
3486 */
3487 protected function showHeaderCopyrightWarning() {
3488 $msg = 'editpage-head-copy-warn';
3489 if ( !$this->context->msg( $msg )->isDisabled() ) {
3490 $this->context->getOutput()->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3491 'editpage-head-copy-warn' );
3492 }
3493 }
3494
3495 /**
3496 * Give a chance for site and per-namespace customizations of
3497 * terms of service summary link that might exist separately
3498 * from the copyright notice.
3499 *
3500 * This will display between the save button and the edit tools,
3501 * so should remain short!
3502 */
3503 protected function showTosSummary() {
3504 $msg = 'editpage-tos-summary';
3505 Hooks::run( 'EditPageTosSummary', [ $this->mTitle, &$msg ] );
3506 if ( !$this->context->msg( $msg )->isDisabled() ) {
3507 $out = $this->context->getOutput();
3508 $out->addHTML( '<div class="mw-tos-summary">' );
3509 $out->addWikiMsg( $msg );
3510 $out->addHTML( '</div>' );
3511 }
3512 }
3513
3514 /**
3515 * Inserts optional text shown below edit and upload forms. Can be used to offer special
3516 * characters not present on most keyboards for copying/pasting.
3517 */
3518 protected function showEditTools() {
3519 $this->context->getOutput()->addHTML( '<div class="mw-editTools">' .
3520 $this->context->msg( 'edittools' )->inContentLanguage()->parse() .
3521 '</div>' );
3522 }
3523
3524 /**
3525 * Get the copyright warning
3526 *
3527 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3528 * @return string
3529 */
3530 protected function getCopywarn() {
3531 return self::getCopyrightWarning( $this->mTitle );
3532 }
3533
3534 /**
3535 * Get the copyright warning, by default returns wikitext
3536 *
3537 * @param Title $title
3538 * @param string $format Output format, valid values are any function of a Message object
3539 * @param Language|string|null $langcode Language code or Language object.
3540 * @return string
3541 */
3542 public static function getCopyrightWarning( $title, $format = 'plain', $langcode = null ) {
3543 global $wgRightsText;
3544 if ( $wgRightsText ) {
3545 $copywarnMsg = [ 'copyrightwarning',
3546 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3547 $wgRightsText ];
3548 } else {
3549 $copywarnMsg = [ 'copyrightwarning2',
3550 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' ];
3551 }
3552 // Allow for site and per-namespace customization of contribution/copyright notice.
3553 Hooks::run( 'EditPageCopyrightWarning', [ $title, &$copywarnMsg ] );
3554
3555 $msg = wfMessage( ...$copywarnMsg )->title( $title );
3556 if ( $langcode ) {
3557 $msg->inLanguage( $langcode );
3558 }
3559 return "<div id=\"editpage-copywarn\">\n" .
3560 $msg->$format() . "\n</div>";
3561 }
3562
3563 /**
3564 * Get the Limit report for page previews
3565 *
3566 * @since 1.22
3567 * @param ParserOutput $output ParserOutput object from the parse
3568 * @return string HTML
3569 */
3570 public static function getPreviewLimitReport( $output ) {
3571 global $wgLang;
3572
3573 if ( !$output || !$output->getLimitReportData() ) {
3574 return '';
3575 }
3576
3577 $limitReport = Html::rawElement( 'div', [ 'class' => 'mw-limitReportExplanation' ],
3578 wfMessage( 'limitreport-title' )->parseAsBlock()
3579 );
3580
3581 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3582 $limitReport .= Html::openElement( 'div', [ 'class' => 'preview-limit-report-wrapper' ] );
3583
3584 $limitReport .= Html::openElement( 'table', [
3585 'class' => 'preview-limit-report wikitable'
3586 ] ) .
3587 Html::openElement( 'tbody' );
3588
3589 foreach ( $output->getLimitReportData() as $key => $value ) {
3590 if ( Hooks::run( 'ParserLimitReportFormat',
3591 [ $key, &$value, &$limitReport, true, true ]
3592 ) ) {
3593 $keyMsg = wfMessage( $key );
3594 $valueMsg = wfMessage( [ "$key-value-html", "$key-value" ] );
3595 if ( !$valueMsg->exists() ) {
3596 $valueMsg = new RawMessage( '$1' );
3597 }
3598 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3599 $limitReport .= Html::openElement( 'tr' ) .
3600 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3601 Html::rawElement( 'td', null,
3602 $wgLang->formatNum( $valueMsg->params( $value )->parse() )
3603 ) .
3604 Html::closeElement( 'tr' );
3605 }
3606 }
3607 }
3608
3609 $limitReport .= Html::closeElement( 'tbody' ) .
3610 Html::closeElement( 'table' ) .
3611 Html::closeElement( 'div' );
3612
3613 return $limitReport;
3614 }
3615
3616 protected function showStandardInputs( &$tabindex = 2 ) {
3617 $out = $this->context->getOutput();
3618 $out->addHTML( "<div class='editOptions'>\n" );
3619
3620 if ( $this->section != 'new' ) {
3621 $this->showSummaryInput( false, $this->summary );
3622 $out->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3623 }
3624
3625 $checkboxes = $this->getCheckboxesWidget(
3626 $tabindex,
3627 [ 'minor' => $this->minoredit, 'watch' => $this->watchthis ]
3628 );
3629 $checkboxesHTML = new OOUI\HorizontalLayout( [ 'items' => $checkboxes ] );
3630
3631 $out->addHTML( "<div class='editCheckboxes'>" . $checkboxesHTML . "</div>\n" );
3632
3633 // Show copyright warning.
3634 $out->addWikiText( $this->getCopywarn() );
3635 $out->addHTML( $this->editFormTextAfterWarn );
3636
3637 $out->addHTML( "<div class='editButtons'>\n" );
3638 $out->addHTML( implode( "\n", $this->getEditButtons( $tabindex ) ) . "\n" );
3639
3640 $cancel = $this->getCancelLink();
3641
3642 $message = $this->context->msg( 'edithelppage' )->inContentLanguage()->text();
3643 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3644 $edithelp =
3645 Html::linkButton(
3646 $this->context->msg( 'edithelp' )->text(),
3647 [ 'target' => 'helpwindow', 'href' => $edithelpurl ],
3648 [ 'mw-ui-quiet' ]
3649 ) .
3650 $this->context->msg( 'word-separator' )->escaped() .
3651 $this->context->msg( 'newwindow' )->parse();
3652
3653 $out->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3654 $out->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3655 $out->addHTML( "</div><!-- editButtons -->\n" );
3656
3657 Hooks::run( 'EditPage::showStandardInputs:options', [ $this, $out, &$tabindex ] );
3658
3659 $out->addHTML( "</div><!-- editOptions -->\n" );
3660 }
3661
3662 /**
3663 * Show an edit conflict. textbox1 is already shown in showEditForm().
3664 * If you want to use another entry point to this function, be careful.
3665 */
3666 protected function showConflict() {
3667 $out = $this->context->getOutput();
3668 // Avoid PHP 7.1 warning of passing $this by reference
3669 $editPage = $this;
3670 if ( Hooks::run( 'EditPageBeforeConflictDiff', [ &$editPage, &$out ] ) ) {
3671 $this->incrementConflictStats();
3672
3673 $this->getEditConflictHelper()->showEditFormTextAfterFooters();
3674 }
3675 }
3676
3677 protected function incrementConflictStats() {
3678 $this->getEditConflictHelper()->incrementConflictStats();
3679 }
3680
3681 /**
3682 * @return string
3683 */
3684 public function getCancelLink() {
3685 $cancelParams = [];
3686 if ( !$this->isConflict && $this->oldid > 0 ) {
3687 $cancelParams['oldid'] = $this->oldid;
3688 } elseif ( $this->getContextTitle()->isRedirect() ) {
3689 $cancelParams['redirect'] = 'no';
3690 }
3691
3692 return new OOUI\ButtonWidget( [
3693 'id' => 'mw-editform-cancel',
3694 'href' => $this->getContextTitle()->getLinkURL( $cancelParams ),
3695 'label' => new OOUI\HtmlSnippet( $this->context->msg( 'cancel' )->parse() ),
3696 'framed' => false,
3697 'infusable' => true,
3698 'flags' => 'destructive',
3699 ] );
3700 }
3701
3702 /**
3703 * Returns the URL to use in the form's action attribute.
3704 * This is used by EditPage subclasses when simply customizing the action
3705 * variable in the constructor is not enough. This can be used when the
3706 * EditPage lives inside of a Special page rather than a custom page action.
3707 *
3708 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3709 * @return string
3710 */
3711 protected function getActionURL( Title $title ) {
3712 return $title->getLocalURL( [ 'action' => $this->action ] );
3713 }
3714
3715 /**
3716 * Check if a page was deleted while the user was editing it, before submit.
3717 * Note that we rely on the logging table, which hasn't been always there,
3718 * but that doesn't matter, because this only applies to brand new
3719 * deletes.
3720 * @return bool
3721 */
3722 protected function wasDeletedSinceLastEdit() {
3723 if ( $this->deletedSinceEdit !== null ) {
3724 return $this->deletedSinceEdit;
3725 }
3726
3727 $this->deletedSinceEdit = false;
3728
3729 if ( !$this->mTitle->exists() && $this->mTitle->isDeletedQuick() ) {
3730 $this->lastDelete = $this->getLastDelete();
3731 if ( $this->lastDelete ) {
3732 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3733 if ( $deleteTime > $this->starttime ) {
3734 $this->deletedSinceEdit = true;
3735 }
3736 }
3737 }
3738
3739 return $this->deletedSinceEdit;
3740 }
3741
3742 /**
3743 * @return bool|stdClass
3744 */
3745 protected function getLastDelete() {
3746 $dbr = wfGetDB( DB_REPLICA );
3747 $commentQuery = CommentStore::getStore()->getJoin( 'log_comment' );
3748 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
3749 $data = $dbr->selectRow(
3750 array_merge( [ 'logging' ], $commentQuery['tables'], $actorQuery['tables'], [ 'user' ] ),
3751 [
3752 'log_type',
3753 'log_action',
3754 'log_timestamp',
3755 'log_namespace',
3756 'log_title',
3757 'log_params',
3758 'log_deleted',
3759 'user_name'
3760 ] + $commentQuery['fields'] + $actorQuery['fields'],
3761 [
3762 'log_namespace' => $this->mTitle->getNamespace(),
3763 'log_title' => $this->mTitle->getDBkey(),
3764 'log_type' => 'delete',
3765 'log_action' => 'delete',
3766 ],
3767 __METHOD__,
3768 [ 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ],
3769 [
3770 'user' => [ 'JOIN', 'user_id=' . $actorQuery['fields']['log_user'] ],
3771 ] + $commentQuery['joins'] + $actorQuery['joins']
3772 );
3773 // Quick paranoid permission checks...
3774 if ( is_object( $data ) ) {
3775 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3776 $data->user_name = $this->context->msg( 'rev-deleted-user' )->escaped();
3777 }
3778
3779 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3780 $data->log_comment_text = $this->context->msg( 'rev-deleted-comment' )->escaped();
3781 $data->log_comment_data = null;
3782 }
3783 }
3784
3785 return $data;
3786 }
3787
3788 /**
3789 * Get the rendered text for previewing.
3790 * @throws MWException
3791 * @return string
3792 */
3793 public function getPreviewText() {
3794 $out = $this->context->getOutput();
3795 $config = $this->context->getConfig();
3796
3797 if ( $config->get( 'RawHtml' ) && !$this->mTokenOk ) {
3798 // Could be an offsite preview attempt. This is very unsafe if
3799 // HTML is enabled, as it could be an attack.
3800 $parsedNote = '';
3801 if ( $this->textbox1 !== '' ) {
3802 // Do not put big scary notice, if previewing the empty
3803 // string, which happens when you initially edit
3804 // a category page, due to automatic preview-on-open.
3805 $parsedNote = $out->parse( "<div class='previewnote'>" .
3806 $this->context->msg( 'session_fail_preview_html' )->text() . "</div>",
3807 true, /* interface */true );
3808 }
3809 $this->incrementEditFailureStats( 'session_loss' );
3810 return $parsedNote;
3811 }
3812
3813 $note = '';
3814
3815 try {
3816 $content = $this->toEditContent( $this->textbox1 );
3817
3818 $previewHTML = '';
3819 if ( !Hooks::run(
3820 'AlternateEditPreview',
3821 [ $this, &$content, &$previewHTML, &$this->mParserOutput ] )
3822 ) {
3823 return $previewHTML;
3824 }
3825
3826 # provide a anchor link to the editform
3827 $continueEditing = '<span class="mw-continue-editing">' .
3828 '[[#' . self::EDITFORM_ID . '|' .
3829 $this->context->getLanguage()->getArrow() . ' ' .
3830 $this->context->msg( 'continue-editing' )->text() . ']]</span>';
3831 if ( $this->mTriedSave && !$this->mTokenOk ) {
3832 if ( $this->mTokenOkExceptSuffix ) {
3833 $note = $this->context->msg( 'token_suffix_mismatch' )->plain();
3834 $this->incrementEditFailureStats( 'bad_token' );
3835 } else {
3836 $note = $this->context->msg( 'session_fail_preview' )->plain();
3837 $this->incrementEditFailureStats( 'session_loss' );
3838 }
3839 } elseif ( $this->incompleteForm ) {
3840 $note = $this->context->msg( 'edit_form_incomplete' )->plain();
3841 if ( $this->mTriedSave ) {
3842 $this->incrementEditFailureStats( 'incomplete_form' );
3843 }
3844 } else {
3845 $note = $this->context->msg( 'previewnote' )->plain() . ' ' . $continueEditing;
3846 }
3847
3848 # don't parse non-wikitext pages, show message about preview
3849 if ( $this->mTitle->isUserConfigPage() || $this->mTitle->isSiteConfigPage() ) {
3850 if ( $this->mTitle->isUserConfigPage() ) {
3851 $level = 'user';
3852 } elseif ( $this->mTitle->isSiteConfigPage() ) {
3853 $level = 'site';
3854 } else {
3855 $level = false;
3856 }
3857
3858 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3859 $format = 'css';
3860 if ( $level === 'user' && !$config->get( 'AllowUserCss' ) ) {
3861 $format = false;
3862 }
3863 } elseif ( $content->getModel() == CONTENT_MODEL_JSON ) {
3864 $format = 'json';
3865 if ( $level === 'user' /* No comparable 'AllowUserJson' */ ) {
3866 $format = false;
3867 }
3868 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3869 $format = 'js';
3870 if ( $level === 'user' && !$config->get( 'AllowUserJs' ) ) {
3871 $format = false;
3872 }
3873 } else {
3874 $format = false;
3875 }
3876
3877 # Used messages to make sure grep find them:
3878 # Messages: usercsspreview, userjsonpreview, userjspreview,
3879 # sitecsspreview, sitejsonpreview, sitejspreview
3880 if ( $level && $format ) {
3881 $note = "<div id='mw-{$level}{$format}preview'>" .
3882 $this->context->msg( "{$level}{$format}preview" )->text() .
3883 ' ' . $continueEditing . "</div>";
3884 }
3885 }
3886
3887 # If we're adding a comment, we need to show the
3888 # summary as the headline
3889 if ( $this->section === "new" && $this->summary !== "" ) {
3890 $content = $content->addSectionHeader( $this->summary );
3891 }
3892
3893 $hook_args = [ $this, &$content ];
3894 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3895
3896 $parserResult = $this->doPreviewParse( $content );
3897 $parserOutput = $parserResult['parserOutput'];
3898 $previewHTML = $parserResult['html'];
3899 $this->mParserOutput = $parserOutput;
3900 $out->addParserOutputMetadata( $parserOutput );
3901 if ( $out->userCanPreview() ) {
3902 $out->addContentOverride( $this->getTitle(), $content );
3903 }
3904
3905 if ( count( $parserOutput->getWarnings() ) ) {
3906 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3907 }
3908
3909 } catch ( MWContentSerializationException $ex ) {
3910 $m = $this->context->msg(
3911 'content-failed-to-parse',
3912 $this->contentModel,
3913 $this->contentFormat,
3914 $ex->getMessage()
3915 );
3916 $note .= "\n\n" . $m->parse();
3917 $previewHTML = '';
3918 }
3919
3920 if ( $this->isConflict ) {
3921 $conflict = '<h2 id="mw-previewconflict">'
3922 . $this->context->msg( 'previewconflict' )->escaped() . "</h2>\n";
3923 } else {
3924 $conflict = '<hr />';
3925 }
3926
3927 $previewhead = "<div class='previewnote'>\n" .
3928 '<h2 id="mw-previewheader">' . $this->context->msg( 'preview' )->escaped() . "</h2>" .
3929 $out->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3930
3931 $pageViewLang = $this->mTitle->getPageViewLanguage();
3932 $attribs = [ 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3933 'class' => 'mw-content-' . $pageViewLang->getDir() ];
3934 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3935
3936 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3937 }
3938
3939 private function incrementEditFailureStats( $failureType ) {
3940 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
3941 $stats->increment( 'edit.failures.' . $failureType );
3942 }
3943
3944 /**
3945 * Get parser options for a preview
3946 * @return ParserOptions
3947 */
3948 protected function getPreviewParserOptions() {
3949 $parserOptions = $this->page->makeParserOptions( $this->context );
3950 $parserOptions->setIsPreview( true );
3951 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3952 $parserOptions->enableLimitReport();
3953 return $parserOptions;
3954 }
3955
3956 /**
3957 * Parse the page for a preview. Subclasses may override this class, in order
3958 * to parse with different options, or to otherwise modify the preview HTML.
3959 *
3960 * @param Content $content The page content
3961 * @return array with keys:
3962 * - parserOutput: The ParserOutput object
3963 * - html: The HTML to be displayed
3964 */
3965 protected function doPreviewParse( Content $content ) {
3966 $user = $this->context->getUser();
3967 $parserOptions = $this->getPreviewParserOptions();
3968 $pstContent = $content->preSaveTransform( $this->mTitle, $user, $parserOptions );
3969 $scopedCallback = $parserOptions->setupFakeRevision(
3970 $this->mTitle, $pstContent, $user );
3971 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
3972 ScopedCallback::consume( $scopedCallback );
3973 return [
3974 'parserOutput' => $parserOutput,
3975 'html' => $parserOutput->getText( [
3976 'enableSectionEditLinks' => false
3977 ] )
3978 ];
3979 }
3980
3981 /**
3982 * @return array
3983 */
3984 public function getTemplates() {
3985 if ( $this->preview || $this->section != '' ) {
3986 $templates = [];
3987 if ( !isset( $this->mParserOutput ) ) {
3988 return $templates;
3989 }
3990 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3991 foreach ( array_keys( $template ) as $dbk ) {
3992 $templates[] = Title::makeTitle( $ns, $dbk );
3993 }
3994 }
3995 return $templates;
3996 } else {
3997 return $this->mTitle->getTemplateLinksFrom();
3998 }
3999 }
4000
4001 /**
4002 * Shows a bulletin board style toolbar for common editing functions.
4003 * It can be disabled in the user preferences.
4004 *
4005 * @param Title $title Title object for the page being edited (optional)
4006 * @return string
4007 */
4008 public static function getEditToolbar( $title = null ) {
4009 global $wgContLang, $wgOut;
4010 global $wgEnableUploads, $wgForeignFileRepos;
4011
4012 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
4013 $showSignature = true;
4014 if ( $title ) {
4015 $showSignature = MWNamespace::wantSignatures( $title->getNamespace() );
4016 }
4017
4018 /**
4019 * $toolarray is an array of arrays each of which includes the
4020 * opening tag, the closing tag, optionally a sample text that is
4021 * inserted between the two when no selection is highlighted
4022 * and. The tip text is shown when the user moves the mouse
4023 * over the button.
4024 *
4025 * Images are defined in ResourceLoaderEditToolbarModule.
4026 */
4027 $toolarray = [
4028 [
4029 'id' => 'mw-editbutton-bold',
4030 'open' => '\'\'\'',
4031 'close' => '\'\'\'',
4032 'sample' => wfMessage( 'bold_sample' )->text(),
4033 'tip' => wfMessage( 'bold_tip' )->text(),
4034 ],
4035 [
4036 'id' => 'mw-editbutton-italic',
4037 'open' => '\'\'',
4038 'close' => '\'\'',
4039 'sample' => wfMessage( 'italic_sample' )->text(),
4040 'tip' => wfMessage( 'italic_tip' )->text(),
4041 ],
4042 [
4043 'id' => 'mw-editbutton-link',
4044 'open' => '[[',
4045 'close' => ']]',
4046 'sample' => wfMessage( 'link_sample' )->text(),
4047 'tip' => wfMessage( 'link_tip' )->text(),
4048 ],
4049 [
4050 'id' => 'mw-editbutton-extlink',
4051 'open' => '[',
4052 'close' => ']',
4053 'sample' => wfMessage( 'extlink_sample' )->text(),
4054 'tip' => wfMessage( 'extlink_tip' )->text(),
4055 ],
4056 [
4057 'id' => 'mw-editbutton-headline',
4058 'open' => "\n== ",
4059 'close' => " ==\n",
4060 'sample' => wfMessage( 'headline_sample' )->text(),
4061 'tip' => wfMessage( 'headline_tip' )->text(),
4062 ],
4063 $imagesAvailable ? [
4064 'id' => 'mw-editbutton-image',
4065 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
4066 'close' => ']]',
4067 'sample' => wfMessage( 'image_sample' )->text(),
4068 'tip' => wfMessage( 'image_tip' )->text(),
4069 ] : false,
4070 $imagesAvailable ? [
4071 'id' => 'mw-editbutton-media',
4072 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
4073 'close' => ']]',
4074 'sample' => wfMessage( 'media_sample' )->text(),
4075 'tip' => wfMessage( 'media_tip' )->text(),
4076 ] : false,
4077 [
4078 'id' => 'mw-editbutton-nowiki',
4079 'open' => "<nowiki>",
4080 'close' => "</nowiki>",
4081 'sample' => wfMessage( 'nowiki_sample' )->text(),
4082 'tip' => wfMessage( 'nowiki_tip' )->text(),
4083 ],
4084 $showSignature ? [
4085 'id' => 'mw-editbutton-signature',
4086 'open' => wfMessage( 'sig-text', '~~~~' )->inContentLanguage()->text(),
4087 'close' => '',
4088 'sample' => '',
4089 'tip' => wfMessage( 'sig_tip' )->text(),
4090 ] : false,
4091 [
4092 'id' => 'mw-editbutton-hr',
4093 'open' => "\n----\n",
4094 'close' => '',
4095 'sample' => '',
4096 'tip' => wfMessage( 'hr_tip' )->text(),
4097 ]
4098 ];
4099
4100 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
4101 foreach ( $toolarray as $tool ) {
4102 if ( !$tool ) {
4103 continue;
4104 }
4105
4106 $params = [
4107 // Images are defined in ResourceLoaderEditToolbarModule
4108 false,
4109 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
4110 // Older browsers show a "speedtip" type message only for ALT.
4111 // Ideally these should be different, realistically they
4112 // probably don't need to be.
4113 $tool['tip'],
4114 $tool['open'],
4115 $tool['close'],
4116 $tool['sample'],
4117 $tool['id'],
4118 ];
4119
4120 $script .= Xml::encodeJsCall(
4121 'mw.toolbar.addButton',
4122 $params,
4123 ResourceLoader::inDebugMode()
4124 );
4125 }
4126
4127 $script .= '});';
4128
4129 $toolbar = '<div id="toolbar"></div>';
4130
4131 if ( Hooks::run( 'EditPageBeforeEditToolbar', [ &$toolbar ] ) ) {
4132 // Only add the old toolbar cruft to the page payload if the toolbar has not
4133 // been over-written by a hook caller
4134 $nonce = $wgOut->getCSPNonce();
4135 $wgOut->addScript( ResourceLoader::makeInlineScript( $script, $nonce ) );
4136 };
4137
4138 return $toolbar;
4139 }
4140
4141 /**
4142 * Return an array of checkbox definitions.
4143 *
4144 * Array keys correspond to the `<input>` 'name' attribute to use for each checkbox.
4145 *
4146 * Array values are associative arrays with the following keys:
4147 * - 'label-message' (required): message for label text
4148 * - 'id' (required): 'id' attribute for the `<input>`
4149 * - 'default' (required): default checkedness (true or false)
4150 * - 'title-message' (optional): used to generate 'title' attribute for the `<label>`
4151 * - 'tooltip' (optional): used to generate 'title' and 'accesskey' attributes
4152 * from messages like 'tooltip-foo', 'accesskey-foo'
4153 * - 'label-id' (optional): 'id' attribute for the `<label>`
4154 * - 'legacy-name' (optional): short name for backwards-compatibility
4155 * @param array $checked Array of checkbox name (matching the 'legacy-name') => bool,
4156 * where bool indicates the checked status of the checkbox
4157 * @return array
4158 */
4159 public function getCheckboxesDefinition( $checked ) {
4160 $checkboxes = [];
4161
4162 $user = $this->context->getUser();
4163 // don't show the minor edit checkbox if it's a new page or section
4164 if ( !$this->isNew && $user->isAllowed( 'minoredit' ) ) {
4165 $checkboxes['wpMinoredit'] = [
4166 'id' => 'wpMinoredit',
4167 'label-message' => 'minoredit',
4168 // Uses messages: tooltip-minoredit, accesskey-minoredit
4169 'tooltip' => 'minoredit',
4170 'label-id' => 'mw-editpage-minoredit',
4171 'legacy-name' => 'minor',
4172 'default' => $checked['minor'],
4173 ];
4174 }
4175
4176 if ( $user->isLoggedIn() ) {
4177 $checkboxes['wpWatchthis'] = [
4178 'id' => 'wpWatchthis',
4179 'label-message' => 'watchthis',
4180 // Uses messages: tooltip-watch, accesskey-watch
4181 'tooltip' => 'watch',
4182 'label-id' => 'mw-editpage-watch',
4183 'legacy-name' => 'watch',
4184 'default' => $checked['watch'],
4185 ];
4186 }
4187
4188 $editPage = $this;
4189 Hooks::run( 'EditPageGetCheckboxesDefinition', [ $editPage, &$checkboxes ] );
4190
4191 return $checkboxes;
4192 }
4193
4194 /**
4195 * Returns an array of checkboxes for the edit form, including 'minor' and 'watch' checkboxes and
4196 * any other added by extensions.
4197 *
4198 * @param int &$tabindex Current tabindex
4199 * @param array $checked Array of checkbox => bool, where bool indicates the checked
4200 * status of the checkbox
4201 *
4202 * @return array Associative array of string keys to OOUI\FieldLayout instances
4203 */
4204 public function getCheckboxesWidget( &$tabindex, $checked ) {
4205 $checkboxes = [];
4206 $checkboxesDef = $this->getCheckboxesDefinition( $checked );
4207
4208 foreach ( $checkboxesDef as $name => $options ) {
4209 $legacyName = $options['legacy-name'] ?? $name;
4210
4211 $title = null;
4212 $accesskey = null;
4213 if ( isset( $options['tooltip'] ) ) {
4214 $accesskey = $this->context->msg( "accesskey-{$options['tooltip']}" )->text();
4215 $title = Linker::titleAttrib( $options['tooltip'] );
4216 }
4217 if ( isset( $options['title-message'] ) ) {
4218 $title = $this->context->msg( $options['title-message'] )->text();
4219 }
4220
4221 $checkboxes[ $legacyName ] = new OOUI\FieldLayout(
4222 new OOUI\CheckboxInputWidget( [
4223 'tabIndex' => ++$tabindex,
4224 'accessKey' => $accesskey,
4225 'id' => $options['id'] . 'Widget',
4226 'inputId' => $options['id'],
4227 'name' => $name,
4228 'selected' => $options['default'],
4229 'infusable' => true,
4230 ] ),
4231 [
4232 'align' => 'inline',
4233 'label' => new OOUI\HtmlSnippet( $this->context->msg( $options['label-message'] )->parse() ),
4234 'title' => $title,
4235 'id' => $options['label-id'] ?? null,
4236 ]
4237 );
4238 }
4239
4240 return $checkboxes;
4241 }
4242
4243 /**
4244 * Get the message key of the label for the button to save the page
4245 *
4246 * @since 1.30
4247 * @return string
4248 */
4249 protected function getSubmitButtonLabel() {
4250 $labelAsPublish =
4251 $this->context->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4252
4253 // Can't use $this->isNew as that's also true if we're adding a new section to an extant page
4254 $newPage = !$this->mTitle->exists();
4255
4256 if ( $labelAsPublish ) {
4257 $buttonLabelKey = $newPage ? 'publishpage' : 'publishchanges';
4258 } else {
4259 $buttonLabelKey = $newPage ? 'savearticle' : 'savechanges';
4260 }
4261
4262 return $buttonLabelKey;
4263 }
4264
4265 /**
4266 * Returns an array of html code of the following buttons:
4267 * save, diff and preview
4268 *
4269 * @param int &$tabindex Current tabindex
4270 *
4271 * @return array
4272 */
4273 public function getEditButtons( &$tabindex ) {
4274 $buttons = [];
4275
4276 $labelAsPublish =
4277 $this->context->getConfig()->get( 'EditSubmitButtonLabelPublish' );
4278
4279 $buttonLabel = $this->context->msg( $this->getSubmitButtonLabel() )->text();
4280 $buttonTooltip = $labelAsPublish ? 'publish' : 'save';
4281
4282 $buttons['save'] = new OOUI\ButtonInputWidget( [
4283 'name' => 'wpSave',
4284 'tabIndex' => ++$tabindex,
4285 'id' => 'wpSaveWidget',
4286 'inputId' => 'wpSave',
4287 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4288 'useInputTag' => true,
4289 'flags' => [ 'progressive', 'primary' ],
4290 'label' => $buttonLabel,
4291 'infusable' => true,
4292 'type' => 'submit',
4293 // Messages used: tooltip-save, tooltip-publish
4294 'title' => Linker::titleAttrib( $buttonTooltip ),
4295 // Messages used: accesskey-save, accesskey-publish
4296 'accessKey' => Linker::accesskey( $buttonTooltip ),
4297 ] );
4298
4299 $buttons['preview'] = new OOUI\ButtonInputWidget( [
4300 'name' => 'wpPreview',
4301 'tabIndex' => ++$tabindex,
4302 'id' => 'wpPreviewWidget',
4303 'inputId' => 'wpPreview',
4304 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4305 'useInputTag' => true,
4306 'label' => $this->context->msg( 'showpreview' )->text(),
4307 'infusable' => true,
4308 'type' => 'submit',
4309 // Message used: tooltip-preview
4310 'title' => Linker::titleAttrib( 'preview' ),
4311 // Message used: accesskey-preview
4312 'accessKey' => Linker::accesskey( 'preview' ),
4313 ] );
4314
4315 $buttons['diff'] = new OOUI\ButtonInputWidget( [
4316 'name' => 'wpDiff',
4317 'tabIndex' => ++$tabindex,
4318 'id' => 'wpDiffWidget',
4319 'inputId' => 'wpDiff',
4320 // Support: IE 6 – Use <input>, otherwise it can't distinguish which button was clicked
4321 'useInputTag' => true,
4322 'label' => $this->context->msg( 'showdiff' )->text(),
4323 'infusable' => true,
4324 'type' => 'submit',
4325 // Message used: tooltip-diff
4326 'title' => Linker::titleAttrib( 'diff' ),
4327 // Message used: accesskey-diff
4328 'accessKey' => Linker::accesskey( 'diff' ),
4329 ] );
4330
4331 // Avoid PHP 7.1 warning of passing $this by reference
4332 $editPage = $this;
4333 Hooks::run( 'EditPageBeforeEditButtons', [ &$editPage, &$buttons, &$tabindex ] );
4334
4335 return $buttons;
4336 }
4337
4338 /**
4339 * Creates a basic error page which informs the user that
4340 * they have attempted to edit a nonexistent section.
4341 */
4342 public function noSuchSectionPage() {
4343 $out = $this->context->getOutput();
4344 $out->prepareErrorPage( $this->context->msg( 'nosuchsectiontitle' ) );
4345
4346 $res = $this->context->msg( 'nosuchsectiontext', $this->section )->parseAsBlock();
4347
4348 // Avoid PHP 7.1 warning of passing $this by reference
4349 $editPage = $this;
4350 Hooks::run( 'EditPageNoSuchSection', [ &$editPage, &$res ] );
4351 $out->addHTML( $res );
4352
4353 $out->returnToMain( false, $this->mTitle );
4354 }
4355
4356 /**
4357 * Show "your edit contains spam" page with your diff and text
4358 *
4359 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
4360 */
4361 public function spamPageWithContent( $match = false ) {
4362 $this->textbox2 = $this->textbox1;
4363
4364 if ( is_array( $match ) ) {
4365 $match = $this->context->getLanguage()->listToText( $match );
4366 }
4367 $out = $this->context->getOutput();
4368 $out->prepareErrorPage( $this->context->msg( 'spamprotectiontitle' ) );
4369
4370 $out->addHTML( '<div id="spamprotected">' );
4371 $out->addWikiMsg( 'spamprotectiontext' );
4372 if ( $match ) {
4373 $out->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4374 }
4375 $out->addHTML( '</div>' );
4376
4377 $out->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4378 $this->showDiff();
4379
4380 $out->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4381 $this->showTextbox2();
4382
4383 $out->addReturnTo( $this->getContextTitle(), [ 'action' => 'edit' ] );
4384 }
4385
4386 /**
4387 * Filter an input field through a Unicode de-armoring process if it
4388 * came from an old browser with known broken Unicode editing issues.
4389 *
4390 * @deprecated since 1.30, does nothing
4391 *
4392 * @param WebRequest $request
4393 * @param string $field
4394 * @return string
4395 */
4396 protected function safeUnicodeInput( $request, $field ) {
4397 return rtrim( $request->getText( $field ) );
4398 }
4399
4400 /**
4401 * Filter an output field through a Unicode armoring process if it is
4402 * going to an old browser with known broken Unicode editing issues.
4403 *
4404 * @deprecated since 1.30, does nothing
4405 *
4406 * @param string $text
4407 * @return string
4408 */
4409 protected function safeUnicodeOutput( $text ) {
4410 return $text;
4411 }
4412
4413 /**
4414 * @since 1.29
4415 */
4416 protected function addEditNotices() {
4417 $out = $this->context->getOutput();
4418 $editNotices = $this->mTitle->getEditNotices( $this->oldid );
4419 if ( count( $editNotices ) ) {
4420 $out->addHTML( implode( "\n", $editNotices ) );
4421 } else {
4422 $msg = $this->context->msg( 'editnotice-notext' );
4423 if ( !$msg->isDisabled() ) {
4424 $out->addHTML(
4425 '<div class="mw-editnotice-notext">'
4426 . $msg->parseAsBlock()
4427 . '</div>'
4428 );
4429 }
4430 }
4431 }
4432
4433 /**
4434 * @since 1.29
4435 */
4436 protected function addTalkPageText() {
4437 if ( $this->mTitle->isTalkPage() ) {
4438 $this->context->getOutput()->addWikiMsg( 'talkpagetext' );
4439 }
4440 }
4441
4442 /**
4443 * @since 1.29
4444 */
4445 protected function addLongPageWarningHeader() {
4446 if ( $this->contentLength === false ) {
4447 $this->contentLength = strlen( $this->textbox1 );
4448 }
4449
4450 $out = $this->context->getOutput();
4451 $lang = $this->context->getLanguage();
4452 $maxArticleSize = $this->context->getConfig()->get( 'MaxArticleSize' );
4453 if ( $this->tooBig || $this->contentLength > $maxArticleSize * 1024 ) {
4454 $out->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
4455 [
4456 'longpageerror',
4457 $lang->formatNum( round( $this->contentLength / 1024, 3 ) ),
4458 $lang->formatNum( $maxArticleSize )
4459 ]
4460 );
4461 } else {
4462 if ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) {
4463 $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
4464 [
4465 'longpage-hint',
4466 $lang->formatSize( strlen( $this->textbox1 ) ),
4467 strlen( $this->textbox1 )
4468 ]
4469 );
4470 }
4471 }
4472 }
4473
4474 /**
4475 * @since 1.29
4476 */
4477 protected function addPageProtectionWarningHeaders() {
4478 $out = $this->context->getOutput();
4479 if ( $this->mTitle->isProtected( 'edit' ) &&
4480 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== [ '' ]
4481 ) {
4482 # Is the title semi-protected?
4483 if ( $this->mTitle->isSemiProtected() ) {
4484 $noticeMsg = 'semiprotectedpagewarning';
4485 } else {
4486 # Then it must be protected based on static groups (regular)
4487 $noticeMsg = 'protectedpagewarning';
4488 }
4489 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle, '',
4490 [ 'lim' => 1, 'msgKey' => [ $noticeMsg ] ] );
4491 }
4492 if ( $this->mTitle->isCascadeProtected() ) {
4493 # Is this page under cascading protection from some source pages?
4494 /** @var Title[] $cascadeSources */
4495 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
4496 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
4497 $cascadeSourcesCount = count( $cascadeSources );
4498 if ( $cascadeSourcesCount > 0 ) {
4499 # Explain, and list the titles responsible
4500 foreach ( $cascadeSources as $page ) {
4501 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
4502 }
4503 }
4504 $notice .= '</div>';
4505 $out->wrapWikiMsg( $notice, [ 'cascadeprotectedwarning', $cascadeSourcesCount ] );
4506 }
4507 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
4508 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle, '',
4509 [ 'lim' => 1,
4510 'showIfEmpty' => false,
4511 'msgKey' => [ 'titleprotectedwarning' ],
4512 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ] );
4513 }
4514 }
4515
4516 /**
4517 * @param OutputPage $out
4518 * @since 1.29
4519 */
4520 protected function addExplainConflictHeader( OutputPage $out ) {
4521 $out->addHTML(
4522 $this->getEditConflictHelper()->getExplainHeader()
4523 );
4524 }
4525
4526 /**
4527 * @param string $name
4528 * @param mixed[] $customAttribs
4529 * @param User $user
4530 * @return mixed[]
4531 * @since 1.29
4532 */
4533 protected function buildTextboxAttribs( $name, array $customAttribs, User $user ) {
4534 return ( new TextboxBuilder() )->buildTextboxAttribs(
4535 $name, $customAttribs, $user, $this->mTitle
4536 );
4537 }
4538
4539 /**
4540 * @param string $wikitext
4541 * @return string
4542 * @since 1.29
4543 */
4544 protected function addNewLineAtEnd( $wikitext ) {
4545 return ( new TextboxBuilder() )->addNewLineAtEnd( $wikitext );
4546 }
4547
4548 /**
4549 * Turns section name wikitext into anchors for use in HTTP redirects. Various
4550 * versions of Microsoft browsers misinterpret fragment encoding of Location: headers
4551 * resulting in mojibake in address bar. Redirect them to legacy section IDs,
4552 * if possible. All the other browsers get HTML5 if the wiki is configured for it, to
4553 * spread the new style links more efficiently.
4554 *
4555 * @param string $text
4556 * @return string
4557 */
4558 private function guessSectionName( $text ) {
4559 global $wgParser;
4560
4561 // Detect Microsoft browsers
4562 $userAgent = $this->context->getRequest()->getHeader( 'User-Agent' );
4563 if ( $userAgent && preg_match( '/MSIE|Edge/', $userAgent ) ) {
4564 // ...and redirect them to legacy encoding, if available
4565 return $wgParser->guessLegacySectionNameFromWikiText( $text );
4566 }
4567 // Meanwhile, real browsers get real anchors
4568 return $wgParser->guessSectionNameFromWikiText( $text );
4569 }
4570
4571 /**
4572 * Set a factory function to create an EditConflictHelper
4573 *
4574 * @param callable $factory Factory function
4575 * @since 1.31
4576 */
4577 public function setEditConflictHelperFactory( callable $factory ) {
4578 $this->editConflictHelperFactory = $factory;
4579 $this->editConflictHelper = null;
4580 }
4581
4582 /**
4583 * @return TextConflictHelper
4584 */
4585 private function getEditConflictHelper() {
4586 if ( !$this->editConflictHelper ) {
4587 $this->editConflictHelper = call_user_func(
4588 $this->editConflictHelperFactory,
4589 $this->getSubmitButtonLabel()
4590 );
4591 }
4592
4593 return $this->editConflictHelper;
4594 }
4595
4596 /**
4597 * @param string $submitButtonLabel
4598 * @return TextConflictHelper
4599 */
4600 private function newTextConflictHelper( $submitButtonLabel ) {
4601 return new TextConflictHelper(
4602 $this->getTitle(),
4603 $this->getContext()->getOutput(),
4604 MediaWikiServices::getInstance()->getStatsdDataFactory(),
4605 $submitButtonLabel
4606 );
4607 }
4608 }