Project

General

Profile

1 1352 Luisehahne
<?php
2
/**
3
 *
4
 * @category        frontend
5
 * @package         framework
6 1705 Luisehahne
 * @author          Ryan Djurovich,WebsiteBaker Project
7
 * @copyright       2009-2012, WebsiteBaker Org. e.V.
8 1352 Luisehahne
 * @link			http://www.websitebaker2.org/
9
 * @license         http://www.gnu.org/licenses/gpl.html
10
 * @platform        WebsiteBaker 2.8.x
11 1374 Luisehahne
 * @requirements    PHP 5.2.2 and higher
12 1352 Luisehahne
 * @version         $Id$
13
 * @filesource		$HeadURL$
14
 * @lastmodified    $Date$
15
 *
16
*/
17 1496 DarkViper
/* -------------------------------------------------------- */
18
// Must include code to stop this file being accessed directly
19 1499 DarkViper
if(!defined('WB_PATH')) {
20
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
21
	throw new IllegalFileException();
22
}
23 1496 DarkViper
/* -------------------------------------------------------- */
24 1352 Luisehahne
// Define that this file has been loaded
25
define('FUNCTIONS_FILE_LOADED', true);
26
27 1365 Luisehahne
/**
28
 * @description: recursively delete a non empty directory
29
 * @param string $directory :
30
 * @param bool $empty : true if you want the folder just emptied, but not deleted
31
 *                      false, or just simply leave it out, the given directory will be deleted, as well
32 1676 Luisehahne
 * @return boolean: true/false
33 1365 Luisehahne
 * @from http://www.php.net/manual/de/function.rmdir.php#98499
34
 */
35 1676 Luisehahne
function rm_full_dir($directory, $empty = false)
36
{
37 1495 DarkViper
	if(substr($directory,-1) == "/") {
38 1365 Luisehahne
        $directory = substr($directory,0,-1);
39
    }
40 1601 Luisehahne
   // If suplied dirname is a file then unlink it
41 1676 Luisehahne
    if (is_file( $directory )&& is_writable( $directory )) {
42 1601 Luisehahne
	  $retval = unlink($directory);
43
	  clearstatcache();
44
      return $retval;
45 1352 Luisehahne
    }
46 1676 Luisehahne
    if(!is_writable($directory) || !is_dir($directory)) {
47 1365 Luisehahne
        return false;
48 1495 DarkViper
    } elseif(!is_readable($directory)) {
49 1365 Luisehahne
        return false;
50
    } else {
51
        $directoryHandle = opendir($directory);
52
        while ($contents = readdir($directoryHandle))
53
		{
54
            if($contents != '.' && $contents != '..')
55 1352 Luisehahne
			{
56 1365 Luisehahne
                $path = $directory . "/" . $contents;
57 1495 DarkViper
                if(is_dir($path)) {
58 1365 Luisehahne
                    rm_full_dir($path);
59
                } else {
60
                    unlink($path);
61 1601 Luisehahne
					clearstatcache();
62 1365 Luisehahne
                }
63 1352 Luisehahne
            }
64 1365 Luisehahne
        }
65
        closedir($directoryHandle);
66 1495 DarkViper
        if($empty == false) {
67 1676 Luisehahne
            if(is_dir($directory) && is_writable(dirname($directory))) {
68
                return rmdir($directory);
69
            } else {
70
				return false;
71 1352 Luisehahne
            }
72
        }
73 1365 Luisehahne
        return true;
74
    }
75 1352 Luisehahne
}
76
77
/*
78
 * returns a recursive list of all subdirectories from a given directory
79
 * @access  public
80
 * @param   string  $directory: from this dir the recursion will start
81
 * @param   bool    $show_hidden:  if set to TRUE also hidden dirs (.dir) will be shown
82
 * @return  array
83
 * example:
84
 *  /srv/www/httpdocs/wb/media/a/b/c/
85
 *  /srv/www/httpdocs/wb/media/a/b/d/
86
 * directory_list('/srv/www/httpdocs/wb/media/') will return:
87
 *  /a
88
 *  /a/b
89
 *  /a/b/c
90
 *  /a/b/d
91
 */
92
 function directory_list($directory, $show_hidden = false)
