Repository navigation
Expand file tree
/
Copy pathHelpers.php
More file actions
989 lines (839 loc) · 31.3 KB
/
Copy pathHelpers.php
File metadata and controls
989 lines (839 loc) · 31.3 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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
<?php
/**
* Plausible Analytics | Helpers
*
* @since 1.0.0
* @package WordPress
* @subpackage Plausible Analytics
*/
namespace Plausible\Analytics\WP;
use Exception;
/**
* We use 'static' (late static binding) instead of 'self' (early binding), so we can mock (where needed) in our tests.
*/
class Helpers {
/**
* Supported multilingual plugins, as returned by @see Helpers::get_multilang_plugin().
*/
const MULTILANG_PLUGIN_WPML = 'wpml';
const MULTILANG_PLUGIN_TRANSLATEPRESS = 'translatepress';
/**
* @var array|null The proxy resources as stored in the DB, retrieved once per request. @see self::get_proxy_resources()
*/
protected static $stored_proxy_resources;
/**
* Returns the language codes of all languages the active multilingual plugin serves to the public.
*
* Languages that aren't public yet (WPML's hidden languages, TranslatePress' unpublished languages) are left out,
* regardless of who's making the request: WPML only lists hidden languages to users who opted to see them, which
* would make the result depend on whether provisioning runs in an admin's or a visitor's request.
*
* @since v2.6.2
*
* @return array Empty when no supported multilingual plugin is active.
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
public static function get_active_languages() {
$languages = [];
switch ( static::get_multilang_plugin() ) {
case static::MULTILANG_PLUGIN_WPML:
$active = apply_filters( 'wpml_active_languages', null, [ 'skip_missing' => 0 ] );
if ( is_array( $active ) ) {
$hidden = (array) apply_filters( 'wpml_setting', [], 'hidden_languages' );
$languages = array_diff( array_keys( $active ), $hidden );
}
break;
case static::MULTILANG_PLUGIN_TRANSLATEPRESS:
$settings = get_option( 'trp_settings', [] );
$languages = $settings['publish-languages'] ?? [];
break;
}
return (array) apply_filters( 'plausible_analytics_active_languages', array_values( (array) $languages ) );
}
/**
* Returns the currency a Revenue goal should be created in for a given language-domain.
*
* WooCommerce Multilingual & Multicurrency (WCML) lets a store pin a default currency per language
* ("WooCommerce → Multilingual → Currencies"). When one is set, the matching per-language dashboard's
* purchase goal is created in that storeview's own currency—mirroring how its view-product goals are
* already localized. Without WCML (or when multi-currency is off, or no default is set for this
* language) the store's base currency is used, and Plausible converts foreign-currency purchases into
* it automatically.
*
* The base currency is read from WooCommerce's setting instead of get_woocommerce_currency(), because multicurrency
* plugins filter the latter to the currency of the current request (e.g. WCML returns the visitor's currency in
* AJAX requests), which would make the goal's currency depend on whichever request happens to provision it.
*
* @since 2.6.2
*
* @param string $domain_key 'default' or a WPML language code (e.g. 'es').
*
* @return string ISO 4217 currency code.
*/
public static function get_currency_for_language( $domain_key = 'default' ) {
$base = Integrations::is_edd_active() ? edd_get_currency() : (string) get_option( 'woocommerce_currency', 'USD' );
// A default currency per language is a WCML (WooCommerce + WPML) concept only.
if ( Integrations::is_edd_active() || static::get_multilang_plugin() !== static::MULTILANG_PLUGIN_WPML ) {
return $base;
}
$wcml = get_option( '_wcml_settings', [] );
if ( empty( $wcml['enable_multi_currency'] ) || empty( $wcml['default_currencies'] ) || ! is_array( $wcml['default_currencies'] ) ) {
return $base; // @codeCoverageIgnore
}
// In "by location" mode the currency follows the visitor's country, so the per-language defaults don't apply.
if ( ( $wcml['currency_mode'] ?? '' ) === 'by_location' ) {
return $base;
}
// The 'default' dashboard tracks WPML's default language.
$language = 'default' === $domain_key ? (string) apply_filters( 'wpml_default_language', null ) : $domain_key;
$currency = $wcml['default_currencies'][ $language ] ?? false;
// Languages without a pinned default currency ("Keep") are stored as false, 0 or '0'.
return is_string( $currency ) && preg_match( '/^[A-Z]{3}$/', $currency ) ? $currency : $base;
}
/**
* Returns the API token.
*
* @return string
*/
public static function get_api_token() {
$settings = static::get_settings();
$current = static::get_current_language_domain_key();
return $settings['api_token'][ $current ] ?? $settings['api_token']['default'] ?? '';
}
/**
* Get Settings.
*
* @since 1.0.0
* @access public
* @return array
*/
public static function get_settings() {
$defaults = [
'domain_name' => [ 'default' => '' ],
'api_token' => [ 'default' => '' ],
'enhanced_measurements' => [
EnhancedMeasurements::FOUR_O_FOUR,
EnhancedMeasurements::FILE_DOWNLOADS,
EnhancedMeasurements::OUTBOUND_LINKS,
EnhancedMeasurements::FORM_COMPLETIONS,
EnhancedMeasurements::SEARCH_QUERIES,
],
'affiliate_links' => [],
'query_params' => [],
'proxy_enabled' => '',
'enable_analytics_dashboard' => '',
'shared_link' => [ 'default' => '' ],
'excluded_pages' => '',
'tracked_user_roles' => [],
'expand_dashboard_access' => [],
'disable_toolbar_menu' => '',
'self_hosted_domain' => '',
'self_hosted_shared_link' => '',
];
$settings = function_exists( 'get_option' ) ? get_option( 'plausible_analytics_settings', [] ) : [];
$settings = wp_parse_args( $settings, $defaults );
/**
* Normalization: Ensure domain_name and api_token are always arrays.
*/
if ( ! is_array( $settings['domain_name'] ) ) {
$settings['domain_name'] = [ 'default' => $settings['domain_name'] ];
}
if ( ! is_array( $settings['api_token'] ) ) {
$settings['api_token'] = [ 'default' => $settings['api_token'] ];
}
if ( ! is_array( $settings['shared_link'] ) ) {
$settings['shared_link'] = [ 'default' => $settings['shared_link'] ];
}
return apply_filters( 'plausible_analytics_settings', $settings );
}
/**
* Returns the key of the currently used Language Domain.
*
* @since v2.6.0
* @since v2.6.2 Added TranslatePress (Multiple Domains) support.
*
* @return string
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
public static function get_current_language_domain_key() {
if ( ! static::is_language_per_domain_mode() ) {
return 'default';
}
$language_domains = [];
$current_language = null;
switch ( static::get_multilang_plugin() ) {
case static::MULTILANG_PLUGIN_WPML:
$language_domains = apply_filters( 'wpml_setting', [], 'language_domains' );
$current_language = apply_filters( 'wpml_current_language', null );
break;
case static::MULTILANG_PLUGIN_TRANSLATEPRESS:
$language_domains = static::get_translatepress_language_domains();
$current_language = static::get_translatepress_current_language();
break;
}
$key = $current_language && isset( $language_domains[ $current_language ] ) ? $current_language : 'default';
return (string) apply_filters( 'plausible_analytics_current_language_domain_key', $key );
}
/**
* Returns true only when a supported multilingual plugin (WPML or TranslatePress) is active, it's configured to serve
* a "different domain per language", AND at least one domain is configured.
*
* @since v2.6.0
* @since v2.6.2 Added TranslatePress (Multiple Domains) support.
*
* @return bool
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
public static function is_language_per_domain_mode() {
static $is_language_per_domain;
if ( defined( 'PLAUSIBLE_CI' ) && PLAUSIBLE_CI ) {
$is_language_per_domain = null;
}
if ( $is_language_per_domain !== null ) {
return $is_language_per_domain; // @codeCoverageIgnore
}
$value = false;
switch ( static::get_multilang_plugin() ) {
case static::MULTILANG_PLUGIN_WPML:
$negotiation_type = (int) apply_filters( 'wpml_setting', 0, 'language_negotiation_type' );
$domains = apply_filters( 'wpml_setting', [], 'language_domains' );
$value = $negotiation_type === 2 && ! empty( $domains );
break;
case static::MULTILANG_PLUGIN_TRANSLATEPRESS:
$value = ! empty( static::get_translatepress_language_domains() );
break;
}
return $is_language_per_domain = (bool) apply_filters( 'plausible_analytics_language_per_domain_mode', $value );
}
/**
* Returns the active multilingual plugin, so we know which of its APIs to talk to.
*
* @since v2.6.2
*
* @return string One of the MULTILANG_PLUGIN_* constants, or an empty string when none is active.
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
public static function get_multilang_plugin() {
$plugin = '';
if ( defined( 'ICL_SITEPRESS_VERSION' ) ) {
$plugin = static::MULTILANG_PLUGIN_WPML;
} elseif ( defined( 'TRP_PLUGIN_VERSION' ) ) {
$plugin = static::MULTILANG_PLUGIN_TRANSLATEPRESS;
}
return (string) apply_filters( 'plausible_analytics_multilang_plugin', $plugin );
}
/**
* Returns TranslatePress' "Multiple Domains" mappings, keyed by language code (excluding the default language, to
* mirror WPML's language_domains behavior).
*
* @since v2.6.2
*
* @return array
*/
protected static function get_translatepress_language_domains() {
$settings = function_exists( 'get_option' ) ? get_option( 'trp_settings', [] ) : [];
$mappings = $settings['trp-multiple-domains'] ?? [];
$default = $settings['default-language'] ?? '';
$domains = [];
if ( ! is_array( $mappings ) ) {
return $domains; // @codeCoverageIgnore
}
foreach ( $mappings as $language_code => $mapping ) {
if ( $language_code === $default || empty( $mapping['enabled'] ) || empty( $mapping['domain'] ) ) {
continue;
}
$domains[ $language_code ] = $mapping['domain'];
}
return $domains;
}
/**
* Returns the language code TranslatePress is currently serving.
*
* @since v2.6.2
*
* @return string|null
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
protected static function get_translatepress_current_language() {
global $TRP_LANGUAGE;
return ! empty( $TRP_LANGUAGE ) ? $TRP_LANGUAGE : null;
}
/**
* Returns the name of the current Plausible domain.
*
* @since v2.6.0 This is now mapped to language domains to provide compatibility with multilang plugins, like WPML.
*
* @return string
*/
public static function get_domain() {
$settings = static::get_settings();
$current_key = static::get_current_language_domain_key();
$domain_name = $settings['domain_name'][ $current_key ] ?? '';
if ( ! empty( $domain_name ) ) {
return $domain_name;
}
if ( ! empty( $settings['domain_name']['default'] ) ) {
return $settings['domain_name']['default'];
}
/**
* Multilingual plugins (e.g. WPML in "different languages in directories" mode) filter home_url() to include the
* current language's directory e.g., https://example.com/fr, so use the unfiltered value instead.
*/
$url = untrailingslashit( get_option( 'home' ) );
return preg_replace( '/^http(s?):\/\/(www\.)?/i', '', $url );
}
/**
* Get Data API URL.
*
* @since 1.2.2
* @access public
* @return string
* @throws Exception
*/
public static function get_endpoint_url() {
if ( static::proxy_enabled() ) {
// This will make sure the API endpoint is properly registered when we're testing.
$append = isset( $_GET['plausible_proxy'] ) ? '?plausible_proxy=1' : '';
return static::get_rest_endpoint() . $append;
}
return esc_url( static::get_hosted_domain_url() . '/api/event' );
}
/**
* Is the proxy enabled?
*
* @param array $settings Allows passing a current settings object.
*
* @return bool
*/
public static function proxy_enabled( $settings = [] ) {
if ( empty( $settings ) ) {
$settings = static::get_settings();
}
return ! empty( $settings['proxy_enabled'] ) || isset( $_GET['plausible_proxy'] );
}
/**
* Returns the Proxy's REST endpoint.
*
* @return string
* @throws Exception
*/
public static function get_rest_endpoint( $abs_url = true ) {
$namespace = static::get_proxy_resource( 'namespace' );
$base = static::get_proxy_resource( 'base' );
$endpoint = static::get_proxy_resource( 'endpoint' );
$uri = "$namespace/v1/$base/$endpoint";
if ( $abs_url ) {
return get_rest_url( null, $uri );
}
return '/' . rest_get_url_prefix() . '/' . $uri;
}
/**
* Get a proxy resource by name.
*
* @param string $resource_name
*
* @return string Value of resource from DB or empty string if Bypass ad blockers option is disabled.
* @throws Exception
*/
public static function get_proxy_resource( $resource_name = '' ) {
$resources = static::get_proxy_resources();
/**
* Create the cache directory if it doesn't exist.
*/
if ( ( $resource_name === 'cache_dir' || $resource_name === 'cache_url' ) && ! is_dir( $resources['cache_dir'] ) ) {
wp_mkdir_p( $resources['cache_dir'] );
}
return $resources[ $resource_name ] ?? '';
}
/**
* Get (and generate/store if non-existent) proxy resources.
*
* @since 2.6.3 Only the cache directory's name is stored: its path and URL are derived from the current uploads
* directory on every request. They used to be stored as absolute values, so after moving the site to another
* host, domain or path the local tracker script was still loaded from the old location, which stalls every
* page (the script is deferred, so DOMContentLoaded waits for it) when the old server is offline.
*
* @return array
* @throws Exception
*
* @codeCoverageIgnore
*/
public static function get_proxy_resources() {
if ( static::$stored_proxy_resources === null ) {
static::$stored_proxy_resources = self::get_stored_proxy_resources();
}
$resources = static::$stored_proxy_resources;
$upload_dir = wp_get_upload_dir();
$resources['cache_dir'] = trailingslashit( $upload_dir['basedir'] ) . trailingslashit( $resources['cache_folder'] );
// set_url_scheme() matches the URL to the current request, e.g. after switching the site to SSL.
$resources['cache_url'] = trailingslashit( set_url_scheme( $upload_dir['baseurl'] ) ) . trailingslashit( $resources['cache_folder'] );
return $resources;
}
/**
* Returns the proxy resources stored in the DB, generating (and storing) them when there are none yet.
*
* @since 2.6.3
*
* @return array
* @throws Exception
*
* @codeCoverageIgnore
*/
private static function get_stored_proxy_resources() {
$stored = get_option( 'plausible_analytics_proxy_resources', [] );
// Installs from before 2.6.3 stored the absolute path of the cache directory, of which only the name is kept.
if ( empty( $stored['cache_folder'] ) && ! empty( $stored['cache_dir'] ) ) {
$stored['cache_folder'] = basename( untrailingslashit( $stored['cache_dir'] ) );
}
if ( ! empty( $stored['namespace'] ) && ! empty( $stored['cache_folder'] ) ) {
return $stored;
}
$stored = [
'namespace' => bin2hex( random_bytes( 3 ) ),
'base' => bin2hex( random_bytes( 2 ) ),
'endpoint' => bin2hex( random_bytes( 4 ) ),
'cache_folder' => bin2hex( random_bytes( 5 ) ),
];
update_option( 'plausible_analytics_proxy_resources', $stored );
return $stored;
}
/**
* Returns the URL of the domain where Plausible Analytics is hosted: self-hosted or cloud.
*
* @return string
*/
public static function get_hosted_domain_url() {
$settings = static::get_settings();
if ( defined( 'PLAUSIBLE_SELF_HOSTED_DOMAIN' ) ) {
return esc_url( 'https://' . PLAUSIBLE_SELF_HOSTED_DOMAIN ); // @codeCoverageIgnore
}
if ( ! empty( $settings['self_hosted_domain'] ) ) {
/**
* Until proven otherwise, let's just assume people are all on SSL.
*/
return esc_url( 'https://' . $settings['self_hosted_domain'] );
}
return esc_url( 'https://plausible.io' );
}
/**
* A convenient way to retrieve the absolute path to the local JS file. Proxy should be enabled when this method is called!
*
* @return string
* @throws Exception
*/
public static function get_js_path() {
$filename = static::get_filename();
if ( empty( $filename ) ) {
return ''; // @codeCoverageIgnore
}
return static::get_proxy_resource( 'cache_dir' ) . $filename . '.js';
}
/**
* Get filename (without file extension)
*
* @since 1.3.0
* @return string
* @throws Exception
*
* @codeCoverageIgnore
*/
public static function get_filename() {
$client = static::get_client();
if ( $client instanceof Client ) {
return $client->get_tracker_id( static::get_current_language_domain_key() );
}
return '';
}
/**
* Build the API client.
*
* @param string $domain_key
*
* @return false|Client
*
* @codeCoverageIgnore This seam's only function is to keep our code testable.
*/
protected static function get_client( $domain_key = '' ) {
$client = new ClientFactory( '', $domain_key );
return $client->build();
}
/**
* Get Analytics URL. Returns an empty string if @see self::get_filename() returns empty.
*
* @since 1.0.0
*
* @return string
* @throws Exception
*/
public static function get_js_url( $local = false ) {
$file_name = static::get_filename();
if ( empty( $file_name ) ) {
return ''; // @codeCoverageIgnore
}
/**
* If the Avoid Ad Blockers option is enabled, return URL pointing to the local file.
*/
if ( $local && static::proxy_enabled() ) {
/**
* The local file may not exist (yet), e.g. right after moving the site to another host without its uploads.
* Load the script from Plausible Analytics until the cron has downloaded it, instead of from a URL that 404s.
*/
if ( ! file_exists( static::get_proxy_resource( 'cache_dir' ) . $file_name . '.js' ) ) {
/**
* Download it right away, rather than on the next daily run. At most once per 15 minutes: if the
* download keeps failing (e.g. the uploads directory isn't writable), every request would schedule a
* new attempt as soon as the previous one has run. wp_next_scheduled() can't be used for this, as the
* daily event uses the same hook.
*/
if ( ! get_transient( 'plausible_analytics_js_download_attempt' ) ) {
set_transient( 'plausible_analytics_js_download_attempt', 1, 15 * MINUTE_IN_SECONDS );
wp_schedule_single_event( time(), Cron::TASK_NAME );
}
return esc_url( static::get_hosted_domain_url() . "/js/$file_name.js" );
}
/**
* The cache URL is built on the main domain, so it needs to be moved to the language domain we're currently
* on.
*/
return esc_url( static::maybe_use_current_language_domain( static::get_proxy_resource( 'cache_url' ) . $file_name . '.js' ) );
}
return esc_url( static::get_hosted_domain_url() . "/js/$file_name.js" );
}
/**
* Moves $url to the language domain that's currently being served, keeping its path and query intact.
*
* Both the proxy endpoint and the locally cached JS file are built from the main WP domain. In "domain per
* language" mode that means the tracker would fire cross-origin requests (CORS) at the default domain, so we
* point them at the domain the visitor is actually on.
*
* @since v2.6.2
*
* @param string $url
*
* @return string
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
public static function maybe_use_current_language_domain( $url ) {
$origin = static::get_current_language_domain_url();
if ( empty( $url ) || empty( $origin ) ) {
return $url;
}
$parts = wp_parse_url( $url );
// Already on the right domain, or nothing we can rewrite.
if ( empty( $parts['host'] ) || strcasecmp( $parts['host'], (string) wp_parse_url( $origin, PHP_URL_HOST ) ) === 0 ) {
return $url;
}
$path = $parts['path'] ?? '';
$query = ! empty( $parts['query'] ) ? '?' . $parts['query'] : '';
return $origin . $path . $query;
}
/**
* Returns the origin (scheme + host + port) of the language domain that's currently being served, or an empty
* string when we're not running in "domain per language" mode.
*
* @since v2.6.2
*
* @return string
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
public static function get_current_language_domain_url() {
if ( ! static::is_language_per_domain_mode() ) {
return '';
}
$domains = static::get_language_domains();
$domain = $domains[ static::get_current_language_domain_key() ] ?? '';
if ( empty( $domain ) ) {
return '';
}
// Language domains are stored as a bare host (WPML) or as a full URL (TranslatePress).
if ( strpos( $domain, '//' ) === false ) {
$domain = ( is_ssl() ? 'https://' : 'http://' ) . $domain;
}
$parts = wp_parse_url( $domain );
if ( empty( $parts['host'] ) ) {
return '';
}
$scheme = $parts['scheme'] ?? ( is_ssl() ? 'https' : 'http' );
$port = ! empty( $parts['port'] ) ? ':' . $parts['port'] : '';
return $scheme . '://' . $parts['host'] . $port;
}
/**
* @since v2.6.0 Provide compatibility with multilang plugins, like WPML.
* @since v2.6.2 Added TranslatePress (Multiple Domains) support.
*
* @return array
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
public static function get_language_domains() {
$domains = [];
switch ( static::get_multilang_plugin() ) {
case static::MULTILANG_PLUGIN_WPML:
$domains = apply_filters( 'wpml_setting', [], 'language_domains' );
break;
case static::MULTILANG_PLUGIN_TRANSLATEPRESS:
$domains = static::get_translatepress_language_domains();
break;
}
$main = wp_parse_url( home_url(), PHP_URL_HOST ) ?: home_url();
// WPML/TranslatePress omit the default language; prepend the main WP domain.
if ( ! in_array( $main, $domains, true ) ) {
$domains = array_merge( [ 'default' => $main ], $domains );
}
return apply_filters( 'plausible_analytics_language_domains', $domains );
}
/**
* Returns the URL prefix the given language is served under e.g., 'es' for https://example.com/es/.
*
* Returns an empty string when the language isn't served under a prefix i.e., in "domain per language" mode, in
* "language as parameter" mode, or for the default language.
*
* @since v2.6.2
*
* @param string $language_code
*
* @return string
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
public static function get_language_url_prefix( $language_code ) {
if ( empty( $language_code ) || static::is_language_per_domain_mode() ) {
return '';
}
$prefix = '';
switch ( static::get_multilang_plugin() ) {
case static::MULTILANG_PLUGIN_WPML:
/**
* wpml_permalink converts a URL to the requested language, whichever negotiation type is in use, so
* whatever it adds in front of the home URL's path is the prefix we're after.
*/
$prefix = static::get_home_relative_path( apply_filters( 'wpml_permalink', home_url( '/' ), $language_code ) );
break;
case static::MULTILANG_PLUGIN_TRANSLATEPRESS:
$settings = get_option( 'trp_settings', [] );
$slugs = $settings['url-slugs'] ?? [];
if ( $language_code !== static::get_default_language() ||
( $settings['add-subdirectory-to-default-language'] ?? 'no' ) === 'yes' ) {
$prefix = $slugs[ $language_code ] ?? $language_code;
}
break;
}
return (string) apply_filters( 'plausible_analytics_language_url_prefix', trim( (string) $prefix, '/' ), $language_code );
}
/**
* Returns the home URL's path without leading/trailing slashes, e.g. 'site' for https://example.com/site/.
*
* @since v2.6.2
*
* @return string Empty when the site is served from the domain's root.
*/
public static function get_home_path() {
return trim( (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH ), '/' );
}
/**
* Returns $url's path, relative to the home URL's path, without leading/trailing slashes.
*
* @since v2.6.2
*
* @param string $url A URL or a path.
*
* @return string
*/
public static function get_home_relative_path( $url ) {
$path = trim( (string) wp_parse_url( $url, PHP_URL_PATH ), '/' );
$home = static::get_home_path();
if ( $home !== '' && ( $path === $home || strpos( $path, "$home/" ) === 0 ) ) {
$path = trim( substr( $path, strlen( $home ) ), '/' );
}
return $path;
}
/**
* Returns the default language code of the active multilingual plugin.
*
* @since v2.6.2
*
* @return string
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
public static function get_default_language() {
$language = '';
switch ( static::get_multilang_plugin() ) {
case static::MULTILANG_PLUGIN_WPML:
$language = apply_filters( 'wpml_default_language', null );
break;
case static::MULTILANG_PLUGIN_TRANSLATEPRESS:
$settings = get_option( 'trp_settings', [] );
$language = $settings['default-language'] ?? '';
break;
}
return (string) apply_filters( 'plausible_analytics_default_language', (string) $language );
}
/**
* Get the name of the active multilang plugin.
*
* @since v2.6.2 Added TranslatePress support.
*
* @return string
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
public static function get_multilang_plugin_name() {
$names = [
static::MULTILANG_PLUGIN_WPML => 'WPML',
static::MULTILANG_PLUGIN_TRANSLATEPRESS => 'TranslatePress',
];
$name = $names[ static::get_multilang_plugin() ] ?? '';
return apply_filters( 'plausible_analytics_multilang_plugin_name', $name );
}
/**
* Get the user role for the logged-in user.
*
* @since 1.3.0
* @access public
* @return string
*/
public static function get_user_role() {
// wp_get_current_user() makes sure the current user is determined, e.g. in REST API requests.
$user_roles = (array) wp_get_current_user()->roles;
return array_shift( $user_roles );
}
/**
* Checks whether the current visitor should be tracked: logged-out visitors always are, logged-in users only when
* their role is enabled under "Track analytics for user roles". A logged-in user without a role on this site (e.g. a
* multisite super admin visiting a subsite) has no role that's enabled, so isn't tracked.
*
* @since 2.6.4
*
* @return bool
*/
public static function is_current_user_tracked() {
if ( ! is_user_logged_in() ) {
return true;
}
$user_role = static::get_user_role();
$tracked_user_roles = static::get_settings()['tracked_user_roles'] ?? [];
return ! empty( $user_role ) && in_array( $user_role, (array) $tracked_user_roles, true );
}
/**
* Wrapper to check if the Cloaked Affiliate Links option contains any values.
*
* @param array $settings Allows passing a current settings object.
*
* @return bool
*/
public static function is_cloaked_affiliate_links_enabled( $settings = [] ) {
if ( empty( $settings ) ) {
$settings = static::get_settings();
}
return static::setting_has_values( $settings, 'affiliate_links' );
}
/**
* Checks if a given array-type setting, within the given settings array, contains any non-empty values.
* Unlike a "get or default" helper, this never falls back to fetching live settings, so it's safe to
* reuse with partial or intentionally empty settings arrays (e.g., old vs. new option values).
*
* @param array $settings The settings array to check against.
* @param string $key The settings key to check.
*
* @return bool
*/
public static function setting_has_values( array $settings, $key ) {
$value = $settings[ $key ] ?? [];
// Assume it's an empty string.
if ( ! is_array( $value ) ) {
$value = []; // @codeCoverageIgnore
}
return ! empty( array_filter( $value ) );
}
/**
* Wrapper to check if the Query Params option contains any values.
*
* @return bool
*/
public static function is_query_params_enabled( $settings = [] ) {
if ( empty( $settings ) ) {
$settings = static::get_settings();
}
return static::setting_has_values( $settings, 'query_params' );
}
/**
* Checks if the main Plausible Analytics script is registered.
*
* The script is registered for every visitor, also for user roles that aren't tracked, so to decide whether to add
* tracking code, use @see self::main_script_is_initialized().
*
* @return bool
*/
public static function main_script_is_registered() {
return wp_script_is( 'plausible-analytics', 'registered' );
}
/**
* Checks if the main Plausible Analytics script is enqueued and initialized, i.e. the current visitor is tracked.
*
* Tracking code must only be added when it is: for a user role that isn't tracked, the script is registered but not
* enqueued, and neither is its inline plausible.init() call. A script that depends on it would still pull the tracker
* onto the page, which then leaves window.plausible an object instead of a function, so any call to it throws
* "window.plausible is not a function".
*
* wp_script_is( 'plausible-analytics', 'enqueued' ) isn't enough: it's also true while any enqueued script depends on
* it, e.g. another plugin's. So check that it's in the queue itself and that @see Assets::maybe_enqueue_main_script()
* added the plausible.init() call, which it only does for visitors that are tracked.
*
* @since 2.6.4
*
* @return bool
*/
public static function main_script_is_initialized() {
$scripts = wp_scripts();
$after = (array) $scripts->get_data( 'plausible-analytics', 'after' );
return in_array( 'plausible-analytics', $scripts->queue, true ) && strpos( implode( "\n", $after ), 'plausible.init(' ) !== false;
}
/**
* Translates a URL slug, e.g., WooCommerce's product base, to the given language.
*
* WPML's String Translation registers these bases as 'URL slug: {post type}' in the 'WordPress' domain, which is
* what WooCommerce Multilingual's Store URLs use too. TranslatePress doesn't translate post type bases.
*
* @since v2.6.2
*
* @param string $slug The untranslated slug, e.g. 'product'.
* @param string $language_code
* @param string $post_type The post-type the slug belongs to, e.g. 'product'.
*
* @return string
*
* @codeCoverageIgnore Because it depends on 3rd party plugins.
*/
public static function translate_url_slug( $slug, $language_code, $post_type = '' ) {
$translated = $slug;
if ( ! empty( $slug ) && ! empty( $language_code ) && ! empty( $post_type ) &&
static::get_multilang_plugin() === static::MULTILANG_PLUGIN_WPML ) {
$translated = apply_filters( 'wpml_translate_single_string', $slug, 'WordPress', "URL slug: $post_type", $language_code );
}
return (string) apply_filters( 'plausible_analytics_translated_url_slug', $translated, $slug, $language_code, $post_type );
}
/**
* @param string $option_name
* @param array|string|int $option_value
* @param string $key
*
* @return void
*/
public static function update_setting( $option_name, $option_value, $key = '' ) {
$settings = static::get_settings();
if ( ! empty( $key ) && is_array( $settings[ $option_name ] ) ) {
$settings[ $option_name ][ $key ] = $option_value;
} else {
$settings[ $option_name ] = $option_value;
}
update_option( 'plausible_analytics_settings', $settings );
}
}