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