93
{
94
	$result_list = array();
95
	if (is_dir($directory))
96
    {
97
    	$dir = dir($directory); // Open the directory
98
    	while (false !== $entry = $dir->read()) // loop through the directory
99
		{
100
			if($entry == '.' || $entry == '..') { continue; } // Skip pointers
101
			if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
102 1495 DarkViper
    		if (is_dir("$directory/$entry")) { // Add dir and contents to list
103 1352 Luisehahne
    			$result_list = array_merge($result_list, directory_list("$directory/$entry"));
104
    			$result_list[] = "$directory/$entry";
105
    		}
106
    	}
107
        $dir->close();
108
    }
109 1365 Luisehahne
	// sorting
110 1495 DarkViper
	if(natcasesort($result_list)) {
111 1365 Luisehahne
		// new indexing
112
		$result_list = array_merge($result_list);
113
	}
114 1352 Luisehahne
	return $result_list; // Now return the list
115
}
116
117
// Function to open a directory and add to a dir list
118
function chmod_directory_contents($directory, $file_mode)
119
{
120
	if (is_dir($directory))
121
    {
122
    	// Set the umask to 0
123
    	$umask = umask(0);
124
    	// Open the directory then loop through its contents
125
    	$dir = dir($directory);
126
    	while (false !== $entry = $dir->read())
127
		{
128
    		// Skip pointers
129
    		if($entry[0] == '.') { continue; }
130
    		// Chmod the sub-dirs contents
131 1495 DarkViper
    		if(is_dir("$directory/$entry")) {
132 1352 Luisehahne
    			chmod_directory_contents($directory.'/'.$entry, $file_mode);
133
    		}
134
    		change_mode($directory.'/'.$entry);
135
    	}
136
        $dir->close();
137
    	// Restore the umask
138
    	umask($umask);
139
    }
140
}
141
142 1365 Luisehahne
/**
143
* Scan a given directory for dirs and files.
144
*
145
* usage: scan_current_dir ($root = '' )
146
*
147
* @param     $root   set a absolute rootpath as string. if root is empty the current path will be scan
148
* @param     $search set a search pattern for files, empty search brings all files
149
* @access    public
150
* @return    array    returns a natsort array with keys 'path' and 'filename'
151
*
152
*/
153
if(!function_exists('scan_current_dir'))
154
{
155
	function scan_current_dir($root = '', $search = '/.*/')
156
	{
157
	    $FILE = array();
158
		$array = array();
159
	    clearstatcache();
160
	    $root = empty ($root) ? getcwd() : $root;
161
	    if (($handle = opendir($root)))
162
	    {
163
	    // Loop through the files and dirs an add to list  DIRECTORY_SEPARATOR
164
	        while (false !== ($file = readdir($handle)))
165
	        {
166
	            if (substr($file, 0, 1) != '.' && $file != 'index.php')
167
	            {
168 1495 DarkViper
	                if (is_dir($root.'/'.$file)) {
169 1365 Luisehahne
	                    $FILE['path'][] = $file;
170 1495 DarkViper
	                } elseif (preg_match($search, $file, $array) ) {
171 1365 Luisehahne
	                    $FILE['filename'][] = $array[0];
172
	                }
173
	            }
174
	        }
175
	        $close_verz = closedir($handle);
176
	    }
177
		// sorting
178 1495 DarkViper
	    if (isset ($FILE['path']) && natcasesort($FILE['path'])) {
179 1365 Luisehahne
			// new indexing
180
	        $FILE['path'] = array_merge($FILE['path']);
181
	    }
182
		// sorting
183 1495 DarkViper
	    if (isset ($FILE['filename']) && natcasesort($FILE['filename'])) {
184 1365 Luisehahne
			// new indexing
185
	        $FILE['filename'] = array_merge($FILE['filename']);
186
	    }
187
	    return $FILE;
188
	}
189
}
190
191 1352 Luisehahne
// Function to open a directory and add to a file list
192
function file_list($directory, $skip = array(), $show_hidden = false)
193
{
194
	$result_list = array();
195
	if (is_dir($directory))
196
    {
197
    	$dir = dir($directory); // Open the directory
198
		while (false !== ($entry = $dir->read())) // loop through the directory
199
		{
200
			if($entry == '.' || $entry == '..') { continue; } // Skip pointers
201
			if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
202
			if( sizeof($skip) > 0 && in_array($entry, $skip) ) { continue; } // Check if we to skip anything else
203 1495 DarkViper
			if(is_file( $directory.'/'.$entry)) { // Add files to list
204 1352 Luisehahne
				$result_list[] = $directory.'/'.$entry;
205
			}
206
		}
207
		$dir->close(); // Now close the folder object
208
	}
209 1365 Luisehahne
210
    // make the list nice. Not all OS do this itself
211 1495 DarkViper
	if(natcasesort($result_list)) {
212 1365 Luisehahne
		$result_list = array_merge($result_list);
213 1495 DarkViper
	}
214 1352 Luisehahne
	return $result_list;
215
}
216
217
// Function to get a list of home folders not to show
218
function get_home_folders()
219
{
220
	global $database, $admin;
221
	$home_folders = array();
222
	// Only return home folders is this feature is enabled
223
	// and user is not admin
224
//	if(HOME_FOLDERS AND ($_SESSION['GROUP_ID']!='1')) {
225
	if(HOME_FOLDERS AND (!in_array('1',explode(',', $_SESSION['GROUPS_ID']))))
226
	{
227 1495 DarkViper
		$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
228
		$sql .= 'WHERE `home_folder`!=\''.$admin->get_home_folder().'\'';
229 1352 Luisehahne
		$query_home_folders = $database->query($sql);
230
		if($query_home_folders->numRows() > 0)
231
		{
232 1495 DarkViper
			while($folder = $query_home_folders->fetchRow()) {
233 1352 Luisehahne
				$home_folders[$folder['home_folder']] = $folder['home_folder'];
234
			}
235
		}
236
		function remove_home_subs($directory = '/', $home_folders = '')
237
		{
238 1365 Luisehahne
			if( ($handle = opendir(WB_PATH.MEDIA_DIRECTORY.$directory)) )
239 1352 Luisehahne
			{
240
				// Loop through the dirs to check the home folders sub-dirs are not shown
241
				while(false !== ($file = readdir($handle)))
242
				{
243 1365 Luisehahne
					if($file[0] != '.' && $file != 'index.php')
244 1352 Luisehahne
					{
245
						if(is_dir(WB_PATH.MEDIA_DIRECTORY.$directory.'/'.$file))
246
						{
247 1495 DarkViper
							if($directory != '/') {
248 1352 Luisehahne
								$file = $directory.'/'.$file;
249 1495 DarkViper
							}else {
250 1352 Luisehahne
								$file = '/'.$file;
251
							}
252
							foreach($home_folders AS $hf)
253
							{
254
								$hf_length = strlen($hf);
255 1495 DarkViper
								if($hf_length > 0) {
256
									if(substr($file, 0, $hf_length+1) == $hf) {
257 1352 Luisehahne
										$home_folders[$file] = $file;
258
									}
259
								}
260
							}
261
							$home_folders = remove_home_subs($file, $home_folders);
262
						}
263
					}
264
				}
265
			}
266
			return $home_folders;
267
		}
268
		$home_folders = remove_home_subs('/', $home_folders);
269
	}
270
	return $home_folders;
271
}
272
273 1365 Luisehahne
/*
274
 * @param object &$wb: $wb from frontend or $admin from backend
275
 * @return array: list of new entries
276
 * @description: callback remove path in files/dirs stored in array
277
 * @example: array_walk($array,'remove_path',PATH);
278
 */
279
//
280
function remove_path(&$path, $key, $vars = '')
281
{
282
	$path = str_replace($vars, '', $path);
283
}
284
285
/*
286
 * @param object &$wb: $wb from frontend or $admin from backend
287
 * @return array: list of ro-dirs
288
 * @description: returns a list of directories beyound /wb/media which are ReadOnly for current user
289
 */
290
function media_dirs_ro( &$wb )
291
{
292
	global $database;
293
	// if user is admin or home-folders not activated then there are no restrictions
294
	$allow_list = array();
295 1495 DarkViper
	if( $wb->get_user_id() == 1 || !HOME_FOLDERS ) {
296 1365 Luisehahne
		return array();
297
	}
298
	// at first read any dir and subdir from /media
299
	$full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
300
	// add own home_folder to allow-list
301 1495 DarkViper
	if( $wb->get_home_folder() ) {
302 1365 Luisehahne
		// old: $allow_list[] = get_home_folder();
303
		$allow_list[] = $wb->get_home_folder();
304
	}
305
	// get groups of current user
306
	$curr_groups = $wb->get_groups_id();
307
	// if current user is in admin-group
308 1495 DarkViper
	if( ($admin_key = array_search('1', $curr_groups)) !== false)
309 1365 Luisehahne
	{
310
		// remove admin-group from list
311
		unset($curr_groups[$admin_key]);
312
		// search for all users where the current user is admin from
313
		foreach( $curr_groups as $group)
314
		{
315
			$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
316
			$sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
317 1495 DarkViper
			if( ($res_hf = $database->query($sql)) != null ) {
318
				while( $rec_hf = $res_hf->fetchrow() ) {
319 1365 Luisehahne
					$allow_list[] = $rec_hf['home_folder'];
320
				}
321
			}
322
		}
323
	}
324
	$tmp_array = $full_list;
325
	// create a list for readonly dir
326
    $array = array();
327
	while( sizeof($tmp_array) > 0)
328
	{
329
        $tmp = array_shift($tmp_array);
330
        $x = 0;
331 1495 DarkViper
		while($x < sizeof($allow_list)) {
332 1365 Luisehahne
			if(strpos ($tmp,$allow_list[$x])) {
333
				$array[] = $tmp;
334
			}
335
			$x++;
336
		}
337
	}
338
	$full_list = array_diff( $full_list, $array );
339
	$tmp = array();
340
	$full_list = array_merge($tmp,$full_list);
341
	return $full_list;
342
}
343
344
/*
345
 * @param object &$wb: $wb from frontend or $admin from backend
346
 * @return array: list of rw-dirs
347
 * @description: returns a list of directories beyound /wb/media which are ReadWrite for current user
348
 */
