Project

General

Profile

1
<?php
2

    
3
// $Id: functions.php 490 2007-06-23 08:13:53Z Ruebenwurzel $
4

    
5
/*
6

    
7
 Website Baker Project <http://www.websitebaker.org/>
8
 Copyright (C) 2004-2007, Ryan Djurovich
9

    
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

    
28
Website Baker functions file
29
This file contains general functions used in Website Baker
30

    
31
*/
32

    
33
// Stop this file from being accessed directly
34
if(!defined('WB_URL')) {
35
	header('Location: ../index.php');
36
	exit(0);
37
}
38

    
39
// Define that this file has been loaded
40
define('FUNCTIONS_FILE_LOADED', true);
41

    
42
// Function to remove a non-empty directory
43
function rm_full_dir($directory)
44
{
45
    // If suplied dirname is a file then unlink it
46
    if (is_file($directory)) {
47
        return unlink($directory);
48
    }
49

    
50
    // Empty the folder
51
    $dir = dir($directory);
52
    while (false !== $entry = $dir->read()) {
53
        // Skip pointers
54
        if ($entry == '.' || $entry == '..') {
55
            continue;
56
        }
57

    
58
        // Deep delete directories      
59
        if (is_dir("$directory/$entry")) {
60
            rm_full_dir("$directory/$entry");
61
        } else {
62
            unlink("$directory/$entry");
63
        }
64
    }
65

    
66
    // Now delete the folder
67
    $dir->close();
68
    return rmdir($directory);
69
}
70

    
71
// Function to open a directory and add to a dir list
72
function directory_list($directory) {
73
	
74
	$list = array();
75

    
76
	// Open the directory then loop through its contents
77
	$dir = dir($directory);
78
	while (false !== $entry = $dir->read()) {
79
		// Skip pointers
80
		if(substr($entry, 0, 1) == '.' || $entry == '.svn') {
81
			continue;
82
		}
83
		// Add dir and contents to list
84
		if (is_dir("$directory/$entry")) {
85
			$list = array_merge($list, directory_list("$directory/$entry"));
86
			$list[] = "$directory/$entry";
87
		}
88
	}
89

    
90
	// Now return the list
91
	return $list;
92
}
93

    
94
// Function to open a directory and add to a dir list
95
function chmod_directory_contents($directory, $file_mode) {
96
	
97
	// Set the umask to 0
98
	$umask = umask(0);
99
	
100
	// Open the directory then loop through its contents
101
	$dir = dir($directory);
102
	while (false !== $entry = $dir->read()) {
103
		// Skip pointers
104
		if(substr($entry, 0, 1) == '.' || $entry == '.svn') {
105
			continue;
106
		}
107
		// Chmod the sub-dirs contents
108
		if(is_dir("$directory/$entry")) {
109
			chmod_directory_contents("$directory/$entry", $file_mode);
110
		}
111
		change_mode($directory.'/'.$entry, 'file');
112
	}
113
	
114
	// Restore the umask
115
	umask($umask);
116

    
117
}
118

    
119
// Function to open a directory and add to a file list
120
function file_list($directory, $skip = array()) {
121
	
122
	$list = array();
123
	$skip_file = false;
124
	
125
	// Open the directory then loop through its contents
126
	$dir = dir($directory);
127
	while (false !== $entry = $dir->read()) {
128
		// Skip pointers
129
		if($entry == '.' || $entry == '..') {
130
			$skip_file = true;
131
		}
132
		// Check if we to skip anything else
133
		if($skip != array()) {
134
			foreach($skip AS $skip_name) {
135
				if($entry == $skip_name) {
136
					$skip_file = true;
137
				}
138
			}
139
		}
140
		// Add dir and contents to list
141
		if($skip_file != true AND is_file("$directory/$entry")) {
142
			$list[] = "$directory/$entry";
143
		}
144
		
145
		// Reset the skip file var
146
		$skip_file = false;
147
	}
148

    
149
	// Now delete the folder
150
	return $list;
151
}
152

    
153
// Function to get a list of home folders not to show
154
function get_home_folders() {
155
	global $database, $admin;
156
	$home_folders = array();
157
	// Only return home folders is this feature is enabled
158
	// and user is not admin
159
	if(HOME_FOLDERS AND ($_SESSION['GROUP_ID']!='1')) {
160
		$query_home_folders = $database->query("SELECT home_folder FROM ".TABLE_PREFIX."users WHERE home_folder != '".$admin->get_home_folder()."'");
161
		if($query_home_folders->numRows() > 0) {
162
			while($folder = $query_home_folders->fetchRow()) {
163
				$home_folders[$folder['home_folder']] = $folder['home_folder'];
164
			}
165
		}
166
		function remove_home_subs($directory = '/', $home_folders) {
167
			if($handle = opendir(WB_PATH.MEDIA_DIRECTORY.$directory)) {
168
				// Loop through the dirs to check the home folders sub-dirs are not shown
169
			   while(false !== ($file = readdir($handle))) {
170
					if(substr($file, 0, 1) != '.' AND $file != '.svn' AND $file != 'index.php') {
171
						if(is_dir(WB_PATH.MEDIA_DIRECTORY.$directory.'/'.$file)) {
172
							if($directory != '/') { $file = $directory.'/'.$file; } else { $file = '/'.$file; }
173
							foreach($home_folders AS $hf) {
174
								$hf_length = strlen($hf);
175
								if($hf_length > 0) {
176
									if(substr($file, 0, $hf_length+1) == $hf) {
177
										$home_folders[$file] = $file;
178
									}
179
								}
180
							}
181
							$home_folders = remove_home_subs($file, $home_folders);
182
						}
183
					}
184
				}
185
			}
186
			return $home_folders;
187
		}
188
		$home_folders = remove_home_subs('/', $home_folders);
189
	}
190
	return $home_folders;
191
}
192

    
193
// Function to create directories
194
function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE) {
195
	if(!file_exists($dir_name)) {
196
		$umask = umask(0);
197
		mkdir($dir_name, $dir_mode);
198
		umask($umask);
199
		return true;
200
	} else {
201
		return false;	
202
	}
203
}
204

    
205
// Function to chmod files and directories
206
function change_mode($name) {
207
	if(OPERATING_SYSTEM != 'windows') {
208
		// Only chmod if os is not windows
209
		if(is_dir($name)) {
210
			$mode = OCTAL_DIR_MODE;
211
		} else {
212
			$mode = OCTAL_FILE_MODE;
213
		}
214
		if(file_exists($name)) {
215
			$umask = umask(0);
216
			chmod($name, $mode);
217
			umask($umask);
218
			return true;
219
		} else {
220
			return false;	
221
		}
222
	} else {
223
		return true;
224
	}
225
}
226

    
227
// Function to figure out if a parent exists
228
function is_parent($page_id) {
229
	global $database;
230
	// Get parent
231
	$query = $database->query("SELECT parent FROM ".TABLE_PREFIX."pages WHERE page_id = '$page_id'");
232
	$fetch = $query->fetchRow();
233
	// If parent isnt 0 return its ID
234
	if($fetch['parent'] == '0') {
235
		return false;
236
	} else {
237
		return $fetch['parent'];
238
	}
239
}
240

    
241
// Function to work out level
242
function level_count($page_id) {
243
	global $database;
244
	// Get page parent
245
	$query_page = $database->query("SELECT parent FROM ".TABLE_PREFIX."pages WHERE page_id = '$page_id' LIMIT 1");
246
	$fetch_page = $query_page->fetchRow();
247
	$parent = $fetch_page['parent'];
248
	if($parent > 0) {
249
		// Get the level of the parent
250
		$query_parent = $database->query("SELECT level FROM ".TABLE_PREFIX."pages WHERE page_id = '$parent' LIMIT 1");
251
		$fetch_parent = $query_parent->fetchRow();
252
		$level = $fetch_parent['level'];
253
		return $level+1;
254
	} else {
255
		return 0;
256
	}
257
}
258

    
259
// Function to work out root parent
260
function root_parent($page_id) {
261
	global $database;
262
	// Get page details
263
	$query_page = $database->query("SELECT parent,level FROM ".TABLE_PREFIX."pages WHERE page_id = '$page_id' LIMIT 1");
264
	$fetch_page = $query_page->fetchRow();
265
	$parent = $fetch_page['parent'];
266
	$level = $fetch_page['level'];	
267
	if($level == 1) {
268
		return $parent;
269
	} elseif($parent == 0) {
270
		return $page_id;
271
	} else {
272
		// Figure out what the root parents id is
273
		$parent_ids = array_reverse(get_parent_ids($page_id));
274
		return $parent_ids[0];
275
	}
276
}
277

    
278
// Function to get page title
279
function get_page_title($id) {
280
	global $database;
281
	// Get title
282
	$query = $database->query("SELECT page_title FROM ".TABLE_PREFIX."pages WHERE page_id = '$id'");
283
	$fetch = $query->fetchRow();
284
	// Return title
285
	return $fetch['page_title'];
286
}
287

    
288
// Function to get a pages menu title
289
function get_menu_title($id) {
290
	// Connect to the database
291
	$database = new database();
292
	// Get title
293
	$query = $database->query("SELECT menu_title FROM ".TABLE_PREFIX."pages WHERE page_id = '$id'");
294
	$fetch = $query->fetchRow();
295
	// Return title
296
	return $fetch['menu_title'];
297
}
298

    
299
// Function to get all parent page titles
300
function get_parent_titles($parent_id) {
301
	$titles[] = get_menu_title($parent_id);
302
	if(is_parent($parent_id) != false) {
303
		$parent_titles = get_parent_titles(is_parent($parent_id));
304
		$titles = array_merge($titles, $parent_titles);
305
	}
306
	return $titles;
307
}
308

    
309
// Function to get all parent page id's
310
function get_parent_ids($parent_id) {
311
	$ids[] = $parent_id;
312
	if(is_parent($parent_id) != false) {
313
		$parent_ids = get_parent_ids(is_parent($parent_id));
314
		$ids = array_merge($ids, $parent_ids);
315
	}
316
	return $ids;
317
}
318

    
319
// Function to genereate page trail
320
function get_page_trail($page_id) {
321
	return implode(',', array_reverse(get_parent_ids($page_id)));
322
}
323

    
324
// Function to get all sub pages id's
325
function get_subs($parent, $subs) {
326
	// Connect to the database
327
	$database = new database();
328
	// Get id's
329
	$query = $database->query("SELECT page_id FROM ".TABLE_PREFIX."pages WHERE parent = '$parent'");
330
	if($query->numRows() > 0) {
331
		while($fetch = $query->fetchRow()) {
332
			$subs[] = $fetch['page_id'];
333
			// Get subs of this sub
334
			$subs = get_subs($fetch['page_id'], $subs);
335
		}
336
	}
337
	// Return subs array
338
	return $subs;
339
}
340

    
341
// Function as replecement for php's htmlspecialchars()
342
function my_htmlspecialchars($string) {
343
	$string = preg_replace("/&(?=[#a-z0-9]+;)/i", "_x_", $string);
344
	$string = strtr($string, array("<"=>"&lt;", ">"=>"&gt;", "&"=>"&amp;", "\""=>"&quot;", "\'"=>"&#39;"));
345
	$string = preg_replace("/_x_(?=[#a-z0-9]+;)/i", "&", $string);
346
	return($string);
347
}
348

    
349
// Function to convert a string from $from- to $to-encoding, using mysql
350
function my_mysql_iconv($string, $from, $to) {
351
	// keep current character set values
352
	global $database;
353
	$query = $database->query("SELECT @@character_set_client");
354
	if($query->numRows() > 0) {
355
		$res = $query->fetchRow();
356
		$character_set_database = $res['@@character_set_client'];
357
	}	else { echo mysql_error()."\n<br />"; }
358
	$query = $database->query("SELECT @@character_set_results");
359
	if($query->numRows() > 0) {
360
		$res = $query->fetchRow();
361
		$character_set_results = $res['@@character_set_results'];
362
	}	else { echo mysql_error()."\n<br />"; }
363
	$query = $database->query("SELECT @@collation_connection");
364
	if($query->numRows() > 0) {
365
		$res = $query->fetchRow();
366
		$collation_results = $res['@@collation_connection'];
367
	}	else { echo mysql_error()."\n<br />"; }
368
	// set new character set values
369
	$query = $database->query("SET character_set_client=$from");
370
	$query = $database->query("SET character_set_results=$to");
371
	$query = $database->query("SET collation_connection=utf8_unicode_ci");
372
	$string_escaped = mysql_real_escape_string($string);
373
	// convert the string
374
	$query = $database->query("SELECT '$string_escaped'");
375
	if($query->numRows() > 0) {
376
		$res = $query->fetchRow();
377
		$converted_string = $res[0];
378
	}	else { echo mysql_error()."\n<br />"; }
379
	// restore previous character set values
380
	$query = $database->query("SET character_set_client=$character_set_database");
381
	$query = $database->query("SET character_set_results=$character_set_results");
382
	$query = $database->query("SET collation_connection=$collation_results");
383
	return $converted_string;
384
}
385

    
386
// Function as wrapper for mb_convert_encoding
387
// converts $charset_in to $charset_out or 
388
// UTF-8 to HTML-ENTITIES or HTML-ENTITIES to UTF-8
389
function mb_convert_encoding_wrapper($string, $charset_out, $charset_in) {
390
	if ($charset_out == $charset_in) {
391
		return $string;
392
	}
393
	$use_iconv = true;
394
	$use_mbstring = true;
395
	/*
396
	if(version_compare(PHP_VERSION, "5.1.0", "<")) {
397
		$use_mbstring = false; // don't rely on mb_convert_encoding if php<5.1.0
398
		$use_iconv = false; // don't rely on iconv neither
399
	}
400
	*/
401
	
402
	// try mb_convert_encoding(). This can handle to or from HTML-ENTITIES, too
403
	if ($use_mbstring && function_exists('mb_convert_encoding')) {
404
		// there's no GB2312 or ISO-8859-11 encoding in php's mb_* functions
405
		if ($charset_in=='ISO-8859-11' || $charset_in=='GB2312') {
406
			if ($use_iconv && function_exists('iconv')) {
407
				$string = iconv($charset_in, 'UTF-8', $string);
408
			}
409
			else {
410
				if ($charset_in == 'GB2312') {
411
					$string=my_mysql_iconv($string, 'gb2312', 'utf8');
412
				} else {
413
					$string=my_mysql_iconv($string, 'tis620', 'utf8');
414
				}
415
			}
416
			$charset_in='UTF-8';
417
			if ($charset_out == 'UTF-8') {
418
				return $string;
419
			}
420
		}
421
		if ($charset_out=='ISO-8859-11' || $charset_out=='GB2312') {
422
			$string=mb_convert_encoding($string, 'UTF-8', $charset_in);
423
			if ($use_iconv && function_exists('iconv')) {
424
				$string = iconv('UTF-8', $charset_out, $string);
425
			}
426
			else {
427
				if ($charset_out == 'GB2312') {
428
					$string=my_mysql_iconv($string, 'utf8', 'gb2312');
429
				} else {
430
					$string=my_mysql_iconv($string, 'utf8', 'tis620');
431
				}
432
			}
433
		} else {
434
			$string = strtr($string, array("&lt;"=>"&_lt;", "&gt;"=>"&_gt;", "&amp;"=>"&_amp;", "&quot;"=>"&_quot;", "&#39;"=>"&_#39;"));
435
			$string=mb_convert_encoding($string, $charset_out, $charset_in);
436
			$string = strtr($string, array("&_lt;"=>"&lt;", "&_gt;"=>"&gt;", "&_amp;"=>"&amp;", "&_quot;"=>"&quot;", "&_#39;"=>"&#39;"));
437
		}
438
		return $string;
439
	}
440

    
441
	// try iconv(). This can't handle to or from HTML-ENTITIES.
442
	if ($use_iconv && function_exists('iconv') && $charset_out!='HTML-ENTITIES' && $charset_in!='HTML-ENTITIES' ) {
443
		$string = iconv($charset_in, $charset_out, $string);
444
		return $string;
445
	}
446

    
447
	// do the UTF-8->HTML-ENTITIES or HTML-ENTITIES->UTF-8 translation if mb_convert_encoding isn't available
448
	if (($charset_in=='HTML-ENTITIES' && $charset_out=='UTF-8') || ($charset_in=='UTF-8' && $charset_out=='HTML-ENTITIES')) {
449
		$string = string_decode_encode_entities($string, $charset_out, $charset_in);
450
		return $string;
451
	}
452

    
453
	// mb_convert_encoding() and iconv() aren't available, so use my_mysql_iconv()
454
	if ($charset_in == 'ISO-8859-1') { $mysqlcharset_from = 'latin1'; }
455
	elseif ($charset_in == 'ISO-8859-2') { $mysqlcharset_from = 'latin2'; }
456
	elseif ($charset_in == 'ISO-8859-3') { $mysqlcharset_from = 'latin1'; }
457
	elseif ($charset_in == 'ISO-8859-4') { $mysqlcharset_from = 'latin7'; }
458
	elseif ($charset_in == 'ISO-8859-5') { $string = convert_cyr_string ($string, "iso8859-5", "windows-1251" ); $mysqlcharset_from = 'cp1251'; }
459
	elseif ($charset_in == 'ISO-8859-6') { $mysqlcharset_from = ''; } //?
460
	elseif ($charset_in == 'ISO-8859-7') { $mysqlcharset_from = 'greek'; }
461
	elseif ($charset_in == 'ISO-8859-8') { $mysqlcharset_from = 'hebrew'; }
462
	elseif ($charset_in == 'ISO-8859-9') { $mysqlcharset_from = 'latin5'; }
463
	elseif ($charset_in == 'ISO-8859-10') { $mysqlcharset_from = 'latin1'; }
464
	elseif ($charset_in == 'BIG5') { $mysqlcharset_from = 'big5'; }
465
	elseif ($charset_in == 'ISO-2022-JP') { $mysqlcharset_from = ''; } //?
466
	elseif ($charset_in == 'ISO-2022-KR') { $mysqlcharset_from = ''; } //?
467
	elseif ($charset_in == 'GB2312') { $mysqlcharset_from = 'gb2312'; }
468
	elseif ($charset_in == 'ISO-8859-11') { $mysqlcharset_from = 'tis620'; }
469
	elseif ($charset_in == 'UTF-8') { $mysqlcharset_from = 'utf8'; }
470
	else { $mysqlcharset_from = 'latin1'; }
471

    
472
	if ($charset_out == 'ISO-8859-1') { $mysqlcharset_to = 'latin1'; }
473
	elseif ($charset_out == 'ISO-8859-2') { $mysqlcharset_to = 'latin2'; }
474
	elseif ($charset_out == 'ISO-8859-3') { $mysqlcharset_to = 'latin1'; }
475
	elseif ($charset_out == 'ISO-8859-4') { $mysqlcharset_to = 'latin7'; }
476
	elseif ($charset_out == 'ISO-8859-5') { $mysqlcharset_to = 'cp1251'; } // use convert_cyr_string afterwards
477
	elseif ($charset_out == 'ISO-8859-6') { $mysqlcharset_to = ''; } //?
478
	elseif ($charset_out == 'ISO-8859-7') { $mysqlcharset_to = 'greek'; }
479
	elseif ($charset_out == 'ISO-8859-8') { $mysqlcharset_to = 'hebrew'; }
480
	elseif ($charset_out == 'ISO-8859-9') { $mysqlcharset_to = 'latin5'; }
481
	elseif ($charset_out == 'ISO-8859-10') { $mysqlcharset_to = 'latin1'; }
482
	elseif ($charset_out == 'BIG5') { $mysqlcharset_to = 'big5'; }
483
	elseif ($charset_out == 'ISO-2022-JP') { $mysqlcharset_to = ''; } //?
484
	elseif ($charset_out == 'ISO-2022-KR') { $mysqlcharset_to = ''; } //?
485
	elseif ($charset_out == 'GB2312') { $mysqlcharset_to = 'gb2312'; }
486
	elseif ($charset_out == 'ISO-8859-11') { $mysqlcharset_to = 'tis620'; }
487
	elseif ($charset_out == 'UTF-8') { $mysqlcharset_to = 'utf8'; }
488
	else { $mysqlcharset_to = 'latin1'; }
489

    
490
	if ($mysqlcharset_from!="" && $mysqlcharset_to!="" && $mysqlcharset_from!=$mysqlcharset_to) {
491
		$string=my_mysql_iconv($string, $mysqlcharset_from, $mysqlcharset_to);
492
		if ($mysqlcharset_to == 'cp1251') { 
493
			$string = convert_cyr_string ($string, "windows-1251", "iso-8859-5" );
494
		}
495
		return($string);
496
	}
497

    
498
	// $string is unchanged. This will happen if we have to deal with ISO-8859-6 or ISO-2022-JP or -KR
499
	// and mbstring _and_ iconv aren't available.
500
	return $string;
501
}
502

    
503
// Decodes or encodes html-entities. Works for utf-8 only!
504
function string_decode_encode_entities($string, $out='HTML-ENTITIES', $in='UTF-8') {
505
	if(!(($in=='UTF-8' || $in=='HTML-ENTITIES') && ($out=='UTF-8' || $out=='HTML-ENTITIES'))) {
506
		return $string;
507
	}
508
	$named_to_numbered_entities=array(
509
		'&Aacute;'=>'&#193;','&aacute;'=>'&#225;',
510
		'&Acirc;'=>'&#194;','&acirc;'=>'&#226;','&acute;'=>'&#180;','&AElig;'=>'&#198;','&aelig;'=>'&#230;',
511
		'&Agrave;'=>'&#192;','&agrave;'=>'&#224;','&alefsym;'=>'&#8501;','&Alpha;'=>'&#913;','&alpha;'=>'&#945;',
512
		'&and;'=>'&#8743;','&ang;'=>'&#8736;','&apos;'=>'&#39;','&Aring;'=>'&#197;','&aring;'=>'&#229;',
513
		'&asymp;'=>'&#8776;','&Atilde;'=>'&#195;','&atilde;'=>'&#227;','&Auml;'=>'&#196;','&auml;'=>'&#228;',
514
		'&bdquo;'=>'&#8222;','&Beta;'=>'&#914;','&beta;'=>'&#946;','&brvbar;'=>'&#166;','&bull;'=>'&#8226;',
515
		'&cap;'=>'&#8745;','&Ccedil;'=>'&#199;','&ccedil;'=>'&#231;','&cedil;'=>'&#184;','&cent;'=>'&#162;',
516
		'&Chi;'=>'&#935;','&chi;'=>'&#967;','&circ;'=>'&#710;','&clubs;'=>'&#9827;','&cong;'=>'&#8773;',
517
		'&copy;'=>'&#169;','&crarr;'=>'&#8629;','&cup;'=>'&#8746;','&curren;'=>'&#164;','&Dagger;'=>'&#8225;',
518
		'&dagger;'=>'&#8224;','&dArr;'=>'&#8659;','&darr;'=>'&#8595;','&deg;'=>'&#176;','&Delta;'=>'&#916;',
519
		'&delta;'=>'&#948;','&diams;'=>'&v#9830;','&divide;'=>'&#247;','&Eacute;'=>'&#201;','&eacute;'=>'&#233;',
520
		'&Ecirc;'=>'&#202;','&ecirc;'=>'&#234;','&Egrave;'=>'&#200;','&egrave;'=>'&#232;','&empty;'=>'&#8709;',
521
		'&emsp;'=>'&#8195;','&ensp;'=>'&#8194;','&Epsilon;'=>'&#917;','&epsilon;'=>'&#949;','&equiv;'=>'&#8801;',
522
		'&Eta;'=>'&#919;','&eta;'=>'&#951;','&ETH;'=>'&#208;','&eth;'=>'&#240;','&Euml;'=>'&#203;','&euml;'=>'&#235;',
523
		'&euro;'=>'&#8364;','&exist;'=>'&#8707;','&fnof;'=>'&#402;','&forall;'=>'&#8704;','&frac12;'=>'&#189;',
524
		'&frac14;'=>'&#188;','&frac34;'=>'&#190;','&frasl;'=>'&#8260;','&Gamma;'=>'&#915;','&gamma;'=>'&#947;',
525
		'&ge;'=>'&#8805;','&hArr;'=>'&#8660;','&harr;'=>'&#8596;','&hearts;'=>'&#9829;',
526
		'&hellip;'=>'&#8230;','&Iacute;'=>'&#205;','&iacute;'=>'&#237;','&Icirc;'=>'&#206;','&icirc;'=>'&#238;',
527
		'&iexcl;'=>'&#161;','&Igrave;'=>'&#204;','&igrave;'=>'&#236;','&image;'=>'&#8465;','&infin;'=>'&#8734;',
528
		'&int;'=>'&#8747;','&Iota;'=>'&#921;','&iota;'=>'&#953;','&iquest;'=>'&#191;','&isin;'=>'&#8712;',
529
		'&Iuml;'=>'&#207;','&iuml;'=>'&#239;','&Kappa;'=>'&#922;','&kappa;'=>'&#954;','&Lambda;'=>'&#923;',
530
		'&lambda;'=>'&#955;','&lang;'=>'&#9001;','&laquo;'=>'&#171;','&lArr;'=>'&#8656;','&larr;'=>'&#8592;',
531
		'&lceil;'=>'&#8968;','&ldquo;'=>'&#8220;','&le;'=>'&#8804;','&lfloor;'=>'&#8970;','&lowast;'=>'&#8727;',
532
		'&loz;'=>'&#9674;','&lrm;'=>'&#8206;','&lsaquo;'=>'&#8249;','&lsquo;'=>'&#8216;',
533
		'&macr;'=>'&#175;','&mdash;'=>'&#8212;','&micro;'=>'&#181;','&middot;'=>'&#183;','&minus;'=>'&#8722;',
534
		'&Mu;'=>'&#924;','&mu;'=>'&#956;','&nabla;'=>'&#8711;','&nbsp;'=>'&#160;','&ndash;'=>'&#8211;',
535
		'&ne;'=>'&#8800;','&ni;'=>'&#8715;','&not;'=>'&#172;','&notin;'=>'&#8713;','&nsub;'=>'&#8836;',
536
		'&Ntilde;'=>'&#209;','&ntilde;'=>'&#241;','&Nu;'=>'&#925;','&nu;'=>'&#957;','&Oacute;'=>'&#211;',
537
		'&oacute;'=>'&#243;','&Ocirc;'=>'&#212;','&ocirc;'=>'&#244;','&OElig;'=>'&#338;','&oelig;'=>'&#339;',
538
		'&Ograve;'=>'&#210;','&ograve;'=>'&#242;','&oline;'=>'&#8254;','&Omega;'=>'&#937;','&omega;'=>'&#969;',
539
		'&Omicron;'=>'&#927;','&omicron;'=>'&#959;','&oplus;'=>'&#8853;','&or;'=>'&#8744;','&ordf;'=>'&#170;',
540
		'&ordm;'=>'&#186;','&Oslash;'=>'&#216;','&oslash;'=>'&#248;','&Otilde;'=>'&#213;','&otilde;'=>'&#245;',
541
		'&otimes;'=>'&#8855;','&Ouml;'=>'&#214;','&ouml;'=>'&#246;','&para;'=>'&#182;','&part;'=>'&#8706;',
542
		'&permil;'=>'&#8240;','&perp;'=>'&#8869;','&Phi;'=>'&#934;','&phi;'=>'&#966;','&Pi;'=>'&#928;',
543
		'&pi;'=>'&#960;','&piv;'=>'&#982;','&plusmn;'=>'&#177;','&pound;'=>'&#163;','&Prime;'=>'&#8243;',
544
		'&prime;'=>'&#8242;','&prod;'=>'&#8719;','&prop;'=>'&#8733;','&Psi;'=>'&#936;','&psi;'=>'&#968;',
545
		'&quot;'=>'&#34;','&radic;'=>'&#8730;','&rang;'=>'&#9002;','&raquo;'=>'&#187;','&rArr;'=>'&#8658;',
546
		'&rarr;'=>'&#8594;','&rceil;'=>'&#8969;','&rdquo;'=>'&#8221;','&real;'=>'&#8476;','&reg;'=>'&#174;',
547
		'&rfloor;'=>'&#8971;','&Rho;'=>'&#929;','&rho;'=>'&#961;','&rlm;'=>'&#8207;','&rsaquo;'=>'&#8250;',
548
		'&rsquo;'=>'&#8217;','&sbquo;'=>'&#8218;','&Scaron;'=>'&#352;','&scaron;'=>'&#353;','&sdot;'=>'&#8901;',
549
		'&sect;'=>'&#167;','&shy;'=>'&#173;','&Sigma;'=>'&#931;','&sigma;'=>'&#963;','&sigmaf;'=>'&#962;',
550
		'&sim;'=>'&#8764;','&spades;'=>'&#9824;','&sub;'=>'&#8834;','&sube;'=>'&#8838;','&sum;'=>'&#8721;',
551
		'&sup;'=>'&#8835;','&sup1;'=>'&#185;','&sup2;'=>'&#178;','&sup3;'=>'&#179;','&supe;'=>'&#8839;',
552
		'&szlig;'=>'&#223;','&Tau;'=>'&#932;','&tau;'=>'&#964;','&there4;'=>'&#8756;','&Theta;'=>'&#920;',
553
		'&theta;'=>'&#952;','&thetasym;'=>'&#977;','&thinsp;'=>'&#8201;','&THORN;'=>'&#222;','&thorn;'=>'&#254;',
554
		'&tilde;'=>'&#732;','&times;'=>'&#215;','&trade;'=>'&#8482;','&Uacute;'=>'&#218;','&uacute;'=>'&#250;',
555
		'&uArr;'=>'&#8657;','&uarr;'=>'&#8593;','&Ucirc;'=>'&#219;','&ucirc;'=>'&#251;','&Ugrave;'=>'&#217;',
556
		'&ugrave;'=>'&#249;','&uml;'=>'&#168;','&upsih;'=>'&#978;','&Upsilon;'=>'&#933;','&upsilon;'=>'&#965;',
557
		'&Uuml;'=>'&#220;','&uuml;'=>'&#252;','&weierp;'=>'&#8472;','&Xi;'=>'&#926;','&xi;'=>'&#958;',
558
		'&Yacute;'=>'&#221;','&yacute;'=>'&#253;','&yen;'=>'&#165;','&Yuml;'=>'&#376;','&yuml;'=>'&#255;',
559
		'&Zeta;'=>'&#918;','&zeta;'=>'&#950;','&zwj;'=>'&#8205;','&zwnj;'=>'&#8204;'
560
	);
561
	$numbered_to_named_entities=array(
562
		'&#193;'=>'&Aacute;','&#225;'=>'&aacute;','&#194;'=>'&Acirc;','&#226;'=>'&acirc;','&#180;'=>'&acute;',
563
		'&#198;'=>'&AElig;','&#230;'=>'&aelig;','&#192;'=>'&Agrave;','&#224;'=>'&agrave;','&#8501;'=>'&alefsym;',
564
		'&#913;'=>'&Alpha;','&#945;'=>'&alpha;','&#8743;'=>'&and;','&#8736;'=>'&ang;',
565
		'&#39;'=>'&apos;','&#197;'=>'&Aring;','&#229;'=>'&aring;','&#8776;'=>'&asymp;','&#195;'=>'&Atilde;',
566
		'&#227;'=>'&atilde;','&#196;'=>'&Auml;','&#228;'=>'&auml;','&#8222;'=>'&bdquo;','&#914;'=>'&Beta;',
567
		'&#946;'=>'&beta;','&#166;'=>'&brvbar;','&#8226;'=>'&bull;','&#8745;'=>'&cap;','&#199;'=>'&Ccedil;',
568
		'&#231;'=>'&ccedil;','&#184;'=>'&cedil;','&#162;'=>'&cent;','&#935;'=>'&Chi;','&#967;'=>'&chi;',
569
		'&#710;'=>'&circ;','&#9827;'=>'&clubs;','&#8773;'=>'&cong;','&#169;'=>'&copy;','&#8629;'=>'&crarr;',
570
		'&#8746;'=>'&cup;','&#164;'=>'&curren;','&#8225;'=>'&Dagger;','&#8224;'=>'&dagger;','&#8659;'=>'&dArr;',
571
		'&#8595;'=>'&darr;','&#176;'=>'&deg;','&#916;'=>'&Delta;','&#948;'=>'&delta;','&v#9830;'=>'&diams;',
572
		'&#247;'=>'&divide;','&#201;'=>'&Eacute;','&#233;'=>'&eacute;','&#202;'=>'&Ecirc;','&#234;'=>'&ecirc;',
573
		'&#200;'=>'&Egrave;','&#232;'=>'&egrave;','&#8709;'=>'&empty;','&#8195;'=>'&emsp;','&#8194;'=>'&ensp;',
574
		'&#917;'=>'&Epsilon;','&#949;'=>'&epsilon;','&#8801;'=>'&equiv;','&#919;'=>'&Eta;','&#951;'=>'&eta;',
575
		'&#208;'=>'&ETH;','&#240;'=>'&eth;','&#203;'=>'&Euml;','&#235;'=>'&euml;','&#8364;'=>'&euro;',
576
		'&#8707;'=>'&exist;','&#402;'=>'&fnof;','&#8704;'=>'&forall;','&#189;'=>'&frac12;','&#188;'=>'&frac14;',
577
		'&#190;'=>'&frac34;','&#8260;'=>'&frasl;','&#915;'=>'&Gamma;','&#947;'=>'&gamma;','&#8805;'=>'&ge;',
578
		'&#8660;'=>'&hArr;','&#8596;'=>'&harr;','&#9829;'=>'&hearts;','&#8230;'=>'&hellip;',
579
		'&#205;'=>'&Iacute;','&#237;'=>'&iacute;','&#206;'=>'&Icirc;','&#238;'=>'&icirc;','&#161;'=>'&iexcl;',
580
		'&#204;'=>'&Igrave;','&#236;'=>'&igrave;','&#8465;'=>'&image;','&#8734;'=>'&infin;','&#8747;'=>'&int;',
581
		'&#921;'=>'&Iota;','&#953;'=>'&iota;','&#191;'=>'&iquest;','&#8712;'=>'&isin;','&#207;'=>'&Iuml;',
582
		'&#239;'=>'&iuml;','&#922;'=>'&Kappa;','&#954;'=>'&kappa;','&#923;'=>'&Lambda;','&#955;'=>'&lambda;',
583
		'&#9001;'=>'&lang;','&#171;'=>'&laquo;','&#8656;'=>'&lArr;','&#8592;'=>'&larr;','&#8968;'=>'&lceil;',
584
		'&#8220;'=>'&ldquo;','&#8804;'=>'&le;','&#8970;'=>'&lfloor;','&#8727;'=>'&lowast;','&#9674;'=>'&loz;',
585
		'&#8206;'=>'&lrm;','&#8249;'=>'&lsaquo;','&#8216;'=>'&lsquo;','&#175;'=>'&macr;',
586
		'&#8212;'=>'&mdash;','&#181;'=>'&micro;','&#183;'=>'&middot;','&#8722;'=>'&minus;','&#924;'=>'&Mu;',
587
		'&#956;'=>'&mu;','&#8711;'=>'&nabla;','&#160;'=>'&nbsp;','&#8211;'=>'&ndash;','&#8800;'=>'&ne;',
588
		'&#8715;'=>'&ni;','&#172;'=>'&not;','&#8713;'=>'&notin;','&#8836;'=>'&nsub;','&#209;'=>'&Ntilde;',
589
		'&#241;'=>'&ntilde;','&#925;'=>'&Nu;','&#957;'=>'&nu;','&#211;'=>'&Oacute;','&#243;'=>'&oacute;',
590
		'&#212;'=>'&Ocirc;','&#244;'=>'&ocirc;','&#338;'=>'&OElig;','&#339;'=>'&oelig;','&#210;'=>'&Ograve;',
591
		'&#242;'=>'&ograve;','&#8254;'=>'&oline;','&#937;'=>'&Omega;','&#969;'=>'&omega;','&#927;'=>'&Omicron;',
592
		'&#959;'=>'&omicron;','&#8853;'=>'&oplus;','&#8744;'=>'&or;','&#170;'=>'&ordf;','&#186;'=>'&ordm;',
593
		'&#216;'=>'&Oslash;','&#248;'=>'&oslash;','&#213;'=>'&Otilde;','&#245;'=>'&otilde;','&#8855;'=>'&otimes;',
594
		'&#214;'=>'&Ouml;','&#246;'=>'&ouml;','&#182;'=>'&para;','&#8706;'=>'&part;','&#8240;'=>'&permil;',
595
		'&#8869;'=>'&perp;','&#934;'=>'&Phi;','&#966;'=>'&phi;','&#928;'=>'&Pi;','&#960;'=>'&pi;','&#982;'=>'&piv;',
596
		'&#177;'=>'&plusmn;','&#163;'=>'&pound;','&#8243;'=>'&Prime;','&#8242;'=>'&prime;','&#8719;'=>'&prod;',
597
		'&#8733;'=>'&prop;','&#936;'=>'&Psi;','&#968;'=>'&psi;','&#34;'=>'&quot;','&#8730;'=>'&radic;',
598
		'&#9002;'=>'&rang;','&#187;'=>'&raquo;','&#8658;'=>'&rArr;','&#8594;'=>'&rarr;','&#8969;'=>'&rceil;',
599
		'&#8221;'=>'&rdquo;','&#8476;'=>'&real;','&#174;'=>'&reg;','&#8971;'=>'&rfloor;','&#929;'=>'&Rho;',
600
		'&#961;'=>'&rho;','&#8207;'=>'&rlm;','&#8250;'=>'&rsaquo;','&#8217;'=>'&rsquo;','&#8218;'=>'&sbquo;',
601
		'&#352;'=>'&Scaron;','&#353;'=>'&scaron;','&#8901;'=>'&sdot;','&#167;'=>'&sect;','&#173;'=>'&shy;',
602
		'&#931;'=>'&Sigma;','&#963;'=>'&sigma;','&#962;'=>'&sigmaf;','&#8764;'=>'&sim;','&#9824;'=>'&spades;',
603
		'&#8834;'=>'&sub;','&#8838;'=>'&sube;','&#8721;'=>'&sum;','&#8835;'=>'&sup;','&#185;'=>'&sup1;',
604
		'&#178;'=>'&sup2;','&#179;'=>'&sup3;','&#8839;'=>'&supe;','&#223;'=>'&szlig;','&#932;'=>'&Tau;',
605
		'&#964;'=>'&tau;','&#8756;'=>'&there4;','&#920;'=>'&Theta;','&#952;'=>'&theta;','&#977;'=>'&thetasym;',
606
		'&#8201;'=>'&thinsp;','&#222;'=>'&THORN;','&#254;'=>'&thorn;','&#732;'=>'&tilde;','&#215;'=>'&times;',
607
		'&#8482;'=>'&trade;','&#218;'=>'&Uacute;','&#250;'=>'&uacute;','&#8657;'=>'&uArr;','&#8593;'=>'&uarr;',
608
		'&#219;'=>'&Ucirc;','&#251;'=>'&ucirc;','&#217;'=>'&Ugrave;','&#249;'=>'&ugrave;','&#168;'=>'&uml;',
609
		'&#978;'=>'&upsih;','&#933;'=>'&Upsilon;','&#965;'=>'&upsilon;','&#220;'=>'&Uuml;','&#252;'=>'&uuml;',
610
		'&#8472;'=>'&weierp;','&#926;'=>'&Xi;','&#958;'=>'&xi;','&#221;'=>'&Yacute;','&#253;'=>'&yacute;',
611
		'&#165;'=>'&yen;','&#376;'=>'&Yuml;','&#255;'=>'&yuml;','&#918;'=>'&Zeta;','&#950;'=>'&zeta;','&#8205;'=>'&zwj;',
612
		'&#8204;'=>'&zwnj;'
613
	);
614
		
615
	if ($in == 'HTML-ENTITIES') {
616
		$string = strtr($string, array('&#039;'=>'&#39;')); // fix a broken entity
617
		$string = strtr($string, $named_to_numbered_entities);
618
		$string = preg_replace("/&#([0-9]+);/e", "code_to_utf8($1)", $string);
619
	}
620
	elseif ($out == 'HTML-ENTITIES') {
621
		//$string = preg_replace("/&#([0-9]+);/e", "code_to_utf8($1)", $string);
622
		$char = "";
623
		while (strlen($string) > 0) {
624
			preg_match("/^(.)(.*)$/su", $string, $match);
625
			if (strlen($match[1]) > 1) {
626
				$char .= "&#".uniord($match[1]).";";
627
			} else $char .= $match[1];
628
			$string = $match[2];
629
		}
630
		$string = $char;
631
		$string = strtr($string, $numbered_to_named_entities);
632
	}
633
	return $string;
634
}
635

    
636
// support-function for string_decode_encode_entities()
637
function uniord($c) {
638
        $ud = 0;
639
        if (ord($c{0}) >= 0 && ord($c{0}) <= 127) $ud = ord($c{0});
640
        if (ord($c{0}) >= 192 && ord($c{0}) <= 223) $ud = (ord($c{0})-192)*64 + (ord($c{1})-128);
641
        if (ord($c{0}) >= 224 && ord($c{0}) <= 239) $ud = (ord($c{0})-224)*4096 + (ord($c{1})-128)*64 + (ord($c{2})-128);
642
        if (ord($c{0}) >= 240 && ord($c{0}) <= 247) $ud = (ord($c{0})-240)*262144 + (ord($c{1})-128)*4096 + (ord($c{2})-128)*64 + (ord($c{3})-128);
643
        if (ord($c{0}) >= 248 && ord($c{0}) <= 251) $ud = (ord($c{0})-248)*16777216 + (ord($c{1})-128)*262144 + (ord($c{2})-128)*4096 + (ord($c{3})-128)*64 + (ord($c{4})-128);
644
        if (ord($c{0}) >= 252 && ord($c{0}) <= 253) $ud = (ord($c{0})-252)*1073741824 + (ord($c{1})-128)*16777216 + (ord($c{2})-128)*262144 + (ord($c{3})-128)*4096 + (ord($c{4})-128)*64 + (ord($c{5})-128);
645
        if (ord($c{0}) >= 254 && ord($c{0}) <= 255) $ud = false; // error
646
        return $ud;
647
}
648
// support-function for mb_convert_encoding_wrapper()
649
function code_to_utf8($num) {
650
	if ($num <= 0x7F) {
651
		return chr($num);
652
	} elseif ($num <= 0x7FF) {
653
		return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
654
	} elseif ($num <= 0xFFFF) {
655
		 return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
656
	} elseif ($num <= 0x1FFFFF) {
657
		return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
658
	}
659
	return " ";
660
}
661

    
662
// Function to convert a string from mixed html-entities/umlauts to pure utf-8-umlauts
663
function string_to_utf8($string, $charset=DEFAULT_CHARSET) {
664
	$charset = strtoupper($charset);
665
	if ($charset == '') { $charset = 'ISO-8859-1'; }
666

    
667
	if (!is_UTF8($string)) {
668
		$string=mb_convert_encoding_wrapper($string, 'UTF-8', $charset);
669
	}
670
	// check if we really get UTF-8. We don't get UTF-8 if charset is ISO-8859-6 or ISO-2022-JP/KR
671
	// and mb_string AND iconv aren't available.
672
	if (is_UTF8($string)) {
673
		$string=mb_convert_encoding_wrapper($string, 'HTML-ENTITIES', 'UTF-8');
674
		$string=mb_convert_encoding_wrapper($string, 'UTF-8', 'HTML-ENTITIES');
675
	} else {
676
		// nothing we can do here :-(
677
	}
678
	return($string);
679
}
680

    
681
// function to check if a string is UTF-8
682
function is_UTF8 ($str) {
683
	if (strlen($str) < 4000) {
684
		// see http://bugs.php.net/bug.php?id=24460 and http://bugs.php.net/bug.php?id=27070 and http://ilia.ws/archives/5-Top-10-ways-to-crash-PHP.html for this.
685
		// 4000 works for me ...
686
		return preg_match('/^(?:[\x09\x0A\x0D\x20-\x7E]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/s', $str);
687
	}	else {
688
		$isUTF8 = true;
689
		while($str{0}) {
690
			if (preg_match("/^[\x09\x0A\x0D\x20-\x7E]/", $str)) { $str = substr($str, 1); continue; }
691
			if (preg_match("/^[\xC2-\xDF][\x80-\xBF]/", $str)) { $str = substr($str, 2); continue; }
692
			if (preg_match("/^\xE0[\xA0-\xBF][\x80-\xBF]/", $str)) { $str = substr($str, 3); continue; }
693
			if (preg_match("/^[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}/", $str)) { $str = substr($str, 3); continue; }
694
			if (preg_match("/^\xED[\x80-\x9F][\x80-\xBF]/", $str)) { $str = substr($str, 3); continue; }
695
			if (preg_match("/^\xF0[\x90-\xBF][\x80-\xBF]{2}/", $str)) { $str = substr($str, 4); continue; }
696
			if (preg_match("/^[\xF1-\xF3][\x80-\xBF]{3}/", $str)) { $str = substr($str, 4); continue; }
697
			if (preg_match("/^\xF4[\x80-\x8F][\x80-\xBF]{2}/", $str)) { $str = substr($str, 4); continue; }
698
			if (preg_match("/^$/", $str)) { break; }
699
			$isUTF8 = false;
700
			break;
701
		}
702
		return ($isUTF8);
703
	}
704
}
705

    
706
// Function to convert a string from mixed html-entities/umlauts to pure $charset_out-umlauts
707
function entities_to_umlauts($string, $charset_out=DEFAULT_CHARSET, $convert_htmlspecialchars=0) {
708
	$charset_out = strtoupper($charset_out);
709
	if ($charset_out == '') { $charset_out = 'ISO-8859-1'; }
710
	$charset_in = strtoupper(DEFAULT_CHARSET);
711
	
712
	// string to utf-8
713
	if ($charset_in == 'ISO-8859-1' || $charset_in == 'UTF-8') {
714
		if ($charset_in == 'ISO-8859-1') {
715
			$string=utf8_encode($string);
716
		}
717
		// decode html-entities
718
		if(preg_match("/&[#a-zA-Z0-9]+;/", $string)) {
719
			$string=string_decode_encode_entities($string, 'UTF-8', 'HTML-ENTITIES');
720
			//$string=mb_convert_encoding_wrapper($string, 'HTML-ENTITIES', 'UTF-8');
721
			//$string=mb_convert_encoding_wrapper($string, 'UTF-8', 'HTML-ENTITIES');
722
		}
723
	}
724
	else {
725
		$string = string_to_utf8($string); // will decode html-entities, too.
726
	}
727
	// string to $charset_out
728
	if($charset_out == 'ISO-8859-1') {
729
			$string=utf8_decode($string);
730
	}
731
	elseif($charset_out != 'UTF-8' && is_UTF8($string)) {
732
		$string=mb_convert_encoding_wrapper($string, $charset_out, 'UTF-8');
733
	}
734
	return $string;
735
}	
736

    
737
// Function to convert a string from mixed html-entitites/$charset_in-umlauts to pure html-entities
738
function umlauts_to_entities($string, $charset_in=DEFAULT_CHARSET, $convert_htmlspecialchars=0) {
739
	$charset_in = strtoupper($charset_in);
740
	if ($charset_in == "") { $charset_in = 'ISO-8859-1'; }
741

    
742
	// string to utf-8
743
	if ($charset_in == 'ISO-8859-1' || $charset_in == 'UTF-8') {
744
		if ($charset_in == 'ISO-8859-1') {
745
			$string=utf8_encode($string);
746
		}
747
		// encode html-entities
748
		$string=string_decode_encode_entities($string, 'HTML-ENTITIES', 'UTF-8'); // this is very slow!
749
		//$string=mb_convert_encoding_wrapper($string, 'HTML-ENTITIES', 'UTF-8');
750
	}
751
	else {
752
		$string = string_to_utf8($string, $charset_in);
753
		// encode html-entities
754
		if (is_UTF8($string)) {
755
			$string=string_decode_encode_entities($string, 'HTML-ENTITIES', 'UTF-8');
756
			//$string=mb_convert_encoding_wrapper($string, 'HTML-ENTITIES', 'UTF-8');
757
		}
758
	}
759
	return $string;
760
}
761

    
762
function umlauts_to_defcharset($string, $charset) {
763
		$charset_out = strtoupper(DEFAULT_CHARSET);
764
		if ($charset_out == "") { $charset_out = 'ISO-8859-1'; }
765
		
766
		if($charset_out == $charset) {
767
			return $string;
768
		}
769
		if($charset_out == 'ISO-8859-1' && $charset == 'UTF-8') {
770
			$string = utf8_decode($string);
771
		}
772
		else {
773
			$string=mb_convert_encoding_wrapper($string, $charset_out, 'UTF-8');
774
		}
775
		
776
	return $string;
777
}
778
	
