PageRenderTime 65ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/inc/libs/clearbricks/text.wiki2xhtml/class.wiki2xhtml.php

https://bitbucket.org/dsls/dotclear
PHP | 1321 lines | 930 code | 179 blank | 212 comment | 210 complexity | ed616f056ce4506747b217cd9140ad49 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0
  1. <?php
  2. ###########################################################
  3. # /!\ /!\ /!\ EDIT THIS FILE IN UTF8 /!\ /!\ /!\ #
  4. ###########################################################
  5. # ***** BEGIN LICENSE BLOCK *****
  6. # This file is part of Clearbricks.
  7. # Copyright (c) 2003-2013 Olivier Meunier & Association Dotclear
  8. # All rights reserved.
  9. #
  10. # Clearbricks is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License as published by
  12. # the Free Software Foundation; either version 2 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # Clearbricks is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU General Public License
  21. # along with Clearbricks; if not, write to the Free Software
  22. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  23. #
  24. # ***** END LICENSE BLOCK *****
  25. #
  26. # Contributor(s):
  27. # Stephanie Booth
  28. # Mathieu Pillard
  29. # Christophe Bonijol
  30. # Jean-Charles Bagneris
  31. # Nicolas Chachereau
  32. # Jérôme Lipowicz
  33. #
  34. # Version : 3.2.9
  35. # Release date : 2013-12-24
  36. # History :
  37. #
  38. # 3.2.9
  39. # => <a name="anchor"></a> est remplacé par <a id="anchor"></a> pour assurer la compatibilité avec HTML5
  40. #
  41. # 3.2.8
  42. # => <acronym> est remplacé par <abbr> pour assurer la compatibilité avec HTML5
  43. #
  44. # 3.2.7
  45. # => Les styles d'alignement des images sont modifiables via les options
  46. #
  47. # 3.2.6
  48. # => Added ``inline html`` support
  49. #
  50. # 3.2.5
  51. # => Changed longdesc by title in images
  52. #
  53. # 3.2.4
  54. # => Auto links
  55. # => Code cleanup
  56. #
  57. # 3.2.3
  58. # Olivier
  59. # => PHP5 Strict
  60. #
  61. # 3.2.2
  62. # Olivier
  63. # => Changement de la gestion des URL spéciales
  64. #
  65. # 3.2.1
  66. # Olivier
  67. # => Changement syntaxe des macros
  68. #
  69. # 3.2
  70. # Olivier
  71. # => Changement de fonctionnement des macros
  72. # => Passage de fonctions externes pour les macros et les mots wiki
  73. #
  74. # 3.1d
  75. # Jérôme Lipowicz
  76. # => antispam
  77. # Olivier
  78. # => centrage d'image
  79. #
  80. # 3.1c
  81. # Olivier
  82. # => Possibilité d'échaper les | dans les marqueurs avec \
  83. #
  84. # 3.1b
  85. # Nicolas Chachereau
  86. # => Changement de regexp pour la correction syntaxique
  87. #
  88. # 3.1a
  89. # Olivier
  90. # => Bug du Call-time pass-by-reference
  91. #
  92. # 3.1
  93. # Olivier
  94. # => Ajout des macros «««..»»»
  95. # => Ajout des blocs vides øøø
  96. # => Ajout du niveau de titre paramétrable
  97. # => Option de blocage du parseur dans les <pre>
  98. # => Titres au format setext (experimental, désactivé)
  99. #
  100. # 3.0
  101. # Olivier => Récriture du parseur inline, plus d'erreur XHTML
  102. # => Ajout d'une vérification d'intégrité pour les listes
  103. # => Les acronymes sont maintenant dans un fichier texte
  104. # => Ajout d'un tag images ((..)), del --..-- et ins ++..++
  105. # => Plus possible de faire des liens JS [lien|javascript:...]
  106. # => Ajout des notes de bas de page §§...§§
  107. # => Ajout des mots wiki
  108. #
  109. # 2.5
  110. # Olivier => Récriture du code, plus besoin du saut de ligne entre blocs !=
  111. #
  112. # 2.0
  113. # Stephanie => correction des PCRE et ajout de fonctionnalités
  114. # Mathieu => ajout du strip-tags, implementation des options, reconnaissance automatique d'url, etc.
  115. # Olivier => chagement de active_link en active_urls
  116. # => ajout des options pour les blocs
  117. # => intégration de l'aide dans le code, avec les options
  118. # => début de quelque chose pour la reconnaissance auto d'url (avec Mat)
  119. # TODO :
  120. # Mathieu => active_wiki_urls (modifier wikiParseUrl ?)
  121. # => active_auto_urls
  122. #
  123. # * => ajouter des options.
  124. # => trouver un meilleur nom pour active_link ? (pour le jour ou ca sera tellement une usine
  125. # a gaz que on generera des tags <link> :)
  126. #
  127. # Wiki2xhtml
  128. class wiki2xhtml
  129. {
  130. public $__version__ = '3.2.8';
  131. public $T;
  132. public $opt;
  133. public $line;
  134. public $acro_table;
  135. public $foot_notes;
  136. public $macros;
  137. public $functions;
  138. public $tags;
  139. public $open_tags;
  140. public $close_tags;
  141. public $custom_tags = array();
  142. public $all_tags;
  143. public $tag_pattern;
  144. public $escape_table;
  145. public $allowed_inline = array();
  146. function __construct()
  147. {
  148. # Mise en place des options
  149. $this->setOpt('active_title',1); # Activation des titres !!!
  150. $this->setOpt('active_setext_title',0); # Activation des titres setext (EXPERIMENTAL)
  151. $this->setOpt('active_hr',1); # Activation des <hr />
  152. $this->setOpt('active_lists',1); # Activation des listes
  153. $this->setOpt('active_quote',1); # Activation du <blockquote>
  154. $this->setOpt('active_pre',1); # Activation du <pre>
  155. $this->setOpt('active_empty',1); # Activation du bloc vide øøø
  156. $this->setOpt('active_auto_urls',0); # Activation de la reconnaissance d'url
  157. $this->setOpt('active_auto_br',0); # Activation du saut de ligne automatique (dans les paragraphes)
  158. $this->setOpt('active_antispam',1); # Activation de l'antispam pour les emails
  159. $this->setOpt('active_urls',1); # Activation des liens []
  160. $this->setOpt('active_auto_img',1); # Activation des images automatiques dans les liens []
  161. $this->setOpt('active_img',1); # Activation des images (())
  162. $this->setOpt('active_anchor',1); # Activation des ancres ~...~
  163. $this->setOpt('active_em',1); # Activation du <em> ''...''
  164. $this->setOpt('active_strong',1); # Activation du <strong> __...__
  165. $this->setOpt('active_br',1); # Activation du <br /> %%%
  166. $this->setOpt('active_q',1); # Activation du <q> {{...}}
  167. $this->setOpt('active_code',1); # Activation du <code> @@...@@
  168. $this->setOpt('active_acronym',1); # Activation des acronymes
  169. $this->setOpt('active_ins',1); # Activation des ins ++..++
  170. $this->setOpt('active_del',1); # Activation des del --..--
  171. $this->setOpt('active_inline_html',1); # Activation du HTML inline ``...``
  172. $this->setOpt('active_footnotes',1); # Activation des notes de bas de page
  173. $this->setOpt('active_wikiwords',0); # Activation des mots wiki
  174. $this->setOpt('active_macros',1); # Activation des macros /// ///
  175. $this->setOpt('parse_pre',1); # Parser l'intérieur de blocs <pre> ?
  176. $this->setOpt('active_fr_syntax',1); # Corrections syntaxe FR
  177. $this->setOpt('first_title_level',3); # Premier niveau de titre <h..>
  178. $this->setOpt('note_prefix','wiki-footnote');
  179. $this->setOpt('note_str','<div class="footnotes"><h4>Notes</h4>%s</div>');
  180. $this->setOpt('note_str_single','<div class="footnotes"><h4>Note</h4>%s</div>');
  181. $this->setOpt('words_pattern',
  182. '((?<![A-Za-z0-9])([A-Z][a-z]+){2,}(?![A-Za-z0-9]))');
  183. $this->setOpt('auto_url_pattern',
  184. '%(?<![\[\|])(http://|https://|ftp://|news:)([^"\s\)!]+)%msu');
  185. $this->setOpt('acronyms_file',dirname(__FILE__).'/acronyms.txt');
  186. $this->setOpt('img_style_left','float:left; margin: 0 1em 1em 0;');
  187. $this->setOpt('img_style_center','display:block; margin:0 auto;');
  188. $this->setOpt('img_style_right','float:right; margin: 0 0 1em 1em;');
  189. $this->acro_table = $this->__getAcronyms();
  190. $this->foot_notes = array();
  191. $this->functions = array();
  192. $this->macros = array();
  193. $this->registerFunction('macro:html',array($this,'__macroHTML'));
  194. }
  195. function setOpt($option, $value)
  196. {
  197. $this->opt[$option] = $value;
  198. }
  199. function setOpts($options)
  200. {
  201. if (!is_array($options)) {
  202. return;
  203. }
  204. foreach ($options as $k => $v) {
  205. $this->opt[$k] = $v;
  206. }
  207. }
  208. function getOpt($option)
  209. {
  210. return (!empty($this->opt[$option])) ? $this->opt[$option] : false;
  211. }
  212. function registerFunction($type,$name)
  213. {
  214. if (is_callable($name)) {
  215. $this->functions[$type] = $name;
  216. }
  217. }
  218. function transform($in)
  219. {
  220. # Initialisation des tags
  221. $this->__initTags();
  222. $this->foot_notes = array();
  223. # Récupération des macros
  224. if ($this->getOpt('active_macros')) {
  225. $in = preg_replace_callback('#^///(.*?)///($|\r)#ms',array($this,'__getMacro'),$in);
  226. }
  227. # Vérification du niveau de titre
  228. if ($this->getOpt('first_title_level') > 4) {
  229. $this->setOpt('first_title_level',4);
  230. }
  231. $res = str_replace("\r", '', $in);
  232. $escape_pattern = array();
  233. # traitement des titres à la setext
  234. if ($this->getOpt('active_setext_title') && $this->getOpt('active_title')) {
  235. $res = preg_replace('/^(.*)\n[=]{5,}$/m','!!!$1',$res);
  236. $res = preg_replace('/^(.*)\n[-]{5,}$/m','!!$1',$res);
  237. }
  238. # Transformation des mots Wiki
  239. if ($this->getOpt('active_wikiwords') && $this->getOpt('words_pattern')) {
  240. $res = preg_replace('/'.$this->getOpt('words_pattern').'/msu','¶¶¶$1¶¶¶',$res);
  241. }
  242. # Transformation des URLs automatiques
  243. if ($this->getOpt('active_auto_urls'))
  244. {
  245. $active_urls = $this->getOpt('active_urls');
  246. $this->setOpt('active_urls',1);
  247. $this->__initTags();
  248. # If urls are not active, escape URLs tags
  249. if (!$active_urls)
  250. {
  251. $res = preg_replace(
  252. '%(?<!\\\\)(['.preg_quote(implode('',$this->tags['a'])).'])%msU',
  253. '\\\$1',$res
  254. );
  255. }
  256. # Transforms urls while preserving tags.
  257. $tree = preg_split($this->tag_pattern,$res,-1,PREG_SPLIT_DELIM_CAPTURE);
  258. foreach ($tree as &$leaf) {
  259. $leaf = preg_replace($this->getOpt('auto_url_pattern'),'[$1$2]',$leaf);
  260. }
  261. unset($leaf);
  262. $res = implode($tree);
  263. }
  264. $this->T = explode("\n",$res);
  265. $this->T[] = '';
  266. # Parse les blocs
  267. $res = $this->__parseBlocks();
  268. # Line break
  269. if ($this->getOpt('active_br')) {
  270. $res = preg_replace('/(?<!\\\)%%%/', '<br />', $res);
  271. $escape_pattern[] = '%%%';
  272. }
  273. # Nettoyage des \s en trop
  274. $res = preg_replace('/([\s]+)(<\/p>|<\/li>|<\/pre>)/u', '$2', $res);
  275. $res = preg_replace('/(<li>)([\s]+)/u', '$1', $res);
  276. # On vire les escapes
  277. if (!empty($escape_pattern)) {
  278. $res = preg_replace('/\\\('.implode('|',$escape_pattern).')/','$1',$res);
  279. }
  280. # On vire les MotWiki qui sont resté (dans les url...)
  281. if ($this->getOpt('active_wikiwords') && $this->getOpt('words_pattern')) {
  282. $res = preg_replace('/¶¶¶'.$this->getOpt('words_pattern').'¶¶¶/msu','$1',$res);
  283. }
  284. # On remet les macros
  285. if ($this->getOpt('active_macros')) {
  286. $res = preg_replace_callback('/^##########MACRO#([0-9]+)#$/ms',array($this,'__putMacro'),$res);
  287. }
  288. # Auto line break dans les paragraphes
  289. if ($this->getOpt('active_auto_br')) {
  290. $res = preg_replace_callback('%(<p>)(.*?)(</p>)%msu',array($this,'__autoBR'),$res);
  291. }
  292. # On ajoute les notes
  293. if (count($this->foot_notes) > 0)
  294. {
  295. $res_notes = '';
  296. $i = 1;
  297. foreach ($this->foot_notes as $k => $v) {
  298. $res_notes .= "\n".'<p>[<a href="#rev-'.$k.'" id="'.$k.'">'.$i.'</a>] '.$v.'</p>';
  299. $i++;
  300. }
  301. $res .= sprintf("\n".(count($this->foot_notes) > 1 ? $this->getOpt('note_str') : $this->getOpt('note_str_single'))."\n",$res_notes);
  302. }
  303. return $res;
  304. }
  305. /* PRIVATE
  306. --------------------------------------------------- */
  307. function __initTags()
  308. {
  309. $tags = array(
  310. 'em' => array("''","''"),
  311. 'strong' => array('__','__'),
  312. 'abbr' => array('??','??'),
  313. 'a' => array('[',']'),
  314. 'img' => array('((','))'),
  315. 'q' => array('{{','}}'),
  316. 'code' => array('@@','@@'),
  317. 'anchor' => array('~','~'),
  318. 'del' => array('--','--'),
  319. 'ins' => array('++','++'),
  320. 'inline' => array('``','``'),
  321. 'note' => array('$$','$$'),
  322. 'word' => array('¶¶¶','¶¶¶')
  323. );
  324. $this->linetags = array(
  325. 'empty' => 'øøø',
  326. 'title' => '([!]{1,4})',
  327. 'hr' => '[-]{4}[- ]',
  328. 'quote' => '(&gt;|;:)',
  329. 'lists' => '([*#]+)',
  330. 'pre' => '[ ]{1}'
  331. );
  332. $this->tags = array_merge($tags,$this->custom_tags);
  333. # Suppression des tags selon les options
  334. if (!$this->getOpt('active_urls')) {
  335. unset($this->tags['a']);
  336. }
  337. if (!$this->getOpt('active_img')) {
  338. unset($this->tags['img']);
  339. }
  340. if (!$this->getOpt('active_anchor')) {
  341. unset($this->tags['anchor']);
  342. }
  343. if (!$this->getOpt('active_em')) {
  344. unset($this->tags['em']);
  345. }
  346. if (!$this->getOpt('active_strong')) {
  347. unset($this->tags['strong']);
  348. }
  349. if (!$this->getOpt('active_q')) {
  350. unset($this->tags['q']);
  351. }
  352. if (!$this->getOpt('active_code')) {
  353. unset($this->tags['code']);
  354. }
  355. if (!$this->getOpt('active_acronym')) {
  356. unset($this->tags['abbr']);
  357. }
  358. if (!$this->getOpt('active_ins')) {
  359. unset($this->tags['ins']);
  360. }
  361. if (!$this->getOpt('active_del')) {
  362. unset($this->tags['del']);
  363. }
  364. if (!$this->getOpt('active_inline_html')) {
  365. unset($this->tags['inline']);
  366. }
  367. if (!$this->getOpt('active_footnotes')) {
  368. unset($this->tags['note']);
  369. }
  370. if (!$this->getOpt('active_wikiwords')) {
  371. unset($this->tags['word']);
  372. }
  373. # Suppression des tags de début de ligne selon les options
  374. if (!$this->getOpt('active_empty')) {
  375. unset($this->linetags['empty']);
  376. }
  377. if (!$this->getOpt('active_title')) {
  378. unset($this->linetags['title']);
  379. }
  380. if (!$this->getOpt('active_hr')) {
  381. unset($this->linetags['hr']);
  382. }
  383. if (!$this->getOpt('active_quote')) {
  384. unset($this->linetags['quote']);
  385. }
  386. if (!$this->getOpt('active_lists')) {
  387. unset($this->linetags['lists']);
  388. }
  389. if (!$this->getOpt('active_pre')) {
  390. unset($this->linetags['pre']);
  391. }
  392. $this->open_tags = $this->__getTags();
  393. $this->close_tags = $this->__getTags(false);
  394. $this->all_tags = $this->__getAllTags();
  395. $this->tag_pattern = $this->__getTagsPattern();
  396. $this->escape_table = $this->all_tags;
  397. array_walk($this->escape_table,create_function('&$a','$a = \'\\\\\'.$a;'));
  398. }
  399. function __getTags($open=true)
  400. {
  401. $res = array();
  402. foreach ($this->tags as $k => $v) {
  403. $res[$k] = ($open) ? $v[0] : $v[1];
  404. }
  405. return $res;
  406. }
  407. function __getAllTags()
  408. {
  409. $res = array();
  410. foreach ($this->tags as $v) {
  411. $res[] = $v[0];
  412. $res[] = $v[1];
  413. }
  414. return array_values(array_unique($res));
  415. }
  416. function __getTagsPattern($escape=false)
  417. {
  418. $res = $this->all_tags;
  419. array_walk($res,create_function('&$a','$a = preg_quote($a,"/");'));
  420. if (!$escape) {
  421. return '/(?<!\\\)('.implode('|',$res).')/';
  422. } else {
  423. return '('.implode('|',$res).')';
  424. }
  425. }
  426. /* Blocs
  427. --------------------------------------------------- */
  428. function __parseBlocks()
  429. {
  430. $mode = $type = null;
  431. $res = '';
  432. $max = count($this->T);
  433. for ($i=0; $i<$max; $i++)
  434. {
  435. $pre_mode = $mode;
  436. $pre_type = $type;
  437. $end = ($i+1 == $max);
  438. $line = $this->__getLine($i,$type,$mode);
  439. if ($type != 'pre' || $this->getOpt('parse_pre')) {
  440. $line = $this->__inlineWalk($line);
  441. }
  442. $res .= $this->__closeLine($type,$mode,$pre_type,$pre_mode);
  443. $res .= $this->__openLine($type,$mode,$pre_type,$pre_mode);
  444. # P dans les blockquotes
  445. if ($type == 'blockquote' && trim($line) == '' && $pre_type == $type) {
  446. $res .= "</p>\n<p>";
  447. }
  448. # Correction de la syntaxe FR dans tous sauf pre et hr
  449. # Sur idée de Christophe Bonijol
  450. # Changement de regex (Nicolas Chachereau)
  451. if ($this->getOpt('active_fr_syntax') && $type != null && $type != 'pre' && $type != 'hr') {
  452. $line = preg_replace('%[ ]+([:?!;\x{00BB}](\s|$))%u','&nbsp;$1',$line);
  453. $line = preg_replace('%(\x{00AB})[ ]+%u','$1&nbsp;',$line);
  454. }
  455. $res .= $line;
  456. }
  457. return trim($res);
  458. }
  459. function __getLine($i,&$type,&$mode)
  460. {
  461. $pre_type = $type;
  462. $pre_mode = $mode;
  463. $type = $mode = null;
  464. if (empty($this->T[$i])) {
  465. return false;
  466. }
  467. $line = htmlspecialchars($this->T[$i],ENT_NOQUOTES);
  468. # Ligne vide
  469. if (empty($line))
  470. {
  471. $type = null;
  472. }
  473. elseif ($this->getOpt('active_empty') && preg_match('/^øøø(.*)$/',$line,$cap))
  474. {
  475. $type = null;
  476. $line = trim($cap[1]);
  477. }
  478. # Titre
  479. elseif ($this->getOpt('active_title') && preg_match('/^([!]{1,4})(.*)$/',$line,$cap))
  480. {
  481. $type = 'title';
  482. $mode = strlen($cap[1]);
  483. $line = trim($cap[2]);
  484. }
  485. # Ligne HR
  486. elseif ($this->getOpt('active_hr') && preg_match('/^[-]{4}[- ]*$/',$line))
  487. {
  488. $type = 'hr';
  489. $line = null;
  490. }
  491. # Blockquote
  492. elseif ($this->getOpt('active_quote') && preg_match('/^(&gt;|;:)(.*)$/',$line,$cap))
  493. {
  494. $type = 'blockquote';
  495. $line = trim($cap[2]);
  496. }
  497. # Liste
  498. elseif ($this->getOpt('active_lists') && preg_match('/^([*#]+)(.*)$/',$line,$cap))
  499. {
  500. $type = 'list';
  501. $mode = $cap[1];
  502. $valid = true;
  503. # Vérification d'intégrité
  504. $dl = ($type != $pre_type) ? 0 : strlen($pre_mode);
  505. $d = strlen($mode);
  506. $delta = $d-$dl;
  507. if ($delta < 0 && strpos($pre_mode,$mode) !== 0) {
  508. $valid = false;
  509. }
  510. if ($delta > 0 && $type == $pre_type && strpos($mode,$pre_mode) !== 0) {
  511. $valid = false;
  512. }
  513. if ($delta == 0 && $mode != $pre_mode) {
  514. $valid = false;
  515. }
  516. if ($delta > 1) {
  517. $valid = false;
  518. }
  519. if (!$valid) {
  520. $type = 'p';
  521. $mode = null;
  522. $line = '<br />'.$line;
  523. } else {
  524. $line = trim($cap[2]);
  525. }
  526. }
  527. # Préformaté
  528. elseif ($this->getOpt('active_pre') && preg_match('/^[ ]{1}(.*)$/',$line,$cap))
  529. {
  530. $type = 'pre';
  531. $line = $cap[1];
  532. }
  533. # Paragraphe
  534. else {
  535. $type = 'p';
  536. if (preg_match('/^\\\((?:('.implode('|',$this->linetags).')).*)$/',$line,$cap)) {
  537. $line = $cap[1];
  538. }
  539. $line = trim($line);
  540. }
  541. return $line;
  542. }
  543. function __openLine($type,$mode,$pre_type,$pre_mode)
  544. {
  545. $open = ($type != $pre_type);
  546. if ($open && $type == 'p')
  547. {
  548. return "\n<p>";
  549. }
  550. elseif ($open && $type == 'blockquote')
  551. {
  552. return "\n<blockquote><p>";
  553. }
  554. elseif (($open || $mode != $pre_mode) && $type == 'title')
  555. {
  556. $fl = $this->getOpt('first_title_level');
  557. $fl = $fl+3;
  558. $l = $fl-$mode;
  559. return "\n<h".($l).'>';
  560. }
  561. elseif ($open && $type == 'pre')
  562. {
  563. return "\n<pre>";
  564. }
  565. elseif ($open && $type == 'hr')
  566. {
  567. return "\n<hr />";
  568. }
  569. elseif ($type == 'list')
  570. {
  571. $dl = ($open) ? 0 : strlen($pre_mode);
  572. $d = strlen($mode);
  573. $delta = $d-$dl;
  574. $res = '';
  575. if($delta > 0) {
  576. if(substr($mode, -1, 1) == '*') {
  577. $res .= "<ul>\n";
  578. } else {
  579. $res .= "<ol>\n";
  580. }
  581. } elseif ($delta < 0) {
  582. $res .= "</li>\n";
  583. for($j = 0; $j < abs($delta); $j++) {
  584. if (substr($pre_mode,(0 - $j - 1), 1) == '*') {
  585. $res .= "</ul>\n</li>\n";
  586. } else {
  587. $res .= "</ol>\n</li>\n";
  588. }
  589. }
  590. } else {
  591. $res .= "</li>\n";
  592. }
  593. return $res."<li>";
  594. }
  595. else
  596. {
  597. return null;
  598. }
  599. }
  600. function __closeLine($type,$mode,$pre_type,$pre_mode)
  601. {
  602. $close = ($type != $pre_type);
  603. if ($close && $pre_type == 'p')
  604. {
  605. return "</p>\n";
  606. }
  607. elseif ($close && $pre_type == 'blockquote')
  608. {
  609. return "</p></blockquote>\n";
  610. }
  611. elseif (($close || $mode != $pre_mode) && $pre_type == 'title')
  612. {
  613. $fl = $this->getOpt('first_title_level');
  614. $fl = $fl+3;
  615. $l = $fl-$pre_mode;
  616. return '</h'.($l).">\n";
  617. }
  618. elseif ($close && $pre_type == 'pre')
  619. {
  620. return "</pre>\n";
  621. }
  622. elseif ($close && $pre_type == 'list')
  623. {
  624. $res = '';
  625. for($j = 0; $j < strlen($pre_mode); $j++) {
  626. if(substr($pre_mode,(0 - $j - 1), 1) == '*') {
  627. $res .= "</li>\n</ul>\n";
  628. } else {
  629. $res .= "</li>\n</ol>\n";
  630. }
  631. }
  632. return $res;
  633. }
  634. else
  635. {
  636. return "\n";
  637. }
  638. }
  639. /* Inline
  640. --------------------------------------------------- */
  641. function __inlineWalk($str,$allow_only=null)
  642. {
  643. $tree = preg_split($this->tag_pattern,$str,-1,PREG_SPLIT_DELIM_CAPTURE);
  644. $res = '';
  645. for ($i=0; $i<count($tree); $i++)
  646. {
  647. $attr = '';
  648. if (in_array($tree[$i],array_values($this->open_tags)) &&
  649. ($allow_only == null || in_array(array_search($tree[$i],$this->open_tags),$allow_only)))
  650. {
  651. $tag = array_search($tree[$i],$this->open_tags);
  652. $tag_type = 'open';
  653. if (($tidy = $this->__makeTag($tree,$tag,$i,$i,$attr,$tag_type)) !== false)
  654. {
  655. if ($tag != '') {
  656. $res .= '<'.$tag.$attr;
  657. $res .= ($tag_type == 'open') ? '>' : ' />';
  658. }
  659. $res .= $tidy;
  660. }
  661. else
  662. {
  663. $res .= $tree[$i];
  664. }
  665. }
  666. else
  667. {
  668. $res .= $tree[$i];
  669. }
  670. }
  671. # Suppression des echappements
  672. $res = str_replace($this->escape_table,$this->all_tags,$res);
  673. return $res;
  674. }
  675. function __makeTag(&$tree,&$tag,$position,&$j,&$attr,&$type)
  676. {
  677. $res = '';
  678. $closed = false;
  679. $itag = $this->close_tags[$tag];
  680. # Recherche fermeture
  681. for ($i=$position+1;$i<count($tree);$i++)
  682. {
  683. if ($tree[$i] == $itag)
  684. {
  685. $closed = true;
  686. break;
  687. }
  688. }
  689. # Résultat
  690. if ($closed)
  691. {
  692. for ($i=$position+1;$i<count($tree);$i++)
  693. {
  694. if ($tree[$i] != $itag)
  695. {
  696. $res .= $tree[$i];
  697. }
  698. else
  699. {
  700. switch ($tag)
  701. {
  702. case 'a':
  703. $res = $this->__parseLink($res,$tag,$attr,$type);
  704. break;
  705. case 'img':
  706. $type = 'close';
  707. $res = $this->__parseImg($res,$attr);
  708. break;
  709. case 'abbr':
  710. $res = $this->__parseAcronym($res,$attr);
  711. break;
  712. case 'q':
  713. $res = $this->__parseQ($res,$attr);
  714. break;
  715. case 'anchor':
  716. $tag = 'a';
  717. $res = $this->__parseAnchor($res,$attr);
  718. break;
  719. case 'note':
  720. $tag = '';
  721. $res = $this->__parseNote($res);
  722. break;
  723. case 'inline':
  724. $tag = '';
  725. $res = $this->__parseInlineHTML($res);
  726. break;
  727. case 'word':
  728. $res = $this->parseWikiWord($res,$tag,$attr,$type);
  729. break;
  730. default :
  731. $res = $this->__inlineWalk($res);
  732. break;
  733. }
  734. if ($type == 'open' && $tag != '') {
  735. $res .= '</'.$tag.'>';
  736. }
  737. $j = $i;
  738. break;
  739. }
  740. }
  741. return $res;
  742. }
  743. else
  744. {
  745. return false;
  746. }
  747. }
  748. function __splitTagsAttr($str)
  749. {
  750. $res = preg_split('/(?<!\\\)\|/',$str);
  751. foreach ($res as $k => $v) {
  752. $res[$k] = str_replace("\|",'|',$v);
  753. }
  754. return $res;
  755. }
  756. # Antispam (Jérôme Lipowicz)
  757. function __antiSpam($str)
  758. {
  759. $encoded = bin2hex($str);
  760. $encoded = chunk_split($encoded, 2, '%');
  761. $encoded = '%'.substr($encoded, 0, strlen($encoded) - 1);
  762. return $encoded;
  763. }
  764. function __parseLink($str,&$tag,&$attr,&$type)
  765. {
  766. $n_str = $this->__inlineWalk($str,array('abbr','img','em','strong'));
  767. $data = $this->__splitTagsAttr($n_str);
  768. $no_image = false;
  769. # Only URL in data
  770. if (count($data) == 1)
  771. {
  772. $url = trim($str);
  773. $content = strlen($url) > 35 ? substr($url,0,35).'...' : $url;
  774. $lang = '';
  775. $title = $url;
  776. }
  777. elseif (count($data) > 1)
  778. {
  779. $url = trim($data[1]);
  780. $content = $data[0];
  781. $lang = (!empty($data[2])) ? $this->protectAttr($data[2],true) : '';
  782. $title = (!empty($data[3])) ? $data[3] : '';
  783. $no_image = (!empty($data[4])) ? (boolean) $data[4] : false;
  784. }
  785. # Remplacement si URL spéciale
  786. $this->__specialUrls($url,$content,$lang,$title);
  787. # On vire les &nbsp; dans l'url
  788. $url = str_replace('&nbsp;',' ',$url);
  789. if (preg_match('/^(.+)[.](gif|jpg|jpeg|png)$/', $url) && !$no_image && $this->getOpt('active_auto_img'))
  790. {
  791. # On ajoute les dimensions de l'image si locale
  792. # Idée de Stephanie
  793. $img_size = null;
  794. if (!preg_match('#[a-zA-Z]+://#', $url)) {
  795. if (preg_match('#^/#',$url)) {
  796. $path_img = $_SERVER['DOCUMENT_ROOT'] . $url;
  797. } else {
  798. $path_img = $url;
  799. }
  800. $img_size = @getimagesize($path_img);
  801. }
  802. $attr = ' src="'.$this->protectAttr($this->protectUrls($url)).'"'.
  803. $attr .= (count($data) > 1) ? ' alt="'.$this->protectAttr($content).'"' : ' alt=""';
  804. $attr .= ($lang) ? ' lang="'.$lang.'"' : '';
  805. $attr .= ($title) ? ' title="'.$this->protectAttr($title).'"' : '';
  806. $attr .= (is_array($img_size)) ? ' '.$img_size[3] : '';
  807. $tag = 'img';
  808. $type = 'close';
  809. return null;
  810. }
  811. else
  812. {
  813. if ($this->getOpt('active_antispam') && preg_match('/^mailto:/',$url)) {
  814. $content = $content == $url ? preg_replace('%^mailto:%','',$content) : $content;
  815. $url = 'mailto:'.$this->__antiSpam(substr($url,7));
  816. }
  817. $attr = ' href="'.$this->protectAttr($this->protectUrls($url)).'"';
  818. $attr .= ($lang) ? ' hreflang="'.$lang.'"' : '';
  819. $attr .= ($title) ? ' title="'.$this->protectAttr($title).'"' : '';
  820. return $content;
  821. }
  822. }
  823. function __specialUrls(&$url,&$content,&$lang,&$title)
  824. {
  825. foreach ($this->functions as $k => $v)
  826. {
  827. if (strpos($k,'url:') === 0 && strpos($url,substr($k,4)) === 0)
  828. {
  829. $res = call_user_func($v,$url,$content);
  830. $url = isset($res['url']) ? $res['url'] : $url;
  831. $content = isset($res['content']) ? $res['content'] : $content;
  832. $lang = isset($res['lang']) ? $res['lang'] : $lang;
  833. $title = isset($res['title']) ? $res['title'] : $title;
  834. break;
  835. }
  836. }
  837. }
  838. function __parseImg($str,&$attr)
  839. {
  840. $data = $this->__splitTagsAttr($str);
  841. $alt = '';
  842. $url = $data[0];
  843. if (!empty($data[1])) {
  844. $alt = $data[1];
  845. }
  846. $attr = ' src="'.$this->protectAttr($this->protectUrls($url)).'"';
  847. $attr .= ' alt="'.$this->protectAttr($alt).'"';
  848. if (!empty($data[2])) {
  849. $data[2] = strtoupper($data[2]);
  850. $style = '';
  851. if ($data[2] == 'G' || $data[2] == 'L') {
  852. $style = $this->getOpt('img_style_left');
  853. } elseif ($data[2] == 'D' || $data[2] == 'R') {
  854. $style = $this->getOpt('img_style_right');
  855. } elseif ($data[2] == 'C') {
  856. $style = $this->getOpt('img_style_center');
  857. }
  858. if ($style != '') {
  859. $attr .= ' style="'.$style.'"';
  860. }
  861. }
  862. if (!empty($data[3])) {
  863. $attr .= ' title="'.$this->protectAttr($data[3]).'"';
  864. }
  865. return null;
  866. }
  867. function __parseQ($str,&$attr)
  868. {
  869. $str = $this->__inlineWalk($str);
  870. $data = $this->__splitTagsAttr($str);
  871. $content = $data[0];
  872. $lang = (!empty($data[1])) ? $this->protectAttr($data[1],true) : '';
  873. $attr .= (!empty($lang)) ? ' lang="'.$lang.'"' : '';
  874. $attr .= (!empty($data[2])) ? ' cite="'.$this->protectAttr($this->protectUrls($data[2])).'"' : '';
  875. return $content;
  876. }
  877. function __parseAnchor($str,&$attr)
  878. {
  879. $name = $this->protectAttr($str,true);
  880. if ($name != '') {
  881. $attr = ' id="'.$name.'"';
  882. }
  883. return null;
  884. }
  885. function __parseNote($str)
  886. {
  887. $i = count($this->foot_notes)+1;
  888. $id = $this->getOpt('note_prefix').'-'.$i;
  889. $this->foot_notes[$id] = $this->__inlineWalk($str);
  890. return '<sup>\[<a href="#'.$id.'" id="rev-'.$id.'">'.$i.'</a>\]</sup>';
  891. }
  892. function __parseInlineHTML($str)
  893. {
  894. return str_replace(array('&gt;','&lt;'),array('>','<'),$str);
  895. }
  896. # Obtenir un acronyme
  897. function __parseAcronym($str,&$attr)
  898. {
  899. $data = $this->__splitTagsAttr($str);
  900. $acronym = $data[0];
  901. $title = $lang = '';
  902. if (count($data) > 1)
  903. {
  904. $title = $data[1];
  905. $lang = (!empty($data[2])) ? $this->protectAttr($data[2],true) : '';
  906. }
  907. if ($title == '' && !empty($this->acro_table[$acronym])) {
  908. $title = $this->acro_table[$acronym];
  909. }
  910. $attr = ($title) ? ' title="'.$this->protectAttr($title).'"' : '';
  911. $attr .= ($lang) ? ' lang="'.$lang.'"' : '';
  912. return $acronym;
  913. }
  914. # Définition des acronymes, dans le fichier acronyms.txt
  915. function __getAcronyms()
  916. {
  917. $file = $this->getOpt('acronyms_file');
  918. $res = array();
  919. if (file_exists($file))
  920. {
  921. if (($fc = @file($file)) !== false)
  922. {
  923. foreach ($fc as $v)
  924. {
  925. $v = trim($v);
  926. if ($v != '')
  927. {
  928. $p = strpos($v,':');
  929. $K = (string) trim(substr($v,0,$p));
  930. $V = (string) trim(substr($v,($p+1)));
  931. if ($K) {
  932. $res[$K] = $V;
  933. }
  934. }
  935. }
  936. }
  937. }
  938. return $res;
  939. }
  940. # Mots wiki (pour héritage)
  941. function parseWikiWord($str,&$tag,&$attr,&$type)
  942. {
  943. $tag = $attr = '';
  944. if (isset($this->functions['wikiword'])) {
  945. return call_user_func($this->functions['wikiword'],$str);
  946. }
  947. return $str;
  948. }
  949. /* Protection des attributs */
  950. function protectAttr($str,$name=false)
  951. {
  952. if ($name && !preg_match('/^[A-Za-z][A-Za-z0-9_:.-]*$/',$str)) {
  953. return '';
  954. }
  955. return str_replace(array("'",'"'),array('&#039;','&quot;'),$str);
  956. }
  957. /* Protection des urls */
  958. function protectUrls($str)
  959. {
  960. if (preg_match('/^javascript:/',$str)) {
  961. $str = '#';
  962. }
  963. return $str;
  964. }
  965. /* Auto BR */
  966. function __autoBR($m)
  967. {
  968. return $m[1].str_replace("\n","<br />\n",$m[2]).$m[3];
  969. }
  970. /* Macro
  971. --------------------------------------------------- */
  972. function __getMacro($s)
  973. {
  974. $s = is_array($s) ? $s[1] : $s;
  975. $this->macros[] = str_replace('\"','"',$s);
  976. return 'øøø##########MACRO#'.(count($this->macros)-1).'#';
  977. }
  978. function __putMacro($id)
  979. {
  980. $id = is_array($id) ? (integer) $id[1] : (integer) $id;
  981. if (isset($this->macros[$id]))
  982. {
  983. $content = str_replace("\r",'',$this->macros[$id]);
  984. $c = explode("\n",$content);
  985. # première ligne, premier mot
  986. $fl = trim($c[0]);
  987. $fw = $fl;
  988. if ($fl) {
  989. if (strpos($fl,' ') !== false) {
  990. $fw = substr($fl,0,strpos($fl,' '));
  991. }
  992. $content = implode("\n",array_slice($c,1));
  993. }
  994. if ($c[0] == "\n") {
  995. $content = implode("\n",array_slice($c,1));
  996. }
  997. if ($fw)
  998. {
  999. if (isset($this->functions['macro:'.$fw]))
  1000. {
  1001. return call_user_func($this->functions['macro:'.$fw],$content,$fl);
  1002. }
  1003. }
  1004. # Si on n'a rien pu faire, on retourne le tout sous
  1005. # forme de <pre>
  1006. return '<pre>'.htmlspecialchars($this->macros[$id]).'</pre>';
  1007. }
  1008. return null;
  1009. }
  1010. function __macroHTML($s)
  1011. {
  1012. return $s;
  1013. }
  1014. /* Aide et debug
  1015. --------------------------------------------------- */
  1016. function help()
  1017. {
  1018. $help['b'] = array();
  1019. $help['i'] = array();
  1020. $help['b'][] = 'Laisser une ligne vide entre chaque bloc <em>de même nature</em>.';
  1021. $help['b'][] = '<strong>Paragraphe</strong> : du texte et une ligne vide';
  1022. if ($this->getOpt('active_title')) {
  1023. $help['b'][] = '<strong>Titre</strong> : <code>!!!</code>, <code>!!</code>, '.
  1024. '<code>!</code> pour des titres plus ou moins importants';
  1025. }
  1026. if ($this->getOpt('active_hr')) {
  1027. $help['b'][] = '<strong>Trait horizontal</strong> : <code>----</code>';
  1028. }
  1029. if ($this->getOpt('active_lists')) {
  1030. $help['b'][] = '<strong>Liste</strong> : ligne débutant par <code>*</code> ou '.
  1031. '<code>#</code>. Il est possible de mélanger les listes '.
  1032. '(<code>*#*</code>) pour faire des listes de plusieurs niveaux. '.
  1033. 'Respecter le style de chaque niveau';
  1034. }
  1035. if ($this->getOpt('active_pre')) {
  1036. $help['b'][] = '<strong>Texte préformaté</strong> : espace devant chaque ligne de texte';
  1037. }
  1038. if ($this->getOpt('active_quote')) {
  1039. $help['b'][] = '<strong>Bloc de citation</strong> : <code>&gt;</code> ou '.
  1040. '<code>;:</code> devant chaque ligne de texte';
  1041. }
  1042. if ($this->getOpt('active_fr_syntax')) {
  1043. $help['i'][] = 'La correction de ponctuation est active. Un espace '.
  1044. 'insécable remplacera automatiquement tout espace '.
  1045. 'précédant les marques ";","?",":" et "!".';
  1046. }
  1047. if ($this->getOpt('active_em')) {
  1048. $help['i'][] = '<strong>Emphase</strong> : deux apostrophes <code>\'\'texte\'\'</code>';
  1049. }
  1050. if ($this->getOpt('active_strong')) {
  1051. $help['i'][] = '<strong>Forte emphase</strong> : deux soulignés <code>__texte__</code>';
  1052. }
  1053. if ($this->getOpt('active_br')) {
  1054. $help['i'][] = '<strong>Retour forcé à la ligne</strong> : <code>%%%</code>';
  1055. }
  1056. if ($this->getOpt('active_ins')) {
  1057. $help['i'][] = '<strong>Insertion</strong> : deux plus <code>++texte++</code>';
  1058. }
  1059. if ($this->getOpt('active_del')) {
  1060. $help['i'][] = '<strong>Suppression</strong> : deux moins <code>--texte--</code>';
  1061. }
  1062. if ($this->getOpt('active_urls')) {
  1063. $help['i'][] = '<strong>Lien</strong> : <code>[url]</code>, <code>[nom|url]</code>, '.
  1064. '<code>[nom|url|langue]</code> ou <code>[nom|url|langue|titre]</code>.';
  1065. $help['i'][] = '<strong>Image</strong> : comme un lien mais avec une extension d\'image.'.
  1066. '<br />Pour désactiver la reconnaissance d\'image mettez 0 dans un dernier '.
  1067. 'argument. Par exemple <code>[image|image.gif||0]</code> fera un lien vers l\'image au '.
  1068. 'lieu de l\'afficher.'.
  1069. '<br />Il est conseillé d\'utiliser la nouvelle syntaxe.';
  1070. }
  1071. if ($this->getOpt('active_img')) {
  1072. $help['i'][] = '<strong>Image</strong> (nouvelle syntaxe) : '.
  1073. '<code>((url|texte alternatif))</code>, '.
  1074. '<code>((url|texte alternatif|position))</code> ou '.
  1075. '<code>((url|texte alternatif|position|description longue))</code>. '.
  1076. '<br />La position peut prendre les valeur L ou G (gauche), R ou D (droite) ou C (centré).';
  1077. }
  1078. if ($this->getOpt('active_anchor')) {
  1079. $help['i'][] = '<strong>Ancre</strong> : <code>~ancre~</code>';
  1080. }
  1081. if ($this->getOpt('active_acronym')) {
  1082. $help['i'][] = '<strong>Acronyme</strong> : <code>??acronyme??</code> ou '.
  1083. '<code>??acronyme|titre??</code>';
  1084. }
  1085. if ($this->getOpt('active_q')) {
  1086. $help['i'][] = '<strong>Citation</strong> : <code>{{citation}}</code>, '.
  1087. '<code>{{citation|langue}}</code> ou <code>{{citation|langue|url}}</code>';
  1088. }
  1089. if ($this->getOpt('active_code')) {
  1090. $help['i'][] = '<strong>Code</strong> : <code>@@code ici@@</code>';
  1091. }
  1092. if ($this->getOpt('active_footnotes')) {
  1093. $help['i'][] = '<strong>Note de bas de page</strong> : <code>$$Corps de la note$$</code>';
  1094. }
  1095. $res = '<dl class="wikiHelp">';
  1096. $res .= '<dt>Blocs</dt><dd>';
  1097. if (count($help['b']) > 0)
  1098. {
  1099. $res .= '<ul><li>';
  1100. $res .= implode('&nbsp;;</li><li>', $help['b']);
  1101. $res .= '.</li></ul>';
  1102. }
  1103. $res .= '</dd>';
  1104. $res .= '<dt>Éléments en ligne</dt><dd>';
  1105. if (count($help['i']) > 0)
  1106. {
  1107. $res .= '<ul><li>';
  1108. $res .= implode('&nbsp;;</li><li>', $help['i']);
  1109. $res .= '.</li></ul>';
  1110. }
  1111. $res .= '</dd>';
  1112. $res .= '</dl>';
  1113. return $res;
  1114. }
  1115. /*
  1116. function debug()
  1117. {
  1118. $mode = $type = null;
  1119. $max = count($this->T);
  1120. $res =
  1121. '<table border="1">'.
  1122. '<tr><th>p-mode</th><th>p-type</th><th>mode</th><th>type</th><th>chaine</th></tr>';
  1123. for ($i=0; $i<$max; $i++)
  1124. {
  1125. $pre_mode = $mode;
  1126. $pre_type = $type;
  1127. $line = $this->__getLine($i,$type,$mode);
  1128. $res .=
  1129. '<tr><td>'.$pre_mode.'</td><td>'.$pre_type.'</td>'.
  1130. '<td>'.$mode.'</td><td>'.$type.'</td><td>'.$line.'</td></tr>';
  1131. }
  1132. $res .= '</table>';
  1133. return $res;
  1134. }
  1135. //*/
  1136. }