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