Project

General

Profile

1 552 thorn
<?php
2
3 554 Ruebenwurz
// $Id$
4 552 thorn
5
/*
6
7
 Website Baker Project <http://www.websitebaker.org/>
8 915 Ruebenwurz
 Copyright (C) 2004-2009, Ryan Djurovich
9 552 thorn
10
 Website Baker 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
 Website Baker 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 Website Baker; if not, write to the Free Software
22
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
24
*/
25
26
/*
27 761 thorn
 * A part of this file is based on 'utf8.php' from the DokuWiki-project.
28 552 thorn
 * (http://www.splitbrain.org/projects/dokuwiki):
29
 **
30
 * UTF8 helper functions
31
 * @license    LGPL (http://www.gnu.org/copyleft/lesser.html)
32
 * @author     Andreas Gohr <andi@splitbrain.org>
33
 **
34
 * modified for use with Website Baker
35
 * from thorn, Jan. 2008
36 761 thorn
 *
37
 * most of the original functions appeared to be to slow with large strings, so i replaced them with my own ones
38
 * thorn, Mar. 2008
39 552 thorn
 */
40
41
// Functions we use in Website Baker:
42
//   entities_to_7bit()
43
//   entities_to_umlauts2()
44
//   umlauts_to_entities2()
45
46 1420 Luisehahne
// Must include code to stop this file being access directly
47
if(defined('WB_PATH') == false) { die("Cannot access this file directly"); }
48 552 thorn
49
/*
50
 * check for mb_string support
51
 */
52 761 thorn
//define('UTF8_NOMBSTRING',1); // uncomment this to forbid use of mb_string-functions
53 552 thorn
if(!defined('UTF8_MBSTRING')){
54
  if(function_exists('mb_substr') && !defined('UTF8_NOMBSTRING')){
55
    define('UTF8_MBSTRING',1);
56
  }else{
57
    define('UTF8_MBSTRING',0);
58
  }
59
}
60
61
if(UTF8_MBSTRING){ mb_internal_encoding('UTF-8'); }
62
63
require_once(WB_PATH.'/framework/charsets_table.php');
64
65
/*
66
 * Checks if a string contains 7bit ASCII only
67
 *
68 758 thorn
 * @author thorn
69 552 thorn
 */
70
function utf8_isASCII($str){
71 758 thorn
	if(preg_match('/[\x80-\xFF]/', $str))
72
		return false;
73
	else
74
		return true;
75 552 thorn
}
76
77
/*
78
 * Tries to detect if a string is in Unicode encoding
79
 *
80
 * @author <bmorel@ssi.fr>
81
 * @link   http://www.php.net/manual/en/function.utf8-encode.php
82
 */
83
function utf8_check($Str) {
84
 for ($i=0; $i<strlen($Str); $i++) {
85
  $b = ord($Str[$i]);
86
  if ($b < 0x80) continue; # 0bbbbbbb
87
  elseif (($b & 0xE0) == 0xC0) $n=1; # 110bbbbb
88
  elseif (($b & 0xF0) == 0xE0) $n=2; # 1110bbbb
89
  elseif (($b & 0xF8) == 0xF0) $n=3; # 11110bbb
90
  elseif (($b & 0xFC) == 0xF8) $n=4; # 111110bb
91
  elseif (($b & 0xFE) == 0xFC) $n=5; # 1111110b
92
  else return false; # Does not match any model
93
  for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
94
   if ((++$i == strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80))
95
   return false;
96
  }
97
 }
98
 return true;
99
}
100
101
/*
102
 * Romanize a non-latin string
103
 *
104
 * @author Andreas Gohr <andi@splitbrain.org>
105
 */
106
function utf8_romanize($string){
107
  if(utf8_isASCII($string)) return $string; //nothing to do
108
109
  global $UTF8_ROMANIZATION;
110
  return strtr($string,$UTF8_ROMANIZATION);
111
}
112
113
/*
114
 * Removes special characters (nonalphanumeric) from a UTF-8 string
115
 *
116
 * This function adds the controlchars 0x00 to 0x19 to the array of
117
 * stripped chars (they are not included in $UTF8_SPECIAL_CHARS2)
118
 *
119
 * @author Andreas Gohr <andi@splitbrain.org>
120
 * @param  string $string     The UTF8 string to strip of special chars
121
 * @param  string $repl       Replace special with this string
122
 * @param  string $additional Additional chars to strip (used in regexp char class)
123
 */
