-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfrench-typo.php
More file actions
1923 lines (1760 loc) · 62.9 KB
/
Copy pathfrench-typo.php
File metadata and controls
1923 lines (1760 loc) · 62.9 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
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: French Typo
* Plugin URI: https://github.com/jaz-on/french-typo
* Description: Automatically applies French typography rules to your content: non-breaking spaces before punctuation marks (; : ! ? % « »), optional French ordinal abbreviations (e.g. 1ère → 1re, 3ème → 3e), and special character replacements ((c) → ©, (r) → ®, (tm)/(TM) → ™).
* Version: 1.2.3
* Requires at least: 6.0
* Requires PHP: 7.4
* Tested up to: 7.0
* Author: Jason Rouet
* Author URI: https://profiles.wordpress.org/jaz_on/
* Contributors: jaz_on, audrasjb, juliobox, beryldlg
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: french-typo
* Domain Path: /languages
* GitHub Plugin URI: https://github.com/jaz-on/french-typo
* Primary Branch: main
*
* @package French_Typo
*/
// Security check: prevent direct access to the file.
defined( 'ABSPATH' ) || die( 'Silence is golden.' );
define( 'FRENCH_TYPO_VERSION', '1.2.3' );
/**
* Load plugin text domain for translations.
*
* @since 1.2.0
*/
function french_typo_load_textdomain() {
load_plugin_textdomain(
'french-typo',
false,
dirname( plugin_basename( __FILE__ ) ) . '/languages'
);
}
add_action( 'init', 'french_typo_load_textdomain', 0 );
/**
* Initialize plugin hooks.
*
* Sets up filters for content processing and admin menu if in admin area.
*
* @since 1.0.0
*/
function french_typo_hooks() {
// Apply typography rules to post titles and content.
add_filter( 'the_title', 'french_typo_replace_wrapper' );
add_filter( 'the_content', 'french_typo_replace_wrapper' );
add_filter( 'the_excerpt', 'french_typo_replace_wrapper' );
// Apply to widgets.
add_filter( 'widget_text', 'french_typo_replace_wrapper' );
add_filter( 'widget_text_content', 'french_typo_replace_wrapper' );
add_filter( 'widget_block_content', 'french_typo_replace_wrapper' );
add_filter( 'widget_title', 'french_typo_replace_wrapper' );
add_filter( 'widget_text_title', 'french_typo_replace_wrapper' );
add_filter( 'widget_block_title', 'french_typo_replace_wrapper' );
// Apply to menu items.
add_filter( 'wp_nav_menu_items', 'french_typo_replace_wrapper' );
// Apply to taxonomies (categories, tags, custom taxonomies).
add_filter( 'term_description', 'french_typo_replace_wrapper' );
add_filter( 'single_term_title', 'french_typo_replace_wrapper' );
add_filter( 'single_cat_title', 'french_typo_replace_wrapper' );
add_filter( 'single_tag_title', 'french_typo_replace_wrapper' );
add_filter( 'single_post_type_archive_title', 'french_typo_replace_wrapper' );
// Apply to archive titles and descriptions.
add_filter( 'get_the_archive_title', 'french_typo_replace_wrapper' );
add_filter( 'get_the_archive_description', 'french_typo_replace_wrapper' );
// Apply to comments.
add_filter( 'comment_text', 'french_typo_replace_wrapper' );
add_filter( 'get_comment_author', 'french_typo_replace_wrapper' );
// Support for Advanced Custom Fields (ACF).
if ( function_exists( 'get_field' ) ) {
add_filter( 'acf/format_value/type=text', 'french_typo_replace_custom_field' );
add_filter( 'acf/format_value/type=textarea', 'french_typo_replace_custom_field' );
add_filter( 'acf/format_value/type=wysiwyg', 'french_typo_replace_custom_field' );
}
// Support for Meta Box plugin.
if ( function_exists( 'rwmb_get_value' ) ) {
add_filter( 'rwmb_the_value', 'french_typo_replace_custom_field' );
}
// Apply to RSS feeds.
add_filter( 'the_title_rss', 'french_typo_replace_rss_title' );
add_filter( 'the_content_feed', 'french_typo_replace_rss_content' );
add_filter( 'the_excerpt_rss', 'french_typo_replace_rss_excerpt' );
add_filter( 'comment_text_rss', 'french_typo_replace_rss_comment' );
// Apply to REST API responses.
add_filter( 'rest_prepare_post', 'french_typo_rest_api_post' );
add_filter( 'rest_prepare_page', 'french_typo_rest_api_post' );
add_filter( 'rest_prepare_attachment', 'french_typo_rest_api_post' );
// Apply to user profiles.
add_filter( 'get_the_author_description', 'french_typo_replace_wrapper' );
add_filter( 'get_user_metadata', 'french_typo_user_meta', 10, 5 );
// Apply to breadcrumbs (Yoast, Rank Math, SEOPress).
if ( defined( 'WPSEO_VERSION' ) ) {
add_filter( 'wpseo_breadcrumb_links', 'french_typo_breadcrumbs' );
}
if ( defined( 'RANK_MATH_VERSION' ) ) {
add_filter( 'rank_math/frontend/breadcrumb/items', 'french_typo_breadcrumbs' );
}
if ( defined( 'SEOPRESS_VERSION' ) ) {
add_filter( 'seopress_breadcrumbs_items', 'french_typo_breadcrumbs' );
}
// Support for SEO plugins meta descriptions.
// Yoast SEO.
if ( defined( 'WPSEO_VERSION' ) ) {
add_filter( 'wpseo_metadesc', 'french_typo_replace' );
add_filter( 'wpseo_title', 'french_typo_replace' );
add_filter( 'wpseo_opengraph_title', 'french_typo_replace' );
add_filter( 'wpseo_opengraph_desc', 'french_typo_replace' );
add_filter( 'wpseo_twitter_title', 'french_typo_replace' );
add_filter( 'wpseo_twitter_description', 'french_typo_replace' );
}
// Rank Math.
if ( defined( 'RANK_MATH_VERSION' ) ) {
add_filter( 'rank_math/frontend/title', 'french_typo_replace' );
add_filter( 'rank_math/frontend/description', 'french_typo_replace' );
add_filter( 'rank_math/opengraph/title', 'french_typo_replace' );
add_filter( 'rank_math/opengraph/description', 'french_typo_replace' );
add_filter( 'rank_math/twitter/title', 'french_typo_replace' );
add_filter( 'rank_math/twitter/description', 'french_typo_replace' );
}
// SEOPress.
if ( defined( 'SEOPRESS_VERSION' ) ) {
add_filter( 'seopress_titles_title', 'french_typo_replace' );
add_filter( 'seopress_titles_desc', 'french_typo_replace' );
add_filter( 'seopress_social_og_title', 'french_typo_replace' );
add_filter( 'seopress_social_og_desc', 'french_typo_replace' );
add_filter( 'seopress_social_twitter_title', 'french_typo_replace' );
add_filter( 'seopress_social_twitter_desc', 'french_typo_replace' );
}
// Generic filter for custom fields and other content.
add_filter( 'french_typo_process_text', 'french_typo_replace' );
// Only load admin functionality when in WordPress admin area.
if ( is_admin() ) {
add_action( 'admin_menu', 'french_typo_admin_menu' );
add_action( 'admin_init', 'french_typo_admin_init' );
add_action( 'admin_init', 'french_typo_handle_mlp_notice_dismiss' );
add_action( 'admin_notices', 'french_typo_mlp_notice' );
add_action( 'admin_enqueue_scripts', 'french_typo_admin_enqueue_scripts' );
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'french_typo_action_links' );
add_filter( 'plugin_row_meta', 'french_typo_plugin_row_meta', 10, 2 );
}
}
add_action( 'init', 'french_typo_hooks' );
/**
* Get plugin options with static cache and processed values.
*
* Retrieves plugin options from database, processes them, and caches them in memory
* to avoid repeated processing. WordPress already caches options via get_option().
*
* @since 1.0.0
*
* @return array Processed plugin options array with ready-to-use values.
*/
function french_typo_get_options() {
static $cached_processed_options = null;
// Test seam: force a fresh read when the test suite needs to mutate options between assertions.
if ( defined( 'FRENCH_TYPO_TEST_NO_OPTIONS_CACHE' ) && FRENCH_TYPO_TEST_NO_OPTIONS_CACHE ) {
$cached_processed_options = null;
}
// If cache is empty, load and process options.
if ( null === $cached_processed_options ) {
$raw_options = get_option( 'french_typo_options', array() );
// Default values for all options.
$defaults = array(
'narrow_space' => false,
'special_characters' => true,
'apply_to_titles' => true,
'apply_to_content' => true,
'apply_to_excerpts' => true,
'apply_to_widgets' => true,
'apply_to_menus' => true,
'apply_to_custom_fields' => true,
'apply_to_taxonomies' => true,
'apply_to_archives' => true,
'apply_to_comments' => true,
'apply_to_rss' => true,
'apply_to_rest_api' => true,
'apply_to_user_profiles' => true,
'apply_to_breadcrumbs' => true,
'ordinal_abbreviations' => true,
// Language restriction (1.2.2).
'language_restriction_mode' => 'off', // One of: off, auto_fr, custom.
'language_restriction_locales' => array(),
'mlp_notice_dismissed' => false,
);
// Merge raw options with defaults using wp_parse_args().
$cached_processed_options = wp_parse_args( $raw_options, $defaults );
if ( $cached_processed_options['narrow_space'] ) {
$cached_processed_options['narrow_space'] = 1 === $cached_processed_options['narrow_space'] ? ' ' : ' ';
} else {
$cached_processed_options['narrow_space'] = false;
}
}
return $cached_processed_options;
}
/**
* Normalize HTML tag name to local lowercase (strip XML / SVG prefix).
*
* @since 1.2.0
*
* @param string $name Raw tag name from markup.
* @return string Local tag name.
*/
function french_typo_markup_tag_local_name( $name ) {
$name = strtolower( $name );
if ( false !== strpos( $name, ':' ) ) {
$parts = explode( ':', $name );
return end( $parts );
}
return $name;
}
/**
* Whether a pre opening tag is Gutenberg Verse without the Code block class.
*
* @since 1.2.0
*
* @param string $attr_region Text between the tag name and the closing '>'.
* @return bool True when typography should still run inside (do not push pre on stack).
*/
function french_typo_markup_pre_is_verse_not_code( $attr_region ) {
if ( ! preg_match( '#\bclass\s*=\s*("|\')([^"\']*)\1#iu', $attr_region, $m ) ) {
return false;
}
$classes = $m[2];
if ( ! preg_match( '#\bwp-block-verse\b#iu', $classes ) ) {
return false;
}
if ( preg_match( '#\bwp-block-code\b#iu', $classes ) ) {
return false;
}
return true;
}
/**
* Update stack of raw-text elements (script, style, pre, code, textarea) from one wp_html_split() tag segment.
*
* Malformed HTML: closing tag pops only when it matches the stack top (strict LIFO).
*
* @since 1.2.0
*
* @param array $stack Stack of open raw tag local names (modified by reference).
* @param string $segment Full tag segment starting with '<'.
*/
function french_typo_markup_stack_update( array &$stack, $segment ) {
static $raw_flip = null;
static $void_flip = null;
if ( null === $raw_flip ) {
$raw_flip = array_flip( array( 'script', 'style', 'pre', 'code', 'textarea' ) );
$void_flip = array_flip(
array(
'area',
'base',
'br',
'col',
'embed',
'hr',
'img',
'input',
'link',
'meta',
'param',
'source',
'track',
'wbr',
)
);
}
$events = array();
if ( preg_match_all( '#</\s*([A-Za-z0-9:]+)\s*>#u', $segment, $m, PREG_OFFSET_CAPTURE ) ) {
foreach ( $m[0] as $i => $hit ) {
$nm = french_typo_markup_tag_local_name( $m[1][ $i ][0] );
if ( isset( $raw_flip[ $nm ] ) ) {
$events[ $hit[1] ] = array( 'close', $nm );
}
}
}
if ( preg_match_all( '#<\s*(?!/)([A-Za-z0-9:]+)([^>]*)>#u', $segment, $m, PREG_OFFSET_CAPTURE ) ) {
foreach ( $m[0] as $i => $hit ) {
$nm = french_typo_markup_tag_local_name( $m[1][ $i ][0] );
$rest = $m[2][ $i ][0];
if ( ! isset( $raw_flip[ $nm ] ) ) {
continue;
}
if ( isset( $void_flip[ $nm ] ) ) {
continue;
}
if ( preg_match( '#/\s*$#u', $rest ) ) {
continue;
}
if ( 'pre' === $nm && french_typo_markup_pre_is_verse_not_code( $rest ) ) {
continue;
}
$events[ $hit[1] ] = array( 'open', $nm );
}
}
ksort( $events, SORT_NUMERIC );
foreach ( $events as $ev ) {
if ( 'close' === $ev[0] ) {
if ( ! empty( $stack ) && end( $stack ) === $ev[1] ) {
array_pop( $stack );
}
} else {
$stack[] = $ev[1];
}
}
}
/**
* Generic wrapper function for French typo filters.
* Uses current_filter() to determine which option to check.
* Optimized for performance - no closures, single function for all simple filters.
*
* @since 1.1
*
* @param string $text The text to process.
* @return string The processed text.
*/
function french_typo_replace_wrapper( $text ) {
// Map hooks to option keys (static for performance).
static $hook_option_map = array(
'the_title' => 'apply_to_titles',
'the_content' => 'apply_to_content',
'the_excerpt' => 'apply_to_excerpts',
'widget_text' => 'apply_to_widgets',
'widget_text_content' => 'apply_to_widgets',
'widget_block_content' => 'apply_to_widgets',
'widget_title' => 'apply_to_widgets',
'widget_text_title' => 'apply_to_widgets',
'widget_block_title' => 'apply_to_widgets',
'wp_nav_menu_items' => 'apply_to_menus',
'term_description' => 'apply_to_taxonomies',
'single_term_title' => 'apply_to_taxonomies',
'single_cat_title' => 'apply_to_taxonomies',
'single_tag_title' => 'apply_to_taxonomies',
'single_post_type_archive_title' => 'apply_to_taxonomies',
'get_the_archive_title' => 'apply_to_archives',
'get_the_archive_description' => 'apply_to_archives',
'comment_text' => 'apply_to_comments',
'get_comment_author' => 'apply_to_comments',
'get_the_author_description' => 'apply_to_user_profiles',
);
// Filters where get_the_ID() reliably yields the current post.
static $post_level_filters = array(
'the_title' => true,
'the_content' => true,
'the_excerpt' => true,
);
$current = current_filter();
// Get the option key for this hook.
$option_key = $hook_option_map[ $current ] ?? null;
// Check if processing is enabled for this content type.
$options = french_typo_get_options();
if ( $options[ $option_key ] ) {
$post_id = null;
if ( isset( $post_level_filters[ $current ] ) && function_exists( 'get_the_ID' ) ) {
$resolved = get_the_ID();
if ( is_int( $resolved ) && $resolved > 0 ) {
$post_id = $resolved;
}
}
return french_typo_replace( $text, $post_id );
}
return $text;
}
/**
* Apply French typography rules to custom fields.
*
* Wrapper function that checks if custom field processing is enabled before applying rules.
*
* @since 1.0.0
*
* @param mixed $value The custom field value to process.
* @return mixed The processed custom field value.
*/
function french_typo_replace_custom_field( $value ) {
// Only process string values.
if ( ! is_string( $value ) ) {
return $value;
}
$options = french_typo_get_options();
if ( $options['apply_to_custom_fields'] ) {
return french_typo_replace( $value );
}
return $value;
}
/**
* Apply French typography rules to RSS feed titles.
*
* Wrapper function that checks if RSS processing is enabled before applying rules.
*
* @since 1.0.0
*
* @param string $text The RSS title text to process.
* @return string The processed RSS title text.
*/
function french_typo_replace_rss_title( $text ) {
$options = french_typo_get_options();
if ( $options['apply_to_rss'] && $options['apply_to_titles'] ) {
return french_typo_replace( $text );
}
return $text;
}
/**
* Apply French typography rules to RSS feed content.
*
* Wrapper function that checks if RSS processing is enabled before applying rules.
*
* @since 1.0.0
*
* @param string $text The RSS content text to process.
* @return string The processed RSS content text.
*/
function french_typo_replace_rss_content( $text ) {
$options = french_typo_get_options();
if ( $options['apply_to_rss'] && $options['apply_to_content'] ) {
return french_typo_replace( $text );
}
return $text;
}
/**
* Apply French typography rules to RSS feed excerpts.
*
* Wrapper function that checks if RSS processing is enabled before applying rules.
*
* @since 1.0.0
*
* @param string $text The RSS excerpt text to process.
* @return string The processed RSS excerpt text.
*/
function french_typo_replace_rss_excerpt( $text ) {
$options = french_typo_get_options();
if ( $options['apply_to_rss'] && $options['apply_to_excerpts'] ) {
return french_typo_replace( $text );
}
return $text;
}
/**
* Apply French typography rules to RSS feed comments.
*
* Wrapper function that checks if RSS processing is enabled before applying rules.
*
* @since 1.0.0
*
* @param string $text The RSS comment text to process.
* @return string The processed RSS comment text.
*/
function french_typo_replace_rss_comment( $text ) {
$options = french_typo_get_options();
if ( $options['apply_to_rss'] && $options['apply_to_comments'] ) {
return french_typo_replace( $text );
}
return $text;
}
/**
* Apply French typography rules to REST API responses.
*
* Processes post/page/attachment data in REST API responses.
*
* @since 1.0.0
*
* @param WP_REST_Response $response The response object.
* @return WP_REST_Response Modified response object.
*/
function french_typo_rest_api_post( $response ) {
$options = french_typo_get_options();
if ( $options['apply_to_rest_api'] ) {
$data = $response->get_data();
// Process title if enabled.
if ( isset( $data['title']['rendered'] ) && $options['apply_to_titles'] ) {
$data['title']['rendered'] = french_typo_replace( $data['title']['rendered'] );
}
// Process content if enabled.
if ( isset( $data['content']['rendered'] ) && $options['apply_to_content'] ) {
$data['content']['rendered'] = french_typo_replace( $data['content']['rendered'] );
}
// Process excerpt if enabled.
if ( isset( $data['excerpt']['rendered'] ) && $options['apply_to_excerpts'] ) {
$data['excerpt']['rendered'] = french_typo_replace( $data['excerpt']['rendered'] );
}
$response->set_data( $data );
}
return $response;
}
/**
* Apply French typography rules to user metadata (biography).
*
* Hooks `get_user_metadata`, fetches the raw value without recursion, then returns
* the processed value when the biography (`description`) field is read.
*
* @since 1.0.0
*
* @param mixed $pre_value Value to return if short-circuiting, or null to continue.
* @param int $object_id User ID.
* @param string $meta_key Meta key.
* @param bool $single Whether to return a single value.
* @param string $meta_type Object type (must be `user`).
* @return mixed Filtered meta, or $pre_value to let WordPress load meta normally.
*/
function french_typo_user_meta( $pre_value, $object_id, $meta_key, $single, $meta_type ) {
if ( 'user' !== $meta_type || 'description' !== $meta_key ) {
return $pre_value;
}
$options = french_typo_get_options();
if ( ! $options['apply_to_user_profiles'] ) {
return $pre_value;
}
remove_filter( 'get_user_metadata', 'french_typo_user_meta', 10 );
$value = get_user_meta( $object_id, $meta_key, $single );
add_filter( 'get_user_metadata', 'french_typo_user_meta', 10, 5 );
if ( is_string( $value ) ) {
return french_typo_replace( $value );
}
if ( is_array( $value ) ) {
return array_map( 'french_typo_replace', $value );
}
return $pre_value;
}
/**
* Apply French typography rules to breadcrumbs.
*
* Processes breadcrumb items from SEO plugins.
*
* @since 1.0.0
*
* @param array $items Array of breadcrumb items.
* @return array Modified array of breadcrumb items.
*/
function french_typo_breadcrumbs( $items ) {
$options = french_typo_get_options();
if ( $options['apply_to_breadcrumbs'] ) {
foreach ( $items as $key => $item ) {
if ( isset( $item['text'] ) && is_string( $item['text'] ) ) {
$items[ $key ]['text'] = french_typo_replace( $item['text'] );
}
if ( isset( $item['title'] ) && is_string( $item['title'] ) ) {
$items[ $key ]['title'] = french_typo_replace( $item['title'] );
}
}
}
return $items;
}
/**
* Normalize French ordinal abbreviations in a plain-text segment (1ère → 1re, 3ème → 3e, n-ième → nième).
*
* English forms (1st, 2nd) and non-standard 1ème are left unchanged. Uses UTF-8-safe patterns.
*
* @since 1.2.0
*
* @param string $segment Text segment (no HTML tags).
* @return string Segment with ordinal abbreviations normalized.
*/
function french_typo_apply_ordinal_abbreviations( $segment ) {
if ( '' === $segment || mb_strlen( $segment ) < 3 ) {
return $segment;
}
// Indefinite ordinals: n-ième / x-ième (hyphen, non-breaking hyphen, en dash).
$segment = preg_replace_callback(
'#(?<![\p{L}\p{N}])([nNxX])([\-\x{2011}\x{2013}])(?i)ième(?![\p{L}\p{N}])#u',
static function ( $m ) {
return $m[1] . 'ième';
},
$segment
);
// Feminine first: 1ère → 1re (not 11ère, 21ère, etc.).
$segment = preg_replace_callback(
'#(?<![0-9])1(?![0-9])((?i)ère)#u',
static function ( $m ) {
$s = $m[1];
$first = mb_substr( $s, 0, 1, 'UTF-8' );
$last = mb_substr( $s, 2, 1, 'UTF-8' );
$r_upper = ( mb_strtoupper( $first, 'UTF-8' ) === $first && preg_match( '/\p{L}/u', $first ) );
$r_char = $r_upper ? 'R' : 'r';
$e_char = ( mb_strtoupper( $last, 'UTF-8' ) === $last && preg_match( '/\p{L}/u', $last ) ) ? 'E' : 'e';
return '1' . $r_char . $e_char;
},
$segment
);
// Abbreviated ordinals ≥ 2: Nème → Ne for N in 2–999 (single digit 2–9 or 10–999).
$segment = preg_replace_callback(
'#(?<![0-9])((?:[2-9]|[1-9][0-9]{1,2}))(?i)(ème)(?![0-9])#u',
static function ( $m ) {
$num = $m[1];
$suf = $m[2];
$last = mb_substr( $suf, -1, 1, 'UTF-8' );
$e_ch = ( mb_strtoupper( $last, 'UTF-8' ) === $last && preg_match( '/\p{L}/u', $last ) ) ? 'E' : 'e';
return $num . $e_ch;
},
$segment
);
return $segment;
}
/**
* Whether a multilingual plugin is currently active (Polylang or WPML).
*
* @since 1.2.2
*
* @return bool
*/
function french_typo_multilingual_plugin_detected() {
return function_exists( 'pll_current_language' ) || defined( 'ICL_LANGUAGE_CODE' );
}
/**
* Return the list of locales the admin can pick from in the "Custom" restriction mode.
*
* Union of:
* - WordPress installed locales (get_available_languages())
* - Site locale + en_US
* - Polylang configured locales (when Polylang is active)
* - WPML configured locales (when WPML is active)
* - Common French locales (so admins can opt-in before installing a language pack)
*
* @since 1.2.2
*
* @return array<int, string> Locales (e.g. 'fr_FR', 'en_US'), unique, indexed from 0.
*/
function french_typo_get_known_locales() {
$list = array( 'fr_FR', 'fr_BE', 'fr_CA', 'fr_CH', 'fr_LU', 'en_US' );
if ( function_exists( 'get_locale' ) ) {
$list[] = get_locale();
}
if ( function_exists( 'get_available_languages' ) ) {
$installed = get_available_languages();
if ( is_array( $installed ) ) {
$list = array_merge( $list, $installed );
}
}
if ( function_exists( 'pll_languages_list' ) ) {
$pll = pll_languages_list( array( 'fields' => 'locale' ) );
if ( is_array( $pll ) ) {
$list = array_merge( $list, $pll );
}
}
if ( function_exists( 'apply_filters' ) ) {
$wpml = apply_filters( 'wpml_active_languages', null );
if ( is_array( $wpml ) ) {
foreach ( $wpml as $lang ) {
if ( is_array( $lang ) && ! empty( $lang['default_locale'] ) ) {
$list[] = (string) $lang['default_locale'];
}
}
}
}
$list = array_filter(
array_map( 'strval', $list ),
static function ( $loc ) {
return '' !== $loc;
}
);
return array_values( array_unique( $list ) );
}
/**
* Resolve the locale for the current filter context.
*
* Priority chain:
* 1. Polylang per-post (when a post id is available and Polylang is active)
* 2. WPML per-post (when a post id is available and WPML is active)
* 3. Polylang current language (no post context)
* 4. WPML current language (via ICL_LANGUAGE_CODE + wpml_active_languages mapping)
* 5. Site locale (get_locale())
*
* The fallback site-locale result is memoized statically per-request; per-post
* results are not memoized because different posts in the same request can have
* different locales (REST list endpoints, RSS feeds, etc.).
*
* @since 1.2.2
*
* @param int|null $post_id Optional post id when known by the caller.
* @return string Locale string (e.g. 'fr_FR'). Falls back to get_locale().
*/
function french_typo_get_current_locale( $post_id = null ) {
static $site_locale_cache = null;
// Test seam: force fresh site-locale read between assertions.
if ( defined( 'FRENCH_TYPO_TEST_NO_LOCALE_CACHE' ) && FRENCH_TYPO_TEST_NO_LOCALE_CACHE ) {
$site_locale_cache = null;
}
if ( null === $post_id && function_exists( 'get_the_ID' ) ) {
$resolved = get_the_ID();
if ( is_int( $resolved ) && $resolved > 0 ) {
$post_id = $resolved;
}
}
if ( $post_id ) {
if ( function_exists( 'pll_get_post_language' ) ) {
$loc = pll_get_post_language( $post_id, 'locale' );
if ( is_string( $loc ) && '' !== $loc ) {
return $loc;
}
}
if ( function_exists( 'apply_filters' ) ) {
$wpml_post = apply_filters( 'wpml_post_language_details', null, $post_id );
if ( is_array( $wpml_post ) && ! empty( $wpml_post['locale'] ) ) {
return (string) $wpml_post['locale'];
}
}
}
if ( function_exists( 'pll_current_language' ) ) {
$loc = pll_current_language( 'locale' );
if ( is_string( $loc ) && '' !== $loc ) {
return $loc;
}
}
if ( defined( 'ICL_LANGUAGE_CODE' ) && function_exists( 'apply_filters' ) ) {
$wpml_active = apply_filters( 'wpml_active_languages', null );
if ( is_array( $wpml_active ) && isset( $wpml_active[ ICL_LANGUAGE_CODE ]['default_locale'] ) ) {
return (string) $wpml_active[ ICL_LANGUAGE_CODE ]['default_locale'];
}
}
if ( null === $site_locale_cache ) {
$site_locale_cache = function_exists( 'get_locale' ) ? (string) get_locale() : '';
}
return $site_locale_cache;
}
/**
* Whether typography should run for the given locale, given the current restriction settings.
*
* @since 1.2.2
*
* @param string $locale Locale string (e.g. 'fr_FR', 'en_US'). Empty string treated as "unknown".
* @param array $options Processed plugin options array (from french_typo_get_options()).
* @return bool True when typography should run.
*/
function french_typo_locale_is_allowed( $locale, $options ) {
$mode = isset( $options['language_restriction_mode'] ) ? $options['language_restriction_mode'] : 'off';
if ( 'off' === $mode ) {
return true;
}
if ( '' === (string) $locale ) {
// Unknown locale: when restriction is on, do not apply (safer default for non-French sites).
return false;
}
if ( 'auto_fr' === $mode ) {
return 'fr' === $locale || 0 === strpos( $locale, 'fr_' );
}
if ( 'custom' === $mode ) {
$locales = isset( $options['language_restriction_locales'] ) && is_array( $options['language_restriction_locales'] )
? $options['language_restriction_locales']
: array();
return in_array( $locale, $locales, true );
}
return true;
}
/**
* Apply French typography rules to text content.
*
* Processes text to add non-breaking spaces before/after punctuation and replaces
* special character sequences. Optionally normalizes French ordinal abbreviations (1ère → 1re, etc.).
* Skips HTML tag segments, shortcode segments (leading `[`),
* and raw text inside script, style, pre, code, and textarea (stack-aware, including nesting).
*
* @since 1.0.0
*
* @param string $text The text content to process.
* @param int|null $post_id Optional post id used for per-post language detection (Polylang / WPML).
* @return string The processed text with French typography rules applied.
*/
function french_typo_replace( $text, $post_id = null ) {
static $cache = array();
// Early return for empty or very short text to avoid unnecessary processing.
if ( ! is_string( $text ) || mb_strlen( $text ) < 3 ) {
return $text;
}
$cache_max_size = 50; // Limit cache to 50 entries to prevent memory issues.
$cache_threshold = 100; // Only cache texts longer than this.
$text_length = mb_strlen( $text );
$use_cache = ( $text_length >= $cache_threshold );
$cache_key = null;
// Get processed plugin options (already cached and ready to use).
$options = french_typo_get_options();
// Language restriction guard: short-circuit when the current locale is not allowed.
// Covers both wrapper-routed filters and direct callers (SEO meta hooks, custom code).
$lang_mode = isset( $options['language_restriction_mode'] ) ? $options['language_restriction_mode'] : 'off';
if ( 'off' !== $lang_mode ) {
$current_locale = french_typo_get_current_locale( $post_id );
if ( ! french_typo_locale_is_allowed( $current_locale, $options ) ) {
return $text;
}
}
$has_typo = $options['narrow_space'] || $options['special_characters'] || ! empty( $options['ordinal_abbreviations'] );
if ( ! $has_typo ) {
return $text;
}
$narrow_key = $options['narrow_space'] ? (string) crc32( (string) $options['narrow_space'] ) : '0';
$special_key = $options['special_characters'] ? '1' : '0';
$ordinal_key = ! empty( $options['ordinal_abbreviations'] ) ? '1' : '0';
$lang_key = 'off' === $lang_mode ? 'a' : 'b';
if ( $use_cache ) {
$cache_key = crc32( $text ) . '_' . $text_length . '_' . $narrow_key . '_' . $special_key . '_' . $ordinal_key . '_' . $lang_key;
if ( isset( $cache[ $cache_key ] ) ) {
return $cache[ $cache_key ];
}
}
static $static_replacements = array(
'(TM)' => '™',
'(c)' => '©',
'(r)' => '®',
'(tm)' => '™',
);
$nbs = $options['narrow_space'] ? $options['narrow_space'] : '';
$nbs_marker = '___FT_NBSP___';
// Matches every NBSP variant we may encounter: U+00A0 / U+202F literals,
// named entity, and decimal / hex numeric entities with optional zero padding.
$nbs_any = '(?:\x{00A0}|\x{202F}| |&\#0*160;|&\#0*8239;|&\#[xX]0*[aA]0;|&\#[xX]0*202[fF];)';
if ( $options['narrow_space'] ) {
// Canonicalize every NBSP variant to a single dedicated marker. The marker is not an HTML
// entity, so the entity-protection step below leaves it intact; the punctuation regex can
// then detect "NBSP already present" reliably and stays idempotent across repeated calls
// (e.g. when Elementor pipes content through both widget_text and the_content filters).
$text = preg_replace( '#' . $nbs_any . '#u', $nbs_marker, $text );
}
$nbs_marker_quoted = preg_quote( $nbs_marker, '#' );
$has_markup = ( false !== strpos( $text, '<' ) || false !== strpos( $text, '[' ) );
// Protect HTML entities before narrow-space regexes. The trailing `;` of an
// entity (e.g. `&`, `&`, ` `) is NOT French punctuation and
// must not trigger the nbsp-before-`;` rule. This protection runs whenever
// the text contains `&`, regardless of whether tags / shortcodes are also
// present — plain titles like "Foo & Bar" (post `convert_chars`) take
// the plain-text path and were previously unprotected.
$entities = array();
$placeholders = array();
if ( $options['narrow_space'] && false !== strpos( $text, '&' ) ) {
preg_match_all( '/&#?[a-zA-Z0-9]{1,31};/', $text, $matches );
if ( ! empty( $matches[0] ) ) {
$entities = array_unique( $matches[0] );
foreach ( $entities as $index => $entity ) {
$placeholders[] = '___FT_ENT_' . $index . '___';
}
$text = str_replace( $entities, $placeholders, $text );
}
}
if ( $has_markup ) {
$segments = wp_html_split( $text );
$processed = '';
$stack = array();
foreach ( $segments as $segment ) {
if ( ! empty( $segment ) && '<' === $segment[0] ) {
french_typo_markup_stack_update( $stack, $segment );
}
if ( ! empty( $segment ) && '<' !== $segment[0] && '[' !== $segment[0] ) {
if ( empty( $stack ) ) {
if ( $options['special_characters'] ) {
$segment = strtr( $segment, $static_replacements );
}
if ( ! empty( $options['ordinal_abbreviations'] ) ) {
$segment = french_typo_apply_ordinal_abbreviations( $segment );
}
if ( $options['narrow_space'] ) {
// Add non-breaking space before punctuation (avoid if already exists).
$segment = preg_replace( '#(?<!' . $nbs_marker_quoted . ')\s*([?!:;%»])(?!\w)(?!/{2})#u', $nbs_marker . '$1', $segment );
// Add non-breaking space after « (avoid if already exists).
$segment = preg_replace( '#([«])(?!' . $nbs_marker_quoted . ')\s*#u', '$1' . $nbs_marker, $segment );
}
}
}
$processed .= $segment;
}
$text = $processed;
} else {
if ( $options['special_characters'] ) {
$text = strtr( $text, $static_replacements );
}
if ( ! empty( $options['ordinal_abbreviations'] ) ) {
$text = french_typo_apply_ordinal_abbreviations( $text );
}
if ( $options['narrow_space'] ) {
// Plain text: process directly without splitting.
// Add non-breaking space before punctuation (avoid if already exists).
$text = preg_replace( '#(?<!' . $nbs_marker_quoted . ')\s*([?!:;%»])(?!\w)(?!/{2})#u', $nbs_marker . '$1', $text );
// Add non-breaking space after « (avoid if already exists).
$text = preg_replace( '#([«])(?!' . $nbs_marker_quoted . ')\s*#u', '$1' . $nbs_marker, $text );
}
}
if ( ! empty( $entities ) ) {
$text = str_replace( $placeholders, $entities, $text );
}
if ( $options['narrow_space'] ) {
// Restore the marker as the configured NBSP form, collapsing accidental runs (e.g. double
// insertion from layered filters) to a single canonical NBSP.
$text = preg_replace( '#(?:' . $nbs_marker_quoted . ')+#u', $nbs, $text );
}
if ( $use_cache ) {
if ( count( $cache ) >= $cache_max_size ) {
$cache = array_slice( $cache, 10, null, true );
}
$cache[ $cache_key ] = $text;
}
return $text;
}
/**
* Display an admin notice on the French Typo settings page when a multilingual
* plugin (Polylang or WPML) is detected and the language-restriction mode is
* still "off". Lets the admin discover the new feature without forcing any
* change of behavior.
*
* @since 1.2.2
*/
function french_typo_mlp_notice() {
if ( ! is_admin() || ! function_exists( 'current_user_can' ) || ! current_user_can( 'manage_options' ) ) {