2
0

Html.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Search_Lucene
  17. * @subpackage Document
  18. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. */
  21. /** Zend_Search_Lucene_Document */
  22. require_once 'Zend/Search/Lucene/Document.php';
  23. /**
  24. * HTML document.
  25. *
  26. * @category Zend
  27. * @package Zend_Search_Lucene
  28. * @subpackage Document
  29. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  30. * @license http://framework.zend.com/license/new-bsd New BSD License
  31. */
  32. class Zend_Search_Lucene_Document_Html extends Zend_Search_Lucene_Document
  33. {
  34. /**
  35. * List of document links
  36. *
  37. * @var array
  38. */
  39. private $_links = array();
  40. /**
  41. * List of document header links
  42. *
  43. * @var array
  44. */
  45. private $_headerLinks = array();
  46. /**
  47. * Stored DOM representation
  48. *
  49. * @var DOMDocument
  50. */
  51. private $_doc;
  52. /**
  53. * Exclud nofollow links flag
  54. *
  55. * If true then links with rel='nofollow' attribute are not included into
  56. * document links.
  57. *
  58. * @var boolean
  59. */
  60. private static $_excludeNoFollowLinks = false;
  61. /**
  62. * Object constructor
  63. *
  64. * @param string $data HTML string (may be HTML fragment, )
  65. * @param boolean $isFile
  66. * @param boolean $storeContent
  67. * @param string $defaultEncoding HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag.
  68. */
  69. private function __construct($data, $isFile, $storeContent, $defaultEncoding = '')
  70. {
  71. $this->_doc = new DOMDocument();
  72. $this->_doc->substituteEntities = true;
  73. if ($isFile) {
  74. $htmlData = file_get_contents($data);
  75. } else {
  76. $htmlData = $data;
  77. }
  78. @$this->_doc->loadHTML($htmlData);
  79. if ($this->_doc->encoding === null) {
  80. // Document encoding is not recognized
  81. /** @todo improve HTML vs HTML fragment recognition */
  82. if (preg_match('/<html>/i', $htmlData, $matches, PREG_OFFSET_CAPTURE)) {
  83. // It's an HTML document
  84. // Add additional HEAD section and recognize document
  85. $htmlTagOffset = $matches[0][1] + strlen($matches[0][1]);
  86. @$this->_doc->loadHTML(iconv($defaultEncoding, 'UTF-8//IGNORE', substr($htmlData, 0, $htmlTagOffset))
  87. . '<head><META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8"/></head>'
  88. . iconv($defaultEncoding, 'UTF-8//IGNORE', substr($htmlData, $htmlTagOffset)));
  89. // Remove additional HEAD section
  90. $xpath = new DOMXPath($this->_doc);
  91. $head = $xpath->query('/html/head')->item(0);
  92. $head->parentNode->removeChild($head);
  93. } else {
  94. // It's an HTML fragment
  95. @$this->_doc->loadHTML('<html><head><META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8"/></head><body>'
  96. . iconv($defaultEncoding, 'UTF-8//IGNORE', $htmlData)
  97. . '</body></html>');
  98. }
  99. }
  100. /** @todo Add correction of wrong HTML encoding recognition processing
  101. * The case is:
  102. * Content-type HTTP-EQUIV meta tag is presented, but ISO-8859-5 encoding is actually used,
  103. * even $this->_doc->encoding demonstrates another recognized encoding
  104. */
  105. $xpath = new DOMXPath($this->_doc);
  106. $docTitle = '';
  107. $titleNodes = $xpath->query('/html/head/title');
  108. foreach ($titleNodes as $titleNode) {
  109. // title should always have only one entry, but we process all nodeset entries
  110. $docTitle .= $titleNode->nodeValue . ' ';
  111. }
  112. $this->addField(Zend_Search_Lucene_Field::Text('title', $docTitle, 'UTF-8'));
  113. $metaNodes = $xpath->query('/html/head/meta[@name]');
  114. foreach ($metaNodes as $metaNode) {
  115. $this->addField(Zend_Search_Lucene_Field::Text($metaNode->getAttribute('name'),
  116. $metaNode->getAttribute('content'),
  117. 'UTF-8'));
  118. }
  119. $docBody = '';
  120. $bodyNodes = $xpath->query('/html/body');
  121. foreach ($bodyNodes as $bodyNode) {
  122. // body should always have only one entry, but we process all nodeset entries
  123. $this->_retrieveNodeText($bodyNode, $docBody);
  124. }
  125. if ($storeContent) {
  126. $this->addField(Zend_Search_Lucene_Field::Text('body', $docBody, 'UTF-8'));
  127. } else {
  128. $this->addField(Zend_Search_Lucene_Field::UnStored('body', $docBody, 'UTF-8'));
  129. }
  130. $linkNodes = $this->_doc->getElementsByTagName('a');
  131. foreach ($linkNodes as $linkNode) {
  132. if (($href = $linkNode->getAttribute('href')) != '' &&
  133. (!self::$_excludeNoFollowLinks || strtolower($linkNode->getAttribute('rel')) != 'nofollow' )
  134. ) {
  135. $this->_links[] = $href;
  136. }
  137. }
  138. $this->_links = array_unique($this->_links);
  139. $linkNodes = $xpath->query('/html/head/link');
  140. foreach ($linkNodes as $linkNode) {
  141. if (($href = $linkNode->getAttribute('href')) != '') {
  142. $this->_headerLinks[] = $href;
  143. }
  144. }
  145. $this->_headerLinks = array_unique($this->_headerLinks);
  146. }
  147. /**
  148. * Set exclude nofollow links flag
  149. *
  150. * @param boolean $newValue
  151. */
  152. public static function setExcludeNoFollowLinks($newValue)
  153. {
  154. self::$_excludeNoFollowLinks = $newValue;
  155. }
  156. /**
  157. * Get exclude nofollow links flag
  158. *
  159. * @return boolean
  160. */
  161. public static function getExcludeNoFollowLinks()
  162. {
  163. return self::$_excludeNoFollowLinks;
  164. }
  165. /**
  166. * Get node text
  167. *
  168. * We should exclude scripts, which may be not included into comment tags, CDATA sections,
  169. *
  170. * @param DOMNode $node
  171. * @param string &$text
  172. */
  173. private function _retrieveNodeText(DOMNode $node, &$text)
  174. {
  175. if ($node->nodeType == XML_TEXT_NODE) {
  176. $text .= $node->nodeValue ;
  177. $text .= ' ';
  178. } else if ($node->nodeType == XML_ELEMENT_NODE && $node->nodeName != 'script') {
  179. foreach ($node->childNodes as $childNode) {
  180. $this->_retrieveNodeText($childNode, $text);
  181. }
  182. }
  183. }
  184. /**
  185. * Get document HREF links
  186. *
  187. * @return array
  188. */
  189. public function getLinks()
  190. {
  191. return $this->_links;
  192. }
  193. /**
  194. * Get document header links
  195. *
  196. * @return array
  197. */
  198. public function getHeaderLinks()
  199. {
  200. return $this->_headerLinks;
  201. }
  202. /**
  203. * Load HTML document from a string
  204. *
  205. * @param string $data
  206. * @param boolean $storeContent
  207. * @param string $defaultEncoding HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag.
  208. * @return Zend_Search_Lucene_Document_Html
  209. */
  210. public static function loadHTML($data, $storeContent = false, $defaultEncoding = '')
  211. {
  212. return new Zend_Search_Lucene_Document_Html($data, false, $storeContent, $defaultEncoding);
  213. }
  214. /**
  215. * Load HTML document from a file
  216. *
  217. * @param string $file
  218. * @param boolean $storeContent
  219. * @param string $defaultEncoding HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag.
  220. * @return Zend_Search_Lucene_Document_Html
  221. */
  222. public static function loadHTMLFile($file, $storeContent = false, $defaultEncoding = '')
  223. {
  224. return new Zend_Search_Lucene_Document_Html($file, true, $storeContent, $defaultEncoding);
  225. }
  226. /**
  227. * Highlight text in text node
  228. *
  229. * @param DOMText $node
  230. * @param array $wordsToHighlight
  231. * @param callback $callback Callback method, used to transform (highlighting) text.
  232. * @param array $params Array of additionall callback parameters (first non-optional parameter is a text to transform)
  233. * @throws Zend_Search_Lucene_Exception
  234. */
  235. protected function _highlightTextNode(DOMText $node, $wordsToHighlight, $callback, $params)
  236. {
  237. $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault();
  238. $analyzer->setInput($node->nodeValue, 'UTF-8');
  239. $matchedTokens = array();
  240. while (($token = $analyzer->nextToken()) !== null) {
  241. if (isset($wordsToHighlight[$token->getTermText()])) {
  242. $matchedTokens[] = $token;
  243. }
  244. }
  245. if (count($matchedTokens) == 0) {
  246. return;
  247. }
  248. $matchedTokens = array_reverse($matchedTokens);
  249. foreach ($matchedTokens as $token) {
  250. // Cut text after matched token
  251. $node->splitText($token->getEndOffset());
  252. // Cut matched node
  253. $matchedWordNode = $node->splitText($token->getStartOffset());
  254. // Retrieve HTML string representation for highlihted word
  255. $fullCallbackparamsList = $params;
  256. array_unshift($fullCallbackparamsList, $matchedWordNode->nodeValue);
  257. $highlightedWordNodeSetHtml = call_user_func_array($callback, $fullCallbackparamsList);
  258. // Transform HTML string to a DOM representation and automatically transform retrieved string
  259. // into valid XHTML (It's automatically done by loadHTML() method)
  260. $highlightedWordNodeSetDomDocument = new DOMDocument('1.0', 'UTF-8');
  261. $success = @$highlightedWordNodeSetDomDocument->
  262. loadHTML('<html><head><meta http-equiv="Content-type" content="text/html; charset=UTF-8"/></head><body>'
  263. . $highlightedWordNodeSetHtml
  264. . '</body></html>');
  265. if (!$success) {
  266. require_once 'Zend/Search/Lucene/Exception.php';
  267. throw new Zend_Search_Lucene_Exception("Error occured while loading highlighted text fragment: '$highlightedNodeHtml'.");
  268. }
  269. $highlightedWordNodeSetXpath = new DOMXPath($highlightedWordNodeSetDomDocument);
  270. $highlightedWordNodeSet = $highlightedWordNodeSetXpath->query('/html/body')->item(0)->childNodes;
  271. for ($count = 0; $count < $highlightedWordNodeSet->length; $count++) {
  272. $nodeToImport = $highlightedWordNodeSet->item($count);
  273. $node->parentNode->insertBefore($this->_doc->importNode($nodeToImport, true /* deep copy */),
  274. $matchedWordNode);
  275. }
  276. $node->parentNode->removeChild($matchedWordNode);
  277. }
  278. }
  279. /**
  280. * highlight words in content of the specified node
  281. *
  282. * @param DOMNode $contextNode
  283. * @param array $wordsToHighlight
  284. * @param callback $callback Callback method, used to transform (highlighting) text.
  285. * @param array $params Array of additionall callback parameters (first non-optional parameter is a text to transform)
  286. */
  287. protected function _highlightNodeRecursive(DOMNode $contextNode, $wordsToHighlight, $callback, $params)
  288. {
  289. $textNodes = array();
  290. if (!$contextNode->hasChildNodes()) {
  291. return;
  292. }
  293. foreach ($contextNode->childNodes as $childNode) {
  294. if ($childNode->nodeType == XML_TEXT_NODE) {
  295. // process node later to leave childNodes structure untouched
  296. $textNodes[] = $childNode;
  297. } else {
  298. // Process node if it's not a script node
  299. if ($childNode->nodeName != 'script') {
  300. $this->_highlightNodeRecursive($childNode, $wordsToHighlight, $callback, $params);
  301. }
  302. }
  303. }
  304. foreach ($textNodes as $textNode) {
  305. $this->_highlightTextNode($textNode, $wordsToHighlight, $callback, $params);
  306. }
  307. }
  308. /**
  309. * Standard callback method used to highlight words.
  310. *
  311. * @param string $stringToHighlight
  312. * @return string
  313. * @internal
  314. */
  315. public function applyColour($stringToHighlight, $colour)
  316. {
  317. return '<b style="color:black;background-color:' . $colour . '">' . $stringToHighlight . '</b>';
  318. }
  319. /**
  320. * Highlight text with specified color
  321. *
  322. * @param string|array $words
  323. * @param string $colour
  324. * @return string
  325. */
  326. public function highlight($words, $colour = '#66ffff')
  327. {
  328. return $this->highlightExtended($words, array($this, 'applyColour'), array($colour));
  329. }
  330. /**
  331. * Highlight text using specified View helper or callback function.
  332. *
  333. * @param string|array $words Words to highlight. Words could be organized using the array or string.
  334. * @param callback $callback Callback method, used to transform (highlighting) text.
  335. * @param array $params Array of additionall callback parameters passed through into it
  336. * (first non-optional parameter is an HTML fragment for highlighting)
  337. * @return string
  338. * @throws Zend_Search_Lucene_Exception
  339. */
  340. public function highlightExtended($words, $callback, $params = array())
  341. {
  342. if (!is_array($words)) {
  343. $words = array($words);
  344. }
  345. $wordsToHighlightList = array();
  346. $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault();
  347. foreach ($words as $wordString) {
  348. $wordsToHighlightList[] = $analyzer->tokenize($wordString);
  349. }
  350. $wordsToHighlight = call_user_func_array('array_merge', $wordsToHighlightList);
  351. if (count($wordsToHighlight) == 0) {
  352. return $this->_doc->saveHTML();
  353. }
  354. $wordsToHighlightFlipped = array();
  355. foreach ($wordsToHighlight as $id => $token) {
  356. $wordsToHighlightFlipped[$token->getTermText()] = $id;
  357. }
  358. if (!is_callable($callback)) {
  359. require_once 'Zend/Search/Lucene/Exception.php';
  360. throw new Zend_Search_Lucene_Exception('$viewHelper parameter mast be a View Helper name, View Helper object or callback.');
  361. }
  362. $xpath = new DOMXPath($this->_doc);
  363. $matchedNodes = $xpath->query("/html/body");
  364. foreach ($matchedNodes as $matchedNode) {
  365. $this->_highlightNodeRecursive($matchedNode, $wordsToHighlightFlipped, $callback, $params);
  366. }
  367. }
  368. /**
  369. * Get HTML
  370. *
  371. * @return string
  372. */
  373. public function getHTML()
  374. {
  375. return $this->_doc->saveHTML();
  376. }
  377. /**
  378. * Get HTML body
  379. *
  380. * @return string
  381. */
  382. public function getHtmlBody()
  383. {
  384. $xpath = new DOMXPath($this->_doc);
  385. $bodyNodes = $xpath->query('/html/body')->item(0)->childNodes;
  386. $outputFragments = array();
  387. for ($count = 0; $count < $bodyNodes->length; $count++) {
  388. $outputFragments[] = $this->_doc->saveXML($bodyNodes->item($count));
  389. }
  390. return implode($outputFragments);
  391. }
  392. }