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