blib/lib/Alvis/HTML.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« blib/lib/Alvis/Canonical.pm ↑ Summary blib/lib/Alvis/Document/Encoding.pm »
1 package Alvis::HTML;
2  
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 0 ▶use Alvis::Document::Encoding;
Subroutine BEGIN: called CC=1 SCAR=2.6
7  
8 $Alvis::HTML::VERSION = '0.31';
9  
10 #############################################################################
11 #
12 # Kimmo Valtonen, based on earlier work assisted by Ville Tuulos and
13 # Antti Tuominen
14 #
15 #############################################################################
16  
17 #############################################################################
18 #
19 # Global variables & constants
20 #
21 ##############################################################################
22  
23 # Do we assert that our assumptions about the source hold?
24 my $DEF_SRC_ASS=1;
25 # Do we check first to see if the document really looks like HTML?
26 my $DEF_ASSERT_HTML=1;
27 # Do we pass on even non-HTML documents?
28 my $DEF_KEEP_ALL=0;
29 # Do we replace character entities with actual characters?
30 my $DEF_CONVERT_CHAR_ENTS=1;
31 # Do we replace numerical character entities with actual characters?
32 my $DEF_CONVERT_NUM_ENTS=0;
33 # Do we try to clean extra whitespace?
34 my $DEF_CLEAN_WS=0;
35 # Source encoding
36 my $DEF_SRC_ENCODING='utf-8';
37  
38 my $DEBUG=0;
39  
40 ###########################################################################
41 #
42 # Symbolic character entity to Unicode (decimal) mapping
43 #
44 ###########################################################################
45  
46 my %Ent2Unicode=(
47 quot =>'34', # " HTML 2.0 quotation mark
48 amp =>'38', # & HTML 2.0 ampersand
49 lt =>'60', # < HTML 2.0 less-than sign
50 gt =>'62', # > HTML 2.0 greater-than sign
51 nbsp =>'160', # HTML 3.2 no-break space
52 iexcl =>'161', # ¡ HTML 3.2 inverted exclamation mark
53 cent =>'162', # ¢ HTML 3.2 cent sign
54 pound =>'163', # £ HTML 3.2 pound sign
55 curren =>'164', # ¤ HTML 3.2 currency sign
56 yen =>'165', # ¥ HTML 3.2 yen sign
57 brvbar =>'166', # ¦ HTML 3.2 broken bar
58 sect =>'167', # § HTML 3.2 section sign
59 uml =>'168', # ¨ HTML 3.2 diaeresis
60 copy =>'169', # © HTML 3.2 copyright sign
61 ordf =>'170', # ª HTML 3.2 feminine ordinal indicator
62 laquo =>'171', # « HTML 3.2 left-pointing double angle quotation mark
63 not =>'172', # ¬ HTML 3.2 not sign
64 shy =>'173', # ­ HTML 3.2 soft hyphen
65 reg =>'174', # ® HTML 3.2 registered sign
66 macr =>'175', # ¯ HTML 3.2 macron
67 deg =>'176', # ° HTML 3.2 degree sign
68 plusmn =>'177', # ± HTML 3.2 plus-minus sign
69 sup2 =>'178', # ² HTML 3.2 superscript two
70 sup3 =>'179', # ³ HTML 3.2 superscript three
71 acute =>'180', # ´ HTML 3.2 acute accent
72 micro =>'181', # µ HTML 3.2 micro sign
73 para =>'182', # ¶ HTML 3.2 pilcrow sign
74 middot =>'183', # · HTML 3.2 middle dot
75 cedil =>'184', # ¸ HTML 3.2 cedilla
76 sup1 =>'185', # ¹ HTML 3.2 superscript one
77 ordm =>'186', # º HTML 3.2 masculine ordinal indicator
78 raquo =>'187', # » HTML 3.2 right-pointing double angle quotation mark
79 frac14 =>'188', # ¼ HTML 3.2 vulgar fraction one quarter
80 frac12 =>'189', # ½ HTML 3.2 vulgar fraction one half
81 frac34 =>'190', # ¾ HTML 3.2 vulgar fraction three quarters
82 iquest =>'191', # ¿ HTML 3.2 inverted question mark
83 Agrave =>'192', # À HTML 2.0 latin capital letter a with grave
84 Aacute =>'193', # Á HTML 2.0 latin capital letter a with acute
85 Acirc =>'194', # Â HTML 2.0 latin capital letter a with circumflex
86 Atilde =>'195', # Ã HTML 2.0 latin capital letter a with tilde
87 Auml =>'196', # Ä HTML 2.0 latin capital letter a with diaeresis
88 Aring =>'197', # Å HTML 2.0 latin capital letter a with ring above
89 AElig =>'198', # Æ HTML 2.0 latin capital letter ae
90 Ccedil =>'199', # Ç HTML 2.0 latin capital letter c with cedilla
91 Egrave =>'200', # È HTML 2.0 latin capital letter e with grave
92 Eacute =>'201', # É HTML 2.0 latin capital letter e with acute
93 Ecirc =>'202', # Ê HTML 2.0 latin capital letter e with circumflex
94 Euml =>'203', # Ë HTML 2.0 latin capital letter e with diaeresis
95 Igrave =>'204', # Ì HTML 2.0 latin capital letter i with grave
96 Iacute =>'205', # Í HTML 2.0 latin capital letter i with acute
97 Icirc =>'206', # Î HTML 2.0 latin capital letter i with circumflex
98 Iuml =>'207', # Ï HTML 2.0 latin capital letter i with diaeresis
99 ETH =>'208', # Ð HTML 2.0 latin capital letter eth
100 Ntilde =>'209', # Ñ HTML 2.0 latin capital letter n with tilde
101 Ograve =>'210', # Ò HTML 2.0 latin capital letter o with grave
102 Oacute =>'211', # Ó HTML 2.0 latin capital letter o with acute
103 Ocirc =>'212', # Ô HTML 2.0 latin capital letter o with circumflex
104 Otilde =>'213', # Õ HTML 2.0 latin capital letter o with tilde
105 Ouml =>'214', # Ö HTML 2.0 latin capital letter o with diaeresis
106 times =>'215', # × HTML 3.2 multiplication sign
107 Oslash =>'216', # Ø HTML 2.0 latin capital letter o with stroke
108 Ugrave =>'217', # Ù HTML 2.0 latin capital letter u with grave
109 Uacute =>'218', # Ú HTML 2.0 latin capital letter u with acute
110 Ucirc =>'219', # Û HTML 2.0 latin capital letter u with circumflex
111 Uuml =>'220', # Ü HTML 2.0 latin capital letter u with diaeresis
112 Yacute =>'221', # Ý HTML 2.0 latin capital letter y with acute
113 THORN =>'222', # Þ HTML 2.0 latin capital letter thorn
114 szlig =>'223', # ß HTML 2.0 latin small letter sharp s
115 agrave =>'224', # à HTML 2.0 latin small letter a with grave
116 aacute =>'225', # á HTML 2.0 latin small letter a with acute
117 acirc =>'226', # â HTML 2.0 latin small letter a with circumflex
118 atilde =>'227', # ã HTML 2.0 latin small letter a with tilde
119 auml =>'228', # ä HTML 2.0 latin small letter a with diaeresis
120 aring =>'229', # å HTML 2.0 latin small letter a with ring above
121 aelig =>'230', # æ HTML 2.0 latin small letter ae
122 ccedil =>'231', # ç HTML 2.0 latin small letter c with cedilla
123 egrave =>'232', # è HTML 2.0 latin small letter e with grave
124 eacute =>'233', # é HTML 2.0 latin small letter e with acute
125 ecirc =>'234', # ê HTML 2.0 latin small letter e with circumflex
126 euml =>'235', # ë HTML 2.0 latin small letter e with diaeresis
127 igrave =>'236', # ì HTML 2.0 latin small letter i with grave
128 iacute =>'237', # í HTML 2.0 latin small letter i with acute
129 icirc =>'238', # î HTML 2.0 latin small letter i with circumflex
130 iuml =>'239', # ï HTML 2.0 latin small letter i with diaeresis
131 eth =>'240', # ð HTML 2.0 latin small letter eth
132 ntilde =>'241', # ñ HTML 2.0 latin small letter n with tilde
133 ograve =>'242', # ò HTML 2.0 latin small letter o with grave
134 oacute =>'243', # ó HTML 2.0 latin small letter o with acute
135 ocirc =>'244', # ô HTML 2.0 latin small letter o with circumflex
136 otilde =>'245', # õ HTML 2.0 latin small letter o with tilde
137 ouml =>'246', # ö HTML 2.0 latin small letter o with diaeresis
138 divide =>'247', # ÷ HTML 3.2 division sign
139 oslash =>'248', # ø HTML 2.0 latin small letter o with stroke
140 ugrave =>'249', # ù HTML 2.0 latin small letter u with grave
141 uacute =>'250', # ú HTML 2.0 latin small letter u with acute
142 ucirc =>'251', # û HTML 2.0 latin small letter u with circumflex
143 uuml =>'252', # ü HTML 2.0 latin small letter u with diaeresis
144 yacute =>'253', # ý HTML 2.0 latin small letter y with acute
145 thorn =>'254', # þ HTML 2.0 latin small letter thorn
146 yuml =>'255', # ÿ HTML 2.0 latin small letter y with diaeresis
147 OElig =>'338', # HTML 4.0 latin capital ligature oe
148 oelig =>'339', # HTML 4.0 latin small ligature oe
149 Scaron =>'352', # HTML 4.0 latin capital letter s with caron
150 scaron =>'353', # HTML 4.0 latin small letter s with caron
151 Yuml =>'376', # HTML 4.0 latin capital letter y with diaeresis
152 fnof =>'402', # HTML 4.0 latin small letter f with hook
153 circ =>'710', # HTML 4.0 modifier letter circumflex accent
154 tilde =>'732', # HTML 4.0 small tilde
155 Alpha =>'913', # HTML 4.0 greek capital letter alpha
156 Beta =>'914', # HTML 4.0 greek capital letter beta
157 Gamma =>'915', # HTML 4.0 greek capital letter gamma
158 Delta =>'916', # HTML 4.0 greek capital letter delta
159 Epsilon =>'917', # HTML 4.0 greek capital letter epsilon
160 Zeta =>'918', # HTML 4.0 greek capital letter zeta
161 Eta =>'919', # HTML 4.0 greek capital letter eta
162 Theta =>'920', # HTML 4.0 greek capital letter theta
163 Iota =>'921', # HTML 4.0 greek capital letter iota
164 Kappa =>'922', # HTML 4.0 greek capital letter kappa
165 Lambda =>'923', # HTML 4.0 greek capital letter lamda
166 Mu =>'924', # HTML 4.0 greek capital letter mu
167 Nu =>'925', # HTML 4.0 greek capital letter nu
168 Xi =>'926', # HTML 4.0 greek capital letter xi
169 Omicron =>'927', # HTML 4.0 greek capital letter omicron
170 Pi =>'928', # HTML 4.0 greek capital letter pi
171 Rho =>'929', # HTML 4.0 greek capital letter rho
172 Sigma =>'931', # HTML 4.0 greek capital letter sigma
173 Tau =>'932', # HTML 4.0 greek capital letter tau
174 Upsilon =>'933', # HTML 4.0 greek capital letter upsilon
175 Phi =>'934', # HTML 4.0 greek capital letter phi
176 Chi =>'935', # HTML 4.0 greek capital letter chi
177 Psi =>'936', # HTML 4.0 greek capital letter psi
178 Omega =>'937', # HTML 4.0 greek capital letter omega
179 alpha =>'945', # HTML 4.0 greek small letter alpha
180 beta =>'946', # HTML 4.0 greek small letter beta
181 gamma =>'947', # HTML 4.0 greek small letter gamma
182 delta =>'948', # HTML 4.0 greek small letter delta
183 epsilon =>'949', # HTML 4.0 greek small letter epsilon
184 zeta =>'950', # HTML 4.0 greek small letter zeta
185 eta =>'951', # HTML 4.0 greek small letter eta
186 theta =>'952', # HTML 4.0 greek small letter theta
187 iota =>'953', # HTML 4.0 greek small letter iota
188 kappa =>'954', # HTML 4.0 greek small letter kappa
189 lambda =>'955', # HTML 4.0 greek small letter lamda
190 mu =>'956', # HTML 4.0 greek small letter mu
191 nu =>'957', # HTML 4.0 greek small letter nu
192 xi =>'958', # HTML 4.0 greek small letter xi
193 omicron =>'959', # HTML 4.0 greek small letter omicron
194 pi =>'960', # HTML 4.0 greek small letter pi
195 rho =>'961', # HTML 4.0 greek small letter rho
196 sigmaf =>'962', # HTML 4.0 greek small letter final sigma
197 sigma =>'963', # HTML 4.0 greek small letter sigma
198 tau =>'964', # HTML 4.0 greek small letter tau
199 upsilon =>'965', # HTML 4.0 greek small letter upsilon
200 phi =>'966', # HTML 4.0 greek small letter phi
201 chi =>'967', # HTML 4.0 greek small letter chi
202 psi =>'968', # HTML 4.0 greek small letter psi
203 omega =>'969', # HTML 4.0 greek small letter omega
204 thetasym =>'977', # HTML 4.0 greek theta symbol
205 upsih =>'978', # HTML 4.0 greek upsilon with hook symbol
206 piv =>'982', # HTML 4.0 greek pi symbol
207 ensp =>'8194', # HTML 4.0 en space [1]
208 emsp =>'8195', # HTML 4.0 em space [2]
209 thinsp =>'8201', # HTML 4.0 thin space [3]
210 zwnj =>'8204', # HTML 4.0 zero width non-joiner
211 zwj =>'8205', # HTML 4.0 zero width joiner
212 lrm =>'8206', # HTML 4.0 left-to-right mark
213 rlm =>'8207', # HTML 4.0 right-to-left mark
214 ndash =>'8211', # HTML 4.0 en dash
215 mdash =>'8212', # HTML 4.0 em dash
216 lsquo =>'8216', # HTML 4.0 left single quotation mark
217 rsquo =>'8217', # HTML 4.0 right single quotation mark
218 sbquo =>'8218', # HTML 4.0 single low-9 quotation mark
219 ldquo =>'8220', # HTML 4.0 left double quotation mark
220 rdquo =>'8221', # HTML 4.0 right double quotation mark
221 bdquo =>'8222', # HTML 4.0 double low-9 quotation mark
222 dagger =>'8224', # HTML 4.0 dagger
223 Dagger =>'8225', # HTML 4.0 double dagger
224 bull =>'8226', # HTML 4.0 bullet
225 hellip =>'8230', # HTML 4.0 horizontal ellipsis
226 permil =>'8240', # HTML 4.0 per mille sign
227 prime =>'8242', # HTML 4.0 prime
228 Prime =>'8243', # HTML 4.0 double prime
229 lsaquo =>'8249', # HTML 4.0 single left-pointing angle quotation mark
230 rsaquo =>'8250', # HTML 4.0 single right-pointing angle quotation mark
231 oline =>'8254', # HTML 4.0 overline
232 frasl =>'8260', # HTML 4.0 fraction slash
233 euro =>'8364', # HTML 4.0 euro sign
234 image =>'8465', # HTML 4.0 black-letter capital i
235 weierp =>'8472', # HTML 4.0 script capital p
236 real =>'8476', # HTML 4.0 black-letter capital r
237 trade =>'8482', # HTML 4.0 trade mark sign
238 alefsym =>'8501', # HTML 4.0 alef symbol
239 larr =>'8592', # HTML 4.0 leftwards arrow
240 uarr =>'8593', # HTML 4.0 upwards arrow
241 rarr =>'8594', # HTML 4.0 rightwards arrow
242 darr =>'8595', # HTML 4.0 downwards arrow
243 harr =>'8596', # HTML 4.0 left right arrow
244 crarr =>'8629', # HTML 4.0 downwards arrow with corner leftwards
245 lArr =>'8656', # HTML 4.0 leftwards double arrow
246 uArr =>'8657', # HTML 4.0 upwards double arrow
247 rArr =>'8658', # HTML 4.0 rightwards double arrow
248 dArr =>'8659', # HTML 4.0 downwards double arrow
249 hArr =>'8660', # HTML 4.0 left right double arrow
250 forall =>'8704', # HTML 4.0 for all
251 part =>'8706', # HTML 4.0 partial differential
252 exist =>'8707', # HTML 4.0 there exists
253 empty =>'8709', # HTML 4.0 empty set
254 nabla =>'8711', # HTML 4.0 nabla
255 isin =>'8712', # HTML 4.0 element of
256 notin =>'8713', # HTML 4.0 not an element of
257 ni =>'8715', # HTML 4.0 contains as member
258 prod =>'8719', # HTML 4.0 n-ary product
259 sum =>'8721', # HTML 4.0 n-ary summation
260 minus =>'8722', # HTML 4.0 minus sign
261 lowast =>'8727', # HTML 4.0 asterisk operator
262 radic =>'8730', # HTML 4.0 square root
263 prop =>'8733', # HTML 4.0 proportional to
264 infin =>'8734', # HTML 4.0 infinity
265 ang =>'8736', # HTML 4.0 angle
266 and =>'8743', # HTML 4.0 logical and
267 or =>'8744', # HTML 4.0 logical or
268 cap =>'8745', # HTML 4.0 intersection
269 cup =>'8746', # HTML 4.0 union
270 int =>'8747', # HTML 4.0 integral
271 there4 =>'8756', # HTML 4.0 therefore
272 sim =>'8764', # HTML 4.0 tilde operator
273 cong =>'8773', # HTML 4.0 congruent to
274 asymp =>'8776', # HTML 4.0 almost equal to
275 ne =>'8800', # HTML 4.0 not equal to
276 equiv =>'8801', # HTML 4.0 identical to
277 le =>'8804', # HTML 4.0 less-than or equal to
278 ge =>'8805', # HTML 4.0 greater-than or equal to
279 sub =>'8834', # HTML 4.0 subset of
280 sup =>'8835', # HTML 4.0 superset of
281 nsub =>'8836', # HTML 4.0 not a subset of
282 sube =>'8838', # HTML 4.0 subset of or equal to
283 supe =>'8839', # HTML 4.0 superset of or equal to
284 oplus =>'8853', # HTML 4.0 circled plus
285 otimes =>'8855', # HTML 4.0 circled times
286 perp =>'8869', # HTML 4.0 up tack
287 sdot =>'8901', # HTML 4.0 dot operator
288 lceil =>'8968', # HTML 4.0 left ceiling
289 rceil =>'8969', # HTML 4.0 right ceiling
290 lfloor =>'8970', # HTML 4.0 left floor
291 rfloor =>'8971', # HTML 4.0 right floor
292 lang =>'9001', # HTML 4.0 left-pointing angle bracket
293 rang =>'9002', # HTML 4.0 right-pointing angle bracket
294 loz =>'9674', # HTML 4.0 lozenge
295 spades =>'9824', # HTML 4.0 black spade suit
296 clubs =>'9827', # HTML 4.0 black club suit
297 hearts =>'9829', # HTML 4.0 black heart suit
298 diams=>'9830', # HTML 4.0 black diamond suit
299 );
300  
301  
302  
303  
304 #############################################################################
305 #
306 # Error message stuff
307 #
308 #############################################################################
309  
310 my $ErrStr;
311 my ($ERR_OK,
312 $ERR_EMPTY_DOC,
313 $ERR_UNK_DOCTYPE,
314 $ERR_NO_SIGNATURE,
315 $ERR_ENC,
316 $ERR_UTF8_CONV,
317 $ERR_TARGET_CONV,
318 $ERR_SRC_NOT_IN_UTF8,
319 $ERR_GUESS_ENC_UTF8_CONV
320 )=(0..8);
321 my %ErrMsgs=($ERR_OK=>"",
322 $ERR_EMPTY_DOC=>"No document (although only HTML expected)",
323 $ERR_UNK_DOCTYPE=>"Unrecognized DOCTYPE (only HTML/WML expected)",
324 $ERR_NO_SIGNATURE=>"No signature (only HTML expected)",
325 $ERR_ENC=>"Unable to instantiate Alvis::Document::Encoding.",
326 $ERR_UTF8_CONV=>"Converting from source encoding to UTF-8 failed.",
327 $ERR_TARGET_CONV=>"Converting to the output encoding failed.",
328 $ERR_SRC_NOT_IN_UTF8=>"The source is not in UTF-8.",
329 $ERR_GUESS_ENC_UTF8_CONV=>"Guessing the source encoding and " .
330 "then converting it to UTF-8 failed."
331 );
332  
333 sub _set_err_state
334 {
335 my $self=shift;
336 my $errcode=shift;
337 my $errmsg=shift;
338  
339 if (!defined($errcode))
340 {
341 confess("set_err_state() called with an undefined argument.");
342 }
343  
344 if (exists($ErrMsgs{$errcode}))
345 {
346 if ($errcode==$ERR_OK)
347 {
348 $self->{errstr}="";
349 }
350 else
351 {
352 $self->{errstr}.=" " . $ErrMsgs{$errcode};
353 if (defined($errmsg))
354 {
355 $self->{errstr}.=" " . $errmsg;
356 }
357 }
358 }
359 else
360 {
361 confess("Internal error: set_err_state() called with an " .
362 "unrecognized argument ($errcode).")
363 }
364 }
365  
366 sub errmsg
367 {
368 my $self=shift;
369  
370 return $self->{errstr};
371 }
372  
373 sub clearerr
374 {
375 my $self=shift;
376  
377 $self->{errstr}="";
378 }
379  
380 sub new
381 {
382 my $proto=shift;
383  
384 my $class=ref($proto)||$proto;
385 my $parent=ref($proto)&&$proto;
386 my $self={};
387 bless($self,$class);
388  
389 $self->_init(@_);
390  
391 $self->{encodingWiz}=Alvis::Document::Encoding->new();
392 if (!defined($self->{encodingWiz}))
393 {
394 $self->_set_err_state($ERR_ENC);
395 return undef;
396 }
397  
398 $self->_set_err_state($ERR_OK);
399  
400 return $self;
401 }
402  
403 sub _init
404 {
405 my $self=shift;
406  
407 $self->{assertHTML}=$DEF_ASSERT_HTML;
408 $self->{keepAll}=$DEF_KEEP_ALL;
409 $self->{assertSourceAssumptions}=$DEF_SRC_ASS;;
410 $self->{convertCharEnts}=$DEF_CONVERT_CHAR_ENTS;
411 $self->{convertNumEnts}=$DEF_CONVERT_NUM_ENTS;
412 $self->{cleanWhitespace}=$DEF_CLEAN_WS;
413 $self->{sourceEncoding}=$DEF_SRC_ENCODING;
414  
415 if (defined(@_))
416 {
417 my %args=@_;
418 @$self{ keys %args }=values(%args);
419 }
420 }
421  
422 #############################################################################
423 #
424 # Public methods
425 #
426 ##############################################################################
427
428 #
429 # Returns (<contents as text>,<header hash ref>)
430 #
431 sub clean
432 {
433 my $self=shift;
434 my $html=shift;
435 my $opts=shift; # if a title/base URL is wished for as well
436 # returned in a header hash with keys
437 # title, baseURL
438  
439 my %header=(title=>undef,
440 baseURL=>undef);
441  
442 $self->_set_err_state($ERR_OK); # clean the slate
443  
444 # Make it utf-8 if not already
445 my $src_enc;
446 if ($opts->{sourceEncoding})
447 {
448 $src_enc=$opts->{sourceEncoding};
449 }
450 elsif (!exists($opts->{sourceEncoding}) && $self->{sourceEncoding})
451 {
452 $src_enc=$self->{sourceEncoding};
453 }
454 if ($src_enc)
455 {
456 if ($src_enc!~/^\s*utf-?8\s*$/)
457 {
458 $html=$self->{encodingWiz}->convert($html,
459 $src_enc,
460 'utf8');
461 if (!defined($html))
462 {
463 $self->_set_err_state($ERR_UTF8_CONV,
464 $self->{encodingWiz}->errmsg());
465 return (undef,\%header); # signals "do not pass on"
466 }
467 }
468 }
469 else # try guessing the encoding
470 {
471 $html=$self->{encodingWiz}->guess_and_convert($html,
472 'text',
473 'html',
474 'utf8');
475 if (!defined($html))
476 {
477 $self->_set_err_state($ERR_GUESS_ENC_UTF8_CONV,
478 $self->{encodingWiz}->errmsg());
479 return (undef,\%header); # signals "do not pass on"
480 }
481 }
482  
483 # ex nihilo nihil
484 #
485 if (!defined($html) || $html=~/^\s*$/sgo)
486 {
487 if ($self->{keepAll})
488 {
489 return ("\n",\%header);
490 }
491 else
492 {
493 $self->_set_err_state($ERR_EMPTY_DOC);
494 return (undef,\%header); # signals "do not pass on"
495 }
496 }
497  
498 # Check if this really looks like "HTML"
499 #
500 if ($self->{assertHTML})
501 {
502 #
503 # If we're lucky...
504 #
505 if ($html=~/<!DOCTYPE\s+(\S+)/isgo)
506 {
507 my $type=$1;
508 if ($type!~/(?:html|wml)/igo)
509 {
510 if ($self->{keepAll})
511 {
512 return ("\n",\%header);
513 }
514 else
515 {
516 $self->_set_err_state($ERR_UNK_DOCTYPE,"($type)");
517 return (undef,\%header); # signals "do not pass on"
518 }
519 }
520 }
521 # Otherwise, use a weaker way of checking... a single
522 # signature start tag will do.
523 #
524 if ($html!~/<(?:(?i)html|body)\W/sgo)
525 {
526 if ($self->{keepAll})
527 {
528 return ("\n",\%header);
529 }
530 else
531 {
532 $self->_set_err_state($ERR_NO_SIGNATURE);
533 return (undef,\%header); # signals "do not pass on"
534 }
535 }
536 }
537  
538 if ($self->{assertSourceAssumptions})
539 {
540 my %err;
541 if (!$self->{encodingWiz}->is_utf8($html,\%err))
542 {
543 $self->_set_err_state($ERR_SRC_NOT_IN_UTF8,
544 $self->{encodingWiz}->errmsg());
545 return (undef,\%header); # signals "do not pass on"
546 }
547 # Remove '\0's just in case. Replace by a ' ' just in case they
548 # separated something meaningful in the original.
549 $html=~s/[\0]+/ /sgo;
550 }
551  
552 # Remove comments
553 #
554 $html=~s/<\!\-\-.*?\-\->//sgo;
555  
556 # Remove some MS & declaration crap Loses some (very little) maybe,
557 # but suffices for Alvis purposes.
558 #
559 $html=~s/<\!.*?>//sgo;
560  
561 # Extract the title if any, if desired
562 #
563 if (defined($opts->{title}))
564 {
565 my $title_cand;
566 if ($html=~/<title\W(.*?)<\/title>/isgo)
567 {
568 #
569 # Extract it
570 #
571 $title_cand=$1;
572 $title_cand=~s/=\s*([\"\'])(.*?)\1/&_neutralize_trouble($1,$2)/sgoe;
573 $title_cand=~s/^.*?>//sgo;
574
575 #
576 # Clean it
577 #
578 my $c;
579 $title_cand=~s/(?:&\#(\d+);?)/$1<256 && $1>0 ? chr($1) : ""/ego;
580 $title_cand=~s/(?:&\#[xX]([0-9a-fA-F]+);?)/$c=hex($1); $c<256 && $c>0 ? chr($c) : ""/ego;
581 $title_cand=~s/(?:&(\w+);?)/$self->_char_ent2char($1)/ego;
582
583 $title_cand=~s/\s+/ /sgo;
584 $title_cand=~s/^\s+//sgo;
585 $title_cand=~s/\s+$//sgo;
586
587 $title_cand=~s/[^A-Za-zÆÁÂÀÅÃÄÇÐÉÊÈËÍÎÌÏÑÓÔÒØÕÖÞÚÛÙÜÝáâæàåãäçéêèðëíîìïñóôòøõößþúûùüýÿ¦¨´¸¼½¾ ,\.\-:\?]//isgo;
588 }
589  
590
591 $header{title}=$title_cand;
592 }
593  
594 # Extract the base URL if any, if desired
595 #
596 if (defined($opts->{baseURL}))
597 {
598 my $base_cand;
599 if ($html=~/<base\W(.*?)>/isgo)
600 {
601 #
602 # Extract the base URL
603 #
604 my $base_pars=$1;
605 $base_pars=~s/=\s*([\"\'])(.*?)\1/&_neutralize_trouble($1,$2)/sgoe;
606
607 if ($base_pars=~/href\s*=\s*([\"\'])(.*?)\1/isgo)
608 {
609 my $href=$2;
610 $href=~s/\&/\&amp;/go;
611 $base_cand=$href;
612 }
613 }
614 $header{baseURL}=$base_cand;
615 }
616  
617 # Decapitation to avoid including the title at least
618 # and to make the following faster.
619 #
620 $html=~s/<head\W.*?<\/head>//isgo;
621  
622 # Remove the entire elements STYLE, (NO)SCRIPT
623 #
624 $html=~s/<style.*?<\/style>//isgo;
625 $html=~s/<script.*?<\/script>//isgo;
626 $html=~s/<noscript.*?<\/noscript>//isgo;
627  
628 # Tag removal. Optimized for speed.
629 # Hangs on the assumption that the input cannot contain '\0's.
630 # Algorithm:
631 # 1. Mark & replace legal tag starts with '\0'.
632 # 2. Go from the start of a tag to the beginning of
633 # the next one, neutralizing any confusing chars
634 # inside possible attribute values.
635 # 3. Pick the leftmost '>' before the start of the next
636 # tag as the end of the tag.
637 # 4. Remove all tags.
638 #
639 if ($self->{alvisKeep})
640 {
641 $html=~s/<\/?(?:(?i)a|frame|iframe|h[1-6]|p|div|dl|ul|ol|table|li|dd|dt|th|td|caption)(?=\W)/\0/sgo;
642 }
643 if ($self->{alvisRemove})
644 {
645 $html=~s/<\/?(?:(?i)tr|blockquote|hr|br|dir|menu|form|fieldset|legend|label|input|select|option|textarea|isindex|noframes|frameset|tfoot|body|tbody|html|head|abbr|acronym|address|applet|area|b|base|basefont|bdo|big|button|center|cite|code|col|colgroup|del|dfn|em|font|i|img|ins|kbd|link|map|ismap|meta|object|param|pre|q|s|samp|small|span|strike|strong|sub|sup|target|title|tt|u|var|\!doctype|\?xml)(?=\W)/\0/sgo;
646 }
647 if ($self->{obsolete})
648 {
649 $html=~s/<\/?(?:(?i)header|nextid|section|listing|xmp|plaintext)(?=\W)/\0/sgo;
650 }
651 if ($self->{proprietary})
652 {
653 $html=~s/<\/?(?:(?i)align|blink|embed|ilayer|keygen|layer|multicol|noembed|nolayer|nosave|spacer|inlineinput|sound|audioscope|blackface|animate|bgsound|comment|marquee|xml|o:p|csaction|csactions|csactiondict|csscriptdict|csactionitem|csobj|wbr|nobr|\/)(?=\W)/\0/sgo;
654 }
655 if ($self->{xhtml})
656 {
657 $html=~s/<\/?(?:(?i)ruby|rbc|rtc|rb|rt|rp)(?=\W)/\0/sgo;
658 }
659 if ($self->{wml})
660 {
661 $html=~s/<\/?(?:(?i)access|card|template|wml|anchor|do|onevent|postfield|go|noop|prev|refresh|fieldset|optgroup|select|setvar|timer)(?=\W)/\0/sgo;
662 }
663  
664 # $html=~s/=\s*([\"\'])([^\0]*?)\1/&_neutralize_trouble($1,$2)/sgoe;
665 $html=~s/(?<=\0).*?>//sgo;
666 $html=~s/\0/ /go;
667
668 # We have removed those tags we wanted to now
669
670 # If we have some tags left, do some fixing
671 if (!$self->{alvisKeep}||!$self->{alvisRemove}||!$self->{obsolete}||
672 !$self->{proprietary}||!$self->{xhtml}||!$self->{wml})
673 {
674 # Often we have <TAG ... </TAG>. Fix that.
675 $html=~s/(<\/?(?:(?i)a|frame|iframe|h[1-6]|p|div|dl|ul|ol|table|li|dd|dt|th|td|caption|tr|blockquote|hr|br|dir|menu|form|fieldset|legend|label|input|select|option|textarea|isindex|noframes|frameset|tfoot|body|tbody|html|head|abbr|acronym|address|applet|area|b|base|basefont|bdo|big|button|center|cite|code|col|colgroup|del|dfn|em|font|i|img|ins|kbd|link|map|ismap|meta|object|param|pre|q|s|samp|small|span|strike|strong|sub|sup|target|title|tt|u|var|\!doctype|\?xml|header|nextid|section|listing|xmp|plaintext|align|blink|embed|ilayer|keygen|layer|multicol|noembed|nolayer|nosave|spacer|inlineinput|sound|audioscope|blackface|animate|bgsound|comment|marquee|xml|o:p|csaction|csactions|csactiondict|csscriptdict|csactionitem|csobj|wbr|nobr|\/|ruby|rbc|rtc|rb|rt|rp|access|card|template|wml|anchor|do|onevent|postfield|go|noop|prev|refresh|fieldset|optgroup|select|setvar|timer))(?=\W)/\0$1/sgo;
676 $html=~s/(?<=\0)([^>]*?)(?=\0)/$1>/sgo;
677 $html=~s/(?<=\0)([^\0>]*?)$/$1>/sgo;
678 $html=~s/\0/ /go;
679 }
680  
681 # Alvis needs some finer tuning
682 if (!$self->{alvisKeep})
683 {
684 # Fix attributes of interest
685 $html=~s/(<a\W[^>]*?href\s*=\s*)([\"\'])(\S*?)(\s.*?)?>/$self->_fix_attr($1,$2,$3,$4)/isgoe;
686 # Fix attributes of interest
687 $html=~s/(<(?:frame|iframe|img)\W[^>]*?src\s*=\s*)([\"\'])(\S*?)(\s.*?)?>/$self->_fix_attr($1,$2,$3,$4)/isgoe;
688  
689 # Sometimes "HTML" contains Alvis tags...double safeguard them
690 $html=~s/<(\/?(?:(?i)section|list|item|ulink).*?)>/\&lt;$1\&gt;/sgo;
691 }
692
693 if ($DEBUG)
694 {
695 warn $html;
696 }
697  
698 # If wished for, convert character entities
699 if ($self->{convertCharEnts})
700 {
701 $html=~s/(?:&(\w+);)/$self->_char_ent2char($1)/ego;
702 }
703  
704 # If wished for, convert numerical character entities
705 if ($self->{convertNumEnts})
706 {
707 #
708 # Numerical entities depend on the presumed character set
709 # of the source HTML. You had better be sure it is UTF-8 or
710 # should we check here?
711 #
712 $html=~s/(?:&\#(\d+);?)/$self->_num_ent2char($1)/ego;
713 $html=~s/(?:&\#[xX]([0-9a-fA-F]+);?)/$self->_hex_ent2char($1)/ego;
714 }
715  
716 if ($self->{cleanWhitespace})
717 {
718 # Might look overcomplicated but is 3-4x faster than the
719 # first, obvious versions and does not have artificial limits on the
720 # number of consecutive non-\n ws compressed.
721 $html=~s/\n/\0/go;
722 $html=~s/\s+/ /go;
723 $html=~s/[ ](?=\0)//go;
724 $html=~s/(?<=\0)[ ]//go;
725 $html=~s/^\0+//sgo;
726 $html=~s/\0+$//sgo;
727 $html=~s/\0{3,}/\n\n/go;
728 $html=~s/\0/\n/go;
729 }
730  
731 return ($html,\%header);
732 }
733  
734 ###########################################################################
735 #
736 # Private methods
737 #
738 ###########################################################################
739  
740 sub _num_ent2char
741 {
742 my $self=shift;
743 my $num=shift;
744  
745 # check for invalid codes
746 if (!$self->{encodingWiz}->code_is_utf8($num))
747 {
748 # must be an error, don't try to fix typos atm
749 return "&#$num;";
750 }
751  
752 my $str=pack("U",$num);
753  
754 return $str;
755 }
756  
757 sub _hex_ent2char
758 {
759 my $self=shift;
760 my $num=shift;
761  
762 $num=hex($num);
763 return $self->_num_ent2char($num);
764 }
765  
766 sub _char_ent2char
767 {
768 my $self=shift;
769 my $name=shift;
770  
771 if (defined($Ent2Unicode{$name}))
772 {
773 return $Ent2Unicode{$name};
774 }
775 else
776 {
777 return "&${name};";
778 }
779 }
780  
781 #
782 # Fix a relevant broken attribute value so it ends with the same
783 # quote char it starts with
784 #
785 sub _fix_attr
786 {
787 my $self=shift;
788 my $prefix=shift;
789 my $quote=shift;
790 my $attr_value=shift;
791 my $suffix=shift;
792
793 my $txt=$prefix . $quote . $attr_value;
794 if ($attr_value!~/$quote/sgo)
795 {
796 # Add the ending quote
797 $txt.=$quote;
798 }
799  
800 if (defined($suffix))
801 {
802 # the attr value breaks at a space, where the closing > should be
803 $txt.=$suffix;
804 }
805  
806 $txt.='>';
807  
808 return $txt;
809 }
810  
811 # Transform all chars with structural meaning to character entities
812 # inside quotes.
813 sub _neutralize_trouble
814 {
815 my $quote_char=shift;
816 my $attr_value=shift;
817  
818 $attr_value=~s/</\&lt;/go;
819 $attr_value=~s/>/\&gt;/go;
820 $attr_value=~s/\"/\&quot;/go;
821 $attr_value=~s/\'/\&apos;/go;
822
823 return "= $quote_char$attr_value$quote_char";
824 }
825  
826 1;
827 __END__
« blib/lib/Alvis/Canonical.pm ↑ Summary blib/lib/Alvis/Document/Encoding.pm »