forked from aramk/crayon-syntax-highlighter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crayon_wp.class.php
1334 lines (1155 loc) · 56.9 KB
/
crayon_wp.class.php
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: Crayon Syntax Highlighter
Plugin URI: https://github.com/aramkocharyan/crayon-syntax-highlighter
Description: Supports multiple languages, themes, highlighting from a URL, local file or post text.
Version: _2.6.7_beta
Author: Aram Kocharyan
Author URI: http://aramk.com/
Text Domain: crayon-syntax-highlighter
Domain Path: /trans/
License: GPL2
Copyright 2013 Aram Kocharyan (email : [email protected])
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
*/
require_once('global.php');
require_once(CRAYON_HIGHLIGHTER_PHP);
if (CRAYON_TAG_EDITOR) {
require_once(CRAYON_TAG_EDITOR_PHP);
}
if (CRAYON_THEME_EDITOR) {
require_once(CRAYON_THEME_EDITOR_PHP);
}
require_once('crayon_settings_wp.class.php');
if (defined('ABSPATH')) {
// Used to get plugin version info
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
crayon_set_info(get_plugin_data(__FILE__));
}
/* The plugin class that manages all other classes and integrates Crayon with WP */
class CrayonWP {
// Properties and Constants ===============================================
// Associative array, keys are post IDs as strings and values are number of crayons parsed as ints
private static $post_queue = array();
// Ditto for comments
private static $comment_queue = array();
private static $post_captures = array();
private static $comment_captures = array();
// Whether we are displaying an excerpt
private static $is_excerpt = FALSE;
// Whether we have added styles and scripts
private static $enqueued = FALSE;
// Whether we have already printed the wp head
private static $wp_head = FALSE;
// Used to keep Crayon IDs
private static $next_id = 0;
// String to store the regex for capturing tags
private static $alias_regex = '';
private static $tags_regex = '';
private static $tags_regex_legacy = '';
private static $tag_regexes = array();
// Defined constants used in bitwise flags
private static $tag_types = array(
CrayonSettings::CAPTURE_MINI_TAG,
CrayonSettings::CAPTURE_PRE,
CrayonSettings::INLINE_TAG,
CrayonSettings::PLAIN_TAG,
CrayonSettings::BACKQUOTE);
private static $tag_bits = array();
// Used to find legacy tags
private static $legacy_flags = NULL;
// Used to detect the shortcode
private static $allowed_atts = array('url' => NULL, 'lang' => NULL, 'title' => NULL, 'mark' => NULL, 'range' => NULL, 'inline' => NULL);
const REGEX_CLOSED = '(?:\[\s*crayon(?:-(\w+))?\b([^\]]*)/\s*\])'; // [crayon atts="" /]
const REGEX_TAG = '(?:\[\s*crayon(?:-(\w+))?\b([^\]]*)\](.*?)\[\s*/\s*crayon\s*\])'; // [crayon atts=""] ... [/crayon]
const REGEX_INLINE_CLASS = '\bcrayon-inline\b';
const REGEX_CLOSED_NO_CAPTURE = '(?:\[\s*crayon\b[^\]]*/\])';
const REGEX_TAG_NO_CAPTURE = '(?:\[\s*crayon\b[^\]]*\].*?\[/crayon\])';
const REGEX_QUICK_CAPTURE = '(?:\[\s*crayon[^\]]*\].*?\[\s*/\s*crayon\s*\])|(?:\[\s*crayon[^\]]*/\s*\])';
const REGEX_BETWEEN_PARAGRAPH = '<p[^<]*>(?:[^<]*<(?!/?p(\s+[^>]*)?>)[^>]+(\s+[^>]*)?>)*[^<]*((?:\[\s*crayon[^\]]*\].*?\[\s*/\s*crayon\s*\])|(?:\[\s*crayon[^\]]*/\s*\]))(?:[^<]*<(?!/?p(\s+[^>]*)?>)[^>]+(\s+[^>]*)?>)*[^<]*</p[^<]*>';
const REGEX_BETWEEN_PARAGRAPH_SIMPLE = '(<p(?:\s+[^>]*)?>)(.*?)(</p(?:\s+[^>]*)?>)';
// For [crayon-id/]
const REGEX_BR_BEFORE = '#<\s*br\s*/?\s*>\s*(\[\s*crayon-\w+\])#msi';
const REGEX_BR_AFTER = '#(\[\s*crayon-\w+\])\s*<\s*br\s*/?\s*>#msi';
const REGEX_ID = '#(?<!\$)\[\s*crayon#mi';
//const REGEX_WITH_ID = '#(\[\s*crayon-\w+)\b([^\]]*["\'])(\s*/?\s*\])#mi';
const REGEX_WITH_ID = '#\[\s*(crayon-\w+)\b[^\]]*\]#mi';
const MODE_NORMAL = 0, MODE_JUST_CODE = 1, MODE_PLAIN_CODE = 2;
// Public Methods =========================================================
public static function post_captures() {
return self::$post_queue;
}
// Methods ================================================================
private function __construct() {
}
public static function regex() {
return '#(?<!\$)(?:' . self::REGEX_CLOSED . '|' . self::REGEX_TAG . ')(?!\$)#msi';
}
public static function regex_with_id($id) {
return '#\[\s*(crayon-' . $id . ')\b[^\]]*\]#mi';
}
public static function regex_no_capture() {
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
*/
public static function shortcode($atts, $content = NULL, $id = NULL) {
CrayonLog::debug('shortcode');
// Load attributes from shortcode
$filtered_atts = shortcode_atts(self::$allowed_atts, $atts);
// Clean attributes
$keys = array_keys($filtered_atts);
for ($i = 0; $i < count($keys); $i++) {
$key = $keys[$i];
$value = $filtered_atts[$key];
if ($value !== NULL) {
$filtered_atts[$key] = trim(strip_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 = CrayonSettings::smart_settings($extra_attr);
}
$url = $lang = $title = $mark = $range = $inline = '';
extract($filtered_atts);
$crayon = self::instance($extra_attr, $id);
// Set URL
$crayon->url($url);
$crayon->code($content);
// Set attributes, should be set after URL to allow language auto detection
$crayon->language($lang);
$crayon->title($title);
$crayon->marked($mark);
$crayon->range($range);
$crayon->is_inline($inline);
// Determine if we should highlight
$highlight = array_key_exists('highlight', $atts) ? CrayonUtil::str_to_bool($atts['highlight'], FALSE) : TRUE;
$crayon->is_highlighted($highlight);
return $crayon;
}
/* Returns Crayon instance */
public static function instance($extra_attr = array(), $id = NULL) {
CrayonLog::debug('instance');
// Create Crayon
$crayon = new CrayonHighlighter();
/* 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)) {
$crayon->settings($extra_attr);
}
if (!empty($id)) {
$crayon->id($id);
}
return $crayon;
}
/* For manually highlighting code, useful for other PHP contexts */
public static function highlight($code, $add_tags = FALSE) {
$captures = CrayonWP::capture_crayons(0, $code);
$the_captures = $captures['capture'];
if (count($the_captures) == 0 && $add_tags) {
// Nothing captured, so wrap in a pre and try again
$code = '<pre>' . $code . '</pre>';
$captures = CrayonWP::capture_crayons(0, $code);
$the_captures = $captures['capture'];
}
$the_content = $captures['content'];
foreach ($the_captures as $id => $capture) {
$atts = $capture['atts'];
$no_enqueue = array(
CrayonSettings::ENQUEUE_THEMES => FALSE,
CrayonSettings::ENQUEUE_FONTS => FALSE);
$atts = array_merge($atts, $no_enqueue);
$code = $capture['code'];
$crayon = CrayonWP::shortcode($atts, $code, $id);
$crayon_formatted = $crayon->output(TRUE, FALSE);
$the_content = CrayonUtil::preg_replace_escape_back(self::regex_with_id($id), $crayon_formatted, $the_content, 1, $count);
}
return $the_content;
}
public static function ajax_highlight() {
$code = isset($_POST['code']) ? $_POST['code'] : null;
if (!$code) {
$code = isset($_GET['code']) ? $_GET['code'] : null;
}
if ($code) {
echo self::highlight($code);
} else {
echo "No code specified.";
}
exit();
}
/* Uses the main query */
public static function wp() {
CrayonLog::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
public static function capture_crayons($wp_id, $wp_content, $extra_settings = array(), $args = array()) {
extract($args);
CrayonUtil::set_var($callback, NULL);
CrayonUtil::set_var($callback_extra_args, NULL);
CrayonUtil::set_var($ignore, TRUE);
CrayonUtil::set_var($preserve_atts, FALSE);
CrayonUtil::set_var($flags, NULL);
CrayonUtil::set_var($skip_setting_check, FALSE);
CrayonUtil::set_var($just_check, FALSE);
// Will contain captured crayons and altered $wp_content
$capture = array('capture' => array(), 'content' => $wp_content, 'has_captured' => FALSE);
// Flags for which Crayons to convert
$in_flag = self::in_flag($flags);
CrayonLog::debug('capture for id ' . $wp_id . ' len ' . strlen($wp_content));
// Convert <pre> tags to crayon tags, if needed
if ((CrayonGlobalSettings::val(CrayonSettings::CAPTURE_PRE) || $skip_setting_check) && $in_flag[CrayonSettings::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', 'CrayonWP::pre_tag', $wp_content);
}
// Convert mini [php][/php] tags to crayon tags, if needed
if ((CrayonGlobalSettings::val(CrayonSettings::CAPTURE_MINI_TAG) || $skip_setting_check) && $in_flag[CrayonSettings::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 (CrayonGlobalSettings::val(CrayonSettings::CODE_TAG_CAPTURE)) {
$inline = CrayonGlobalSettings::val(CrayonSettings::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 ((CrayonGlobalSettings::val(CrayonSettings::INLINE_TAG) || $skip_setting_check) && $in_flag[CrayonSettings::INLINE_TAG]) {
if (CrayonGlobalSettings::val(CrayonSettings::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', 'CrayonWP::span_tag', $wp_content);
}
// Convert [plain] tags into <pre><code></code></pre>, if needed
if ((CrayonGlobalSettings::val(CrayonSettings::PLAIN_TAG) || $skip_setting_check) && $in_flag[CrayonSettings::PLAIN_TAG]) {
$wp_content = preg_replace_callback('#(?<!\$)\[\s*plain\s*\](.*?)\[\s*/\s*plain\s*\]#msi', 'CrayonFormatter::plain_code', $wp_content);
}
// Add IDs to the Crayons
CrayonLog::debug('capture adding id ' . $wp_id . ' , now has len ' . strlen($wp_content));
$wp_content = preg_replace_callback(self::REGEX_ID, 'CrayonWP::add_crayon_id', $wp_content);
CrayonLog::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'] = count($matches[0]) != 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;
}
CrayonLog::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
CrayonSettingsWP::load_settings();
CrayonLog::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;
for ($i = 0; $i < count($full_matches); $i++) {
// Get attributes
if (!empty($closed_atts[$i])) {
$atts = $closed_atts[$i];
} else if (!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 (count($att_matches[0]) != 0) {
for ($j = 0; $j < count($att_matches[1]); $j++) {
$atts_array[trim(strtolower($att_matches[1][$j]))] = trim($att_matches[3][$j]);
}
}
if (@$atts_array[CrayonSettings::IGNORE]) {
// TODO(aramk) Revert to the original content.
continue;
}
// Capture theme
$theme_id = array_key_exists(CrayonSettings::THEME, $atts_array) ? $atts_array[CrayonSettings::THEME] : '';
$theme = CrayonResources::themes()->get($theme_id);
// If theme not found, use fallbacks
if (!$theme) {
// Given theme is invalid, try global setting
$theme_id = CrayonGlobalSettings::val(CrayonSettings::THEME);
$theme = CrayonResources::themes()->get($theme_id);
if (!$theme) {
// Global setting is invalid, fall back to default
$theme = CrayonResources::themes()->get_default();
$theme_id = CrayonThemes::DEFAULT_THEME;
}
}
// If theme is now valid, change the array
if ($theme) {
if (!$preserve_atts || isset($atts_array[CrayonSettings::THEME])) {
$atts_array[CrayonSettings::THEME] = $theme_id;
}
$theme->used(TRUE);
}
// Capture font
$font_id = array_key_exists(CrayonSettings::FONT, $atts_array) ? $atts_array[CrayonSettings::FONT] : '';
$font = CrayonResources::fonts()->get($font_id);
// If font not found, use fallbacks
if (!$font) {
// Given font is invalid, try global setting
$font_id = CrayonGlobalSettings::val(CrayonSettings::FONT);
$font = CrayonResources::fonts()->get($font_id);
if (!$font) {
// Global setting is invalid, fall back to default
$font = CrayonResources::fonts()->get_default();
$font_id = CrayonFonts::DEFAULT_FONT;
}
}
// If font is now valid, change the array
if ($font /* != NULL && $font_id != CrayonFonts::DEFAULT_FONT*/) {
if (!$preserve_atts || isset($atts_array[CrayonSettings::FONT])) {
$atts_array[CrayonSettings::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];
//if ($ignore) {
$code = self::crayon_remove_ignore($contents[$i]);
//}
$c = array('post_id' => $wp_id, 'atts' => $atts_array, 'code' => $code);
$capture['capture'][$id] = $c;
CrayonLog::debug('capture finished for post id ' . $wp_id . ' crayon-id ' . $id . ' atts: ' . count($atts_array) . ' code: ' . strlen($code));
$is_inline = isset($atts_array['inline']) && CrayonUtil::str_to_bool($atts_array['inline'], FALSE) ? '-i' : '';
if ($callback === NULL) {
$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;
}
public static function replace_backquotes($wp_content) {
// 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 (CrayonGlobalSettings::val(CrayonSettings::BACKQUOTE)) {
$wp_content = preg_replace('#(?<!\\\\)`([^`]*)`#msi', '<code>$1</code>', $wp_content);
}
$result['changed'] = $prev_count !== strlen($wp_content);
$result['content'] = $wp_content;
return $result;
}
/* Search for Crayons in posts and queue them for creation */
public static function the_posts($posts) {
CrayonLog::debug('the_posts');
// Whether to enqueue syles/scripts
CrayonSettingsWP::load_settings(TRUE); // We will eventually need more than the settings
self::init_tags_regex();
$crayon_posts = CrayonSettingsWP::load_posts(); // Loads posts containing crayons
// Search for shortcode in posts
foreach ($posts as $post) {
$wp_id = $post->ID;
$is_page = $post->post_type == 'page';
if (!in_array($wp_id, $crayon_posts)) {
// 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 (CrayonGlobalSettings::val(CrayonSettings::SAFE_ENQUEUE) && $is_page) {
CrayonGlobalSettings::set(CrayonSettings::ENQUEUE_THEMES, false);
CrayonGlobalSettings::set(CrayonSettings::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 ($captures['has_captured'] === TRUE) {
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 (CrayonGlobalSettings::val(CrayonSettings::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(CrayonSettings::DECODE => TRUE));
self::$comment_captures[$id_str] = $captures['content'];
if ($captures['has_captured'] === TRUE) {
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;
}
private static function add_crayon_id($content) {
$uid = $content[0] . '-' . str_replace('.', '', uniqid('', true));
CrayonLog::debug('add_crayon_id ' . $uid);
return $uid;
}
private static function get_crayon_id() {
return self::$next_id++;
}
public static function enqueue_resources() {
if (!self::$enqueued) {
CrayonLog::debug('enqueue');
global $CRAYON_VERSION;
if (CRAYON_MINIFY) {
wp_enqueue_style('crayon', plugins_url(CRAYON_STYLE_MIN, __FILE__), array(), $CRAYON_VERSION);
wp_enqueue_script('crayon_js', plugins_url(CRAYON_JS_MIN, __FILE__), array('jquery'), $CRAYON_VERSION);
} else {
wp_enqueue_style('crayon_style', plugins_url(CRAYON_STYLE, __FILE__), array(), $CRAYON_VERSION);
wp_enqueue_style('crayon_global_style', plugins_url(CRAYON_STYLE_GLOBAL, __FILE__), array(), $CRAYON_VERSION);
wp_enqueue_script('crayon_util_js', plugins_url(CRAYON_JS_UTIL, __FILE__), array('jquery'), $CRAYON_VERSION);
CrayonSettingsWP::other_scripts();
}
CrayonSettingsWP::init_js_settings();
self::$enqueued = TRUE;
}
}
private static function init_tags_regex($force = FALSE, $flags = NULL, &$tags_regex = NULL) {
CrayonSettingsWP::load_settings();
self::init_tag_bits();
// Default output
if ($tags_regex === NULL) {
$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[CrayonSettings::CAPTURE_MINI_TAG] && (CrayonGlobalSettings::val(CrayonSettings::CAPTURE_MINI_TAG)) || $force) ||
($in_flag[CrayonSettings::INLINE_TAG] && (CrayonGlobalSettings::val(CrayonSettings::INLINE_TAG) && CrayonGlobalSettings::val(CrayonSettings::INLINE_TAG_CAPTURE)) || $force)
) {
$aliases = CrayonResources::langs()->ids_and_aliases();
self::$alias_regex = '';
for ($i = 0; $i < count($aliases); $i++) {
$alias = $aliases[$i];
$alias_regex = CrayonUtil::esc_hash(CrayonUtil::esc_regex($alias));
if ($i != count($aliases) - 1) {
$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(
CrayonSettings::CAPTURE_MINI_TAG => '(\[\s*(' . self::$alias_regex . ')\b)',
CrayonSettings::CAPTURE_PRE => '(<\s*pre\b)',
CrayonSettings::INLINE_TAG => '(' . self::REGEX_INLINE_CLASS . ')' . '|(\{\s*(' . self::$alias_regex . ')\b([^\}]*)\})',
CrayonSettings::PLAIN_TAG => '(\s*\[\s*plain\b)',
CrayonSettings::BACKQUOTE => '(`[^`]*`)'
);
foreach ($tag_regexes as $tag => $regex) {
if ($in_flag[$tag] && (CrayonGlobalSettings::val($tag) || $force)) {
$tags_regex .= '|' . $regex;
}
}
$tags_regex .= ')#msi';
}
}
private static function init_tag_bits() {
if (count(self::$tag_bits) == 0) {
$values = array();
for ($i = 0; $i < count(self::$tag_types); $i++) {
$j = pow(2, $i);
self::$tag_bits[self::$tag_types[$i]] = $j;
}
}
}
public static function tag_bit($tag) {
self::init_tag_bits();
if (isset(self::$tag_bits[$tag])) {
return self::$tag_bits[$tag];
} else {
return null;
}
}
public static function in_flag($flags) {
$in_flag = array();
foreach (self::$tag_types as $tag) {
$in_flag[$tag] = $flags === NULL || ($flags & self::tag_bit($tag)) > 0;
}
return $in_flag;
}
private static function init_legacy_tag_bits() {
if (self::$legacy_flags === NULL) {
self::$legacy_flags = self::tag_bit(CrayonSettings::CAPTURE_MINI_TAG) |
self::tag_bit(CrayonSettings::INLINE_TAG) |
self::tag_bit(CrayonSettings::PLAIN_TAG);
}
if (self::$tags_regex_legacy === "") {
self::init_tags_regex(TRUE, self::$legacy_flags, self::$tags_regex_legacy);
}
}
// Add Crayon into the_content
public static function the_content($the_content) {
CrayonLog::debug('the_content');
// Some themes make redundant queries and don't need extra work...
if (strlen($the_content) == 0) {
CrayonLog::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) {
CrayonLog::debug('excerpt');
if (CrayonGlobalSettings::val(CrayonSettings::EXCERPT_STRIP)) {
CrayonLog::debug('excerpt strip');
// Remove Crayon from content if we are displaying an excerpt
$the_content = preg_replace(self::REGEX_WITH_ID, '', $the_content);
}
// Otherwise Crayon remains with ID and replaced later
return $the_content;
}
// Find if this post has Crayons
if (array_key_exists($post_id, self::$post_queue)) {
self::enqueue_resources();
// XXX We want the plain post content, no formatting
$the_content_original = $the_content;
// Replacing may cause <p> tags to become disjoint with a <div> inside them, close and reopen them if needed
$the_content = preg_replace_callback('#' . self::REGEX_BETWEEN_PARAGRAPH_SIMPLE . '#msi', 'CrayonWP::add_paragraphs', $the_content);
// Loop through Crayons
$post_in_queue = self::$post_queue[$post_id];
foreach ($post_in_queue as $id => $v) {
$atts = $v['atts'];
$content = $v['code']; // The code we replace post content with
$crayon = self::shortcode($atts, $content, $id);
if (is_feed()) {
// Convert the plain code to entities and put in a <pre></pre> tag
$crayon_formatted = CrayonFormatter::plain_code($crayon->code(), $crayon->setting_val(CrayonSettings::DECODE));
} else {
// Apply shortcode to the content
$crayon_formatted = $crayon->output(TRUE, FALSE);
}
// Replace the code with the Crayon
CrayonLog::debug('the_content: id ' . $post_id . ' has UID ' . $id . ' : ' . intval(stripos($the_content, $id) !== FALSE));
$the_content = CrayonUtil::preg_replace_escape_back(self::regex_with_id($id), $crayon_formatted, $the_content, 1, $count);
CrayonLog::debug('the_content: REPLACED for id ' . $post_id . ' from len ' . strlen($the_content_original) . ' to ' . strlen($the_content));
}
}
return $the_content;
}
public static function pre_comment_text($text) {
global $comment;
$comment_id = strval($comment->comment_ID);
if (array_key_exists($comment_id, self::$comment_captures)) {
// Replace with IDs now that we need to
$text = self::$comment_captures[$comment_id];
}
return $text;
}
public static function comment_text($text) {
global $comment;
$comment_id = strval($comment->comment_ID);
// Find if this post has Crayons
if (array_key_exists($comment_id, self::$comment_queue)) {
// XXX We want the plain post content, no formatting
$the_content_original = $text;
// Loop through Crayons
$post_in_queue = self::$comment_queue[$comment_id];
foreach ($post_in_queue as $id => $v) {
$atts = $v['atts'];
$content = $v['code']; // The code we replace post content with
$crayon = self::shortcode($atts, $content, $id);
$crayon_formatted = $crayon->output(TRUE, FALSE);
// Replacing may cause <p> tags to become disjoint with a <div> inside them, close and reopen them if needed
if (!$crayon->is_inline()) {
$text = preg_replace_callback('#' . self::REGEX_BETWEEN_PARAGRAPH_SIMPLE . '#msi', 'CrayonWP::add_paragraphs', $text);
}
// Replace the code with the Crayon
$text = CrayonUtil::preg_replace_escape_back(self::regex_with_id($id), $crayon_formatted, $text, 1, $text);
}
}
return $text;
}
public static function add_paragraphs($capture) {
if (count($capture) != 4) {
CrayonLog::debug('add_paragraphs: 0');
return $capture[0];
}
$capture[2] = preg_replace('#(?:<\s*br\s*/\s*>\s*)?(\[\s*crayon-\w+/\])(?:<\s*br\s*/\s*>\s*)?#msi', '</p>$1<p>', $capture[2]);
// If [crayon appears right after <p> then we will generate <p></p>, remove all these
$paras = $capture[1] . $capture[2] . $capture[3];
return $paras;
}
// Remove Crayons from the_excerpt
public static function the_excerpt($the_excerpt) {
CrayonLog::debug('excerpt');
global $post;
if (!empty($post->post_excerpt)) {
// Use custom excerpt if defined
$the_excerpt = wpautop($post->post_excerpt);
} else {
// Pass wp_trim_excerpt('') to gen from content (and remove [crayons])
$the_excerpt = wpautop(wp_trim_excerpt(''));
}
// XXX Returning "" may cause it to default to full contents...
return $the_excerpt . ' ';
}
// Used to capture pre and span tags which have settings in class attribute
public static function class_tag($matches) {
// If class exists, atts is not captured
$pre_class = $matches[1];
$quotes = $matches[2];
$class = $matches[3];
$post_class = $matches[4];
$atts = $matches[5];
$content = $matches[6];
// If we find a crayon=false in the attributes, or a crayon[:_]false in the class, then we should not capture
$ignore_regex_atts = '#crayon\s*=\s*(["\'])\s*(false|no|0)\s*\1#msi';
$ignore_regex_class = '#crayon\s*[:_]\s*(false|no|0)#msi';
if (preg_match($ignore_regex_atts, $atts) !== 0 ||
preg_match($ignore_regex_class, $class) !== 0
) {
return $matches[0];
}
if (!empty($class)) {
if (preg_match('#\bignore\s*:\s*true#', $class)) {
// Prevent any changes if ignoring the tag.
return $matches[0];
}
// crayon-inline is turned into inline="1"
$class = preg_replace('#' . self::REGEX_INLINE_CLASS . '#mi', 'inline="1"', $class);
// "setting[:_]value" style settings in the class attribute
$class = preg_replace('#\b([A-Za-z-]+)[_:](\S+)#msi', '$1=' . $quotes . '$2' . $quotes, $class);
}
// data-url is turned into url=""
if (!empty($post_class)) {
$post_class = preg_replace('#\bdata-url\s*=#mi', 'url=', $post_class);
}
if (!empty($pre_class)) {
$pre_class = preg_replace('#\bdata-url\s*=#mi', 'url=', $post_class);
}
if (!empty($class)) {
return "[crayon $pre_class $class $post_class]{$content}[/crayon]";
} else {
return "[crayon $atts]{$content}[/crayon]";
}
}
// Capture span tag and extract settings from the class attribute, if present.
public static function span_tag($matches) {
// Only use <span> tags with crayon-inline class
if (preg_match('#' . self::REGEX_INLINE_CLASS . '#mi', $matches[3])) {
// no $atts
$matches[6] = $matches[5];
$matches[5] = '';
return self::class_tag($matches);
} else {
// Don't turn regular <span>s into Crayons
return $matches[0];
}
}
// Capture pre tag and extract settings from the class attribute, if present.
public static function pre_tag($matches) {
return self::class_tag($matches);
}
/**
* Check if the $ notation has been used to ignore [crayon] tags within posts and remove all matches
* Can also remove if used without $ as a regular crayon
*
* @depreciated
*/
public static function crayon_remove_ignore($the_content, $ignore_flag = '$') {
if ($ignore_flag == FALSE) {
$ignore_flag = '';
}
$ignore_flag_regex = preg_quote($ignore_flag);
$the_content = preg_replace('#' . $ignore_flag_regex . '(\s*\[\s*crayon)#msi', '$1', $the_content);
$the_content = preg_replace('#(crayon\s*\])\s*\$#msi', '$1', $the_content);
if (CrayonGlobalSettings::val(CrayonSettings::CAPTURE_PRE)) {
$the_content = str_ireplace(array($ignore_flag . '<pre', 'pre>' . $ignore_flag), array('<pre', 'pre>'), $the_content);
// Remove any <code> tags wrapping around the whole code, since we won't needed them
// XXX This causes <code> tags to be stripped in the post content! Disabled now.
// $the_content = preg_replace('#(^\s*<\s*code[^>]*>)|(<\s*/\s*code[^>]*>\s*$)#msi', '', $the_content);
}
if (CrayonGlobalSettings::val(CrayonSettings::PLAIN_TAG)) {
$the_content = str_ireplace(array($ignore_flag . '[plain', 'plain]' . $ignore_flag), array('[plain', 'plain]'), $the_content);
}
if (CrayonGlobalSettings::val(CrayonSettings::CAPTURE_MINI_TAG) ||
(CrayonGlobalSettings::val(CrayonSettings::INLINE_TAG && CrayonGlobalSettings::val(CrayonSettings::INLINE_TAG_CAPTURE)))
) {
self::init_tags_regex();
// $the_content = preg_replace('#'.$ignore_flag_regex.'\s*([\[\{])\s*('. self::$alias_regex .')#', '$1$2', $the_content);
// $the_content = preg_replace('#('. self::$alias_regex .')\s*([\]\}])\s*'.$ignore_flag_regex.'#', '$1$2', $the_content);
$the_content = preg_replace('#' . $ignore_flag_regex . '(\s*[\[\{]\s*(' . self::$alias_regex . ')[^\]]*[\]\}])#', '$1', $the_content);
}
if (CrayonGlobalSettings::val(CrayonSettings::BACKQUOTE)) {
$the_content = str_ireplace('\\`', '`', $the_content);
}
return $the_content;
}
public static function wp_head() {
CrayonLog::debug('head');
self::$wp_head = TRUE;
if (!self::$enqueued) {
CrayonLog::debug('head: missed enqueue');
// We have missed our chance to check before enqueuing. Use setting to either load always or only in the_post
CrayonSettingsWP::load_settings(TRUE); // Ensure settings are loaded
// If we need the tag editor loaded at all times, we must enqueue at all times
if (!CrayonGlobalSettings::val(CrayonSettings::EFFICIENT_ENQUEUE) || CrayonGlobalSettings::val(CrayonSettings::TAG_EDITOR_FRONT)) {
CrayonLog::debug('head: force enqueue');
// Efficient enqueuing disabled, always load despite enqueuing or not in the_post
self::enqueue_resources();
}
}
// Enqueue Theme CSS
if (CrayonGlobalSettings::val(CrayonSettings::ENQUEUE_THEMES)) {
self::crayon_theme_css();
}
// Enqueue Font CSS
if (CrayonGlobalSettings::val(CrayonSettings::ENQUEUE_FONTS)) {
self::crayon_font_css();
}
}
public static function save_post($update_id, $post) {
self::refresh_post($post);
}
public static function filter_post_data($data, $postarr) {
// Remove the selected CSS that may be present from the tag editor.
CrayonTagEditorWP::init_settings();
$css_selected = CrayonTagEditorWP::$settings['css_selected'];
$data['post_content'] = preg_replace("#(class\s*=\s*(\\\\[\"'])[^\"']*)$css_selected([^\"']*\\2)#msi", '$1$3', $data['post_content']);
return $data;
}
public static function refresh_post($post, $refresh_legacy = TRUE, $save = TRUE) {
$postID = $post->ID;
if (wp_is_post_revision($postID)) {
// Ignore revisions
return;
}
if (CrayonWP::scan_post($post)) {
CrayonSettingsWP::add_post($postID, $save);
if ($refresh_legacy) {
if (self::scan_legacy_post($post)) {
CrayonSettingsWP::add_legacy_post($postID, $save);
} else {
CrayonSettingsWP::remove_legacy_post($postID, $save);
}
}
} else {
CrayonSettingsWP::remove_post($postID, $save);
CrayonSettingsWP::remove_legacy_post($postID, $save);
}
}
public static function refresh_posts() {
CrayonSettingsWP::remove_posts();
CrayonSettingsWP::remove_legacy_posts();
foreach (CrayonWP::get_posts() as $post) {
self::refresh_post($post, TRUE, FALSE);
}
CrayonSettingsWP::save_posts();
CrayonSettingsWP::save_legacy_posts();
}
public static function save_comment($id, $is_spam = NULL, $comment = NULL) {
self::init_tags_regex();
if ($comment === NULL) {
$comment = get_comment($id);
}
$content = $comment->comment_content;
$post_id = $comment->comment_post_ID;
$found = preg_match(self::$tags_regex, $content);
if ($found) {
CrayonSettingsWP::add_post($post_id);
}
return $found;
}
public static function crayon_theme_css() {
global $CRAYON_VERSION;
CrayonSettingsWP::load_settings();
$css = CrayonResources::themes()->get_used_css();
foreach ($css as $theme => $url) {
wp_enqueue_style('crayon-theme-' . $theme, $url, array(), $CRAYON_VERSION);
}
}
public static function crayon_font_css() {
global $CRAYON_VERSION;
CrayonSettingsWP::load_settings();
$css = CrayonResources::fonts()->get_used_css();
foreach ($css as $font_id => $url) {
wp_enqueue_style('crayon-font-' . $font_id, $url, array(), $CRAYON_VERSION);
}
}
public static function init($request) {
CrayonLog::debug('init');
crayon_load_plugin_textdomain();
}
public static function init_ajax() {
add_action('wp_ajax_crayon-tag-editor', 'CrayonTagEditorWP::content');
add_action('wp_ajax_nopriv_crayon-tag-editor', 'CrayonTagEditorWP::content');
add_action('wp_ajax_crayon-highlight', 'CrayonWP::ajax_highlight');
add_action('wp_ajax_nopriv_crayon-highlight', 'CrayonWP::ajax_highlight');
if (is_admin()) {
add_action('wp_ajax_crayon-ajax', 'CrayonWP::ajax');
add_action('wp_ajax_crayon-theme-editor', 'CrayonThemeEditorWP::content');
add_action('wp_ajax_crayon-theme-editor-save', 'CrayonThemeEditorWP::save');
add_action('wp_ajax_crayon-theme-editor-delete', 'CrayonThemeEditorWP::delete');
add_action('wp_ajax_crayon-theme-editor-duplicate', 'CrayonThemeEditorWP::duplicate');
add_action('wp_ajax_crayon-theme-editor-submit', 'CrayonThemeEditorWP::submit');
add_action('wp_ajax_crayon-show-posts', 'CrayonSettingsWP::show_posts');
add_action('wp_ajax_crayon-show-langs', 'CrayonSettingsWP::show_langs');
add_action('wp_ajax_crayon-show-preview', 'CrayonSettingsWP::show_preview');
}
}
public static function ajax() {
$allowed = array(CrayonSettings::HIDE_HELP);
foreach ($allowed as $allow) {
if (array_key_exists($allow, $_GET)) {
CrayonGlobalSettings::set($allow, $_GET[$allow]);
CrayonSettingsWP::save_settings();
}
}
}
public static function get_posts() {
$query = new WP_Query(array('post_type' => 'any', 'suppress_filters' => TRUE, 'posts_per_page' => '-1'));
if (isset($query->posts)) {