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 1747 2012-09-09 17:01:33Z Luisehahne $
13
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
14
 * @lastmodified    $Date: 2012-09-09 19:01:33 +0200 (Sun, 09 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
	$query_page = $database->query($sql);
482
	$fetch_page = $query_page->fetchRow();
483
	$parent = $fetch_page['parent'];
484
	$level = $fetch_page['level'];
485
	if($level == 1) {
486
		return $parent;
487
	}elseif($parent == 0) {
488
		return $page_id;
489
	}else {	// Figure out what the root parents id is
490
		$parent_ids = array_reverse(get_parent_ids($page_id));
491
		return $parent_ids[0];
492
	}
493
}
494

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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