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 1651 2012-03-26 14:18:12Z darkviper $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
15
 * @lastmodified    $Date: 2012-03-26 16:18:12 +0200 (Mon, 26 Mar 2012) $
16
 *
17
*/
18
/* -------------------------------------------------------- */
19
// Must include code to stop this file being accessed directly
20
if(!defined('WB_PATH')) {
21
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
22
	throw new IllegalFileException();
23
}
24
/* -------------------------------------------------------- */
25
// Define that this file has been loaded
26
define('FUNCTIONS_FILE_LOADED', true);
27

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

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

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

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

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

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

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

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

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

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

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

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

    
417
/**
418
 * Function to chmod files and/or directories
419
 * @param string $sName
420
 * @param int rights in dec-value. 0= use wb-defaults
421
 * @return bool
422
 */
423
function change_mode($sName, $iMode = 0)
424
{
425
	$bRetval = true;
426
	if((substr(__FILE__, 0, 1)) == '/')
427
	{ // Only chmod if os is not windows
428
		$bRetval = false;
429
		if(!$iMode) {
430
			$iMode = (is_file($sName) ? octdec(STRING_FILE_MODE) : octdec(STRING_DIR_MODE));
431
		}
432
		if(is_writable($sName)) {
433
			$bRetval = chmod($sName, $iMode);
434
		}
435
	}
436
	return $bRetval;
437
}
438

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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