A tumblelog CMS built on AJAX, PHP and MySQL.

textile.class.php 37KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. <?php
  2. if(!defined('entry') || !entry) die('Not a valid page');
  3. /**
  4. * Example: get XHTML from a given Textile-markup string ($string)
  5. *
  6. * $textile = new Textile;
  7. * echo $textile->TextileThis($string);
  8. *
  9. */
  10. /*
  11. $Id: classTextile.php 216 2006-10-17 22:31:53Z zem $
  12. $LastChangedRevision: 216 $
  13. */
  14. /*
  15. _____________
  16. T E X T I L E
  17. A Humane Web Text Generator
  18. Version 2.0
  19. Copyright (c) 2003-2004, Dean Allen <dean@textism.com>
  20. All rights reserved.
  21. Thanks to Carlo Zottmann <carlo@g-blog.net> for refactoring
  22. Textile's procedural code into a class framework
  23. Additions and fixes Copyright (c) 2006 Alex Shiels http://thresholdstate.com/
  24. _____________
  25. L I C E N S E
  26. Redistribution and use in source and binary forms, with or without
  27. modification, are permitted provided that the following conditions are met:
  28. * Redistributions of source code must retain the above copyright notice,
  29. this list of conditions and the following disclaimer.
  30. * Redistributions in binary form must reproduce the above copyright notice,
  31. this list of conditions and the following disclaimer in the documentation
  32. and/or other materials provided with the distribution.
  33. * Neither the name Textile nor the names of its contributors may be used to
  34. endorse or promote products derived from this software without specific
  35. prior written permission.
  36. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  37. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  38. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  39. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  40. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  41. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  42. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  43. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  44. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  45. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  46. POSSIBILITY OF SUCH DAMAGE.
  47. _________
  48. U S A G E
  49. Block modifier syntax:
  50. Header: h(1-6).
  51. Paragraphs beginning with 'hn. ' (where n is 1-6) are wrapped in header tags.
  52. Example: h1. Header... -> <h1>Header...</h1>
  53. Paragraph: p. (also applied by default)
  54. Example: p. Text -> <p>Text</p>
  55. Blockquote: bq.
  56. Example: bq. Block quotation... -> <blockquote>Block quotation...</blockquote>
  57. Blockquote with citation: bq.:http://citation.url
  58. Example: bq.:http://textism.com/ Text...
  59. -> <blockquote cite="http://textism.com">Text...</blockquote>
  60. Footnote: fn(1-100).
  61. Example: fn1. Footnote... -> <p id="fn1">Footnote...</p>
  62. Numeric list: #, ##
  63. Consecutive paragraphs beginning with # are wrapped in ordered list tags.
  64. Example: <ol><li>ordered list</li></ol>
  65. Bulleted list: *, **
  66. Consecutive paragraphs beginning with * are wrapped in unordered list tags.
  67. Example: <ul><li>unordered list</li></ul>
  68. Phrase modifier syntax:
  69. _emphasis_ -> <em>emphasis</em>
  70. __italic__ -> <i>italic</i>
  71. *strong* -> <strong>strong</strong>
  72. **bold** -> <b>bold</b>
  73. ??citation?? -> <cite>citation</cite>
  74. -deleted text- -> <del>deleted</del>
  75. +inserted text+ -> <ins>inserted</ins>
  76. ^superscript^ -> <sup>superscript</sup>
  77. ~subscript~ -> <sub>subscript</sub>
  78. @code@ -> <code>computer code</code>
  79. %(bob)span% -> <span class="bob">span</span>
  80. ==notextile== -> leave text alone (do not format)
  81. "linktext":url -> <a href="url">linktext</a>
  82. "linktext(title)":url -> <a href="url" title="title">linktext</a>
  83. !imageurl! -> <img src="imageurl" />
  84. !imageurl(alt text)! -> <img src="imageurl" alt="alt text" />
  85. !imageurl!:linkurl -> <a href="linkurl"><img src="imageurl" /></a>
  86. ABC(Always Be Closing) -> <acronym title="Always Be Closing">ABC</acronym>
  87. Table syntax:
  88. Simple tables:
  89. |a|simple|table|row|
  90. |And|Another|table|row|
  91. |_. A|_. table|_. header|_.row|
  92. |A|simple|table|row|
  93. Tables with attributes:
  94. table{border:1px solid black}.
  95. {background:#ddd;color:red}. |{}| | | |
  96. Applying Attributes:
  97. Most anywhere Textile code is used, attributes such as arbitrary css style,
  98. css classes, and ids can be applied. The syntax is fairly consistent.
  99. The following characters quickly alter the alignment of block elements:
  100. < -> left align ex. p<. left-aligned para
  101. > -> right align h3>. right-aligned header 3
  102. = -> centred h4=. centred header 4
  103. <> -> justified p<>. justified paragraph
  104. These will change vertical alignment in table cells:
  105. ^ -> top ex. |^. top-aligned table cell|
  106. - -> middle |-. middle aligned|
  107. ~ -> bottom |~. bottom aligned cell|
  108. Plain (parentheses) inserted between block syntax and the closing dot-space
  109. indicate classes and ids:
  110. p(hector). paragraph -> <p class="hector">paragraph</p>
  111. p(#fluid). paragraph -> <p id="fluid">paragraph</p>
  112. (classes and ids can be combined)
  113. p(hector#fluid). paragraph -> <p class="hector" id="fluid">paragraph</p>
  114. Curly {brackets} insert arbitrary css style
  115. p{line-height:18px}. paragraph -> <p style="line-height:18px">paragraph</p>
  116. h3{color:red}. header 3 -> <h3 style="color:red">header 3</h3>
  117. Square [brackets] insert language attributes
  118. p[no]. paragraph -> <p lang="no">paragraph</p>
  119. %[fr]phrase% -> <span lang="fr">phrase</span>
  120. Usually Textile block element syntax requires a dot and space before the block
  121. begins, but since lists don't, they can be styled just using braces
  122. #{color:blue} one -> <ol style="color:blue">
  123. # big <li>one</li>
  124. # list <li>big</li>
  125. <li>list</li>
  126. </ol>
  127. Using the span tag to style a phrase
  128. It goes like this, %{color:red}the fourth the fifth%
  129. -> It goes like this, <span style="color:red">the fourth the fifth</span>
  130. */
  131. // define these before including this file to override the standard glyphs
  132. @define('txt_quote_single_open', '&#8216;');
  133. @define('txt_quote_single_close', '&#8217;');
  134. @define('txt_quote_double_open', '&#8220;');
  135. @define('txt_quote_double_close', '&#8221;');
  136. @define('txt_apostrophe', '&#8217;');
  137. @define('txt_prime', '&#8242;');
  138. @define('txt_prime_double', '&#8243;');
  139. @define('txt_ellipsis', '&#8230;');
  140. @define('txt_emdash', '&#8212;');
  141. @define('txt_endash', '&#8211;');
  142. @define('txt_dimension', '&#215;');
  143. @define('txt_trademark', '&#8482;');
  144. @define('txt_registered', '&#174;');
  145. @define('txt_copyright', '&#169;');
  146. class Textile
  147. {
  148. var $hlgn;
  149. var $vlgn;
  150. var $clas;
  151. var $lnge;
  152. var $styl;
  153. var $cspn;
  154. var $rspn;
  155. var $a;
  156. var $s;
  157. var $c;
  158. var $pnct;
  159. var $rel;
  160. var $fn;
  161. var $shelf = array();
  162. var $restricted = false;
  163. var $noimage = false;
  164. var $lite = false;
  165. var $url_schemes = array();
  166. var $glyph = array();
  167. var $hu = '';
  168. var $ver = '2.0.0';
  169. var $rev = '$Rev: 216 $';
  170. // -------------------------------------------------------------
  171. function Textile()
  172. {
  173. $this->hlgn = "(?:\<(?!>)|(?<!<)\>|\<\>|\=|[()]+(?! ))";
  174. $this->vlgn = "[\-^~]";
  175. $this->clas = "(?:\([^)]+\))";
  176. $this->lnge = "(?:\[[^]]+\])";
  177. $this->styl = "(?:\{[^}]+\})";
  178. $this->cspn = "(?:\\\\\d+)";
  179. $this->rspn = "(?:\/\d+)";
  180. $this->a = "(?:{$this->hlgn}|{$this->vlgn})*";
  181. $this->s = "(?:{$this->cspn}|{$this->rspn})*";
  182. $this->c = "(?:{$this->clas}|{$this->styl}|{$this->lnge}|{$this->hlgn})*";
  183. $this->pnct = '[\!"#\$%&\'()\*\+,\-\./:;<=>\?@\[\\\]\^_`{\|}\~]';
  184. $this->urlch = '[\w"$\-_.+!*\'(),";\/?:@=&%#{}|\\^~\[\]`]';
  185. $this->url_schemes = array('http','https','ftp','mailto');
  186. $this->btag = array('bq', 'bc', 'notextile', 'pre', 'h[1-6]', 'fn\d+', 'p');
  187. $this->glyph = array(
  188. 'quote_single_open' => txt_quote_single_open,
  189. 'quote_single_close' => txt_quote_single_close,
  190. 'quote_double_open' => txt_quote_double_open,
  191. 'quote_double_close' => txt_quote_double_close,
  192. 'apostrophe' => txt_apostrophe,
  193. 'prime' => txt_prime,
  194. 'prime_double' => txt_prime_double,
  195. 'ellipsis' => txt_ellipsis,
  196. 'emdash' => txt_emdash,
  197. 'endash' => txt_endash,
  198. 'dimension' => txt_dimension,
  199. 'trademark' => txt_trademark,
  200. 'registered' => txt_registered,
  201. 'copyright' => txt_copyright,
  202. );
  203. if (defined('hu'))
  204. $this->hu = hu;
  205. }
  206. // -------------------------------------------------------------
  207. function TextileThis($text, $lite='', $encode='', $noimage='', $strict='', $rel='')
  208. {
  209. if ($rel)
  210. $this->rel = ' rel="'.$rel.'" ';
  211. $this->lite = $lite;
  212. $this->noimage = $noimage;
  213. if ($encode) {
  214. $text = $this->incomingEntities($text);
  215. $text = str_replace("x%x%", "&#38;", $text);
  216. return $text;
  217. } else {
  218. if(!$strict) {
  219. $text = $this->cleanWhiteSpace($text);
  220. }
  221. $text = $this->getRefs($text);
  222. if (!$lite) {
  223. $text = $this->block($text);
  224. }
  225. $text = $this->retrieve($text);
  226. // just to be tidy
  227. $text = str_replace("<br />", "<br />\n", $text);
  228. return $text;
  229. }
  230. }
  231. // -------------------------------------------------------------
  232. function TextileRestricted($text, $lite=1, $noimage=1, $rel='nofollow')
  233. {
  234. $this->restricted = true;
  235. $this->lite = $lite;
  236. $this->noimage = $noimage;
  237. if ($rel)
  238. $this->rel = ' rel="'.$rel.'" ';
  239. // escape any raw html
  240. $text = $this->encode_html($text, 0);
  241. $text = $this->cleanWhiteSpace($text);
  242. $text = $this->getRefs($text);
  243. if ($lite) {
  244. $text = $this->blockLite($text);
  245. }
  246. else {
  247. $text = $this->block($text);
  248. }
  249. $text = $this->retrieve($text);
  250. // just to be tidy
  251. $text = str_replace("<br />", "<br />\n", $text);
  252. return $text;
  253. }
  254. // -------------------------------------------------------------
  255. function pba($in, $element = "") // "parse block attributes"
  256. {
  257. $style = '';
  258. $class = '';
  259. $lang = '';
  260. $colspan = '';
  261. $rowspan = '';
  262. $id = '';
  263. $atts = '';
  264. if (!empty($in)) {
  265. $matched = $in;
  266. if ($element == 'td') {
  267. if (preg_match("/\\\\(\d+)/", $matched, $csp)) $colspan = $csp[1];
  268. if (preg_match("/\/(\d+)/", $matched, $rsp)) $rowspan = $rsp[1];
  269. }
  270. if ($element == 'td' or $element == 'tr') {
  271. if (preg_match("/($this->vlgn)/", $matched, $vert))
  272. $style[] = "vertical-align:" . $this->vAlign($vert[1]) . ";";
  273. }
  274. if (preg_match("/\{([^}]*)\}/", $matched, $sty)) {
  275. $style[] = rtrim($sty[1], ';') . ';';
  276. $matched = str_replace($sty[0], '', $matched);
  277. }
  278. if (preg_match("/\[([^]]+)\]/U", $matched, $lng)) {
  279. $lang = $lng[1];
  280. $matched = str_replace($lng[0], '', $matched);
  281. }
  282. if (preg_match("/\(([^()]+)\)/U", $matched, $cls)) {
  283. $class = $cls[1];
  284. $matched = str_replace($cls[0], '', $matched);
  285. }
  286. if (preg_match("/([(]+)/", $matched, $pl)) {
  287. $style[] = "padding-left:" . strlen($pl[1]) . "em;";
  288. $matched = str_replace($pl[0], '', $matched);
  289. }
  290. if (preg_match("/([)]+)/", $matched, $pr)) {
  291. // $this->dump($pr);
  292. $style[] = "padding-right:" . strlen($pr[1]) . "em;";
  293. $matched = str_replace($pr[0], '', $matched);
  294. }
  295. if (preg_match("/($this->hlgn)/", $matched, $horiz))
  296. $style[] = "text-align:" . $this->hAlign($horiz[1]) . ";";
  297. if (preg_match("/^(.*)#(.*)$/", $class, $ids)) {
  298. $id = $ids[2];
  299. $class = $ids[1];
  300. }
  301. if ($this->restricted)
  302. return ($lang) ? ' lang="' . $lang .'"':'';
  303. return join('',array(
  304. ($style) ? ' style="' . join("", $style) .'"':'',
  305. ($class) ? ' class="' . $class .'"':'',
  306. ($lang) ? ' lang="' . $lang .'"':'',
  307. ($id) ? ' id="' . $id .'"':'',
  308. ($colspan) ? ' colspan="' . $colspan .'"':'',
  309. ($rowspan) ? ' rowspan="' . $rowspan .'"':''
  310. ));
  311. }
  312. return '';
  313. }
  314. // -------------------------------------------------------------
  315. function hasRawText($text)
  316. {
  317. // checks whether the text has text not already enclosed by a block tag
  318. $r = trim(preg_replace('@<(p|blockquote|div|form|table|ul|ol|pre|h\d)[^>]*?>.*</\1>@s', '', trim($text)));
  319. $r = trim(preg_replace('@<(hr|br)[^>]*?/>@', '', $r));
  320. return '' != $r;
  321. }
  322. // -------------------------------------------------------------
  323. function table($text)
  324. {
  325. $text = $text . "\n\n";
  326. return preg_replace_callback("/^(?:table(_?{$this->s}{$this->a}{$this->c})\. ?\n)?^({$this->a}{$this->c}\.? ?\|.*\|)\n\n/smU",
  327. array(&$this, "fTable"), $text);
  328. }
  329. // -------------------------------------------------------------
  330. function fTable($matches)
  331. {
  332. $tatts = $this->pba($matches[1], 'table');
  333. foreach(preg_split("/\|$/m", $matches[2], -1, PREG_SPLIT_NO_EMPTY) as $row) {
  334. if (preg_match("/^($this->a$this->c\. )(.*)/m", ltrim($row), $rmtch)) {
  335. $ratts = $this->pba($rmtch[1], 'tr');
  336. $row = $rmtch[2];
  337. } else $ratts = '';
  338. $cells = array();
  339. foreach(explode("|", $row) as $cell) {
  340. $ctyp = "d";
  341. if (preg_match("/^_/", $cell)) $ctyp = "h";
  342. if (preg_match("/^(_?$this->s$this->a$this->c\. )(.*)/", $cell, $cmtch)) {
  343. $catts = $this->pba($cmtch[1], 'td');
  344. $cell = $cmtch[2];
  345. } else $catts = '';
  346. $cell = $this->graf($this->span($cell));
  347. if (trim($cell) != '')
  348. $cells[] = "\t\t\t<t$ctyp$catts>$cell</t$ctyp>";
  349. }
  350. $rows[] = "\t\t<tr$ratts>\n" . join("\n", $cells) . ($cells ? "\n" : "") . "\t\t</tr>";
  351. unset($cells, $catts);
  352. }
  353. return "\t<table$tatts>\n" . join("\n", $rows) . "\n\t</table>\n\n";
  354. }
  355. // -------------------------------------------------------------
  356. function lists($text)
  357. {
  358. return preg_replace_callback("/^([#*]+$this->c .*)$(?![^#*])/smU", array(&$this, "fList"), $text);
  359. }
  360. // -------------------------------------------------------------
  361. function fList($m)
  362. {
  363. $text = explode("\n", $m[0]);
  364. foreach($text as $line) {
  365. $nextline = next($text);
  366. if (preg_match("/^([#*]+)($this->a$this->c) (.*)$/s", $line, $m)) {
  367. list(, $tl, $atts, $content) = $m;
  368. $nl = '';
  369. if (preg_match("/^([#*]+)\s.*/", $nextline, $nm))
  370. $nl = $nm[1];
  371. if (!isset($lists[$tl])) {
  372. $lists[$tl] = true;
  373. $atts = $this->pba($atts);
  374. $line = "\t<" . $this->lT($tl) . "l$atts>\n\t\t<li>" . $this->graf($content);
  375. } else {
  376. $line = "\t\t<li>" . $this->graf($content);
  377. }
  378. if(strlen($nl) <= strlen($tl)) $line .= "</li>";
  379. foreach(array_reverse($lists) as $k => $v) {
  380. if(strlen($k) > strlen($nl)) {
  381. $line .= "\n\t</" . $this->lT($k) . "l>";
  382. if(strlen($k) > 1)
  383. $line .= "</li>";
  384. unset($lists[$k]);
  385. }
  386. }
  387. }
  388. $out[] = $line;
  389. }
  390. return join("\n", $out);
  391. }
  392. // -------------------------------------------------------------
  393. function lT($in)
  394. {
  395. return preg_match("/^#+/", $in) ? 'o' : 'u';
  396. }
  397. // -------------------------------------------------------------
  398. function doPBr($in)
  399. {
  400. return preg_replace_callback('@<(p)([^>]*?)>(.*)(</\1>)@s', array(&$this, 'doBr'), $in);
  401. }
  402. // -------------------------------------------------------------
  403. function doBr($m)
  404. {
  405. $content = preg_replace("@(.+)(?<!<br>|<br />)\n(?![#*\s|])@", '$1<br />', $m[3]);
  406. return '<'.$m[1].$m[2].'>'.$content.$m[4];
  407. }
  408. // -------------------------------------------------------------
  409. function block($text)
  410. {
  411. $find = $this->btag;
  412. $tre = join('|', $find);
  413. $text = explode("\n\n", $text);
  414. $tag = 'p';
  415. $atts = $cite = $graf = $ext = '';
  416. foreach($text as $line) {
  417. $anon = 0;
  418. if (preg_match("/^($tre)($this->a$this->c)\.(\.?)(?::(\S+))? (.*)$/s", $line, $m)) {
  419. // last block was extended, so close it
  420. if ($ext)
  421. $out[count($out)-1] .= $c1;
  422. // new block
  423. list(,$tag,$atts,$ext,$cite,$graf) = $m;
  424. list($o1, $o2, $content, $c2, $c1) = $this->fBlock(array(0,$tag,$atts,$ext,$cite,$graf));
  425. // leave off c1 if this block is extended, we'll close it at the start of the next block
  426. if ($ext)
  427. $line = $o1.$o2.$content.$c2;
  428. else
  429. $line = $o1.$o2.$content.$c2.$c1;
  430. }
  431. else {
  432. // anonymous block
  433. $anon = 1;
  434. if ($ext or !preg_match('/^ /', $line)) {
  435. list($o1, $o2, $content, $c2, $c1) = $this->fBlock(array(0,$tag,$atts,$ext,$cite,$line));
  436. // skip $o1/$c1 because this is part of a continuing extended block
  437. if ($tag == 'p' and !$this->hasRawText($content)) {
  438. $line = $content;
  439. }
  440. else {
  441. $line = $o2.$content.$c2;
  442. }
  443. }
  444. else {
  445. $line = $this->graf($line);
  446. }
  447. }
  448. $line = $this->doPBr($line);
  449. $line = preg_replace('/<br>/', '<br />', $line);
  450. if ($ext and $anon)
  451. $out[count($out)-1] .= "\n".$line;
  452. else
  453. $out[] = $line;
  454. if (!$ext) {
  455. $tag = 'p';
  456. $atts = '';
  457. $cite = '';
  458. $graf = '';
  459. }
  460. }
  461. if ($ext) $out[count($out)-1] .= $c1;
  462. return join("\n\n", $out);
  463. }
  464. // -------------------------------------------------------------
  465. function fBlock($m)
  466. {
  467. // $this->dump($m);
  468. list(, $tag, $atts, $ext, $cite, $content) = $m;
  469. $atts = $this->pba($atts);
  470. $o1 = $o2 = $c2 = $c1 = '';
  471. if (preg_match("/fn(\d+)/", $tag, $fns)) {
  472. $tag = 'p';
  473. $fnid = empty($this->fn[$fns[1]]) ? $fns[1] : $this->fn[$fns[1]];
  474. $atts .= ' id="fn' . $fnid . '"';
  475. if (strpos($atts, 'class=') === false)
  476. $atts .= ' class="footnote"';
  477. $content = '<sup>' . $fns[1] . '</sup> ' . $content;
  478. }
  479. if ($tag == "bq") {
  480. $cite = $this->checkRefs($cite);
  481. $cite = ($cite != '') ? ' cite="' . $cite . '"' : '';
  482. $o1 = "\t<blockquote$cite$atts>\n";
  483. $o2 = "\t\t<p$atts>";
  484. $c2 = "</p>";
  485. $c1 = "\n\t</blockquote>";
  486. }
  487. elseif ($tag == 'bc') {
  488. $o1 = "<pre$atts>";
  489. $o2 = "<code$atts>";
  490. $c2 = "</code>";
  491. $c1 = "</pre>";
  492. $content = $this->shelve($this->encode_html(rtrim($content, "\n")."\n"));
  493. }
  494. elseif ($tag == 'notextile') {
  495. $content = $this->shelve($content);
  496. $o1 = $o2 = '';
  497. $c1 = $c2 = '';
  498. }
  499. elseif ($tag == 'pre') {
  500. $content = $this->shelve($this->encode_html(rtrim($content, "\n")."\n"));
  501. $o1 = "<pre$atts>";
  502. $o2 = $c2 = '';
  503. $c1 = "</pre>";
  504. }
  505. else {
  506. $o2 = "\t<$tag$atts>";
  507. $c2 = "</$tag>";
  508. }
  509. $content = $this->graf($content);
  510. return array($o1, $o2, $content, $c2, $c1);
  511. }
  512. // -------------------------------------------------------------
  513. function graf($text)
  514. {
  515. // handle normal paragraph text
  516. if (!$this->lite) {
  517. $text = $this->noTextile($text);
  518. $text = $this->code($text);
  519. }
  520. $text = $this->links($text);
  521. if (!$this->noimage)
  522. $text = $this->image($text);
  523. if (!$this->lite) {
  524. $text = $this->lists($text);
  525. $text = $this->table($text);
  526. }
  527. $text = $this->span($text);
  528. $text = $this->footnoteRef($text);
  529. $text = $this->glyphs($text);
  530. return rtrim($text, "\n");
  531. }
  532. // -------------------------------------------------------------
  533. function span($text)
  534. {
  535. $qtags = array('\*\*','\*','\?\?','-','__','_','%','\+','~','\^');
  536. $pnct = ".,\"'?!;:";
  537. foreach($qtags as $f) {
  538. $text = preg_replace_callback("/
  539. (?:^|(?<=[\s>$pnct])|([{[]))
  540. ($f)(?!$f)
  541. ({$this->c})
  542. (?::(\S+))?
  543. ([^\s$f]+|\S[^$f\n]*[^\s$f\n])
  544. ([$pnct]*)
  545. $f
  546. (?:$|([\]}])|(?=[[:punct:]]{1,2}|\s))
  547. /x", array(&$this, "fSpan"), $text);
  548. }
  549. return $text;
  550. }
  551. // -------------------------------------------------------------
  552. function fSpan($m)
  553. {
  554. $qtags = array(
  555. '*' => 'strong',
  556. '**' => 'b',
  557. '??' => 'cite',
  558. '_' => 'em',
  559. '__' => 'i',
  560. '-' => 'del',
  561. '%' => 'span',
  562. '+' => 'ins',
  563. '~' => 'sub',
  564. '^' => 'sup',
  565. );
  566. list(,, $tag, $atts, $cite, $content, $end) = $m;
  567. $tag = $qtags[$tag];
  568. $atts = $this->pba($atts);
  569. $atts .= ($cite != '') ? 'cite="' . $cite . '"' : '';
  570. $out = "<$tag$atts>$content$end</$tag>";
  571. // $this->dump($out);
  572. return $out;
  573. }
  574. // -------------------------------------------------------------
  575. function links($text)
  576. {
  577. return preg_replace_callback('/
  578. (?:^|(?<=[\s>.$pnct\(])|([{[])) # $pre
  579. " # start
  580. (' . $this->c . ') # $atts
  581. ([^"]+) # $text
  582. \s?
  583. (?:\(([^)]+)\)(?="))? # $title
  584. ":
  585. ('.$this->urlch.'+) # $url
  586. (\/)? # $slash
  587. ([^\w\/;]*) # $post
  588. (?:([\]}])|(?=\s|$|\)))
  589. /Ux', array(&$this, "fLink"), $text);
  590. }
  591. // -------------------------------------------------------------
  592. function fLink($m)
  593. {
  594. list(, $pre, $atts, $text, $title, $url, $slash, $post) = $m;
  595. $url = $this->checkRefs($url);
  596. $atts = $this->pba($atts);
  597. $atts .= ($title != '') ? ' title="' . $this->encode_html($title) . '"' : '';
  598. if (!$this->noimage)
  599. $text = $this->image($text);
  600. $text = $this->span($text);
  601. $text = $this->glyphs($text);
  602. $url = $this->relURL($url);
  603. $out = '<a href="' . $this->encode_html($url . $slash) . '"' . $atts . $this->rel . '>' . $text . '</a>' . $post;
  604. // $this->dump($out);
  605. return $this->shelve($out);
  606. }
  607. // -------------------------------------------------------------
  608. function getRefs($text)
  609. {
  610. return preg_replace_callback("/(?<=^|\s)\[(.+)\]((?:http:\/\/|\/)\S+)(?=\s|$)/U",
  611. array(&$this, "refs"), $text);
  612. }
  613. // -------------------------------------------------------------
  614. function refs($m)
  615. {
  616. list(, $flag, $url) = $m;
  617. $this->urlrefs[$flag] = $url;
  618. return '';
  619. }
  620. // -------------------------------------------------------------
  621. function checkRefs($text)
  622. {
  623. return (isset($this->urlrefs[$text])) ? $this->urlrefs[$text] : $text;
  624. }
  625. // -------------------------------------------------------------
  626. function relURL($url)
  627. {
  628. $parts = parse_url($url);
  629. if ((empty($parts['scheme']) or @$parts['scheme'] == 'http') and
  630. empty($parts['host']) and
  631. preg_match('/^\w/', @$parts['path']))
  632. $url = $this->hu.$url;
  633. if ($this->restricted and !empty($parts['scheme']) and
  634. !in_array($parts['scheme'], $this->url_schemes))
  635. return '#';
  636. return $url;
  637. }
  638. // -------------------------------------------------------------
  639. function image($text)
  640. {
  641. return preg_replace_callback("/
  642. (?:[[{])? # pre
  643. \! # opening !
  644. (\<|\=|\>)?? # optional alignment atts
  645. ($this->c) # optional style,class atts
  646. (?:\. )? # optional dot-space
  647. ([^\s(!]+) # presume this is the src
  648. \s? # optional space
  649. (?:\(([^\)]+)\))? # optional title
  650. \! # closing
  651. (?::(\S+))? # optional href
  652. (?:[\]}]|(?=\s|$)) # lookahead: space or end of string
  653. /Ux", array(&$this, "fImage"), $text);
  654. }
  655. // -------------------------------------------------------------
  656. function fImage($m)
  657. {
  658. list(, $algn, $atts, $url) = $m;
  659. $atts = $this->pba($atts);
  660. $atts .= ($algn != '') ? ' align="' . $this->iAlign($algn) . '"' : '';
  661. $atts .= (isset($m[4])) ? ' title="' . $m[4] . '"' : '';
  662. $atts .= (isset($m[4])) ? ' alt="' . $m[4] . '"' : ' alt=""';
  663. $size = @getimagesize($url);
  664. if ($size) $atts .= " $size[3]";
  665. $href = (isset($m[5])) ? $this->checkRefs($m[5]) : '';
  666. $url = $this->checkRefs($url);
  667. $url = $this->relURL($url);
  668. $out = array(
  669. ($href) ? '<a href="' . $href . '">' : '',
  670. '<img src="' . $url . '"' . $atts . ' />',
  671. ($href) ? '</a>' : ''
  672. );
  673. return join('',$out);
  674. }
  675. // -------------------------------------------------------------
  676. function code($text)
  677. {
  678. $text = $this->doSpecial($text, '<code>', '</code>', 'fCode');
  679. $text = $this->doSpecial($text, '@', '@', 'fCode');
  680. $text = $this->doSpecial($text, '<pre>', '</pre>', 'fPre');
  681. return $text;
  682. }
  683. // -------------------------------------------------------------
  684. function fCode($m)
  685. {
  686. @list(, $before, $text, $after) = $m;
  687. if ($this->restricted)
  688. // $text is already escaped
  689. return $before.$this->shelve('<code>'.$text.'</code>').$after;
  690. else
  691. return $before.$this->shelve('<code>'.$this->encode_html($text).'</code>').$after;
  692. }
  693. // -------------------------------------------------------------
  694. function fPre($m)
  695. {
  696. @list(, $before, $text, $after) = $m;
  697. if ($this->restricted)
  698. // $text is already escaped
  699. return $before.'<pre>'.$this->shelve($text).'</pre>'.$after;
  700. else
  701. return $before.'<pre>'.$this->shelve($this->encode_html($text)).'</pre>'.$after;
  702. }
  703. // -------------------------------------------------------------
  704. function shelve($val)
  705. {
  706. $i = uniqid(rand());
  707. $this->shelf[$i] = $val;
  708. return $i;
  709. }
  710. // -------------------------------------------------------------
  711. function retrieve($text)
  712. {
  713. if (is_array($this->shelf))
  714. do {
  715. $old = $text;
  716. $text = strtr($text, $this->shelf);
  717. } while ($text != $old);
  718. return $text;
  719. }
  720. // -------------------------------------------------------------
  721. // NOTE: deprecated
  722. function incomingEntities($text)
  723. {
  724. return preg_replace("/&(?![#a-z0-9]+;)/i", "x%x%", $text);
  725. }
  726. // -------------------------------------------------------------
  727. // NOTE: deprecated
  728. function encodeEntities($text)
  729. {
  730. return (function_exists('mb_encode_numericentity'))
  731. ? $this->encode_high($text)
  732. : htmlentities($text, ENT_NOQUOTES, "utf-8");
  733. }
  734. // -------------------------------------------------------------
  735. // NOTE: deprecated
  736. function fixEntities($text)
  737. {
  738. /* de-entify any remaining angle brackets or ampersands */
  739. return str_replace(array("&gt;", "&lt;", "&amp;"),
  740. array(">", "<", "&"), $text);
  741. }
  742. // -------------------------------------------------------------
  743. function cleanWhiteSpace($text)
  744. {
  745. $out = str_replace("\r\n", "\n", $text);
  746. $out = preg_replace("/\n{3,}/", "\n\n", $out);
  747. $out = preg_replace("/\n *\n/", "\n\n", $out);
  748. $out = preg_replace('/"$/', "\" ", $out);
  749. return $out;
  750. }
  751. // -------------------------------------------------------------
  752. function doSpecial($text, $start, $end, $method='fSpecial')
  753. {
  754. return preg_replace_callback('/(^|\s|[[({>])'.preg_quote($start, '/').'(.*?)'.preg_quote($end, '/').'(\s|$|[\])}])?/ms',
  755. array(&$this, $method), $text);
  756. }
  757. // -------------------------------------------------------------
  758. function fSpecial($m)
  759. {
  760. // A special block like notextile or code
  761. @list(, $before, $text, $after) = $m;
  762. return $before.$this->shelve($this->encode_html($text)).$after;
  763. }
  764. // -------------------------------------------------------------
  765. function noTextile($text)
  766. {
  767. $text = $this->doSpecial($text, '<notextile>', '</notextile>', 'fTextile');
  768. return $this->doSpecial($text, '==', '==', 'fTextile');
  769. }
  770. // -------------------------------------------------------------
  771. function fTextile($m)
  772. {
  773. @list(, $before, $notextile, $after) = $m;
  774. #$notextile = str_replace(array_keys($modifiers), array_values($modifiers), $notextile);
  775. return $before.$this->shelve($notextile).$after;
  776. }
  777. // -------------------------------------------------------------
  778. function footnoteRef($text)
  779. {
  780. return preg_replace('/\b\[([0-9]+)\](\s)?/Ue',
  781. '$this->footnoteID(\'\1\',\'\2\')', $text);
  782. }
  783. // -------------------------------------------------------------
  784. function footnoteID($id, $t)
  785. {
  786. if (empty($this->fn[$id]))
  787. $this->fn[$id] = uniqid(rand());
  788. $fnid = $this->fn[$id];
  789. return '<sup class="footnote"><a href="#fn'.$fnid.'">'.$id.'</a></sup>'.$t;
  790. }
  791. // -------------------------------------------------------------
  792. function glyphs($text)
  793. {
  794. // fix: hackish
  795. $text = preg_replace('/"\z/', "\" ", $text);
  796. $pnc = '[[:punct:]]';
  797. $glyph_search = array(
  798. '/(\w)\'(\w)/', // apostrophe's
  799. '/(\s)\'(\d+\w?)\b(?!\')/', // back in '88
  800. '/(\S)\'(?=\s|'.$pnc.'|<|$)/', // single closing
  801. '/\'/', // single opening
  802. '/(\S)\"(?=\s|'.$pnc.'|<|$)/', // double closing
  803. '/"/', // double opening
  804. '/\b([A-Z][A-Z0-9]{2,})\b(?:[(]([^)]*)[)])/', // 3+ uppercase acronym
  805. '/\b([A-Z][A-Z\'\-]+[A-Z])(?=[\s.,\)>])/', // 3+ uppercase
  806. '/\b( )?\.{3}/', // ellipsis
  807. '/(\s?)--(\s?)/', // em dash
  808. '/\s-(?:\s|$)/', // en dash
  809. '/(\d+)( ?)x( ?)(?=\d+)/', // dimension sign
  810. '/\b ?[([]TM[])]/i', // trademark
  811. '/\b ?[([]R[])]/i', // registered
  812. '/\b ?[([]C[])]/i', // copyright
  813. );
  814. extract($this->glyph, EXTR_PREFIX_ALL, 'txt');
  815. $glyph_replace = array(
  816. '$1'.$txt_apostrophe.'$2', // apostrophe's
  817. '$1'.$txt_apostrophe.'$2', // back in '88
  818. '$1'.$txt_quote_single_close, // single closing
  819. $txt_quote_single_open, // single opening
  820. '$1'.$txt_quote_double_close, // double closing
  821. $txt_quote_double_open, // double opening
  822. '<acronym title="$2">$1</acronym>', // 3+ uppercase acronym
  823. '<span class="caps">$1</span>', // 3+ uppercase
  824. '$1'.$txt_ellipsis, // ellipsis
  825. '$1'.$txt_emdash.'$2', // em dash
  826. ' '.$txt_endash.' ', // en dash
  827. '$1$2'.$txt_dimension.'$3', // dimension sign
  828. $txt_trademark, // trademark
  829. $txt_registered, // registered
  830. $txt_copyright, // copyright
  831. );
  832. $text = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  833. foreach($text as $line) {
  834. if (!preg_match("/<.*>/", $line)) {
  835. $line = preg_replace($glyph_search, $glyph_replace, $line);
  836. }
  837. $glyph_out[] = $line;
  838. }
  839. return join('', $glyph_out);
  840. }
  841. // -------------------------------------------------------------
  842. function iAlign($in)
  843. {
  844. $vals = array(
  845. '<' => 'left',
  846. '=' => 'center',
  847. '>' => 'right');
  848. return (isset($vals[$in])) ? $vals[$in] : '';
  849. }
  850. // -------------------------------------------------------------
  851. function hAlign($in)
  852. {
  853. $vals = array(
  854. '<' => 'left',
  855. '=' => 'center',
  856. '>' => 'right',
  857. '<>' => 'justify');
  858. return (isset($vals[$in])) ? $vals[$in] : '';
  859. }
  860. // -------------------------------------------------------------
  861. function vAlign($in)
  862. {
  863. $vals = array(
  864. '^' => 'top',
  865. '-' => 'middle',
  866. '~' => 'bottom');
  867. return (isset($vals[$in])) ? $vals[$in] : '';
  868. }
  869. // -------------------------------------------------------------
  870. // NOTE: deprecated
  871. function encode_high($text, $charset = "UTF-8")
  872. {
  873. return mb_encode_numericentity($text, $this->cmap(), $charset);
  874. }
  875. // -------------------------------------------------------------
  876. // NOTE: deprecated
  877. function decode_high($text, $charset = "UTF-8")
  878. {
  879. return mb_decode_numericentity($text, $this->cmap(), $charset);
  880. }
  881. // -------------------------------------------------------------
  882. // NOTE: deprecated
  883. function cmap()
  884. {
  885. $f = 0xffff;
  886. $cmap = array(
  887. 0x0080, 0xffff, 0, $f);
  888. return $cmap;
  889. }
  890. // -------------------------------------------------------------
  891. function encode_html($str, $quotes=1)
  892. {
  893. $a = array(
  894. '&' => '&#38;',
  895. '<' => '&#60;',
  896. '>' => '&#62;',
  897. );
  898. if ($quotes) $a = $a + array(
  899. "'" => '&#39;',
  900. '"' => '&#34;',
  901. );
  902. return strtr($str, $a);
  903. }
  904. // -------------------------------------------------------------
  905. function textile_popup_help($name, $helpvar, $windowW, $windowH)
  906. {
  907. return ' <a target="_blank" href="http://www.textpattern.com/help/?item=' . $helpvar . '" onclick="window.open(this.href, \'popupwindow\', \'width=' . $windowW . ',height=' . $windowH . ',scrollbars,resizable\'); return false;">' . $name . '</a><br />';
  908. return $out;
  909. }
  910. // -------------------------------------------------------------
  911. // NOTE: deprecated
  912. function txtgps($thing)
  913. {
  914. if (isset($_POST[$thing])) {
  915. if (get_magic_quotes_gpc()) {
  916. return stripslashes($_POST[$thing]);
  917. }
  918. else {
  919. return $_POST[$thing];
  920. }
  921. }
  922. else {
  923. return '';
  924. }
  925. }
  926. // -------------------------------------------------------------
  927. // NOTE: deprecated
  928. function dump()
  929. {
  930. foreach (func_get_args() as $a)
  931. echo "\n<pre>",(is_array($a)) ? print_r($a) : $a, "</pre>\n";
  932. }
  933. // -------------------------------------------------------------
  934. function blockLite($text)
  935. {
  936. $this->btag = array('bq', 'p');
  937. return $this->block($text."\n\n");
  938. }
  939. } // end class
  940. ?>