PageRenderTime 66ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/uBillboard/lib/classTextile.php

https://github.com/nunomorgadinho/AMMPro
PHP | 1711 lines | 1226 code | 121 blank | 364 comment | 94 complexity | 4ee5056df67078fc3c3e7e53315cbee0 MD5 | raw file
Possible License(s): GPL-2.0, GPL-3.0, AGPL-1.0, LGPL-2.1

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

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