da8823fa5d8d604d9e9ab209d6f992b4c6e02d46
[lhc/web/wiklou.git] / includes / normal / UtfNormalUtil.php
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 # Some of these functions are adapted from places in MediaWiki.
21 # Should probably merge them for consistency.
22
23 function codepointToUtf8( $codepoint ) {
24 if($codepoint < 0x80) return chr($codepoint);
25 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
26 chr($codepoint & 0x3f | 0x80);
27 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
28 chr($codepoint >> 6 & 0x3f | 0x80) .
29 chr($codepoint & 0x3f | 0x80);
30 if($codepoint < 0x110000) return chr($codepoint >> 18 & 0x07 | 0xf0) .
31 chr($codepoint >> 12 & 0x3f | 0x80) .
32 chr($codepoint >> 6 & 0x3f | 0x80) .
33 chr($codepoint & 0x3f | 0x80);
34
35 die("Asked for code outside of range ($codepoint)\n");
36 }
37
38 function hexSequenceToUtf8( $sequence ) {
39 $utf = '';
40 foreach( explode( ' ', $sequence ) as $hex ) {
41 $n = hexdec( $hex );
42 $utf .= codepointToUtf8( $n );
43 }
44 return $utf;
45 }
46
47 function utf8ToCodepoint( $char ) {
48 # Find the length
49 $z = ord( $char{0} );
50 if ( $z & 0x80 ) {
51 $length = 0;
52 while ( $z & 0x80 ) {
53 $length++;
54 $z <<= 1;
55 }
56 } else {
57 $length = 1;
58 }
59
60 if ( $length != strlen( $char ) ) {
61 return false;
62 }
63 if ( $length == 1 ) {
64 return ord( $char );
65 }
66
67 # Mask off the length-determining bits and shift back to the original location
68 $z &= 0xff;
69 $z >>= $length;
70
71 # Add in the free bits from subsequent bytes
72 for ( $i=1; $i<$length; $i++ ) {
73 $z <<= 6;
74 $z |= ord( $char{$i} ) & 0x3f;
75 }
76
77 # Make entity
78 return $z;
79 }
80
81 function escapeSingleString( $string ) {
82 return strtr( $string,
83 array(
84 '\\' => '\\\\',
85 '\'' => '\\\''
86 ));
87 }
88
89 ?>