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