Debian Codegraph @

extensions/VisualEditor/includes/Hooks.php

raw symbols SCIP
1 <?php
2 /**
3 * VisualEditor extension hooks
4 *
5 * @file
6 * @ingroup Extensions
7 * @copyright 2011-2020 VisualEditor Team and others; see AUTHORS.txt
8 * @license MIT
9 */
10
11 namespace MediaWiki\Extension\VisualEditor;
12
13 use Article;
14 use MediaWiki\Actions\ActionEntryPoint;
15 use MediaWiki\Auth\Hook\UserLoggedInHook;
16 use MediaWiki\ChangeTags\Hook\ChangeTagsListActiveHook;
17 use MediaWiki\ChangeTags\Hook\ListDefinedTagsHook;
18 use MediaWiki\Config\Config;
19 use MediaWiki\Context\IContextSource;
20 use MediaWiki\Context\RequestContext;
21 use MediaWiki\Deferred\DeferredUpdates;
22 use MediaWiki\Diff\Hook\DifferenceEngineViewHeaderHook;
23 use MediaWiki\Diff\Hook\TextSlotDiffRendererTablePrefixHook;
24 use MediaWiki\EditPage\EditPage;
25 use MediaWiki\Extension\VisualEditor\EditCheck\ApiEditCheckReferenceUrl;
26 use MediaWiki\Hook\BeforeInitializeHook;
27 use MediaWiki\Hook\CustomEditorHook;
28 use MediaWiki\Hook\EditPage__showEditForm_fieldsHook;
29 use MediaWiki\Hook\ParserTestGlobalsHook;
30 use MediaWiki\Hook\RecentChange_saveHook;
31 use MediaWiki\Hook\SkinEditSectionLinksHook;
32 use MediaWiki\Hook\SkinTemplateNavigation__UniversalHook;
33 use MediaWiki\Html\Html;
34 use MediaWiki\HTMLForm\HTMLForm;
35 use MediaWiki\Language\Language;
36 use MediaWiki\MediaWikiServices;
37 use MediaWiki\Output\Hook\BeforePageDisplayHook;
38 use MediaWiki\Output\Hook\MakeGlobalVariablesScriptHook;
39 use MediaWiki\Output\Hook\OutputPageBodyAttributesHook;
40 use MediaWiki\Output\OutputPage;
41 use MediaWiki\Preferences\Hook\GetPreferencesHook;
42 use MediaWiki\Preferences\Hook\PreferencesFormPreSaveHook;
43 use MediaWiki\Registration\ExtensionRegistry;
44 use MediaWiki\Request\WebRequest;
45 use MediaWiki\ResourceLoader\Hook\ResourceLoaderGetConfigVarsHook;
46 use MediaWiki\ResourceLoader\Hook\ResourceLoaderRegisterModulesHook;
47 use MediaWiki\ResourceLoader\ResourceLoader;
48 use MediaWiki\SpecialPage\Hook\RedirectSpecialArticleRedirectParamsHook;
49 use MediaWiki\SpecialPage\SpecialPage;
50 use MediaWiki\Title\Title;
51 use MediaWiki\User\User;
52 use MediaWiki\User\UserIdentity;
53 use OOUI\ButtonGroupWidget;
54 use OOUI\ButtonWidget;
55 use RecentChange;
56 use Skin;
57 use SkinTemplate;
58 use TextSlotDiffRenderer;
59
60 /**
61 * @phpcs:disable MediaWiki.NamingConventions.LowerCamelFunctionsName.FunctionName
62 */
63 class Hooks implements
64 TextSlotDiffRendererTablePrefixHook,
65 BeforeInitializeHook,
66 BeforePageDisplayHook,
67 ChangeTagsListActiveHook,
68 CustomEditorHook,
69 DifferenceEngineViewHeaderHook,
70 EditPage__showEditForm_fieldsHook,
71 GetPreferencesHook,
72 ListDefinedTagsHook,
73 MakeGlobalVariablesScriptHook,
74 OutputPageBodyAttributesHook,
75 ParserTestGlobalsHook,
76 PreferencesFormPreSaveHook,
77 RecentChange_saveHook,
78 RedirectSpecialArticleRedirectParamsHook,
79 ResourceLoaderGetConfigVarsHook,
80 ResourceLoaderRegisterModulesHook,
81 SkinEditSectionLinksHook,
82 SkinTemplateNavigation__UniversalHook,
83 UserLoggedInHook
84 {
85
86 // Known parameters that VE does not handle
87 // TODO: Other params too?
88 // Known-good parameters: edit, veaction, section, oldid, lintid, preload, preloadparams, editintro
89 // Partially-good: preloadtitle (source-mode only)
90 private const UNSUPPORTED_EDIT_PARAMS = [
91 'undo',
92 'undoafter',
93 // Only for WTE. This parameter is not supported right now, and NWE has a very different design
94 // for previews, so we might not want to support this at all.
95 'preview',
96 'veswitched'
97 ];
98
99 private const TAGS = [
100 'visualeditor',
101 'visualeditor-wikitext',
102 // Edit check
103 'editcheck-references',
104 'editcheck-references-activated',
105 'editcheck-newcontent',
106 'editcheck-newreference',
107 'editcheck-reference-decline-common-knowledge',
108 'editcheck-reference-decline-irrelevant',
109 'editcheck-reference-decline-uncertain',
110 'editcheck-reference-decline-other',
111 // No longer in active use:
112 'visualeditor-needcheck',
113 'visualeditor-switched'
114 ];
115
116 /**
117 * Initialise the 'VisualEditorAvailableNamespaces' setting, and add content
118 * namespaces to it. This will run after LocalSettings.php is processed.
119 * Also ensure Parsoid extension is loaded when necessary.
120 */
121 public static function onRegistration(): void {
122 global $wgVisualEditorAvailableNamespaces, $wgContentNamespaces;
123
124 foreach ( $wgContentNamespaces as $contentNamespace ) {
125 if ( !isset( $wgVisualEditorAvailableNamespaces[$contentNamespace] ) ) {
126 $wgVisualEditorAvailableNamespaces[$contentNamespace] = true;
127 }
128 }
129 }
130
131 /**
132 * Adds VisualEditor JS to the output.
133 *
134 * This is attached to the MediaWiki 'BeforePageDisplay' hook.
135 *
136 * @param OutputPage $output The page view.
137 * @param Skin $skin The skin that's going to build the UI.
138 */
139 public function onBeforePageDisplay( $output, $skin ): void {
140 $services = MediaWikiServices::getInstance();
141 $hookRunner = new VisualEditorHookRunner( $services->getHookContainer() );
142 if ( !$hookRunner->onVisualEditorBeforeEditor( $output, $skin ) ) {
143 $output->addJsConfigVars( 'wgVisualEditorDisabledByHook', true );
144 return;
145 }
146 if ( !(
147 ExtensionRegistry::getInstance()->isLoaded( 'MobileFrontend' ) &&
148 $services->getService( 'MobileFrontend.Context' )
149 ->shouldDisplayMobileView()
150 ) ) {
151 $output->addModules( [
152 'ext.visualEditor.desktopArticleTarget.init',
153 'ext.visualEditor.targetLoader'
154 ] );
155 $output->addModuleStyles( [ 'ext.visualEditor.desktopArticleTarget.noscript' ] );
156 }
157 if (
158 $services->getUserOptionsLookup()->getOption( $skin->getUser(), 'visualeditor-collab' ) ||
159 // Joining a collab session
160 $output->getRequest()->getVal( 'collabSession' )
161 ) {
162 $output->addModules( 'ext.visualEditor.collab' );
163 }
164
165 // add scroll offset js variable to output
166 $veConfig = $services->getConfigFactory()->makeConfig( 'visualeditor' );
167 $skinsToolbarScrollOffset = $veConfig->get( 'VisualEditorSkinToolbarScrollOffset' );
168 $toolbarScrollOffset = 0;
169 $skinName = $skin->getSkinName();
170 if ( isset( $skinsToolbarScrollOffset[$skinName] ) ) {
171 $toolbarScrollOffset = $skinsToolbarScrollOffset[$skinName];
172 }
173 // T220158: Don't add this unless it's non-default
174 // TODO: Move this to packageFiles as it's not relevant to the HTML request.
175 if ( $toolbarScrollOffset !== 0 ) {
176 $output->addJsConfigVars( 'wgVisualEditorToolbarScrollOffset', $toolbarScrollOffset );
177 }
178
179 $output->addJsConfigVars(
180 'wgEditSubmitButtonLabelPublish',
181 $veConfig->get( 'EditSubmitButtonLabelPublish' )
182 );
183
184 // Don't index VE edit pages (T319124)
185 if ( $output->getRequest()->getVal( 'veaction' ) ) {
186 $output->setRobotPolicy( 'noindex,nofollow' );
187 }
188 }
189
190 /**
191 * @internal For internal use in extension.json only.
192 */
193 public static function getDataForDesktopArticleTargetInitModule(): array {
194 return [
195 'unsupportedEditParams' => self::UNSUPPORTED_EDIT_PARAMS,
196 ];
197 }
198
199 /**
200 * Load modules required for a diff page
201 *
202 * @param OutputPage $output Output page
203 */
204 private function loadDiffModules( OutputPage $output ) {
205 $output->addModuleStyles( [
206 'ext.visualEditor.diffPage.init.styles',
207 'oojs-ui.styles.icons-accessibility',
208 'oojs-ui.styles.icons-editing-advanced'
209 ] );
210 $output->addModules( 'ext.visualEditor.diffPage.init' );
211 $output->enableOOUI();
212 }
213
214 /** @inheritDoc */
215 public function onDifferenceEngineViewHeader( $differenceEngine ) {
216 // T344596: Must load this module unconditionally. The TextSlotDiffRendererTablePrefix hook
217 // below doesn't run when the diff is e.g. a log entry with no change to the content.
218 $this->loadDiffModules( $differenceEngine->getContext()->getOutput() );
219 }
220
221 /**
222 * Handler for the DifferenceEngineViewHeader hook, to add visual diffs code as configured
223 *
224 * @param TextSlotDiffRenderer $textSlotDiffRenderer
225 * @param IContextSource $context
226 * @param string[] &$parts
227 * @return void
228 */
229 public function onTextSlotDiffRendererTablePrefix(
230 TextSlotDiffRenderer $textSlotDiffRenderer,
231 IContextSource $context,
232 array &$parts
233 ) {
234 $services = MediaWikiServices::getInstance();
235 $veConfig = $services->getConfigFactory()
236 ->makeConfig( 'visualeditor' );
237 $output = $context->getOutput();
238
239 // Return early if not viewing a diff of an allowed type.
240 if ( !ApiVisualEditor::isAllowedContentType( $veConfig, $textSlotDiffRenderer->getContentModel() )
241 || $output->getActionName() !== 'view'
242 ) {
243 return;
244 }
245
246 // onDifferenceEngineViewHeader may not run, so load modules here as well for styling (T361775)
247 $this->loadDiffModules( $output );
248
249 $parts['50_ve-init-mw-diffPage-diffMode'] = '<div class="ve-init-mw-diffPage-diffMode">' .
250 // Will be replaced by a ButtonSelectWidget in JS
251 new ButtonGroupWidget( [
252 'items' => [
253 new ButtonWidget( [
254 'data' => 'visual',
255 'icon' => 'eye',
256 'disabled' => true,
257 'label' => $output->msg( 'visualeditor-savedialog-review-visual' )->plain()
258 ] ),
259 new ButtonWidget( [
260 'data' => 'source',
261 'icon' => 'wikiText',
262 'active' => true,
263 'label' => $output->msg( 'visualeditor-savedialog-review-wikitext' )->plain()
264 ] )
265 ]
266 ] ) .
267 '</div>';
268 }
269
270 /**
271 * @param Title $title
272 * @param User $user
273 * @param WebRequest $req
274 * @return bool
275 */
276 private static function isSupportedEditPage( Title $title, User $user, WebRequest $req ): bool {
277 if (
278 $req->getVal( 'action' ) !== 'edit' ||
279 !MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan( 'edit', $user, $title )
280 ) {
281 return false;
282 }
283
284 foreach ( self::UNSUPPORTED_EDIT_PARAMS as $param ) {
285 if ( $req->getVal( $param ) !== null ) {
286 return false;
287 }
288 }
289
290 switch ( self::getEditPageEditor( $user, $req ) ) {
291 case 'visualeditor':
292 return self::isVisualAvailable( $title, $req, $user ) ||
293 self::isWikitextAvailable( $title, $user );
294 case 'wikitext':
295 default:
296 return self::isWikitextAvailable( $title, $user );
297 }
298 }
299
300 /**
301 * @param UserIdentity $user
302 * @return bool
303 */
304 private static function enabledForUser( UserIdentity $user ): bool {
305 $services = MediaWikiServices::getInstance();
306 $veConfig = $services->getConfigFactory()->makeConfig( 'visualeditor' );
307 $userOptionsLookup = $services->getUserOptionsLookup();
308 $isBeta = $veConfig->get( 'VisualEditorEnableBetaFeature' );
309
310 return ( $isBeta ?
311 $userOptionsLookup->getOption( $user, 'visualeditor-enable' ) :
312 !$userOptionsLookup->getOption( $user, 'visualeditor-betatempdisable' ) ) &&
313 !$userOptionsLookup->getOption( $user, 'visualeditor-autodisable' );
314 }
315
316 /**
317 * @param Title $title
318 * @param WebRequest $req
319 * @param UserIdentity $user
320 * @return bool
321 */
322 private static function isVisualAvailable( Title $title, WebRequest $req, UserIdentity $user ): bool {
323 $veConfig = MediaWikiServices::getInstance()->getConfigFactory()
324 ->makeConfig( 'visualeditor' );
325
326 return (
327 // If forced by the URL parameter, skip the namespace check (T221892) and preference check
328 ( $req->getVal( 'veaction' ) === 'edit' || (
329 // Only in enabled namespaces
330 ApiVisualEditor::isAllowedNamespace( $veConfig, $title->getNamespace() ) &&
331
332 // Enabled per user preferences
333 self::enabledForUser( $user )
334 ) ) &&
335 // Only for pages with a supported content model
336 ApiVisualEditor::isAllowedContentType( $veConfig, $title->getContentModel() )
337 );
338 }
339
340 /**
341 * @param Title $title
342 * @param UserIdentity $user
343 * @return bool
344 */
345 private static function isWikitextAvailable( Title $title, UserIdentity $user ): bool {
346 $services = MediaWikiServices::getInstance();
347 $userOptionsLookup = $services->getUserOptionsLookup();
348 return $userOptionsLookup->getOption( $user, 'visualeditor-newwikitext' ) &&
349 $title->getContentModel() === 'wikitext';
350 }
351
352 /**
353 * @param UserIdentity $user
354 * @param string $key
355 * @param string $value
356 */
357 private static function deferredSetUserOption( UserIdentity $user, string $key, string $value ): void {
358 DeferredUpdates::addCallableUpdate( static function () use ( $user, $key, $value ) {
359 $services = MediaWikiServices::getInstance();
360 if ( $services->getReadOnlyMode()->isReadOnly() ) {
361 return;
362 }
363 $userOptionsManager = $services->getUserOptionsManager();
364 $userOptionsManager->setOption( $user, $key, $value );
365 $userOptionsManager->saveOptions( $user );
366 } );
367 }
368
369 /**
370 * Decide whether to bother showing the wikitext editor at all.
371 * If not, we expect the VE initialisation JS to activate.
372 *
373 * @param Article $article The article being viewed.
374 * @param User $user The user-specific settings.
375 * @return bool Whether to show the wikitext editor or not.
376 */
377 public function onCustomEditor( $article, $user ) {
378 $req = $article->getContext()->getRequest();
379 $services = MediaWikiServices::getInstance();
380 $urlUtils = $services->getUrlUtils();
381 $veConfig = $services->getConfigFactory()->makeConfig( 'visualeditor' );
382
383 if ( ExtensionRegistry::getInstance()->isLoaded( 'MobileFrontend' ) ) {
384 // If mobilefrontend is involved it can make its own decisions about this
385 $mobFrontContext = MediaWikiServices::getInstance()->getService( 'MobileFrontend.Context' );
386 if ( $mobFrontContext->shouldDisplayMobileView() ) {
387 return true;
388 }
389 }
390
391 if ( !self::enabledForUser( $user ) ) {
392 return true;
393 }
394
395 $title = $article->getTitle();
396
397 if ( $req->getVal( 'venoscript' ) ) {
398 $req->response()->setCookie( 'VEE', 'wikitext', 0, [ 'prefix' => '' ] );
399 if ( $user->isNamed() ) {
400 self::deferredSetUserOption( $user, 'visualeditor-editor', 'wikitext' );
401 }
402 return true;
403 }
404
405 if ( self::isSupportedEditPage( $title, $user, $req ) ) {
406 $params = $req->getValues();
407 $params['venoscript'] = '1';
408 $url = wfScript() . '?' . wfArrayToCgi( $params );
409
410 $out = $article->getContext()->getOutput();
411 $titleMsg = $title->exists() ? 'editing' : 'creating';
412 $out->setPageTitleMsg( wfMessage( $titleMsg, $title->getPrefixedText() ) );
413 $out->showPendingTakeover( $url, 'visualeditor-toload', $urlUtils->expand( $url ) );
414
415 $out->setRevisionId( $req->getInt( 'oldid', $article->getRevIdFetched() ) );
416 return false;
417 }
418 return true;
419 }
420
421 /**
422 * @param User $user
423 * @param WebRequest $req
424 * @return string 'wikitext' or 'visual'
425 */
426 private static function getEditPageEditor( User $user, WebRequest $req ): string {
427 $config = MediaWikiServices::getInstance()->getConfigFactory()
428 ->makeConfig( 'visualeditor' );
429 if ( $config->get( 'VisualEditorDisableForAnons' ) && !$user->isRegistered() ) {
430 return 'wikitext';
431 }
432 $isRedLink = $req->getBool( 'redlink' );
433 // On dual-edit-tab wikis, the edit page must mean the user wants wikitext,
434 // unless following a redlink
435 if ( !$config->get( 'VisualEditorUseSingleEditTab' ) && !$isRedLink ) {
436 return 'wikitext';
437 }
438 return self::getPreferredEditor( $user, $req, !$isRedLink );
439 }
440
441 /**
442 * @param User $user
443 * @param WebRequest $req
444 * @param bool $useWikitextInMultiTab
445 * @return string 'wikitext' or 'visual'
446 */
447 public static function getPreferredEditor(
448 User $user, WebRequest $req, bool $useWikitextInMultiTab = false
449 ): string {
450 // VisualEditor shouldn't even call this method when it's disabled, but it is a public API for
451 // other extensions (e.g. DiscussionTools), and the editor preferences might have surprising
452 // values if the user has tried VisualEditor in the past and then disabled it. (T257234)
453 if ( !self::enabledForUser( $user ) ) {
454 return 'wikitext';
455 }
456
457 $services = MediaWikiServices::getInstance();
458 $userOptionsLookup = $services->getUserOptionsLookup();
459
460 switch ( $userOptionsLookup->getOption( $user, 'visualeditor-tabs' ) ) {
461 case 'prefer-ve':
462 return 'visualeditor';
463 case 'prefer-wt':
464 return 'wikitext';
465 case 'multi-tab':
466 // May have got here by switching from VE
467 // TODO: Make such an action explicitly request wikitext
468 // so we can use getLastEditor here instead.
469 return $useWikitextInMultiTab ?
470 'wikitext' :
471 self::getLastEditor( $user, $req );
472 case 'remember-last':
473 default:
474 return self::getLastEditor( $user, $req );
475 }
476 }
477
478 /**
479 * @param User $user
480 * @param WebRequest $req
481 * @return string
482 */
483 private static function getLastEditor( User $user, WebRequest $req ): string {
484 // This logic matches getLastEditor in:
485 // modules/ve-mw/init/targets/ve.init.mw.DesktopArticleTarget.init.js
486 $editor = $req->getCookie( 'VEE', '' );
487 // Set editor to user's preference or site's default (ignore the cookie) if …
488 if (
489 // … user is logged in,
490 $user->isNamed() ||
491 // … no cookie is set, or
492 !$editor ||
493 // value is invalid.
494 !( $editor === 'visualeditor' || $editor === 'wikitext' )
495 ) {
496 $services = MediaWikiServices::getInstance();
497 $userOptionsLookup = $services->getUserOptionsLookup();
498 $editor = $userOptionsLookup->getOption( $user, 'visualeditor-editor' );
499 }
500 return $editor;
501 }
502
503 /**
504 * Changes the Edit tab and adds the VisualEditor tab.
505 *
506 * This is attached to the MediaWiki 'SkinTemplateNavigation::Universal' hook.
507 *
508 * @param SkinTemplate $skin The skin template on which the UI is built.
509 * @param array &$links Navigation links.
510 */
511 public function onSkinTemplateNavigation__Universal( $skin, &$links ): void {
512 $services = MediaWikiServices::getInstance();
513 $userOptionsLookup = $services->getUserOptionsLookup();
514 $config = $services->getConfigFactory()
515 ->makeConfig( 'visualeditor' );
516
517 self::onSkinTemplateNavigationSpecialPage( $skin, $links );
518
519 if (
520 ExtensionRegistry::getInstance()->isLoaded( 'MobileFrontend' ) &&
521 $services->getService( 'MobileFrontend.Context' )->shouldDisplayMobileView()
522 ) {
523 return;
524 }
525
526 // Exit if there's no edit link for whatever reason (e.g. protected page)
527 if ( !isset( $links['views']['edit'] ) ) {
528 return;
529 }
530
531 $hookRunner = new VisualEditorHookRunner( $services->getHookContainer() );
532 if ( !$hookRunner->onVisualEditorBeforeEditor( $skin->getOutput(), $skin ) ) {
533 return;
534 }
535
536 $user = $skin->getUser();
537 if (
538 $config->get( 'VisualEditorUseSingleEditTab' ) &&
539 $userOptionsLookup->getOption( $user, 'visualeditor-tabs' ) === 'prefer-wt'
540 ) {
541 return;
542 }
543
544 if (
545 $config->get( 'VisualEditorUseSingleEditTab' ) &&
546 wfTimestampNow() < $config->get( 'VisualEditorSingleEditTabSwitchTimeEnd' ) &&
547 $user->isNamed() &&
548 self::enabledForUser( $user ) &&
549 !$userOptionsLookup->getOption( $user, 'visualeditor-hidetabdialog' ) &&
550 $userOptionsLookup->getOption( $user, 'visualeditor-tabs' ) === 'remember-last'
551 ) {
552 // Check if the user has made any edits before the SET switch time
553 $dbr = $services->getConnectionProvider()->getReplicaDatabase();
554 $revExists = $dbr->newSelectQueryBuilder()
555 ->from( 'revision' )
556 ->field( '1' )
557 ->where( [
558 'rev_actor' => $user->getActorId(),
559 $dbr->expr( 'rev_timestamp', '<', $dbr->timestamp(
560 $config->get( 'VisualEditorSingleEditTabSwitchTime' )
561 ) )
562 ] )
563 ->caller( __METHOD__ )
564 ->fetchField();
565 if ( $revExists ) {
566 $links['views']['edit']['class'] .= ' visualeditor-showtabdialog';
567 }
568 }
569
570 // Exit if the user doesn't have VE enabled
571 if (
572 !self::enabledForUser( $user ) ||
573 // T253941: This option does not actually disable the editor, only leaves the tabs/links unchanged
574 ( $config->get( 'VisualEditorDisableForAnons' ) && !$user->isRegistered() )
575 ) {
576 return;
577 }
578
579 $title = $skin->getRelevantTitle();
580 // Don't exit if this page isn't VE-enabled, since we should still
581 // change "Edit" to "Edit source".
582 $isAvailable = self::isVisualAvailable( $title, $skin->getRequest(), $user );
583
584 $tabMessages = $config->get( 'VisualEditorTabMessages' );
585 // Rebuild the $links['views'] array and inject the VisualEditor tab before or after
586 // the edit tab as appropriate. We have to rebuild the array because PHP doesn't allow
587 // us to splice into the middle of an associative array.
588 $newViews = [];
589 $wikiPageFactory = $services->getWikiPageFactory();
590 $isRemote = !$wikiPageFactory->newFromTitle( $title )->isLocal();
591
592 $skinHasEditIcons = in_array(
593 $skin->getSkinName(),
594 ExtensionRegistry::getInstance()->getAttribute( 'VisualEditorIconSkins' )
595 );
596
597 foreach ( $links['views'] as $action => $data ) {
598 if ( $action === 'edit' ) {
599 // Build the VisualEditor tab
600 $existing = $title->exists() || (
601 $title->inNamespace( NS_MEDIAWIKI ) &&
602 $title->getDefaultMessageText() !== false
603 );
604 $action = $existing ? 'edit' : 'create';
605 $veParams = $skin->editUrlOptions();
606 // Remove action=edit
607 unset( $veParams['action'] );
608 // Set veaction=edit
609 $veParams['veaction'] = 'edit';
610 $veTabMessage = $tabMessages[$action];
611 $veTabText = $veTabMessage === null ? $data['text'] :
612 $skin->msg( $veTabMessage )->text();
613 if ( $isRemote ) {
614 // The following messages can be used here:
615 // * tooltip-ca-ve-edit-local
616 // * tooltip-ca-ve-create-local
617 // The following messages can be generated upstream:
618 // * accesskey-ca-ve-edit-local
619 // * accesskey-ca-ve-create-local
620 $veTooltip = 'ca-ve-' . $action . '-local';
621 } else {
622 // The following messages can be used here:
623 // * tooltip-ca-ve-edit
624 // * tooltip-ca-ve-create
625 // The following messages can be generated upstream:
626 // * accesskey-ca-ve-edit
627 // * accesskey-ca-ve-create
628 $veTooltip = 'ca-ve-' . $action;
629 }
630 $veTab = [
631 'href' => $title->getLocalURL( $veParams ),
632 'text' => $veTabText,
633 'single-id' => $veTooltip,
634 'primary' => true,
635 'icon' => $skinHasEditIcons ? 'edit' : null,
636 'class' => '',
637 ];
638
639 // Alter the edit tab
640 $editTab = $data;
641 if ( $isRemote ) {
642 // The following messages can be used here:
643 // * visualeditor-ca-editlocaldescriptionsource
644 // * visualeditor-ca-createlocaldescriptionsource
645 $editTabMessage = $tabMessages[$action . 'localdescriptionsource'];
646 // The following messages can be used here:
647 // * tooltip-ca-editsource-local
648 // * tooltip-ca-createsource-local
649 // The following messages can be generated upstream:
650 // * accesskey-ca-editsource-local
651 // * accesskey-ca-createsource-local
652 $editTabTooltip = 'ca-' . $action . 'source-local';
653 } else {
654 // The following messages can be used here:
655 // * visualeditor-ca-editsource
656 // * visualeditor-ca-createsource
657 $editTabMessage = $tabMessages[$action . 'source'];
658 // The following messages can be used here:
659 // * tooltip-ca-editsource
660 // * tooltip-ca-createsource
661 // The following messages can be generated upstream:
662 // * accesskey-ca-editsource
663 // * accesskey-ca-createsource
664 $editTabTooltip = 'ca-' . $action . 'source';
665 }
666
667 if ( $editTabMessage !== null ) {
668 $editTab['text'] = $skin->msg( $editTabMessage )->text();
669 $editTab['single-id'] = $editTabTooltip;
670 }
671
672 $editor = self::getLastEditor( $user, $skin->getRequest() );
673 if (
674 $isAvailable &&
675 $config->get( 'VisualEditorUseSingleEditTab' ) &&
676 (
677 $userOptionsLookup->getOption( $user, 'visualeditor-tabs' ) === 'prefer-ve' ||
678 (
679 $userOptionsLookup->getOption( $user, 'visualeditor-tabs' ) === 'remember-last' &&
680 $editor === 'visualeditor'
681 )
682 )
683 ) {
684 $editTab['text'] = $veTabText;
685 $newViews['edit'] = $editTab;
686 } elseif (
687 $isAvailable &&
688 (
689 !$config->get( 'VisualEditorUseSingleEditTab' ) ||
690 $userOptionsLookup->getOption( $user, 'visualeditor-tabs' ) === 'multi-tab'
691 )
692 ) {
693 // Change icon
694 $editTab['icon'] = $skinHasEditIcons ? 'wikiText' : null;
695 // Inject the VE tab before or after the edit tab
696 if ( $config->get( 'VisualEditorTabPosition' ) === 'before' ) {
697 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
698 $editTab['class'] .= ' collapsible';
699 $newViews['ve-edit'] = $veTab;
700 $newViews['edit'] = $editTab;
701 } else {
702 $veTab['class'] .= ' collapsible';
703 $newViews['edit'] = $editTab;
704 $newViews['ve-edit'] = $veTab;
705 }
706 } elseif (
707 !$config->get( 'VisualEditorUseSingleEditTab' ) ||
708 !$isAvailable ||
709 $userOptionsLookup->getOption( $user, 'visualeditor-tabs' ) === 'multi-tab' ||
710 (
711 $userOptionsLookup->getOption( $user, 'visualeditor-tabs' ) === 'remember-last' &&
712 $editor === 'wikitext'
713 )
714 ) {
715 // Don't add ve-edit, but do update the edit tab (e.g. "Edit source").
716 $newViews['edit'] = $editTab;
717 } else {
718 // This should not happen.
719 }
720 } else {
721 // Just pass through
722 $newViews[$action] = $data;
723 }
724 }
725 $links['views'] = $newViews;
726 }
727
728 /**
729 * @param SkinTemplate $skin The skin template on which the UI is built.
730 * @param array &$links Navigation links.
731 */
732 private static function onSkinTemplateNavigationSpecialPage( SkinTemplate $skin, array &$links ) {
733 $title = $skin->getTitle();
734 if ( !$title || !$title->isSpecialPage() ) {
735 return;
736 }
737 [ $special, $subPage ] = MediaWikiServices::getInstance()->getSpecialPageFactory()
738 ->resolveAlias( $title->getDBkey() );
739 if ( $special !== 'CollabPad' ) {
740 return;
741 }
742 $links['namespaces']['special']['text'] = $skin->msg( 'collabpad' )->text();
743 $subPageTitle = Title::newFromText( $subPage );
744 if ( $subPageTitle ) {
745 $links['namespaces']['special']['href'] = SpecialPage::getTitleFor( $special )->getLocalURL();
746 $links['namespaces']['special']['class'] = '';
747
748 $links['namespaces']['pad']['text'] = $subPageTitle->getPrefixedText();
749 $links['namespaces']['pad']['href'] = '';
750 $links['namespaces']['pad']['class'] = 'selected';
751 }
752 }
753
754 /**
755 * Called when the normal wikitext editor is shown.
756 * Inserts a 'veswitched' hidden field if requested by the client
757 *
758 * @param EditPage $editPage The edit page view.
759 * @param OutputPage $output The page view.
760 */
761 public function onEditPage__showEditForm_fields( $editPage, $output ) {
762 $request = $output->getRequest();
763 if ( $request->getBool( 'veswitched' ) ) {
764 $output->addHTML( Html::hidden( 'veswitched', '1' ) );
765 }
766 }
767
768 /**
769 * Called when an edit is saved
770 * Adds 'visualeditor-switched' tag to the edit if requested
771 * Adds whatever tags from static::TAGS are present in the vetags parameter
772 *
773 * @param RecentChange $rc The new RC entry.
774 */
775 public function onRecentChange_Save( $rc ) {
776 $request = RequestContext::getMain()->getRequest();
777 if ( $request->getBool( 'veswitched' ) && $rc->getAttribute( 'rc_this_oldid' ) ) {
778 $rc->addTags( 'visualeditor-switched' );
779 }
780
781 $tags = explode( ',', $request->getVal( 'vetags' ) ?? '' );
782 $tags = array_values( array_intersect( $tags, static::TAGS ) );
783 if ( $tags ) {
784 $rc->addTags( $tags );
785 }
786 }
787
788 /**
789 * Changes the section edit links to add a VE edit link.
790 *
791 * This is attached to the MediaWiki 'SkinEditSectionLinks' hook.
792 *
793 * @param Skin $skin Skin being used to render the UI
794 * @param Title $title Title being used for request
795 * @param string $section The name of the section being pointed to.
796 * @param string $tooltip The default tooltip.
797 * @param array &$result All link detail arrays.
798 * @phan-param array{editsection:array{text:string,targetTitle:Title,attribs:array,query:array}} $result
799 * @param Language $lang The user interface language.
800 */
801 public function onSkinEditSectionLinks( $skin, $title, $section,
802 $tooltip, &$result, $lang
803 ) {
804 $services = MediaWikiServices::getInstance();
805 $userOptionsLookup = $services->getUserOptionsLookup();
806 $config = $services->getConfigFactory()
807 ->makeConfig( 'visualeditor' );
808
809 // Exit if we're in parserTests
810 if ( isset( $GLOBALS[ 'wgVisualEditorInParserTests' ] ) ) {
811 return;
812 }
813
814 if (
815 ExtensionRegistry::getInstance()->isLoaded( 'MobileFrontend' ) &&
816 $services->getService( 'MobileFrontend.Context' )->shouldDisplayMobileView()
817 ) {
818 return;
819 }
820
821 $user = $skin->getUser();
822 // Exit if the user doesn't have VE enabled
823 if (
824 !self::enabledForUser( $user ) ||
825 // T253941: This option does not actually disable the editor, only leaves the tabs/links unchanged
826 ( $config->get( 'VisualEditorDisableForAnons' ) && !$user->isRegistered() )
827 ) {
828 return;
829 }
830
831 // Exit if we're on a foreign file description page
832 if (
833 $title->inNamespace( NS_FILE ) &&
834 !$services->getWikiPageFactory()->newFromTitle( $title )->isLocal()
835 ) {
836 return;
837 }
838
839 $editor = self::getLastEditor( $user, $skin->getRequest() );
840 if (
841 !$config->get( 'VisualEditorUseSingleEditTab' ) ||
842 $userOptionsLookup->getOption( $user, 'visualeditor-tabs' ) === 'multi-tab' ||
843 (
844 $userOptionsLookup->getOption( $user, 'visualeditor-tabs' ) === 'remember-last' &&
845 $editor === 'wikitext'
846 )
847 ) {
848 // Don't add ve-edit, but do update the edit tab (e.g. "Edit source").
849 $tabMessages = $config->get( 'VisualEditorTabMessages' );
850 // The following messages can be used here:
851 // * visualeditor-ca-editsource-section
852 $sourceEditSection = $tabMessages['editsectionsource'];
853 $result['editsection']['text'] = $skin->msg( $sourceEditSection )->inLanguage( $lang )->text();
854 // The following messages can be used here:
855 // * visualeditor-ca-editsource-section-hint
856 $sourceEditSectionHint = $tabMessages['editsectionsourcehint'];
857 $result['editsection']['attribs']['title'] = $skin->msg( $sourceEditSectionHint )
858 ->plaintextParams( $tooltip )
859 ->inLanguage( $lang )->text();
860 }
861
862 // Exit if we're using the single edit tab.
863 if (
864 $config->get( 'VisualEditorUseSingleEditTab' ) &&
865 $userOptionsLookup->getOption( $user, 'visualeditor-tabs' ) !== 'multi-tab'
866 ) {
867 return;
868 }
869
870 $skinHasEditIcons = in_array(
871 $skin->getSkinName(),
872 ExtensionRegistry::getInstance()->getAttribute( 'VisualEditorIconSkins' )
873 );
874
875 // add VE edit section in VE available namespaces
876 if ( self::isVisualAvailable( $title, $skin->getRequest(), $user ) ) {
877 // The following messages can be used here:
878 // * editsection
879 $veEditSection = $tabMessages['editsection'];
880 // The following messages can be used here:
881 // * editsectionhint
882 $veEditSectionHint = $tabMessages['editsectionhint'];
883
884 $attribs = $result['editsection']['attribs'];
885 // class goes to SkinComponentLink which will accept a string or
886 // an array, and either might be provided at this point.
887 $class = $attribs['class'] ?? '';
888 if ( is_array( $class ) ) {
889 $class[] = 'mw-editsection-visualeditor';
890 } else {
891 $class .= ' mw-editsection-visualeditor';
892 }
893 $attribs['class'] = $class;
894 $attribs['title'] = $skin->msg( $veEditSectionHint )
895 ->plaintextParams( $tooltip )
896 ->inLanguage( $lang )->text();
897
898 $veLink = [
899 'text' => $skin->msg( $veEditSection )->inLanguage( $lang )->text(),
900 'icon' => $skinHasEditIcons ? 'edit' : null,
901 'targetTitle' => $title,
902 'attribs' => $attribs,
903 'query' => [ 'veaction' => 'edit', 'section' => $section ],
904 'options' => [ 'noclasses', 'known' ]
905 ];
906 // Change icon
907 $result['editsection']['icon'] = $skinHasEditIcons ? 'wikiText' : null;
908
909 $result['veeditsection'] = $veLink;
910 if ( $config->get( 'VisualEditorTabPosition' ) === 'before' ) {
911 krsort( $result );
912 // TODO: This will probably cause weird ordering if any other extensions added something
913 // already.
914 // ... wfArrayInsertBefore?
915 }
916 }
917 }
918
919 /**
920 * @param OutputPage $out
921 * @param Skin $sk
922 * @param string[] &$bodyAttrs
923 */
924 public function onOutputPageBodyAttributes( $out, $sk, &$bodyAttrs ): void {
925 $specialTitle = $sk->getTitle();
926
927 // HACK: Replace classes generated by Skin::getPageClasses as if an article title
928 // was passed in, instead of a special page.
929 if ( $specialTitle && $specialTitle->isSpecial( 'CollabPad' ) ) {
930 $articleTitle = Title::newFromText( 'DummyPage' );
931
932 $specialClasses = $sk->getPageClasses( $specialTitle );
933 $articleClasses = $sk->getPageClasses( $articleTitle );
934
935 $bodyAttrs['class'] = str_replace( $specialClasses, $articleClasses, $bodyAttrs['class'] );
936 }
937 }
938
939 /**
940 * Handler for the GetPreferences hook, to add and hide user preferences as configured
941 *
942 * @param User $user
943 * @param array &$preferences Their preferences object
944 */
945 public function onGetPreferences( $user, &$preferences ) {
946 $services = MediaWikiServices::getInstance();
947 $userOptionsLookup = $services->getUserOptionsLookup();
948 $veConfig = $services->getConfigFactory()->makeConfig( 'visualeditor' );
949 $isBeta = $veConfig->get( 'VisualEditorEnableBetaFeature' );
950
951 // Use the old preference keys to avoid having to migrate data for now.
952 // (One day we might write and run a maintenance script to update the
953 // entries in the database and make this unnecessary.) (T344762)
954 if ( $isBeta ) {
955 $preferences['visualeditor-enable'] = [
956 'type' => 'toggle',
957 'label-message' => 'visualeditor-preference-visualeditor',
958 'section' => 'editing/editor',
959 ];
960 } else {
961 $preferences['visualeditor-betatempdisable'] = [
962 'invert' => true,
963 'type' => 'toggle',
964 'label-message' => 'visualeditor-preference-visualeditor',
965 'section' => 'editing/editor',
966 'default' => $userOptionsLookup->getOption( $user, 'visualeditor-betatempdisable' ) ||
967 $userOptionsLookup->getOption( $user, 'visualeditor-autodisable' )
968 ];
969 }
970
971 if ( $veConfig->get( 'VisualEditorEnableWikitext' ) ) {
972 $preferences['visualeditor-newwikitext'] = [
973 'type' => 'toggle',
974 'label-message' => 'visualeditor-preference-newwikitexteditor-enable',
975 'help-message' => 'visualeditor-preference-newwikitexteditor-help',
976 'section' => 'editing/editor'
977 ];
978 }
979
980 // Config option for Single Edit Tab
981 if (
982 $veConfig->get( 'VisualEditorUseSingleEditTab' ) &&
983 self::enabledForUser( $user )
984 ) {
985 $preferences['visualeditor-tabs'] = [
986 'type' => 'select',
987 'label-message' => 'visualeditor-preference-tabs',
988 'section' => 'editing/editor',
989 'options-messages' => [
990 'visualeditor-preference-tabs-remember-last' => 'remember-last',
991 'visualeditor-preference-tabs-prefer-ve' => 'prefer-ve',
992 'visualeditor-preference-tabs-prefer-wt' => 'prefer-wt',
993 'visualeditor-preference-tabs-multi-tab' => 'multi-tab'
994 ]
995 ];
996 }
997
998 $api = [ 'type' => 'api' ];
999 // The "autodisable" preference records whether the user has explicitly opted out of VE.
1000 // This is saved even when VE is off by default, which allows changing it to be on by default
1001 // without affecting the users who opted out. There's also a maintenance script to silently
1002 // opt-out existing users en masse before changing the default, thus only affecting new users.
1003 // (This option is no longer set to 'true' anywhere, but we can still encounter old true
1004 // values until they are migrated: T344760.)
1005 $preferences['visualeditor-autodisable'] = $api;
1006 // The diff mode is persisted for each editor mode separately,
1007 // e.g. use visual diffs for visual mode only.
1008 $preferences['visualeditor-diffmode-source'] = $api;
1009 $preferences['visualeditor-diffmode-visual'] = $api;
1010 $preferences['visualeditor-diffmode-historical'] = $api;
1011 $preferences['visualeditor-editor'] = $api;
1012 $preferences['visualeditor-hidebetawelcome'] = $api;
1013 $preferences['visualeditor-hidetabdialog'] = $api;
1014 $preferences['visualeditor-hidesourceswitchpopup'] = $api;
1015 $preferences['visualeditor-hidevisualswitchpopup'] = $api;
1016 $preferences['visualeditor-hideusered'] = $api;
1017 $preferences['visualeditor-findAndReplace-diacritic'] = $api;
1018 $preferences['visualeditor-findAndReplace-findText'] = $api;
1019 $preferences['visualeditor-findAndReplace-replaceText'] = $api;
1020 $preferences['visualeditor-findAndReplace-regex'] = $api;
1021 $preferences['visualeditor-findAndReplace-matchCase'] = $api;
1022 $preferences['visualeditor-findAndReplace-word'] = $api;
1023 }
1024
1025 /**
1026 * Implements the PreferencesFormPreSave hook, to remove the 'autodisable' flag
1027 * when the user it was set on explicitly enables VE.
1028 *
1029 * @param array $data User-submitted data
1030 * @param HTMLForm $form A ContextSource
1031 * @param User $user User with new preferences already set
1032 * @param bool &$result Success or failure
1033 * @param array $oldUserOptions
1034 */
1035 public function onPreferencesFormPreSave( $data, $form, $user, &$result, $oldUserOptions ) {
1036 $services = MediaWikiServices::getInstance();
1037 $veConfig = $services->getConfigFactory()->makeConfig( 'visualeditor' );
1038 $userOptionsManager = $services->getUserOptionsManager();
1039 $isBeta = $veConfig->get( 'VisualEditorEnableBetaFeature' );
1040
1041 // The "autodisable" preference records whether the user has explicitly opted out of VE
1042 // while it was in beta (which would otherwise not be saved, since it's the same as default).
1043
1044 if (
1045 // When the user enables VE, clear the preference.
1046 $userOptionsManager->getOption( $user, 'visualeditor-autodisable' ) &&
1047 ( $isBeta ?
1048 $userOptionsManager->getOption( $user, 'visualeditor-enable' ) :
1049 !$userOptionsManager->getOption( $user, 'visualeditor-betatempdisable' ) )
1050 ) {
1051 $userOptionsManager->setOption( $user, 'visualeditor-autodisable', false );
1052 }
1053 }
1054
1055 /**
1056 * @param array &$tags
1057 */
1058 public function onChangeTagsListActive( &$tags ) {
1059 $this->onListDefinedTags( $tags );
1060 }
1061
1062 /**
1063 * Implements the ListDefinedTags and ChangeTagsListActive hooks, to
1064 * populate core Special:Tags with the change tags in use by VisualEditor.
1065 *
1066 * @param array &$tags Available change tags.
1067 */
1068 public function onListDefinedTags( &$tags ) {
1069 $tags = array_merge( $tags, static::TAGS );
1070 }
1071
1072 /**
1073 * Adds extra variables to the page config.
1074 *
1075 * @param array &$vars Global variables object
1076 * @param OutputPage $out The page view.
1077 */
1078 public function onMakeGlobalVariablesScript( &$vars, $out ): void {
1079 $pageLanguage = ApiVisualEditor::getPageLanguage( $out->getTitle() );
1080 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
1081 ->getLanguageConverter( $pageLanguage );
1082
1083 $fallbacks = $converter->getVariantFallbacks( $converter->getPreferredVariant() );
1084
1085 $vars['wgVisualEditor'] = [
1086 'pageLanguageCode' => $pageLanguage->getHtmlCode(),
1087 'pageLanguageDir' => $pageLanguage->getDir(),
1088 'pageVariantFallbacks' => $fallbacks,
1089 ];
1090 }
1091
1092 /**
1093 * Adds extra variables to the global config
1094 *
1095 * @param array &$vars Global variables object
1096 * @param string $skin
1097 * @param Config $config
1098 */
1099 public function onResourceLoaderGetConfigVars( array &$vars, $skin, Config $config ): void {
1100 $coreConfig = RequestContext::getMain()->getConfig();
1101 $services = MediaWikiServices::getInstance();
1102 $veConfig = $services->getConfigFactory()->makeConfig( 'visualeditor' );
1103 $extensionRegistry = ExtensionRegistry::getInstance();
1104 $availableNamespaces = ApiVisualEditor::getAvailableNamespaceIds( $veConfig );
1105 $availableContentModels = array_filter(
1106 array_merge(
1107 $extensionRegistry->getAttribute( 'VisualEditorAvailableContentModels' ),
1108 $veConfig->get( 'VisualEditorAvailableContentModels' )
1109 )
1110 );
1111
1112 $namespacesWithSubpages = $coreConfig->get( 'NamespacesWithSubpages' );
1113 // Export as a list of namespaces where subpages are enabled instead of an object
1114 // mapping namespaces to if subpages are enabled or not, so filter out disabled
1115 // namespaces and then just use the keys. See T291729.
1116 $namespacesWithSubpages = array_filter( $namespacesWithSubpages );
1117 $namespacesWithSubpagesEnabled = array_keys( $namespacesWithSubpages );
1118 // $wgNamespacesWithSubpages can include namespaces that don't exist, no need
1119 // to include those in the JavaScript data. See T291727.
1120 // Run this filtering after the filter for subpages being enabled, to reduce
1121 // the number of calls needed to namespace info.
1122 $nsInfo = $services->getNamespaceInfo();
1123 $namespacesWithSubpagesEnabled = array_values( array_filter(
1124 $namespacesWithSubpagesEnabled,
1125 [ $nsInfo, 'exists' ]
1126 ) );
1127
1128 $defaultSortPrefix = $services->getMagicWordFactory()->get( 'defaultsort' )->getSynonym( 0 );
1129 // Sanitize trailing colon. /languages/messages/*.php are not consistent but the
1130 // presence or absence of a trailing colon in the message makes no difference.
1131 $defaultSortPrefix = preg_replace( '/:$/', '', $defaultSortPrefix );
1132
1133 $vars['wgVisualEditorConfig'] = [
1134 'usePageImages' => $extensionRegistry->isLoaded( 'PageImages' ),
1135 'usePageDescriptions' => $extensionRegistry->isLoaded( 'WikibaseClient' ),
1136 'isBeta' => $veConfig->get( 'VisualEditorEnableBetaFeature' ),
1137 'disableForAnons' => $veConfig->get( 'VisualEditorDisableForAnons' ),
1138 'preloadModules' => $veConfig->get( 'VisualEditorPreloadModules' ),
1139 'namespaces' => $availableNamespaces,
1140 'contentModels' => $availableContentModels,
1141 'pluginModules' => array_merge(
1142 $extensionRegistry->getAttribute( 'VisualEditorPluginModules' ),
1143 // @todo deprecate the global setting
1144 $veConfig->get( 'VisualEditorPluginModules' )
1145 ),
1146 'thumbLimits' => $coreConfig->get( 'ThumbLimits' ),
1147 'galleryOptions' => $coreConfig->get( 'GalleryOptions' ),
1148 'tabPosition' => $veConfig->get( 'VisualEditorTabPosition' ),
1149 'tabMessages' => array_filter( $veConfig->get( 'VisualEditorTabMessages' ) ),
1150 'singleEditTab' => $veConfig->get( 'VisualEditorUseSingleEditTab' ),
1151 'enableVisualSectionEditing' => $veConfig->get( 'VisualEditorEnableVisualSectionEditing' ),
1152 'showBetaWelcome' => $veConfig->get( 'VisualEditorShowBetaWelcome' ),
1153 'allowExternalLinkPaste' => $veConfig->get( 'VisualEditorAllowExternalLinkPaste' ),
1154 'enableHelpCompletion' => $veConfig->get( 'VisualEditorEnableHelpCompletion' ),
1155 'enableTocWidget' => $veConfig->get( 'VisualEditorEnableTocWidget' ),
1156 'enableWikitext' => $veConfig->get( 'VisualEditorEnableWikitext' ),
1157 'useChangeTagging' => $veConfig->get( 'VisualEditorUseChangeTagging' ),
1158 'editCheckTagging' => $veConfig->get( 'VisualEditorEditCheckTagging' ),
1159 'editCheck' => $veConfig->get( 'VisualEditorEditCheck' ),
1160 'editCheckABTest' => $veConfig->get( 'VisualEditorEditCheckABTest' ),
1161 'editCheckReliabilityAvailable' => ApiEditCheckReferenceUrl::isAvailable(),
1162 'namespacesWithSubpages' => $namespacesWithSubpagesEnabled,
1163 'specialBooksources' => urldecode( SpecialPage::getTitleFor( 'Booksources' )->getPrefixedURL() ),
1164 'rebaserUrl' => $coreConfig->get( 'VisualEditorRebaserURL' ),
1165 'feedbackApiUrl' => $veConfig->get( 'VisualEditorFeedbackAPIURL' ),
1166 'feedbackTitle' => $veConfig->get( 'VisualEditorFeedbackTitle' ),
1167 'sourceFeedbackTitle' => $veConfig->get( 'VisualEditorSourceFeedbackTitle' ),
1168 // TODO: Remove when all usages in .js files are removed
1169 'transclusionDialogNewSidebar' => true,
1170 'cirrusSearchLookup' => $extensionRegistry->isLoaded( 'CirrusSearch' ),
1171 'defaultSortPrefix' => $defaultSortPrefix,
1172 ];
1173 }
1174
1175 /**
1176 * Conditionally register the jquery.uls.data and jquery.i18n modules, in case they've already
1177 * been registered by the UniversalLanguageSelector extension or the TemplateData extension.
1178 *
1179 * @param ResourceLoader $resourceLoader Client-side code and assets to be loaded.
1180 */
1181 public function onResourceLoaderRegisterModules( ResourceLoader $resourceLoader ): void {
1182 $veResourceTemplate = [
1183 'localBasePath' => dirname( __DIR__ ),
1184 'remoteExtPath' => 'VisualEditor',
1185 ];
1186
1187 // Only register VisualEditor core's local version of jquery.uls.data if it hasn't been
1188 // installed locally already (presumably, by the UniversalLanguageSelector extension).
1189 if ( !$resourceLoader->isModuleRegistered( 'jquery.uls.data' ) ) {
1190 $resourceLoader->register( [
1191 'jquery.uls.data' => $veResourceTemplate + [
1192 'scripts' => [
1193 'lib/ve/lib/jquery.uls/src/jquery.uls.data.js',
1194 'lib/ve/lib/jquery.uls/src/jquery.uls.data.utils.js',
1195 ],
1196 ] ] );
1197 }
1198 }
1199
1200 /**
1201 * Ensures that we know whether we're running inside a parser test.
1202 *
1203 * @param array &$settings The settings with which MediaWiki is being run.
1204 */
1205 public function onParserTestGlobals( &$settings ) {
1206 $settings['wgVisualEditorInParserTests'] = true;
1207 }
1208
1209 /**
1210 * @param array &$redirectParams Parameters preserved on special page redirects
1211 * to wiki pages
1212 */
1213 public function onRedirectSpecialArticleRedirectParams( &$redirectParams ) {
1214 $redirectParams[] = 'veaction';
1215 }
1216
1217 /**
1218 * If the user has specified that they want to edit the page with VE, suppress any redirect.
1219 *
1220 * @param Title $title Title being used for request
1221 * @param Article|null $article The page being viewed.
1222 * @param OutputPage $output The page view.
1223 * @param User $user The user-specific settings.
1224 * @param WebRequest $request
1225 * @param ActionEntryPoint $mediaWiki Helper class.
1226 */
1227 public function onBeforeInitialize(
1228 $title, $article, $output, $user, $request, $mediaWiki
1229 ) {
1230 if ( $request->getVal( 'veaction' ) ) {
1231 $request->setVal( 'redirect', 'no' );
1232 }
1233 }
1234
1235 /**
1236 * On login, if user has a VEE cookie, set their preference equal to it.
1237 *
1238 * @param User $user The user-specific settings.
1239 */
1240 public function onUserLoggedIn( $user ) {
1241 $cookie = RequestContext::getMain()->getRequest()->getCookie( 'VEE', '' );
1242 if ( $user->isNamed() && ( $cookie === 'visualeditor' || $cookie === 'wikitext' ) ) {
1243 self::deferredSetUserOption( $user, 'visualeditor-editor', $cookie );
1244 }
1245 }
1246 }