Project

General

Profile

1
<?php
2
/**
3
 *
4
 * @category        frontend
5
 * @package         framework
6
 * @author          WebsiteBaker Project
7
 * @copyright       2004-2009, Ryan Djurovich
8
 * @copyright       2009-2011, Website Baker Org. e.V.
9
 * @link			http://www.websitebaker2.org/
10
 * @license         http://www.gnu.org/licenses/gpl.html
11
 * @platform        WebsiteBaker 2.8.x
12
 * @requirements    PHP 5.2.2 and higher
13
 * @version         $Id: functions.php 1495 2011-08-11 15:53:59Z DarkViper $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
15
 * @lastmodified    $Date: 2011-08-11 17:53:59 +0200 (Thu, 11 Aug 2011) $
16
 *
17
*/
18

    
19
// Must include code to stop this file being access directly
20
if(defined('WB_PATH') == false) { die("Cannot access this file directly"); }
21

    
22
// Define that this file has been loaded
23
define('FUNCTIONS_FILE_LOADED', true);
24

    
25
/**
26
 * @description: recursively delete a non empty directory
27
 * @param string $directory :
28
 * @param bool $empty : true if you want the folder just emptied, but not deleted
29
 *                      false, or just simply leave it out, the given directory will be deleted, as well
30
 * @return boolean: list of ro-dirs
31
 * @from http://www.php.net/manual/de/function.rmdir.php#98499
32
 */
33
function rm_full_dir($directory, $empty = false) {
34
    
35
	if(substr($directory,-1) == "/") {
36
        $directory = substr($directory,0,-1);
37
    }
38
    // If suplied dirname is a file then unlink it
39
    if (is_file( $directory )) {
40
        return unlink($directory);
41
    }
42
    if(!file_exists($directory) || !is_dir($directory)) {
43
        return false;
44
    } elseif(!is_readable($directory)) {
45
        return false;
46
    } else {
47
        $directoryHandle = opendir($directory);
48
        while ($contents = readdir($directoryHandle))
49
		{
50
            if($contents != '.' && $contents != '..')
51
			{
52
                $path = $directory . "/" . $contents;
53
                if(is_dir($path)) {
54
                    rm_full_dir($path);
55
                } else {
56
                    unlink($path);
57
                }
58
            }
59
        }
60
        closedir($directoryHandle);
61
        if($empty == false) {
62
            if(!rmdir($directory)) {
63
                return false;
64
            }
65
        }
66
        return true;
67
    }
68
}
69

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

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

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

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

    
203
    // make the list nice. Not all OS do this itself
204
	if(natcasesort($result_list)) {
205
		$result_list = array_merge($result_list);
206
	}
207
	return $result_list;
208
}
209

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

    
266
/*
267
 * @param object &$wb: $wb from frontend or $admin from backend
268
 * @return array: list of new entries
269
 * @description: callback remove path in files/dirs stored in array
270
 * @example: array_walk($array,'remove_path',PATH);
271
 */
272
//
273
function remove_path(&$path, $key, $vars = '')
274
{
275
	$path = str_replace($vars, '', $path);
276
}
277

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

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

    
379
	$tmp_array = $full_list;
380
	// create a list for readwrite dir
381
	while( sizeof($tmp_array) > 0)
382
	{
383
        $tmp = array_shift($tmp_array);
384
        $x = 0;
385
		while($x < sizeof($allow_list)) {
386
			if(strpos ($tmp,$allow_list[$x])) {
387
				$array[] = $tmp;
388
			}
389
			$x++;
390
		}
391
	}
392
	$tmp = array();
393
    $array = array_unique($array);
394
	$full_list = array_merge($tmp,$array);
395
    unset($array);
396
    unset($allow_list);
397
	return $full_list;
398
}
399

    
400
// Function to create directories
401
function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE)
402
{
403
	if(!is_dir($dir_name))
404
    {
405
		$umask = umask(0);
406
		mkdir($dir_name, $dir_mode);
407
		umask($umask);
408
		return true;
409
	} else {
410
		return false;
411
	}
412
}
413

    
414
// Function to chmod files and directories
415
function change_mode($name)
416
{
417
	if(OPERATING_SYSTEM != 'windows')
418
    {
419
		// Only chmod if os is not windows
420
		if(is_dir($name)) {
421
			$mode = OCTAL_DIR_MODE;
422
		}else {
423
			$mode = OCTAL_FILE_MODE;
424
		}
425
		if(file_exists($name)) {
426
			$umask = umask(0);
427
			chmod($name, $mode);
428
			umask($umask);
429
			return true;
430
		}else {
431
			return false;
432
		}
433
	}else {
434
		return true;
435
	}
436
}
437

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

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

    
470
// Function to work out root parent
471
function root_parent($page_id)
472
{
473
	global $database;
474
	// Get page details
475
	$sql = 'SELECT `parent`, `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
476
	$query_page = $database->query($sql);
477
	$fetch_page = $query_page->fetchRow();
478
	$parent = $fetch_page['parent'];
479
	$level = $fetch_page['level'];
480
	if($level == 1) {
481
		return $parent;
482
	}elseif($parent == 0) {
483
		return $page_id;
484
	}else {	// Figure out what the root parents id is
485
		$parent_ids = array_reverse(get_parent_ids($page_id));
486
		return $parent_ids[0];
487
	}
488
}
489

    
490
// Function to get page title
491
function get_page_title($id)
492
{
493
	global $database;
494
	// Get title
495
	$sql = 'SELECT `page_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
496
	$page_title = $database->get_one($sql);
497
	return $page_title;
498
}
499

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

    
510
// Function to get all parent page titles
511
function get_parent_titles($parent_id)
512
{
513
	$titles[] = get_menu_title($parent_id);
514
	if(is_parent($parent_id) != false) {
515
		$parent_titles = get_parent_titles(is_parent($parent_id));
516
		$titles = array_merge($titles, $parent_titles);
517
	}
518
	return $titles;
519
}
520

    
521
// Function to get all parent page id's
522
function get_parent_ids($parent_id)
523
{
524
	$ids[] = $parent_id;
525
	if(is_parent($parent_id) != false) {
526
		$parent_ids = get_parent_ids(is_parent($parent_id));
527
		$ids = array_merge($ids, $parent_ids);
528
	}
529
	return $ids;
530
}
531

    
532
// Function to genereate page trail
533
function get_page_trail($page_id)
534
{
535
	return implode(',', array_reverse(get_parent_ids($page_id)));
536
}
537

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

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

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

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

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

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

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

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

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

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

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

    
681
		// write content into file
