File: Html.php

package info (click to toggle)
zendframework 1.10.6-1squeeze2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 29,480 kB
  • ctags: 46,247
  • sloc: xml: 233,973; php: 195,700; sql: 90; sh: 19; makefile: 10
file content (481 lines) | stat: -rw-r--r-- 16,999 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Html.php 21946 2010-04-19 08:21:02Z alexander $
 */


/** Zend_Search_Lucene_Document */
require_once 'Zend/Search/Lucene/Document.php';


/**
 * HTML document.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Document_Html extends Zend_Search_Lucene_Document
{
    /**
     * List of document links
     *
     * @var array
     */
    private $_links = array();

    /**
     * List of document header links
     *
     * @var array
     */
    private $_headerLinks = array();

    /**
     * Stored DOM representation
     *
     * @var DOMDocument
     */
    private $_doc;

    /**
     * Exclud nofollow links flag
     *
     * If true then links with rel='nofollow' attribute are not included into
     * document links.
     *
     * @var boolean
     */
    private static $_excludeNoFollowLinks = false;

    /**
     *
     * List of inline tags
     *
     * @var array
     */
    private $_inlineTags = array('a', 'abbr', 'acronym', 'dfn', 'em', 'strong', 'code',
                                'samp', 'kbd', 'var', 'b', 'i', 'big', 'small', 'strike',
                                'tt', 'u', 'font', 'span', 'bdo', 'cite', 'del', 'ins',
                                'q', 'sub', 'sup');

    /**
     * Object constructor
     *
     * @param string  $data         HTML string (may be HTML fragment, )
     * @param boolean $isFile
     * @param boolean $storeContent
     * @param string  $defaultEncoding   HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag.
     */
    private function __construct($data, $isFile, $storeContent, $defaultEncoding = '')
    {
        $this->_doc = new DOMDocument();
        $this->_doc->substituteEntities = true;

        if ($isFile) {
            $htmlData = file_get_contents($data);
        } else {
            $htmlData = $data;
        }
        @$this->_doc->loadHTML($htmlData);

        if ($this->_doc->encoding === null) {
            // Document encoding is not recognized

            /** @todo improve HTML vs HTML fragment recognition */
            if (preg_match('/<html>/i', $htmlData, $matches, PREG_OFFSET_CAPTURE)) {
                // It's an HTML document
                // Add additional HEAD section and recognize document
                $htmlTagOffset = $matches[0][1] + strlen($matches[0][0]);

                @$this->_doc->loadHTML(iconv($defaultEncoding, 'UTF-8//IGNORE', substr($htmlData, 0, $htmlTagOffset))
                                     . '<head><META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8"/></head>'
                                     . iconv($defaultEncoding, 'UTF-8//IGNORE', substr($htmlData, $htmlTagOffset)));

                // Remove additional HEAD section
                $xpath = new DOMXPath($this->_doc);
                $head  = $xpath->query('/html/head')->item(0);
                $head->parentNode->removeChild($head);
            } else {
                // It's an HTML fragment
                @$this->_doc->loadHTML('<html><head><META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8"/></head><body>'
                                     . iconv($defaultEncoding, 'UTF-8//IGNORE', $htmlData)
                                     . '</body></html>');
            }

        }
        /** @todo Add correction of wrong HTML encoding recognition processing
         * The case is:
         * Content-type HTTP-EQUIV meta tag is presented, but ISO-8859-5 encoding is actually used,
         * even $this->_doc->encoding demonstrates another recognized encoding
         */

        $xpath = new DOMXPath($this->_doc);

        $docTitle = '';
        $titleNodes = $xpath->query('/html/head/title');
        foreach ($titleNodes as $titleNode) {
            // title should always have only one entry, but we process all nodeset entries
            $docTitle .= $titleNode->nodeValue . ' ';
        }
        $this->addField(Zend_Search_Lucene_Field::Text('title', $docTitle, 'UTF-8'));

        $metaNodes = $xpath->query('/html/head/meta[@name]');
        foreach ($metaNodes as $metaNode) {
            $this->addField(Zend_Search_Lucene_Field::Text($metaNode->getAttribute('name'),
                                                           $metaNode->getAttribute('content'),
                                                           'UTF-8'));
        }

        $docBody = '';
        $bodyNodes = $xpath->query('/html/body');
        foreach ($bodyNodes as $bodyNode) {
            // body should always have only one entry, but we process all nodeset entries
            $this->_retrieveNodeText($bodyNode, $docBody);
        }
        if ($storeContent) {
            $this->addField(Zend_Search_Lucene_Field::Text('body', $docBody, 'UTF-8'));
        } else {
            $this->addField(Zend_Search_Lucene_Field::UnStored('body', $docBody, 'UTF-8'));
        }

        $linkNodes = $this->_doc->getElementsByTagName('a');
        foreach ($linkNodes as $linkNode) {
            if (($href = $linkNode->getAttribute('href')) != '' &&
                (!self::$_excludeNoFollowLinks  ||  strtolower($linkNode->getAttribute('rel')) != 'nofollow' )
               ) {
                $this->_links[] = $href;
            }
        }
        $linkNodes = $this->_doc->getElementsByTagName('area');
        foreach ($linkNodes as $linkNode) {
            if (($href = $linkNode->getAttribute('href')) != '' &&
                (!self::$_excludeNoFollowLinks  ||  strtolower($linkNode->getAttribute('rel')) != 'nofollow' )
               ) {
                $this->_links[] = $href;
            }
        }
        $this->_links = array_unique($this->_links);

        $linkNodes = $xpath->query('/html/head/link');
        foreach ($linkNodes as $linkNode) {
            if (($href = $linkNode->getAttribute('href')) != '') {
                $this->_headerLinks[] = $href;
            }
        }
        $this->_headerLinks = array_unique($this->_headerLinks);
    }

    /**
     * Set exclude nofollow links flag
     *
     * @param boolean $newValue
     */
    public static function setExcludeNoFollowLinks($newValue)
    {
        self::$_excludeNoFollowLinks = $newValue;
    }

    /**
     * Get exclude nofollow links flag
     *
     * @return boolean
     */
    public static function getExcludeNoFollowLinks()
    {
        return self::$_excludeNoFollowLinks;
    }

    /**
     * Get node text
     *
     * We should exclude scripts, which may be not included into comment tags, CDATA sections,
     *
     * @param DOMNode $node
     * @param string &$text
     */
    private function _retrieveNodeText(DOMNode $node, &$text)
    {
        if ($node->nodeType == XML_TEXT_NODE) {
            $text .= $node->nodeValue;
            if(!in_array($node->parentNode->tagName, $this->_inlineTags)) {
                $text .= ' ';
            }
        } else if ($node->nodeType == XML_ELEMENT_NODE  &&  $node->nodeName != 'script') {
            foreach ($node->childNodes as $childNode) {
                $this->_retrieveNodeText($childNode, $text);
            }
        }
    }

    /**
     * Get document HREF links
     *
     * @return array
     */
    public function getLinks()
    {
        return $this->_links;
    }

    /**
     * Get document header links
     *
     * @return array
     */
    public function getHeaderLinks()
    {
        return $this->_headerLinks;
    }

    /**
     * Load HTML document from a string
     *
     * @param string  $data
     * @param boolean $storeContent
     * @param string  $defaultEncoding   HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag.
     * @return Zend_Search_Lucene_Document_Html
     */
    public static function loadHTML($data, $storeContent = false, $defaultEncoding = '')
    {
        return new Zend_Search_Lucene_Document_Html($data, false, $storeContent, $defaultEncoding);
    }

    /**
     * Load HTML document from a file
     *
     * @param string  $file
     * @param boolean $storeContent
     * @param string  $defaultEncoding   HTML encoding, is used if it's not specified using Content-type HTTP-EQUIV meta tag.
     * @return Zend_Search_Lucene_Document_Html
     */
    public static function loadHTMLFile($file, $storeContent = false, $defaultEncoding = '')
    {
        return new Zend_Search_Lucene_Document_Html($file, true, $storeContent, $defaultEncoding);
    }


    /**
     * Highlight text in text node
     *
     * @param DOMText $node
     * @param array   $wordsToHighlight
     * @param callback $callback   Callback method, used to transform (highlighting) text.
     * @param array    $params     Array of additionall callback parameters (first non-optional parameter is a text to transform)
     * @throws Zend_Search_Lucene_Exception
     */
    protected function _highlightTextNode(DOMText $node, $wordsToHighlight, $callback, $params)
    {
        /** Zend_Search_Lucene_Analysis_Analyzer */
        require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';

        $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault();
        $analyzer->setInput($node->nodeValue, 'UTF-8');

        $matchedTokens = array();

        while (($token = $analyzer->nextToken()) !== null) {
            if (isset($wordsToHighlight[$token->getTermText()])) {
                $matchedTokens[] = $token;
            }
        }

        if (count($matchedTokens) == 0) {
            return;
        }

        $matchedTokens = array_reverse($matchedTokens);

        foreach ($matchedTokens as $token) {
            // Cut text after matched token
            $node->splitText($token->getEndOffset());

            // Cut matched node
            $matchedWordNode = $node->splitText($token->getStartOffset());

            // Retrieve HTML string representation for highlihted word
            $fullCallbackparamsList = $params;
            array_unshift($fullCallbackparamsList, $matchedWordNode->nodeValue);
            $highlightedWordNodeSetHtml = call_user_func_array($callback, $fullCallbackparamsList);

            // Transform HTML string to a DOM representation and automatically transform retrieved string
            // into valid XHTML (It's automatically done by loadHTML() method)
            $highlightedWordNodeSetDomDocument = new DOMDocument('1.0', 'UTF-8');
            $success = @$highlightedWordNodeSetDomDocument->
                                loadHTML('<html><head><meta http-equiv="Content-type" content="text/html; charset=UTF-8"/></head><body>'
                                       . $highlightedWordNodeSetHtml
                                       . '</body></html>');
            if (!$success) {
                require_once 'Zend/Search/Lucene/Exception.php';
                throw new Zend_Search_Lucene_Exception("Error occured while loading highlighted text fragment: '$highlightedWordNodeSetHtml'.");
            }
            $highlightedWordNodeSetXpath = new DOMXPath($highlightedWordNodeSetDomDocument);
            $highlightedWordNodeSet      = $highlightedWordNodeSetXpath->query('/html/body')->item(0)->childNodes;

            for ($count = 0; $count < $highlightedWordNodeSet->length; $count++) {
                $nodeToImport = $highlightedWordNodeSet->item($count);
                $node->parentNode->insertBefore($this->_doc->importNode($nodeToImport, true /* deep copy */),
                                                $matchedWordNode);
            }

            $node->parentNode->removeChild($matchedWordNode);
        }
    }


    /**
     * highlight words in content of the specified node
     *
     * @param DOMNode $contextNode
     * @param array $wordsToHighlight
     * @param callback $callback   Callback method, used to transform (highlighting) text.
     * @param array    $params     Array of additionall callback parameters (first non-optional parameter is a text to transform)
     */
    protected function _highlightNodeRecursive(DOMNode $contextNode, $wordsToHighlight, $callback, $params)
    {
        $textNodes = array();

        if (!$contextNode->hasChildNodes()) {
            return;
        }

        foreach ($contextNode->childNodes as $childNode) {
            if ($childNode->nodeType == XML_TEXT_NODE) {
                // process node later to leave childNodes structure untouched
                $textNodes[] = $childNode;
            } else {
                // Process node if it's not a script node
                if ($childNode->nodeName != 'script') {
                    $this->_highlightNodeRecursive($childNode, $wordsToHighlight, $callback, $params);
                }
            }
        }

        foreach ($textNodes as $textNode) {
            $this->_highlightTextNode($textNode, $wordsToHighlight, $callback, $params);
        }
    }

    /**
     * Standard callback method used to highlight words.
     *
     * @param  string  $stringToHighlight
     * @return string
     * @internal
     */
    public function applyColour($stringToHighlight, $colour)
    {
        return '<b style="color:black;background-color:' . $colour . '">' . $stringToHighlight . '</b>';
    }

    /**
     * Highlight text with specified color
     *
     * @param string|array $words
     * @param string $colour
     * @return string
     */
    public function highlight($words, $colour = '#66ffff')
    {
        return $this->highlightExtended($words, array($this, 'applyColour'), array($colour));
    }



    /**
     * Highlight text using specified View helper or callback function.
     *
     * @param string|array $words  Words to highlight. Words could be organized using the array or string.
     * @param callback $callback   Callback method, used to transform (highlighting) text.
     * @param array    $params     Array of additionall callback parameters passed through into it
     *                             (first non-optional parameter is an HTML fragment for highlighting)
     * @return string
     * @throws Zend_Search_Lucene_Exception
     */
    public function highlightExtended($words, $callback, $params = array())
    {
        /** Zend_Search_Lucene_Analysis_Analyzer */
        require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';

        if (!is_array($words)) {
            $words = array($words);
        }

        $wordsToHighlightList = array();
        $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault();
        foreach ($words as $wordString) {
            $wordsToHighlightList[] = $analyzer->tokenize($wordString);
        }
        $wordsToHighlight = call_user_func_array('array_merge', $wordsToHighlightList);

        if (count($wordsToHighlight) == 0) {
            return $this->_doc->saveHTML();
        }

        $wordsToHighlightFlipped = array();
        foreach ($wordsToHighlight as $id => $token) {
            $wordsToHighlightFlipped[$token->getTermText()] = $id;
        }

        if (!is_callable($callback)) {
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('$viewHelper parameter mast be a View Helper name, View Helper object or callback.');
        }

        $xpath = new DOMXPath($this->_doc);

        $matchedNodes = $xpath->query("/html/body");
        foreach ($matchedNodes as $matchedNode) {
            $this->_highlightNodeRecursive($matchedNode, $wordsToHighlightFlipped, $callback, $params);
        }
    }


    /**
     * Get HTML
     *
     * @return string
     */
    public function getHTML()
    {
        return $this->_doc->saveHTML();
    }

    /**
     * Get HTML body
     *
     * @return string
     */
    public function getHtmlBody()
    {
        $xpath = new DOMXPath($this->_doc);
        $bodyNodes = $xpath->query('/html/body')->item(0)->childNodes;

        $outputFragments = array();
        for ($count = 0; $count < $bodyNodes->length; $count++) {
            $outputFragments[] = $this->_doc->saveXML($bodyNodes->item($count));
        }

        return implode($outputFragments);
    }
}