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