Project

General

Profile

1
<?php
2
/**
3
 *
4
 * @category        frontend
5
 * @package         framework
6
 * @author          Ryan Djurovich,WebsiteBaker Project
7
 * @copyright       2009-2012, WebsiteBaker Org. e.V.
8
 * @link			http://www.websitebaker2.org/
9
 * @license         http://www.gnu.org/licenses/gpl.html
10
 * @platform        WebsiteBaker 2.8.x
11
 * @requirements    PHP 5.2.2 and higher
12
 * @version         $Id: functions.php 1754 2012-09-15 16:00:56Z Luisehahne $
13
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
14
 * @lastmodified    $Date: 2012-09-15 18:00:56 +0200 (Sat, 15 Sep 2012) $
15
 *
16
*/
17
/* -------------------------------------------------------- */
18
// Must include code to stop this file being accessed directly
19
if(!defined('WB_PATH')) {
20
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
21
	throw new IllegalFileException();
22
}
23
/* -------------------------------------------------------- */
24
// Define that this file has been loaded
25
define('FUNCTIONS_FILE_LOADED', true);
26

    
27
/**
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: true/false
33
 * @from http://www.php.net/manual/de/function.rmdir.php#98499
34
 */
35
function rm_full_dir($directory, $empty = false)
36
{
37
	if(substr($directory,-1) == "/") {
38
        $directory = substr($directory,0,-1);
39
    }
40
   // If suplied dirname is a file then unlink it
41
    if (is_file( $directory )&& is_writable( $directory )) {
42
	  $retval = unlink($directory);
43
	  clearstatcache();
44
      return $retval;
45
    }
46
    if(!is_writable($directory) || !is_dir($directory)) {
47
        return false;
48
    } elseif(!is_readable($directory)) {
49
        return false;
50
    } else {
51
        $directoryHandle = opendir($directory);
52
        while ($contents = readdir($directoryHandle))
53
		{
54
            if($contents != '.' && $contents != '..')
55
			{
56
                $path = $directory . "/" . $contents;
57
                if(is_dir($path)) {
58
                    rm_full_dir($path);
59
                } else {
60
                    unlink($path);
61
					clearstatcache();
62
                }
63
            }
64
        }
65
        closedir($directoryHandle);
66
        if($empty == false) {
67
            if(is_dir($directory) && is_writable(dirname($directory))) {
68
                return rmdir($directory);
69
            } else {
70
				return false;
71
            }
72
        }
73
        return true;
74
    }
75
}
76

    
77
/*
78
 * returns a recursive list of all subdirectories from a given directory
79
 * @access  public
80
 * @param   string  $directory: from this dir the recursion will start
81
 * @param   bool    $show_hidden:  if set to TRUE also hidden dirs (.dir) will be shown
82
 * @return  array
83
 * example:
84
 *  /srv/www/httpdocs/wb/media/a/b/c/
85
 *  /srv/www/httpdocs/wb/media/a/b/d/
86
 * directory_list('/srv/www/httpdocs/wb/media/') will return:
87
 *  /a
88
 *  /a/b
89
 *  /a/b/c
90
 *  /a/b/d
91
 */
92
 function directory_list($directory, $show_hidden = false)
