PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/shopaholic/lib/Zend/Search/Lucene/Document/Html.php

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