PageRenderTime 29ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/classTextile.php

http://github.com/netcarver/textile
PHP | 2056 lines | 1518 code | 143 blank | 395 comment | 112 complexity | f9771858394073d856362ef34e832144 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Example: get XHTML from a given Textile-markup string ($string)
  4. *
  5. * $textile = new Textile;
  6. * echo $textile->TextileThis($string);
  7. */
  8. /*
  9. _____________
  10. T E X T I L E
  11. A Humane Web Text Generator
  12. Version 2.4.0
  13. Copyright (c) 2003-2004, Dean Allen <dean@textism.com>
  14. All rights reserved.
  15. Thanks to Carlo Zottmann <carlo@g-blog.net> for refactoring
  16. Textile's procedural code into a class framework
  17. Additions and fixes Copyright (c) 2006 Alex Shiels http://thresholdstate.com/
  18. Additions and fixes Copyright (c) 2010 Stef Dawson http://stefdawson.com/
  19. Additions and fixes Copyright (c) 2010-12 Netcarver http://github.com/netcarver
  20. Additions and fixes Copyright (c) 2011 Jeff Soo http://ipsedixit.net
  21. Additions and fixes Copyright (c) 2012 Robert Wetzlmayr http://wetzlmayr.com/
  22. _____________
  23. L I C E N S E
  24. Redistribution and use in source and binary forms, with or without
  25. modification, are permitted provided that the following conditions are met:
  26. * Redistributions of source code must retain the above copyright notice,
  27. this list of conditions and the following disclaimer.
  28. * Redistributions in binary form must reproduce the above copyright notice,
  29. this list of conditions and the following disclaimer in the documentation
  30. and/or other materials provided with the distribution.
  31. * Neither the name Textile nor the names of its contributors may be used to
  32. endorse or promote products derived from this software without specific
  33. prior written permission.
  34. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  35. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  36. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  37. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  38. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  39. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  40. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  41. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  42. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  44. POSSIBILITY OF SUCH DAMAGE.
  45. _________
  46. U S A G E
  47. Block modifier syntax:
  48. Header: h(1-6).
  49. Paragraphs beginning with 'hn. ' (where n is 1-6) are wrapped in header tags.
  50. Example: h1. Header... -> <h1>Header...</h1>
  51. Paragraph: p. (also applied by default)
  52. Example: p. Text -> <p>Text</p>
  53. Blockquote: bq.
  54. Example: bq. Block quotation... -> <blockquote>Block quotation...</blockquote>
  55. Blockquote with citation: bq.:http://citation.url
  56. Example: bq.:http://textism.com/ Text...
  57. -> <blockquote cite="http://textism.com">Text...</blockquote>
  58. Footnote: fn(1-100).
  59. Example: fn1. Footnote... -> <p id="fn1">Footnote...</p>
  60. Numeric list: #, ##
  61. Consecutive paragraphs beginning with # are wrapped in ordered list tags.
  62. Example: <ol><li>ordered list</li></ol>
  63. Bulleted list: *, **
  64. Consecutive paragraphs beginning with * are wrapped in unordered list tags.
  65. Example: <ul><li>unordered list</li></ul>
  66. Definition list:
  67. Terms ;, ;;
  68. Definitions :, ::
  69. Consecutive paragraphs beginning with ; or : are wrapped in definition list tags.
  70. Example: <dl><dt>term</dt><dd>definition</dd></dl>
  71. Redcloth-style Definition list:
  72. - Term1 := Definition1
  73. - Term2 := Extended
  74. definition =:
  75. Phrase modifier syntax:
  76. _emphasis_ -> <em>emphasis</em>
  77. __italic__ -> <i>italic</i>
  78. *strong* -> <strong>strong</strong>
  79. **bold** -> <b>bold</b>
  80. ??citation?? -> <cite>citation</cite>
  81. -deleted text- -> <del>deleted</del>
  82. +inserted text+ -> <ins>inserted</ins>
  83. ^superscript^ -> <sup>superscript</sup>
  84. ~subscript~ -> <sub>subscript</sub>
  85. @code@ -> <code>computer code</code>
  86. %(bob)span% -> <span class="bob">span</span>
  87. ==notextile== -> leave text alone (do not format)
  88. "linktext":url -> <a href="url">linktext</a>
  89. "linktext(title)":url -> <a href="url" title="title">linktext</a>
  90. "$":url -> <a href="url">url</a>
  91. "$(title)":url -> <a href="url" title="title">url</a>
  92. !imageurl! -> <img src="imageurl" />
  93. !imageurl(alt text)! -> <img src="imageurl" alt="alt text" />
  94. !imageurl!:linkurl -> <a href="linkurl"><img src="imageurl" /></a>
  95. ABC(Always Be Closing) -> <acronym title="Always Be Closing">ABC</acronym>
  96. Linked Notes:
  97. ============
  98. Allows the generation of an automated list of notes with links.
  99. Linked notes are composed of three parts, a set of named _definitions_, a set of
  100. _references_ to those definitions and one or more _placeholders_ indicating where
  101. the consolidated list of notes is to be placed in your document.
  102. Definitions.
  103. -----------
  104. Each note definition must occur in its own paragraph and should look like this...
  105. note#mynotelabel. Your definition text here.
  106. You are free to use whatever label you wish after the # as long as it is made up
  107. of letters, numbers, colon(:) or dash(-).
  108. References.
  109. ----------
  110. Each note reference is marked in your text like this[#mynotelabel] and
  111. it will be replaced with a superscript reference that links into the list of
  112. note definitions.
  113. List Placeholder(s).
  114. -------------------
  115. The note list can go anywhere in your document. You have to indicate where
  116. like this...
  117. notelist.
  118. notelist can take attributes (class#id) like this: notelist(class#id).
  119. By default, the note list will show each definition in the order that they
  120. are referenced in the text by the _references_. It will show each definition with
  121. a full list of backlinks to each reference. If you do not want this, you can choose
  122. to override the backlinks like this...
  123. notelist(class#id)!. Produces a list with no backlinks.
  124. notelist(class#id)^. Produces a list with only the first backlink.
  125. Should you wish to have a specific definition display backlinks differently to this
  126. then you can override the backlink method by appending a link override to the
  127. _definition_ you wish to customise.
  128. note#label. Uses the citelist's setting for backlinks.
  129. note#label!. Causes that definition to have no backlinks.
  130. note#label^. Causes that definition to have one backlink (to the first ref.)
  131. note#label*. Causes that definition to have all backlinks.
  132. Any unreferenced notes will be left out of the list unless you explicitly state
  133. you want them by adding a '+'. Like this...
  134. notelist(class#id)!+. Giving a list of all notes without any backlinks.
  135. You can mix and match the list backlink control and unreferenced links controls
  136. but the backlink control (if any) must go first. Like so: notelist^+. , not
  137. like this: notelist+^.
  138. Example...
  139. Scientists say[#lavader] the moon is small.
  140. note#other. An unreferenced note.
  141. note#lavader(myliclass). "Proof":url of a small moon.
  142. notelist(myclass#myid)+.
  143. Would output (the actual IDs used would be randomised)...
  144. <p>Scientists say<sup><a href="#def_id_1" id="ref_id_1a">1</sup> the moon is small.</p>
  145. <ol class="myclass" id="myid">
  146. <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>
  147. <li>An unreferenced note.</li>
  148. </ol>
  149. The 'a b c' backlink characters can be altered too.
  150. For example if you wanted the notes to have numeric backlinks starting from 1:
  151. notelist:1.
  152. Table syntax:
  153. Simple tables:
  154. |a|simple|table|row|
  155. |And|Another|table|row|
  156. |With an||empty|cell|
  157. |=. My table caption goes here
  158. |_. A|_. table|_. header|_.row|
  159. |A|simple|table|row|
  160. Tables with attributes:
  161. table{border:1px solid black}. My table summary here
  162. {background:#ddd;color:red}. |{}| | | |
  163. To specify thead / tfoot / tbody groups, add one of these on its own line
  164. above the row(s) you wish to wrap (you may specify attributes before the dot):
  165. |^. # thead
  166. |-. # tbody
  167. |~. # tfoot
  168. Column groups:
  169. |:\3. 100|
  170. Becomes:
  171. <colgroup span="3" width="100"></colgroup>
  172. You can omit either or both of the \N or width values. You may also
  173. add cells after the colgroup definition to specify col elements with
  174. span, width, or standard Textile attributes:
  175. |:. 50|(firstcol). |\2. 250||300|
  176. Becomes:
  177. <colgroup width="50">
  178. <col class="firstcol" />
  179. <col span="2" width="250" />
  180. <col />
  181. <col width="300" />
  182. </colgroup>
  183. (Note that, per the HTML specification, you should not add span
  184. to the colgroup if specifying col elements.)
  185. Applying Attributes:
  186. Most anywhere Textile code is used, attributes such as arbitrary css style,
  187. css classes, and ids can be applied. The syntax is fairly consistent.
  188. The following characters quickly alter the alignment of block elements:
  189. < -> left align ex. p<. left-aligned para
  190. > -> right align h3>. right-aligned header 3
  191. = -> centred h4=. centred header 4
  192. <> -> justified p<>. justified paragraph
  193. These will change vertical alignment in table cells:
  194. ^ -> top ex. |^. top-aligned table cell|
  195. - -> middle |-. middle aligned|
  196. ~ -> bottom |~. bottom aligned cell|
  197. Plain (parentheses) inserted between block syntax and the closing dot-space
  198. indicate classes and ids:
  199. p(hector). paragraph -> <p class="hector">paragraph</p>
  200. p(#fluid). paragraph -> <p id="fluid">paragraph</p>
  201. (classes and ids can be combined)
  202. p(hector#fluid). paragraph -> <p class="hector" id="fluid">paragraph</p>
  203. Curly {brackets} insert arbitrary css style
  204. p{line-height:18px}. paragraph -> <p style="line-height:18px">paragraph</p>
  205. h3{color:red}. header 3 -> <h3 style="color:red">header 3</h3>
  206. Square [brackets] insert language attributes
  207. p[no]. paragraph -> <p lang="no">paragraph</p>
  208. %[fr]phrase% -> <span lang="fr">phrase</span>
  209. Usually Textile block element syntax requires a dot and space before the block
  210. begins, but since lists don't, they can be styled just using braces
  211. #{color:blue} one -> <ol style="color:blue">
  212. # big <li>one</li>
  213. # list <li>big</li>
  214. <li>list</li>
  215. </ol>
  216. Using the span tag to style a phrase
  217. It goes like this, %{color:red}the fourth the fifth%
  218. -> It goes like this, <span style="color:red">the fourth the fifth</span>
  219. Ordered List Start & Continuation:
  220. You can control the start attribute of an ordered list like so;
  221. #5 Item 5
  222. # Item 6
  223. You can resume numbering list items after some intervening anonymous block like so...
  224. #_ Item 7
  225. # Item 8
  226. */
  227. // define these before including this file to override the standard glyphs
  228. @define('txt_quote_single_open', '&#8216;');
  229. @define('txt_quote_single_close', '&#8217;');
  230. @define('txt_quote_double_open', '&#8220;');
  231. @define('txt_quote_double_close', '&#8221;');
  232. @define('txt_apostrophe', '&#8217;');
  233. @define('txt_prime', '&#8242;');
  234. @define('txt_prime_double', '&#8243;');
  235. @define('txt_ellipsis', '&#8230;');
  236. @define('txt_emdash', '&#8212;');
  237. @define('txt_endash', '&#8211;');
  238. @define('txt_dimension', '&#215;');
  239. @define('txt_trademark', '&#8482;');
  240. @define('txt_registered', '&#174;');
  241. @define('txt_copyright', '&#169;');
  242. @define('txt_half', '&#189;');
  243. @define('txt_quarter', '&#188;');
  244. @define('txt_threequarters', '&#190;');
  245. @define('txt_degrees', '&#176;');
  246. @define('txt_plusminus', '&#177;');
  247. @define('txt_has_unicode', @preg_match('/\pL/u', 'a')); // Detect if Unicode is compiled into PCRE
  248. @define('txt_fn_ref_pattern', '<sup{atts}>{marker}</sup>');
  249. @define('txt_fn_foot_pattern', '<sup{atts}>{marker}</sup>');
  250. @define('txt_nl_ref_pattern', '<sup{atts}>{marker}</sup>');
  251. class Textile
  252. {
  253. var $hlgn;
  254. var $vlgn;
  255. var $clas;
  256. var $lnge;
  257. var $styl;
  258. var $cspn;
  259. var $rspn;
  260. var $a;
  261. var $s;
  262. var $c;
  263. var $pnct;
  264. var $rel;
  265. var $fn;
  266. var $shelf = array();
  267. var $restricted = false;
  268. var $noimage = false;
  269. var $lite = false;
  270. var $url_schemes = array();
  271. var $glyph = array();
  272. var $hu = '';
  273. var $max_span_depth = 5;
  274. var $ver = '2.4.0';
  275. var $rev = '$Rev: 3359 $';
  276. var $doc_root;
  277. var $doctype;
  278. // -------------------------------------------------------------
  279. function Textile( $doctype = 'xhtml' )
  280. {
  281. $doctype_whitelist = array( # All lower case please...
  282. 'xhtml',
  283. 'html5',
  284. );
  285. $doctype = strtolower( $doctype );
  286. if( !in_array( $doctype, $doctype_whitelist ) )
  287. $this->doctype = 'xhtml';
  288. else
  289. $this->doctype = $doctype;
  290. $this->hlgn = "(?:\<(?!>)|(?<!<)\>|\<\>|\=|[()]+(?! ))";
  291. $this->vlgn = "[\-^~]";
  292. $this->clas = "(?:\([^)\n]+\))"; # Don't allow classes/ids/languages/styles to span across newlines
  293. $this->lnge = "(?:\[[^]\n]+\])";
  294. $this->styl = "(?:\{[^}\n]+\})";
  295. $this->cspn = "(?:\\\\\d+)";
  296. $this->rspn = "(?:\/\d+)";
  297. $this->a = "(?:{$this->hlgn}|{$this->vlgn})*";
  298. $this->s = "(?:{$this->cspn}|{$this->rspn})*";
  299. $this->c = "(?:{$this->clas}|{$this->styl}|{$this->lnge}|{$this->hlgn})*";
  300. $this->lc = "(?:{$this->clas}|{$this->styl}|{$this->lnge})*";
  301. $this->pnct = '[\!"#\$%&\'()\*\+,\-\./:;<=>\?@\[\\\]\^_`{\|}\~]';
  302. $this->urlch = '[\w"$\-_.+!*\'(),";\/?:@=&%#{}|\\^~\[\]`]';
  303. $this->syms = '¤§ľś†‡•???????';
  304. $pnc = '[[:punct:]]';
  305. $this->restricted_url_schemes = array('http','https','ftp','mailto');
  306. $this->unrestricted_url_schemes = array('http','https','ftp','mailto','file','tel','callto','sftp');
  307. $this->btag = array('bq', 'bc', 'notextile', 'pre', 'h[1-6]', 'fn\d+', 'p', '###' );
  308. if (txt_has_unicode) {
  309. $this->regex_snippets = array(
  310. 'acr' => '\p{Lu}\p{Nd}',
  311. 'abr' => '\p{Lu}',
  312. 'nab' => '\p{Ll}',
  313. 'wrd' => '(?:\p{L}|\p{M}|\p{N}|\p{Pc})',
  314. 'mod' => 'u', # Make sure to mark the unicode patterns as such, Some servers seem to need this.
  315. );
  316. } else {
  317. $this->regex_snippets = array(
  318. 'acr' => 'A-Z0-9',
  319. 'abr' => 'A-Z',
  320. 'nab' => 'a-z',
  321. 'wrd' => '\w',
  322. 'mod' => '',
  323. );
  324. }
  325. extract( $this->regex_snippets );
  326. $this->urlch = '['.$wrd.'"$\-_.+!*\'(),";\/?:@=&%#{}|\\^~\[\]`]';
  327. $this->glyph_search = array(
  328. '/('.$wrd.'|\))\'('.$wrd.')/'.$mod, // I'm an apostrophe
  329. '/(\s)\'(\d+'.$wrd.'?)\b(?![.]?['.$wrd.']*?\')/'.$mod, // back in '88/the '90s but not in his '90s', '1', '1.' '10m' or '5.png'
  330. '/(\S)\'(?=\s|'.$pnc.'|<|$)/', // single closing
  331. '/\'/', // single opening
  332. '/(\S)\"(?=\s|'.$pnc.'|<|$)/', // double closing
  333. '/"/', // double opening
  334. '/\b(['.$abr.']['.$acr.']{2,})\b(?:[(]([^)]*)[)])/'.$mod, // 3+ uppercase acronym
  335. '/(?<=\s|^|[>(;-])(['.$abr.']{3,})(['.$nab.']*)(?=\s|'.$pnc.'|<|$)(?=[^">]*?(<|$))/'.$mod, // 3+ uppercase
  336. '/([^.]?)\.{3}/', // ellipsis
  337. '/(\s?)--(\s?)/', // em dash
  338. '/( )-( )/', // en dash
  339. '/(\d+)( ?)x( ?)(?=\d+)/', // dimension sign
  340. '/(\b ?|\s|^)[([]TM[])]/i', // trademark
  341. '/(\b ?|\s|^)[([]R[])]/i', // registered
  342. '/(\b ?|\s|^)[([]C[])]/i', // copyright
  343. '/[([]1\/4[])]/', // 1/4
  344. '/[([]1\/2[])]/', // 1/2
  345. '/[([]3\/4[])]/', // 3/4
  346. '/[([]o[])]/', // degrees -- that's a small 'oh'
  347. '/[([]\+\/-[])]/', // plus minus
  348. );
  349. $this->glyph_replace = array(
  350. '$1'.txt_apostrophe.'$2', // I'm an apostrophe
  351. '$1'.txt_apostrophe.'$2', // back in '88
  352. '$1'.txt_quote_single_close, // single closing
  353. txt_quote_single_open, // single opening
  354. '$1'.txt_quote_double_close, // double closing
  355. txt_quote_double_open, // double opening
  356. (('html5' === $this->doctype) ? '<abbr title="$2">$1</abbr>' : '<acronym title="$2">$1</acronym>'), // 3+ uppercase acronym
  357. '<span class="caps">glyph:$1</span>$2', // 3+ uppercase
  358. '$1'.txt_ellipsis, // ellipsis
  359. '$1'.txt_emdash.'$2', // em dash
  360. '$1'.txt_endash.'$2', // en dash
  361. '$1$2'.txt_dimension.'$3', // dimension sign
  362. '$1'.txt_trademark, // trademark
  363. '$1'.txt_registered, // registered
  364. '$1'.txt_copyright, // copyright
  365. txt_quarter, // 1/4
  366. txt_half, // 1/2
  367. txt_threequarters, // 3/4
  368. txt_degrees, // degrees
  369. txt_plusminus, // plus minus
  370. );
  371. if (defined('hu'))
  372. $this->hu = hu;
  373. if (defined('DIRECTORY_SEPARATOR'))
  374. $this->ds = constant('DIRECTORY_SEPARATOR');
  375. else
  376. $this->ds = '/';
  377. $this->doc_root = @$_SERVER['DOCUMENT_ROOT'];
  378. if (!$this->doc_root)
  379. $this->doc_root = @$_SERVER['PATH_TRANSLATED']; // IIS
  380. $this->doc_root = rtrim($this->doc_root, $this->ds).$this->ds;
  381. }
  382. // -------------------------------------------------------------
  383. function TextileThis($text, $lite = '', $encode = '', $noimage = '', $strict = '', $rel = '')
  384. {
  385. $this->span_depth = 0;
  386. $this->tag_index = 1;
  387. $this->notes = $this->unreferencedNotes = $this->notelist_cache = array();
  388. $this->note_index = 1;
  389. $this->rel = ($rel) ? ' rel="'.$rel.'"' : '';
  390. $this->lite = $lite;
  391. $this->noimage = $noimage;
  392. $this->url_schemes = $this->unrestricted_url_schemes;
  393. if ($encode)
  394. {
  395. $text = $this->incomingEntities($text);
  396. $text = str_replace("x%x%", "&amp;", $text);
  397. return $text;
  398. } else {
  399. if(!$strict) {
  400. $text = $this->prePadLists($text);
  401. $text = $this->cleanWhiteSpace($text);
  402. }
  403. if(!$lite) {
  404. $text = $this->block($text);
  405. $text = $this->placeNoteLists($text);
  406. }
  407. $text = $this->retrieve($text);
  408. $text = $this->replaceGlyphs($text);
  409. $text = $this->retrieveTags($text);
  410. $text = $this->retrieveURLs($text);
  411. $this->span_depth = 0;
  412. // just to be tidy
  413. $text = str_replace("<br />", "<br />\n", $text);
  414. return $text;
  415. }
  416. }
  417. // -------------------------------------------------------------
  418. function TextileRestricted($text, $lite = 1, $noimage = 1, $rel = 'nofollow')
  419. {
  420. $this->restricted = true;
  421. $this->lite = $lite;
  422. $this->noimage = $noimage;
  423. $this->url_schemes = $this->restricted_url_schemes;
  424. $this->span_depth = 0;
  425. $this->tag_index = 1;
  426. $this->notes = $this->unreferencedNotes = $this->notelist_cache = array();
  427. $this->note_index = 1;
  428. $this->rel = ($rel) ? ' rel="'.$rel.'"' : '';
  429. // escape any raw html
  430. $text = $this->encode_html($text, 0);
  431. $text = $this->prePadLists($text);
  432. $text = $this->cleanWhiteSpace($text);
  433. if($lite) {
  434. $text = $this->blockLite($text);
  435. } else {
  436. $text = $this->block($text);
  437. $text = $this->placeNoteLists($text);
  438. }
  439. $text = $this->retrieve($text);
  440. $text = $this->replaceGlyphs($text);
  441. $text = $this->retrieveTags($text);
  442. $text = $this->retrieveURLs($text);
  443. $this->span_depth = 0;
  444. // just to be tidy
  445. $text = str_replace("<br />", "<br />\n", $text);
  446. return $text;
  447. }
  448. // -------------------------------------------------------------
  449. function cleanba( $in )
  450. {
  451. $tmp = $in;
  452. $before = -1;
  453. $after = 0;
  454. $max = 3;
  455. $i = 0;
  456. while( ($after != $before) && ($i < $max) )
  457. {
  458. $before = strlen( $tmp );
  459. $tmp = rawurldecode($tmp);
  460. $after = strlen( $tmp );
  461. $i++;
  462. }
  463. if( $i === $max ) # If we hit the max allowed decodes, assume the input is tainted and consume it.
  464. $out = '';
  465. else
  466. $out = strtr( $tmp, array(
  467. '"'=>'',
  468. "'"=>'',
  469. '='=>'',
  470. ));
  471. return $out;
  472. }
  473. // -------------------------------------------------------------
  474. function pba($in, $element = "", $include_id = 1, $autoclass = '') // "parse block attributes"
  475. {
  476. $style = '';
  477. $class = '';
  478. $lang = '';
  479. $colspan = '';
  480. $rowspan = '';
  481. $span = '';
  482. $width = '';
  483. $id = '';
  484. $atts = '';
  485. $align = '';
  486. $matched = $in;
  487. if ($element == 'td') {
  488. if (preg_match("/\\\\(\d+)/", $matched, $csp)) $colspan = $csp[1];
  489. if (preg_match("/\/(\d+)/", $matched, $rsp)) $rowspan = $rsp[1];
  490. }
  491. if ($element == 'td' or $element == 'tr') {
  492. if (preg_match("/($this->vlgn)/", $matched, $vert))
  493. $style[] = "vertical-align:" . $this->vAlign($vert[1]);
  494. }
  495. if (preg_match("/\{([^}]*)\}/", $matched, $sty)) {
  496. $style[] = rtrim($sty[1], ';');
  497. $matched = str_replace($sty[0], '', $matched);
  498. }
  499. if (preg_match("/\[([^]]+)\]/U", $matched, $lng)) {
  500. $matched = str_replace($lng[0], '', $matched); # Consume entire lang block -- valid or invalid...
  501. if (preg_match("/\[([a-zA-Z]{2}(?:[\-\_][a-zA-Z]{2})?)\]/U", $lng[0], $lng)) {
  502. $lang = $lng[1];
  503. }
  504. }
  505. if (preg_match("/\(([^()]+)\)/U", $matched, $cls)) {
  506. $matched = str_replace($cls[0], '', $matched); # Consume entire class block -- valid or invalid...
  507. # Only allow a restricted subset of the CSS standard characters for classes/ids. No encoding markers allowed...
  508. if (preg_match("/\(([-a-zA-Z 0-9_\.\:\#]+)\)/U", $cls[0], $cls)) {
  509. $hashpos = strpos( $cls[1], '#' );
  510. # If a textile class block attribute was found with a '#' in it
  511. # split it into the css class and css id...
  512. if( false !== $hashpos ) {
  513. if (preg_match("/#([-a-zA-Z0-9_\.\:]*)$/", substr( $cls[1], $hashpos ), $ids))
  514. $id = $ids[1];
  515. if (preg_match("/^([-a-zA-Z 0-9_]*)/", substr( $cls[1], 0, $hashpos ), $ids))
  516. $class = $ids[1];
  517. }
  518. else {
  519. if (preg_match("/^([-a-zA-Z 0-9_]*)$/", $cls[1], $ids))
  520. $class = $ids[1];
  521. }
  522. }
  523. }
  524. if (preg_match("/([(]+)/", $matched, $pl)) {
  525. $style[] = "padding-left:" . strlen($pl[1]) . "em";
  526. $matched = str_replace($pl[0], '', $matched);
  527. }
  528. if (preg_match("/([)]+)/", $matched, $pr)) {
  529. $style[] = "padding-right:" . strlen($pr[1]) . "em";
  530. $matched = str_replace($pr[0], '', $matched);
  531. }
  532. if (preg_match("/($this->hlgn)/", $matched, $horiz))
  533. $style[] = "text-align:" . $this->hAlign($horiz[1]);
  534. if ($element == 'col') {
  535. if (preg_match("/(?:\\\\(\d+))?\s*(\d+)?/", $matched, $csp)) {
  536. $span = isset($csp[1]) ? $csp[1] : '';
  537. $width = isset($csp[2]) ? $csp[2] : '';
  538. }
  539. }
  540. if ($this->restricted) {
  541. $class = trim( $autoclass );
  542. return join( '', array(
  543. ($lang) ? ' lang="' . $this->cleanba($lang) . '"': '',
  544. ($class) ? ' class="' . $this->cleanba($class) . '"': '',
  545. ));
  546. }
  547. else
  548. $class = trim( $class . ' ' . $autoclass );
  549. $o = '';
  550. if( $style ) {
  551. foreach($style as $s) {
  552. $parts = explode(';', $s);
  553. foreach( $parts as $p ) {
  554. $p = trim($p, '; ');
  555. if( !empty( $p ) )
  556. $o .= $p.'; ';
  557. }
  558. }
  559. $style = trim( strtr($o, array("\n"=>'',';;'=>';')) );
  560. }
  561. return join('',array(
  562. ($style) ? ' style="' . $this->cleanba($style) .'"' : '',
  563. ($class) ? ' class="' . $this->cleanba($class) .'"' : '',
  564. ($lang) ? ' lang="' . $this->cleanba($lang) .'"' : '',
  565. ($id and $include_id) ? ' id="' . $this->cleanba($id) .'"' : '',
  566. ($colspan) ? ' colspan="' . $this->cleanba($colspan) .'"' : '',
  567. ($rowspan) ? ' rowspan="' . $this->cleanba($rowspan) .'"' : '',
  568. ($span) ? ' span="' . $this->cleanba($span) .'"' : '',
  569. ($width) ? ' width="' . $this->cleanba($width) .'"' : '',
  570. ));
  571. }
  572. // -------------------------------------------------------------
  573. function hasRawText($text)
  574. {
  575. // checks whether the text has text not already enclosed by a block tag
  576. $r = trim(preg_replace('@<(p|blockquote|div|form|table|ul|ol|dl|pre|h\d)[^>]*?'.chr(62).'.*</\1>@s', '', trim($text)));
  577. $r = trim(preg_replace('@<(hr|br)[^>]*?/>@', '', $r));
  578. return '' != $r;
  579. }
  580. // -------------------------------------------------------------
  581. function table($text)
  582. {
  583. $text = $text . "\n\n";
  584. return preg_replace_callback("/^(?:table(_?{$this->s}{$this->a}{$this->c})\.(.*)?\n)?^({$this->a}{$this->c}\.? ?\|.*\|)[\s]*\n\n/smU",
  585. array(&$this, "fTable"), $text);
  586. }
  587. // -------------------------------------------------------------
  588. function fTable($matches)
  589. {
  590. $tatts = $this->pba($matches[1], 'table');
  591. $sum = trim($matches[2]) ? ' summary="'.htmlspecialchars(trim($matches[2])).'"' : '';
  592. $cap = '';
  593. $colgrp = $last_rgrp = '';
  594. $c_row = 1;
  595. foreach(preg_split("/\|\s*?$/m", $matches[3], -1, PREG_SPLIT_NO_EMPTY) as $row) {
  596. $row = ltrim($row);
  597. // Caption -- can only occur on row 1, otherwise treat '|=. foo |...' as a normal center-aligned cell.
  598. if ( ($c_row <= 1) && preg_match("/^\|\=($this->s$this->a$this->c)\. ([^\n]*)(.*)/s", ltrim($row), $cmtch)) {
  599. $capts = $this->pba($cmtch[1]);
  600. $cap = "\t<caption".$capts.">".trim($cmtch[2])."</caption>\n";
  601. $row = ltrim($cmtch[3]);
  602. if( empty($row) )
  603. continue;
  604. }
  605. $c_row += 1;
  606. // Colgroup
  607. if (preg_match("/^\|:($this->s$this->a$this->c\. .*)/m", ltrim($row), $gmtch)) {
  608. $nl = strpos($row,"\n"); # Is this colgroup def missing a closing pipe? If so, there will be a newline in the middle of $row somewhere.
  609. $idx=0;
  610. foreach (explode('|', str_replace('.', '', $gmtch[1])) as $col) {
  611. $gatts = $this->pba(trim($col), 'col');
  612. $colgrp .= "\t<col".(($idx==0) ? "group".$gatts.">" : $gatts." />")."\n";
  613. $idx++;
  614. }
  615. $colgrp .= "\t</colgroup>\n";
  616. if($nl === false) {
  617. continue;
  618. }
  619. else {
  620. $row = ltrim(substr( $row, $nl )); # Recover from our missing pipe and process the rest of the line...
  621. }
  622. }
  623. preg_match("/(:?^\|($this->vlgn)($this->s$this->a$this->c)\.\s*$\n)?^(.*)/sm", ltrim($row), $grpmatch);
  624. // Row group
  625. $rgrp = isset($grpmatch[2]) ? (($grpmatch[2] == '^') ? 'head' : ( ($grpmatch[2] == '~') ? 'foot' : (($grpmatch[2] == '-') ? 'body' : '' ) ) ) : '';
  626. $rgrpatts = isset($grpmatch[3]) ? $this->pba($grpmatch[3]) : '';
  627. $row = $grpmatch[4];
  628. if (preg_match("/^($this->a$this->c\. )(.*)/m", ltrim($row), $rmtch)) {
  629. $ratts = $this->pba($rmtch[1], 'tr');
  630. $row = $rmtch[2];
  631. } else $ratts = '';
  632. $cells = array();
  633. $cellctr = 0;
  634. $row = strtr( $row, array( "\n" => '<br />' ) );
  635. foreach(explode("|", $row) as $cell) {
  636. $ctyp = "d";
  637. if (preg_match("/^_/", $cell)) $ctyp = "h";
  638. if (preg_match("/^(_?$this->s$this->a$this->c\. )(.*)/", $cell, $cmtch)) {
  639. $catts = $this->pba($cmtch[1], 'td');
  640. $cell = $cmtch[2];
  641. } else $catts = '';
  642. $cell = $this->graf($cell);
  643. if ($cellctr>0) // Ignore first 'cell': it precedes the opening pipe
  644. $cells[] = $this->doTagBr("t$ctyp", "\t\t\t<t$ctyp$catts>$cell</t$ctyp>");
  645. $cellctr++;
  646. }
  647. $grp = (($rgrp && $last_rgrp) ? "\t</t".$last_rgrp.">\n" : '') . (($rgrp) ? "\t<t".$rgrp.$rgrpatts.">\n" : '');
  648. $last_rgrp = ($rgrp) ? $rgrp : $last_rgrp;
  649. $rows[] = $grp."\t\t<tr$ratts>\n" . join("\n", $cells) . ($cells ? "\n" : "") . "\t\t</tr>";
  650. unset($cells, $catts);
  651. }
  652. return "\t<table{$tatts}{$sum}>\n" .$cap. $colgrp. join("\n", $rows) . "\n".(($last_rgrp) ? "\t</t".$last_rgrp.">\n" : '')."\t</table>\n\n";
  653. }
  654. // -------------------------------------------------------------
  655. function redcloth_lists($text)
  656. {
  657. return preg_replace_callback("/^([-]+$this->lc[ .].*:=.*)$(?![^-])/smU", array(&$this, "fRCList"), $text);
  658. }
  659. // -------------------------------------------------------------
  660. function fRCList($m)
  661. {
  662. $out = array();
  663. $text = preg_split('/\n(?=[-])/m', $m[0]);
  664. foreach($text as $nr => $line) {
  665. if (preg_match("/^[-]+($this->lc)[ .](.*)$/s", $line, $m)) {
  666. list(, $atts, $content) = $m;
  667. $content = trim($content);
  668. $atts = $this->pba($atts);
  669. preg_match( "/^(.*?)[\s]*:=(.*?)[\s]*(=:|:=)?[\s]*$/s", $content, $xm );
  670. list( , $term, $def, ) = $xm;
  671. $term = trim( $term );
  672. $def = trim( $def, ' ' );
  673. if( empty( $out ) ) {
  674. if(''==$def)
  675. $out[] = "<dl$atts>";
  676. else
  677. $out[] = '<dl>';
  678. }
  679. if( '' != $def && '' != $term )
  680. {
  681. $pos = strpos( $def, "\n" );
  682. $def = str_replace( "\n", "<br />", trim($def) );
  683. if( 0 === $pos )
  684. $def = '<p>' . $def . '</p>';
  685. $term = $this->graf($term);
  686. $def = $this->graf($def);
  687. $out[] = "\t<dt$atts>$term</dt>";
  688. $out[] = "\t<dd>$def</dd>";
  689. }
  690. }
  691. }
  692. $out[] = '</dl>';
  693. return implode("\n", $out);
  694. }
  695. // -------------------------------------------------------------
  696. function prePadLists($text)
  697. {
  698. $list_item = "[#*;:]+(?:_|[\d]+)?$this->lc[ .].*\n";
  699. $non_blank_lines = ".+\n";
  700. $text = preg_replace_callback(
  701. "/^(?:$list_item)(?:$non_blank_lines)*\n/m",
  702. array(&$this, "fPrePadLists"),
  703. $text."\n\n"
  704. );
  705. return $text;
  706. }
  707. // -------------------------------------------------------------
  708. function fPrePadLists($m)
  709. {
  710. return "\n".$m[0];
  711. }
  712. // -------------------------------------------------------------
  713. function lists($text)
  714. {
  715. return preg_replace_callback("/^([#*;:]+(?:_|[\d]+)?$this->lc[ .].*)$(?![^#*;:])/smU", array(&$this, "fList"), $text);
  716. }
  717. // -------------------------------------------------------------
  718. function fList($m)
  719. {
  720. $text = preg_split('/\n(?=[*#;:])/m', $m[0]);
  721. $pt = '';
  722. foreach($text as $nr => $line) {
  723. $nextline = isset($text[$nr+1]) ? $text[$nr+1] : false;
  724. if (preg_match("/^([#*;:]+)(_|[\d]+)?($this->lc)[ .](.*)$/s", $line, $m)) {
  725. list(, $tl, $st, $atts, $content) = $m;
  726. $content = trim($content);
  727. $nl = '';
  728. $ltype = $this->lT($tl);
  729. $litem = (strpos($tl, ';') !== false) ? 'dt' : ((strpos($tl, ':') !== false) ? 'dd' : 'li');
  730. $showitem = (strlen($content) > 0);
  731. if( 'o' === $ltype ) { // handle list continuation/start attribute on ordered lists...
  732. if( !isset($this->olstarts[$tl]) )
  733. $this->olstarts[$tl] = 1;
  734. if( strlen($tl) > strlen($pt) ) { // first line of this level of ol -- has a start attribute?
  735. if( '' == $st )
  736. $this->olstarts[$tl] = 1; // no => reset count to 1.
  737. elseif( '_' !== $st )
  738. $this->olstarts[$tl] = (int)$st; // yes, and numeric => reset to given.
  739. // TRICKY: the '_' continuation marker just means
  740. // output the count so don't need to do anything
  741. // here.
  742. }
  743. if( (strlen($tl) > strlen($pt)) && '' !== $st) // output the start attribute if needed...
  744. $st = ' start="' . $this->olstarts[$tl] . '"';
  745. if( $showitem ) // TRICKY: Only increment the count for list items; not when a list definition line is encountered.
  746. $this->olstarts[$tl] += 1;
  747. }
  748. if (preg_match("/^([#*;:]+)(_|[\d]+)?($this->lc)[ .].*/", $nextline, $nm))
  749. $nl = $nm[1];
  750. if ((strpos($pt, ';') !== false) && (strpos($tl, ':') !== false)) {
  751. $lists[$tl] = 2; // We're already in a <dl> so flag not to start another
  752. }
  753. $atts = $this->pba($atts);
  754. if (!isset($lists[$tl])) {
  755. $lists[$tl] = 1;
  756. $line = "\t<" . $ltype . "l$atts$st>" . (($showitem) ? "\n\t\t<$litem>" . $content : '');
  757. } else {
  758. $line = ($showitem) ? "\t\t<$litem$atts>" . $content : '';
  759. }
  760. if((strlen($nl) <= strlen($tl))) $line .= (($showitem) ? "</$litem>" : '');
  761. foreach(array_reverse($lists) as $k => $v) {
  762. if(strlen($k) > strlen($nl)) {
  763. $line .= ($v==2) ? '' : "\n\t</" . $this->lT($k) . "l>";
  764. if((strlen($k) > 1) && ($v != 2))
  765. $line .= "</".$litem.">";
  766. unset($lists[$k]);
  767. }
  768. }
  769. $pt = $tl; // Remember the current Textile tag
  770. }
  771. else {
  772. $line .= "\n";
  773. }
  774. $out[] = $line;
  775. }
  776. return $this->doTagBr($litem, join("\n", $out));
  777. }
  778. // -------------------------------------------------------------
  779. function lT($in)
  780. {
  781. return preg_match("/^#+/", $in) ? 'o' : ((preg_match("/^\*+/", $in)) ? 'u' : 'd');
  782. }
  783. // -------------------------------------------------------------
  784. function doTagBr($tag, $in)
  785. {
  786. return preg_replace_callback('@<('.preg_quote($tag).')([^>]*?)>(.*)(</\1>)@s', array(&$this, 'fBr'), $in);
  787. }
  788. // -------------------------------------------------------------
  789. function doPBr($in)
  790. {
  791. return preg_replace_callback('@<(p)([^>]*?)>(.*)(</\1>)@s', array(&$this, 'fPBr'), $in);
  792. }
  793. // -------------------------------------------------------------
  794. function fPBr($m)
  795. {
  796. # Less restrictive version of fBr() ... used only in paragraphs where the next
  797. # row may start with a smiley or perhaps something like '#8 bolt...' or '*** stars...'
  798. $content = preg_replace("@(.+)(?<!<br>|<br />)\n(?![\s|])@", '$1<br />', $m[3]);
  799. return '<'.$m[1].$m[2].'>'.$content.$m[4];
  800. }
  801. // -------------------------------------------------------------
  802. function fBr($m)
  803. {
  804. $content = preg_replace("@(.+)(?<!<br>|<br />)\n(?![#*;:\s|])@", '$1<br />', $m[3]);
  805. return '<'.$m[1].$m[2].'>'.$content.$m[4];
  806. }
  807. // -------------------------------------------------------------
  808. function block($text)
  809. {
  810. $find = $this->btag;
  811. $tre = join('|', $find);
  812. $text = explode("\n\n", $text);
  813. $tag = 'p';
  814. $atts = $cite = $graf = $ext = '';
  815. $eat = false;
  816. $out = array();
  817. foreach($text as $line) {
  818. $anon = 0;
  819. if (preg_match("/^($tre)($this->a$this->c)\.(\.?)(?::(\S+))? (.*)$/s", $line, $m)) {
  820. // last block was extended, so close it
  821. if ($ext)
  822. $out[count($out)-1] .= $c1;
  823. // new block
  824. list(,$tag,$atts,$ext,$cite,$graf) = $m;
  825. list($o1, $o2, $content, $c2, $c1, $eat) = $this->fBlock(array(0,$tag,$atts,$ext,$cite,$graf));
  826. // leave off c1 if this block is extended, we'll close it at the start of the next block
  827. if ($ext)
  828. $line = $o1.$o2.$content.$c2;
  829. else
  830. $line = $o1.$o2.$content.$c2.$c1;
  831. }
  832. else {
  833. // anonymous block
  834. $anon = 1;
  835. if ($ext or !preg_match('/^ /', $line)) {
  836. list($o1, $o2, $content, $c2, $c1, $eat) = $this->fBlock(array(0,$tag,$atts,$ext,$cite,$line));
  837. // skip $o1/$c1 because this is part of a continuing extended block
  838. if ($tag == 'p' and !$this->hasRawText($content)) {
  839. $line = $content;
  840. }
  841. else {
  842. $line = $o2.$content.$c2;
  843. }
  844. }
  845. else {
  846. $line = $this->graf($line);
  847. }
  848. }
  849. $line = $this->doPBr($line);
  850. $line = preg_replace('/<br>/', '<br />', $line);
  851. if ($ext and $anon)
  852. $out[count($out)-1] .= "\n".$line;
  853. elseif(!$eat)
  854. $out[] = $line;
  855. if (!$ext) {
  856. $tag = 'p';
  857. $atts = '';
  858. $cite = '';
  859. $graf = '';
  860. $eat = false;
  861. }
  862. }
  863. if ($ext) $out[count($out)-1] .= $c1;
  864. return join("\n\n", $out);
  865. }
  866. // -------------------------------------------------------------
  867. function formatFootnote( $marker, $atts='', $anchor=true )
  868. {
  869. $pattern = ($anchor) ? txt_fn_foot_pattern : txt_fn_ref_pattern;
  870. return $this->replaceMarkers( $pattern, array( 'atts' => $atts, 'marker' => $marker ) );
  871. }
  872. // -------------------------------------------------------------
  873. function replaceMarkers( $text, $replacements )
  874. {
  875. if( !empty( $replacements ) )
  876. foreach( $replacements as $k => $r )
  877. $text = str_replace( '{'.$k.'}', $r, $text );
  878. return $text;
  879. }
  880. // -------------------------------------------------------------
  881. function fBlock($m)
  882. {
  883. extract($this->regex_snippets);
  884. list(, $tag, $att, $ext, $cite, $content) = $m;
  885. $atts = $this->pba($att);
  886. $o1 = $o2 = $c2 = $c1 = '';
  887. $eat = false;
  888. if( $tag === 'p' ) {
  889. # Is this an anonymous block with a note definition?
  890. $notedef = preg_replace_callback("/
  891. ^note\# # start of note def marker
  892. ([^%<*!@#^([{ \s.]+) # !label
  893. ([*!^]?) # !link
  894. ({$this->c}) # !att
  895. \.? # optional period.
  896. [\s]+ # whitespace ends def marker
  897. (.*)$ # !content
  898. /x$mod", array(&$this, "fParseNoteDefs"), $content);
  899. if( '' === $notedef ) # It will be empty if the regex matched and ate it.
  900. return array($o1, $o2, $notedef, $c2, $c1, true);
  901. }
  902. if (preg_match("/fn(\d+)/", $tag, $fns)) {
  903. $tag = 'p';
  904. $fnid = empty($this->fn[$fns[1]]) ? $fns[1] : $this->fn[$fns[1]];
  905. # If there is an author-specified ID goes on the wrapper & the auto-id gets pushed to the <sup>
  906. $supp_id = '';
  907. if (strpos($atts, ' id=') === false)
  908. $atts .= ' id="fn' . $fnid . '"';
  909. else
  910. $supp_id = ' id="fn' . $fnid . '"';
  911. if (strpos($atts, 'class=') === false)
  912. $atts .= ' class="footnote"';
  913. $sup = (strpos($att, '^') === false) ? $this->formatFootnote($fns[1], $supp_id) : $this->formatFootnote('<a href="#fnrev' . $fnid . '">'.$fns[1] .'</a>', $supp_id);
  914. $content = $sup . ' ' . $content;
  915. }
  916. if ($tag == "bq") {
  917. $cite = $this->shelveURL($cite);
  918. $cite = ($cite != '') ? ' cite="' . $cite . '"' : '';
  919. $o1 = "\t<blockquote$cite$atts>\n";
  920. $o2 = "\t\t<p".$this->pba($att, '', 0).">";
  921. $c2 = "</p>";
  922. $c1 = "\n\t</blockquote>";
  923. }
  924. elseif ($tag == 'bc') {
  925. $o1 = "<pre$atts>";
  926. $o2 = "<code>";
  927. $c2 = "</code>";
  928. $c1 = "</pre>";
  929. $content = $this->shelve($this->r_encode_html(rtrim($content, "\n")."\n"));
  930. }
  931. elseif ($tag == 'notextile') {
  932. $content = $this->shelve($content);
  933. $o1 = $o2 = '';
  934. $c1 = $c2 = '';
  935. }
  936. elseif ($tag == 'pre') {
  937. $content = $this->shelve($this->r_encode_html(rtrim($content, "\n")."\n"));
  938. $o1 = "<pre$atts>";
  939. $o2 = $c2 = '';
  940. $c1 = "</pre>";
  941. }
  942. elseif ($tag == '###') {
  943. $eat = true;
  944. }
  945. else {
  946. $o2 = "\t<$tag$atts>";
  947. $c2 = "</$tag>";
  948. }
  949. $content = (!$eat) ? $this->graf($content) : '';
  950. return array($o1, $o2, $content, $c2, $c1, $eat);
  951. }
  952. // -------------------------------------------------------------
  953. function fParseHTMLComments($m)
  954. {
  955. list( , $content ) = $m;
  956. if( $this->restricted )
  957. $content = $this->shelve($this->r_encode_html($content));
  958. else
  959. $content = $this->shelve($content);
  960. return "<!--$content-->";
  961. }
  962. function getHTMLComments($text)
  963. {
  964. $text = preg_replace_callback("/
  965. \<!-- # start
  966. (.*?) # !content
  967. --> # end
  968. /sx", array(&$this, "fParseHTMLComments"), $text);
  969. return $text;
  970. }
  971. // -------------------------------------------------------------
  972. function graf($text)
  973. {
  974. // handle normal paragraph text
  975. if (!$this->lite) {
  976. $text = $this->noTextile($text);
  977. $text = $this->code($text);
  978. }
  979. $text = $this->getHTMLComments($text);
  980. $text = $this->getRefs($text);
  981. $text = $this->links($text);
  982. if (!$this->noimage)
  983. $text = $this->image($text);
  984. if (!$this->lite) {
  985. $text = $this->table($text);
  986. $text = $this->redcloth_lists($text);
  987. $text = $this->lists($text);
  988. }
  989. $text = $this->span($text);
  990. $text = $this->footnoteRef($text);
  991. $text = $this->noteRef($text);
  992. $text = $this->glyphs($text);
  993. return rtrim($text, "\n");
  994. }
  995. // -------------------------------------------------------------
  996. function span($text)
  997. {
  998. $qtags = array('\*\*','\*','\?\?','-','__','_','%','\+','~','\^');
  999. $pnct = ".,\"'?!;:‹›Ťť„“”‚‘’";
  1000. $this->span_depth++;
  1001. if( $this->span_depth <= $this->max_span_depth )
  1002. {
  1003. foreach($qtags as $f)
  1004. {
  1005. $text = preg_replace_callback("/
  1006. (^|(?<=[\s>$pnct\(])|[{[]) # pre
  1007. ($f)(?!$f) # tag
  1008. ({$this->c}) # atts
  1009. (?::(\S+))? # cite
  1010. ([^\s$f]+|\S.*?[^\s$f\n]) # content
  1011. ([$pnct]*) # end
  1012. $f
  1013. ($|[\[\]}<]|(?=[$pnct]{1,2}|\s|\))) # tail
  1014. /x".$this->regex_snippets['mod'], array(&$this, "fSpan"), $text);
  1015. }
  1016. }
  1017. $this->span_depth--;
  1018. return $text;
  1019. }
  1020. // -------------------------------------------------------------
  1021. function fSpan($m)
  1022. {
  1023. $qtags = array(
  1024. '*' => 'strong',
  1025. '**' => 'b',
  1026. '??' => 'cite',
  1027. '_' => 'em',
  1028. '__' => 'i',
  1029. '-' => 'del',
  1030. '%' => 'span',
  1031. '+' => 'ins',
  1032. '~' => 'sub',
  1033. '^' => 'sup',
  1034. );
  1035. list(, $pre, $tag, $atts, $cite, $content, $end, $tail) = $m;
  1036. $tag = $qtags[$tag];
  1037. $atts = $this->pba($atts);
  1038. $atts .= ($cite != '') ? 'cite="' . $cite . '"' : '';
  1039. $content = $this->span($content);
  1040. $opentag = '<'.$tag.$atts.'>';
  1041. $closetag = '</'.$tag.'>';
  1042. $tags = $this->storeTags($opentag, $closetag);
  1043. $out = "{$tags['open']}{$content}{$end}{$tags['close']}";
  1044. if (($pre and !$tail) or ($tail and !$pre))
  1045. $out = $pre.$out.$tail;
  1046. return $out;
  1047. }
  1048. // -------------------------------------------------------------
  1049. function storeTags($opentag,$closetag='')
  1050. {
  1051. $key = ($this->tag_index++);
  1052. $key = str_pad( (string)$key, 10, '0', STR_PAD_LEFT ); # $key must be of fixed length to allow proper matching in retrieveTags
  1053. $this->tagCache[$key] = array('open'=>$opentag, 'close'=>$closetag);
  1054. $tags = array(
  1055. 'open' => "textileopentag{$key} ",
  1056. 'close' => " textileclosetag{$key}",
  1057. );
  1058. return $tags;
  1059. }
  1060. // -------------------------------------------------------------
  1061. function retrieveTags($text)
  1062. {
  1063. $text = preg_replace_callback('/textileopentag([\d]{10}) /' , array(&$this, 'fRetrieveOpenTags'), $text);
  1064. $text = preg_replace_callback('/ textileclosetag([\d]{10})/', array(&$this, 'fRetrieveCloseTags'), $text);
  1065. return $text;
  1066. }
  1067. // -------------------------------------------------------------
  1068. function fRetrieveOpenTags($m)
  1069. {
  1070. list(, $key ) = $m;
  1071. return $this->tagCache[$key]['open'];
  1072. }
  1073. // -------------------------------------------------------------
  1074. function fRetrieveCloseTags($m)
  1075. {
  1076. list(, $key ) = $m;
  1077. return $this->tagCache[$key]['close'];
  1078. }
  1079. // -------------------------------------------------------------
  1080. function placeNoteLists($text)
  1081. {
  1082. extract($this->regex_snippets);
  1083. # Sequence all referenced definitions...
  1084. if( !empty($this->notes) ) {
  1085. $o = array();
  1086. foreach( $this->notes as $label=>$info ) {
  1087. $i = @$info['seq'];
  1088. if( !empty($i) ) {
  1089. $info['seq'] = $label;
  1090. $o[$i] = $info;
  1091. } else {
  1092. $this->unreferencedNotes[] = $info; # unreferenced definitions go here for possible future use.
  1093. }
  1094. }
  1095. if( !empty($o) ) ksort($o);
  1096. $this->notes = $o;
  1097. }
  1098. # Replace list markers...
  1099. $text = preg_replace_callback("@<p>notelist({$this->c})(?:\:([$wrd|{$this->syms}]))?([\^!]?)(\+?)\.?[\s]*</p>@U$mod", array(&$this, "fNoteLists"), $text );
  1100. return $text;
  1101. }
  1102. // -------------------------------------------------------------
  1103. function fNoteLists($m)
  1104. {
  1105. list(, $att, $start_char, $g_links, $extras) = $m;
  1106. if( !$start_char ) $start_char = 'a';
  1107. $index = $g_links.$extras.$start_char;
  1108. if( empty($this->notelist_cache[$index]) ) { # If not in cache, build the entry...
  1109. $o = array();
  1110. if( !empty($this->notes)) {
  1111. foreach($this->notes as $seq=>$info) {
  1112. $links = $this->makeBackrefLink($info, $g_links, $start_char );
  1113. $atts = '';
  1114. if( !empty($info['def'])) {
  1115. $id = $info['id'];
  1116. extract($info['def']);
  1117. $o[] = "\t".'<li'.$atts.'>'.$links.'<span id="note'.$id.'"> </span>'.$content.'</li>';
  1118. } else {
  1119. $o[] = "\t".'<li'.$atts.'>'.$links.' Undefined Note [#'.$info['seq'].'].</li>';
  1120. }
  1121. }
  1122. }
  1123. if( '+' == $extras && !empty($this->unreferencedNotes) ) {
  1124. foreach($this->unreferencedNotes as $seq=>$info) {
  1125. if( !empty($info['def'])) {
  1126. extract($info['def']);
  1127. $o[] = "\t".'<li'.$atts.'>'.$content.'</li>';
  1128. }
  1129. }
  1130. }
  1131. $this->notelist_cache[$index] = join("\n",$o);
  1132. }
  1133. $_ = ($this->notelist_cache[$index]) ? $this->notelist_cache[$index] : '';
  1134. if( !empty($_) ) {
  1135. $list_atts = $this->pba($att);
  1136. $_ = "<ol$list_atts>\n$_\n</ol>";
  1137. }
  1138. return $_;
  1139. }
  1140. // -------------------------------------------------------------
  1141. function makeBackrefLink( &$info, $g_links, $i )
  1142. {
  1143. $atts = $content = $id = $link = '';
  1144. @extract( $info['def'] );
  1145. $backlink_type = ($link) ? $link : $g_links;
  1146. $allow_inc = (false === strpos( $this->syms, $i ) );
  1147. $i_ = strtr( $this->encode_high($i) , array('&'=>'', ';'=>'', '#'=>''));
  1148. $decode = (strlen($i) !== strlen($i_));
  1149. if( $backlink_type === '!' )
  1150. return '';
  1151. elseif( $backlink_type === '^' )
  1152. return '<sup><a href="#noteref'.$info['refids'][0].'">'.$i.'</a></sup>';
  1153. else {
  1154. $_ = array();
  1155. foreach( $info['refids'] as $id ) {
  1156. $_[] = '<sup><a href="#noteref'.$id.'">'. ( ($decode) ? $this->decode_high('&#'.$i_.';') : $i_ ) .'</a></sup>';
  1157. if( $allow_inc )
  1158. $i_++;
  1159. }
  1160. $_ = join( ' ', $_ );
  1161. return $_;
  1162. }
  1163. return '';
  1164. }
  1165. // -------------------------------------------------------------
  1166. function fParseNoteDefs($m)
  1167. {
  1168. list(, $label, $link, $att, $content) = $m;
  1169. # Assign an id if the note reference parse hasn't found the label yet.
  1170. $id = @$this->notes[$label]['id'];
  1171. if( !$id )
  1172. $this->notes[$label]['id'] = uniqid(rand());
  1173. if( empty($this->notes[$label]['def']) ) # Ignores subsequent defs using the same label
  1174. {
  1175. $this->notes[$label]['def'] = array(
  1176. 'atts' => $this->pba($att),
  1177. 'content' => $this->graf($content),
  1178. 'link' => $link,
  1179. );
  1180. }
  1181. return '';
  1182. }
  1183. // -------------------------------------------------------------
  1184. function noteRef($text)
  1185. {
  1186. $text = preg_replace_callback("/
  1187. \[ # start
  1188. ({$this->c}) # !atts
  1189. \#
  1190. ([^\]!]+?) # !label
  1191. ([!]?) # !nolink
  1192. \]
  1193. /Ux", array(&$this, "fParseNoteRefs"), $text);
  1194. return $text;
  1195. }
  1196. // -------------------------------------------------------------
  1197. function fParseNoteRefs($m)
  1198. {
  1199. # By the time this function is called, all the defs will have been processed
  1200. # into the notes array. So now we can resolve the link numbers in the order
  1201. # we process the refs...
  1202. list(, $atts, $label, $nolink) = $m;
  1203. $atts = $this->pba($atts);
  1204. $nolink = ($nolink === '!');
  1205. # Assign a sequence number to this reference if there isn't one already...
  1206. $num = @$this->notes[$label]['seq'];
  1207. if( !$num )
  1208. $num = $this->notes[$label]['seq'] = ($this->note_index++);
  1209. # Make our anchor point & stash it for possible use in backlinks when the
  1210. # note list is generated later...
  1211. $this->notes[$label]['refids'][] = $refid = uniqid(rand());
  1212. # If we are referencing a note that hasn't had the definition parsed yet, then assign it an ID...
  1213. $id = @$this->notes[$label]['id'];
  1214. if( !$id )
  1215. $id = $this->notes[$label]['id'] = uniqid(rand());
  1216. # Build the link (if any)...
  1217. $_ = '<span id="noteref'.$refid.'">'.$num.'</span>';
  1218. if( !$nolink )
  1219. $_ = '<a href="#note'.$id.'">'.$_.'</a>';
  1220. # Build the reference...
  1221. $_ = $this->replaceMarkers( txt_nl_ref_pattern, array( 'atts' => $atts, 'marker' => $_ ) );
  1222. return $_;
  1223. }
  1224. // -------------------------------------------------------------
  1225. /**
  1226. * Parse URI
  1227. *
  1228. * Regex taken from the RFC at http://tools.ietf.org/html/rfc3986#appendix-B
  1229. **/
  1230. function parseURI( $uri, &$m )
  1231. {
  1232. $r = "@^((?<scheme>[^:/?#]+):)?(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\?(?<query>[^#]*))?(#(?<fragment>.*))?@";
  1233. # 12 3 4 5 6 7 8 9
  1234. #
  1235. # scheme = $2
  1236. # authority = $4
  1237. # path = $5
  1238. # query = $7
  1239. # fragment = $9
  1240. $ok = preg_match( $r, $uri, $m );
  1241. return $ok;
  1242. }
  1243. function addPart( &$mask, $name, &$parts ) {
  1244. return (in_array($name, $mask) && isset( $parts[$name]) && '' !== $parts[$name]);
  1245. }
  1246. // -------------------------------------------------------------
  1247. /**
  1248. * Rebuild a URI from parsed parts and a mask.
  1249. *
  1250. * Algorithm based on example from http://tools.ietf.org/html/rfc3986#section-5.3
  1251. **/
  1252. function rebuildURI( $parts, $mask='scheme,authority,path,query,fragment', $encode=true )
  1253. {
  1254. $mask = explode( ',', $mask );
  1255. $out = '';
  1256. if( $this->addPart( $mask, 'scheme', $parts ) ) {
  1257. $out .= $parts['scheme'] . ':';
  1258. }
  1259. if( $this->addPart( $mask, 'authority', $parts) ) {
  1260. $out .= '//' . $parts['authority'];
  1261. }
  1262. if( $this->addPart( $mask, 'path', $parts ) ) {
  1263. if( !$encode )
  1264. $out .= $parts['path'];
  1265. else {
  1266. $pp = explode( '/', $parts['path'] );
  1267. foreach( $pp as &$p ) {
  1268. $p = strtr( rawurlencode( $p ), array( '%40' => '@' ) );
  1269. }
  1270. $pp = implode( '/', $pp );
  1271. $out .= $pp;
  1272. }
  1273. }
  1274. if( $this->addPart( $mask, 'query', $parts ) ) {
  1275. $out .= '?' . $parts['query'];
  1276. }
  1277. if( $this->addPart( $mask, 'fragment', $parts ) ) {
  1278. $out .= '#' . $parts['fragment'];
  1279. }
  1280. return $out;
  1281. }
  1282. // -------------------------------------------------------------
  1283. function links($text)
  1284. {
  1285. return preg_replace_callback('/
  1286. (^|(?<=[\s>.\(])|[{[]) # $pre
  1287. " # start
  1288. (' . $this->c . ') # $atts
  1289. ([^"]+?) # $text
  1290. (?:\(([^)]+?)\)(?="))? # $title
  1291. ":
  1292. ('.$this->urlch.'+?) # $url
  1293. (\/)? # $slash
  1294. ([^'.$this->regex_snippets['wrd'].'\/;]*?) # $post
  1295. ([\]}]|(?=\s|$|\))) # $tail
  1296. /x'.$this->regex_snippets['mod'], array(&$this, "fLink"), $text);
  1297. }
  1298. // -------------------------------------------------------------
  1299. function fLink($m)
  1300. {
  1301. list(, $pre, $atts, $text, $title, $url, $slash, $post, $tail) = $m;
  1302. $uri_parts = array();
  1303. $this->parseURI( $url, $uri_parts );
  1304. $scheme = $uri_parts['scheme'];
  1305. $scheme_in_list = in_array( $scheme, $this->url_schemes );
  1306. $scheme_ok = '' === $scheme || $scheme_in_list;
  1307. if( !$scheme_ok )
  1308. return $m[0];
  1309. if( '$' === $text ) {
  1310. if( $scheme_in_list )
  1311. $text = ltrim( $this->rebuildURI( $uri_parts, 'authority,path,query,fragment', false ), '/' );
  1312. else
  1313. $text = $url;
  1314. }
  1315. $atts = $this->pba($atts);
  1316. $atts .= ($title != '') ? ' title="' . $this->encode_html($title) . '"' : '';
  1317. if (!$this->noimage)
  1318. $text = $this->image($text);
  1319. $text = $this->span($text);
  1320. $text = $this->glyphs($text);
  1321. $url = $this->shelveURL( $this->rebuildURI( $uri_parts ) . $slash );
  1322. $opentag = '<a href="' . $url . '"' . $atts . $this->rel . '>';
  1323. $closetag = '</a>';
  1324. $tags = $this->storeTags($opentag, $closetag);
  1325. $out = $tags['open'].trim($text).$tags['close'];
  1326. if (($pre and !$tail)

Large files files are truncated, but you can click here to view the full file