93
{
94
	$result_list = array();
95
	if (is_dir($directory))
96
    {
97
    	$dir = dir($directory); // Open the directory
98
    	while (false !== $entry = $dir->read()) // loop through the directory
99
		{
100
			if($entry == '.' || $entry == '..') { continue; } // Skip pointers
101
			if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
102
    		if (is_dir("$directory/$entry")) { // Add dir and contents to list
103
    			$result_list = array_merge($result_list, directory_list("$directory/$entry"));
104
    			$result_list[] = "$directory/$entry";
105
    		}
106
    	}
107
        $dir->close();
108
    }
109
	// sorting
110
	if(natcasesort($result_list)) {
111
		// new indexing
112
		$result_list = array_merge($result_list);
113
	}
114
	return $result_list; // Now return the list
115
}
116

    
117
// Function to open a directory and add to a dir list
118
function chmod_directory_contents($directory, $file_mode)
119
{
120
	if (is_dir($directory))
121
    {
122
    	// Set the umask to 0
123
    	$umask = umask(0);
124
    	// Open the directory then loop through its contents
125
    	$dir = dir($directory);
126
    	while (false !== $entry = $dir->read())
127
		{
128
    		// Skip pointers
129
    		if($entry[0] == '.') { continue; }
130
    		// Chmod the sub-dirs contents
131
    		if(is_dir("$directory/$entry")) {
132
    			chmod_directory_contents($directory.'/'.$entry, $file_mode);
133
    		}
134
    		change_mode($directory.'/'.$entry);
135
    	}
136
        $dir->close();
137
    	// Restore the umask
138
    	umask($umask);
139
    }
140
}
141

    
142
/**
143
* Scan a given directory for dirs and files.
144
*
145
* usage: scan_current_dir ($root = '' )
146
*
147
* @param     $root   set a absolute rootpath as string. if root is empty the current path will be scan
148
* @param     $search set a search pattern for files, empty search brings all files
149
* @access    public
150
* @return    array    returns a natsort array with keys 'path' and 'filename'
151
*
152
*/
153
if(!function_exists('scan_current_dir'))
154
{
155
	function scan_current_dir($root = '', $search = '/.*/')
156
	{
157
	    $FILE = array();
158
		$array = array();
159
	    clearstatcache();
160
	    $root = empty ($root) ? getcwd() : $root;
161
	    if (($handle = opendir($root)))
162
	    {
163
	    // Loop through the files and dirs an add to list  DIRECTORY_SEPARATOR
164
	        while (false !== ($file = readdir($handle)))
165
	        {
166
	            if (substr($file, 0, 1) != '.' && $file != 'index.php')
167
	            {
168
	                if (is_dir($root.'/'.$file)) {
169
	                    $FILE['path'][] = $file;
170
	                } elseif (preg_match($search, $file, $array) ) {
171
	                    $FILE['filename'][] = $array[0];
172
	                }
173
	            }
174
	        }
175
	        $close_verz = closedir($handle);
176
	    }
177
		// sorting
178
	    if (isset ($FILE['path']) && natcasesort($FILE['path'])) {
179
			// new indexing
180
	        $FILE['path'] = array_merge($FILE['path']);
181
	    }
182
		// sorting
183
	    if (isset ($FILE['filename']) && natcasesort($FILE['filename'])) {
184
			// new indexing
185
	        $FILE['filename'] = array_merge($FILE['filename']);
186
	    }
187
	    return $FILE;
188
	}
189
}
190

    
191
// Function to open a directory and add to a file list
192
function file_list($directory, $skip = array(), $show_hidden = false)
193
{
194
	$result_list = array();
195
	if (is_dir($directory))
196
    {
197
    	$dir = dir($directory); // Open the directory
198
		while (false !== ($entry = $dir->read())) // loop through the directory
199
		{
200
			if($entry == '.' || $entry == '..') { continue; } // Skip pointers
201
			if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
202
			if( sizeof($skip) > 0 && in_array($entry, $skip) ) { continue; } // Check if we to skip anything else
203
			if(is_file( $directory.'/'.$entry)) { // Add files to list
204
				$result_list[] = $directory.'/'.$entry;
205
			}
206
		}
207
		$dir->close(); // Now close the folder object
208
	}
209

    
210
    // make the list nice. Not all OS do this itself
211
	if(natcasesort($result_list)) {
212
		$result_list = array_merge($result_list);
213
	}
214
	return $result_list;
215
}
216

    
217
// Function to get a list of home folders not to show
218
function get_home_folders()
219
{
220
	global $database, $admin;
221
	$home_folders = array();
222
	// Only return home folders is this feature is enabled
223
	// and user is not admin
224
//	if(HOME_FOLDERS AND ($_SESSION['GROUP_ID']!='1')) {
225
	if(HOME_FOLDERS AND (!in_array('1',explode(',', $_SESSION['GROUPS_ID']))))
226
	{
227
		$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
228
		$sql .= 'WHERE `home_folder`!=\''.$admin->get_home_folder().'\'';
229
		$query_home_folders = $database->query($sql);
230
		if($query_home_folders->numRows() > 0)
231
		{
232
			while($folder = $query_home_folders->fetchRow()) {
233
				$home_folders[$folder['home_folder']] = $folder['home_folder'];
234
			}
235
		}
236
		function remove_home_subs($directory = '/', $home_folders = '')
237
		{
238
			if( ($handle = opendir(WB_PATH.MEDIA_DIRECTORY.$directory)) )
239
			{
240
				// Loop through the dirs to check the home folders sub-dirs are not shown
241
				while(false !== ($file = readdir($handle)))
242
				{
243
					if($file[0] != '.' && $file != 'index.php')
244
					{
245
						if(is_dir(WB_PATH.MEDIA_DIRECTORY.$directory.'/'.$file))
246
						{
247
							if($directory != '/') {
248
								$file = $directory.'/'.$file;
249
							}else {
250
								$file = '/'.$file;
251
							}
252
							foreach($home_folders AS $hf)
253
							{
254
								$hf_length = strlen($hf);
255
								if($hf_length > 0) {
256
									if(substr($file, 0, $hf_length+1) == $hf) {
257
										$home_folders[$file] = $file;
258
									}
259
								}
260
							}
261
							$home_folders = remove_home_subs($file, $home_folders);
262
						}
263
					}
264
				}
265
			}
266
			return $home_folders;
267
		}
268
		$home_folders = remove_home_subs('/', $home_folders);
269
	}
270
	return $home_folders;
271
}
272

    
273
/*
274
 * @param object &$wb: $wb from frontend or $admin from backend
275
 * @return array: list of new entries
276
 * @description: callback remove path in files/dirs stored in array
277
 * @example: array_walk($array,'remove_path',PATH);
278
 */
279
//
280
function remove_path(&$path, $key, $vars = '')
281
{
282
	$path = str_replace($vars, '', $path);
283
}
284

    
285
/*
286
 * @param object &$wb: $wb from frontend or $admin from backend
287
 * @return array: list of ro-dirs
288
 * @description: returns a list of directories beyound /wb/media which are ReadOnly for current user
289
 */
290
function media_dirs_ro( &$wb )
291
{
292
	global $database;
293
	// if user is admin or home-folders not activated then there are no restrictions
294
	$allow_list = array();
295
	if( $wb->get_user_id() == 1 || !HOME_FOLDERS ) {
296
		return array();
297
	}
298
	// at first read any dir and subdir from /media
299
	$full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
300
	// add own home_folder to allow-list
301
	if( $wb->get_home_folder() ) {
302
		// old: $allow_list[] = get_home_folder();
303
		$allow_list[] = $wb->get_home_folder();
304
	}
305
	// get groups of current user
306
	$curr_groups = $wb->get_groups_id();
307
	// if current user is in admin-group
308
	if( ($admin_key = array_search('1', $curr_groups)) !== false)
309
	{
310
		// remove admin-group from list
311
		unset($curr_groups[$admin_key]);
312
		// search for all users where the current user is admin from
313
		foreach( $curr_groups as $group)
314
		{
315
			$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
316
			$sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
317
			if( ($res_hf = $database->query($sql)) != null ) {
318
				while( $rec_hf = $res_hf->fetchrow() ) {
319
					$allow_list[] = $rec_hf['home_folder'];
320
				}
321
			}
322
		}
323
	}
324
	$tmp_array = $full_list;
325
	// create a list for readonly dir
326
    $array = array();
327
	while( sizeof($tmp_array) > 0)
328
	{
329
        $tmp = array_shift($tmp_array);
330
        $x = 0;
331
		while($x < sizeof($allow_list)) {
332
			if(strpos ($tmp,$allow_list[$x])) {
333
				$array[] = $tmp;
334
			}
335
			$x++;
336
		}
337
	}
338
	$full_list = array_diff( $full_list, $array );
339
	$tmp = array();
340
	$full_list = array_merge($tmp,$full_list);
341
	return $full_list;
342
}
343

    
344
/*
345
 * @param object &$wb: $wb from frontend or $admin from backend
346
 * @return array: list of rw-dirs
347
 * @description: returns a list of directories beyound /wb/media which are ReadWrite for current user
348
 */
