Project

General

Profile

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