source: gsdl/trunk/perllib/unicode.pm@ 14374

Last change on this file since 14374 was 10983, checked in by jrm21, 18 years ago

better error message when we can't load an encoding

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 15.2 KB
Line 
1###########################################################################
2#
3# unicode.pm --
4# A component of the Greenstone digital library software
5# from the New Zealand Digital Library Project at the
6# University of Waikato, New Zealand.
7#
8# Copyright (C) 1999-2004 New Zealand Digital Library Project
9#
10# This program is free software; you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23#
24###########################################################################
25
26# useful functions for dealing with Unicode
27
28# Unicode strings are stored as arrays of scalars as perl
29# lacks characters are 8-bit (currently)
30
31package unicode;
32
33eval {require bytes};
34
35use encodings;
36use util;
37
38# ascii2unicode takes an (extended) ascii string (ISO-8859-1)
39# and returns a unicode array.
40sub ascii2unicode {
41 my ($in) = @_;
42 my $out = [];
43
44 my $i = 0;
45 my $len = length($in);
46 while ($i < $len) {
47 push (@$out, ord(substr ($in, $i, 1)));
48 $i++;
49 }
50
51 return $out;
52}
53
54# ascii2utf8 takes a reference to an (extended) ascii string and returns a
55# UTF-8 encoded string. This is just a faster version of
56# "&unicode2utf8(&ascii2unicode($str));"
57# "Extended ascii" really means "iso_8859_1"
58sub ascii2utf8 {
59 my ($in) = @_;
60 my $out = "";
61
62 if (!defined($in)|| !defined($$in)) {
63 return $out;
64 }
65
66 my ($c);
67 my $i = 0;
68 my $len = length($$in);
69 while ($i < $len) {
70 $c = ord (substr ($$in, $i, 1));
71 if ($c < 0x80) {
72 # ascii character
73 $out .= chr ($c);
74
75 } else {
76 # extended ascii character
77 $out .= chr (0xc0 + (($c >> 6) & 0x1f));
78 $out .= chr (0x80 + ($c & 0x3f));
79 }
80 $i++;
81 }
82
83 return $out;
84}
85
86# unicode2utf8 takes a unicode array as input and encodes it
87# using utf-8
88sub unicode2utf8 {
89 my ($in) = @_;
90 my $out = "";
91
92 foreach my $num (@$in) {
93 next unless defined $num;
94 if ($num < 0x80) {
95 $out .= chr ($num);
96
97 } elsif ($num < 0x800) {
98 $out .= chr (0xc0 + (($num >> 6) & 0x1f));
99 $out .= chr (0x80 + ($num & 0x3f));
100
101 } elsif ($num < 0xFFFF) {
102 $out .= chr (0xe0 + (($num >> 12) & 0xf));
103 $out .= chr (0x80 + (($num >> 6) & 0x3f));
104 $out .= chr (0x80 + ($num & 0x3f));
105
106 } else {
107 # error, don't encode anything
108 die;
109 }
110 }
111 return $out;
112}
113
114# utf82unicode takes a utf-8 string and produces a unicode
115# array
116sub utf82unicode {
117 my ($in) = @_;
118 my $out = [];
119
120 my $i = 0;
121 my ($c1, $c2, $c3);
122 my $len = length($in);
123 while ($i < $len) {
124 if (($c1 = ord(substr ($in, $i, 1))) < 0x80) {
125 # normal ascii character
126 push (@$out, $c1);
127
128 } elsif ($c1 < 0xc0) {
129 # error, was expecting the first byte of an
130 # encoded character. Do nothing.
131
132 } elsif ($c1 < 0xe0 && $i+1 < $len) {
133 # an encoded character with two bytes
134 $c2 = ord (substr ($in, $i+1, 1));
135 if ($c2 >= 0x80 && $c2 < 0xc0) {
136 # everything looks ok
137 push (@$out, ((($c1 & 0x1f) << 6) +
138 ($c2 & 0x3f)));
139 $i++; # gobbled an extra byte
140 }
141
142 } elsif ($c1 < 0xf0 && $i+2 < $len) {
143 # an encoded character with three bytes
144 $c2 = ord (substr ($in, $i+1, 1));
145 $c3 = ord (substr ($in, $i+2, 1));
146 if ($c2 >= 0x80 && $c2 < 0xc0 &&
147 $c3 >= 0x80 && $c3 < 0xc0) {
148 # everything looks ok
149 push (@$out, ((($c1 & 0xf) << 12) +
150 (($c2 & 0x3f) << 6) +
151 ($c3 & 0x3f)));
152
153 $i += 2; # gobbled an extra two bytes
154 }
155
156 } else {
157 # error, only decode Unicode characters not full UCS.
158 # Do nothing.
159 }
160
161 $i++;
162 }
163
164 return $out;
165}
166
167# unicode2ucs2 takes a unicode array and produces a UCS-2
168# unicode string (every two bytes forms a unicode character)
169sub unicode2ucs2 {
170 my ($in) = @_;
171 my $out = "";
172
173 foreach my $num (@$in) {
174 $out .= chr (($num & 0xff00) >> 8);
175 $out .= chr ($num & 0xff);
176 }
177
178 return $out;
179}
180
181# ucs22unicode takes a UCS-2 string and produces a unicode array
182sub ucs22unicode {
183 my ($in) = @_;
184 my $out = [];
185
186 my $i = 0;
187 my $len = length ($in);
188 while ($i+1 < $len) {
189 push (@$out, ord (substr($in, $i, 1)) << 8 +
190 ord (substr($in, $i+1, 1)));
191
192 $i ++;
193 }
194
195 return $out;
196}
197
198# takes a reference to a string and returns a reference to a unicode array
199sub convert2unicode {
200 my ($encoding, $textref) = @_;
201
202 if (!defined $encodings::encodings->{$encoding}) {
203 print STDERR "unicode::convert2unicode: ERROR: Unsupported encoding ($encoding)\n";
204 return [];
205 }
206
207 my $encodename = "$encoding-unicode";
208 my $enc_info = $encodings::encodings->{$encoding};
209 my $mapfile = &util::filename_cat($ENV{'GSDLHOME'}, "mappings",
210 "to_uc", $enc_info->{'mapfile'});
211 if (!&loadmapencoding ($encodename, $mapfile)) {
212 print STDERR "unicode: ERROR - could not load encoding $encodename: $! $mapfile\n";
213 return [];
214 }
215
216 if (defined $enc_info->{'converter'}) {
217 my $converter = $enc_info->{'converter'};
218 return &$converter ($encodename, $textref);
219 }
220
221 if ($unicode::translations{$encodename}->{'count'} == 1) {
222 return &singlebyte2unicode ($encodename, $textref);
223 } else {
224 return &doublebyte2unicode ($encodename, $textref);
225 }
226}
227
228# singlebyte2unicode converts simple 8 bit encodings where characters below
229# 0x80 are normal ascii characters and the rest are decoded using the
230# appropriate mapping files.
231#
232# Examples of encodings that may be converted using singlebyte2unicode are
233# the iso-8859 and windows-125* series.
234sub singlebyte2unicode {
235 my ($encodename, $textref) = @_;
236
237 my @outtext = ();
238 my $len = length($$textref);
239 my ($c);
240 my $i = 0;
241
242 while ($i < $len) {
243 if (($c = ord(substr($$textref, $i, 1))) < 0x80) {
244 # normal ascii character
245 push (@outtext, $c);
246 } else {
247 $c = &transchar ($encodename, $c);
248 # put a black square if cannot translate
249 $c = 0x25A1 if $c == 0;
250 push (@outtext, $c);
251 }
252 $i ++;
253 }
254 return \@outtext;
255}
256
257# doublebyte2unicode converts simple two byte encodings where characters
258# below code point 0x80 are single-byte characters and the rest are
259# double-byte characters.
260#
261# Examples of encodings that may be converted using doublebyte2unicode are
262# CJK encodings like GB encoded Chinese and UHC Korean.
263#
264# Note that no error checking is performed to make sure that the input text
265# is valid for the given encoding.
266#
267# Also, encodings that may contain characters of more than two bytes are
268# not supported (any EUC encoded text may in theory contain 3-byte
269# characters but in practice only one and two byte characters are used).
270sub doublebyte2unicode {
271 my ($encodename, $textref) = @_;
272
273 my @outtext = ();
274 my $len = length($$textref);
275 my ($c1, $c2);
276 my $i = 0;
277
278 while ($i < $len) {
279 if (($c1 = ord(substr($$textref, $i, 1))) >= 0x80) {
280 if ($i+1 < $len) {
281 # double-byte character
282 $c2 = ord(substr($$textref, $i+1, 1));
283 my $c = &transchar ($encodename, ($c1 << 8) | $c2);
284 # put a black square if cannot translate
285 $c = 0x25A1 if $c == 0;
286 push (@outtext, $c);
287 $i += 2;
288
289 } else {
290 # error
291 print STDERR "unicode: ERROR missing second half of double-byte character\n";
292 $i++;
293 }
294
295 } else {
296 # single-byte character
297 push (@outtext, $c1);
298 $i++;
299 }
300 }
301 return \@outtext;
302}
303
304# Shift-JIS to unicode
305# We can't use doublebyte2unicode for Shift-JIS because it uses some
306# single-byte characters above code point 0x80 (i.e. half-width katakana
307# characters in the range 0xA1-0xDF)
308sub shiftjis2unicode {
309 my ($encodename, $textref) = @_;
310
311 my @outtext = ();
312 my $len = length($$textref);
313 my ($c1, $c2);
314 my $i = 0;
315
316 while ($i < $len) {
317 $c1 = ord(substr($$textref, $i, 1));
318
319 if (($c1 >= 0xA1 && $c1 <= 0xDF) || $c1 == 0x5c || $c1 == 0x7E) {
320 # Single-byte half-width katakana character or
321 # JIS Roman yen or overline characters
322 my $c = &transchar ($encodename, $c1);
323 # - put a black square if cannot translate
324 $c = 0x25A1 if $c == 0;
325 push (@outtext, $c);
326 $i++;
327
328 } elsif ($c1 < 0x80) {
329 # ASCII
330 push (@outtext, $c1);
331 $i ++;
332
333 } elsif ($c1 < 0xEF) {
334 if ($i+1 < $len) {
335 $c2 = ord(substr($$textref, $i+1, 1));
336 if (($c2 >= 0x40 && $c2 <= 0x7E) || ($c2 >= 0x80 && $c2 <= 0xFC)) {
337 # Double-byte shift-jis character
338 my $c = &transchar ($encodename, ($c1 << 8) | $c2);
339 # put a black square if cannot translate
340 $c = 0x25A1 if $c == 0;
341 push (@outtext, $c);
342 } else {
343 # error
344 print STDERR "unicode: ERROR Invalid Shift-JIS character\n";
345 }
346 $i += 2;
347 } else {
348 # error
349 print STDERR "unicode: ERROR missing second half of Shift-JIS character\n";
350 $i ++;
351 }
352 } else {
353 # error
354 print STDERR "unicode: ERROR Invalid Shift-JIS character\n";
355 $i ++;
356 }
357 }
358 return \@outtext;
359}
360
361sub transchar {
362 my ($encoding, $from) = @_;
363 my $high = ($from / 256) % 256;
364 my $low = $from % 256;
365
366 return 0 unless defined $unicode::translations{$encoding};
367
368 my $block = $unicode::translations{$encoding}->{'map'};
369
370 if (ref ($block->[$high]) ne "ARRAY") {
371 return 0;
372 }
373 return $block->[$high]->[$low];
374}
375
376# %translations is of the form:
377#
378# encodings{encodingname-encodingname}->{'map'}->blocktranslation
379# blocktranslation->[[0-255],[256-511], ..., [65280-65535]]
380#
381# Any of the top translation blocks can point to an undefined
382# value. This data structure aims to allow fast translation and
383# efficient storage.
384%unicode::translations = ();
385
386# @array256 is used for initialisation, there must be
387# a better way...
388# What about this?: @array256 = (0) x 256;
389@unicode::array256 = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
390 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
391 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
392 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
393 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
394 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
395 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
396 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
397 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
398 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
399 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
400 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
401 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
402 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
403 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
404 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
405
406# returns 1 if successful, 0 if unsuccessful
407sub loadmapencoding {
408 my ($encoding, $mapfile) = @_;
409
410 # check to see if the encoding has already been loaded
411 return 1 if (defined $unicode::translations{$encoding});
412
413 if (! -r $mapfile || -d $mapfile) {
414 return 0;
415 }
416 return 0 unless open (MAPFILE, $mapfile);
417 binmode (MAPFILE);
418
419 $unicode::translations{$encoding} = {'map' => [@unicode::array256], 'count' => 0};
420 my $block = $unicode::translations{$encoding};
421
422 my ($in,$i,$j);
423 while (1) {
424 my $ret=read(MAPFILE, $in, 1);
425 if (!defined($ret)) { # error
426 print STDERR "unicode.pm: error reading mapfile: $!\n";
427 last;
428 }
429 if ($ret != 1) { last }
430 $i = unpack ("C", $in);
431 $block->{'map'}->[$i] = [@unicode::array256];
432 for ($j=0; $j<256 && read(MAPFILE, $in, 2)==2; $j++) {
433 my ($n1, $n2) = unpack ("CC", $in);
434 $block->{'map'}->[$i]->[$j] = ($n1*256) + $n2;
435 }
436 $block->{'count'} ++;
437 }
438
439 close (MAPFILE);
440}
441
442# unicode2singlebyte converts unicode to simple 8 bit encodings where
443# characters below 0x80 are normal ascii characters and the rest are encoded
444# using the appropriate mapping files.
445#
446# Examples of encodings that may be converted using unicode2singlebyte are
447# the iso-8859 and windows-125* series, KOI8-R (Russian), and the Kazakh encoding.
448sub unicode2singlebyte {
449 my ($uniref, $encoding) = @_;
450
451 my $outtext = "";
452 my $encodename = "unicode-$encoding";
453
454 if (!exists $encodings::encodings->{$encoding}) {
455 print STDERR "unicode.pm: ERROR - unsupported encoding "
456 . "'$encoding' requested\n";
457 return "";
458 }
459
460 my $enc_info = $encodings::encodings->{$encoding};
461 my $mapfile = &util::filename_cat($ENV{'GSDLHOME'}, "mappings",
462 "from_uc", $enc_info->{'mapfile'});
463 if (!&loadmapencoding ($encodename, $mapfile)) {
464 print STDERR "unicode: ERROR - could not load encoding $encodename: $! $mapfile\n";
465 return "";
466 }
467
468 foreach my $c (@$uniref) {
469 if ($c < 0x80) {
470 # normal ascii character
471 $outtext .= chr($c);
472 } else {
473 # extended ascii character
474 $c = &transchar ($encodename, $c);
475
476 # put a question mark if cannot translate
477 if ($c == 0) {
478 $outtext .= "?";
479 } else {
480 $outtext .= chr($c);
481 }
482 }
483 }
484 return $outtext;
485}
486
487
488# this makes sure that the referenced input string is utf8 encoded, and
489# will change/remove bytes that aren't.
490# returns 0 if the text was already utf8, or 1 if text modified to become utf8
491sub ensure_utf8 {
492 my $stringref=shift;
493
494 if (!defined($stringref) || ref($stringref) ne 'SCALAR') {
495 return $stringref;
496 }
497
498 my $value=$$stringref;
499
500 my $non_utf8_found = 0;
501 $value =~ m/^/g; # to set \G
502 while ($value =~ m!\G.*?([\x80-\xff]+)!sg) {
503 my $highbytes=$1;
504 my $highbyteslength=length($highbytes);
505 # make sure this block of high bytes is utf-8
506 $highbytes =~ /^/g; # set pos()
507 my $byte_replaced = 0;
508 while ($highbytes =~
509 m!\G (?: [\xc0-\xdf][\x80-\xbf] | # 2 byte utf-8
510 [\xe0-\xef][\x80-\xbf]{2} | # 3 byte
511 [\xf0-\xf7][\x80-\xbf]{3} | # 4 byte
512 [\xf8-\xfb][\x80-\xbf]{4} | # 5 byte
513 [\xfc-\xfd][\x80-\xbf]{5} | # 6 byte
514 )*([\x80-\xff])? !xg
515 ) {
516 # this highbyte is "out-of-place" for valid utf-8
517 my $badbyte=$1;
518 if (!defined $badbyte) {next} # hit end of string
519 my $pos=pos($highbytes);
520 # replace bad byte. assume iso-8859-1 -> utf-8
521 # ascii2utf8 does "extended ascii"... ie iso-8859-1
522 my $replacement=&unicode::ascii2utf8(\$badbyte);
523 substr($highbytes, $pos-1, 1, $replacement);
524 # update the position to continue searching (for \G)
525 pos($highbytes) = $pos+length($replacement)-1;
526 $byte_replaced = 1;
527 }
528 if ($byte_replaced) {
529 # replace this block of high bytes in the $value
530 $non_utf8_found = 1;
531 my $replength=length($highbytes); # we've changed the length
532 my $textpos=pos($value); # pos at end of last match
533 # replace bad bytes with good bytes
534 substr($value, $textpos-$highbyteslength,
535 $highbyteslength, $highbytes);
536 # update the position to continue searching (for \G)
537 pos($value)=$textpos+($replength-$highbyteslength)+1;
538 }
539 }
540
541 $$stringref = $value;
542 return $non_utf8_found;
543}
544
545
546sub substr
547{
548 my ($utf8_string, $offset, $length) = @_;
549
550 my @unicode_string = @{&utf82unicode($utf8_string)};
551 my $unicode_string_length = scalar(@unicode_string);
552
553 my $substr_start = $offset;
554 if ($substr_start >= $unicode_string_length) {
555 return "";
556 }
557
558 my $substr_end = $offset + $length - 1;
559 if ($substr_end >= $unicode_string_length) {
560 $substr_end = $unicode_string_length - 1;
561 }
562
563 my @unicode_substring = @unicode_string[$substr_start..$substr_end];
564 return &unicode2utf8(\@unicode_substring);
565}
566
567
5681;
Note: See TracBrowser for help on using the repository browser.