forked from WordPress/wordpress-develop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnectors.php
More file actions
818 lines (754 loc) · 27.8 KB
/
connectors.php
File metadata and controls
818 lines (754 loc) · 27.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
<?php
/**
* Connectors API: core functions for registering and managing connectors.
*
* The Connectors API provides a unified framework for registering and managing
* external service integrations within WordPress. A "connector" represents a
* connection to an external service — currently focused on AI providers — with
* standardized metadata, authentication configuration, and plugin association.
*
* ## Overview
*
* The Connectors API enables developers to:
*
* - Register AI provider connectors with standardized interfaces.
* - Define authentication methods and credential sources.
* - Associate connectors with WordPress.org plugins for install/activate UI.
* - Expose connector settings through the REST API with automatic key masking.
*
* ## AI Provider Plugins
*
* AI provider plugins that register with the WP AI Client's `ProviderRegistry`
* get automatic connector integration — no explicit connector registration is
* needed. The system discovers providers from the WP AI Client registry and
* creates connectors with the correct name, description, logo, authentication
* method, and setting name derived from the provider's configuration.
*
* The authentication method (`api_key` or `none`) is determined by the provider's
* metadata in the WP AI Client. For `api_key` providers, a `setting_name` is
* automatically generated following the same naming convention used for environment
* variables and PHP constants (e.g., provider `openai` maps to `OPENAI_API_KEY`
* for env/constant lookup).
*
* @see WordPress\AiClient\Providers\ProviderRegistry
*
* ## Admin UI Integration
*
* Registered `ai_provider` connectors appear on the Settings → Connectors
* admin screen. The screen renders each connector as a card using the
* registry data:
*
* - `name`, `description`, and `logo_url` are displayed on the card.
* - `plugin.slug` enables install/activate controls — the screen checks
* whether the plugin is installed and active, and shows the appropriate
* action button.
* - `authentication.credentials_url` is rendered as a link directing users
* to the provider's site to obtain API credentials.
* - For `api_key` connectors, the screen shows the current key source
* (environment variable, PHP constant, or database) and connection status.
*
* On the backend, `api_key` connectors also receive automatic settings
* registration via the Settings API (`show_in_rest`), API key masking in
* REST API responses, and key validation against the provider on update.
*
* Connectors with other authentication methods or types are registered in the PHP
* registry and exposed via the script module data, but require a client-side
* JavaScript registration for custom frontend UI. Support for additional
* authentication methods and connector types is planned for future releases.
*
* ## Custom Connectors
*
* The `wp_connectors_init` action hook allows plugins to override metadata on
* existing connectors. AI provider connectors are auto-discovered from the WP
* AI Client registry and should not be manually registered here.
*
* Example — overriding the description of an auto-discovered connector:
*
* add_action( 'wp_connectors_init', function ( WP_Connector_Registry $registry ) {
* if ( $registry->is_registered( 'openai' ) ) {
* $connector = $registry->unregister( 'openai' );
* $connector['description'] = __( 'Custom description for OpenAI.', 'my-plugin' );
* $registry->register( 'openai', $connector );
* }
* } );
*
* Non-AI-provider connector types are not yet fully supported. The PHP registry
* accepts any connector type, but only `ai_provider` connectors with `api_key`
* authentication receive automatic admin UI. Support for additional connector
* types with dedicated frontend integration is planned for future releases.
* When available, this action will be the primary hook for registering those
* new connector types.
*
* ## Initialization Lifecycle
*
* During `init`, the system:
*
* 1. Creates the `WP_Connector_Registry` singleton.
* 2. Registers built-in connectors (Anthropic, Google, OpenAI) with hardcoded defaults.
* 3. Auto-discovers providers from the WP AI Client registry and merges their
* metadata (name, description, logo, authentication) on top of defaults,
* with registry values taking precedence.
* 4. Fires the `wp_connectors_init` action so plugins can override metadata
* on existing connectors or register additional connectors.
* 5. Registers settings and passes stored API keys to the WP AI Client.
*
* ## Authentication
*
* Connectors support two authentication methods:
*
* - `api_key`: Requires an API key, which can be provided via environment variable,
* PHP constant, or the database (checked in that order).
* - `none`: No authentication required.
*
* API keys stored in the database are automatically masked in REST API responses
* and validated against the provider on update.
*
* @package WordPress
* @subpackage Connectors
* @since 7.0.0
*/
use WordPress\AiClient\AiClient;
use WordPress\AiClient\Providers\Http\DTO\ApiKeyRequestAuthentication;
/**
* Checks if a connector is registered.
*
* Example:
*
* if ( wp_is_connector_registered( 'openai' ) ) {
* // The OpenAI connector is available.
* }
*
* @since 7.0.0
*
* @see WP_Connector_Registry::is_registered()
* @see wp_get_connector()
* @see wp_get_connectors()
*
* @param string $id The connector identifier.
* @return bool True if the connector is registered, false otherwise.
*/
function wp_is_connector_registered( string $id ): bool {
$registry = WP_Connector_Registry::get_instance();
if ( null === $registry ) {
return false;
}
return $registry->is_registered( $id );
}
/**
* Retrieves a registered connector.
*
* Example:
*
* $connector = wp_get_connector( 'openai' );
* if ( $connector ) {
* echo $connector['name']; // 'OpenAI'
* }
*
* @since 7.0.0
*
* @see WP_Connector_Registry::get_registered()
* @see wp_is_connector_registered()
* @see wp_get_connectors()
*
* @param string $id The connector identifier.
* @return array|null {
* Connector data, or null if not registered.
*
* @type string $name The connector's display name.
* @type string $description The connector's description.
* @type string $logo_url Optional. URL to the connector's logo image.
* @type string $type The connector type. Currently, only 'ai_provider' is supported.
* @type array $authentication {
* Authentication configuration. When method is 'api_key', includes
* credentials_url and setting_name. When 'none', only method is present.
*
* @type string $method The authentication method: 'api_key' or 'none'.
* @type string $credentials_url Optional. URL where users can obtain API credentials.
* @type string $setting_name Optional. The setting name for the API key.
* }
* @type array $plugin {
* Optional. Plugin data for install/activate UI.
*
* @type string $slug The WordPress.org plugin slug.
* }
* }
* @phpstan-return ?array{
* name: non-empty-string,
* description: non-empty-string,
* logo_url?: non-empty-string,
* type: 'ai_provider',
* authentication: array{
* method: 'api_key'|'none',
* credentials_url?: non-empty-string,
* setting_name?: non-empty-string
* },
* plugin?: array{
* slug: non-empty-string
* }
* }
*/
function wp_get_connector( string $id ): ?array {
$registry = WP_Connector_Registry::get_instance();
if ( null === $registry ) {
return null;
}
return $registry->get_registered( $id );
}
/**
* Retrieves all registered connectors.
*
* Example:
*
* $connectors = wp_get_connectors();
* foreach ( $connectors as $id => $connector ) {
* printf( '%s: %s', $connector['name'], $connector['description'] );
* }
*
* @since 7.0.0
*
* @see WP_Connector_Registry::get_all_registered()
* @see wp_is_connector_registered()
* @see wp_get_connector()
*
* @return array {
* Connector settings keyed by connector ID.
*
* @type array ...$0 {
* Data for a single connector.
*
* @type string $name The connector's display name.
* @type string $description The connector's description.
* @type string $logo_url Optional. URL to the connector's logo image.
* @type string $type The connector type. Currently, only 'ai_provider' is supported.
* @type array $authentication {
* Authentication configuration. When method is 'api_key', includes
* credentials_url and setting_name. When 'none', only method is present.
*
* @type string $method The authentication method: 'api_key' or 'none'.
* @type string $credentials_url Optional. URL where users can obtain API credentials.
* @type string $setting_name Optional. The setting name for the API key.
* }
* @type array $plugin {
* Optional. Plugin data for install/activate UI.
*
* @type string $slug The WordPress.org plugin slug.
* }
* }
* }
* @phpstan-return array<string, array{
* name: non-empty-string,
* description: non-empty-string,
* logo_url?: non-empty-string,
* type: 'ai_provider',
* authentication: array{
* method: 'api_key'|'none',
* credentials_url?: non-empty-string,
* setting_name?: non-empty-string
* },
* plugin?: array{
* slug: non-empty-string
* }
* }>
*/
function wp_get_connectors(): array {
$registry = WP_Connector_Registry::get_instance();
if ( null === $registry ) {
return array();
}
return $registry->get_all_registered();
}
/**
* Resolves an AI provider logo file path to a URL.
*
* Converts an absolute file path to a plugin URL. The path must reside within
* the plugins or must-use plugins directory.
*
* @since 7.0.0
* @access private
*
* @param string $path Absolute path to the logo file.
* @return string|null The URL to the logo file, or null if the path is invalid.
*/
function _wp_connectors_resolve_ai_provider_logo_url( string $path ): ?string {
if ( ! $path ) {
return null;
}
$path = wp_normalize_path( $path );
if ( ! file_exists( $path ) ) {
return null;
}
$mu_plugin_dir = wp_normalize_path( WPMU_PLUGIN_DIR );
if ( str_starts_with( $path, $mu_plugin_dir . '/' ) ) {
return plugins_url( substr( $path, strlen( $mu_plugin_dir ) ), WPMU_PLUGIN_DIR . '/.' );
}
$plugin_dir = wp_normalize_path( WP_PLUGIN_DIR );
if ( str_starts_with( $path, $plugin_dir . '/' ) ) {
return plugins_url( substr( $path, strlen( $plugin_dir ) ) );
}
_doing_it_wrong(
__FUNCTION__,
__( 'Provider logo path must be located within the plugins or must-use plugins directory.' ),
'7.0.0'
);
return null;
}
/**
* Initializes the connector registry with default connectors and fires the registration action.
*
* This function orchestrates the full connector initialization sequence:
*
* 1. Creates the `WP_Connector_Registry` singleton instance.
* 2. Defines built-in connectors (Anthropic, Google, OpenAI) with hardcoded defaults
* including name, description, type, plugin slug, and authentication configuration.
* 3. Merges metadata from the WP AI Client provider registry on top of defaults.
* Registry values (from provider plugins) take precedence over hardcoded fallbacks
* for name, description, logo URL, and authentication method.
* 4. Registers all connectors (built-in and AI Client-discovered) on the registry.
* 5. Fires the `wp_connectors_init` action for plugins to override metadata
* on existing connectors or register additional connectors.
*
* Built-in connectors are registered before the action fires and cannot be unhooked.
* Plugins should use the `wp_connectors_init` action to override metadata or
* register new connectors via `$registry->register()`.
*
* @since 7.0.0
* @access private
*/
function _wp_connectors_init(): void {
$registry = new WP_Connector_Registry();
WP_Connector_Registry::set_instance( $registry );
// Only register default AI providers if AI support is enabled.
if ( wp_supports_ai() ) {
_wp_connectors_register_default_ai_providers( $registry );
}
/**
* Fires when the connector registry is ready for plugins to register connectors.
*
* Built-in connectors and any AI providers auto-discovered from the WP AI Client
* registry have already been registered at this point and cannot be unhooked.
*
* AI provider plugins that register with the WP AI Client do not need to use
* this action — their connectors are created automatically. This action is
* primarily for registering non-AI-provider connectors or overriding metadata
* on existing connectors.
*
* Use `$registry->register()` within this action to add new connectors.
* To override an existing connector, unregister it first, then re-register
* with updated data.
*
* Example — overriding metadata on an auto-discovered connector:
*
* add_action( 'wp_connectors_init', function ( WP_Connector_Registry $registry ) {
* if ( $registry->is_registered( 'openai' ) ) {
* $connector = $registry->unregister( 'openai' );
* $connector['description'] = __( 'Custom description for OpenAI.', 'my-plugin' );
* $registry->register( 'openai', $connector );
* }
* } );
*
* @since 7.0.0
*
* @param WP_Connector_Registry $registry Connector registry instance.
*/
do_action( 'wp_connectors_init', $registry );
}
/**
* Registers connectors for the built-in AI providers.
*
* @since 7.0.0
* @access private
*
* @param WP_Connector_Registry $registry The connector registry instance.
*/
function _wp_connectors_register_default_ai_providers( WP_Connector_Registry $registry ): void {
// Built-in connectors.
$defaults = array(
'anthropic' => array(
'name' => 'Anthropic',
'description' => __( 'Text generation with Claude.' ),
'type' => 'ai_provider',
'plugin' => array(
'slug' => 'ai-provider-for-anthropic',
),
'authentication' => array(
'method' => 'api_key',
'credentials_url' => 'https://platform.claude.com/settings/keys',
),
),
'google' => array(
'name' => 'Google',
'description' => __( 'Text and image generation with Gemini and Imagen.' ),
'type' => 'ai_provider',
'plugin' => array(
'slug' => 'ai-provider-for-google',
),
'authentication' => array(
'method' => 'api_key',
'credentials_url' => 'https://aistudio.google.com/api-keys',
),
),
'openai' => array(
'name' => 'OpenAI',
'description' => __( 'Text and image generation with GPT and Dall-E.' ),
'type' => 'ai_provider',
'plugin' => array(
'slug' => 'ai-provider-for-openai',
),
'authentication' => array(
'method' => 'api_key',
'credentials_url' => 'https://platform.openai.com/api-keys',
),
),
);
// Merge AI Client registry data on top of defaults.
// Registry values (from provider plugins) take precedence over hardcoded fallbacks.
$ai_registry = AiClient::defaultRegistry();
foreach ( $ai_registry->getRegisteredProviderIds() as $connector_id ) {
$provider_class_name = $ai_registry->getProviderClassName( $connector_id );
$provider_metadata = $provider_class_name::metadata();
$auth_method = $provider_metadata->getAuthenticationMethod();
$is_api_key = null !== $auth_method && $auth_method->isApiKey();
if ( $is_api_key ) {
$credentials_url = $provider_metadata->getCredentialsUrl();
$authentication = array(
'method' => 'api_key',
'credentials_url' => $credentials_url ? $credentials_url : null,
);
} else {
$authentication = array( 'method' => 'none' );
}
$name = $provider_metadata->getName();
$description = $provider_metadata->getDescription();
$logo_url = $provider_metadata->getLogoPath()
? _wp_connectors_resolve_ai_provider_logo_url( $provider_metadata->getLogoPath() )
: null;
if ( isset( $defaults[ $connector_id ] ) ) {
// Override fields with non-empty registry values.
if ( $name ) {
$defaults[ $connector_id ]['name'] = $name;
}
if ( $description ) {
$defaults[ $connector_id ]['description'] = $description;
}
if ( $logo_url ) {
$defaults[ $connector_id ]['logo_url'] = $logo_url;
}
// Always update auth method; keep existing credentials_url as fallback.
$defaults[ $connector_id ]['authentication']['method'] = $authentication['method'];
if ( ! empty( $authentication['credentials_url'] ) ) {
$defaults[ $connector_id ]['authentication']['credentials_url'] = $authentication['credentials_url'];
}
} else {
$defaults[ $connector_id ] = array(
'name' => $name ? $name : ucwords( $connector_id ),
'description' => $description ? $description : '',
'type' => 'ai_provider',
'authentication' => $authentication,
'logo_url' => $logo_url,
);
}
}
// Register all default connectors directly on the registry.
foreach ( $defaults as $id => $args ) {
$registry->register( $id, $args );
}
}
/**
* Masks an API key, showing only the last 4 characters.
*
* @since 7.0.0
* @access private
*
* @param string $key The API key to mask.
* @return string The masked key, e.g. "************fj39".
*/
function _wp_connectors_mask_api_key( string $key ): string {
if ( strlen( $key ) <= 4 ) {
return $key;
}
return str_repeat( "\u{2022}", min( strlen( $key ) - 4, 16 ) ) . substr( $key, -4 );
}
/**
* Determines the source of an API key for a given provider.
*
* Checks in order: environment variable, PHP constant, database.
* Uses the same naming convention as the WP AI Client ProviderRegistry.
*
* @since 7.0.0
* @access private
*
* @param string $provider_id The provider ID (e.g., 'openai', 'anthropic', 'google').
* @param string $setting_name The option name for the API key (e.g., 'connectors_ai_openai_api_key').
* @return string The key source: 'env', 'constant', 'database', or 'none'.
*/
function _wp_connectors_get_api_key_source( string $provider_id, string $setting_name ): string {
// Convert provider ID to CONSTANT_CASE for env var name.
// e.g., 'openai' -> 'OPENAI', 'anthropic' -> 'ANTHROPIC'.
$constant_case_id = strtoupper(
preg_replace( '/([a-z])([A-Z])/', '$1_$2', str_replace( '-', '_', $provider_id ) )
);
$env_var_name = "{$constant_case_id}_API_KEY";
// Check environment variable first.
$env_value = getenv( $env_var_name );
if ( false !== $env_value && '' !== $env_value ) {
return 'env';
}
// Check PHP constant.
if ( defined( $env_var_name ) ) {
$const_value = constant( $env_var_name );
if ( is_string( $const_value ) && '' !== $const_value ) {
return 'constant';
}
}
// Check database.
$db_value = get_option( $setting_name, '' );
if ( '' !== $db_value ) {
return 'database';
}
return 'none';
}
/**
* Checks whether an API key is valid for a given provider.
*
* @since 7.0.0
* @access private
*
* @param string $key The API key to check.
* @param string $provider_id The WP AI client provider ID.
* @return bool|null True if valid, false if invalid, null if unable to determine.
*/
function _wp_connectors_is_ai_api_key_valid( string $key, string $provider_id ): ?bool {
try {
$registry = AiClient::defaultRegistry();
if ( ! $registry->hasProvider( $provider_id ) ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: %s: AI provider ID. */
__( 'The provider "%s" is not registered in the AI client registry.' ),
$provider_id
),
'7.0.0'
);
return null;
}
$registry->setProviderRequestAuthentication(
$provider_id,
new ApiKeyRequestAuthentication( $key )
);
return $registry->isProviderConfigured( $provider_id );
} catch ( Exception $e ) {
wp_trigger_error( __FUNCTION__, $e->getMessage() );
return null;
}
}
/**
* Masks and validates connector API keys in REST responses.
*
* On every `/wp/v2/settings` response, masks connector API key values so raw
* keys are never exposed via the REST API.
*
* On POST or PUT requests, validates each updated key against the provider
* before masking. If validation fails, the key is reverted to an empty string.
*
* @since 7.0.0
* @access private
*
* @param WP_REST_Response $response The response object.
* @param WP_REST_Server $server The server instance.
* @param WP_REST_Request $request The request object.
* @return WP_REST_Response The modified response with masked/validated keys.
*/
function _wp_connectors_rest_settings_dispatch( WP_REST_Response $response, WP_REST_Server $server, WP_REST_Request $request ): WP_REST_Response {
if ( '/wp/v2/settings' !== $request->get_route() ) {
return $response;
}
$data = $response->get_data();
if ( ! is_array( $data ) ) {
return $response;
}
$is_update = 'POST' === $request->get_method() || 'PUT' === $request->get_method();
foreach ( wp_get_connectors() as $connector_id => $connector_data ) {
$auth = $connector_data['authentication'];
if ( 'ai_provider' !== $connector_data['type'] || 'api_key' !== $auth['method'] || empty( $auth['setting_name'] ) ) {
continue;
}
$setting_name = $auth['setting_name'];
if ( ! array_key_exists( $setting_name, $data ) ) {
continue;
}
$value = $data[ $setting_name ];
// On update, validate the key before masking.
if ( $is_update && is_string( $value ) && '' !== $value ) {
if ( true !== _wp_connectors_is_ai_api_key_valid( $value, $connector_id ) ) {
update_option( $setting_name, '' );
$data[ $setting_name ] = '';
continue;
}
}
// Mask the key in the response.
if ( is_string( $value ) && '' !== $value ) {
$data[ $setting_name ] = _wp_connectors_mask_api_key( $value );
}
}
$response->set_data( $data );
return $response;
}
add_filter( 'rest_post_dispatch', '_wp_connectors_rest_settings_dispatch', 10, 3 );
/**
* Registers default connector settings.
*
* Only registers settings for `ai_provider` connectors with `api_key`
* authentication whose provider is present in the WP AI Client registry.
* Each setting is registered with `show_in_rest` enabled, making it
* accessible through the `/wp/v2/settings` REST endpoint.
*
* @since 7.0.0
* @access private
*/
function _wp_register_default_connector_settings(): void {
$ai_registry = AiClient::defaultRegistry();
foreach ( wp_get_connectors() as $connector_id => $connector_data ) {
$auth = $connector_data['authentication'];
if ( 'ai_provider' !== $connector_data['type'] || 'api_key' !== $auth['method'] || empty( $auth['setting_name'] ) ) {
continue;
}
// Skip registering the setting if the provider is not in the registry.
if ( ! $ai_registry->hasProvider( $connector_id ) ) {
continue;
}
register_setting(
'connectors',
$auth['setting_name'],
array(
'type' => 'string',
'label' => sprintf(
/* translators: %s: AI provider name. */
__( '%s API Key' ),
$connector_data['name']
),
'description' => sprintf(
/* translators: %s: AI provider name. */
__( 'API key for the %s AI provider.' ),
$connector_data['name']
),
'default' => '',
'show_in_rest' => true,
'sanitize_callback' => 'sanitize_text_field',
)
);
}
}
add_action( 'init', '_wp_register_default_connector_settings', 20 );
/**
* Passes stored connector API keys to the WP AI client.
*
* @since 7.0.0
* @access private
*/
function _wp_connectors_pass_default_keys_to_ai_client(): void {
try {
$ai_registry = AiClient::defaultRegistry();
foreach ( wp_get_connectors() as $connector_id => $connector_data ) {
if ( 'ai_provider' !== $connector_data['type'] ) {
continue;
}
$auth = $connector_data['authentication'];
if ( 'api_key' !== $auth['method'] || empty( $auth['setting_name'] ) ) {
continue;
}
if ( ! $ai_registry->hasProvider( $connector_id ) ) {
continue;
}
// Skip if the key is already provided via env var or constant.
$key_source = _wp_connectors_get_api_key_source( $connector_id, $auth['setting_name'] );
if ( 'env' === $key_source || 'constant' === $key_source ) {
continue;
}
$api_key = get_option( $auth['setting_name'], '' );
if ( '' === $api_key ) {
continue;
}
$ai_registry->setProviderRequestAuthentication(
$connector_id,
new ApiKeyRequestAuthentication( $api_key )
);
}
} catch ( Exception $e ) {
wp_trigger_error( __FUNCTION__, $e->getMessage() );
}
}
add_action( 'init', '_wp_connectors_pass_default_keys_to_ai_client', 20 );
/**
* Provides connector data to the Settings → Connectors admin screen.
*
* This function is the bridge between the PHP connector registry and the
* frontend admin UI. It transforms each registered connector into the data
* structure consumed by the `options-connectors-wp-admin` script module,
* enriching registry data with runtime state:
*
* - Plugin install/activate status (via `get_plugins()` and `is_plugin_active()`).
* - API key source detection (`env`, `constant`, `database`, or `none`).
* - Connection status for `api_key` connectors (via the WP AI Client registry).
*
* Hooked to the `script_module_data_options-connectors-wp-admin` filter.
*
* @since 7.0.0
* @access private
*
* @see _wp_connectors_get_api_key_source()
*
* @param array<string, mixed> $data Existing script module data.
* @return array<string, mixed> Script module data with a `connectors` key added,
* keyed by connector ID and sorted alphabetically.
*/
function _wp_connectors_get_connector_script_module_data( array $data ): array {
$registry = AiClient::defaultRegistry();
// Build a slug-to-file map for plugin installation status.
if ( ! function_exists( 'get_plugins' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$plugin_files_by_slug = array();
foreach ( array_keys( get_plugins() ) as $plugin_file ) {
$slug = str_contains( $plugin_file, '/' ) ? dirname( $plugin_file ) : str_replace( '.php', '', $plugin_file );
$plugin_files_by_slug[ $slug ] = $plugin_file;
}
$connectors = array();
foreach ( wp_get_connectors() as $connector_id => $connector_data ) {
$auth = $connector_data['authentication'];
$auth_out = array( 'method' => $auth['method'] );
if ( 'api_key' === $auth['method'] ) {
$auth_out['settingName'] = $auth['setting_name'] ?? '';
$auth_out['credentialsUrl'] = $auth['credentials_url'] ?? null;
$auth_out['keySource'] = _wp_connectors_get_api_key_source( $connector_id, $auth['setting_name'] ?? '' );
try {
$auth_out['isConnected'] = $registry->hasProvider( $connector_id ) && $registry->isProviderConfigured( $connector_id );
} catch ( Exception $e ) {
$auth_out['isConnected'] = false;
}
}
$connector_out = array(
'name' => $connector_data['name'],
'description' => $connector_data['description'],
'logoUrl' => ! empty( $connector_data['logo_url'] ) ? $connector_data['logo_url'] : null,
'type' => $connector_data['type'],
'authentication' => $auth_out,
);
if ( ! empty( $connector_data['plugin']['slug'] ) ) {
$plugin_slug = $connector_data['plugin']['slug'];
$plugin_file = $plugin_files_by_slug[ $plugin_slug ] ?? null;
$is_installed = null !== $plugin_file;
$is_activated = $is_installed && is_plugin_active( $plugin_file );
$connector_out['plugin'] = array(
'slug' => $plugin_slug,
'isInstalled' => $is_installed,
'isActivated' => $is_activated,
);
}
$connectors[ $connector_id ] = $connector_out;
}
ksort( $connectors );
$data['connectors'] = $connectors;
return $data;
}
add_filter( 'script_module_data_options-connectors-wp-admin', '_wp_connectors_get_connector_script_module_data' );