349
function media_dirs_rw ( &$wb )
350
{
351
	global $database;
352
	// if user is admin or home-folders not activated then there are no restrictions
353
	// at first read any dir and subdir from /media
354
	$full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
355
    $array = array();
356
	$allow_list = array();
357 1495 DarkViper
	if( ($wb->ami_group_member('1')) && !HOME_FOLDERS ) {
358 1365 Luisehahne
		return $full_list;
359
	}
360
	// add own home_folder to allow-list
361 1495 DarkViper
	if( $wb->get_home_folder() ) {
362 1365 Luisehahne
	  	$allow_list[] = $wb->get_home_folder();
363
	} else {
364
		$array = $full_list;
365
	}
366
	// get groups of current user
367
	$curr_groups = $wb->get_groups_id();
368
	// if current user is in admin-group
369
	if( ($admin_key = array_search('1', $curr_groups)) == true)
370
	{
371
		// remove admin-group from list
372
		// unset($curr_groups[$admin_key]);
373
		// search for all users where the current user is admin from
374
		foreach( $curr_groups as $group)
375
		{
376
			$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
377
			$sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
378 1495 DarkViper
			if( ($res_hf = $database->query($sql)) != null ) {
379
				while( $rec_hf = $res_hf->fetchrow() ) {
380 1365 Luisehahne
					$allow_list[] = $rec_hf['home_folder'];
381
				}
382
			}
383
		}
384
	}
385
386
	$tmp_array = $full_list;
387
	// create a list for readwrite dir
388
	while( sizeof($tmp_array) > 0)
389
	{
390
        $tmp = array_shift($tmp_array);
391
        $x = 0;
392 1495 DarkViper
		while($x < sizeof($allow_list)) {
393 1365 Luisehahne
			if(strpos ($tmp,$allow_list[$x])) {
394
				$array[] = $tmp;
395
			}
396
			$x++;
397
		}
398
	}
399
	$tmp = array();
400
    $array = array_unique($array);
401
	$full_list = array_merge($tmp,$array);
402
    unset($array);
403
    unset($allow_list);
404
	return $full_list;
405
}
406
407 1352 Luisehahne
// Function to create directories
408 1556 Luisehahne
function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE, $recursive=true)
409 1352 Luisehahne
{
410 1555 Luisehahne
	$retVal = false;
411 1352 Luisehahne
	if(!is_dir($dir_name))
412
    {
413 1555 Luisehahne
		$retVal = mkdir($dir_name, $dir_mode,$recursive);
414 1352 Luisehahne
	}
415 1555 Luisehahne
	return $retVal;
416 1352 Luisehahne
}
417
418 1651 darkviper
/**
419
 * Function to chmod files and/or directories
420 1653 darkviper
 * the function also prevents the owner to loose rw-rights
421 1651 darkviper
 * @param string $sName
422
 * @param int rights in dec-value. 0= use wb-defaults
423 1676 Luisehahne
 * @return bool
424 1651 darkviper
 */