349
function media_dirs_rw ( &$wb )
350
{
351
	global $database;
352
	// if user is admin or home-folders not activated then there are no restrictions
353
	// at first read any dir and subdir from /media
354
	$full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
355
    $array = array();
356
	$allow_list = array();
357
	if( ($wb->ami_group_member('1')) && !HOME_FOLDERS ) {
358
		return $full_list;
359
	}
360
	// add own home_folder to allow-list
361
	if( $wb->get_home_folder() ) {
362
	  	$allow_list[] = $wb->get_home_folder();
363
	} else {
364
		$array = $full_list;
365
	}
366
	// get groups of current user
367
	$curr_groups = $wb->get_groups_id();
368
	// if current user is in admin-group
369
	if( ($admin_key = array_search('1', $curr_groups)) == true)
370
	{
371
		// remove admin-group from list
372
		// unset($curr_groups[$admin_key]);
373
		// search for all users where the current user is admin from
374
		foreach( $curr_groups as $group)
375
		{
376
			$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
377
			$sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
378
			if( ($res_hf = $database->query($sql)) != null ) {
379
				while( $rec_hf = $res_hf->fetchrow() ) {
380
					$allow_list[] = $rec_hf['home_folder'];
381
				}
382
			}
383
		}
384
	}
385

    
386
	$tmp_array = $full_list;
387
	// create a list for readwrite dir
388
	while( sizeof($tmp_array) > 0)
389
	{
390
        $tmp = array_shift($tmp_array);
391
        $x = 0;
392
		while($x < sizeof($allow_list)) {
393
			if(strpos ($tmp,$allow_list[$x])) {
394
				$array[] = $tmp;
395
			}
396
			$x++;
397
		}
398
	}
399
	$tmp = array();
400
    $array = array_unique($array);
401
	$full_list = array_merge($tmp,$array);
402
    unset($array);
403
    unset($allow_list);
404
	return $full_list;
405
}
406

    
407
// Function to create directories
408
function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE, $recursive=true)
409
{
410
	$retVal = false;
411
	if(!is_dir($dir_name))
412
    {
413
		$retVal = mkdir($dir_name, $dir_mode,$recursive);
414
	}
415
	return $retVal;
416
}
417

    
418
/**
419
 * Function to chmod files and/or directories
420
 * the function also prevents the owner to loose rw-rights
421
 * @param string $sName
422
 * @param int rights in dec-value. 0= use wb-defaults
423
 * @return bool
424
 */
