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 1496 2011-08-11 16:15:31Z DarkViper $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
15
 * @lastmodified    $Date: 2011-08-11 18:15:31 +0200 (Thu, 11 Aug 2011) $
16
 *
17
*/
18

    
19
/* -------------------------------------------------------- */
20
// Must include code to stop this file being accessed directly
21
require_once('globalExceptionHandler.php');
22
if(!defined('WB_PATH')) { throw new IllegalFileException(); }
23
/* -------------------------------------------------------- */
24
// 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: list of ro-dirs
33
 * @from http://www.php.net/manual/de/function.rmdir.php#98499
34
 */
35
function rm_full_dir($directory, $empty = false) {
36
    
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 )) {
42
        return unlink($directory);
43
    }
44
    if(!file_exists($directory) || !is_dir($directory)) {
45
        return false;
46
    } elseif(!is_readable($directory)) {
47
        return false;
48
    } else {
49
        $directoryHandle = opendir($directory);
50
        while ($contents = readdir($directoryHandle))
51
		{
52
            if($contents != '.' && $contents != '..')
53
			{
54
                $path = $directory . "/" . $contents;
55
                if(is_dir($path)) {
56
                    rm_full_dir($path);
57
                } else {
58
                    unlink($path);
59
                }
60
            }
61
        }
62
        closedir($directoryHandle);
63
        if($empty == false) {
64
            if(!rmdir($directory)) {
65
                return false;
66
            }
67
        }
68
        return true;
69
    }
70
}
71

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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