425
function change_mode($sName, $iMode = 0)
426 1352 Luisehahne
{
427 1651 darkviper
	$bRetval = true;
428 1653 darkviper
	$iMode = intval($iMode) & 0777; // sanitize value
429 1705 Luisehahne
	if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
430 1651 darkviper
	{ // Only chmod if os is not windows
431
		$bRetval = false;
432
		if(!$iMode) {
433
			$iMode = (is_file($sName) ? octdec(STRING_FILE_MODE) : octdec(STRING_DIR_MODE));
434 1352 Luisehahne
		}
435 1653 darkviper
		$iMode |= 0600; // set o+rw
436 1651 darkviper
		if(is_writable($sName)) {
437
			$bRetval = chmod($sName, $iMode);
438 1352 Luisehahne
		}
439
	}
440 1651 darkviper
	return $bRetval;
441 1352 Luisehahne
}
442
443
// Function to figure out if a parent exists
444
function is_parent($page_id)
445
{
446
	global $database;
447
	// Get parent
448
	$sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
449
	$parent = $database->get_one($sql);
450
	// If parent isnt 0 return its ID
451 1495 DarkViper
	if(is_null($parent)) {
452 1352 Luisehahne
		return false;
453 1495 DarkViper
	}else {
454 1352 Luisehahne
		return $parent;
455
	}
456
}
457
458
// Function to work out level
459
function level_count($page_id)
460
{
461
	global $database;
462
	// Get page parent
463
	$sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
464
	$parent = $database->get_one($sql);
465 1495 DarkViper
	if($parent > 0)
466 1352 Luisehahne
	{	// Get the level of the parent
467
		$sql = 'SELECT `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$parent;
468
		$level = $database->get_one($sql);
469
		return $level+1;
470 1495 DarkViper
	}else {
471 1352 Luisehahne
		return 0;
472
	}
473
}
474
475
// Function to work out root parent
476
function root_parent($page_id)
477
{
478
	global $database;
479
	// Get page details
480
	$sql = 'SELECT `parent`, `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
481
	$query_page = $database->query($sql);
482
	$fetch_page = $query_page->fetchRow();
483
	$parent = $fetch_page['parent'];
484 1495 DarkViper
	$level = $fetch_page['level'];
485
	if($level == 1) {
486 1352 Luisehahne
		return $parent;
487 1495 DarkViper
	}elseif($parent == 0) {
488 1352 Luisehahne
		return $page_id;
489 1495 DarkViper
	}else {	// Figure out what the root parents id is
490 1352 Luisehahne
		$parent_ids = array_reverse(get_parent_ids($page_id));
491
		return $parent_ids[0];
492
	}
493
}
494
495
// Function to get page title
496
function get_page_title($id)
497
{
498
	global $database;
499
	// Get title
500
	$sql = 'SELECT `page_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
501
	$page_title = $database->get_one($sql);
502
	return $page_title;
503
}
504
505
// Function to get a pages menu title
506
function get_menu_title($id)
507
{
508
	global $database;
509
	// Get title
510
	$sql = 'SELECT `menu_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
511
	$menu_title = $database->get_one($sql);
512
	return $menu_title;
513
}
514
515
// Function to get all parent page titles
516
function get_parent_titles($parent_id)
517
{
518
	$titles[] = get_menu_title($parent_id);
519 1495 DarkViper
	if(is_parent($parent_id) != false) {
520 1352 Luisehahne
		$parent_titles = get_parent_titles(is_parent($parent_id));
521
		$titles = array_merge($titles, $parent_titles);
522
	}
523
	return $titles;
524
}
525
526
// Function to get all parent page id's
527
function get_parent_ids($parent_id)
528
{
529
	$ids[] = $parent_id;
530 1495 DarkViper
	if(is_parent($parent_id) != false) {
531 1352 Luisehahne
		$parent_ids = get_parent_ids(is_parent($parent_id));
532
		$ids = array_merge($ids, $parent_ids);
533
	}
534
	return $ids;
535
}
536
537
// Function to genereate page trail
538 1495 DarkViper
function get_page_trail($page_id)
539
{
540 1352 Luisehahne
	return implode(',', array_reverse(get_parent_ids($page_id)));
541
}
542
543
// Function to get all sub pages id's
544 1514 Luisehahne
function get_subs($parent, array $subs )
545 1352 Luisehahne
{
546
	// Connect to the database
547
	global $database;
548
	// Get id's
549
	$sql = 'SELECT `page_id` FROM `'.TABLE_PREFIX.'pages` WHERE `parent` = '.$parent;
550 1514 Luisehahne
	if( ($query = $database->query($sql)) ) {
551 1495 DarkViper
		while($fetch = $query->fetchRow()) {
552 1352 Luisehahne
			$subs[] = $fetch['page_id'];
553 1514 Luisehahne
			// Get subs of this sub recursive
554 1352 Luisehahne
			$subs = get_subs($fetch['page_id'], $subs);
555
		}
556
	}
557
	// Return subs array
558
	return $subs;
559
}
560
561
// Function as replacement for php's htmlspecialchars()
562
// Will not mangle HTML-entities
563
function my_htmlspecialchars($string)
564
{
565
	$string = preg_replace('/&(?=[#a-z0-9]+;)/i', '__amp;_', $string);
566
	$string = strtr($string, array('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;', '\''=>'&#39;'));
567
	$string = preg_replace('/__amp;_(?=[#a-z0-9]+;)/i', '&', $string);
568
	return($string);
569
}
570
571
// Convert a string from mixed html-entities/umlauts to pure $charset_out-umlauts
572
// Will replace all numeric and named entities except &gt; &lt; &apos; &quot; &#039; &nbsp;
573
// In case of error the returned string is unchanged, and a message is emitted.
574
function entities_to_umlauts($string, $charset_out=DEFAULT_CHARSET)
575
{
576
	require_once(WB_PATH.'/framework/functions-utf8.php');
577
	return entities_to_umlauts2($string, $charset_out);
578
}
579
580
// Will convert a string in $charset_in encoding to a pure ASCII string with HTML-entities.
581
// In case of error the returned string is unchanged, and a message is emitted.
582
function umlauts_to_entities($string, $charset_in=DEFAULT_CHARSET)
583
{
584
	require_once(WB_PATH.'/framework/functions-utf8.php');
585
	return umlauts_to_entities2($string, $charset_in);
586
}
587
588
// Function to convert a page title to a page filename
589
function page_filename($string)
590
{
591
	require_once(WB_PATH.'/framework/functions-utf8.php');
592
	$string = entities_to_7bit($string);
593
	// Now remove all bad characters
594
	$bad = array(
595
	'\'', /* /  */ '"', /* " */	'<', /* < */	'>', /* > */
596
	'{', /* { */	'}', /* } */	'[', /* [ */	']', /* ] */	'`', /* ` */
597
	'!', /* ! */	'@', /* @ */	'#', /* # */	'$', /* $ */	'%', /* % */
598
	'^', /* ^ */	'&', /* & */	'*', /* * */	'(', /* ( */	')', /* ) */
599
	'=', /* = */	'+', /* + */	'|', /* | */	'/', /* / */	'\\', /* \ */
600
	';', /* ; */	':', /* : */	',', /* , */	'?' /* ? */
601
	);
602
	$string = str_replace($bad, '', $string);
603
	// replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
604
	$string = preg_replace(array('/\.+/', '/\.+$/'), array('.', ''), $string);
605
	// Now replace spaces with page spcacer
606
	$string = trim($string);
607
	$string = preg_replace('/(\s)+/', PAGE_SPACER, $string);
608
	// Now convert to lower-case
609
	$string = strtolower($string);
610
	// If there are any weird language characters, this will protect us against possible problems they could cause
611
	$string = str_replace(array('%2F', '%'), array('/', ''), urlencode($string));
612
	// Finally, return the cleaned string
613
	return $string;
614
}
615
616 1457 Luisehahne
// Function to convert a desired media filename to a clean mediafilename
617 1352 Luisehahne
function media_filename($string)
618
{
619
	require_once(WB_PATH.'/framework/functions-utf8.php');
620
	$string = entities_to_7bit($string);
621
	// Now remove all bad characters
622 1454 DarkViper
	$bad = array('\'','"','`','!','@','#','$','%','^','&','*','=','+','|','/','\\',';',':',',','?');
623 1352 Luisehahne
	$string = str_replace($bad, '', $string);
624
	// replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
625 1454 DarkViper
	$string = preg_replace(array('/\.+/', '/\.+$/', '/\s/'), array('.', '', '_'), $string);
626 1352 Luisehahne
	// Clean any page spacers at the end of string
627
	$string = trim($string);
628
	// Finally, return the cleaned string
629
	return $string;
630
}
631
632
// Function to work out a page link
633
if(!function_exists('page_link'))
634
{
635
	function page_link($link)
636
	{
637
		global $admin;
638
		return $admin->page_link($link);
639
	}
640
}
641
642 1468 Luisehahne
// Create a new directory and/or protected file in the given directory
643 1477 Luisehahne
function createFolderProtectFile($sAbsDir='',$make_dir=true)
644 1457 Luisehahne
{
645
	global $admin, $MESSAGE;
646
	$retVal = array();
647 1484 Luisehahne
	$wb_path = rtrim(str_replace('\/\\', '/', WB_PATH), '/');
648
    if( ($sAbsDir=='') || ($sAbsDir == $wb_path) ) { return $retVal;}
649 1457 Luisehahne
650
	if ( $make_dir==true ) {
651
		// Check to see if the folder already exists
652 1477 Luisehahne
		if(file_exists($sAbsDir)) {
653 1457 Luisehahne
			// $admin->print_error($MESSAGE['MEDIA_DIR_EXISTS']);
654 1477 Luisehahne
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_EXISTS'];
655 1457 Luisehahne
		}
656 1555 Luisehahne
		if (!is_dir($sAbsDir) && !make_dir($sAbsDir) ) {
657 1457 Luisehahne
			// $admin->print_error($MESSAGE['MEDIA_DIR_NOT_MADE']);
658 1477 Luisehahne
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_NOT_MADE'];
659
		} else {
660
			change_mode($sAbsDir);
661 1457 Luisehahne
		}
662
	}
663
664 1477 Luisehahne
	if( is_writable($sAbsDir) )
665 1457 Luisehahne
	{
666 1477 Luisehahne
        // if(file_exists($sAbsDir.'/index.php')) { unlink($sAbsDir.'/index.php'); }
667 1457 Luisehahne
	    // Create default "index.php" file
668 1484 Luisehahne
		$rel_pages_dir = str_replace($wb_path, '', dirname($sAbsDir) );
669 1457 Luisehahne
		$step_back = str_repeat( '../', substr_count($rel_pages_dir, '/')+1 );
670
671
		$sResponse  = $_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently';
672
		$content =
673
			'<?php'."\n".
674
			'// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
675
			'// *** Creation date: '.date('c')."\n".
676
			'// *** Do not modify this file manually'."\n".
677
			'// *** WB will rebuild this file from time to time!!'."\n".
678
			'// *************************************************'."\n".
679
			"\t".'header(\''.$sResponse.'\');'."\n".
680
			"\t".'header(\'Location: '.WB_URL.'/index.php\');'."\n".
681
			'// *************************************************'."\n";
682 1477 Luisehahne
		$filename = $sAbsDir.'/index.php';
683 1484 Luisehahne
684 1457 Luisehahne
		// write content into file
685 1551 Luisehahne
		  if(is_writable($filename) || !file_exists($filename)) {
686
		      if(file_put_contents($filename, $content)) {
687
		//    print 'create => '.str_replace( $wb_path,'',$filename).'<br />';
688
		          change_mode($filename, 'file');
689
		      }else {
690
		    $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'].' :: '.$filename;
691
		   }
692
		  }
693
		 } else {
694
		   $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'];
695
		 }
696
		 return $retVal;
697 1457 Luisehahne
}
698
699
function rebuildFolderProtectFile($dir='')
700
{
701 1675 Luisehahne
	global $MESSAGE;
702 1495 DarkViper
	$retVal = array();
703
	$dir = rtrim(str_replace('\/\\', '/', $dir), '/');
704
	try {
705
		$files = array();
706
		$files[] = $dir;
707
		foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $fileInfo) {
708
			$files[] = $fileInfo->getPath();
709
		}
710
		$files = array_unique($files);
711
		foreach( $files as $file) {
712
			$protect_file = rtrim(str_replace('\/\\', '/', $file), '/');
713
			$retVal[] = createFolderProtectFile($protect_file,false);
714
		}
715
	} catch ( Exception $e ) {
716
		$retVal[] = $MESSAGE['MEDIA_DIR_ACCESS_DENIED'];
717
	}