425
function change_mode($sName, $iMode = 0)
426
{
427
	$bRetval = true;
428
	$iMode = intval($iMode) & 0777; // sanitize value
429
	if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
430
	{ // Only chmod if os is not windows
431
		$bRetval = false;
432
		if(!$iMode) {
433
			$iMode = (is_file($sName) ? octdec(STRING_FILE_MODE) : octdec(STRING_DIR_MODE));
434
		}
435
		$iMode |= 0600; // set o+rw
436
		if(is_writable($sName)) {
437
			$bRetval = chmod($sName, $iMode);
438
		}
439
	}
440
	return $bRetval;
441
}
442

    
443
// Function to figure out if a parent exists
444
function is_parent($page_id)
445
{
446
	global $database;
447
	// Get parent
448
	$sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
449
	$parent = $database->get_one($sql);
450
	// If parent isnt 0 return its ID
451
	if(is_null($parent)) {
452
		return false;
453
	}else {
454
		return $parent;
455
	}
456
}
457

    
458
// Function to work out level
459
function level_count($page_id)
460
{
461
	global $database;
462
	// Get page parent
463
	$sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
464
	$parent = $database->get_one($sql);
465
	if($parent > 0)
466
	{	// Get the level of the parent
467
		$sql = 'SELECT `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$parent;
468
		$level = $database->get_one($sql);
469
		return $level+1;
470
	}else {
471
		return 0;
472
	}
473
}
474

    
475
// Function to work out root parent
476
function root_parent($page_id)
477
{
478
	global $database;
479
	// Get page details
480
	$sql = 'SELECT `parent`, `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
481

    
482
	$query_page = $database->query($sql);
483
	$fetch_page = $query_page->fetchRow();
484
	$parent = $fetch_page['parent'];
485
	$level = $fetch_page['level'];
486
	if($level == 1) {
487
		return $parent;
488
	} elseif($parent == 0) {
489
		return $page_id;
490
	} else {	// Figure out what the root parents id is
491
		$parent_ids = array_reverse(get_parent_ids($page_id));
492
		return $parent_ids[0];
493
	}
494
}
495

    
496
// Function to get page title
497
function get_page_title($id)
498
{
499
	global $database;
500
	// Get title
501
	$sql = 'SELECT `page_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
502
	$page_title = $database->get_one($sql);
503
	return $page_title;
504
}
505

    
506
// Function to get a pages menu title
507
function get_menu_title($id)
508
{
509
	global $database;
510
	// Get title
511
	$sql = 'SELECT `menu_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
512
	$menu_title = $database->get_one($sql);
513
	return $menu_title;
514
}
515

    
516
// Function to get all parent page titles
517
function get_parent_titles($parent_id)
518
{
519
	$titles[] = get_menu_title($parent_id);
520
	if(is_parent($parent_id) != false) {
521
		$parent_titles = get_parent_titles(is_parent($parent_id));
522
		$titles = array_merge($titles, $parent_titles);
523
	}
524
	return $titles;
525
}
526

    
527
// Function to get all parent page id's
528
function get_parent_ids($parent_id)
529
{
530
	$ids[] = $parent_id;
531
	if(is_parent($parent_id) != false) {
532
		$parent_ids = get_parent_ids(is_parent($parent_id));
533
		$ids = array_merge($ids, $parent_ids);
534
	}
535
	return $ids;
536
}
537

    
538
// Function to genereate page trail
539
function get_page_trail($page_id)
540
{
541
	return implode(',', array_reverse(get_parent_ids($page_id)));
542
}
543

    
544
// Function to get all sub pages id's
545
function get_subs($parent, array $subs )
546
{
547
	// Connect to the database
548
	global $database;
549
	// Get id's
550
	$sql = 'SELECT `page_id` FROM `'.TABLE_PREFIX.'pages` WHERE `parent` = '.$parent;
551
	if( ($query = $database->query($sql)) ) {
552
		while($fetch = $query->fetchRow()) {
553
			$subs[] = $fetch['page_id'];
554
			// Get subs of this sub recursive
555
			$subs = get_subs($fetch['page_id'], $subs);
556
		}
557
	}
558
	// Return subs array
559
	return $subs;
560
}
561

    
562
// Function as replacement for php's htmlspecialchars()
563
// Will not mangle HTML-entities
564
function my_htmlspecialchars($string)
565
{
566
	$string = preg_replace('/&(?=[#a-z0-9]+;)/i', '__amp;_', $string);
567
	$string = strtr($string, array('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;', '\''=>'&#39;'));
568
	$string = preg_replace('/__amp;_(?=[#a-z0-9]+;)/i', '&', $string);
569
	return($string);
570
}
571

    
572
// Convert a string from mixed html-entities/umlauts to pure $charset_out-umlauts
573
// Will replace all numeric and named entities except &gt; &lt; &apos; &quot; &#039; &nbsp;
574
// In case of error the returned string is unchanged, and a message is emitted.
575
function entities_to_umlauts($string, $charset_out=DEFAULT_CHARSET)
576
{
577
	require_once(WB_PATH.'/framework/functions-utf8.php');
578
	return entities_to_umlauts2($string, $charset_out);
579
}
580

    
581
// Will convert a string in $charset_in encoding to a pure ASCII string with HTML-entities.
582
// In case of error the returned string is unchanged, and a message is emitted.
583
function umlauts_to_entities($string, $charset_in=DEFAULT_CHARSET)
584
{
585
	require_once(WB_PATH.'/framework/functions-utf8.php');
586
	return umlauts_to_entities2($string, $charset_in);
587
}
588

    
589
// Function to convert a page title to a page filename
590
function page_filename($string)
591
{
592
	require_once(WB_PATH.'/framework/functions-utf8.php');
593
	$string = entities_to_7bit($string);
594
	// Now remove all bad characters
595
	$bad = array(
596
	'\'', /* /  */ '"', /* " */	'<', /* < */	'>', /* > */
597
	'{', /* { */	'}', /* } */	'[', /* [ */	']', /* ] */	'`', /* ` */
598
	'!', /* ! */	'@', /* @ */	'#', /* # */	'$', /* $ */	'%', /* % */
599
	'^', /* ^ */	'&', /* & */	'*', /* * */	'(', /* ( */	')', /* ) */
600
	'=', /* = */	'+', /* + */	'|', /* | */	'/', /* / */	'\\', /* \ */
601
	';', /* ; */	':', /* : */	',', /* , */	'?' /* ? */
602
	);
603
	$string = str_replace($bad, '', $string);
604
	// replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
605
	$string = preg_replace(array('/\.+/', '/\.+$/'), array('.', ''), $string);
606
	// Now replace spaces with page spcacer
607
	$string = trim($string);
608
	$string = preg_replace('/(\s)+/', PAGE_SPACER, $string);
609
	// Now convert to lower-case
610
	$string = strtolower($string);
611
	// If there are any weird language characters, this will protect us against possible problems they could cause
612
	$string = str_replace(array('%2F', '%'), array('/', ''), urlencode($string));
613
	// Finally, return the cleaned string
614
	return $string;
615
}
616

    
617
// Function to convert a desired media filename to a clean mediafilename
618
function media_filename($string)
619
{
620
	require_once(WB_PATH.'/framework/functions-utf8.php');
621
	$string = entities_to_7bit($string);
622
	// Now remove all bad characters
623
	$bad = array('\'','"','`','!','@','#','$','%','^','&','*','=','+','|','/','\\',';',':',',','?');
624
	$string = str_replace($bad, '', $string);
625
	// replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
626
	$string = preg_replace(array('/\.+/', '/\.+$/', '/\s/'), array('.', '', '_'), $string);
627
	// Clean any page spacers at the end of string
628
	$string = trim($string);
629
	// Finally, return the cleaned string
630
	return $string;
631
}
632

    
633
// Function to work out a page link
634
if(!function_exists('page_link'))
635
{
636
	function page_link($link)
637
	{
638
		global $admin;
639
		return $admin->page_link($link);
640
	}
641
}
642

    
643
// Create a new directory and/or protected file in the given directory
644
function createFolderProtectFile($sAbsDir='',$make_dir=true)
645
{
646
	global $admin, $MESSAGE;
647
	$retVal = array();
648
	$wb_path = rtrim(str_replace('\/\\', '/', WB_PATH), '/');
649
    if( ($sAbsDir=='') || ($sAbsDir == $wb_path) ) { return $retVal;}
650

    
651
	if ( $make_dir==true ) {
652
		// Check to see if the folder already exists
653
		if(file_exists($sAbsDir)) {
654
			// $admin->print_error($MESSAGE['MEDIA_DIR_EXISTS']);
655
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_EXISTS'];
656
		}
657
		if (!is_dir($sAbsDir) && !make_dir($sAbsDir) ) {
658
			// $admin->print_error($MESSAGE['MEDIA_DIR_NOT_MADE']);
659
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_NOT_MADE'];
660
		} else {
661
			change_mode($sAbsDir);
662
		}
663
	}
664

    
665
	if( is_writable($sAbsDir) )
666
	{
667
        // if(file_exists($sAbsDir.'/index.php')) { unlink($sAbsDir.'/index.php'); }
668
	    // Create default "index.php" file
669
		$rel_pages_dir = str_replace($wb_path, '', dirname($sAbsDir) );
670
		$step_back = str_repeat( '../', substr_count($rel_pages_dir, '/')+1 );
671

    
672
		$sResponse  = $_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently';
673
		$content =
674
			'<?php'."\n".
675
			'// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
676
			'// *** Creation date: '.date('c')."\n".
677
			'// *** Do not modify this file manually'."\n".
678
			'// *** WB will rebuild this file from time to time!!'."\n".
679
			'// *************************************************'."\n".
680
			"\t".'header(\''.$sResponse.'\');'."\n".
681
			"\t".'header(\'Location: '.WB_URL.'/index.php\');'."\n".
682
			'// *************************************************'."\n";
683
		$filename = $sAbsDir.'/index.php';
684

    
685
		// write content into file
686
		  if(is_writable($filename) || !file_exists($filename)) {
687
		      if(file_put_contents($filename, $content)) {
688
		//    print 'create => '.str_replace( $wb_path,'',$filename).'<br />';
689
		          change_mode($filename, 'file');
690
		      }else {
691
		    $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'].' :: '.$filename;
692
		   }
693
		  }
694
		 } else {
695
		   $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'];
696
		 }
697
		 return $retVal;
698
}
699

    
700
function rebuildFolderProtectFile($dir='')
701
{
702
	global $MESSAGE;
703
	$retVal = array();
704
	$dir = rtrim(str_replace('\/\\', '/', $dir), '/');
705
	try {
706
		$files = array();
707
		$files[] = $dir;
708
		foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $fileInfo) {
709
			$files[] = $fileInfo->getPath();
710
		}
711
		$files = array_unique($files);
712
		foreach( $files as $file) {
713
			$protect_file = rtrim(str_replace('\/\\', '/', $file), '/');
714
			$retVal[] = createFolderProtectFile($protect_file,false);
715
		}
716
	} catch ( Exception $e ) {
717
		$retVal[] = $MESSAGE['MEDIA_DIR_ACCESS_DENIED'];
718
	}
