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