682
		if(is_writable($filename)) {
683
		    if(file_put_contents($filename, $content)) {
684
				print 'create => '.str_replace( $wb_path,'',$filename).'<br />';
685
		        change_mode($filename, 'file');
686
		    }
687
		}
688
	} else {
689
			$retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'];
690
	}
691
	return $retVal;
692
}
693

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

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

    
755
	if( ($handle = fopen($filename, 'w')) ) {
756
		fwrite($handle, $content);
757
		fclose($handle);
758
		// Chmod the file
759
		change_mode($filename);
760
	} else {
761
		$admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE']);
762
	}
763
	return;
764
 }
765

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

    
783
            // images
784
            'png'	=> 'image/png',
785
            'jpe'	=> 'image/jpeg',
786
            'jpeg'	=> 'image/jpeg',
787
            'jpg'	=> 'image/jpeg',
788
            'gif'	=> 'image/gif',
789
            'bmp'	=> 'image/bmp',
790
            'ico'	=> 'image/vnd.microsoft.icon',
791
            'tiff'	=> 'image/tiff',
792
            'tif'	=> 'image/tiff',
793
            'svg'	=> 'image/svg+xml',
794
            'svgz'	=> 'image/svg+xml',
795

    
796
            // archives
797
            'zip'	=> 'application/zip',
798
            'rar'	=> 'application/x-rar-compressed',
799
            'exe'	=> 'application/x-msdownload',
800
            'msi'	=> 'application/x-msdownload',
801
            'cab'	=> 'application/vnd.ms-cab-compressed',
802

    
803
            // audio/video
804
            'mp3'	=> 'audio/mpeg',
805
            'mp4'	=> 'audio/mpeg',
806
            'qt'	=> 'video/quicktime',
807
            'mov'	=> 'video/quicktime',
808

    
809
            // adobe
810
            'pdf'	=> 'application/pdf',
811
            'psd'	=> 'image/vnd.adobe.photoshop',
812
            'ai'	=> 'application/postscript',
813
            'eps'	=> 'application/postscript',
814
            'ps'	=> 'application/postscript',
815

    
816
            // ms office
817
            'doc'	=> 'application/msword',
818
            'rtf'	=> 'application/rtf',
819
            'xls'	=> 'application/vnd.ms-excel',
820
            'ppt'	=> 'application/vnd.ms-powerpoint',
821

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

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

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

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

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

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

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

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

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

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

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

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

    
1238
/*
1239
 * @param string $modulname: like saved in addons.directory
1240
 * @param boolean $source: true reads from database, false from info.php
1241
 * @return string:  the version as string, if not found returns null
1242
 */
1243

    
1244
	function get_modul_version($modulname, $source = true)
1245
	{
1246
		global $database;
1247
		$version = null;
1248
		if( $source != true )
1249
		{
1250
			$sql  = 'SELECT `version` FROM `'.TABLE_PREFIX.'addons` ';
1251
			$sql .= 'WHERE `directory`=\''.$modulname.'\'';
1252
			$version = $database->get_one($sql);
1253
		} else {
1254
			$info_file = WB_PATH.'/modules/'.$modulname.'/info.php';
1255
			if(file_exists($info_file)) {
1256
				if(($info_file = file_get_contents($info_file))) {
1257
					$version = get_variable_content('module_version', $info_file, false, false);
1258
					$version = ($version !== false) ? $version : null;
1259
				}
1260
			}
1261
		}
1262
		return $version;
1263
	}
1264

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

    
1288
/*
1289
 * filter directory traversal more thoroughly, thanks to hal 9000
1290
 * @param string $dir: directory relative to MEDIA_DIRECTORY
1291
 * @param bool $with_media_dir: true when to include MEDIA_DIRECTORY
1292
 * @return: false if directory traversal detected, real path if not
1293
 */
1294
	function check_media_path($directory, $with_media_dir = true)
1295
	{
1296
		$md = ($with_media_dir) ? MEDIA_DIRECTORY : '';
1297
		$dir = realpath(WB_PATH . $md . '/' . utf8_decode($directory));
1298
		$required = realpath(WB_PATH . MEDIA_DIRECTORY);
1299
		if (strstr($dir, $required)) {
1300
			return $dir;
1301
		} else {
1302
			return false;
1303
		}
1304
	}
1305

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