PageRenderTime 55ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/serendipity_event_textile/lib2/classTextile.php

https://github.com/jotbe/Serendipity
PHP | 2129 lines | 1570 code | 165 blank | 394 comment | 136 complexity | fc65fe0de6e4c627ab77ff08e60afb6c MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0

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

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