718
	return $retVal;
719 1457 Luisehahne
}
720
721
// Create a new file in the pages directory
722 1352 Luisehahne
function create_access_file($filename,$page_id,$level)
723
{
724
	global $admin, $MESSAGE;
725 1495 DarkViper
	// First make sure parent folder exists
726
	$parent_folders = explode('/',str_replace(WB_PATH.PAGES_DIRECTORY, '', dirname($filename)));
727
	$parents = '';
728
	foreach($parent_folders AS $parent_folder)
729 1352 Luisehahne
	{
730 1495 DarkViper
		if($parent_folder != '/' AND $parent_folder != '')
731 1352 Luisehahne
		{
732 1495 DarkViper
			$parents .= '/'.$parent_folder;
733
			$acces_file = WB_PATH.PAGES_DIRECTORY.$parents;
734
			// can only be dirs
735
			if(!file_exists($acces_file)) {
736
				if(!make_dir($acces_file)) {
737
					$admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE_FOLDER']);
738 1352 Luisehahne
				}
739 1457 Luisehahne
			}
740 1352 Luisehahne
		}
741 1495 DarkViper
	}
742
	// The depth of the page directory in the directory hierarchy
743
	// '/pages' is at depth 1
744
	$pages_dir_depth = count(explode('/',PAGES_DIRECTORY))-1;
745
	// Work-out how many ../'s we need to get to the index page
746
	$index_location = '';
747
	for($i = 0; $i < $level + $pages_dir_depth; $i++) {
748
		$index_location .= '../';
749
	}
750
	$content =
751
		'<?php'."\n".
752
		'// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
753
		'// *** Creation date: '.date('c')."\n".
754
		'// *** Do not modify this file manually'."\n".
755
		'// *** WB will rebuild this file from time to time!!'."\n".
756
		'// *************************************************'."\n".
757
		"\t".'$page_id    = '.$page_id.';'."\n".
758
		"\t".'require(\''.$index_location.'index.php\');'."\n".
759
		'// *************************************************'."\n";
760 1352 Luisehahne
761 1495 DarkViper
	if( ($handle = fopen($filename, 'w')) ) {
762
		fwrite($handle, $content);
763
		fclose($handle);
764
		// Chmod the file
765
		change_mode($filename);
766
	} else {
767
		$admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE']);
768
	}
769 1457 Luisehahne
	return;
770
 }
771
772 1352 Luisehahne
// Function for working out a file mime type (if the in-built PHP one is not enabled)
773
if(!function_exists('mime_content_type'))
774
{
775 1457 Luisehahne
    function mime_content_type($filename)
776 1352 Luisehahne
	{
777
	    $mime_types = array(
778
            'txt'	=> 'text/plain',
779
            'htm'	=> 'text/html',
780
            'html'	=> 'text/html',
781
            'php'	=> 'text/html',
782
            'css'	=> 'text/css',
783
            'js'	=> 'application/javascript',
784
            'json'	=> 'application/json',
785
            'xml'	=> 'application/xml',
786
            'swf'	=> 'application/x-shockwave-flash',
787
            'flv'	=> 'video/x-flv',
788
789
            // images
790
            'png'	=> 'image/png',
791
            'jpe'	=> 'image/jpeg',
792
            'jpeg'	=> 'image/jpeg',
793
            'jpg'	=> 'image/jpeg',
794
            'gif'	=> 'image/gif',
795
            'bmp'	=> 'image/bmp',
796
            'ico'	=> 'image/vnd.microsoft.icon',
797
            'tiff'	=> 'image/tiff',
798
            'tif'	=> 'image/tiff',
799
            'svg'	=> 'image/svg+xml',
800
            'svgz'	=> 'image/svg+xml',
801
802
            // archives
803
            'zip'	=> 'application/zip',
804
            'rar'	=> 'application/x-rar-compressed',
805
            'exe'	=> 'application/x-msdownload',
806
            'msi'	=> 'application/x-msdownload',
807
            'cab'	=> 'application/vnd.ms-cab-compressed',
808
809
            // audio/video
810
            'mp3'	=> 'audio/mpeg',
811
            'mp4'	=> 'audio/mpeg',
812
            'qt'	=> 'video/quicktime',
813
            'mov'	=> 'video/quicktime',
814
815
            // adobe
816
            'pdf'	=> 'application/pdf',
817
            'psd'	=> 'image/vnd.adobe.photoshop',
818
            'ai'	=> 'application/postscript',
819
            'eps'	=> 'application/postscript',
820
            'ps'	=> 'application/postscript',
821
822
            // ms office
823
            'doc'	=> 'application/msword',
824
            'rtf'	=> 'application/rtf',
825
            'xls'	=> 'application/vnd.ms-excel',
826
            'ppt'	=> 'application/vnd.ms-powerpoint',
827
828
            // open office
829
            'odt'	=> 'application/vnd.oasis.opendocument.text',
830
            'ods'	=> 'application/vnd.oasis.opendocument.spreadsheet',
831
        );
832
        $temp = explode('.',$filename);
833
        $ext = strtolower(array_pop($temp));
834 1495 DarkViper
        if (array_key_exists($ext, $mime_types)) {
835 1352 Luisehahne
            return $mime_types[$ext];
836 1495 DarkViper
        }elseif (function_exists('finfo_open')) {
837 1352 Luisehahne
            $finfo = finfo_open(FILEINFO_MIME);
838
            $mimetype = finfo_file($finfo, $filename);
839
            finfo_close($finfo);
840
            return $mimetype;
841 1495 DarkViper
        }else {
842 1352 Luisehahne
            return 'application/octet-stream';
843
        }
844
    }
845
}
846
847
// Generate a thumbnail from an image
848
function make_thumb($source, $destination, $size)
849
{
850
	// Check if GD is installed
851 1365 Luisehahne
	if(extension_loaded('gd') && function_exists('imageCreateFromJpeg'))
852 1352 Luisehahne
	{
853
		// First figure out the size of the thumbnail
854
		list($original_x, $original_y) = getimagesize($source);
855 1495 DarkViper
		if ($original_x > $original_y) {
856 1352 Luisehahne
			$thumb_w = $size;
857
			$thumb_h = $original_y*($size/$original_x);
858
		}
859 1495 DarkViper
		if ($original_x < $original_y) {
860 1352 Luisehahne
			$thumb_w = $original_x*($size/$original_y);
861
			$thumb_h = $size;
862
		}
863 1495 DarkViper
		if ($original_x == $original_y) {
864 1352 Luisehahne
			$thumb_w = $size;
865 1495 DarkViper
			$thumb_h = $size;
866 1352 Luisehahne
		}
867
		// Now make the thumbnail
868
		$source = imageCreateFromJpeg($source);
869
		$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
870
		imagecopyresampled($dst_img,$source,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);
871
		imagejpeg($dst_img, $destination);
872
		// Clear memory
873
		imagedestroy($dst_img);
874
		imagedestroy($source);
875
	   // Return true
876
		return true;
877
	} else {
878
		return false;
879
	}
880
}
881
882
/*
883
 * Function to work-out a single part of an octal permission value
884
 *
885
 * @param mixed $octal_value: an octal value as string (i.e. '0777') or real octal integer (i.e. 0777 | 777)
886
 * @param string $who: char or string for whom the permission is asked( U[ser] / G[roup] / O[thers] )
887
 * @param string $action: char or string with the requested action( r[ead..] / w[rite..] / e|x[ecute..] )
888
 * @return boolean
889
 */
