PageRenderTime 58ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/include/inc_ext/php-textile/classTextile.php

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

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