-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendmark.php
More file actions
1675 lines (1444 loc) · 71.3 KB
/
endmark.php
File metadata and controls
1675 lines (1444 loc) · 71.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
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: Endmark
* Plugin URI: https://github.com/menj/endmark
* Description: Adds an end-of-article symbol to the end of posts and pages.
* Version: 4.2
* Author: MENJ
* Author URI: https://menj.org
* License: GPL-3.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
* Text Domain: endmark
* Domain Path: /languages
* Requires at least: 5.0
* Requires PHP: 7.4
*/
if (!defined('ABSPATH')) {
exit;
}
/**
* Main Endmark Plugin Class
*/
class Endmark_Plugin {
/**
* Plugin version
*/
const VERSION = '4.2';
/**
* Option names
*/
const OPTION_SITE = 'endmark_settings';
const OPTION_NETWORK = 'endmark_network_settings';
const OPTION_PRESETS = 'endmark_presets';
const OPTION_VERSION = 'endmark_version';
/**
* Detection constants
*/
const ANTI_DUP_COMMENT = '<!-- endmark:inserted -->';
const WRAPPER_CLASS = 'endmark-wrap';
const WRAPPER_CLASS_TOKEN = 'class="endmark-wrap"';
const SHORTCODE_TAG = 'endmark';
const BLOCK_NAME = 'endmark/endmark';
/**
* Protected schema types that endmark must not interfere with
*/
const PROTECTED_SCHEMA_TYPES = array(
'FAQPage',
'HowTo',
'HowToStep',
'QAPage',
'Question',
'Answer',
'Recipe',
'Review',
'Product',
);
/**
* Allowed schema types for endmark output
*/
const ALLOWED_SCHEMA_TYPES = array('WebPageElement', 'CreativeWork');
/**
* Forbidden schema types that endmark must never output
*/
const FORBIDDEN_SCHEMA_TYPES = array(
'Article',
'BlogPosting',
'FAQPage',
'HowTo',
'BreadcrumbList',
'Product',
'Review',
);
/**
* Single instance
*/
private static $instance = null;
/**
* Site-level defaults
*/
private $site_defaults = array(
'enabled' => true,
'where' => 'post',
'type' => 'symbol',
'symbol' => '∎',
'image_url' => '',
'image_id' => 0,
'image_size_px' => 16,
'placement_mode' => 'last_paragraph',
'placement_selector' => '',
'min_word_count' => 0,
'exclude_categories' => array(),
'exclude_tags' => array(),
'exclude_post_ids' => array(),
'hide_on_mobile' => false,
'disable_on_amp' => true,
'use_css_variables' => true,
'margin_top' => '0',
'margin_left' => '0.25em',
'typography_scale_enabled' => false,
'typography_scale_unit' => 'px',
'fast_mode' => false,
'allow_svg' => false,
'schema_enabled' => false,
'schema_mode' => 'WebPageElement',
);
/**
* Allowlists for sanitization
*/
private $allowlists = array(
'where' => array('post', 'page', 'both'),
'type' => array('symbol', 'image'),
'placement_mode' => array('last_paragraph', 'before_footnotes', 'after_footnotes', 'append', 'selector'),
'typography_scale_unit' => array('px', 'em', 'rem'),
'schema_mode' => array('WebPageElement', 'CreativeWork'),
);
/**
* Unsafe HTML containers
*/
private $unsafe_containers = array('table', 'ul', 'ol', 'blockquote', 'figure', 'pre', 'code');
/**
* Footnote detection patterns
*/
private $footnote_patterns = array(
'<ol class="footnotes"',
'<div class="footnotes"',
'<div id="footnotes"',
'<section class="footnotes"',
'<div class="simple-footnotes"',
'<div id="notes"',
'<h2 class="wp-block-heading" id="notes"',
'<h3 class="wp-block-heading" id="notes"',
'>Notes</h2>',
'>Notes</h3>',
'>Notes</',
);
/**
* Protected microdata itemtype patterns (regex)
*/
private $protected_microdata_patterns = array(
'/itemtype=["\']https?:\/\/schema\.org\/FAQPage["\']/i',
'/itemtype=["\']https?:\/\/schema\.org\/HowTo["\']/i',
'/itemtype=["\']https?:\/\/schema\.org\/HowToStep["\']/i',
'/itemtype=["\']https?:\/\/schema\.org\/QAPage["\']/i',
'/itemtype=["\']https?:\/\/schema\.org\/Question["\']/i',
'/itemtype=["\']https?:\/\/schema\.org\/Answer["\']/i',
'/itemtype=["\']https?:\/\/schema\.org\/Recipe["\']/i',
'/itemtype=["\']https?:\/\/schema\.org\/Review["\']/i',
'/itemtype=["\']https?:\/\/schema\.org\/Product["\']/i',
);
/**
* Protected Gutenberg comment ranges
*/
private $protected_gutenberg_ranges = array(
array('start' => '<!-- wp:yoast/faq-block', 'end' => '<!-- /wp:yoast/faq-block -->'),
array('start' => '<!-- wp:rank-math/faq-block', 'end' => '<!-- /wp:rank-math/faq-block -->'),
);
/**
* Flag to track if endmark was rendered (for schema output)
*/
private $endmark_rendered = false;
/**
* Get singleton instance
*/
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*/
private function __construct() {
add_action('plugins_loaded', array($this, 'load_textdomain'));
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_init', array($this, 'register_settings'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
add_filter('plugin_action_links_' . plugin_basename(__FILE__), array($this, 'add_settings_link'));
add_filter('the_content', array($this, 'insert_endmark'), 9999);
add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_styles'));
add_action('admin_init', array($this, 'maybe_migrate_options'));
add_action('init', array($this, 'register_shortcode'));
add_action('init', array($this, 'register_block'));
add_action('wp_head', array($this, 'output_schema_json_ld'), 99);
}
/**
* Load text domain for translations
*/
public function load_textdomain() {
load_plugin_textdomain(
'endmark',
false,
dirname(plugin_basename(__FILE__)) . '/languages/'
);
}
/**
* Migrate options from older versions
*/
public function maybe_migrate_options() {
$current_version = get_option(self::OPTION_VERSION, '0');
// Migrate from v3.x or earlier
if (version_compare($current_version, '4.0', '<')) {
$old_settings = get_option('endmark_settings', array());
if (!empty($old_settings)) {
$new_settings = $this->site_defaults;
// Map old settings to new
if (isset($old_settings['type'])) {
$new_settings['type'] = $old_settings['type'];
}
if (isset($old_settings['symbol'])) {
$new_settings['symbol'] = $old_settings['symbol'];
}
if (isset($old_settings['image'])) {
$new_settings['image_url'] = $old_settings['image'];
}
if (isset($old_settings['image_id'])) {
$new_settings['image_id'] = $old_settings['image_id'];
}
if (isset($old_settings['image_size'])) {
$new_settings['image_size_px'] = $old_settings['image_size'];
}
if (isset($old_settings['where'])) {
// Map old values to new
$where_map = array(
'posts' => 'post',
'pages' => 'page',
'both' => 'both',
);
$new_settings['where'] = isset($where_map[$old_settings['where']])
? $where_map[$old_settings['where']]
: 'post';
}
update_option(self::OPTION_SITE, $new_settings);
}
// Also check for very old individual options
if (false !== get_option('endmark_type')) {
$legacy_settings = array(
'type' => get_option('endmark_type', 'symbol'),
'symbol' => get_option('endmark_symbol', '∎'),
'image_url' => get_option('endmark_image', ''),
'image_id' => 0,
'where' => get_option('endmark_where', 'post'),
);
$new_settings = wp_parse_args($legacy_settings, $this->site_defaults);
update_option(self::OPTION_SITE, $new_settings);
// Clean up old options
delete_option('endmark_type');
delete_option('endmark_symbol');
delete_option('endmark_image');
delete_option('endmark_where');
}
update_option(self::OPTION_VERSION, self::VERSION);
}
}
/**
* Get settings with defaults
*/
public function get_settings() {
$settings = get_option(self::OPTION_SITE, array());
return wp_parse_args($settings, $this->site_defaults);
}
/**
* Add settings link to plugins page
*/
public function add_settings_link($links) {
$settings_link = sprintf(
'<a href="%s">%s</a>',
admin_url('options-general.php?page=endmark'),
esc_html__('Settings', 'endmark')
);
array_unshift($links, $settings_link);
return $links;
}
/**
* Add admin menu
*/
public function add_admin_menu() {
add_options_page(
__('Endmark Settings', 'endmark'),
__('Endmark', 'endmark'),
'manage_options',
'endmark',
array($this, 'render_settings_page')
);
}
/**
* Enqueue admin assets
*/
public function enqueue_admin_assets($hook) {
if ('settings_page_endmark' !== $hook) {
return;
}
wp_enqueue_media();
// Enqueue admin CSS
wp_enqueue_style(
'endmark-admin',
plugin_dir_url(__FILE__) . 'assets/css/admin.css',
array(),
self::VERSION
);
// Enqueue admin JavaScript
wp_enqueue_script(
'endmark-admin',
plugin_dir_url(__FILE__) . 'assets/js/admin.js',
array('jquery'),
self::VERSION,
true
);
// Localize script with data needed by JavaScript
wp_localize_script('endmark-admin', 'endmarkAdmin', array(
'optionName' => self::OPTION_SITE,
'i18n' => array(
'selectImage' => __('Select Endmark Image', 'endmark'),
'useImage' => __('Use this image', 'endmark'),
),
));
}
/**
* Register settings
*/
public function register_settings() {
register_setting(
'endmark_settings_group',
self::OPTION_SITE,
array(
'type' => 'array',
'sanitize_callback' => array($this, 'sanitize_settings'),
'default' => $this->site_defaults,
)
);
}
/**
* Sanitize settings input
*/
public function sanitize_settings($input) {
$sanitized = array();
// Boolean fields
$sanitized['enabled'] = !empty($input['enabled']);
$sanitized['hide_on_mobile'] = !empty($input['hide_on_mobile']);
$sanitized['disable_on_amp'] = !empty($input['disable_on_amp']);
$sanitized['use_css_variables'] = !empty($input['use_css_variables']);
$sanitized['typography_scale_enabled'] = !empty($input['typography_scale_enabled']);
$sanitized['fast_mode'] = !empty($input['fast_mode']);
$sanitized['allow_svg'] = !empty($input['allow_svg']);
$sanitized['schema_enabled'] = !empty($input['schema_enabled']);
// Allowlist validated fields
$sanitized['where'] = isset($input['where']) && in_array($input['where'], $this->allowlists['where'], true)
? $input['where']
: 'post';
$sanitized['type'] = isset($input['type']) && in_array($input['type'], $this->allowlists['type'], true)
? $input['type']
: 'symbol';
$sanitized['placement_mode'] = isset($input['placement_mode']) && in_array($input['placement_mode'], $this->allowlists['placement_mode'], true)
? $input['placement_mode']
: 'last_paragraph';
$sanitized['typography_scale_unit'] = isset($input['typography_scale_unit']) && in_array($input['typography_scale_unit'], $this->allowlists['typography_scale_unit'], true)
? $input['typography_scale_unit']
: 'px';
$sanitized['schema_mode'] = isset($input['schema_mode']) && in_array($input['schema_mode'], $this->allowlists['schema_mode'], true)
? $input['schema_mode']
: 'WebPageElement';
// Symbol - sanitize and limit to 12 characters
$symbol = isset($input['symbol']) ? sanitize_text_field($input['symbol']) : '∎';
$sanitized['symbol'] = mb_substr($symbol, 0, 12);
// Image URL
$sanitized['image_url'] = isset($input['image_url']) ? esc_url_raw($input['image_url']) : '';
// Image ID
$sanitized['image_id'] = isset($input['image_id']) ? absint($input['image_id']) : 0;
// Image size - clamp between 12 and 32
$image_size = isset($input['image_size_px']) ? absint($input['image_size_px']) : 16;
$sanitized['image_size_px'] = max(12, min(32, $image_size));
// Placement selector - validate format
$selector = isset($input['placement_selector']) ? sanitize_text_field($input['placement_selector']) : '';
$selector = mb_substr($selector, 0, 200);
// Validate selector format: must start with . or # followed by alphanumeric, _, -
if (!empty($selector) && !preg_match('/^(\.[A-Za-z0-9_-]+|\#[A-Za-z0-9_-]+)$/', $selector)) {
$selector = '';
}
$sanitized['placement_selector'] = $selector;
// Min word count - clamp between 0 and 50000
$min_words = isset($input['min_word_count']) ? absint($input['min_word_count']) : 0;
$sanitized['min_word_count'] = max(0, min(50000, $min_words));
// Exclude arrays
$sanitized['exclude_categories'] = $this->sanitize_id_array($input, 'exclude_categories');
$sanitized['exclude_tags'] = $this->sanitize_id_array($input, 'exclude_tags');
$sanitized['exclude_post_ids'] = $this->sanitize_id_array($input, 'exclude_post_ids');
// Margin values (CSS)
$sanitized['margin_top'] = isset($input['margin_top']) ? sanitize_text_field($input['margin_top']) : '0';
$sanitized['margin_left'] = isset($input['margin_left']) ? sanitize_text_field($input['margin_left']) : '0.25em';
return $sanitized;
}
/**
* Sanitize array of IDs
*/
private function sanitize_id_array($input, $key) {
if (!isset($input[$key])) {
return array();
}
$values = $input[$key];
if (is_string($values)) {
$values = array_map('trim', explode(',', $values));
}
return array_values(array_filter(array_map('absint', (array) $values)));
}
/**
* Register shortcode
*/
public function register_shortcode() {
add_shortcode(self::SHORTCODE_TAG, array($this, 'render_shortcode'));
}
/**
* Render shortcode
*/
public function render_shortcode($atts) {
$settings = $this->get_settings();
return $this->render_endmark_html($settings);
}
/**
* Register Gutenberg block
*/
public function register_block() {
if (!function_exists('register_block_type')) {
return;
}
register_block_type(self::BLOCK_NAME, array(
'render_callback' => array($this, 'render_block'),
'attributes' => array(
'useGlobalSettings' => array(
'type' => 'boolean',
'default' => true,
),
),
));
}
/**
* Render block
*/
public function render_block($attributes) {
$settings = $this->get_settings();
return $this->render_endmark_html($settings);
}
/**
* Check if current request is AMP
*/
private function is_amp_request() {
return function_exists('amp_is_request') && amp_is_request();
}
/**
* Check if current request is mobile
*/
private function is_mobile_request() {
return wp_is_mobile();
}
/**
* Check if post is excluded by category
*/
private function is_excluded_by_category($post_id, $excluded_categories) {
if (empty($excluded_categories)) {
return false;
}
$post_categories = wp_get_post_categories($post_id, array('fields' => 'ids'));
return !empty(array_intersect($post_categories, $excluded_categories));
}
/**
* Check if post is excluded by tag
*/
private function is_excluded_by_tag($post_id, $excluded_tags) {
if (empty($excluded_tags)) {
return false;
}
$post_tags = wp_get_post_tags($post_id, array('fields' => 'ids'));
return !empty(array_intersect($post_tags, $excluded_tags));
}
/**
* Count words in content
*/
private function count_words($content) {
$text = wp_strip_all_tags($content);
return str_word_count($text);
}
/**
* Check eligibility for endmark insertion
*/
private function check_eligibility($content, $settings) {
// Must be singular view
if (!is_singular()) {
return false;
}
// Must be in the loop
if (!in_the_loop()) {
return false;
}
// Must be main query
if (!is_main_query()) {
return false;
}
// Not in feeds
if (is_feed()) {
return false;
}
// Check if enabled
if (empty($settings['enabled'])) {
return false;
}
// Check where setting
$where = $settings['where'];
$is_post = is_singular('post');
$is_page = is_page();
if ('post' === $where && !$is_post) {
return false;
}
if ('page' === $where && !$is_page) {
return false;
}
if ('both' === $where && !$is_post && !$is_page) {
return false;
}
$post_id = get_the_ID();
// Check excluded post IDs
if (!empty($settings['exclude_post_ids']) && in_array($post_id, $settings['exclude_post_ids'], true)) {
return false;
}
// Check min word count
if ($settings['min_word_count'] > 0 && $this->count_words($content) < $settings['min_word_count']) {
return false;
}
// Check excluded categories
if ($this->is_excluded_by_category($post_id, $settings['exclude_categories'])) {
return false;
}
// Check excluded tags
if ($this->is_excluded_by_tag($post_id, $settings['exclude_tags'])) {
return false;
}
// Check AMP
if ($settings['disable_on_amp'] && $this->is_amp_request()) {
return false;
}
// Check mobile
if ($settings['hide_on_mobile'] && $this->is_mobile_request()) {
return false;
}
return true;
}
/**
* Check for manual placement (shortcode, block, or already inserted)
*/
private function has_manual_placement($content) {
// Check for shortcode
if (has_shortcode($content, self::SHORTCODE_TAG)) {
return true;
}
// Check for block
if (has_block(self::BLOCK_NAME)) {
return true;
}
// Check for wrapper class token
if (false !== strpos($content, self::WRAPPER_CLASS_TOKEN)) {
return true;
}
// Check for anti-duplication comment
if (false !== strpos($content, self::ANTI_DUP_COMMENT)) {
return true;
}
return false;
}
/**
* Hygiene prepass - clean up content
*/
private function hygiene_prepass($content) {
// Trim trailing whitespace
$content = rtrim($content);
// Remove trailing empty paragraphs
$content = preg_replace('/(<p[^>]*>\s*( |\s)*<\/p>\s*)+$/i', '', $content);
// Collapse trailing repeated br tags
$content = preg_replace('/(<br\s*\/?>\s*){2,}$/i', '', $content);
return $content;
}
/**
* Find all protected microdata ranges in content
*
* @param string $content The content to search
* @return array Array of protected ranges with 'start' and 'end' positions
*/
private function find_protected_microdata_ranges($content) {
$ranges = array();
foreach ($this->protected_microdata_patterns as $pattern) {
if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[0] as $match) {
$start_pos = $match[1];
// Find the opening tag that contains this itemtype
$tag_start = strrpos(substr($content, 0, $start_pos + 1), '<');
if ($tag_start === false) {
continue;
}
// Extract tag name
preg_match('/<([a-z0-9]+)/i', substr($content, $tag_start, 50), $tag_match);
if (empty($tag_match[1])) {
continue;
}
$tag_name = $tag_match[1];
// Find the closing tag
$end_pos = $this->find_closing_tag_position($content, $tag_name, $tag_start);
if ($end_pos !== false) {
$ranges[] = array(
'start' => $tag_start,
'end' => $end_pos,
'type' => 'microdata',
);
}
}
}
}
return $ranges;
}
/**
* Find all protected Gutenberg block ranges in content
*
* @param string $content The content to search
* @return array Array of protected ranges with 'start' and 'end' positions
*/
private function find_protected_gutenberg_ranges($content) {
$ranges = array();
foreach ($this->protected_gutenberg_ranges as $range_def) {
$search_pos = 0;
while (($start_pos = strpos($content, $range_def['start'], $search_pos)) !== false) {
$end_pos = strpos($content, $range_def['end'], $start_pos);
if ($end_pos !== false) {
$ranges[] = array(
'start' => $start_pos,
'end' => $end_pos + strlen($range_def['end']),
'type' => 'gutenberg',
);
$search_pos = $end_pos + strlen($range_def['end']);
} else {
break;
}
}
}
return $ranges;
}
/**
* Find all protected ranges in content (combined microdata and Gutenberg)
*
* @param string $content The content to search
* @return array Array of all protected ranges, sorted by start position
*/
private function find_all_protected_ranges($content) {
$microdata_ranges = $this->find_protected_microdata_ranges($content);
$gutenberg_ranges = $this->find_protected_gutenberg_ranges($content);
$all_ranges = array_merge($microdata_ranges, $gutenberg_ranges);
// Sort by start position
usort($all_ranges, function($a, $b) {
return $a['start'] - $b['start'];
});
// Allow filtering of protected patterns
return apply_filters('endmark_protected_patterns', $all_ranges, $content);
}
/**
* Find closing tag position for a given tag
*
* @param string $content The content
* @param string $tag_name The tag name to find closing for
* @param int $start_pos Position of opening tag
* @return int|false Position after closing tag or false if not found
*/
private function find_closing_tag_position($content, $tag_name, $start_pos) {
$depth = 0;
$pos = $start_pos;
$len = strlen($content);
$tag_lower = strtolower($tag_name);
while ($pos < $len) {
$next_open = stripos($content, '<' . $tag_name, $pos + 1);
$next_close = stripos($content, '</' . $tag_name, $pos + 1);
if ($next_close === false) {
return false;
}
if ($next_open !== false && $next_open < $next_close) {
// Check if it's actually an opening tag (not self-closing)
$tag_end = strpos($content, '>', $next_open);
if ($tag_end !== false && $content[$tag_end - 1] !== '/') {
$depth++;
}
$pos = $next_open;
} else {
if ($depth === 0) {
// Find the end of this closing tag
$close_end = strpos($content, '>', $next_close);
return $close_end !== false ? $close_end + 1 : false;
}
$depth--;
$pos = $next_close;
}
}
return false;
}
/**
* Check if a position falls within any protected range
*
* @param int $position The position to check
* @param array $protected_ranges Array of protected ranges
* @return bool True if position is within a protected range
*/
private function is_position_in_protected_range($position, $protected_ranges) {
foreach ($protected_ranges as $range) {
if ($position >= $range['start'] && $position < $range['end']) {
return true;
}
}
return false;
}
/**
* Find the end of the protected range that contains a position
*
* @param int $position The position to check
* @param array $protected_ranges Array of protected ranges
* @return int|false End position of the containing range or false
*/
private function find_protected_range_end($position, $protected_ranges) {
foreach ($protected_ranges as $range) {
if ($position >= $range['start'] && $position < $range['end']) {
return $range['end'];
}
}
return false;
}
/**
* Adjust insertion point to avoid protected ranges
* Uses "move_after_protected_range_or_append" strategy
*
* @param string $content The content
* @param int $insertion_point The original insertion point
* @param array $protected_ranges Array of protected ranges
* @return int Adjusted insertion point
*/
private function adjust_insertion_for_protected_ranges($content, $insertion_point, $protected_ranges) {
if (empty($protected_ranges)) {
return $insertion_point;
}
// Check if insertion point is in a protected range
if ($this->is_position_in_protected_range($insertion_point, $protected_ranges)) {
// Move to after the protected range
$range_end = $this->find_protected_range_end($insertion_point, $protected_ranges);
if ($range_end !== false) {
return $range_end;
}
// Fallback to end of content
return strlen($content);
}
return $insertion_point;
}
/**
* Find footnotes position in content
*/
private function find_footnotes_position($content) {
foreach ($this->footnote_patterns as $pattern) {
$pos = stripos($content, $pattern);
if (false !== $pos) {
return $pos;
}
}
return false;
}
/**
* Check if position is inside an unsafe container
*/
private function is_inside_unsafe_container($content, $position) {
foreach ($this->unsafe_containers as $tag) {
// Find all opening and closing tags before position
$open_pattern = '/<' . $tag . '\b[^>]*>/i';
$close_pattern = '/<\/' . $tag . '>/i';
preg_match_all($open_pattern, substr($content, 0, $position), $opens, PREG_OFFSET_CAPTURE);
preg_match_all($close_pattern, substr($content, 0, $position), $closes, PREG_OFFSET_CAPTURE);
$open_count = count($opens[0]);
$close_count = count($closes[0]);
// If we have more opens than closes, we're inside
if ($open_count > $close_count) {
return true;
}
}
return false;
}
/**
* Find insertion point based on selector mode
*/
private function find_selector_insertion_point($content, $selector) {
// Convert CSS selector to regex pattern
$selector_type = substr($selector, 0, 1);
$selector_value = substr($selector, 1);
if ($selector_type === '.') {
// Class selector
$pattern = '/<[^>]*\bclass\s*=\s*["\'][^"\']*\b' . preg_quote($selector_value, '/') . '\b[^"\']*["\'][^>]*>/i';
} elseif ($selector_type === '#') {
// ID selector
$pattern = '/<[^>]*\bid\s*=\s*["\']' . preg_quote($selector_value, '/') . '["\'][^>]*>/i';
} else {
return false;
}
if (preg_match($pattern, $content, $match, PREG_OFFSET_CAPTURE)) {
// Insert before the matched element
return $match[0][1];
}
return false;
}
/**
* Find last valid paragraph for insertion
*/
private function find_last_paragraph_insertion_point($content, $footnotes_pos = false) {
if (!preg_match_all('/<p\b[^>]*>(.*?)<\/p>/is', $content, $matches, PREG_OFFSET_CAPTURE)) {
return false;
}
$last_valid_index = -1;
foreach ($matches[0] as $i => $match) {
$p_start = $match[1];
$p_html = $match[0];
$p_end = $p_start + strlen($p_html);
// If footnotes exist, only consider paragraphs that end before footnotes start
if (false !== $footnotes_pos && $p_end > $footnotes_pos) {
continue;
}
// Check if inside unsafe container
if ($this->is_inside_unsafe_container($content, $p_start)) {
continue;
}
// Check if paragraph has real content
$inner_html = $matches[1][$i][0];
$text = trim(wp_strip_all_tags(str_replace(' ', '', preg_replace('/<br\s*\/?>/i', '', $inner_html))));
if ($text !== '') {
$last_valid_index = $i;
}
}
if ($last_valid_index === -1) {
return false;
}
// Return position just before closing </p> tag
$p_html = $matches[0][$last_valid_index][0];
$p_start = $matches[0][$last_valid_index][1];
$close_tag_pos = strripos($p_html, '</p>');
return $p_start + $close_tag_pos;
}
/**
* Insert endmark into content
*/
public function insert_endmark($content) {
$settings = $this->get_settings();
// Check eligibility
if (!$this->check_eligibility($content, $settings)) {
return $content;
}
// Check for manual placement
if ($this->has_manual_placement($content)) {
return $content;
}
// Get endmark HTML
$endmark = $this->render_endmark_html($settings);
if (empty($endmark)) {
return $content;
}
// Hygiene prepass
$content = $this->hygiene_prepass($content);