parsingHTML.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php
  2. /**
  3. * Logiciel : HTML2PDF - classe ParsingHTML
  4. *
  5. * Convertisseur HTML => PDF, utilise fpdf de Olivier PLATHEY
  6. * Distribué sous la licence LGPL.
  7. *
  8. * @author Laurent MINGUET <webmaster@spipu.net>
  9. * @version 3.26 - 16/11/2009
  10. */
  11. if (!defined('__CLASS_PARSINGHTML__'))
  12. {
  13. define('__CLASS_PARSINGHTML__', true);
  14. class parsingHTML
  15. {
  16. var $html = ''; // code HTML à parser
  17. var $code = array(); // code HTML parsé
  18. var $num = 0; // numéro de table
  19. var $level = 0; // niveaux de table
  20. /**
  21. * Constructeur
  22. *
  23. * @return null
  24. */
  25. function parsingHTML()
  26. {
  27. $this->num = 0;
  28. $this->level = array($this->num);
  29. $this->html = '';
  30. $this->code = array();
  31. }
  32. /**
  33. * Définir le code HTML à parser
  34. *
  35. * @param string code html
  36. * @return null
  37. */
  38. function setHTML($html)
  39. {
  40. $html = preg_replace('/<!--(.*)-->/isU', '', $html);
  41. $this->html = $html;
  42. }
  43. /**
  44. * parser le code HTML
  45. *
  46. * @return null
  47. */
  48. function parse()
  49. {
  50. $parents = array();
  51. // chercher les balises HTML du code
  52. $tmp = array();
  53. $this->searchCode($tmp);
  54. // identifier les balises une à une
  55. $pre_in = false;
  56. $pre_br = array(
  57. 'name' => 'br',
  58. 'close' => false,
  59. 'param' => array(
  60. 'style' => array(),
  61. 'num' => 0
  62. )
  63. );
  64. $balises_no_closed = array('br', 'hr', 'img', 'input', 'link', 'option', 'col');
  65. $todos = array();
  66. foreach($tmp as $part)
  67. {
  68. // si c'est un texte
  69. if ($part[0]=='txt')
  70. {
  71. // enregistrer l'action correspondante
  72. if (!$pre_in)
  73. {
  74. // if (trim($part[1])!=='')
  75. // {
  76. // remplacer tous les espaces, tabulations, saufs de ligne multiples par de simples espaces
  77. $part[1] = preg_replace('/([\s]+)/is', ' ', $part[1]);
  78. $todos[] = array(
  79. 'name' => 'write',
  80. 'close' => false,
  81. 'param' => array('txt' => $part[1]),
  82. );
  83. // }
  84. }
  85. else
  86. {
  87. $part[1] = str_replace("\r", '', $part[1]);
  88. $part[1] = explode("\n", $part[1]);
  89. foreach($part[1] as $k => $txt)
  90. {
  91. $txt = str_replace("\t", ' ', $txt);
  92. $txt = str_replace(' ', '&nbsp;', $txt);
  93. if ($k>0) $todos[] = $pre_br;
  94. $todos[] = array(
  95. 'name' => 'write',
  96. 'close' => false,
  97. 'param' => array('txt' => $txt),
  98. );
  99. }
  100. }
  101. }
  102. // sinon, analyser le code
  103. else
  104. {
  105. $res = $this->analiseCode($part[1]);
  106. if ($res)
  107. {
  108. $res['html_pos'] = $part[2];
  109. if (!in_array($res['name'], $balises_no_closed))
  110. {
  111. if ($res['close'])
  112. {
  113. if (count($parents)<1)
  114. @HTML2PDF::makeError(3, __FILE__, __LINE__, $res['name'], $this->getHtmlErrorCode($res['html_pos']));
  115. else if ($parents[count($parents)-1]!=$res['name'])
  116. @HTML2PDF::makeError(4, __FILE__, __LINE__, $parents, $this->getHtmlErrorCode($res['html_pos']));
  117. else
  118. unset($parents[count($parents)-1]);
  119. }
  120. else
  121. {
  122. if ($res['autoclose'])
  123. {
  124. $todos[] = $res;
  125. $res['params'] = array();
  126. $res['close'] = true;
  127. }
  128. else
  129. $parents[count($parents)] = $res['name'];
  130. }
  131. if (($res['name']=='pre' || $res['name']=='code') && !$res['autoclose'])
  132. $pre_in = !$res['close'];
  133. }
  134. $todos[] = $res;
  135. }
  136. }
  137. }
  138. // pour chaque action identifiée, il faut nettoyer le début et la fin des textes
  139. // en fonction des balises qui l'entourent.
  140. $balises_clean = array('page', 'page_header', 'page_footer', 'form',
  141. 'table', 'thead', 'tfoot', 'tr', 'td', 'th', 'br',
  142. 'div', 'hr', 'p', 'ul', 'ol', 'li',
  143. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  144. 'bookmark');
  145. $nb = count($todos);
  146. for($k=0; $k<$nb; $k++)
  147. {
  148. //si c'est un texte
  149. if ($todos[$k]['name']=='write')
  150. {
  151. // et qu'une balise spécifique le précède => on nettoye les espaces du début du texte
  152. if ($k>0 && in_array($todos[$k-1]['name'], $balises_clean))
  153. $todos[$k]['param']['txt'] = ltrim($todos[$k]['param']['txt']);
  154. // et qu'une balise spécifique le suit => on nettoye les espaces de la fin du texte
  155. if ($k<count($todos)-1 && in_array($todos[$k+1]['name'], $balises_clean))
  156. $todos[$k]['param']['txt'] = rtrim($todos[$k]['param']['txt']);
  157. if (!strlen($todos[$k]['param']['txt']))
  158. unset($todos[$k]);
  159. }
  160. }
  161. if (count($parents)) @HTML2PDF::makeError(5, __FILE__, __LINE__, $parents);
  162. // liste des actions sauvée
  163. $this->code = array_values($todos);;
  164. }
  165. /**
  166. * parser le code HTML
  167. *
  168. * @param &array tableau de retour des données
  169. * @return null
  170. */
  171. function searchCode(&$tmp)
  172. {
  173. // séparer les balises du texte
  174. $tmp = array();
  175. $reg = '/(<[^>]+>)|([^<]+)+/isU';
  176. // pour chaque élément trouvé :
  177. $str = '';
  178. $offset = 0;
  179. while(preg_match($reg, $this->html, $parse, PREG_OFFSET_CAPTURE, $offset))
  180. {
  181. // si une balise a été détectée
  182. if ($parse[1][0])
  183. {
  184. // sauvegarde du texte précédent si il existe
  185. if ($str!=='') $tmp[] = array('txt',$str);
  186. // sauvegarde de la balise
  187. $tmp[] = array('code',trim($parse[1][0]), $offset);
  188. // initialisation du texte suivant
  189. $str = '';
  190. }
  191. else
  192. {
  193. // ajout du texte à la fin de celui qui est déjà détecté
  194. $str.= $parse[2][0];
  195. }
  196. // Update offset to the end of the match
  197. $offset = $parse[0][1] + strlen($parse[0][0]);
  198. unset($parse);
  199. }
  200. // si un texte est présent à la fin, on l'enregistre
  201. if ($str!='') $tmp[] = array('txt',$str);
  202. unset($str);
  203. }
  204. /**
  205. * analyse une balise HTML
  206. *
  207. * @param string code HTML à identifier
  208. * @return array action correspondante
  209. */
  210. function analiseCode($code)
  211. {
  212. // nom de la balise et ouverture ou fermeture
  213. $balise = '<([\/]{0,1})([_a-z0-9]+)([\/>\s]+)';
  214. preg_match('/'.$balise.'/isU', $code, $match);
  215. $close = ($match[1]=='/' ? true : false);
  216. $autoclose = preg_match('/\/>$/isU', $code);
  217. $name = strtolower($match[2]);
  218. // paramètres obligatoires en fonction du nom de la balise
  219. $param = array();
  220. $param['style'] = '';
  221. if ($name=='img') { $param['alt'] = ''; $param['src'] = ''; }
  222. if ($name=='a') { $param['href'] = ''; }
  223. // lecture des paramétres du type nom=valeur
  224. $prop = '([a-zA-Z0-9_]+)=([^"\'\s>]+)';
  225. preg_match_all('/'.$prop.'/is', $code, $match);
  226. for($k=0; $k<count($match[0]); $k++)
  227. $param[trim(strtolower($match[1][$k]))] = trim($match[2][$k]);
  228. // lecture des paramétres du type nom="valeur"
  229. $prop = '([a-zA-Z0-9_]+)=["]([^"]*)["]';
  230. preg_match_all('/'.$prop.'/is', $code, $match);
  231. for($k=0; $k<count($match[0]); $k++)
  232. $param[trim(strtolower($match[1][$k]))] = trim($match[2][$k]);
  233. // lecture des paramétres du type nom='valeur'
  234. $prop = "([a-zA-Z0-9_]+)=[']([^']*)[']";
  235. preg_match_all('/'.$prop.'/is', $code, $match);
  236. for($k=0; $k<count($match[0]); $k++)
  237. $param[trim(strtolower($match[1][$k]))] = trim($match[2][$k]);
  238. // mise en conformité en style de chaque paramètre
  239. $color = "#000000";
  240. $border = null;
  241. foreach($param as $key => $val)
  242. {
  243. $key = strtolower($key);
  244. switch($key)
  245. {
  246. case 'width':
  247. unset($param[$key]);
  248. $param['style'] = 'width: '.$val.'px; '.$param['style'];
  249. break;
  250. case 'align':
  251. if ($name!=='table')
  252. {
  253. unset($param[$key]);
  254. $param['style'] = 'text-align: '.$val.'; '.$param['style'];
  255. }
  256. break;
  257. case 'valign':
  258. unset($param[$key]);
  259. $param['style'] = 'vertical-align: '.$val.'; '.$param['style'];
  260. break;
  261. case 'height':
  262. unset($param[$key]);
  263. $param['style'] = 'height: '.$val.'px; '.$param['style'];
  264. break;
  265. case 'bgcolor':
  266. unset($param[$key]);
  267. $param['style'] = 'background: '.$val.'; '.$param['style'];
  268. break;
  269. case 'bordercolor':
  270. unset($param[$key]);
  271. $color = $val;
  272. break;
  273. case 'border':
  274. unset($param[$key]);
  275. if (preg_match('/^[0-9]$/isU', $val)) $val = $val.'px';
  276. $border = $val;
  277. break;
  278. case 'cellpadding':
  279. case 'cellspacing':
  280. if (preg_match('/^([0-9]+)$/isU', $val)) $param[$key] = $val.'px';
  281. break;
  282. case 'colspan':
  283. case 'rowspan':
  284. $val = preg_replace('/[^0-9]/isU', '', $val);
  285. if (!$val) $val = 1;
  286. $param[$key] = $val;
  287. break;
  288. }
  289. }
  290. if ($border!==null)
  291. {
  292. if ($border) $param['style'] = 'border: solid '.$border.' '.$color.'; '.$param['style'];
  293. else $param['style'] = 'border: none'.$param['style'];
  294. }
  295. // lecture des styles - décomposition
  296. $styles = explode(';', $param['style']);
  297. $param['style'] = array();
  298. foreach($styles as $style)
  299. {
  300. $tmp = explode(':', $style);
  301. if (count($tmp)>1)
  302. {
  303. $cod = $tmp[0]; unset($tmp[0]); $tmp = implode(':', $tmp);
  304. $param['style'][trim(strtolower($cod))] = preg_replace('/[\s]+/isU', ' ', trim($tmp));
  305. }
  306. }
  307. // détermination du niveau de table pour les ouverture, avec ajout d'un level
  308. if (in_array($name, array('ul', 'ol', 'table')) && !$close)
  309. {
  310. $this->num++;
  311. $this->level[count($this->level)] = $this->num;
  312. }
  313. // attribution du niveau de table où se trouve l'élément
  314. if (!isset($param['num'])) $param['num'] = $this->level[count($this->level)-1];
  315. // pour les fins de table : suppression d'un level
  316. if (in_array($name, array('ul', 'ol', 'table')) && $close)
  317. {
  318. unset($this->level[count($this->level)-1]);
  319. }
  320. // retour de l'action identifiée
  321. return array('name' => $name, 'close' => $close ? 1 : 0, 'autoclose' => $autoclose, 'param' => $param);
  322. }
  323. // récupérer un niveau complet d'HTML entre une ouverture de balise et la fermeture correspondante
  324. function getLevel($k)
  325. {
  326. // si le code n'existe pas : fin
  327. if (!isset($this->code[$k])) return '';
  328. // quelle balise faudra-t-il détecter
  329. $detect = $this->code[$k]['name'];
  330. $level = 0; // niveau de profondeur
  331. $end = false; // etat de fin de recherche
  332. $code = ''; // code extrait
  333. // tant que c'est pas fini, on boucle
  334. while (!$end)
  335. {
  336. // action courante
  337. $row = $this->code[$k];
  338. // si write => on ajoute le texte
  339. if ($row['name']=='write')
  340. {
  341. $code.= $row['param']['txt'];
  342. }
  343. // sinon, c'est une balise html
  344. else
  345. {
  346. $not = false; // indicateur de non prise en compte de la balise courante
  347. // si c'est la balise que l'on cherche
  348. if ($row['name']==$detect)
  349. {
  350. if ($level==0) { $not = true; } // si on est à la premiere balise : on l'ignore
  351. $level+= ($row['close'] ? -1 : 1); // modification du niveau en cours en fonction de l'ouvertre / fermeture
  352. if ($level==0) { $not = true; $end = true; } // si on est au niveau 0 : on a fini
  353. }
  354. // si on doit prendre en compte la balise courante
  355. if (!$not)
  356. {
  357. // ecriture du code HTML de la balise
  358. $code.= '<'.($row['close'] ? '/' : '').$row['name'];
  359. foreach($row['param'] as $key => $val)
  360. {
  361. if ($key=='style')
  362. {
  363. $tmp = '';
  364. if (isset($val['text-align'])) unset($val['text-align']);
  365. foreach($val as $ks => $vs) $tmp.= $ks.':'.$vs.'; ';
  366. if (trim($tmp)) $code.= ' '.$key.'="'.$tmp.'"';
  367. }
  368. else
  369. {
  370. $code.= ' '.$key.'="'.$val.'"';
  371. }
  372. }
  373. $code.= '>';
  374. }
  375. }
  376. // on continue tant qu'il y a du code à analyser...
  377. if (isset($this->code[$k+1]))
  378. $k++;
  379. else
  380. $end = true;
  381. }
  382. // retourne la position finale et le code HTML extrait
  383. return array($k, $code);
  384. }
  385. function getHtmlErrorCode($pos)
  386. {
  387. return substr($this->html, $pos-30, 70);
  388. }
  389. }
  390. }