forked from b2evolution/code_highlight_plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_code_highlight.plugin.php
792 lines (695 loc) · 28.6 KB
/
_code_highlight.plugin.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
<?php
/**
* This file implements the AstonishMe Code plugin.
*
* This file is part of the b2evolution project - {@link http://b2evolution.net/}
*
* @license GNU GPL v2 - {@link http://b2evolution.net/about/gnu-gpl-license}
*
* @copyright (c)2003-2018 by Francois Planque - {@link http://fplanque.com/}
* Parts of this file are copyright (c)2005-2007 by Yabba/Scott - {@link http://astonishme.co.uk/contact/}.
*
* @package plugins
*
* @author Yabba: Paul Jones - {@link http://astonishme.co.uk/}
* @author Stk: Scott Kimler - {@link http://astonishme.co.uk/}
*/
/**
* AstonishMe Display Code plugin.
*
* Features:
* 1) Character entity rendering on-the-fly
* 2) Easy to use, just cut'n-paste your code
* 3) Automatically adds line numbers and alternate colouring
* 4) Customizable CSS for integrating for your site
* 5) XHTML (Strict) and CSS valid code
* 6) Auto-senses code block length
* 7) BBCode tags pass through and allow to highlight the code
* 8) No accidental smilie rendering
* 9) PHP Syntax highlighting
* 10) Variable start line numbers
* 11) Links php functions to the php.net documentation
* 12) Code is preserved if plugin uninstalled ( stored as : <!--amphp--><pre><php echo 'hello world'; ?></pre><!--/amphp--> )
*
* To use:
* ************************************** THIS WILL NEED REWRITING ******************************************
* * Upload and install the plugin via the back office
* * Paste your code between <amcode> </amcode> tags
* * Paste your php between <amphp> </amphp> tags
* * start from any line number with the line attribute
* * <amcode line="99"> or <amphp line="999">
*
* @todo fp> for semantic purposes, <code> </code> should be automagically added
* yabs > I assume you mean that <code> block </code> should also be converted/highlighted
* in which case "done", I also added in <php> </php> ( was an easier regex :p )
* obviously we originally picked the tag names to suit ourselves
*
* @todo dh> I'd like to be able to disable line numbering in codeblocks.
* Line numbers do not make sense for short code blocks (and also for longer ones
* not necessarily).
* fp> how about if no line=".." attribute is specified then no numbering?
* dh> Well.. this would change the default "[codeblock]" though. Yes, when
* clicking the button it uses '[codeblock lang="" line="1"][/codeblock]', but
* the "default" is still just the tag, and at least I've been using that
* (typing instead of clicking).
*/
if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' );
/**
* @package plugins
*/
class code_highlight_plugin extends Plugin
{
var $name = 'Code highlight';
var $code = 'evo_code';
var $priority = 27;
var $version = '7.0.2';
var $author = 'Astonish Me';
var $group = 'rendering';
var $help_topic = 'code-highlight-plugin';
var $number_of_installs = 1;
/**
* Text php functions array
*
* @access private
*/
var $php_functions = array();
/**
* Text php syntax highlighting colours array
*
* @access private
*/
var $highlight_colours = array();
/**
* EXPERIMENTAL - array language classes cache
*
* @access private
*/
var $languageCache = array();
/**
* TRUE when HTML tags are allowed for content of current rendered post/comment/message
* In this case we should prepare a content with function htmlspecialchars() to display a code as it is
*
* @var boolean
*/
var $allow_html = false;
/**
* Init
*/
function PluginInit( & $params )
{
$this->short_desc = T_( 'Display computer code in a post.' ).' '.T_( '(Plugin not available in WYSIWYG mode)' );
$this->long_desc = T_( 'Display computer code easily with syntax coloring and allowing for easy copy/paste.' ).' '.T_( '(Plugin not available in WYSIWYG mode)' );
}
/**
* Define the GLOBAL settings of the plugin here. These can then be edited in the backoffice in System > Plugins.
*
* @param array Associative array of parameters (since v1.9).
* 'for_editing': true, if the settings get queried for editing;
* false, if they get queried for instantiating {@link Plugin::$Settings}.
* @return array see {@link Plugin::GetDefaultSettings()}.
* The array to be returned should define the names of the settings as keys (max length is 30 chars)
* and assign an array with the following keys to them (only 'label' is required):
*/
function GetDefaultSettings( & $params )
{
$r = array(
'strict' => array(
'label' => $this->T_( 'XHTML strict' ),
'type' => 'checkbox',
'defaultvalue' => '0', // use transitional as default
'note' => $this->T_( 'If enabled this will remove the \' target="_blank" \' from the PHP documentation links' ),
),
'toolbar_default' => array(
'label' => $this->T_( 'Display code toolbar' ),
'type' => 'checkbox',
'defaultvalue' => '1',
'note' => $this->T_( 'Display code toolbar in expert mode and on comment form (indivdual users can override this).' ),
),
);
return $r;
}
/**
* Define the PER-USER settings of the plugin here. These can then be edited by each user.
*
* @see Plugin::GetDefaultSettings()
* @param array Associative array of parameters.
* 'for_editing': true, if the settings get queried for editing;
* false, if they get queried for instantiating
* @return array See {@link Plugin::GetDefaultSettings()}.
*/
function GetDefaultUserSettings( & $params )
{
return array(
'display_toolbar' => array(
'label' => T_( 'Display code toolbar' ),
'defaultvalue' => $this->Settings->get('toolbar_default'),
'type' => 'checkbox',
'note' => $this->T_( 'Display code toolbar' ),
),
);
}
/**
* Define here default collection/blog settings that are to be made available in the backoffice.
*
* @param array Associative array of parameters.
* @return array See {@link Plugin::GetDefaultSettings()}.
*/
function get_coll_setting_definitions( & $params )
{
$default_params = array_merge( $params, array( 'default_comment_rendering' => 'never' ) );
return parent::get_coll_setting_definitions( $default_params );
}
/**
* Event handler: Called when displaying editor toolbars on comment form.
*
* @param array Associative array of parameters
* @return boolean did we display a toolbar?
*/
function DisplayCommentToolbar( & $params )
{
if( !empty( $params['Comment'] ) )
{ // Comment is set, get Blog from comment
$Comment = & $params['Comment'];
if( !empty( $Comment->item_ID ) )
{
$comment_Item = & $Comment->get_Item();
$Collection = $Blog = & $comment_Item->get_Blog();
}
}
if( empty( $Blog ) )
{ // Comment is not set, try global Blog
global $Collection, $Blog;
if( empty( $Blog ) )
{ // We can't get a Blog, this way "apply_comment_rendering" plugin collection setting is not available
return false;
}
}
$apply_rendering = $this->get_coll_setting( 'coll_apply_comment_rendering', $Blog );
if( !empty( $apply_rendering ) && $apply_rendering != 'never'
&& ( ( is_logged_in() && $this->UserSettings->get( 'display_toolbar' ) )
|| ( !is_logged_in() && $this->Settings->get( 'toolbar_default' ) ) ) )
{
return $this->DisplayCodeToolbar( $params );
}
return false;
}
/**
* Event handler: Called when displaying editor toolbars for message.
*
* @param array Associative array of parameters
* @return boolean did we display a toolbar?
*/
function DisplayMessageToolbar( & $params )
{
$apply_rendering = $this->get_msg_setting( 'msg_apply_rendering' );
if( !empty( $apply_rendering ) && $apply_rendering != 'never'
&& ( ( is_logged_in() && $this->UserSettings->get( 'display_toolbar' ) )
|| ( !is_logged_in() && $this->Settings->get( 'toolbar_default' ) ) ) )
{
return $this->DisplayCodeToolbar( $params );
}
return false;
}
/**
* Event handler: Called when displaying editor toolbars for email.
*
* @param array Associative array of parameters
* @return boolean did we display a toolbar?
*/
function DisplayEmailToolbar( & $params )
{
$apply_rendering = $this->get_email_setting( 'email_apply_rendering' );
if( !empty( $apply_rendering ) && $apply_rendering != 'never'
&& ( ( is_logged_in() && $this->UserSettings->get( 'display_toolbar' ) )
|| ( !is_logged_in() && $this->Settings->get( 'toolbar_default' ) ) ) )
{
return $this->DisplayCodeToolbar( $params );
}
return false;
}
/**
* Event handler: Called when displaying editor toolbars on post/item form.
*
* This is for post/item edit forms only. Comments, PMs and emails use different events.
*
* @param array Associative array of parameters
* @return boolean did we display a toolbar?
*/
function AdminDisplayToolbar( & $params )
{
if( !empty( $params['Item'] ) )
{ // Item is set, get Blog from post
$edited_Item = & $params['Item'];
$Collection = $Blog = & $edited_Item->get_Blog();
}
if( empty( $Blog ) )
{ // Item is not set, try global Blog
global $Collection, $Blog;
if( empty( $Blog ) )
{ // We can't get a Blog, this way "apply_rendering" plugin collection setting is not available
return false;
}
}
$apply_rendering = $this->get_coll_setting( 'coll_apply_rendering', $Blog );
if( empty( $apply_rendering ) || $apply_rendering == 'never' || ! $this->UserSettings->get( 'display_toolbar' ) )
{ // This plugin is disabled for this blog or user doesn't want the toolbar, don't display it:
return false;
}
$this->DisplayCodeToolbar( $params );
}
/**
* Display toolbar
*
* @param array Params
*/
function DisplayCodeToolbar( $params = array() )
{
$params = array_merge( array(
'js_prefix' => '', // Use different prefix if you use several toolbars on one page
), $params );
echo $this->get_template( 'toolbar_before', array( '$toolbar_class$' => $params['js_prefix'].$this->code.'_toolbar' ) );
// TODO: dh> make this optional.. just like with line numbers, this "Code" line is not feasible with oneliners.
echo $this->get_template( 'toolbar_title_before' ).T_('Code').': '.$this->get_template( 'toolbar_title_after' );
echo $this->get_template( 'toolbar_group_before' );
echo '<input type="button" id="code_samp" title="'.T_('Insert <samp> tag').'" class="'.$this->get_template( 'toolbar_button_class' ).'" data-func="'.$params['js_prefix'].'code_tag|samp" value="samp" />';
echo '<input type="button" id="code_kbd" title="'.T_('Insert <kbd> tag').'" class="'.$this->get_template( 'toolbar_button_class' ).'" data-func="'.$params['js_prefix'].'code_tag|kbd" value="kbd" />';
echo '<input type="button" id="code_var" title="'.T_('Insert <var> tag').'" class="'.$this->get_template( 'toolbar_button_class' ).'" data-func="'.$params['js_prefix'].'code_tag|var" value="var" />';
echo '<input type="button" id="code_code" title="'.T_('Insert <code> tag').'" class="'.$this->get_template( 'toolbar_button_class' ).'" data-func="'.$params['js_prefix'].'code_tag|code" value="code" />';
echo $this->get_template( 'toolbar_group_after' );
echo $this->get_template( 'toolbar_group_before' );
echo '<input type="button" id="codespan" title="'.T_('Insert codespan').'" class="'.$this->get_template( 'toolbar_button_class' ).'" data-func="'.$params['js_prefix'].'codespan_tag| " value="codespan" />';
echo $this->get_template( 'toolbar_group_after' );
echo $this->get_template( 'toolbar_group_before' );
echo '<input type="button" id="codeblock" title="'.T_('Insert codeblock').'" class="'.$this->get_template( 'toolbar_button_class' ).'" data-func="'.$params['js_prefix'].'codeblock_tag| " value="codeblock" />';
echo '<input type="button" id="codeblock_xml" title="'.T_('Insert XML codeblock').'" class="'.$this->get_template( 'toolbar_button_class' ).'" data-func="'.$params['js_prefix'].'codeblock_tag|xml" value="XML" />';
echo '<input type="button" id="codeblock_html" title="'.T_('Insert HTML codeblock').'" class="'.$this->get_template( 'toolbar_button_class' ).'" data-func="'.$params['js_prefix'].'codeblock_tag|html" value="HTML" />';
echo '<input type="button" id="codeblock_php" title="'.T_('Insert PHP codeblock').'" class="'.$this->get_template( 'toolbar_button_class' ).'" data-func="'.$params['js_prefix'].'codeblock_tag|php" value="PHP" />';
echo '<input type="button" id="codeblock_css" title="'.T_('Insert CSS codeblock').'" class="'.$this->get_template( 'toolbar_button_class' ).'" data-func="'.$params['js_prefix'].'codeblock_tag|css" value="CSS" />';
echo '<input type="button" id="codeblock_shell" title="'.T_('Insert Shell codeblock').'" class="'.$this->get_template( 'toolbar_button_class' ).'" data-func="'.$params['js_prefix'].'codeblock_tag|shell" value="Shell" />';
echo $this->get_template( 'toolbar_group_after' );
echo $this->get_template( 'toolbar_after' );
// Load js to work with textarea
require_js( 'functions.js', 'blog', true, true );
?><script>
//<![CDATA[
function <?php echo $params['js_prefix']; ?>code_tag( tag_name )
{
tag = '<' + tag_name + '>';
textarea_wrap_selection( <?php echo $params['js_prefix']; ?>b2evoCanvas, tag, '</' + tag_name + '>', 0 );
}
function <?php echo $params['js_prefix']; ?>codespan_tag( lang )
{
tag = '[codespan]';
textarea_wrap_selection( <?php echo $params['js_prefix']; ?>b2evoCanvas, tag, '[/codespan]', 0 );
}
function <?php echo $params['js_prefix']; ?>codeblock_tag( lang )
{
tag = '[codeblock lang="'+lang+'" line="1"]';
textarea_wrap_selection( <?php echo $params['js_prefix']; ?>b2evoCanvas, tag, '[/codeblock]', 0 );
}
//]]>
</script><?php
return true;
}
/**
* Filters out the custom tag that would not validate, PLUS escapes the actual code.
*
* @param mixed $params
*/
function FilterItemContents( & $params )
{
$title = & $params['title'];
$content = & $params['content'];
// echo 'FILTERING CODE';
// Note : This regex is different from the original - just in case it gets moved again ;)
// change all <codeblock> || [codeblock] segments before format_to_post() gets a hold of them
// 1 - amcode or codeblock
// 2 - attribs : lang &| line
// 3 - code block
$content = preg_replace_callback( '#[<\[](codeblock)([^>\]]*?)[>\]]([\s\S]+?)?[<\[]/\1[>\]]#i',
array( $this, 'filter_codeblock_callback' ), $content );
// Quick and dirty escaping of inline code <codespan> || [codespan]:
// fp> please provide example of what the following fix does: it looks weird to me :p
// $content = preg_replace_callback( '#[<\[]codespan[^>\]](.*?)[<\[]/codespan[>\]]#',
$content = preg_replace_callback( '#[<\[]codespan[>\]]([\s\S]*?)[<\[]/codespan[>\]]#',
array( $this, 'filter_codespan_callback' ), $content );
return true;
}
/**
* Format codespan for display
*
* @todo This is a bit quick 'n dirty.
* @todo We might want to unfilter this too.
* @todo We might want to highlight this too (based on a lang attribute).
*/
function filter_codespan_callback( $matches )
{
$code = $matches[1];
return '<code class="codespan">'.$code.'</code>';
}
/**
* Formats post contents ready for editing
*
* @param mixed $params
*/
function UnfilterItemContents( & $params )
{
$title = & $params['title'];
$content = & $params['content'];
// 1 - attribs : lang &| line
// 2 - codeblock
$content = preg_replace_callback( '#<\!--\s*codeblock([^-]*?)\s*--><pre[^>]*><code>(.+?)</code></pre><\!--\s+/codeblock\s*-->#is', array( $this, 'format_to_edit' ), $content );
$content = preg_replace_callback( '#<code class="codespan">(.+?)</code>#is', array( $this, 'format_span_to_edit' ), $content );
return true;
}
function CommentFormSent( & $params )
{
$ItemCache = & get_ItemCache();
$comment_Item = & $ItemCache->get_by_ID( $params['comment_item_ID'], false );
if( !$comment_Item )
{ // Incorrect item
return false;
}
$item_Blog = & $comment_Item->get_Blog();
$apply_rendering = $this->get_coll_setting( 'coll_apply_comment_rendering', $item_Blog );
if( $this->is_renderer_enabled( $apply_rendering, $params['renderers'] ) )
{ // render code blocks in comment
$params['content' ] = & $params['comment'];
$this->FilterItemContents( $params );
if( empty( $params['dont_remove_pre'] ) || !$params['dont_remove_pre'] )
{ // remove <pre>
$params['comment'] = preg_replace( '#(<\!--\s*codeblock[^-]*?\s*-->)<pre[^>]*><code>(.+?)</code></pre>(<\!--\s+/codeblock\s*-->)#is', '$1<code>$2</code>$3', $params['comment'] );
}
}
}
function MessageThreadFormSent( & $params )
{
$apply_rendering = $this->get_msg_setting( 'msg_apply_rendering' );
if( $this->is_renderer_enabled( $apply_rendering, $params['renderers'] ) )
{ // render code blocks in message
$this->FilterItemContents( $params );
if( empty( $params['dont_remove_pre'] ) || !$params['dont_remove_pre'] )
{ // remove <pre>
$params['content'] = preg_replace( '#(<\!--\s*codeblock[^-]*?\s*-->)<pre[^>]*><code>(.+?)</code></pre>(<\!--\s+/codeblock\s*-->)#is', '$1<code>$2</code>$3', $params['content'] );
}
}
}
/**
* Event handler: Called before at the beginning, if an email form gets sent (and received).
*/
function EmailFormSent( & $params )
{
$apply_rendering = $this->get_email_setting( 'email_apply_rendering' );
if( $this->is_renderer_enabled( $apply_rendering, $params['renderers'] ) )
{ // render code blocks in email:
$this->FilterItemContents( $params );
if( empty( $params['dont_remove_pre'] ) || !$params['dont_remove_pre'] )
{ // remove <pre>:
$params['content'] = preg_replace( '#(<\!--\s*codeblock[^-]*?\s*-->)<pre[^>]*><code>(.+?)</code></pre>(<\!--\s+/codeblock\s*-->)#is', '$1<code>$2</code>$3', $params['content'] );
}
}
}
function BeforeCommentFormInsert( & $params )
{
$Comment = & $params['Comment'];
$comment_Item = & $Comment->get_Item();
$item_Blog = & $comment_Item->get_Blog();
if( $this->get_coll_setting( 'coll_apply_comment_rendering', $item_Blog ) )
{ // render code blocks in comment
// add <pre> back in so highlighting is done, will be removed by highlighter
$params['Comment']->content = preg_replace( '#(<\!--\s*codeblock[^-]*?\s*-->)<code>(.+?)</code>(<\!--\s+/codeblock\s*-->)#is', '$1<pre class="codeblock"><code>$2</code></pre>$3', $params['Comment']->content );
}
}
/**
* Perform rendering
*
* @see Plugin::RenderItemAsHtml()
*/
function RenderItemAsHtml( & $params )
{
$content = & $params['data'];
// 2 - attribs : lang &| line
// 4 - codeblock
$content = preg_replace_callback( '#(\<p>)?\<!--\s*codeblock([^-]*?)\s*-->(\</p>)?\<pre[^>]*><code>([\s\S]+?)</code>\</pre>(\<p>)?\<!--\s*/codeblock\s*-->(\</p>)?#i',
array( $this, 'render_codeblock_callback' ), $content );
if( strpos( $content, '\\/codespan' ) !== false || strpos( $content, '\\/codeblock' ) !== false )
{ // Replace [\/codeblock] or [\/codespan] to normal view
$content = preg_replace( '#([<\[])\\\/code(span|block)([>\]])#i', '$1/code$2$3', $content );
}
return true;
}
/**
* Perform rendering
*
* @see Plugin::RenderItemAsXml()
*
* Note : Do we actually want to do this? - yabs
*/
function RenderItemAsXml( & $params )
{
$this->RenderItemAsHtml( $params );
}
/**
* Tidys up a block of code ready for numbering
*
* @param string $block - the code to be tidied up
* @param string $line_seperator - the seperator between lines of code ( default \n )
* @return string - the tidied code
*/
function tidy_code_output( $block, $line_seperator = "\n" )
{
// lets split the block into individual lines
$code = explode( $line_seperator,
// after removing windows garbage
str_replace( "\r", '', $block ) );
// time to rock and roll ;)
$still_open = array(); // this holds all the spans that need closing and re-opening on the following code line
for( $i = 0; $i < count( $code ); $i++ )
{
// we need to note all opening spans
$spans =
// get rid of the first element, it's always empty
array_slice(
// split line at each opening span
explode( '<span class="',
// add any open spans back in
implode( '', $still_open )
.$code[$i] )
, 1 );
// pre_dump( $spans );
// reset still_open array
$still_open = array();
// $spans now contains a list of opening spans
for( $z = 0; $z < count( $spans ); $z++ )
{
// add the span to the still_open array
$still_open[] = '<span class="'.substr( $spans[$z], 0, strpos( $spans[$z], '"' ) ).'">';
// pre_dump( $still_open );
// count all closing spans and remove them from the open spans list
if( $closed = substr_count( $spans[$z], '</span>' ) )
$still_open = array_slice( $still_open, 0, $closed * -1 );
}
// lets rebuild the code line and close any remaining spans
$code[$i] = '<span class="'.implode( '<span class="', $spans ).str_repeat( '</span>', count( $still_open ) );
}
// lets stitch it all back together again
$cleaned = implode( "\n", $code );
// and get rid of any empty spans
while( preg_match( '#\<span[^>]+?>\</span>#', $cleaned ) )
$cleaned = preg_replace( '#\<span[^>]+?>\</span>#', '', $cleaned );
// pre_dump( $cleaned );
// return the cleaned up code
return $cleaned;
}
/**
* Formats code ready for the database
*
* @param array $block ( 2 - attributes, 3 - the code )
* @return string formatted code || empty
*/
function filter_codeblock_callback( $block )
{ // if code block exists then tidy everything up for the database, otherwise just remove the pointless tag
$attributes = str_replace( array( '"', '\'' ), '', html_entity_decode( $block[2] ) );
return ( empty( $block[3] ) || !trim( $block[3] ) ? '' : '<!-- codeblock'.$attributes.' --><pre class="codeblock"><code>'
.$block[3]
.'</code></pre><!-- /codeblock -->' );
}
/**
* Formats codeblock ready for editing
*
* @param array $block ( 1 - attributes, 2 - the code )
* @return string formatted code
*/
function format_to_edit( $block )
{
return '[codeblock'.$block[1].']'.$block[2].'[/codeblock]';
}
/**
* Formats codespan ready for editing
*
* @param array $span ( 1 - the code )
* @return string formatted code
*/
function format_span_to_edit( $span )
{
return '[codespan]'.$span[1].'[/codespan]';
}
/**
* Event handler: Called at the beginning of the skin's HTML HEAD section.
*
* Use this to add any HTML HEAD lines (like CSS styles or links to resource files (CSS, JavaScript, ..)).
*
* @param array Associative array of parameters
*/
function SkinBeginHtmlHead( & $params )
{
global $Collection, $Blog;
if( ! isset( $Blog ) || (
$this->get_coll_setting( 'coll_apply_rendering', $Blog ) == 'never' &&
$this->get_coll_setting( 'coll_apply_comment_rendering', $Blog ) == 'never' ) )
{ // Don't load css/js files when plugin is not enabled
return;
}
$this->require_css( 'amcode.css' );
}
/**
* Event handler: Called when ending the admin html head section.
*
* @param array Associative array of parameters
* @return boolean did we do something?
*/
function AdminEndHtmlHead( & $params )
{
$this->SkinBeginHtmlHead( $params );
}
/**
* Formats code ready for displaying
* With "SwipeFriendly" line numbers
*
* @todo fp> no table should be needed. Also since we have odd/even coloring, word wrapping may be ok.
* yabs > unfortunately the tables are required to make the odd/even colouring and swipeable numbers work :(
*
* an example :
* Danny uploaded a page to demo his colours of choice ( http://brendoman.com/dev/youtube.html )
* if you scroll down to RenderItemAsHtml() you'll see it has 4 problems
* 1) some lines wrap - but they wrap underneath the line number
* 2) some lines don't wrap so they force a browser scrollbar
* ( although a scrollable div will cure this)
* 3) the lines that don't wrap lose their background colour once they become longer than the browser width
* ( a scrollable div has the same problem )
* 4) If you try and copy/paste the code you also get the line numbers
* ( like every other code formatter that we've seen on the web that uses line numbers ... which is why most don't ;) )
*
* compare that to the same section of code using this plugin ( http://cvs.astonishme.co.uk/index.php/2007/04/01/a_demo )
*
* fp> almost all that can be fixed with proper CSS and will have the advantage of not adding extra space in front of the lines when copy/pasting. I'll work on it when I have time.
*
* yabs> The operative word in that sentance is "almost" ;) ... I've removed the trailing spaces for all but empty lines ( required to "prop them open" ) ... I'd forgotten all about them :p
*
* @param string the code block to be wrapped up
* @param string the attributes - currently only the starting line number
* @param string the code type ( code || php )
*
* @return string formatted code
*/
function do_numbering( $code, $offset = 0, $type = 'code' )
{
$temp = str_replace( array( ' ', ' ', "\t", '[x', '[/x' ), array( '  ', '  ', '  ', '[', '[/' ), $code );
$temp = explode( "\n", $temp );
$count = 0;
$output = '';
$odd_line = false;
foreach( $temp as $line )
{
$output .= '<tr class="amc_code_'.( ( $odd_line = !$odd_line ) ? 'odd' : 'even' ).'"><td class="amc_line">'
.$this->create_number( ++$count + $offset ).'</td><td><code class="codeblock">'.$line
// add an to empty lines to stop them "collapsing"
.( empty( $line ) ? ' ' : '' )
.'</code></td></tr>';//."\n"; yura: I commented this because Auto-P plugin creates the tags <p></p> from this symbol
}
// make "long" value a setting ? - yabs
return '<p class="codeblock_title">'.$this->languageCache[ $type ]->language_title.'</p><div class="codeblock codeblock_with_title amc_'.$type.' '.( $count < 26 ? 'amc_short' : 'amc_long' ).'"><table>'.$output.'</table></div>';
}
/**
* Creates the SwipeFriendly line numbers
*
* @param integer the line number to produce
* @return string the html for the line number
*/
function create_number( $num )
{ // part of Swipe 'n' Paste magic ;)
$result = '';
$count = 0;
while ( $num )
{
$result .= '<div class="amc'.( $num - ( floor( $num / 10 ) * 10 ) ).'">';
$num = floor( $num / 10 );
$count++;
}
$result .= str_repeat( '</div>', $count );
return $result;
}
/**
* Formats codeblock ready for displaying
* Each language is stored as a classfile
* This would allow new languages to be added more easily
* It would also allow Geshi to be used as the highlighter with no code changes ;)
*
* Replaces both (current) highlighter functions
*
* ..... still requires some more thought though :p
*
* @param array $block ( 2 - attributes, 4 - the code )
* @return string formatted code
*/
function render_codeblock_callback( $block )
{
// set the offset if present - default : 0
preg_match( '#line=("|\'?)([0-9]+?)(["\']?)$#', $block[2], $match );
$offset = ( empty( $match[2] ) ? 0 : $match[2] - 1 );
// set the language if present - default : code
preg_match( '#lang=("|\'?)([^\1]+?)([\s"\']+?)#', $block[2], $match );
$language = strtolower( ( empty( $match[2] ) ? 'code' : $match[2] ) );
if( $code = trim( $block[4] ) )
{ // we have a code block
// is the relevant language highlighter already cached?
if( empty( $this->languageCache[ $language ] ) )
{ // lets attempt to load the language
$language_file = dirname(__FILE__).'/highlighters/'.$language.'.highlighter.php';
if( is_file( $language_file ) )
{ // language class exists, lets load and cache an instance of it
require_once $language_file;
$class = 'am_'.$language.'_highlighter';
$this->languageCache[ $language ] = new $class( $this );
}
else
{ // language class doesn't exists, fallback to default highlighter
$language = 'code';
if( empty( $this->languageCache[ $language ] ) )
{ // lets attempt to load the default language
$language_file = dirname(__FILE__).'/highlighters/'.$language.'.highlighter.php';
if( is_file( $language_file ) )
{ // default lanugage exists
require_once $language_file;
$class = 'am_'.$language.'_highlighter';
// add the language to the cache
$this->languageCache[ $language ] = new $class( $this );
}
else
{ // if we hit this we might as well go to the pub ;)
// echo '***** error ***** no language or default language file is present';
return $code;
}
}
}
}
$this->languageCache[ $language ]->requested_language = $language;
$this->languageCache[ $language ]->strict_mode = $this->Settings->get( 'strict' );
$code = $this->languageCache[ $language ]->highlight_code( $code );
// add the line numbers
$code = $this->do_numbering( $code, $offset, $language );
}
return $code;
}
}
?>