PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/titania/includes/library/Zend/Search/Lucene/Document/Html.php

http://github.com/phpbb/customisation-db
PHP | 460 lines | 219 code | 63 blank | 178 comment | 38 complexity | c2cd12eb71298dfd61a8c0ec555e206b MD5 | raw file
Possible License(s): AGPL-1.0
  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$
  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][0]);
  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. /** Zend_Search_Lucene_Analysis_Analyzer */
  239. require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';
  240. $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault();
  241. $analyzer->setInput($node->nodeValue, 'UTF-8');
  242. $matchedTokens = array();
  243. while (($token = $analyzer->nextToken()) !== null) {
  244. if (isset($wordsToHighlight[$token->getTermText()])) {
  245. $matchedTokens[] = $token;
  246. }
  247. }
  248. if (count($matchedTokens) == 0) {
  249. return;
  250. }
  251. $matchedTokens = array_reverse($matchedTokens);
  252. foreach ($matchedTokens as $token) {
  253. // Cut text after matched token
  254. $node->splitText($token->getEndOffset());
  255. // Cut matched node
  256. $matchedWordNode = $node->splitText($token->getStartOffset());
  257. // Retrieve HTML string representation for highlihted word
  258. $fullCallbackparamsList = $params;
  259. array_unshift($fullCallbackparamsList, $matchedWordNode->nodeValue);
  260. $highlightedWordNodeSetHtml = call_user_func_array($callback, $fullCallbackparamsList);
  261. // Transform HTML string to a DOM representation and automatically transform retrieved string
  262. // into valid XHTML (It's automatically done by loadHTML() method)
  263. $highlightedWordNodeSetDomDocument = new DOMDocument('1.0', 'UTF-8');
  264. $success = @$highlightedWordNodeSetDomDocument->
  265. loadHTML('<html><head><meta http-equiv="Content-type" content="text/html; charset=UTF-8"/></head><body>'
  266. . $highlightedWordNodeSetHtml
  267. . '</body></html>');
  268. if (!$success) {
  269. require_once 'Zend/Search/Lucene/Exception.php';
  270. throw new Zend_Search_Lucene_Exception("Error occured while loading highlighted text fragment: '$highlightedNodeHtml'.");
  271. }
  272. $highlightedWordNodeSetXpath = new DOMXPath($highlightedWordNodeSetDomDocument);
  273. $highlightedWordNodeSet = $highlightedWordNodeSetXpath->query('/html/body')->item(0)->childNodes;
  274. for ($count = 0; $count < $highlightedWordNodeSet->length; $count++) {
  275. $nodeToImport = $highlightedWordNodeSet->item($count);
  276. $node->parentNode->insertBefore($this->_doc->importNode($nodeToImport, true /* deep copy */),
  277. $matchedWordNode);
  278. }
  279. $node->parentNode->removeChild($matchedWordNode);
  280. }
  281. }
  282. /**
  283. * highlight words in content of the specified node
  284. *
  285. * @param DOMNode $contextNode
  286. * @param array $wordsToHighlight
  287. * @param callback $callback Callback method, used to transform (highlighting) text.
  288. * @param array $params Array of additionall callback parameters (first non-optional parameter is a text to transform)
  289. */
  290. protected function _highlightNodeRecursive(DOMNode $contextNode, $wordsToHighlight, $callback, $params)
  291. {
  292. $textNodes = array();
  293. if (!$contextNode->hasChildNodes()) {
  294. return;
  295. }
  296. foreach ($contextNode->childNodes as $childNode) {
  297. if ($childNode->nodeType == XML_TEXT_NODE) {
  298. // process node later to leave childNodes structure untouched
  299. $textNodes[] = $childNode;
  300. } else {
  301. // Process node if it's not a script node
  302. if ($childNode->nodeName != 'script') {
  303. $this->_highlightNodeRecursive($childNode, $wordsToHighlight, $callback, $params);
  304. }
  305. }
  306. }
  307. foreach ($textNodes as $textNode) {
  308. $this->_highlightTextNode($textNode, $wordsToHighlight, $callback, $params);
  309. }
  310. }
  311. /**
  312. * Standard callback method used to highlight words.
  313. *
  314. * @param string $stringToHighlight
  315. * @return string
  316. * @internal
  317. */
  318. public function applyColour($stringToHighlight, $colour)
  319. {
  320. return '<b style="color:black;background-color:' . $colour . '">' . $stringToHighlight . '</b>';
  321. }
  322. /**
  323. * Highlight text with specified color
  324. *
  325. * @param string|array $words
  326. * @param string $colour
  327. * @return string
  328. */
  329. public function highlight($words, $colour = '#66ffff')
  330. {
  331. return $this->highlightExtended($words, array($this, 'applyColour'), array($colour));
  332. }
  333. /**
  334. * Highlight text using specified View helper or callback function.
  335. *
  336. * @param string|array $words Words to highlight. Words could be organized using the array or string.
  337. * @param callback $callback Callback method, used to transform (highlighting) text.
  338. * @param array $params Array of additionall callback parameters passed through into it
  339. * (first non-optional parameter is an HTML fragment for highlighting)
  340. * @return string
  341. * @throws Zend_Search_Lucene_Exception
  342. */
  343. public function highlightExtended($words, $callback, $params = array())
  344. {
  345. /** Zend_Search_Lucene_Analysis_Analyzer */
  346. require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';
  347. if (!is_array($words)) {
  348. $words = array($words);
  349. }
  350. $wordsToHighlightList = array();
  351. $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault();
  352. foreach ($words as $wordString) {
  353. $wordsToHighlightList[] = $analyzer->tokenize($wordString);
  354. }
  355. $wordsToHighlight = call_user_func_array('array_merge', $wordsToHighlightList);
  356. if (count($wordsToHighlight) == 0) {
  357. return $this->_doc->saveHTML();
  358. }
  359. $wordsToHighlightFlipped = array();
  360. foreach ($wordsToHighlight as $id => $token) {
  361. $wordsToHighlightFlipped[$token->getTermText()] = $id;
  362. }
  363. if (!is_callable($callback)) {
  364. require_once 'Zend/Search/Lucene/Exception.php';
  365. throw new Zend_Search_Lucene_Exception('$viewHelper parameter mast be a View Helper name, View Helper object or callback.');
  366. }
  367. $xpath = new DOMXPath($this->_doc);
  368. $matchedNodes = $xpath->query("/html/body");
  369. foreach ($matchedNodes as $matchedNode) {
  370. $this->_highlightNodeRecursive($matchedNode, $wordsToHighlightFlipped, $callback, $params);
  371. }
  372. }
  373. /**
  374. * Get HTML
  375. *
  376. * @return string
  377. */
  378. public function getHTML()
  379. {
  380. return $this->_doc->saveHTML();
  381. }
  382. /**
  383. * Get HTML body
  384. *
  385. * @return string
  386. */
  387. public function getHtmlBody()
  388. {
  389. $xpath = new DOMXPath($this->_doc);
  390. $bodyNodes = $xpath->query('/html/body')->item(0)->childNodes;
  391. $outputFragments = array();
  392. for ($count = 0; $count < $bodyNodes->length; $count++) {
  393. $outputFragments[] = $this->_doc->saveXML($bodyNodes->item($count));
  394. }
  395. return implode($outputFragments);
  396. }
  397. }