890
function extract_permission($octal_value, $who, $action)
891
{
892
	// Make sure that all arguments are set and $octal_value is a real octal-integer
893 1495 DarkViper
	if(($who == '') || ($action == '') || (preg_match( '/[^0-7]/', (string)$octal_value ))) {
894 1352 Luisehahne
		return false; // invalid argument, so return false
895
	}
896
	// convert $octal_value into a decimal-integer to be sure having a valid value
897
	$right_mask = octdec($octal_value);
898
	$action_mask = 0;
899
	// set the $action related bit in $action_mask
900 1495 DarkViper
	switch($action[0]) { // get action from first char of $action
901 1352 Luisehahne
		case 'r':
902
		case 'R':
903
			$action_mask = 4; // set read-bit only (2^2)
904
			break;
905
		case 'w':
906
		case 'W':
907
			$action_mask = 2; // set write-bit only (2^1)
908
			break;
909
		case 'e':
910
		case 'E':
911
		case 'x':
912
		case 'X':
913
			$action_mask = 1; // set execute-bit only (2^0)
914
			break;
915
		default:
916
			return false; // undefined action name, so return false
917
	}
918
	// shift action-mask into the right position
919 1495 DarkViper
	switch($who[0]) { // get who from first char of $who
920 1352 Luisehahne
		case 'u':
921
		case 'U':
922
			$action_mask <<= 3; // shift left 3 bits
923
		case 'g':
924
		case 'G':
925
			$action_mask <<= 3; // shift left 3 bits
926
		case 'o':
927
		case 'O':
928
			/* NOP */
929
			break;
930
		default:
931
			return false; // undefined who, so return false
932
	}
933
	return( ($right_mask & $action_mask) != 0 ); // return result of binary-AND
934
}
935
936
// Function to delete a page
937 1365 Luisehahne
	function delete_page($page_id)
938 1352 Luisehahne
	{
939 1365 Luisehahne
		global $admin, $database, $MESSAGE;
940
		// Find out more about the page
941 1495 DarkViper
		$sql  = 'SELECT `page_id`, `menu_title`, `page_title`, `level`, ';
942
		$sql .=        '`link`, `parent`, `modified_by`, `modified_when` ';
943
		$sql .= 'FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
944 1365 Luisehahne
		$results = $database->query($sql);
945
		if($database->is_error())    { $admin->print_error($database->get_error()); }
946
		if($results->numRows() == 0) { $admin->print_error($MESSAGE['PAGES']['NOT_FOUND']); }
947
		$results_array = $results->fetchRow();
948
		$parent     = $results_array['parent'];
949
		$level      = $results_array['level'];
950
		$link       = $results_array['link'];
951
		$page_title = $results_array['page_title'];
952
		$menu_title = $results_array['menu_title'];
953
		// Get the sections that belong to the page
954 1495 DarkViper
		$sql  = 'SELECT `section_id`, `module` FROM `'.TABLE_PREFIX.'sections` ';
955
		$sql .= 'WHERE `page_id`='.$page_id;
956 1365 Luisehahne
		$query_sections = $database->query($sql);
957
		if($query_sections->numRows() > 0)
958 1352 Luisehahne
		{
959 1495 DarkViper
			while($section = $query_sections->fetchRow()) {
960 1365 Luisehahne
				// Set section id
961
				$section_id = $section['section_id'];
962
				// Include the modules delete file if it exists
963 1495 DarkViper
				if(file_exists(WB_PATH.'/modules/'.$section['module'].'/delete.php')) {
964 1365 Luisehahne
					include(WB_PATH.'/modules/'.$section['module'].'/delete.php');
965
				}
966 1352 Luisehahne
			}
967
		}
968 1365 Luisehahne
		// Update the pages table
969 1495 DarkViper
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
970 1365 Luisehahne
		$database->query($sql);
971 1495 DarkViper
		if($database->is_error()) {
972 1365 Luisehahne
			$admin->print_error($database->get_error());
973
		}
974
		// Update the sections table
975 1495 DarkViper
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'sections` WHERE `page_id`='.$page_id;
976 1365 Luisehahne
		$database->query($sql);
977
		if($database->is_error()) {
978
			$admin->print_error($database->get_error());
979
		}
980
		// Include the ordering class or clean-up ordering
981
		include_once(WB_PATH.'/framework/class.order.php');
982
		$order = new order(TABLE_PREFIX.'pages', 'position', 'page_id', 'parent');
983
		$order->clean($parent);
984
		// Unlink the page access file and directory
985
		$directory = WB_PATH.PAGES_DIRECTORY.$link;
986
		$filename = $directory.PAGE_EXTENSION;
987
		$directory .= '/';
988
		if(file_exists($filename))
989
		{
990 1495 DarkViper
			if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/')) {
991 1365 Luisehahne
				$admin->print_error($MESSAGE['PAGES']['CANNOT_DELETE_ACCESS_FILE']);
992 1495 DarkViper
			}else {
993 1365 Luisehahne
				unlink($filename);
994
				if( file_exists($directory) &&
995
				   (rtrim($directory,'/') != WB_PATH.PAGES_DIRECTORY) &&
996
				   (substr($link, 0, 1) != '.'))
997
				{
998
					rm_full_dir($directory);
999
				}
1000
			}
1001
		}
1002 1352 Luisehahne
	}
1003 1365 Luisehahne
1004
/*
1005
 * @param string $file: name of the file to read
1006
 * @param int $size: number of maximum bytes to read (0 = complete file)
1007
 * @return string: the content as string, false on error
1008
 */
1009
	function getFilePart($file, $size = 0)
1010 1352 Luisehahne
	{
1011 1365 Luisehahne
		$file_content = '';
1012
		if( file_exists($file) && is_file($file) && is_readable($file))
1013 1352 Luisehahne
		{
1014 1495 DarkViper
			if($size == 0) {
1015 1365 Luisehahne
				$size = filesize($file);
1016
			}
1017 1495 DarkViper
			if(($fh = fopen($file, 'rb'))) {
1018
				if( ($file_content = fread($fh, $size)) !== false ) {
1019 1365 Luisehahne
					return $file_content;
1020
				}
1021
				fclose($fh);
1022
			}
1023 1352 Luisehahne
		}
1024 1365 Luisehahne
		return false;
1025
	}