124
function utf8_stripspecials($string,$repl='',$additional=''){
125
  global $UTF8_SPECIAL_CHARS2;
126
127
  static $specials = null;
128
  if(is_null($specials)){
129
    $specials = preg_quote($UTF8_SPECIAL_CHARS2, '/');
130
  }
131
132
  return preg_replace('/['.$additional.'\x00-\x19'.$specials.']/u',$repl,$string);
133
}
134
135
/*
136 761 thorn
 * added functions - thorn
137 552 thorn
 */
138
139
/*
140 761 thorn
 * faster replacement for utf8_entities_to_umlauts()
141
 * not all features of utf8_entities_to_umlauts() --> utf8_unhtml() are supported!
142
 * @author thorn
143 552 thorn
 */
144 761 thorn
function utf8_fast_entities_to_umlauts($str) {
145
	if(UTF8_MBSTRING) {
146
		// we need this for use with mb_convert_encoding
147 881 thorn
		$str = str_replace(array('&amp;','&gt;','&lt;','&quot;','&#039;','&nbsp;'), array('&amp;amp;','&amp;gt;','&amp;lt;','&amp;quot;','&amp;#39;','&amp;nbsp;'), $str);
148 761 thorn
		// we need two mb_convert_encoding()-calls - is this a bug?
149
		// mb_convert_encoding("ö&ouml;", 'UTF-8', 'HTML-ENTITIES'); // with string in utf-8-encoding doesn't work. Result: "öö"
150
		// Work-around: convert all umlauts to entities first ("ö&ouml;"->"&ouml;&ouml;"), then all entities to umlauts ("&ouml;&ouml;"->"öö")
151
		return(mb_convert_encoding(mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8'),'UTF-8', 'HTML-ENTITIES'));
152
	} else {
153
		global $named_entities;global $numbered_entities;
154
		$str = str_replace($named_entities, $numbered_entities, $str);
155
		$str = preg_replace("/&#([0-9]+);/e", "code_to_utf8($1)", $str);
156
	}
157
	return($str);
158 552 thorn
}
159 761 thorn
// support-function for utf8_fast_entities_to_umlauts()
160
function code_to_utf8($num) {
161
	if ($num <= 0x7F) {
162
		return chr($num);
163
	} elseif ($num <= 0x7FF) {
164
		return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
165
	} elseif ($num <= 0xFFFF) {
166
		 return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
167
	} elseif ($num <= 0x1FFFFF) {
168
		return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
169
	}
170
	return "?";
171 552 thorn
}
172
173
/*
174 761 thorn
 * faster replacement for utf8_umlauts_to_entities()
175
 * not all features of utf8_umlauts_to_entities() --> utf8_tohtml() are supported!
176
 * @author thorn
177 552 thorn
 */
178 761 thorn
function utf8_fast_umlauts_to_entities($string, $named_entities=true) {
179
	if(UTF8_MBSTRING)
180
		return(mb_convert_encoding($string, 'HTML-ENTITIES', 'UTF-8'));
181
	else {
182
		global $named_entities;global $numbered_entities;
183
		$new = "";
184
		$i=0;
185
		$len=strlen($string);
186
		if($len==0) return $string;
187
		do {
188
			if(ord($string{$i}) <= 127) $ud = $string{$i++};
189
			elseif(ord($string{$i}) <= 223) $ud = (ord($string{$i++})-192)*64 + (ord($string{$i++})-128);
190
			elseif(ord($string{$i}) <= 239) $ud = (ord($string{$i++})-224)*4096 + (ord($string{$i++})-128)*64 + (ord($string{$i++})-128);
191
			elseif(ord($string{$i}) <= 247) $ud = (ord($string{$i++})-240)*262144 + (ord($string{$i++})-128)*4096 + (ord($string{$i++})-128)*64 + (ord($string{$i++})-128);
192
			else $ud = ord($string{$i++}); // error!
193
			if($ud > 127) {
194
				$new .= "&#$ud;";
195
			} else {
196
				$new .= $ud;
197
			}
198
		} while($i < $len);
199
		$string = $new;
200
		if($named_entities)
201
			$string = str_replace($numbered_entities, $named_entities, $string);
202
	}
203
	return($string);
204 552 thorn
}
205
206
/*
207
 * Converts from various charsets to UTF-8
208
 *
209
 * Will convert a string from various charsets to UTF-8.
210 761 thorn
 * HTML-entities may be converted, too.
211 552 thorn
 * In case of error the returned string is unchanged, and a message is emitted.
212
 * Supported charsets are:
213
 * direct: iso_8859_1 iso_8859_2 iso_8859_3 iso_8859_4 iso_8859_5
214
 *         iso_8859_6 iso_8859_7 iso_8859_8 iso_8859_9 iso_8859_10 iso_8859_11
215
 * mb_convert_encoding: all wb charsets (except those from 'direct'); but not GB2312
216
 * iconv:  all wb charsets (except those from 'direct')
217
 *
218
 * @param  string  A string in supported encoding
219
 * @param  string  The charset to convert from, defaults to DEFAULT_CHARSET
220
 * @return string  A string in UTF-8-encoding, with all entities decoded, too.
221
 *                 String is unchanged in case of error.
222 761 thorn
 * @author thorn
223 552 thorn
 */
224 761 thorn
function charset_to_utf8($str, $charset_in=DEFAULT_CHARSET, $decode_entities=true) {
225 552 thorn
	global $iso_8859_2_to_utf8, $iso_8859_3_to_utf8, $iso_8859_4_to_utf8, $iso_8859_5_to_utf8, $iso_8859_6_to_utf8, $iso_8859_7_to_utf8, $iso_8859_8_to_utf8, $iso_8859_9_to_utf8, $iso_8859_10_to_utf8, $iso_8859_11_to_utf8;
226
	$charset_in = strtoupper($charset_in);
227
	if ($charset_in == "") { $charset_in = 'UTF-8'; }
228
	$wrong_ISO8859 = false;
229
	$converted = false;
230
231 782 thorn
	if((!function_exists('iconv') && !UTF8_MBSTRING && ($charset_in=='BIG5' || $charset_in=='ISO-2022-JP' || $charset_in=='ISO-2022-KR')) || (!function_exists('iconv') && $charset_in=='GB2312')) {
232 552 thorn
		// Nothing we can do here :-(
233
		// Charset is one of those obscure ISO-2022... or BIG5, GB2312 or something
234
		// and we can't use mb_convert_encoding() or iconv();
235
		// Emit an error-message.
236
		trigger_error("Can't convert from $charset_in without mb_convert_encoding() or iconv(). Use UTF-8 instead.", E_USER_WARNING);
237
		return($str);
238
	}
239
240
	// check if we have UTF-8 or a plain ASCII string
241
	if($charset_in == 'UTF-8' || utf8_isASCII($str)) {
242
		// we have utf-8. Just replace HTML-entities and return
243 761 thorn
		if($decode_entities && preg_match('/&[#0-9a-zA-Z]+;/',$str))
244
			return(utf8_fast_entities_to_umlauts($str));
245 552 thorn
		else // nothing to do
246
			return($str);
247
	}
248
249
	// Convert $str to utf8
250
	if(substr($charset_in,0,8) == 'ISO-8859') {
251
		switch($charset_in) {
252
			case 'ISO-8859-1': $str=utf8_encode($str); break;
253
			case 'ISO-8859-2': $str=strtr($str, $iso_8859_2_to_utf8); break;
254
			case 'ISO-8859-3': $str=strtr($str, $iso_8859_3_to_utf8); break;
255
			case 'ISO-8859-4': $str=strtr($str, $iso_8859_4_to_utf8); break;
256
			case 'ISO-8859-5': $str=strtr($str, $iso_8859_5_to_utf8); break;
257
			case 'ISO-8859-6': $str=strtr($str, $iso_8859_6_to_utf8); break;
258
			case 'ISO-8859-7': $str=strtr($str, $iso_8859_7_to_utf8); break;
259
			case 'ISO-8859-8': $str=strtr($str, $iso_8859_8_to_utf8); break;
260
			case 'ISO-8859-9': $str=strtr($str, $iso_8859_9_to_utf8); break;
261
			case 'ISO-8859-10': $str=strtr($str, $iso_8859_10_to_utf8); break;
262
			case 'ISO-8859-11': $str=strtr($str, $iso_8859_11_to_utf8); break;
263
			default: $wrong_ISO8859 = true;
264
		}
265
		if(!$wrong_ISO8859)
266
			$converted = true;
267
	}
268
	if(!$converted && UTF8_MBSTRING && $charset_in != 'GB2312') {
269
		// $charset is neither UTF-8 nor a known ISO-8859...
270
		// Try mb_convert_encoding() - but there's no GB2312 encoding in php's mb_* functions
271
		$str = mb_convert_encoding($str, 'UTF-8', $charset_in);
272
		$converted = true;
273
	} elseif(!$converted) { // Try iconv
274
		if(function_exists('iconv')) {
275
			$str = iconv($charset_in, 'UTF-8', $str);
276
			$converted = true;
277
		}
278
	}
279
	if($converted) {
280
		// we have utf-8, now replace HTML-entities and return
281 761 thorn
		if($decode_entities && preg_match('/&[#0-9a-zA-Z]+;/',$str))
282
			$str = utf8_fast_entities_to_umlauts($str);
283 552 thorn
		return($str);
284
	}
285
286
	// Nothing we can do here :-(
287
	// Charset is one of those obscure ISO-2022... or BIG5, GB2312 or something
288
	// and we can't use mb_convert_encoding() or iconv();
289
	// Emit an error-message.
290
	trigger_error("Can't convert from $charset_in without mb_convert_encoding() or iconv(). Use UTF-8 instead.", E_USER_WARNING);
291
292
	return $str;
293
}
294
295
/*
296
 * Converts from UTF-8 to various charsets
297
 *
298
 * Will convert a string from UTF-8 to various charsets.
299 761 thorn
 * HTML-entities will not! be converted.
300 552 thorn
 * In case of error the returned string is unchanged, and a message is emitted.
301
 * Supported charsets are:
302
 * direct: iso_8859_1 iso_8859_2 iso_8859_3 iso_8859_4 iso_8859_5
303
 *         iso_8859_6 iso_8859_7 iso_8859_8 iso_8859_9 iso_8859_10 iso_8859_11
304
 * mb_convert_encoding: all wb charsets (except those from 'direct'); but not GB2312
305
 * iconv:  all wb charsets (except those from 'direct')
306
 *
307
 * @param  string  An UTF-8 encoded string
308
 * @param  string  The charset to convert to, defaults to DEFAULT_CHARSET
309
 * @return string  A string in a supported encoding, with all entities decoded, too.
310
 *                 String is unchanged in case of error.
311 761 thorn
 * @author thorn
312 552 thorn
 */
313
function utf8_to_charset($str, $charset_out=DEFAULT_CHARSET) {
314
	global $utf8_to_iso_8859_2, $utf8_to_iso_8859_3, $utf8_to_iso_8859_4, $utf8_to_iso_8859_5, $utf8_to_iso_8859_6, $utf8_to_iso_8859_7, $utf8_to_iso_8859_8, $utf8_to_iso_8859_9, $utf8_to_iso_8859_10, $utf8_to_iso_8859_11;
315
	$charset_out = strtoupper($charset_out);
316
	$wrong_ISO8859 = false;
317
	$converted = false;
318
319 782 thorn
	if((!function_exists('iconv') && !UTF8_MBSTRING && ($charset_out=='BIG5' || $charset_out=='ISO-2022-JP' || $charset_out=='ISO-2022-KR')) || (!function_exists('iconv') && $charset_out=='GB2312')) {
320 552 thorn
		// Nothing we can do here :-(
321
		// Charset is one of those obscure ISO-2022... or BIG5, GB2312 or something
322
		// and we can't use mb_convert_encoding() or iconv();
323
		// Emit an error-message.
324
		trigger_error("Can't convert into $charset_out without mb_convert_encoding() or iconv(). Use UTF-8 instead.", E_USER_WARNING);
325
		return($str);
326
	}
327
328 761 thorn
	// the string comes from charset_to_utf8(), so we can skip this
329 552 thorn
	// replace HTML-entities first
330 761 thorn
	//if(preg_match('/&[#0-9a-zA-Z]+;/',$str))
331
	//	$str = utf8_entities_to_umlauts($str);
332 552 thorn
333
	// check if we need to convert
334
	if($charset_out == 'UTF-8' || utf8_isASCII($str)) {
335
		// Nothing to do. Just return
336
			return($str);
337
	}
338
339
	// Convert $str to $charset_out
340
	if(substr($charset_out,0,8) == 'ISO-8859') {
341
		switch($charset_out) {
342
			case 'ISO-8859-1': $str=utf8_decode($str); break;
343
			case 'ISO-8859-2': $str=strtr($str, $utf8_to_iso_8859_2); break;
344
			case 'ISO-8859-3': $str=strtr($str, $utf8_to_iso_8859_3); break;
345
			case 'ISO-8859-4': $str=strtr($str, $utf8_to_iso_8859_4); break;
346
			case 'ISO-8859-5': $str=strtr($str, $utf8_to_iso_8859_5); break;
347
			case 'ISO-8859-6': $str=strtr($str, $utf8_to_iso_8859_6); break;
348
			case 'ISO-8859-7': $str=strtr($str, $utf8_to_iso_8859_7); break;
349
			case 'ISO-8859-8': $str=strtr($str, $utf8_to_iso_8859_8); break;
350
			case 'ISO-8859-9': $str=strtr($str, $utf8_to_iso_8859_9); break;
351
			case 'ISO-8859-10': $str=strtr($str, $utf8_to_iso_8859_10); break;
352
			case 'ISO-8859-11': $str=strtr($str, $utf8_to_iso_8859_11); break;
353
			default: $wrong_ISO8859 = true;
354
		}
355
		if(!$wrong_ISO8859)
356
			$converted = true;
357
	}
358
	if(!$converted && UTF8_MBSTRING && $charset_out != 'GB2312') {
359
		// $charset is neither UTF-8 nor a known ISO-8859...
360
		// Try mb_convert_encoding() - but there's no GB2312 encoding in php's mb_* functions
361
		$str = mb_convert_encoding($str, $charset_out, 'UTF-8');
362
		$converted = true;
363
	} elseif(!$converted) { // Try iconv
364
		if(function_exists('iconv')) {
365
			$str = iconv('UTF-8', $charset_out, $str);
366
			$converted = true;
367
		}
368
	}
369
	if($converted) {
370
		return($str);
371
	}
372
373
	// Nothing we can do here :-(
374
	// Charset is one of those obscure ISO-2022... or BIG5, GB2312 or something
375
	// and we can't use mb_convert_encoding() or iconv();
376
	// Emit an error-message.
377
	trigger_error("Can't convert into $charset_out without mb_convert_encoding() or iconv(). Use UTF-8 instead.", E_USER_WARNING);
378
379
	return $str;
380
}
381
382
/*
383
 * convert Filenames to ASCII
384
 *
385
 * Convert all non-ASCII characters and all HTML-entities to their plain 7bit equivalents
386
 * Characters without an equivalent will be converted to hex-values.
387
 * The name entities_to_7bit() is somewhat misleading, but kept for compatibility-reasons.
388
 *
389
 * @param  string  Filename to convert (all encodings from charset_to_utf8() are allowed)
390
 * @return string  ASCII encoded string, to use as filename in wb's page_filename() and media_filename
391 761 thorn
 * @author thorn
392 552 thorn
 */
393
function entities_to_7bit($str) {
394
	// convert to UTF-8
395
	$str = charset_to_utf8($str);
396 731 thorn
	if(!utf8_check($str))
397
		return($str);
398 552 thorn
	// replace some specials
399
	$str = utf8_stripspecials($str, '_');
400
	// translate non-ASCII characters to ASCII
401
	$str = utf8_romanize($str);
402
	// missed some? - Many UTF-8-chars can't be romanized
403
	// convert to HTML-entities, and replace entites by hex-numbers
404 761 thorn
	$str = utf8_fast_umlauts_to_entities($str, false);
405 881 thorn
	$str = str_replace('&#039;', '&apos;', $str);
406 552 thorn
	$str = preg_replace('/&#([0-9]+);/e', "dechex('$1')",  $str);
407
	// maybe there are some &gt; &lt; &apos; &quot; &amp; &nbsp; left, replace them too
408 881 thorn
	$str = str_replace(array('&gt;', '&lt;', '&apos;', '\'', '&quot;', '&amp;'), '', $str);
409
	$str = str_replace('&amp;', '', $str);
410 552 thorn
411
	return($str);
412
}
413
414
/*
415
 * Convert a string from mixed html-entities/umlauts to pure $charset_out-umlauts
416
 *
417
 * Will replace all numeric and named entities except
418 881 thorn
 * &gt; &lt; &apos; &quot; &#039; &nbsp;
419 761 thorn
 * @author thorn
420 552 thorn
 */
421
function entities_to_umlauts2($string, $charset_out=DEFAULT_CHARSET) {
422 761 thorn
	$string = charset_to_utf8($string, DEFAULT_CHARSET, true);
423
	//if(utf8_check($string)) // this check is to much time-consuming (this may fail only if AddDefaultCharset is set)
424 552 thorn
		$string = utf8_to_charset($string, $charset_out);
425
	return ($string);
426
}
427
428
/*
429
 * Convert a string from mixed html-entities/umlauts to pure ASCII with HTML-entities
430
 *
431
 * Will convert a string in $charset_in encoding to a pure ASCII string with HTML-entities.
432 761 thorn
 * @author thorn
433 552 thorn
 */
434
function umlauts_to_entities2($string, $charset_in=DEFAULT_CHARSET) {
435 761 thorn
	$string = charset_to_utf8($string, $charset_in, false);
436
	//if(utf8_check($string)) // this check is to much time-consuming (this may fail only if AddDefaultCharset is set)
437
		$string = utf8_fast_umlauts_to_entities($string, false);
438 552 thorn
	return($string);
439
}