forked from urvanov-ru/crayon-syntax-highlighter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass-urvanov-syntax-highlighter-plugin.php
More file actions
1976 lines (1650 loc) · 63.4 KB
/
class-urvanov-syntax-highlighter-plugin.php
File metadata and controls
1976 lines (1650 loc) · 63.4 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: Urvanov Syntax Highlighter
* Plugin URI: https://github.com/urvanov-ru/crayon-syntax-highlighter
* Description: Supports multiple languages, themes, highlighting from a URL, local file or post text.
* Version: 2.9.0
* Author: Fedor Urvanov, Aram Kocharyan, Kevin Provance
* Author URI: https://urvanov.ru
* Text Domain: urvanov-syntax-highlighter
* Domain Path: /trans/
*
* License: GPL2
* Copyright 2013 Aram Kocharyan (email : akarmenia@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* @package Crayon Syntax Highlighter
* @author Fedor Urvanov, Aram Kocharyan
* @copyright Copyright 2013, Aram Kocharyan
* @link https://urvanov.ru
*/
defined( 'ABSPATH' ) || exit;
require_once 'class-urvanov-syntax-highlighter-global.php';
require_once URVANOV_SYNTAX_HIGHLIGHTER_HIGHLIGHTER_PHP;
if ( URVANOV_SYNTAX_HIGHLIGHTER_TAG_EDITOR ) {
require_once URVANOV_SYNTAX_HIGHLIGHTER_TAG_EDITOR_PHP;
}
if ( URVANOV_SYNTAX_HIGHLIGHTER_THEME_EDITOR ) {
require_once URVANOV_SYNTAX_HIGHLIGHTER_THEME_EDITOR_PHP;
}
require_once 'class-urvanov-syntax-highlighter-wp.php';
Urvanov_Syntax_Highlighter_Global::set_info(
array(
'Version' => '2.9.0', // DO NOT EDIT THIS LINE! Gulp will handle it.
'Date' => 'April 11, 2021', // DO NOT EDIT THIS LINE! Gulp will handle it.
'AuthorName' => 'Fedor Urvanov & Aram Kocharyan',
'PluginURI' => 'https://github.com/urvanov-ru/crayon-syntax-highlighter',
)
);
/**
* The plugin class that manages all other classes and integrates Crayon with WP.
*
* Class Urvanov_Syntax_Highlighter_Plugin (Old name: CrayonWP).
*/
class Urvanov_Syntax_Highlighter_Plugin {
/**
* Associative array, keys are post IDs as strings and values are number of crayons parsed as ints.
*
* @var array
*/
private static $post_queue = array();
/**
* Ditto for comments
*
* @var array
*/
private static $comment_queue = array();
/**
* Post ccaptures.
*
* @var array
*/
private static $post_captures = array();
/**
* Comment captures.
*
* @var array
*/
private static $comment_captures = array();
/**
* Whether we are displaying an excerpt.
*
* @var bool
*/
private static $is_excerpt = false;
/**
* Whether we have added styles and scripts.
*
* @var bool
*/
private static $enqueued = false;
/**
* Used to keep Crayon IDs.
*
* @var int
*/
private static $next_id = 0;
/**
* String to store the regex for capturing tags.
*
* @var string
*/
private static $alias_regex = '';
/**
* Tags RegEx.
*
* @var string
*/
private static $tags_regex = '';
/**
* Legacy RegEx.
*
* @var string
*/
private static $tags_regex_legacy = '';
/**
* Tag RegEx.
*
* @var array
*/
private static $tag_regexes = array();
/**
* Defined constants used in bitwise flags.
*
* @var array
*/
private static $tag_types = array(
Urvanov_Syntax_Highlighter_Settings::CAPTURE_MINI_TAG,
Urvanov_Syntax_Highlighter_Settings::CAPTURE_PRE,
Urvanov_Syntax_Highlighter_Settings::INLINE_TAG,
Urvanov_Syntax_Highlighter_Settings::PLAIN_TAG,
Urvanov_Syntax_Highlighter_Settings::BACKQUOTE,
);
/**
* Tag bits.
*
* @var array
*/
private static $tag_bits = array();
/**
* Used to find legacy tags.
*
* @var null
*/
private static $legacy_flags = null;
/**
* Used to detect the shortcode.
*
* @var null[]
*/
private static $allowed_atts = array(
'url' => null,
'lang' => null,
'title' => null,
'mark' => null,
'range' => null,
'inline' => null,
);
/**
* RegEx Closed.
*/
const REGEX_CLOSED = '(?:\[\s*crayon(?:-(\w+))?\b([^\]]*)/\s*\])';
/**
* RegEx Tags.
*/
const REGEX_TAG = '(?:\[\s*crayon(?:-(\w+))?\b([^\]]*)\](.*?)\[\s*/\s*crayon\s*\])';
/**
* RegEx inline class.
*/
const REGEX_INLINE_CLASS = '\bcrayon-inline\b';
/**
* RegEx Close no capture.
*/
const REGEX_CLOSED_NO_CAPTURE = '(?:\[\s*crayon\b[^\]]*/\])';
/**
* RegEx tag no capture.
*/
const REGEX_TAG_NO_CAPTURE = '(?:\[\s*crayon\b[^\]]*\].*?\[/crayon\])';
/**
* RegEx quick capture.
*/
const REGEX_QUICK_CAPTURE = '(?:\[\s*crayon[^\]]*\].*?\[\s*/\s*crayon\s*\])|(?:\[\s*crayon[^\]]*/\s*\])';
/**
* RegEx between paragraphs.
*/
const REGEX_BETWEEN_PARAGRAPH = '<p[^<]*>(?:[^<]*<(?!/?p(\s+[^>]*)?>)[^>]+(\s+[^>]*)?>)*[^<]*((?:\[\s*crayon[^\]]*\].*?\[\s*/\s*crayon\s*\])|(?:\[\s*crayon[^\]]*/\s*\]))(?:[^<]*<(?!/?p(\s+[^>]*)?>)[^>]+(\s+[^>]*)?>)*[^<]*</p[^<]*>';
/**
* RegEx paragraph simple.
*/
const REGEX_BETWEEN_PARAGRAPH_SIMPLE = '(<p(?:\s+[^>]*)?>)(.*?)(</p(?:\s+[^>]*)?>)';
/**
* For [crayon-id/] after.
*/
const REGEX_BR_AFTER = '#(\[\s*crayon-\w+\])\s*<\s*br\s*/?\s*>#msi';
/**
* RegEx ID.
*/
const REGEX_ID = '#(?<!\$)\[\s*crayon#mi';
/**
* RegEx with ID.
*/
const REGEX_WITH_ID = '#\[\s*(crayon-\w+)\b[^\]]*\]#mi';
/**
* Modes.
*/
const MODE_NORMAL = 0, MODE_JUST_CODE = 1, MODE_PLAIN_CODE = 2;
/**
* Post capture.
*
* @return array
*/
public static function post_captures(): array {
return self::$post_queue;
}
/**
* Urvanov_Syntax_Highlighter_Plugin constructor.
*/
private function __construct() {}
/**
* RegEx.
*
* @return string
*/
public static function regex(): string {
return '#(?<!\$)(?:' . self::REGEX_CLOSED . '|' . self::REGEX_TAG . ')(?!\$)#msi';
}
/**
* RegEx with ID.
*
* @param string $id ID.
*
* @return string
*/
public static function regex_with_id( string $id ): string {
return '#\[\s*(crayon-' . $id . ')\b[^\]]*\]#mi';
}
/**
* RegEx no capture.
*
* @return string
*/
public static function regex_no_capture(): string {
return '#(?<!\$)(?:' . self::REGEX_CLOSED_NO_CAPTURE . '|' . self::REGEX_TAG_NO_CAPTURE . ')(?!\$)#msi';
}
/**
* Adds the actual Crayon instance.
* $mode can be: 0 = return crayon content, 1 = return only code, 2 = return only plain code
*
* @param array $atts Attributes.
* @param string $content Content.
* @param string $id ID.
*
* @return Urvanov_Syntax_Highlighter
*/
public static function shortcode( $atts = array(), $content = null, $id = null ): Urvanov_Syntax_Highlighter {
UrvanovSyntaxHighlighterLog::debug( 'shortcode' );
// Load attributes from shortcode.
$filtered_atts = shortcode_atts( self::$allowed_atts, $atts );
// Clean attributes.
$keys = array_keys( $filtered_atts );
$count = count( $keys );
for ( $i = 0; $i < $count; $i ++ ) {
$key = $keys[ $i ];
$value = $filtered_atts[ $key ];
if ( null !== $value ) {
$filtered_atts[ $key ] = trim( wp_strip_all_tags( $value ) );
}
}
// Contains all other attributes not found in allowed, used to override global settings.
$extra_attr = array();
if ( ! empty( $atts ) ) {
$extra_attr = array_diff_key( $atts, self::$allowed_atts );
$extra_attr = Urvanov_Syntax_Highlighter_Settings::smart_settings( $extra_attr );
}
$url = '';
$lang = '';
$title = '';
$mark = '';
$range = '';
$inline = '';
// phpcs:ignore WordPress.PHP.DontExtract
extract( $filtered_atts );
$highlighter_instance = self::instance( $extra_attr, $id );
// Set URL.
$highlighter_instance->url( $url );
$highlighter_instance->code( $content );
// Set attributes, should be set after URL to allow language auto detection.
$highlighter_instance->language( $lang );
$highlighter_instance->title( $title );
$highlighter_instance->marked( $mark );
$highlighter_instance->range( $range );
$highlighter_instance->is_inline( $inline );
// Determine if we should highlight.
$highlight = ! array_key_exists( 'highlight', $atts ) || UrvanovSyntaxHighlighterUtil::str_to_bool( $atts['highlight'], false );
$highlighter_instance->is_highlighted( $highlight );
return $highlighter_instance;
}
/**
* Returns Crayon instance.
*
* @param array $extra_attr Extra attributes.
* @param mixed $id ID.
*
* @return Urvanov_Syntax_Highlighter
*/
public static function instance( $extra_attr = array(), $id = null ): Urvanov_Syntax_Highlighter {
UrvanovSyntaxHighlighterLog::debug( 'instance' );
// Create Crayon.
$highlighter_instance = new Urvanov_Syntax_Highlighter();
/**
* Load settings and merge shortcode attributes which will override any existing.
* Stores the other shortcode attributes as settings in the crayon.
*/
if ( ! empty( $extra_attr ) ) {
$highlighter_instance->settings( $extra_attr );
}
if ( ! empty( $id ) ) {
$highlighter_instance->id( $id );
}
return $highlighter_instance;
}
/**
* For manually highlighting code, useful for other PHP contexts.
*
* @param string $code Code.
* @param bool $add_tags Add tags.
*
* @return array|string|string[]|null
*/
public static function highlight( $code = '', $add_tags = false ) {
$captures = self::capture_crayons( 0, $code );
$the_captures = $captures['capture'];
if ( 0 === count( $the_captures ) && $add_tags ) {
// Nothing captured, so wrap in a pre and try again.
$code = '<pre>' . $code . '</pre>';
$captures = self::capture_crayons( 0, $code );
$the_captures = $captures['capture'];
}
$the_content = $captures['content'];
$the_content = UrvanovSyntaxHighlighterUtil::strip_tags_blacklist( $the_content, array( 'script' ) );
$the_content = UrvanovSyntaxHighlighterUtil::strip_event_attributes( $the_content );
foreach ( $the_captures as $id => $capture ) {
$atts = $capture['atts'];
$no_enqueue = array(
Urvanov_Syntax_Highlighter_Settings::ENQUEUE_THEMES => false,
Urvanov_Syntax_Highlighter_Settings::ENQUEUE_FONTS => false,
);
$atts = array_merge( $atts, $no_enqueue );
$code = $capture['code'];
$crayon = self::shortcode( $atts, $code, $id );
$crayon_formatted = $crayon->output( true, false );
$the_content = UrvanovSyntaxHighlighterUtil::preg_replace_escape_back( self::regex_with_id( $id ), $crayon_formatted, $the_content, 1, $count );
}
return $the_content;
}
/**
* AJAX highlights.
*
* TODO: COme back and fix this with a nonce.
*/
public static function ajax_highlight() {
header( 'Content-Type: text/plain' );
$code = isset( $_POST['code'] ) ? sanitize_text_field( wp_unslash( $_POST['code'] ) ) : null;
if ( ! $code ) {
$code = isset( $_GET['code'] ) ? sanitize_text_field( wp_unslash( $_GET['code'] ) ) : null;
}
if ( $code ) {
echo wp_kses_post( self::highlight( $code ) );
} else {
echo 'No code specified.';
}
exit();
}
/**
* Uses the main query.
*/
public static function wp() {
UrvanovSyntaxHighlighterLog::debug( 'wp (global)' );
global $wp_the_query;
if ( isset( $wp_the_query->posts ) ) {
$posts = $wp_the_query->posts;
self::the_posts( $posts );
}
}
/**
* TODO put args into an array.
*
* @param mixed $wp_id ID.
* @param mixed $wp_content Content.
* @param array $extra_settings Extra settings.
* @param array $args Args.
*
* @return array
*/
public static function capture_crayons( $wp_id, $wp_content, $extra_settings = array(), $args = array() ): array {
// phpcs:ignore WordPress.PHP.DontExtract
extract( $args );
UrvanovSyntaxHighlighterUtil::set_var( $callback, null );
UrvanovSyntaxHighlighterUtil::set_var( $callback_extra_args, null );
UrvanovSyntaxHighlighterUtil::set_var( $ignore, true );
UrvanovSyntaxHighlighterUtil::set_var( $preserve_atts, false );
UrvanovSyntaxHighlighterUtil::set_var( $flags, null );
UrvanovSyntaxHighlighterUtil::set_var( $skip_setting_check, false );
UrvanovSyntaxHighlighterUtil::set_var( $just_check, false );
// Will contain captured crayons and altered $wp_content.
$capture = array(
'capture' => array(),
'content' => $wp_content,
'has_captured' => false,
);
// Do not apply Crayon for posts older than a certain date.
$disable_date = trim( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::DISABLE_DATE ) );
if ( $disable_date && get_post_time( 'U', true, $wp_id ) <= strtotime( $disable_date ) ) {
return $capture;
}
// Flags for which Crayons to convert.
$in_flag = self::in_flag( $flags );
UrvanovSyntaxHighlighterLog::debug( 'capture for id ' . $wp_id . ' len ' . strlen( $wp_content ) );
// Convert <pre> tags to crayon tags, if needed.
if ( ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::CAPTURE_PRE ) || $skip_setting_check ) && $in_flag[ Urvanov_Syntax_Highlighter_Settings::CAPTURE_PRE ] ) {
// XXX This will fail if <pre></pre> is used inside another <pre></pre>.
$wp_content = preg_replace_callback( '#(?<!\$)<\s*pre(?=(?:([^>]*)\bclass\s*=\s*(["\'])(.*?)\2([^>]*))?)([^>]*)>(.*?)<\s*/\s*pre\s*>#msi', 'Urvanov_Syntax_Highlighter_Plugin::pre_tag', $wp_content );
}
// Convert mini [php][/php] tags to crayon tags, if needed.
if ( ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::CAPTURE_MINI_TAG ) || $skip_setting_check ) && $in_flag[ Urvanov_Syntax_Highlighter_Settings::CAPTURE_MINI_TAG ] ) {
$wp_content = preg_replace( '#(?<!\$)\[\s*(' . self::$alias_regex . ')\b([^\]]*)\](.*?)\[\s*/\s*(?:\1)\s*\](?!\$)#msi', '[crayon lang="\1" \2]\3[/crayon]', $wp_content );
$wp_content = preg_replace( '#(?<!\$)\[\s*(' . self::$alias_regex . ')\b([^\]]*)/\s*\](?!\$)#msi', '[crayon lang="\1" \2 /]', $wp_content );
}
// Convert <code> to inline tags.
if ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::CODE_TAG_CAPTURE ) ) {
$inline = Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::CODE_TAG_CAPTURE_TYPE ) === 0;
$inline_setting = $inline ? 'inline="true"' : '';
$wp_content = preg_replace( '#<(\s*code\b)([^>]*)>(.*?)</\1[^>]*>#msi', '[crayon ' . $inline_setting . ' \2]\3[/crayon]', $wp_content );
}
if ( ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::INLINE_TAG ) || $skip_setting_check ) && $in_flag[ Urvanov_Syntax_Highlighter_Settings::INLINE_TAG ] ) {
if ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::INLINE_TAG_CAPTURE ) ) {
// Convert inline {php}{/php} tags to crayon tags, if needed.
$wp_content = preg_replace( '#(?<!\$)\{\s*(' . self::$alias_regex . ')\b([^\}]*)\}(.*?)\{/(?:\1)\}(?!\$)#msi', '[crayon lang="\1" inline="true" \2]\3[/crayon]', $wp_content );
}
// Convert <span class="crayon-inline"> tags to inline crayon tags.
$wp_content = preg_replace_callback( '#(?<!\$)<\s*span([^>]*)\bclass\s*=\s*(["\'])(.*?)\2([^>]*)>(.*?)<\s*/\s*span\s*>#msi', 'Urvanov_Syntax_Highlighter_Plugin::span_tag', $wp_content );
}
// Convert [plain] tags into <pre><code></code></pre>, if needed.
if ( ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::PLAIN_TAG ) || $skip_setting_check ) && $in_flag[ Urvanov_Syntax_Highlighter_Settings::PLAIN_TAG ] ) {
$wp_content = preg_replace_callback( '#(?<!\$)\[\s*plain\s*\](.*?)\[\s*/\s*plain\s*\]#msi', 'Urvanov_Syntax_Highlighter_Formatter::plain_code', $wp_content );
}
// Add IDs to the Crayons.
UrvanovSyntaxHighlighterLog::debug( 'capture adding id ' . $wp_id . ' , now has len ' . strlen( $wp_content ) );
$wp_content = preg_replace_callback( self::REGEX_ID, 'Urvanov_Syntax_Highlighter_Plugin::add_crayon_id', $wp_content );
UrvanovSyntaxHighlighterLog::debug( 'capture added id ' . $wp_id . ' : ' . strlen( $wp_content ) );
// Only include if a post exists with Crayon tag.
preg_match_all( self::regex(), $wp_content, $matches );
$capture['has_captured'] = 0 !== count( $matches[0] );
if ( $just_check ) {
// Backticks are matched after other tags, so they need to be captured here.
$result = self::replace_backquotes( $wp_content );
$wp_content = $result['content'];
$capture['has_captured'] = $capture['has_captured'] || $result['changed'];
$capture['content'] = $wp_content;
return $capture;
}
UrvanovSyntaxHighlighterLog::debug( 'capture ignore for id ' . $wp_id . ' : ' . strlen( $capture['content'] ) . ' vs ' . strlen( $wp_content ) );
if ( $capture['has_captured'] ) {
// Crayons found! Load settings first to ensure global settings loaded.
Urvanov_Syntax_Highlighter_Settings_WP::load_settings();
UrvanovSyntaxHighlighterLog::debug( 'CAPTURED FOR ID ' . $wp_id );
$full_matches = $matches[0];
$closed_ids = $matches[1];
$closed_atts = $matches[2];
$open_ids = $matches[3];
$open_atts = $matches[4];
$contents = $matches[5];
// Make sure we enqueue the styles/scripts.
$enqueue = true;
$count = count( $full_matches );
for ( $i = 0; $i < count( $full_matches ); $i ++ ) {
if ( ! empty( $closed_atts[ $i ] ) ) {
$atts = $closed_atts[ $i ];
} elseif ( ! empty( $open_atts[ $i ] ) ) {
$atts = $open_atts[ $i ];
} else {
$atts = '';
}
// Capture attributes.
preg_match_all( '#([^="\'\s]+)[\t ]*=[\t ]*("|\')(.*?)\2#', $atts, $att_matches );
// Add extra attributes.
$atts_array = $extra_settings;
if ( 0 !== count( $att_matches[0] ) ) {
$count = count( $att_matches[1] );
for ( $j = 0; $j < $count; $j ++ ) {
$atts_array[ trim( strtolower( $att_matches[1][ $j ] ) ) ] = trim( $att_matches[3][ $j ] );
}
}
if ( isset( $atts_array[ Urvanov_Syntax_Highlighter_Settings::IGNORE ] ) && $atts_array[ Urvanov_Syntax_Highlighter_Settings::IGNORE ] ) {
// TODO(aramk) Revert to the original content.
continue;
}
// Capture theme.
$theme_id = array_key_exists( Urvanov_Syntax_Highlighter_Settings::THEME, $atts_array ) ? $atts_array[ Urvanov_Syntax_Highlighter_Settings::THEME ] : '';
$theme = Urvanov_Syntax_Highlighter_Resources::themes()->get( $theme_id );
// If theme not found, use fallbacks.
if ( ! $theme ) {
// Given theme is invalid, try global setting.
$theme_id = Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::THEME );
$theme = Urvanov_Syntax_Highlighter_Resources::themes()->get( $theme_id );
if ( ! $theme ) {
// Global setting is invalid, fall back to default.
$theme = Urvanov_Syntax_Highlighter_Resources::themes()->get_default();
$theme_id = Urvanov_Syntax_Highlighter_Themes::DEFAULT_THEME;
}
}
// If theme is now valid, change the array.
if ( $theme ) {
if ( ! $preserve_atts || isset( $atts_array[ Urvanov_Syntax_Highlighter_Settings::THEME ] ) ) {
$atts_array[ Urvanov_Syntax_Highlighter_Settings::THEME ] = $theme_id;
}
$theme->used( true );
}
// Capture font.
$font_id = array_key_exists( Urvanov_Syntax_Highlighter_Settings::FONT, $atts_array ) ? $atts_array[ Urvanov_Syntax_Highlighter_Settings::FONT ] : '';
$font = Urvanov_Syntax_Highlighter_Resources::fonts()->get( $font_id );
// If font not found, use fallbacks.
if ( ! $font ) {
// Given font is invalid, try global setting.
$font_id = Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::FONT );
$font = Urvanov_Syntax_Highlighter_Resources::fonts()->get( $font_id );
if ( ! $font ) {
// Global setting is invalid, fall back to default.
$font = Urvanov_Syntax_Highlighter_Resources::fonts()->get_default();
$font_id = Urvanov_Syntax_Highlighter_Fonts::DEFAULT_FONT;
}
}
// If font is now valid, change the array.
if ( $font /* != NULL && $font_id != CrayonFonts::DEFAULT_FONT*/ ) {
if ( ! $preserve_atts || isset( $atts_array[ Urvanov_Syntax_Highlighter_Settings::FONT ] ) ) {
$atts_array[ Urvanov_Syntax_Highlighter_Settings::FONT ] = $font_id;
}
$font->used( true );
}
// Add array of atts and content to post queue with key as post ID
// XXX If at this point no ID is added we have failed!
$id = ! empty( $open_ids[ $i ] ) ? $open_ids[ $i ] : $closed_ids[ $i ];
$code = self::crayon_remove_ignore( $contents[ $i ] );
$c = array(
'post_id' => $wp_id,
'atts' => $atts_array,
'code' => $code,
);
$capture['capture'][ $id ] = $c;
UrvanovSyntaxHighlighterLog::debug( 'capture finished for post id ' . $wp_id . ' crayon-id ' . $id . ' atts: ' . count( $atts_array ) . ' code: ' . strlen( $code ) );
$is_inline = isset( $atts_array['inline'] ) && UrvanovSyntaxHighlighterUtil::str_to_bool( $atts_array['inline'], false ) ? '-i' : '';
if ( null === $callback ) {
$wp_content = str_replace( $full_matches[ $i ], '[crayon-' . $id . $is_inline . '/]', $wp_content );
} else {
$wp_content = call_user_func( $callback, $c, $full_matches[ $i ], $id, $is_inline, $wp_content, $callback_extra_args );
}
}
}
if ( $ignore ) {
// We need to escape ignored Crayons, since they won't be captured
// XXX Do this after replacing the Crayon with the shorter ID tag, otherwise $full_matches will be different from $wp_content.
$wp_content = self::crayon_remove_ignore( $wp_content );
}
$result = self::replace_backquotes( $wp_content );
$wp_content = $result['content'];
$capture['content'] = $wp_content;
return $capture;
}
/**
* Replace backquotes.
*
* @param string $wp_content Content.
*
* @return array
*/
public static function replace_backquotes( string $wp_content ): array {
// Convert `` backquote tags into <code></code>, if needed
// XXX Some code may contain `` so must do it after all Crayons are captured.
$result = array();
$prev_count = strlen( $wp_content );
if ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::BACKQUOTE ) ) {
$wp_content = preg_replace( '#(?<!\\\\)`([^`]*)`#msi', '<code>$1</code>', $wp_content );
}
$result['changed'] = strlen( $wp_content ) !== $prev_count;
$result['content'] = $wp_content;
return $result;
}
/**
* Search for Crayons in posts and queue them for creation.
*
* @param array $posts Posts.
*
* @return array
*/
public static function the_posts( array $posts ): array {
UrvanovSyntaxHighlighterLog::debug( 'the_posts' );
// Whether to enqueue syles/scripts.
Urvanov_Syntax_Highlighter_Settings_WP::load_settings( true ); // We will eventually need more than the settings.
self::init_tags_regex();
$crayon_posts = Urvanov_Syntax_Highlighter_Settings_WP::load_posts(); // Loads posts containing crayons.
// Search for shortcode in posts.
foreach ( $posts as $post ) {
$wp_id = $post->ID;
$is_page = 'page' === $post->post_type;
if ( ! in_array( $wp_id, $crayon_posts, true ) ) {
// If we get query for a page, then that page might have a template and load more posts containing Crayons
// By this state, we would be unable to enqueue anything (header already written).
if ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::SAFE_ENQUEUE ) && $is_page ) {
Urvanov_Syntax_Highlighter_Global_Settings::set( Urvanov_Syntax_Highlighter_Settings::ENQUEUE_THEMES, false );
Urvanov_Syntax_Highlighter_Global_Settings::set( Urvanov_Syntax_Highlighter_Settings::ENQUEUE_FONTS, false );
}
// Only include crayon posts.
continue;
}
$id_str = strval( $wp_id );
if ( wp_is_post_revision( $wp_id ) ) {
// Ignore post revisions, use the parent, which has the updated post content.
continue;
}
if ( isset( self::$post_captures[ $id_str ] ) ) {
// Don't capture twice
// XXX post->post_content is reset each loop, replace content
// Doing this might cause content changed by other plugins between the last loop
// to fail, so be cautious.
$post->post_content = self::$post_captures[ $id_str ];
continue;
}
// Capture post Crayons.
$captures = self::capture_crayons( intval( $post->ID ), $post->post_content );
// XXX Careful not to undo changes by other plugins
// XXX Must replace to remove $ for ignored Crayons.
$post->post_content = $captures['content'];
self::$post_captures[ $id_str ] = $captures['content'];
if ( true === $captures['has_captured'] ) {
self::$post_queue[ $id_str ] = array();
foreach ( $captures['capture'] as $capture_id => $capture_content ) {
self::$post_queue[ $id_str ][ $capture_id ] = $capture_content;
}
}
// Search for shortcode in comments.
if ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::COMMENTS ) ) {
$comments = get_comments( array( 'post_id' => $post->ID ) );
foreach ( $comments as $comment ) {
$id_str = strval( $comment->comment_ID );
if ( isset( self::$comment_queue[ $id_str ] ) ) {
// Don't capture twice.
continue;
}
// Capture comment Crayons, decode their contents if decode not specified.
$content = apply_filters( 'get_comment_text', $comment->comment_content, $comment );
$captures = self::capture_crayons( $comment->comment_ID, $content, array( Urvanov_Syntax_Highlighter_Settings::DECODE => true ) );
self::$comment_captures[ $id_str ] = $captures['content'];
if ( true === $captures['has_captured'] ) {
self::$comment_queue[ $id_str ] = array();
foreach ( $captures['capture'] as $capture_id => $capture_content ) {
self::$comment_queue[ $id_str ][ $capture_id ] = $capture_content;
}
}
}
}
}
return $posts;
}
/**
* Add crayon ID.
*
* @param array $content Content.
*
* @return string
*/
private static function add_crayon_id( array $content ): string {
$uid = $content[0] . '-' . str_replace( '.', '', uniqid( '', true ) );
UrvanovSyntaxHighlighterLog::debug( 'add_crayon_id ' . $uid );
return $uid;
}
/**
* Get cryaon ID.
*
* @return int
*/
private static function get_crayon_id(): int {
return self::$next_id ++;
}
/**
* Enqueue resources.
*/
public static function enqueue_resources() {
if ( ! self::$enqueued ) {
UrvanovSyntaxHighlighterLog::debug( 'enqueue' );
global $urvanov_syntax_highlighter_version;
UrvanovSyntaxHighlighterLog::debug( 'Loading settings...' );
Urvanov_Syntax_Highlighter_Settings_WP::load_settings( true );
if ( URVANOV_SYNTAX_HIGHLIGHTER_MINIFY ) {
wp_enqueue_style( 'urvanov_syntax_highlighter', plugins_url( URVANOV_SYNTAX_HIGHLIGHTER_STYLE_MIN, __FILE__ ), array(), $urvanov_syntax_highlighter_version );
wp_enqueue_script( 'urvanov_syntax_highlighter_js', plugins_url( URVANOV_SYNTAX_HIGHLIGHTER_JS_MIN, __FILE__ ), array( 'jquery' ), $urvanov_syntax_highlighter_version, Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::DELAY_LOAD_JS ) );
} else {
wp_enqueue_style( 'urvanov_syntax_highlighter_style', plugins_url( URVANOV_SYNTAX_HIGHLIGHTER_STYLE, __FILE__ ), array(), $urvanov_syntax_highlighter_version );
wp_enqueue_style( 'urvanov_syntax_highlighter_global_style', plugins_url( URVANOV_SYNTAX_HIGHLIGHTER_STYLE_GLOBAL, __FILE__ ), array(), $urvanov_syntax_highlighter_version );
wp_enqueue_script( 'urvanov_syntax_highlighter_util_js', plugins_url( URVANOV_SYNTAX_HIGHLIGHTER_JS_UTIL, __FILE__ ), array( 'jquery' ), $urvanov_syntax_highlighter_version, false );
Urvanov_Syntax_Highlighter_Settings_WP::other_scripts();
}
UrvanovSyntaxHighlighterLog::debug( 'Initializing js settings...' );
Urvanov_Syntax_Highlighter_Settings_WP::init_js_settings();
self::$enqueued = true;
}
}
/**
* Init Tags.
*
* @param bool $force Force.
* @param mixed $flags Flags.
* @param string $tags_regex RegEx.
*/
private static function init_tags_regex( $force = false, $flags = null, &$tags_regex = null ) {
Urvanov_Syntax_Highlighter_Settings_WP::load_settings();
self::init_tag_bits();
// Default output.
if ( null === $tags_regex ) {
$tags_regex = &self::$tags_regex;
}
if ( $force || '' === $tags_regex ) {
// Check which tags are in $flags. If it's NULL, then all flags are true.
$in_flag = self::in_flag( $flags );
if ( ( $in_flag[ Urvanov_Syntax_Highlighter_Settings::CAPTURE_MINI_TAG ] && ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::CAPTURE_MINI_TAG ) ) || $force ) ||
( $in_flag[ Urvanov_Syntax_Highlighter_Settings::INLINE_TAG ] && ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::INLINE_TAG ) && Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::INLINE_TAG_CAPTURE ) ) )
) {
$aliases = Urvanov_Syntax_Highlighter_Resources::langs()->ids_and_aliases();
self::$alias_regex = '';
$count = count( $aliases );
for ( $i = 0; $i < $count; $i ++ ) {
$alias = $aliases[ $i ];
$alias_regex = UrvanovSyntaxHighlighterUtil::esc_hash( UrvanovSyntaxHighlighterUtil::esc_regex( $alias ) );
if ( count( $aliases ) - 1 !== $i ) {
$alias_regex .= '|';
}
self::$alias_regex .= $alias_regex;
}
}
// Add other tags.
$tags_regex = '#(?<!\$)(?:(\s*\[\s*crayon\b)';
// TODO this is duplicated in capture_crayons().
$tag_regexes = array(
Urvanov_Syntax_Highlighter_Settings::CAPTURE_MINI_TAG => '(\[\s*(' . self::$alias_regex . ')\b)',
Urvanov_Syntax_Highlighter_Settings::CAPTURE_PRE => '(<\s*pre\b)',
Urvanov_Syntax_Highlighter_Settings::INLINE_TAG => '(' . self::REGEX_INLINE_CLASS . ')|(\{\s*(' . self::$alias_regex . ')\b([^\}]*)\})',
Urvanov_Syntax_Highlighter_Settings::PLAIN_TAG => '(\s*\[\s*plain\b)',
Urvanov_Syntax_Highlighter_Settings::BACKQUOTE => '(`[^`]*`)',
);
foreach ( $tag_regexes as $tag => $regex ) {
if ( $in_flag[ $tag ] && ( Urvanov_Syntax_Highlighter_Global_Settings::val( $tag ) || $force ) ) {
$tags_regex .= '|' . $regex;
}
}
$tags_regex .= ')#msi';
}
}
/**
* Init tag bits.
*/
private static function init_tag_bits() {
if ( 0 === count( self::$tag_bits ) ) {
$values = array();
$count = count( self::$tag_types );
for ( $i = 0; $i < $count; $i ++ ) {
$j = pow( 2, $i );
self::$tag_bits[ self::$tag_types[ $i ] ] = $j;
}
}
}
/**
* Tag bit.
*
* @param mixed $tag Tag.
*
* @return mixed|null
*/
public static function tag_bit( $tag ) {
self::init_tag_bits();
if ( isset( self::$tag_bits[ $tag ] ) ) {
return self::$tag_bits[ $tag ];
} else {
return null;
}
}
/**
* In flag.
*
* @param mixed $flags Flags.
*
* @return array
*/
public static function in_flag( $flags ): array {
$in_flag = array();
foreach ( self::$tag_types as $tag ) {
$in_flag[ $tag ] = null === $flags || ( $flags & self::tag_bit( $tag ) ) > 0;
}
return $in_flag;
}
/**
* Init legacy tag bits.
*/
private static function init_legacy_tag_bits() {
if ( null === self::$legacy_flags ) {
self::$legacy_flags = self::tag_bit( Urvanov_Syntax_Highlighter_Settings::CAPTURE_MINI_TAG ) |
self::tag_bit( Urvanov_Syntax_Highlighter_Settings::INLINE_TAG ) |
self::tag_bit( Urvanov_Syntax_Highlighter_Settings::PLAIN_TAG );
}
if ( '' === self::$tags_regex_legacy ) {
self::init_tags_regex( true, self::$legacy_flags, self::$tags_regex_legacy );
}
}
/**
* Add Crayon into the_content.
*
* @param string $the_content Content.
*
* @return array|string|string[]|null
*/
public static function the_content( string $the_content ) {
UrvanovSyntaxHighlighterLog::debug( 'the_content' );
// Some themes make redundant queries and don't need extra work...
if ( 0 === strlen( $the_content ) ) {
UrvanovSyntaxHighlighterLog::debug( 'the_content blank' );
return $the_content;
}
global $post;
// Go through queued posts and find crayons.
$post_id = strval( $post->ID );
if ( self::$is_excerpt ) {
UrvanovSyntaxHighlighterLog::debug( 'excerpt' );
if ( Urvanov_Syntax_Highlighter_Global_Settings::val( Urvanov_Syntax_Highlighter_Settings::EXCERPT_STRIP ) ) {
UrvanovSyntaxHighlighterLog::debug( 'excerpt strip' );
// Remove Crayon from content if we are displaying an excerpt.
$the_content = preg_replace( self::REGEX_WITH_ID, '', $the_content );
}