1026
1027
	/**
1028
	* replace varnames with values in a string
1029
	*
1030
	* @param string $subject: stringvariable with vars placeholder
1031
	* @param array $replace: values to replace vars placeholder
1032
	* @return string
1033
	*/
1034
    function replace_vars($subject = '', &$replace = null )
1035
    {
1036
		if(is_array($replace))
1037 1352 Luisehahne
		{
1038 1495 DarkViper
			foreach ($replace  as $key => $value) {
1039 1365 Luisehahne
				$subject = str_replace("{{".$key."}}", $value, $subject);
1040 1352 Luisehahne
			}
1041
		}
1042 1365 Luisehahne
		return $subject;
1043
    }
1044 1352 Luisehahne
1045
// Load module into DB
1046
function load_module($directory, $install = false)
1047
{
1048
	global $database,$admin,$MESSAGE;
1049 1365 Luisehahne
	$retVal = false;
1050
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1051 1352 Luisehahne
	{
1052
		require($directory.'/info.php');
1053
		if(isset($module_name))
1054
		{
1055 1365 Luisehahne
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1056
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1057
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1058 1352 Luisehahne
			$module_function = strtolower($module_function);
1059
			// Check that it doesn't already exist
1060 1365 Luisehahne
			$sqlwhere = 'WHERE `type` = \'module\' AND `directory` = \''.$module_directory.'\'';
1061
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1062 1495 DarkViper
			if( $database->get_one($sql) ) {
1063 1365 Luisehahne
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1064
			}else{
1065 1352 Luisehahne
				// Load into DB
1066
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1067 1365 Luisehahne
				$sqlwhere = '';
1068
			}
1069 1495 DarkViper
			$sql .= '`directory`=\''.$module_directory.'\', ';
1070
			$sql .= '`name`=\''.$module_name.'\', ';
1071
			$sql .= '`description`=\''.addslashes($module_description).'\', ';
1072
			$sql .= '`type`=\'module\', ';
1073
			$sql .= '`function`=\''.$module_function.'\', ';
1074
			$sql .= '`version`=\''.$module_version.'\', ';
1075
			$sql .= '`platform`=\''.$module_platform.'\', ';
1076
			$sql .= '`author`=\''.addslashes($module_author).'\', ';
1077
			$sql .= '`license`=\''.addslashes($module_license).'\'';
1078 1365 Luisehahne
			$sql .= $sqlwhere;
1079
			$retVal = $database->query($sql);
1080
			// Run installation script
1081 1495 DarkViper
			if($install == true) {
1082
				if(file_exists($directory.'/install.php')) {
1083 1365 Luisehahne
					require($directory.'/install.php');
1084 1352 Luisehahne
				}
1085
			}
1086
		}
1087
	}
1088
}
1089
1090
// Load template into DB
1091
function load_template($directory)
1092
{
1093
	global $database, $admin;
1094 1365 Luisehahne
	$retVal = false;
1095
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1096 1352 Luisehahne
	{
1097
		require($directory.'/info.php');
1098
		if(isset($template_name))
1099
		{
1100 1495 DarkViper
			if(!isset($template_license)) {
1101 1352 Luisehahne
              $template_license = 'GNU General Public License';
1102
            }
1103 1495 DarkViper
			if(!isset($template_platform) && isset($template_designed_for)) {
1104 1352 Luisehahne
              $template_platform = $template_designed_for;
1105
            }
1106 1495 DarkViper
			if(!isset($template_function)) {
1107 1352 Luisehahne
              $template_function = 'template';
1108
            }
1109
			// Check that it doesn't already exist
1110 1495 DarkViper
			$sqlwhere = 'WHERE `type`=\'template\' AND `directory`=\''.$template_directory.'\'';
1111 1365 Luisehahne
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1112 1495 DarkViper
			if( $database->get_one($sql) ) {
1113 1365 Luisehahne
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1114
			}else{
1115 1352 Luisehahne
				// Load into DB
1116
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1117 1365 Luisehahne
				$sqlwhere = '';
1118 1352 Luisehahne
			}
1119 1495 DarkViper
			$sql .= '`directory`=\''.$template_directory.'\', ';
1120
			$sql .= '`name`=\''.$template_name.'\', ';
1121
			$sql .= '`description`=\''.addslashes($template_description).'\', ';
1122
			$sql .= '`type`=\'template\', ';
1123
			$sql .= '`function`=\''.$template_function.'\', ';
1124
			$sql .= '`version`=\''.$template_version.'\', ';
1125
			$sql .= '`platform`=\''.$template_platform.'\', ';
1126
			$sql .= '`author`=\''.addslashes($template_author).'\', ';
1127
			$sql .= '`license`=\''.addslashes($template_license).'\' ';
1128 1365 Luisehahne
			$sql .= $sqlwhere;
1129
			$retVal = $database->query($sql);
1130 1352 Luisehahne
		}
1131
	}
1132 1365 Luisehahne
	return $retVal;
1133 1352 Luisehahne
}
1134
1135
// Load language into DB
1136
function load_language($file)
1137
{
1138
	global $database,$admin;
1139 1365 Luisehahne
	$retVal = false;
1140 1352 Luisehahne
	if (file_exists($file) && preg_match('#^([A-Z]{2}.php)#', basename($file)))
1141
	{
1142 1365 Luisehahne
		// require($file);  it's to large
1143
		// read contents of the template language file into string
1144
		$data = @file_get_contents(WB_PATH.'/languages/'.str_replace('.php','',basename($file)).'.php');
1145
		// use regular expressions to fetch the content of the variable from the string
1146 1435 Luisehahne
		$language_name = get_variable_content('language_name', $data, false, false);
1147
		$language_code = get_variable_content('language_code', $data, false, false);
1148
		$language_author = get_variable_content('language_author', $data, false, false);
1149
		$language_version = get_variable_content('language_version', $data, false, false);
1150
		$language_platform = get_variable_content('language_platform', $data, false, false);
1151 1365 Luisehahne
1152 1352 Luisehahne
		if(isset($language_name))
1153
		{
1154 1365 Luisehahne
			if(!isset($language_license)) { $language_license = 'GNU General Public License'; }
1155
			if(!isset($language_platform) && isset($language_designed_for)) { $language_platform = $language_designed_for; }
1156 1352 Luisehahne
			// Check that it doesn't already exist
1157 1495 DarkViper
			$sqlwhere = 'WHERE `type`=\'language\' AND `directory`=\''.$language_code.'\'';
1158 1365 Luisehahne
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1159 1495 DarkViper
			if( $database->get_one($sql) ) {
1160 1365 Luisehahne
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1161
			}else{
1162 1352 Luisehahne
				// Load into DB
1163
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1164 1365 Luisehahne
				$sqlwhere = '';
1165 1352 Luisehahne
			}
1166 1495 DarkViper
			$sql .= '`directory`=\''.$language_code.'\', ';
1167
			$sql .= '`name`=\''.$language_name.'\', ';
1168 1747 Luisehahne
            $sql .= '`description`=\'\', ';
1169
			$sql .= '`function`=\'\', ';
1170 1495 DarkViper
			$sql .= '`type`=\'language\', ';
1171
			$sql .= '`version`=\''.$language_version.'\', ';
1172
			$sql .= '`platform`=\''.$language_platform.'\', ';
1173
			$sql .= '`author`=\''.addslashes($language_author).'\', ';
1174
			$sql .= '`license`=\''.addslashes($language_license).'\' ';
1175 1365 Luisehahne
			$sql .= $sqlwhere;
1176
			$retVal = $database->query($sql);
1177 1352 Luisehahne
		}
1178
	}
1179 1365 Luisehahne
	return $retVal;
1180 1352 Luisehahne
}
1181
1182
// Upgrade module info in DB, optionally start upgrade script
1183
function upgrade_module($directory, $upgrade = false)
1184
{
1185
	global $database, $admin, $MESSAGE, $new_module_version;
1186
	$mod_directory = WB_PATH.'/modules/'.$directory;
1187
	if(file_exists($mod_directory.'/info.php'))
1188
	{
1189
		require($mod_directory.'/info.php');
1190
		if(isset($module_name))
1191
		{
1192 1365 Luisehahne
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1193 1352 Luisehahne
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1194 1365 Luisehahne
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1195 1352 Luisehahne
			$module_function = strtolower($module_function);
1196
			// Check that it does already exist
1197
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` ';
1198 1495 DarkViper
			$sql .= 'WHERE `directory`=\''.$module_directory.'\'';
1199 1352 Luisehahne
			if( $database->get_one($sql) )
1200
			{
1201
				// Update in DB
1202
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1203 1495 DarkViper
				$sql .= '`version`=\''.$module_version.'\', ';
1204
				$sql .= '`description`=\''.addslashes($module_description).'\', ';
1205
				$sql .= '`platform`=\''.$module_platform.'\', ';
1206
				$sql .= '`author`=\''.addslashes($module_author).'\', ';
1207
				$sql .= '`license`=\''.addslashes($module_license).'\' ';
1208
				$sql .= 'WHERE `directory`=\''.$module_directory.'\' ';
1209 1352 Luisehahne
				$database->query($sql);
1210
				if($database->is_error()) {
1211
					$admin->print_error($database->get_error());
1212
				}
1213
				// Run upgrade script
1214 1495 DarkViper
				if($upgrade == true) {
1215
					if(file_exists($mod_directory.'/upgrade.php')) {
1216 1352 Luisehahne
						require($mod_directory.'/upgrade.php');
1217
					}
1218
				}
1219
			}
1220
		}
1221
	}
1222
}
1223
1224
// extracts the content of a string variable from a string (save alternative to including files)
1225
if(!function_exists('get_variable_content'))
1226
{
1227
	function get_variable_content($search, $data, $striptags=true, $convert_to_entities=true)
1228
	{
1229
		$match = '';
1230
		// search for $variable followed by 0-n whitespace then by = then by 0-n whitespace
1231
		// then either " or ' then 0-n characters then either " or ' followed by 0-n whitespace and ;
1232
		// the variable name is returned in $match[1], the content in $match[3]
1233
		if (preg_match('/(\$' .$search .')\s*=\s*("|\')(.*)\2\s*;/', $data, $match))
1234
		{
1235 1495 DarkViper
			if(strip_tags(trim($match[1])) == '$' .$search) {
1236 1352 Luisehahne
				// variable name matches, return it's value
1237
				$match[3] = ($striptags == true) ? strip_tags($match[3]) : $match[3];
1238
				$match[3] = ($convert_to_entities == true) ? htmlentities($match[3]) : $match[3];
1239
				return $match[3];
1240
			}
1241
		}
1242
		return false;
1243
	}
1244
}
1245
1246 1365 Luisehahne
/*
1247
 * @param string $modulname: like saved in addons.directory
1248
 * @param boolean $source: true reads from database, false from info.php
1249
 * @return string:  the version as string, if not found returns null
1250
 */
1251
1252
	function get_modul_version($modulname, $source = true)
1253
	{
1254
		global $database;
1255
		$version = null;
1256
		if( $source != true )
1257
		{
1258 1495 DarkViper
			$sql  = 'SELECT `version` FROM `'.TABLE_PREFIX.'addons` ';
1259
			$sql .= 'WHERE `directory`=\''.$modulname.'\'';
1260 1365 Luisehahne
			$version = $database->get_one($sql);
1261
		} else {
1262
			$info_file = WB_PATH.'/modules/'.$modulname.'/info.php';
1263 1495 DarkViper
			if(file_exists($info_file)) {
1264
				if(($info_file = file_get_contents($info_file))) {
1265 1365 Luisehahne
					$version = get_variable_content('module_version', $info_file, false, false);
1266
					$version = ($version !== false) ? $version : null;
1267
				}
1268
			}
1269
		}
1270
		return $version;
1271
	}
1272
1273
/*
1274
 * @param string $varlist: commaseperated list of varnames to move into global space
1275
 * @return bool:  false if one of the vars already exists in global space (error added to msgQueue)
1276
 */
1277
	function vars2globals_wrapper($varlist)
1278
	{
1279
		$retval = true;
1280
		if( $varlist != '')
1281
		{
1282
			$vars = explode(',', $varlist);
1283
			foreach( $vars as $var)
1284
			{
1285 1495 DarkViper
				if( isset($GLOBALS[$var]) ){
1286 1365 Luisehahne
					ErrorLog::write( 'variabe $'.$var.' already defined in global space!!',__FILE__, __FUNCTION__, __LINE__);
1287
					$retval = false;
1288 1495 DarkViper
				}else {
1289 1365 Luisehahne
					global $$var;
1290
				}
1291
			}
1292
		}
1293
		return $retval;
1294
	}
1295
1296 1400 FrankH
/*
1297
 * filter directory traversal more thoroughly, thanks to hal 9000
1298
 * @param string $dir: directory relative to MEDIA_DIRECTORY
1299
 * @param bool $with_media_dir: true when to include MEDIA_DIRECTORY
1300
 * @return: false if directory traversal detected, real path if not
1301
 */
1302
	function check_media_path($directory, $with_media_dir = true)
1303
	{
1304 1495 DarkViper
		$md = ($with_media_dir) ? MEDIA_DIRECTORY : '';
1305 1400 FrankH
		$dir = realpath(WB_PATH . $md . '/' . utf8_decode($directory));
1306
		$required = realpath(WB_PATH . MEDIA_DIRECTORY);
1307
		if (strstr($dir, $required)) {
1308
			return $dir;
1309
		} else {
1310
			return false;
1311
		}
1312
	}
1313 1475 Luisehahne
1314
/*
1315
urlencode function and rawurlencode are mostly based on RFC 1738.
1316
However, since 2005 the current RFC in use for URIs standard is RFC 3986.
1317
Here is a function to encode URLs according to RFC 3986.
1318
*/
1319
if(!function_exists('url_encode')){
1320
	function url_encode($string) {
1321
	    $string = html_entity_decode($string,ENT_QUOTES,'UTF-8');
1322 1477 Luisehahne
	    $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
1323
	    $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
1324
	    return str_replace($entities,$replacements, rawurlencode($string));
1325 1475 Luisehahne
	}
1326 1705 Luisehahne
}