779
// translate any latin/greek/cyrillic html-entities to their plain 7bit equivalents
780
// and numbered-entities into hex
781
function entities_to_7bit($string) {
782
	require(WB_PATH.'/framework/convert.php');
783
	$string = strtr($string, $conversion_array);
784
	$string = preg_replace('/&#([0-9]+);/e', "dechex('$1')",  $string);
785
	return($string);
786
}
787

    
788
// Function to convert a page title to a page filename
789
function page_filename($string) {
790
	$string = entities_to_7bit(umlauts_to_entities($string));
791
	// Now replace spaces with page spcacer
792
	$string = str_replace(' ', PAGE_SPACER, $string);
793
	// Now remove all bad characters
794
	$bad = array(
795
	'\'', /* /  */ '"', /* " */	'<', /* < */	'>', /* > */
796
	'{', /* { */	'}', /* } */	'[', /* [ */	']', /* ] */	'`', /* ` */
797
	'!', /* ! */	'@', /* @ */	'#', /* # */	'$', /* $ */	'%', /* % */
798
	'^', /* ^ */	'&', /* & */	'*', /* * */	'(', /* ( */	')', /* ) */
799
	'=', /* = */	'+', /* + */	'|', /* | */	'/', /* / */	'\\', /* \ */
800
	';', /* ; */	':', /* : */	',', /* , */	'?' /* ? */
801
	);
802
	$string = str_replace($bad, '', $string);
803
	// Now convert to lower-case
804
	$string = strtolower($string);
805
	// Now remove multiple page spacers
806
	$string = str_replace(PAGE_SPACER.PAGE_SPACER, PAGE_SPACER, $string);
807
	// Clean any page spacers at the end of string
808
	$string = str_replace(PAGE_SPACER, ' ', $string);
809
	$string = trim($string);
810
	$string = str_replace(' ', PAGE_SPACER, $string);
811
	// If there are any weird language characters, this will protect us against possible problems they could cause
812
	$string = str_replace(array('%2F', '%'), array('/', ''), urlencode($string));
813
	// Finally, return the cleaned string
814
	return $string;
815
}
816

    
817
// Function to convert a desired media filename to a clean filename
818
function media_filename($string) {
819
	$string = entities_to_7bit(umlauts_to_entities($string));
820
	// Now remove all bad characters
821
	$bad = array(
822
	'\'', // '
823
	'"', // "
824
	'`', // `
825
	'!', // !
826
	'@', // @
827
	'#', // #
828
	'$', // $
829
	'%', // %
830
	'^', // ^
831
	'&', // &
832
	'*', // *
833
	'=', // =
834
	'+', // +
835
	'|', // |
836
	'/', // /
837
	'\\', // \
838
	';', // ;
839
	':', // :
840
	',', // ,
841
	'?' // ?
842
	);
843
	$string = str_replace($bad, '', $string);
844
	// Clean any page spacers at the end of string
845
	$string = trim($string);
846
	// Finally, return the cleaned string
847
	return $string;
848
}
849

    
850
// Function to work out a page link
851
if(!function_exists('page_link')) {
852
	function page_link($link) {
853
		global $admin;
854
		return $admin->page_link($link);
855
	}
856
}
857

    
858
// Create a new file in the pages directory
859
function create_access_file($filename,$page_id,$level) {
860
	global $admin;
861
	if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/')) {
862
		$admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE']);
863
	} else {
864
		// First make sure parent folder exists
865
		$parent_folders = explode('/',str_replace(WB_PATH.PAGES_DIRECTORY, '', dirname($filename)));
866
		$parents = '';
867
		foreach($parent_folders AS $parent_folder) {
868
			if($parent_folder != '/' AND $parent_folder != '') {
869
				$parents .= '/'.$parent_folder;
870
				if(!file_exists(WB_PATH.PAGES_DIRECTORY.$parents)) {
871
					make_dir(WB_PATH.PAGES_DIRECTORY.$parents);
872
				}
873
			}	
874
		}
875
		// The depth of the page directory in the directory hierarchy
876
		// '/pages' is at depth 1
877
		$pages_dir_depth=count(explode('/',PAGES_DIRECTORY))-1;
878
		// Work-out how many ../'s we need to get to the index page
879
		$index_location = '';
880
		for($i = 0; $i < $level + $pages_dir_depth; $i++) {
881
			$index_location .= '../';
882
		}
883
		$content = ''.
884
'<?php
885
$page_id = '.$page_id.';
886
require("'.$index_location.'config.php");
887
require(WB_PATH."/index.php");
888
?>';
889
		$handle = fopen($filename, 'w');
890
		fwrite($handle, $content);
891
		fclose($handle);
892
		// Chmod the file
893
		change_mode($filename, 'file');
894
	}
