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