source: main/tags/2.52/gsdl/perllib/unicode.pm@ 25422

Last change on this file since 25422 was 8217, checked in by jrm21, 20 years ago

added a safety check to ensure_utf8()

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 14.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 $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 $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 $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\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 ($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 $translations{$encoding};
367
368 my $block = $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%translations = ();
385
386# @array256 is used for initialisation, there must be
387# a better way...
388# What about this?: @array256 = (0) x 256;
389@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 $translations{$encoding});
412
413 return 0 unless open (MAPFILE, $mapfile);
414 binmode (MAPFILE);
415
416 $translations{$encoding} = {'map' => [@array256], 'count' => 0};
417 my $block = $translations{$encoding};
418
419 my ($in,$i,$j);
420 while (read(MAPFILE, $in, 1) == 1) {
421 $i = unpack ("C", $in);
422 $block->{'map'}->[$i] = [@array256];
423 for ($j=0; $j<256 && read(MAPFILE, $in, 2)==2; $j++) {
424 my ($n1, $n2) = unpack ("CC", $in);
425 $block->{'map'}->[$i]->[$j] = ($n1*256) + $n2;
426 }
427 $block->{'count'} ++;
428 }
429
430 close (MAPFILE);
431}
432
433# unicode2singlebyte converts unicode to simple 8 bit encodings where
434# characters below 0x80 are normal ascii characters and the rest are encoded
435# using the appropriate mapping files.
436#
437# Examples of encodings that may be converted using unicode2singlebyte are
438# the iso-8859 and windows-125* series, KOI8-R (Russian), and the Kazakh encoding.
439sub unicode2singlebyte {
440 my ($uniref, $encoding) = @_;
441
442 my $outtext = "";
443 my $encodename = "unicode-$encoding";
444 my $enc_info = $encodings::encodings->{"$encoding"};
445 my $mapfile = &util::filename_cat($ENV{'GSDLHOME'}, "mappings",
446 "from_uc", $enc_info->{'mapfile'});
447 if (!&loadmapencoding ($encodename, $mapfile)) {
448 print STDERR "unicode: ERROR - could not load encoding $encodename\n";
449 return "";
450 }
451
452 foreach my $c (@$uniref) {
453 if ($c < 0x80) {
454 # normal ascii character
455 $outtext .= chr($c);
456 } else {
457 # extended ascii character
458 $c = &transchar ($encodename, $c);
459
460 # put a question mark if cannot translate
461 if ($c == 0) {
462 $outtext .= "?";
463 } else {
464 $outtext .= chr($c);
465 }
466 }
467 }
468 return $outtext;
469}
470
471
472# this makes sure that the referenced input string is utf8 encoded, and
473# will change/remove bytes that aren't.
474# returns 0 if the text was already utf8, or 1 if text modified to become utf8
475sub ensure_utf8 {
476 my $stringref=shift;
477
478 if (!defined($stringref) || ref($stringref) ne 'SCALAR') {
479 return $stringref;
480 }
481
482 my $value=$$stringref;
483
484 my $non_utf8_found = 0;
485 $value =~ m/^/g; # to set \G
486 while ($value =~ m!\G.*?([\x80-\xff]+)!sg) {
487 my $highbytes=$1;
488 my $highbyteslength=length($highbytes);
489 # make sure this block of high bytes is utf-8
490 $highbytes =~ /^/g; # set pos()
491 my $byte_replaced = 0;
492 while ($highbytes =~
493 m!\G (?: [\xc0-\xdf][\x80-\xbf] | # 2 byte utf-8
494 [\xe0-\xef][\x80-\xbf]{2} | # 3 byte
495 [\xf0-\xf7][\x80-\xbf]{3} # 4 byte
496 [\xf8-\xfb][\x80-\xbf]{4} # 5 byte
497 [\xfc-\xfd][\x80-\xbf]{5} # 6 byte
498 )*([\x80-\xff])? !xg
499 ) {
500 # this highbyte is "out-of-place" for valid utf-8
501 my $badbyte=$1;
502 if (!defined $badbyte) {next} # hit end of string
503 my $pos=pos($highbytes);
504 # replace bad byte. assume iso-8859-1 -> utf-8
505 # ascii2utf8 does "extended ascii"... ie iso-8859-1
506 my $replacement=&unicode::ascii2utf8(\$badbyte);
507 substr($highbytes, $pos-1, 1, $replacement);
508 # update the position to continue searching (for \G)
509 pos($highbytes) = $pos+length($replacement)-1;
510 $byte_replaced = 1;
511 }
512 if ($byte_replaced) {
513 # replace this block of high bytes in the $value
514 $non_utf8_found = 1;
515 my $replength=length($highbytes); # we've changed the length
516 my $textpos=pos($value); # pos at end of last match
517 # replace bad bytes with good bytes
518 substr($value, $textpos-$highbyteslength,
519 $highbyteslength, $highbytes);
520 # update the position to continue searching (for \G)
521 pos($value)=$textpos+($replength-$highbyteslength)+1;
522 }
523 }
524
525 $$stringref = $value;
526 return $non_utf8_found;
527}
528
5291;
Note: See TracBrowser for help on using the repository browser.