895
}
896

    
897
// Function for working out a file mime type (if the in-built PHP one is not enabled)
898
if(!function_exists('mime_content_type')) {
899
   function mime_content_type($file) {
900
       $file = escapeshellarg($file);
901
       return trim(`file -bi $file`);
902
   }
903
}
904

    
905
// Generate a thumbnail from an image
906
function make_thumb($source, $destination, $size) {
907
	// Check if GD is installed
908
	if(extension_loaded('gd') AND function_exists('imageCreateFromJpeg')) {
909
		// First figure out the size of the thumbnail
910
		list($original_x, $original_y) = getimagesize($source);
911
		if ($original_x > $original_y) {
912
			$thumb_w = $size;
913
			$thumb_h = $original_y*($size/$original_x);
914
		}
915
		if ($original_x < $original_y) {
916
			$thumb_w = $original_x*($size/$original_y);
917
			$thumb_h = $size;
918
		}
919
		if ($original_x == $original_y) {
920
			$thumb_w = $size;
921
			$thumb_h = $size;	
922
		}
923
		// Now make the thumbnail
924
		$source = imageCreateFromJpeg($source);
925
		$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
926
		imagecopyresampled($dst_img,$source,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);
927
		imagejpeg($dst_img, $destination);
928
		// Clear memory
929
		imagedestroy($dst_img);
930
	   imagedestroy($source);
931
	   // Return true
932
	   return true;
933
   } else {
934
   	return false;
935
   }
936
}
937

    
938
// Function to work-out a single part of an octal permission value
939
function extract_permission($octal_value, $who, $action) {
940
	// Make sure the octal value is 4 chars long
941
	if(strlen($octal_value) == 0) {
942
		$octal_value = '0000';
943
	} elseif(strlen($octal_value) == 1) {
944
		$octal_value = '000'.$octal_value;
945
	} elseif(strlen($octal_value) == 2) {
946
		$octal_value = '00'.$octal_value;
947
	} elseif(strlen($octal_value) == 3) {
948
		$octal_value = '0'.$octal_value;
949
	} elseif(strlen($octal_value) == 4) {
950
		$octal_value = ''.$octal_value;
951
	} else {
952
		$octal_value = '0000';
953
	}
954
	// Work-out what position of the octal value to look at
955
	switch($who) {
956
	case 'u':
957
		$position = '1';
958
		break;
959
	case 'user':
960
		$position = '1';
961
		break;
962
	case 'g':
963
		$position = '2';
964
		break;
965
	case 'group':
966
		$position = '2';
967
		break;
968
	case 'o':
969
		$position = '3';
970
		break;
971
	case 'others':
972
		$position = '3';
973
		break;
974
	}
975
	// Work-out how long the octal value is and ajust acording
976
	if(strlen($octal_value) == 4) {
977
		$position = $position+1;
978
	} elseif(strlen($octal_value) != 3) {
979
		exit('Error');
980
	}
981
	// Now work-out what action the script is trying to look-up
982
	switch($action) {
983
	case 'r':
984
		$action = 'r';
985
		break;
986
	case 'read':
987
		$action = 'r';
988
		break;
989
	case 'w':
990
		$action = 'w';
991
		break;
992
	case 'write':
993
		$action = 'w';
994
		break;
995
	case 'e':
996
		$action = 'e';
997
		break;
998
	case 'execute':
999
		$action = 'e';
1000
		break;
1001
	}
1002
	// Get the value for "who"
1003
	$value = substr($octal_value, $position-1, 1);
1004
	// Now work-out the details of the value
1005
	switch($value) {
1006
	case '0':
1007
		$r = false;
1008
		$w = false;
1009
		$e = false;
1010
		break;
1011
	case '1':
1012
		$r = false;
1013
		$w = false;
1014
		$e = true;
1015
		break;
1016
	case '2':
1017
		$r = false;
1018
		$w = true;
1019
		$e = false;
1020
		break;
1021
	case '3':
1022
		$r = false;
1023
		$w = true;
1024
		$e = true;
1025
		break;
1026
	case '4':
1027
		$r = true;
1028
		$w = false;
1029
		$e = false;
1030
		break;
1031
	case '5':
1032
		$r = true;
1033
		$w = false;
1034
		$e = true;
1035
		break;
1036
	case '6':
1037
		$r = true;
1038
		$w = true;
1039
		$e = false;
1040
		break;
1041
	case '7':
1042
		$r = true;
1043
		$w = true;
1044
		$e = true;
1045
		break;
1046
	default:
1047
		$r = false;
1048
		$w = false;
1049
		$e = false;
1050
	}
1051
	// And finally, return either true or false
1052
	return $$action;
1053
}
1054

    
1055
// Function to delete a page
1056
function delete_page($page_id) {
1057
	
1058
	global $admin, $database;
1059
	
1060
	// Find out more about the page
1061
	$database = new database();
1062
	$query = "SELECT page_id,menu_title,page_title,level,link,parent,modified_by,modified_when FROM ".TABLE_PREFIX."pages WHERE page_id = '$page_id'";
1063
	$results = $database->query($query);
1064
	if($database->is_error()) {
1065
		$admin->print_error($database->get_error());
1066
	}
1067
	if($results->numRows() == 0) {
1068
		$admin->print_error($MESSAGE['PAGES']['NOT_FOUND']);
1069
	}
1070
	$results_array = $results->fetchRow();
1071
	$parent = $results_array['parent'];
1072
	$level = $results_array['level'];
1073
	$link = $results_array['link'];
1074
	$page_title = ($results_array['page_title']);
1075
	$menu_title = ($results_array['menu_title']);
1076
	
1077
	// Get the sections that belong to the page
1078
	$query_sections = $database->query("SELECT section_id,module FROM ".TABLE_PREFIX."sections WHERE page_id = '$page_id'");
1079
	if($query_sections->numRows() > 0) {
1080
		while($section = $query_sections->fetchRow()) {
1081
			// Set section id
1082
			$section_id = $section['section_id'];
1083
			// Include the modules delete file if it exists
1084
			if(file_exists(WB_PATH.'/modules/'.$section['module'].'/delete.php')) {
1085
				require(WB_PATH.'/modules/'.$section['module'].'/delete.php');
1086
			}
1087
		}
1088
	}
1089
	
1090
	// Update the pages table
1091
	$query = "DELETE FROM ".TABLE_PREFIX."pages WHERE page_id = '$page_id'";
1092
	$database->query($query);
1093
	if($database->is_error()) {
1094
		$admin->print_error($database->get_error());
1095
	}
1096
	
1097
	// Update the sections table
1098
	$query = "DELETE FROM ".TABLE_PREFIX."sections WHERE page_id = '$page_id'";
1099
	$database->query($query);
1100
	if($database->is_error()) {
1101
		$admin->print_error($database->get_error());
1102
	}
1103
	
1104
	// Include the ordering class or clean-up ordering
1105
	require_once(WB_PATH.'/framework/class.order.php');
1106
	$order = new order(TABLE_PREFIX.'pages', 'position', 'page_id', 'parent');
1107
	$order->clean($parent);
1108
	
1109
	// Unlink the page access file and directory
1110
	$directory = WB_PATH.PAGES_DIRECTORY.$link;
1111
	$filename = $directory.'.php';
1112
	$directory .= '/';
1113
	if(file_exists($filename) && substr($filename,0,1<>'.')) {
1114
		if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/')) {
1115
			$admin->print_error($MESSAGE['PAGES']['CANNOT_DELETE_ACCESS_FILE']);
1116
		} else {
1117
			unlink($filename);
1118
			if(file_exists($directory)) {
1119
				rm_full_dir($directory);
1120
			}
1121
		}
1122
	}