719
	return $retVal;
720
}
721

    
722
// Create a new file in the pages directory
723
function create_access_file($filename,$page_id,$level)
724
{
725
	global $admin, $MESSAGE;
726
	// First make sure parent folder exists
727
	$parent_folders = explode('/',str_replace(WB_PATH.PAGES_DIRECTORY, '', dirname($filename)));
728
	$parents = '';
729
	foreach($parent_folders AS $parent_folder)
730
	{
731
		if($parent_folder != '/' AND $parent_folder != '')
732
		{
733
			$parents .= '/'.$parent_folder;
734
			$acces_file = WB_PATH.PAGES_DIRECTORY.$parents;
735
			// can only be dirs
736
			if(!file_exists($acces_file)) {
737
				if(!make_dir($acces_file)) {
738
					$admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE_FOLDER']);
739
				}
740
			}
741
		}
742
	}
743
	// The depth of the page directory in the directory hierarchy
744
	// '/pages' is at depth 1
745
	$pages_dir_depth = count(explode('/',PAGES_DIRECTORY))-1;
746
	// Work-out how many ../'s we need to get to the index page
747
	$index_location = '';
748
	for($i = 0; $i < $level + $pages_dir_depth; $i++) {
749
		$index_location .= '../';
750
	}
751
	$content =
752
		'<?php'."\n".
753
		'// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
754
		'// *** Creation date: '.date('c')."\n".
755
		'// *** Do not modify this file manually'."\n".
756
		'// *** WB will rebuild this file from time to time!!'."\n".
757
		'// *************************************************'."\n".
758
		"\t".'$page_id    = '.$page_id.';'."\n".
759
		"\t".'require(\''.$index_location.'index.php\');'."\n".
760
		'// *************************************************'."\n";
761

    
762
	if( ($handle = fopen($filename, 'w')) ) {
763
		fwrite($handle, $content);
764
		fclose($handle);
765
		// Chmod the file
766
		change_mode($filename);
767
	} else {
768
		$admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE']);
769
	}
770
	return;
771
 }
772

    
773
// Function for working out a file mime type (if the in-built PHP one is not enabled)
774
if(!function_exists('mime_content_type'))
775
{
776
    function mime_content_type($filename)
777
	{
778
	    $mime_types = array(
779
            'txt'	=> 'text/plain',
780
            'htm'	=> 'text/html',
781
            'html'	=> 'text/html',
782
            'php'	=> 'text/html',
783
            'css'	=> 'text/css',
784
            'js'	=> 'application/javascript',
785
            'json'	=> 'application/json',
786
            'xml'	=> 'application/xml',
787
            'swf'	=> 'application/x-shockwave-flash',
788
            'flv'	=> 'video/x-flv',
789

    
790
            // images
791
            'png'	=> 'image/png',
792
            'jpe'	=> 'image/jpeg',
793
            'jpeg'	=> 'image/jpeg',
794
            'jpg'	=> 'image/jpeg',
795
            'gif'	=> 'image/gif',
796
            'bmp'	=> 'image/bmp',
797
            'ico'	=> 'image/vnd.microsoft.icon',
798
            'tiff'	=> 'image/tiff',
799
            'tif'	=> 'image/tiff',
800
            'svg'	=> 'image/svg+xml',
801
            'svgz'	=> 'image/svg+xml',
802

    
803
            // archives
804
            'zip'	=> 'application/zip',
805
            'rar'	=> 'application/x-rar-compressed',
806
            'exe'	=> 'application/x-msdownload',
807
            'msi'	=> 'application/x-msdownload',
808
            'cab'	=> 'application/vnd.ms-cab-compressed',
809

    
810
            // audio/video
811
            'mp3'	=> 'audio/mpeg',
812
            'mp4'	=> 'audio/mpeg',
813
            'qt'	=> 'video/quicktime',
814
            'mov'	=> 'video/quicktime',
815

    
816
            // adobe
817
            'pdf'	=> 'application/pdf',
818
            'psd'	=> 'image/vnd.adobe.photoshop',
819
            'ai'	=> 'application/postscript',
820
            'eps'	=> 'application/postscript',
821
            'ps'	=> 'application/postscript',
822

    
823
            // ms office
824
            'doc'	=> 'application/msword',
825
            'rtf'	=> 'application/rtf',
826
            'xls'	=> 'application/vnd.ms-excel',
827
            'ppt'	=> 'application/vnd.ms-powerpoint',
828

    
829
            // open office
830
            'odt'	=> 'application/vnd.oasis.opendocument.text',
831
            'ods'	=> 'application/vnd.oasis.opendocument.spreadsheet',
832
        );
833
        $temp = explode('.',$filename);
834
        $ext = strtolower(array_pop($temp));
835
        if (array_key_exists($ext, $mime_types)) {
836
            return $mime_types[$ext];
837
        }elseif (function_exists('finfo_open')) {
838
            $finfo = finfo_open(FILEINFO_MIME);
839
            $mimetype = finfo_file($finfo, $filename);
840
            finfo_close($finfo);
841
            return $mimetype;
842
        }else {
843
            return 'application/octet-stream';
844
        }
845
    }
846
}
847

    
848
// Generate a thumbnail from an image
849
function make_thumb($source, $destination, $size)
850
{
851
	// Check if GD is installed
852
	if(extension_loaded('gd') && function_exists('imageCreateFromJpeg'))
853
	{
854
		// First figure out the size of the thumbnail
855
		list($original_x, $original_y) = getimagesize($source);
856
		if ($original_x > $original_y) {
857
			$thumb_w = $size;
858
			$thumb_h = $original_y*($size/$original_x);
859
		}
860
		if ($original_x < $original_y) {
861
			$thumb_w = $original_x*($size/$original_y);
862
			$thumb_h = $size;
863
		}
864
		if ($original_x == $original_y) {
865
			$thumb_w = $size;
866
			$thumb_h = $size;
867
		}
868
		// Now make the thumbnail
869
		$source = imageCreateFromJpeg($source);
870
		$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
871
		imagecopyresampled($dst_img,$source,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);
872
		imagejpeg($dst_img, $destination);
873
		// Clear memory
874
		imagedestroy($dst_img);
875
		imagedestroy($source);
876
	   // Return true
877
		return true;
878
	} else {
879
		return false;
880
	}
881
}
882

    
883
/*
884
 * Function to work-out a single part of an octal permission value
885
 *
886
 * @param mixed $octal_value: an octal value as string (i.e. '0777') or real octal integer (i.e. 0777 | 777)
887
 * @param string $who: char or string for whom the permission is asked( U[ser] / G[roup] / O[thers] )
888
 * @param string $action: char or string with the requested action( r[ead..] / w[rite..] / e|x[ecute..] )
889
 * @return boolean
890
 */
