Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

    
407
// Function to create directories
408
function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE, $recursive=true)
409
{
410
	$retVal = false;
411
	if(!is_dir($dir_name))
412
    {
413
		// To create the folder with 0777 permissions, we need to set umask to zero.
414
		$oldumask = umask(0) ;
415
		$retVal = mkdir($dir_name, $dir_mode,$recursive);
416
		umask( $oldumask ) ;
417
	}
418
	return $retVal;
419
}
420

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

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

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

    
480
// Function to work out root parent
481
function root_parent($page_id)
482
{
483
	global $database;
484
	// Get page details
485
	$sql = 'SELECT `parent`, `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
486

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

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

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

    
521
// Function to get all parent page titles
522
function get_parent_titles($parent_id)
523
{
524
	$titles[] = get_menu_title($parent_id);
525
	if(is_parent($parent_id) != false) {
526
		$parent_titles = get_parent_titles(is_parent($parent_id));
527
		$titles = array_merge($titles, $parent_titles);
528
	}
529
	return $titles;
530
}
531

    
532
// Function to get all parent page id's
533
function get_parent_ids($parent_id)
534
{
535
	$ids[] = $parent_id;
536
	if(is_parent($parent_id) != false) {
537
		$parent_ids = get_parent_ids(is_parent($parent_id));
538
		$ids = array_merge($ids, $parent_ids);
539
	}
540
	return $ids;
541
}
542

    
543
// Function to genereate page trail
544
function get_page_trail($page_id)
545
{
546
	return implode(',', array_reverse(get_parent_ids($page_id)));
547
}
548

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

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

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

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

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

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

    
638
// Function to work out a page link
639
if(!function_exists('page_link'))
640
{
641
	function page_link($link)
642
	{
643
		global $admin;
644
		return $admin->page_link($link);
645
	}
646
}
647

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

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

    
670
	if( is_writable($sAbsDir) )
671
	{
672
        // if(file_exists($sAbsDir.'/index.php')) { unlink($sAbsDir.'/index.php'); }
673
	    // Create default "index.php" file
674
		$rel_pages_dir = str_replace($wb_path, '', dirname($sAbsDir) );
675
		$step_back = str_repeat( '../', substr_count($rel_pages_dir, '/')+1 );
676

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

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

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

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

    
767
	if( ($handle = fopen($filename, 'w')) ) {
768
		fwrite($handle, $content);
769
		fclose($handle);
770
		// Chmod the file
771
		change_mode($filename);
772
	} else {
773
		$admin->print_error($MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE']);
774
	}
775
	return;
776
 }
777

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

    
795
            // images
796
            'png'	=> 'image/png',
797
            'jpe'	=> 'image/jpeg',
798
            'jpeg'	=> 'image/jpeg',
799
            'jpg'	=> 'image/jpeg',
800
            'gif'	=> 'image/gif',
801
            'bmp'	=> 'image/bmp',
802
            'ico'	=> 'image/vnd.microsoft.icon',
803
            'tiff'	=> 'image/tiff',
804
            'tif'	=> 'image/tiff',
805
            'svg'	=> 'image/svg+xml',
806
            'svgz'	=> 'image/svg+xml',
807

    
808
            // archives
809
            'zip'	=> 'application/zip',
810
            'rar'	=> 'application/x-rar-compressed',
811
            'exe'	=> 'application/x-msdownload',
812
            'msi'	=> 'application/x-msdownload',
813
            'cab'	=> 'application/vnd.ms-cab-compressed',
814

    
815
            // audio/video
816
            'mp3'	=> 'audio/mpeg',
817
            'mp4'	=> 'audio/mpeg',
818
            'qt'	=> 'video/quicktime',
819
            'mov'	=> 'video/quicktime',
820

    
821
            // adobe
822
            'pdf'	=> 'application/pdf',
823
            'psd'	=> 'image/vnd.adobe.photoshop',
824
            'ai'	=> 'application/postscript',
825
            'eps'	=> 'application/postscript',
826
            'ps'	=> 'application/postscript',
827

    
828
            // ms office
829
            'doc'	=> 'application/msword',
830
            'rtf'	=> 'application/rtf',
831
            'xls'	=> 'application/vnd.ms-excel',
832
            'ppt'	=> 'application/vnd.ms-powerpoint',
833

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

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

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

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

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

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

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

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

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

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

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

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

    
1252
/*
1253
 * @param string $modulname: like saved in addons.directory
1254
 * @param boolean $source: true reads from database, false from info.php
1255
 * @return string:  the version as string, if not found returns null
1256
 */
1257

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

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

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

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