PageRenderTime 58ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/text.wiki2xhtml/class.wiki2xhtml.php

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