891
function extract_permission($octal_value, $who, $action)
892
{
893
	// Make sure that all arguments are set and $octal_value is a real octal-integer
894
	if(($who == '') || ($action == '') || (preg_match( '/[^0-7]/', (string)$octal_value ))) {
895
		return false; // invalid argument, so return false
896
	}
897
	// convert $octal_value into a decimal-integer to be sure having a valid value
898
	$right_mask = octdec($octal_value);
899
	$action_mask = 0;
900
	// set the $action related bit in $action_mask
901
	switch($action[0]) { // get action from first char of $action
902
		case 'r':
903
		case 'R':
904
			$action_mask = 4; // set read-bit only (2^2)
905
			break;
906
		case 'w':
907
		case 'W':
908
			$action_mask = 2; // set write-bit only (2^1)
909
			break;
910
		case 'e':
911
		case 'E':
912
		case 'x':
913
		case 'X':
914
			$action_mask = 1; // set execute-bit only (2^0)
915
			break;
916
		default:
917
			return false; // undefined action name, so return false
918
	}
919
	// shift action-mask into the right position
920
	switch($who[0]) { // get who from first char of $who
921
		case 'u':
922
		case 'U':
923
			$action_mask <<= 3; // shift left 3 bits
924
		case 'g':
925
		case 'G':
926
			$action_mask <<= 3; // shift left 3 bits
927
		case 'o':
928
		case 'O':
929
			/* NOP */
930
			break;
931
		default:
932
			return false; // undefined who, so return false
933
	}
934
	return( ($right_mask & $action_mask) != 0 ); // return result of binary-AND
935
}
936

    
937
// Function to delete a page
938
	function delete_page($page_id)
939
	{
940
		global $admin, $database, $MESSAGE;
941
		// Find out more about the page
942
		$sql  = 'SELECT `page_id`, `menu_title`, `page_title`, `level`, ';
943
		$sql .=        '`link`, `parent`, `modified_by`, `modified_when` ';
944
		$sql .= 'FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
945
		$results = $database->query($sql);
946
		if($database->is_error())    { $admin->print_error($database->get_error()); }
947
		if($results->numRows() == 0) { $admin->print_error($MESSAGE['PAGES']['NOT_FOUND']); }
948
		$results_array = $results->fetchRow();
949
		$parent     = $results_array['parent'];
950
		$level      = $results_array['level'];
951
		$link       = $results_array['link'];
952
		$page_title = $results_array['page_title'];
953
		$menu_title = $results_array['menu_title'];
954
		// Get the sections that belong to the page
955
		$sql  = 'SELECT `section_id`, `module` FROM `'.TABLE_PREFIX.'sections` ';
956
		$sql .= 'WHERE `page_id`='.$page_id;
957
		$query_sections = $database->query($sql);
958
		if($query_sections->numRows() > 0)
959
		{
960
			while($section = $query_sections->fetchRow()) {
961
				// Set section id
962
				$section_id = $section['section_id'];
963
				// Include the modules delete file if it exists
964
				if(file_exists(WB_PATH.'/modules/'.$section['module'].'/delete.php')) {
965
					include(WB_PATH.'/modules/'.$section['module'].'/delete.php');
966
				}
967
			}
968
		}
969
		// Update the pages table
970
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
971
		$database->query($sql);
972
		if($database->is_error()) {
973
			$admin->print_error($database->get_error());
974
		}
975
		// Update the sections table
976
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'sections` WHERE `page_id`='.$page_id;
977
		$database->query($sql);
978
		if($database->is_error()) {
979
			$admin->print_error($database->get_error());
980
		}
981
		// Include the ordering class or clean-up ordering
982
		include_once(WB_PATH.'/framework/class.order.php');
983
		$order = new order(TABLE_PREFIX.'pages', 'position', 'page_id', 'parent');
984
		$order->clean($parent);
985
		// Unlink the page access file and directory
986
		$directory = WB_PATH.PAGES_DIRECTORY.$link;
987
		$filename = $directory.PAGE_EXTENSION;
988
		$directory .= '/';
989
		if(file_exists($filename))
990
		{
991
			if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/')) {
992
				$admin->print_error($MESSAGE['PAGES']['CANNOT_DELETE_ACCESS_FILE']);
993
			}else {
994
				unlink($filename);
995
				if( file_exists($directory) &&
996
				   (rtrim($directory,'/') != WB_PATH.PAGES_DIRECTORY) &&
997
				   (substr($link, 0, 1) != '.'))
998
				{
999
					rm_full_dir($directory);
1000
				}
1001
			}
1002
		}
1003
	}
1004

    
1005
/*
1006
 * @param string $file: name of the file to read
1007
 * @param int $size: number of maximum bytes to read (0 = complete file)
1008
 * @return string: the content as string, false on error
1009
 */
1010
	function getFilePart($file, $size = 0)
