-
Notifications
You must be signed in to change notification settings - Fork 44
/
classTextile.php
2509 lines (2068 loc) · 81.8 KB
/
classTextile.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
/**
* Example: get XHTML from a given Textile-markup string ($string)
*
* $textile = new Textile();
* echo $textile->textileThis($string);
*
*/
/*
_____________
T E X T I L E
A Humane Web Text Generator
Version 2.4.1
Copyright (c) 2003-2004, Dean Allen <[email protected]>
All rights reserved.
Thanks to Carlo Zottmann <[email protected]> for refactoring
Textile's procedural code into a class framework
Additions and fixes Copyright (c) 2006 Alex Shiels http://thresholdstate.com/
Additions and fixes Copyright (c) 2010 Stef Dawson http://stefdawson.com/
Additions and fixes Copyright (c) 2010-12 Netcarver http://github.com/netcarver
Additions and fixes Copyright (c) 2011 Jeff Soo http://ipsedixit.net
Additions and fixes Copyright (c) 2012 Robert Wetzlmayr http://wetzlmayr.com/
_____________
L I C E N S E
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name Textile nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
_________
U S A G E
Block modifier syntax:
Header: h(1-6).
Paragraphs beginning with 'hn. ' (where n is 1-6) are wrapped in header tags.
Example: h1. Header... -> <h1>Header...</h1>
Paragraph: p. (also applied by default)
Example: p. Text -> <p>Text</p>
Blockquote: bq.
Example: bq. Block quotation... -> <blockquote>Block quotation...</blockquote>
Blockquote with citation: bq.:http://citation.url
Example: bq.:http://textism.com/ Text...
-> <blockquote cite="http://textism.com">Text...</blockquote>
Footnote: fn(1-100).
Example: fn1. Footnote... -> <p id="fn1">Footnote...</p>
Numeric list: #, ##
Consecutive paragraphs beginning with # are wrapped in ordered list tags.
Example: <ol><li>ordered list</li></ol>
Bulleted list: *, **
Consecutive paragraphs beginning with * are wrapped in unordered list tags.
Example: <ul><li>unordered list</li></ul>
Definition list:
Terms ;, ;;
Definitions :, ::
Consecutive paragraphs beginning with ; or : are wrapped in definition list tags.
Example: <dl><dt>term</dt><dd>definition</dd></dl>
Redcloth-style Definition list:
- Term1 := Definition1
- Term2 := Extended
definition =:
Phrase modifier syntax:
_emphasis_ -> <em>emphasis</em>
__italic__ -> <i>italic</i>
*strong* -> <strong>strong</strong>
**bold** -> <b>bold</b>
??citation?? -> <cite>citation</cite>
-deleted text- -> <del>deleted</del>
+inserted text+ -> <ins>inserted</ins>
^superscript^ -> <sup>superscript</sup>
~subscript~ -> <sub>subscript</sub>
@code@ -> <code>computer code</code>
%(bob)span% -> <span class="bob">span</span>
==notextile== -> leave text alone (do not format)
"linktext":url -> <a href="url">linktext</a>
"linktext(title)":url -> <a href="url" title="title">linktext</a>
"$":url -> <a href="url">url</a>
"$(title)":url -> <a href="url" title="title">url</a>
!imageurl! -> <img src="imageurl" />
!imageurl(alt text)! -> <img src="imageurl" alt="alt text" />
!imageurl!:linkurl -> <a href="linkurl"><img src="imageurl" /></a>
ABC(Always Be Closing) -> <acronym title="Always Be Closing">ABC</acronym>
Linked Notes:
============
Allows the generation of an automated list of notes with links.
Linked notes are composed of three parts, a set of named _definitions_, a set of
_references_ to those definitions and one or more _placeholders_ indicating where
the consolidated list of notes is to be placed in your document.
Definitions.
-----------
Each note definition must occur in its own paragraph and should look like this...
note#mynotelabel. Your definition text here.
You are free to use whatever label you wish after the # as long as it is made up
of letters, numbers, colon(:) or dash(-).
References.
----------
Each note reference is marked in your text like this[#mynotelabel] and
it will be replaced with a superscript reference that links into the list of
note definitions.
List Placeholder(s).
-------------------
The note list can go anywhere in your document. You have to indicate where
like this...
notelist.
notelist can take attributes (class#id) like this: notelist(class#id).
By default, the note list will show each definition in the order that they
are referenced in the text by the _references_. It will show each definition with
a full list of backlinks to each reference. If you do not want this, you can choose
to override the backlinks like this...
notelist(class#id)!. Produces a list with no backlinks.
notelist(class#id)^. Produces a list with only the first backlink.
Should you wish to have a specific definition display backlinks differently to this
then you can override the backlink method by appending a link override to the
_definition_ you wish to customise.
note#label. Uses the citelist's setting for backlinks.
note#label!. Causes that definition to have no backlinks.
note#label^. Causes that definition to have one backlink (to the first ref.)
note#label*. Causes that definition to have all backlinks.
Any unreferenced notes will be left out of the list unless you explicitly state
you want them by adding a '+'. Like this...
notelist(class#id)!+. Giving a list of all notes without any backlinks.
You can mix and match the list backlink control and unreferenced links controls
but the backlink control (if any) must go first. Like so: notelist^+. , not
like this: notelist+^.
Example...
Scientists say[#lavader] the moon is small.
note#other. An unreferenced note.
note#lavader(myliclass). "Proof":url of a small moon.
notelist(myclass#myid)+.
Would output (the actual IDs used would be randomised)...
<p>Scientists say<sup><a href="#def_id_1" id="ref_id_1a">1</sup> the moon is small.</p>
<ol class="myclass" id="myid">
<li class="myliclass"><a href="#ref_id_1a"><sup>a</sup></a><span id="def_id_1"> </span><a href="url">Proof</a> of a small moon.</li>
<li>An unreferenced note.</li>
</ol>
The 'a b c' backlink characters can be altered too.
For example if you wanted the notes to have numeric backlinks starting from 1:
notelist:1.
Table syntax:
Simple tables:
|a|simple|table|row|
|And|Another|table|row|
|With an||empty|cell|
|=. My table caption goes here (NB. Table captions *must* be the first line of the table else treated as a center-aligned cell.)
|_. A|_. table|_. header|_.row|
|A|simple|table|row|
Tables with attributes:
table{border:1px solid black}. My table summary here
{background:#ddd;color:red}. |{}| | | |
To specify thead / tfoot / tbody groups, add one of these on its own line
above the row(s) you wish to wrap (you may specify attributes before the dot):
|^. # thead
|-. # tbody
|~. # tfoot
Column groups:
|:\3. 100|
Becomes:
<colgroup span="3" width="100"></colgroup>
You can omit either or both of the \N or width values. You may also
add cells after the colgroup definition to specify col elements with
span, width, or standard Textile attributes:
|:. 50|(firstcol). |\2. 250||300|
Becomes:
<colgroup width="50">
<col class="firstcol" />
<col span="2" width="250" />
<col />
<col width="300" />
</colgroup>
(Note that, per the HTML specification, you should not add span
to the colgroup if specifying col elements.)
Applying Attributes:
Most anywhere Textile code is used, attributes such as arbitrary css style,
css classes, and ids can be applied. The syntax is fairly consistent.
The following characters quickly alter the alignment of block elements:
< -> left align ex. p<. left-aligned para
> -> right align h3>. right-aligned header 3
= -> centred h4=. centred header 4
<> -> justified p<>. justified paragraph
These will change vertical alignment in table cells:
^ -> top ex. |^. top-aligned table cell|
- -> middle |-. middle aligned|
~ -> bottom |~. bottom aligned cell|
Plain (parentheses) inserted between block syntax and the closing dot-space
indicate classes and ids:
p(hector). paragraph -> <p class="hector">paragraph</p>
p(#fluid). paragraph -> <p id="fluid">paragraph</p>
(classes and ids can be combined)
p(hector#fluid). paragraph -> <p class="hector" id="fluid">paragraph</p>
Curly {brackets} insert arbitrary css style
p{line-height:18px}. paragraph -> <p style="line-height:18px">paragraph</p>
h3{color:red}. header 3 -> <h3 style="color:red">header 3</h3>
Square [brackets] insert language attributes
p[no]. paragraph -> <p lang="no">paragraph</p>
%[fr]phrase% -> <span lang="fr">phrase</span>
Usually Textile block element syntax requires a dot and space before the block
begins, but since lists don't, they can be styled just using braces
#{color:blue} one -> <ol style="color:blue">
# big <li>one</li>
# list <li>big</li>
<li>list</li>
</ol>
Using the span tag to style a phrase
It goes like this, %{color:red}the fourth the fifth%
-> It goes like this, <span style="color:red">the fourth the fifth</span>
Ordered List Start & Continuation:
You can control the start attribute of an ordered list like so;
#5 Item 5
# Item 6
You can resume numbering list items after some intervening anonymous block like so...
#_ Item 7
# Item 8
*/
/**
* Class to allow simple assignment to members of the internal data array
**/
class TextileBag
{
protected $data;
public function __construct($initial_data)
{
$this->data = (is_array($initial_data)) ? $initial_data : array();
}
/**
* Allows setting of an element in the $data array. eg...
*
* $bag->key(value);
*
* ...sets $bag's $data['key'] to $value provided $value is not empty.
* The set can be made forced by following $value with true...
*
* $bag->key(value, true);
*
* Would force the value into the data array even if it were empty.
**/
public function __call($k, $params)
{
$allow_empty = isset($params[1]) && is_bool($params[1]) ? $params[1] : false;
if ($allow_empty || '' != $params[0])
$this->data[$k] = $params[0];
return $this;
}
}
/**
* Class to allow contruction of HTML tags on conversion of an object to a string
*
* Example usage...
*
* $img = new TextileTag('img')->class('big blue')->src('images/elephant.jpg');
* echo $img;
**/
class TextileTag extends TextileBag
{
protected $tag;
protected $selfclose;
public function __construct($name, $attribs=array(), $selfclosing=true)
{
parent::__construct($attribs);
$this->tag = $name;
$this->selfclose = $selfclosing;
}
public function __toString() {
$attribs = '';
if (count($this->data)) {
ksort($this->data);
foreach ($this->data as $k=>$v)
$attribs .= " $k=\"$v\"";
}
if ($this->tag)
$o = '<' . $this->tag . $attribs . (($this->selfclose) ? " />" : '>');
else
$o = $attribs;
return $o;
}
}
class Textile
{
protected $hlgn;
protected $vlgn;
protected $clas;
protected $lnge;
protected $styl;
protected $cspn;
protected $rspn;
protected $a;
protected $s;
protected $c;
protected $pnct;
protected $rel;
protected $fn;
protected $shelf = array();
protected $restricted = false;
protected $noimage = false;
protected $lite = false;
protected $url_schemes = array();
protected $glyph_search = null;
protected $glyph_replace = null;
protected $rebuild_glyphs = true;
protected $relativeImagePrefix = '';
protected $max_span_depth = 5;
protected $ver = '2.4.1';
protected $doc_root;
protected $doctype;
protected $symbols;
/**
* Constructor for an instance of class Textile.
*
* @access public
* @param string $doctype The output document type to target
* @return void
**/
public function __construct($doctype = 'xhtml')
{
$doctype_whitelist = array(
'xhtml',
'html5',
);
$doctype = strtolower($doctype);
if (!in_array($doctype, $doctype_whitelist))
$this->doctype = 'xhtml';
else
$this->doctype = $doctype;
// Basic symbols used in textile glyph replacements. To override these, call
// setSymbol('symbol_name', 'new_string') before calling textileThis() or
// textileRestricted().
$this->symbols = array(
'quote_single_open' => '‘',
'quote_single_close' => '’',
'quote_double_open' => '“',
'quote_double_close' => '”',
'apostrophe' => '’',
'prime' => '′',
'prime_double' => '″',
'ellipsis' => '…',
'emdash' => '—',
'endash' => '–',
'dimension' => '×',
'trademark' => '™',
'registered' => '®',
'copyright' => '©',
'half' => '½',
'quarter' => '¼',
'threequarters' => '¾',
'degrees' => '°',
'plusminus' => '±',
'fn_ref_pattern' => '<sup{atts}>{marker}</sup>',
'fn_foot_pattern' => '<sup{atts}>{marker}</sup>',
'nl_ref_pattern' => '<sup{atts}>{marker}</sup>',
);
$this->hlgn = "(?:\<(?!>)|<>|>|<|(?<!<)\>|\<\>|\=|[()]+(?! ))";
$this->vlgn = "[\-^~]";
$this->clas = "(?:\([^)\n]+\))"; // Don't allow classes/ids/languages/styles to span across newlines if used in a dotall regex
$this->lnge = "(?:\[[^]\n]+\])";
$this->styl = "(?:\{[^}\n]+\})";
$this->cspn = "(?:\\\\\d+)";
$this->rspn = "(?:\/\d+)";
$this->a = "(?:$this->hlgn|$this->vlgn)*";
$this->s = "(?:$this->cspn|$this->rspn)*";
$this->c = "(?:$this->clas|$this->styl|$this->lnge|$this->hlgn)*";
$this->lc = "(?:$this->clas|$this->styl|$this->lnge)*";
$this->pnct = '[\!"#\$%&\'()\*\+,\-\./:;<=>\?@\[\\\]\^_`{\|}\~]';
$this->urlch = '[\w"$\-_.+!*\'(),";\/?:@=&%#{}|\\^~\[\]`]';
$this->syms = '¤§µ¶†‡•∗∴◊♠♣♥♦';
$pnc = '[[:punct:]]';
$this->mb = is_callable('mb_strlen');
$this->cmap = array(0x0080, 0xffff, 0, 0xffff);
$this->restricted_url_schemes = array('http','https','ftp','mailto');
$this->unrestricted_url_schemes = array('http','https','ftp','mailto','file','tel','callto','sftp');
if (@preg_match('/\pL/u', 'a')) {
$this->regex_snippets = array(
'acr' => '\p{Lu}\p{Nd}',
'abr' => '\p{Lu}',
'nab' => '\p{Ll}',
'wrd' => '(?:\p{L}|\p{M}|\p{N}|\p{Pc})',
'mod' => 'u', // Make sure to mark the unicode patterns as such, Some servers seem to need this.
'cur' => '\p{Sc}',
);
} else {
$this->regex_snippets = array(
'acr' => 'A-Z0-9',
'abr' => 'A-Z',
'nab' => 'a-z',
'wrd' => '\w',
'mod' => '',
'cur' => '',
);
}
extract($this->regex_snippets);
$this->urlch = '['.$wrd.'"$\-_.+!*\'(),";\/?:@=&%#{}|\\^~\[\]`]';
$this->span_tags = array(
'*' => 'strong',
'**' => 'b',
'??' => 'cite',
'_' => 'em',
'__' => 'i',
'-' => 'del',
'%' => 'span',
'+' => 'ins',
'~' => 'sub',
'^' => 'sup',
);
if (defined('DIRECTORY_SEPARATOR'))
$this->ds = constant('DIRECTORY_SEPARATOR');
else
$this->ds = '/';
$this->doc_root = @$_SERVER['DOCUMENT_ROOT'];
if (!$this->doc_root)
$this->doc_root = @$_SERVER['PATH_TRANSLATED']; // IIS
$this->doc_root = rtrim($this->doc_root, $this->ds).$this->ds;
}
/**
* Call this (if needed) post constructor call to redefine a substitution symbol to
* be used when parsing a textile document.
*
* @access public
* @param string $name Name of the symbol to assign a new value to.
* @param string $value New value for the symbol.
* @return object $this
**/
public function setSymbol($name, $value)
{
$this->symbols[$name] = $value;
$this->rebuild_glyphs = true;
return $this;
}
/**
* getSymbol() returns an array containing the symbol table or the value of the named symbol
*
* @access public
* @param string $name The name of the symbol to access or null if requesting the symbol table
* @return array|string The symbol table or the requested symbol
**/
public function getSymbol($name=null)
{
return ($name) ? @$this->symbols['name'] : $this->symbols;
}
/**
* Allows client systems to have textile convert relative image paths to
* absolute (or prefixed) paths.
*
* @access public
* @param string $prefix The string to prefix all relative image paths with
* @return object $this
**/
public function setRelativeImagePrefix($prefix='')
{
$this->relativeImagePrefix = $prefix;
return $this;
}
/**
* Returns the internal version of this instance of textile.
*
* @access public
* @return string Version
**/
public function getVersion()
{
return $this->ver;
}
/**
* Encodes the given text.
*
* @access public
* @param string $text The text to be encoded.
* @return string The encoded text.
**/
public function textileEncode($text)
{
$text = preg_replace("/&(?![#a-z0-9]+;)/i", "x%x%", $text);
$text = str_replace("x%x%", "&", $text);
return $text;
}
/**
* Causes an un-restricted parse of the input textile text to start.
*
* @access public
* @param string $text The input document in textile format
* @param string $lite Optional flag to switch the parser into lite mode.
* @param string $encode Optional flag that causes the unput document to be encoded and returned.
* @param string $noimage Optional flag controlling the conversion of images into HTML <img/> tags.
* @param string $strict Optional flag controlling the application of whitespace cleanup prior to parsing the text.
* @param string $rel Relationship to apply to all generated links.
* @return string The text from the input document
**/
public function textileThis($text, $lite = '', $encode = '', $noimage = '', $strict = '', $rel = '')
{
$this->prepare($lite, $noimage, $rel);
$this->url_schemes = $this->unrestricted_url_schemes;
if ($encode) // Use of the $encode flag is discouraged. Calling textileEncode() is prefered.
return $this->textileEncode($text);
if (!$strict)
$text = $this->cleanWhiteSpace($text);
return $this->textileCommon($text, $lite);
}
/**
* Causes a restricted parse of the input textile text. Use this on any untrusted user input.
*
* @access public
* @param string $text The input document in textile format
* @param string $lite Optional flag to switch the parser into lite mode. Lite mode is the default.
* @param string $noimage Optional flag controlling the conversion of images into HTML <img/> tags. noimage mode is the default.
* @param string $rel Relationship to apply to all generated links. 'nofollow' is the default
* @return string The text from the input document
**/
public function textileRestricted($text, $lite = 1, $noimage = 1, $rel = 'nofollow')
{
$this->prepare($lite, $noimage, $rel);
$this->url_schemes = $this->restricted_url_schemes;
$this->restricted = true;
// Escape any raw html
$text = $this->encodeHTML($text, 0);
$text = $this->cleanWhiteSpace($text);
return $this->textileCommon($text, $lite);
}
/**
* Perform common parse actions
*
* @internal
**/
protected function textileCommon($text, $lite)
{
if ($lite) {
$this->btag = array('bq', 'p');
$text = $this->block($text."\n\n");
} else {
$this->btag = array('bq', 'p', 'bc', 'notextile', 'pre', 'h[1-6]', 'fn\d+', '###');
$text = $this->block($text);
$text = $this->placeNoteLists($text);
}
$text = $this->retrieve($text);
$text = $this->replaceGlyphs($text);
$text = $this->retrieveTags($text);
$text = $this->retrieveURLs($text);
$text = str_replace("<br />", "<br />\n", $text);
return $text;
}
/**
* If needed, prepares the glyph find-and-replace patterns from the internal symbol table
*
* @internal
* @return void
**/
protected function prepGlyphs()
{
if ((null!==$this->glyph_search) && (null!==$this->glyph_replace) && !$this->rebuild_glyphs)
return;
extract($this->symbols, EXTR_PREFIX_ALL, 'txt');
extract($this->regex_snippets );
$pnc = '[[:punct:]]';
if ($cur)
$cur = '(?:['.$cur.']\s*)?';
$this->glyph_search = array(
'/([0-9]+[\])]?[\'"]? ?)[xX]( ?[\[(]?)(?=[+-]?'.$cur.'[0-9]*\.?[0-9]+)/'.$mod, // Dimension sign
'/('.$wrd.'|\))\'('.$wrd.')/'.$mod, // I'm an apostrophe
'/(\s)\'(\d+'.$wrd.'?)\b(?![.]?['.$wrd.']*?\')/'.$mod, // Back in '88/the '90s but not in his '90s', '1', '1.' '10m' or '5.png'
"/([([{])'(?=\S)/", // Single open following open bracket
'/(\S)\'(?=\s|'.$pnc.'|<|$)/', // Single closing
"/'/", // Default single opening
'/([([{])"(?=\S)/', // Double open following an open bracket. Allows things like Hello ["(Mum) & dad"]
'/(\S)"(?=\s|'.$pnc.'|<|$)/', // Double closing
'/"/', // Default double opening
'/\b(['.$abr.']['.$acr.']{2,})\b(?:[(]([^)]*)[)])/'.$mod, // 3+ uppercase acronym
'/(?<=\s|^|[>(;-])(['.$abr.']{3,})(['.$nab.']*)(?=\s|'.$pnc.'|<|$)(?=[^">]*?(<|$))/'.$mod, // 3+ uppercase
'/([^.]?)\.{3}/', // Ellipsis
'/--/', // em dash
'/ - /', // en dash
'/(\b ?|\s|^)[([]TM[])]/i', // Trademark
'/(\b ?|\s|^)[([]R[])]/i', // Registered
'/(\b ?|\s|^)[([]C[])]/i', // Copyright
'/[([]1\/4[])]/', // 1/4
'/[([]1\/2[])]/', // 1/2
'/[([]3\/4[])]/', // 3/4
'/[([]o[])]/', // Degrees -- that's a small 'oh'
'/[([]\+\/-[])]/', // Plus minus
);
$this->glyph_replace = array(
'$1'.$txt_dimension.'$2', // Dimension sign
'$1'.$txt_apostrophe.'$2', // I'm an apostrophe
'$1'.$txt_apostrophe.'$2', // Back in '88
'$1'.$txt_quote_single_open, // Single open following open bracket
'$1'.$txt_quote_single_close, // Single closing
$txt_quote_single_open, // Default single opening
'$1'.$txt_quote_double_open, // Double open following open bracket
'$1'.$txt_quote_double_close, // Double closing
$txt_quote_double_open, // Default double opening
(('html5' === $this->doctype) ? '<abbr title="$2">$1</abbr>' : '<acronym title="$2">$1</acronym>'), // 3+ uppercase acronym
'<span class="caps">glyph:$1</span>$2', // 3+ uppercase
'$1'.$txt_ellipsis, // Ellipsis
$txt_emdash, // em dash
' '.$txt_endash.' ', // en dash
'$1'.$txt_trademark, // Trademark
'$1'.$txt_registered, // Registered
'$1'.$txt_copyright, // Copyright
$txt_quarter, // 1/4
$txt_half, // 1/2
$txt_threequarters, // 3/4
$txt_degrees, // Degrees
$txt_plusminus, // Plus minus
);
$this->rebuild_glyphs = false; // No need to rebuild next run unless a symbol is redefined
}
/**
* Prepares the transient internal state of the textile parser in preparation for
* parsing a new document.
*
* @internal
*
* @param bool|string $lite Set to true/non-empty to parse in lite mode. Default ''.
* @param bool|string $noimage Disallow images in the generated docuemnt
* @param string $rel A relationship to be applied to all links. eg. 'nofollow'
* @return void
**/
protected function prepare($lite, $noimage, $rel)
{
$this->unreferencedNotes = array();
$this->notelist_cache = array();
$this->notes = array();
$this->urlshelf = array();
$this->urlrefs = array();
$this->shelf = array();
$this->fn = array();
$this->span_depth = 0;
$this->tag_index = 1;
$this->note_index = 1;
$this->rel = ($rel) ? ' rel="'.$rel.'"' : '';
$this->lite = $lite;
$this->noimage = $noimage;
$this->prepGlyphs();
}
/**
* @internal
**/
protected function cleanAttribs($in)
{
$tmp = $in;
$before = -1;
$after = 0;
$max = 3;
$i = 0;
while (($after != $before) && ($i < $max))
{
$before = strlen($tmp);
$tmp = rawurldecode($tmp);
$after = strlen($tmp);
$i++;
}
if ($i === $max) // If we hit the max allowed decodes, assume the input is tainted and consume it.
$out = '';
else
$out = str_replace(array('"', "'", '='), '', $tmp);
return $out;
}
/**
* Helper method that creates a new instance of TextileTag
*
* @internal
*
* @param string $name The type of tag to create. eg. newTag('p',...) for a paragraph tag.
* @param $atts The textile attributes to apply to the tag
* @param bool $selfclosing Determines if the tag should be selfclosing. Default: true
* @return TextileTag
**/
protected function newTag($name, $atts, $selfclosing = true)
{
return new TextileTag($name, $atts, $selfclosing);
}
/**
* Parses textile attributes
*
* @internal
*
* @param string $in The textile attribute string to be parsed
* @param string $element Focus the routine to interpret the attributes as applying to a specific HTML tag
* @param int $include_id A value interpreted as a true when cast to bool allows ids to be included in the output
* @param string $autoclass An additional class or classes to be applied to the output
* @return array HTML attributes as key=>value mappings
**/
protected function parseAttribs($in, $element = "", $include_id = 1, $autoclass = '')
{
$out = '';
$o = $this->parseAttribsToArray($in, $element, $include_id, $autoclass);
ksort($o);
if (count($o))
foreach ($o as $k=>$v) $out .= " $k=\"$v\"";
return $out;
}
/**
* @internal
**/
protected function parseAttribsToArray($in, $element = "", $include_id = 1, $autoclass = '')
{
$style = '';
$class = '';
$lang = '';
$colspan = '';
$rowspan = '';
$span = '';
$width = '';
$id = '';
$atts = '';
$align = '';
$matched = $in;
if ($element == 'td') {
if (preg_match("/\\\\(\d+)/", $matched, $csp))
$colspan = $csp[1];
if (preg_match("/\/(\d+)/", $matched, $rsp))
$rowspan = $rsp[1];
}
if ($element == 'td' or $element == 'tr') {
if (preg_match("/($this->vlgn)/", $matched, $vert))
$style[] = "vertical-align:" . $this->vAlign($vert[1]);
}
if (preg_match("/\{([^}]*)\}/", $matched, $sty)) {
$style[] = rtrim($sty[1], ';');
$matched = str_replace($sty[0], '', $matched);
}
if (preg_match("/\[([^]]+)\]/U", $matched, $lng)) {
$matched = str_replace($lng[0], '', $matched); // Consume entire lang block -- valid or invalid...
if (preg_match("/\[([a-zA-Z]{2}(?:[\-\_][a-zA-Z]{2})?)\]/U", $lng[0], $lng)) {
$lang = $lng[1];
}
}
if (preg_match("/\(([^()]+)\)/U", $matched, $cls)) {
$matched = str_replace($cls[0], '', $matched); // Consume entire class block -- valid or invalid...
// Only allow a restricted subset of the CSS standard characters for classes/ids. No encoding markers allowed...
if (preg_match("/\(([-a-zA-Z 0-9_\.\:\#]+)\)/U", $cls[0], $cls)) {
$hashpos = strpos($cls[1], '#');
// If a textile class block attribute was found with a '#' in it
// split it into the css class and css id...
if (false !== $hashpos) {
if (preg_match("/#([-a-zA-Z0-9_\.\:]*)$/", substr($cls[1], $hashpos), $ids))
$id = $ids[1];
if (preg_match("/^([-a-zA-Z 0-9_]*)/", substr($cls[1], 0, $hashpos), $ids))
$class = $ids[1];
}
else {
if (preg_match("/^([-a-zA-Z 0-9_]*)$/", $cls[1], $ids))
$class = $ids[1];
}
}
}
if (preg_match("/([(]+)/", $matched, $pl)) {
$style[] = "padding-left:" . strlen($pl[1]) . "em";
$matched = str_replace($pl[0], '', $matched);
}
if (preg_match("/([)]+)/", $matched, $pr)) {
$style[] = "padding-right:" . strlen($pr[1]) . "em";
$matched = str_replace($pr[0], '', $matched);
}
if (preg_match("/($this->hlgn)/", $matched, $horiz))
$style[] = "text-align:" . $this->hAlign($horiz[1]);
if ($element == 'col') {
if (preg_match("/(?:\\\\(\d+))?\s*(\d+)?/", $matched, $csp)) {
$span = isset($csp[1]) ? $csp[1] : '';
$width = isset($csp[2]) ? $csp[2] : '';
}
}
if ($this->restricted) {
$o = array();
$class = trim($autoclass);
if ($class)
$o['class'] = $this->cleanAttribs($class);
if ($lang)
$o['lang'] = $this->cleanAttribs($lang);
return $o;
}
else
$class = trim($class . ' ' . $autoclass);
$o = '';
if ($style) {
$tmps = array();
foreach ($style as $s) {
$parts = explode(';', $s);
foreach ($parts as $p)
$tmps[] = $p;
}
sort($tmps);
foreach ($tmps as $p) {
if (!empty($p))
$o .= $p.';';
}
$style = trim(str_replace(array("\n", ';;'), array('', ';'), $o));
}
$o = array();
if ($class) $o['class'] = $this->cleanAttribs($class);
if ($colspan) $o['colspan'] = $this->cleanAttribs($colspan);
if ($id && $include_id)
$o['id'] = $this->cleanAttribs($id);
if ($lang) $o['lang'] = $this->cleanAttribs($lang);
if ($rowspan) $o['rowspan'] = $this->cleanAttribs($rowspan);
if ($span) $o['span'] = $this->cleanAttribs($span);
if ($style) $o['style'] = $this->cleanAttribs($style);