1123
	
1124
}
1125

    
1126
// Load module into DB
1127
function load_module($directory, $install = false) {
1128
	global $database,$admin,$MESSAGE;
1129
	if(file_exists($directory.'/info.php')) {
1130
		require($directory.'/info.php');
1131
		if(isset($module_name)) {
1132
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1133
			if(!isset($module_platform) AND isset($module_designed_for)) { $module_platform = $module_designed_for; }
1134
			if(!isset($module_function) AND isset($module_type)) { $module_function = $module_type; }
1135
			$module_function = strtolower($module_function);
1136
			// Check that it doesn't already exist
1137
			$result = $database->query("SELECT addon_id FROM ".TABLE_PREFIX."addons WHERE directory = '".$module_directory."' LIMIT 0,1");
1138
			if($result->numRows() == 0) {
1139
				// Load into DB
1140
				$query = "INSERT INTO ".TABLE_PREFIX."addons ".
1141
				"(directory,name,description,type,function,version,platform,author,license) ".
1142
				"VALUES ('$module_directory','$module_name','".addslashes($module_description)."','module',".
1143
				"'$module_function','$module_version','$module_platform','$module_author','$module_license')";
1144
				$database->query($query);
1145
				// Run installation script
1146
				if($install == true) {
1147
					if(file_exists($directory.'/install.php')) {
1148
						require($directory.'/install.php');
1149
					}
1150
				}
1151
			}
1152
		}
1153
	}
1154
}
1155

    
1156
// Load template into DB
1157
function load_template($directory) {
1158
	global $database;
1159
	if(file_exists($directory.'/info.php')) {
1160
		require($directory.'/info.php');
1161
		if(isset($template_name)) {
1162
			if(!isset($template_license)) { $template_license = 'GNU General Public License'; }
1163
			if(!isset($template_platform) AND isset($template_designed_for)) { $template_platform = $template_designed_for; }
1164
			// Check that it doesn't already exist
1165
			$result = $database->query("SELECT addon_id FROM ".TABLE_PREFIX."addons WHERE directory = '".$template_directory."' LIMIT 0,1");
1166
			if($result->numRows() == 0) {
1167
				// Load into DB
1168
				$query = "INSERT INTO ".TABLE_PREFIX."addons ".
1169
				"(directory,name,description,type,version,platform,author,license) ".
1170
				"VALUES ('$template_directory','$template_name','".addslashes($template_description)."','template',".
1171
				"'$template_version','$template_platform','$template_author','$template_license')";
1172
				$database->query($query);
1173
			}
1174
		}
1175
	}
1176
}
1177

    
1178
// Load language into DB
1179
function load_language($file) {
1180
	global $database;
1181
	if(file_exists($file)) {
1182
		require($file);
1183
		if(isset($language_name)) {
1184
			if(!isset($language_license)) { $language_license = 'GNU General Public License'; }
1185
			if(!isset($language_platform) AND isset($language_designed_for)) { $language_platform = $language_designed_for; }
1186
			// Check that it doesn't already exist
1187
			$result = $database->query("SELECT addon_id FROM ".TABLE_PREFIX."addons WHERE directory = '".$language_code."' LIMIT 0,1");
1188
			if($result->numRows() == 0) {
1189
				// Load into DB
1190
				$query = "INSERT INTO ".TABLE_PREFIX."addons ".
1191
				"(directory,name,type,version,platform,author,license) ".
1192
				"VALUES ('$language_code','$language_name','language',".
1193
				"'$language_version','$language_platform','$language_author','$language_license')";
1194
	 		$database->query($query);
1195
			}
1196
		}
1197
	}
1198
}
1199

    
1200
// Upgrade module info in DB, optionally start upgrade script
1201
function upgrade_module($directory, $upgrade = false) {
1202
	global $database, $admin, $MESSAGE;
1203
	$directory = WB_PATH . "/modules/$directory";
1204
	if(file_exists($directory.'/info.php')) {
1205
		require($directory.'/info.php');
1206
		if(isset($module_name)) {
1207
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1208
			if(!isset($module_platform) AND isset($module_designed_for)) { $module_platform = $module_designed_for; }
1209
			if(!isset($module_function) AND isset($module_type)) { $module_function = $module_type; }
1210
			$module_function = strtolower($module_function);
1211
			// Check that it does already exist
1212
			$result = $database->query("SELECT addon_id FROM ".TABLE_PREFIX."addons WHERE directory = '".$module_directory."' LIMIT 0,1");
1213
			if($result->numRows() > 0) {
1214
				// Update in DB
1215
				$query = "UPDATE " . TABLE_PREFIX . "addons SET " .
1216
					"version = '$module_version', " .
1217
					"description = '" . addslashes($module_description) . "', " .
1218
					"platform = '$module_platform', " .
1219
					"author = '$module_author', " .
1220
					"license = '$module_license'" .
1221
					"WHERE directory = '$module_directory'";
1222
				$database->query($query);
1223
				// Run upgrade script
1224
				if($upgrade == true) {
1225
					if(file_exists($directory.'/upgrade.php')) {
1226
						require($directory.'/upgrade.php');
1227
					}
1228
				}
1229
			}
1230
		}
1231
	}
1232
}
1233

    
1234
?>
(10-10/12)