1011
	{
1012
		$file_content = '';
1013
		if( file_exists($file) && is_file($file) && is_readable($file))
1014
		{
1015
			if($size == 0) {
1016
				$size = filesize($file);
1017
			}
1018
			if(($fh = fopen($file, 'rb'))) {
1019
				if( ($file_content = fread($fh, $size)) !== false ) {
1020
					return $file_content;
1021
				}
1022
				fclose($fh);
1023
			}
1024
		}
1025
		return false;
1026
	}
1027

    
1028
	/**
1029
	* replace varnames with values in a string
1030
	*
1031
	* @param string $subject: stringvariable with vars placeholder
1032
	* @param array $replace: values to replace vars placeholder
1033
	* @return string
1034
	*/
1035
    function replace_vars($subject = '', &$replace = null )
1036
    {
1037
		if(is_array($replace))
1038
		{
1039
			foreach ($replace  as $key => $value) {
1040
				$subject = str_replace("{{".$key."}}", $value, $subject);
1041
			}
1042
		}
1043
		return $subject;
1044
    }
1045

    
1046
// Load module into DB
1047
function load_module($directory, $install = false)
1048
{
1049
	global $database,$admin,$MESSAGE;
1050
	$retVal = false;
1051
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1052
	{
1053
		require($directory.'/info.php');
1054
		if(isset($module_name))
1055
		{
1056
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1057
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1058
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1059
			$module_function = strtolower($module_function);
1060
			// Check that it doesn't already exist
1061
			$sqlwhere = 'WHERE `type` = \'module\' AND `directory` = \''.$module_directory.'\'';
1062
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1063
			if( $database->get_one($sql) ) {
1064
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1065
			}else{
1066
				// Load into DB
1067
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1068
				$sqlwhere = '';
1069
			}
1070
			$sql .= '`directory`=\''.$module_directory.'\', ';
1071
			$sql .= '`name`=\''.$module_name.'\', ';
1072
			$sql .= '`description`=\''.addslashes($module_description).'\', ';
1073
			$sql .= '`type`=\'module\', ';
1074
			$sql .= '`function`=\''.$module_function.'\', ';
1075
			$sql .= '`version`=\''.$module_version.'\', ';
1076
			$sql .= '`platform`=\''.$module_platform.'\', ';
1077
			$sql .= '`author`=\''.addslashes($module_author).'\', ';
1078
			$sql .= '`license`=\''.addslashes($module_license).'\'';
1079
			$sql .= $sqlwhere;
1080
			$retVal = $database->query($sql);
1081
			// Run installation script
1082
			if($install == true) {
1083
				if(file_exists($directory.'/install.php')) {
1084
					require($directory.'/install.php');
1085
				}
1086
			}
1087
		}
1088
	}
1089
}
1090

    
1091
// Load template into DB
1092
function load_template($directory)
1093
{
1094
	global $database, $admin;
1095
	$retVal = false;
1096
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1097
	{
1098
		require($directory.'/info.php');
1099
		if(isset($template_name))
1100
		{
1101
			if(!isset($template_license)) {
1102
              $template_license = 'GNU General Public License';
1103
            }
1104
			if(!isset($template_platform) && isset($template_designed_for)) {
1105
              $template_platform = $template_designed_for;
1106
            }
1107
			if(!isset($template_function)) {
1108
              $template_function = 'template';
1109
            }
1110
			// Check that it doesn't already exist
1111
			$sqlwhere = 'WHERE `type`=\'template\' AND `directory`=\''.$template_directory.'\'';
1112
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1113
			if( $database->get_one($sql) ) {
1114
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1115
			}else{
1116
				// Load into DB
1117
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1118
				$sqlwhere = '';
1119
			}
1120
			$sql .= '`directory`=\''.$template_directory.'\', ';
1121
			$sql .= '`name`=\''.$template_name.'\', ';
1122
			$sql .= '`description`=\''.addslashes($template_description).'\', ';
1123
			$sql .= '`type`=\'template\', ';
1124
			$sql .= '`function`=\''.$template_function.'\', ';
1125
			$sql .= '`version`=\''.$template_version.'\', ';
1126
			$sql .= '`platform`=\''.$template_platform.'\', ';
1127
			$sql .= '`author`=\''.addslashes($template_author).'\', ';
1128
			$sql .= '`license`=\''.addslashes($template_license).'\' ';
1129
			$sql .= $sqlwhere;
1130
			$retVal = $database->query($sql);
1131
		}
1132
	}
1133
	return $retVal;
1134
}
1135

    
1136
// Load language into DB
1137
function load_language($file)
1138
{
1139
	global $database,$admin;
1140
	$retVal = false;
1141
	if (file_exists($file) && preg_match('#^([A-Z]{2}.php)#', basename($file)))
1142
	{
1143
		// require($file);  it's to large
1144
		// read contents of the template language file into string
1145
		$data = @file_get_contents(WB_PATH.'/languages/'.str_replace('.php','',basename($file)).'.php');
1146
		// use regular expressions to fetch the content of the variable from the string
1147
		$language_name = get_variable_content('language_name', $data, false, false);
1148
		$language_code = get_variable_content('language_code', $data, false, false);
1149
		$language_author = get_variable_content('language_author', $data, false, false);
1150
		$language_version = get_variable_content('language_version', $data, false, false);
1151
		$language_platform = get_variable_content('language_platform', $data, false, false);
1152

    
1153
		if(isset($language_name))
1154
		{
1155
			if(!isset($language_license)) { $language_license = 'GNU General Public License'; }
1156
			if(!isset($language_platform) && isset($language_designed_for)) { $language_platform = $language_designed_for; }
1157
			// Check that it doesn't already exist
1158
			$sqlwhere = 'WHERE `type`=\'language\' AND `directory`=\''.$language_code.'\'';
1159
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1160
			if( $database->get_one($sql) ) {
1161
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1162
			}else{
1163
				// Load into DB
1164
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1165
				$sqlwhere = '';
1166
			}
1167
			$sql .= '`directory`=\''.$language_code.'\', ';
1168
			$sql .= '`name`=\''.$language_name.'\', ';
1169
            $sql .= '`description`=\'\', ';
1170
			$sql .= '`function`=\'\', ';
1171
			$sql .= '`type`=\'language\', ';
1172
			$sql .= '`version`=\''.$language_version.'\', ';
1173
			$sql .= '`platform`=\''.$language_platform.'\', ';
1174
			$sql .= '`author`=\''.addslashes($language_author).'\', ';
1175
			$sql .= '`license`=\''.addslashes($language_license).'\' ';
1176
			$sql .= $sqlwhere;
1177
			$retVal = $database->query($sql);
1178
		}
1179
	}
1180
	return $retVal;
1181
}
1182

    
1183
// Upgrade module info in DB, optionally start upgrade script
1184
function upgrade_module($directory, $upgrade = false)
1185
{
1186
	global $database, $admin, $MESSAGE, $new_module_version;
1187
	$mod_directory = WB_PATH.'/modules/'.$directory;
1188
	if(file_exists($mod_directory.'/info.php'))
1189
	{
1190
		require($mod_directory.'/info.php');
1191
		if(isset($module_name))
1192
		{
1193
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1194
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1195
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1196
			$module_function = strtolower($module_function);
1197
			// Check that it does already exist
1198
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` ';
1199
			$sql .= 'WHERE `directory`=\''.$module_directory.'\'';
1200
			if( $database->get_one($sql) )
1201
			{
1202
				// Update in DB
1203
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1204
				$sql .= '`version`=\''.$module_version.'\', ';
1205
				$sql .= '`description`=\''.addslashes($module_description).'\', ';
1206
				$sql .= '`platform`=\''.$module_platform.'\', ';
1207
				$sql .= '`author`=\''.addslashes($module_author).'\', ';
1208
				$sql .= '`license`=\''.addslashes($module_license).'\' ';
1209
				$sql .= 'WHERE `directory`=\''.$module_directory.'\' ';
1210
				$database->query($sql);
1211
				if($database->is_error()) {
1212
					$admin->print_error($database->get_error());
1213
				}
1214
				// Run upgrade script
1215
				if($upgrade == true) {
1216
					if(file_exists($mod_directory.'/upgrade.php')) {
1217
						require($mod_directory.'/upgrade.php');
1218
					}
1219
				}
1220
			}
1221
		}
1222
	}
1223
}
1224

    
1225
// extracts the content of a string variable from a string (save alternative to including files)
1226
if(!function_exists('get_variable_content'))
1227
{
1228
	function get_variable_content($search, $data, $striptags=true, $convert_to_entities=true)
1229
	{
1230
		$match = '';
1231
		// search for $variable followed by 0-n whitespace then by = then by 0-n whitespace
1232
		// then either " or ' then 0-n characters then either " or ' followed by 0-n whitespace and ;
1233
		// the variable name is returned in $match[1], the content in $match[3]
1234
		if (preg_match('/(\$' .$search .')\s*=\s*("|\')(.*)\2\s*;/', $data, $match))
1235
		{
1236
			if(strip_tags(trim($match[1])) == '$' .$search) {
1237
				// variable name matches, return it's value
1238
				$match[3] = ($striptags == true) ? strip_tags($match[3]) : $match[3];
1239
				$match[3] = ($convert_to_entities == true) ? htmlentities($match[3]) : $match[3];
1240
				return $match[3];
1241
			}
1242
		}
1243
		return false;
1244
	}
1245
}
1246

    
1247
/*
1248
 * @param string $modulname: like saved in addons.directory
1249
 * @param boolean $source: true reads from database, false from info.php
1250
 * @return string:  the version as string, if not found returns null
1251
 */
1252

    
1253
	function get_modul_version($modulname, $source = true)
1254
	{
1255
		global $database;
1256
		$version = null;
1257
		if( $source != true )
1258
		{
1259
			$sql  = 'SELECT `version` FROM `'.TABLE_PREFIX.'addons` ';
1260
			$sql .= 'WHERE `directory`=\''.$modulname.'\'';
1261
			$version = $database->get_one($sql);
1262
		} else {
1263
			$info_file = WB_PATH.'/modules/'.$modulname.'/info.php';
1264
			if(file_exists($info_file)) {
1265
				if(($info_file = file_get_contents($info_file))) {
1266
					$version = get_variable_content('module_version', $info_file, false, false);
1267
					$version = ($version !== false) ? $version : null;
1268
				}
1269
			}
1270
		}
1271
		return $version;
1272
	}
1273

    
1274
/*
1275
 * @param string $varlist: commaseperated list of varnames to move into global space
1276
 * @return bool:  false if one of the vars already exists in global space (error added to msgQueue)
1277
 */
1278
	function vars2globals_wrapper($varlist)
1279
	{
1280
		$retval = true;
1281
		if( $varlist != '')
1282
		{
1283
			$vars = explode(',', $varlist);
1284
			foreach( $vars as $var)
1285
			{
1286
				if( isset($GLOBALS[$var]) ){
1287
					ErrorLog::write( 'variabe $'.$var.' already defined in global space!!',__FILE__, __FUNCTION__, __LINE__);
1288
					$retval = false;
1289
				}else {
1290
					global $$var;
1291
				}
1292
			}
1293
		}
1294
		return $retval;
1295
	}
1296

    
1297
/*
1298
 * filter directory traversal more thoroughly, thanks to hal 9000
1299
 * @param string $dir: directory relative to MEDIA_DIRECTORY
1300
 * @param bool $with_media_dir: true when to include MEDIA_DIRECTORY
1301
 * @return: false if directory traversal detected, real path if not
1302
 */
1303
	function check_media_path($directory, $with_media_dir = true)
1304
	{
1305
		$md = ($with_media_dir) ? MEDIA_DIRECTORY : '';
1306
		$dir = realpath(WB_PATH . $md . '/' . utf8_decode($directory));
1307
		$required = realpath(WB_PATH . MEDIA_DIRECTORY);
1308
		if (strstr($dir, $required)) {
1309
			return $dir;
1310
		} else {
1311
			return false;
1312
		}
1313
	}
1314

    
1315
/*
1316
urlencode function and rawurlencode are mostly based on RFC 1738.
1317
However, since 2005 the current RFC in use for URIs standard is RFC 3986.
1318
Here is a function to encode URLs according to RFC 3986.
1319
*/
1320
if(!function_exists('url_encode')){
1321
	function url_encode($string) {
1322
	    $string = html_entity_decode($string,ENT_QUOTES,'UTF-8');
1323
	    $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
1324
	    $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
1325
	    return str_replace($entities,$replacements, rawurlencode($string));
1326
	}
1327
}
(20-20/25)