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 1475 2011-07-12 23:07:10Z Luisehahne $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
15
 * @lastmodified    $Date: 2011-07-13 01:07:10 +0200 (Wed, 13 Jul 2011) $
16
 *
17
*/
18

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

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

    
25
/**
26
 * @description: recursively delete a non empty directory
27
 * @param string $directory :
28
 * @param bool $empty : true if you want the folder just emptied, but not deleted
29
 *                      false, or just simply leave it out, the given directory will be deleted, as well
30
 * @return boolean: list of ro-dirs
31
 * @from http://www.php.net/manual/de/function.rmdir.php#98499
32
 */
33
function rm_full_dir($directory, $empty = false) {
34

    
35
    if(substr($directory,-1) == "/")
36
	{
37
        $directory = substr($directory,0,-1);
38
    }
39

    
40
    // If suplied dirname is a file then unlink it
41
    if (is_file( $directory ))
42
	{
43
        return unlink($directory);
44
    }
45

    
46
    if(!file_exists($directory) || !is_dir($directory))
47
	{
48
        return false;
49
    } elseif(!is_readable($directory))
50
	{
51
        return false;
52
    } else {
53
        $directoryHandle = opendir($directory);
54

    
55
        while ($contents = readdir($directoryHandle))
56
		{
57
            if($contents != '.' && $contents != '..')
58
			{
59
                $path = $directory . "/" . $contents;
60

    
61
                if(is_dir($path))
62
				{
63
                    rm_full_dir($path);
64
                } else {
65
                    unlink($path);
66
                }
67
            }
68
        }
69

    
70
        closedir($directoryHandle);
71

    
72
        if($empty == false)
73
		{
74
            if(!rmdir($directory))
75
			{
76
                return false;
77
            }
78
        }
79

    
80
        return true;
81
    }
82
}
83

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

    
118
	// sorting
119
	if(natcasesort($result_list))
120
	{
121
		// new indexing
122
		$result_list = array_merge($result_list);
123
	}
124
	return $result_list; // Now return the list
125
}
126

    
127
// Function to open a directory and add to a dir list
128
function chmod_directory_contents($directory, $file_mode)
129
{
130
	if (is_dir($directory))
131
    {
132
    	// Set the umask to 0
133
    	$umask = umask(0);
134
    	// Open the directory then loop through its contents
135
    	$dir = dir($directory);
136
    	while (false !== $entry = $dir->read())
137
		{
138
    		// Skip pointers
139
    		if($entry[0] == '.') { continue; }
140
    		// Chmod the sub-dirs contents
141
    		if(is_dir("$directory/$entry"))
142
			{
143
    			chmod_directory_contents($directory.'/'.$entry, $file_mode);
144
    		}
145
    		change_mode($directory.'/'.$entry);
146
    	}
147
        $dir->close();
148
    	// Restore the umask
149
    	umask($umask);
150
    }
151
}
152

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

    
191
		// sorting
192
	    if (isset ($FILE['path']) && natcasesort($FILE['path']))
193
	    {
194
			// new indexing
195
	        $FILE['path'] = array_merge($FILE['path']);
196
	    }
197
		// sorting
198
	    if (isset ($FILE['filename']) && natcasesort($FILE['filename']))
199
	    {
200
			// new indexing
201
	        $FILE['filename'] = array_merge($FILE['filename']);
202
	    }
203
	    return $FILE;
204
	}
205
}
206

    
207
// Function to open a directory and add to a file list
208
function file_list($directory, $skip = array(), $show_hidden = false)
209
{
210
	$result_list = array();
211
	if (is_dir($directory))
212
    {
213
    	$dir = dir($directory); // Open the directory
214
		while (false !== ($entry = $dir->read())) // loop through the directory
215
		{
216
			if($entry == '.' || $entry == '..') { continue; } // Skip pointers
217
			if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
218
			if( sizeof($skip) > 0 && in_array($entry, $skip) ) { continue; } // Check if we to skip anything else
219
			if(is_file( $directory.'/'.$entry)) // Add files to list
220
			{
221
				$result_list[] = $directory.'/'.$entry;
222
			}
223
		}
224
		$dir->close(); // Now close the folder object
225
	}
226

    
227
    // make the list nice. Not all OS do this itself
228
   if(natcasesort($result_list))
229
   {
230
		$result_list = array_merge($result_list);
231
   }
232

    
233
	return $result_list;
234
}
235

    
236
// Function to get a list of home folders not to show
237
function get_home_folders()
238
{
239
	global $database, $admin;
240
	$home_folders = array();
241
	// Only return home folders is this feature is enabled
242
	// and user is not admin
243
//	if(HOME_FOLDERS AND ($_SESSION['GROUP_ID']!='1')) {
244
	if(HOME_FOLDERS AND (!in_array('1',explode(',', $_SESSION['GROUPS_ID']))))
245
	{
246
		$sql = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` WHERE `home_folder` != "'.$admin->get_home_folder().'"';
247
		$query_home_folders = $database->query($sql);
248
		if($query_home_folders->numRows() > 0)
249
		{
250
			while($folder = $query_home_folders->fetchRow())
251
			{
252
				$home_folders[$folder['home_folder']] = $folder['home_folder'];
253
			}
254
		}
255
		function remove_home_subs($directory = '/', $home_folders = '')
256
		{
257
			if( ($handle = opendir(WB_PATH.MEDIA_DIRECTORY.$directory)) )
258
			{
259
				// Loop through the dirs to check the home folders sub-dirs are not shown
260
				while(false !== ($file = readdir($handle)))
261
				{
262
					if($file[0] != '.' && $file != 'index.php')
263
					{
264
						if(is_dir(WB_PATH.MEDIA_DIRECTORY.$directory.'/'.$file))
265
						{
266
							if($directory != '/')
267
							{
268
								$file = $directory.'/'.$file;
269
							}
270
							else
271
							{
272
								$file = '/'.$file;
273
							}
274
							foreach($home_folders AS $hf)
275
							{
276
								$hf_length = strlen($hf);
277
								if($hf_length > 0)
278
								{
279
									if(substr($file, 0, $hf_length+1) == $hf)
280
									{
281
										$home_folders[$file] = $file;
282
									}
283
								}
284
							}
285
							$home_folders = remove_home_subs($file, $home_folders);
286
						}
287
					}
288
				}
289
			}
290
			return $home_folders;
291
		}
292
		$home_folders = remove_home_subs('/', $home_folders);
293
	}
294
	return $home_folders;
295
}
296

    
297
/*
298
 * @param object &$wb: $wb from frontend or $admin from backend
299
 * @return array: list of new entries
300
 * @description: callback remove path in files/dirs stored in array
301
 * @example: array_walk($array,'remove_path',PATH);
302
 */
303
//
304
function remove_path(&$path, $key, $vars = '')
305
{
306
	$path = str_replace($vars, '', $path);
307
}
308

    
309
/*
310
 * @param object &$wb: $wb from frontend or $admin from backend
311
 * @return array: list of ro-dirs
312
 * @description: returns a list of directories beyound /wb/media which are ReadOnly for current user
313
 */
314
function media_dirs_ro( &$wb )
315
{
316
	global $database;
317
	// if user is admin or home-folders not activated then there are no restrictions
318
	$allow_list = array();
319
	if( $wb->get_user_id() == 1 || !HOME_FOLDERS )
320
	{
321
		return array();
322
	}
323
	// at first read any dir and subdir from /media
324
	$full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
325
	// add own home_folder to allow-list
326
	if( $wb->get_home_folder() )
327
	{
328
		// old: $allow_list[] = get_home_folder();
329
		$allow_list[] = $wb->get_home_folder();
330
	}
331
	// get groups of current user
332
	$curr_groups = $wb->get_groups_id();
333
	// if current user is in admin-group
334
	 if( ($admin_key = array_search('1', $curr_groups)) !== false)
335
	{
336
		// remove admin-group from list
337
		unset($curr_groups[$admin_key]);
338
		// search for all users where the current user is admin from
339
		foreach( $curr_groups as $group)
340
		{
341
			$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
342
			$sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
343
			if( ($res_hf = $database->query($sql)) != null )
344
			{
345
				while( $rec_hf = $res_hf->fetchrow() )
346
				{
347
					$allow_list[] = $rec_hf['home_folder'];
348
				}
349
			}
350
		}
351
	}
352
	$tmp_array = $full_list;
353
	// create a list for readonly dir
354
    $array = array();
355
	while( sizeof($tmp_array) > 0)
356
	{
357
        $tmp = array_shift($tmp_array);
358
        $x = 0;
359
		while($x < sizeof($allow_list))
360
		{
361
			if(strpos ($tmp,$allow_list[$x])) {
362
				$array[] = $tmp;
363
			}
364
			$x++;
365
		}
366
	}
367

    
368
	$full_list = array_diff( $full_list, $array );
369
	$tmp = array();
370
	$full_list = array_merge($tmp,$full_list);
371

    
372
	return $full_list;
373
}
374

    
375
/*
376
 * @param object &$wb: $wb from frontend or $admin from backend
377
 * @return array: list of rw-dirs
378
 * @description: returns a list of directories beyound /wb/media which are ReadWrite for current user
379
 */
380
function media_dirs_rw ( &$wb )
381
{
382
	global $database;
383
	// if user is admin or home-folders not activated then there are no restrictions
384
	// at first read any dir and subdir from /media
385
	$full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
386
    $array = array();
387
	$allow_list = array();
388
	if( ($wb->ami_group_member('1')) && !HOME_FOLDERS )
389
	{
390
		return $full_list;
391
	}
392
	// add own home_folder to allow-list
393
	if( $wb->get_home_folder() )
394
	{
395
	  	$allow_list[] = $wb->get_home_folder();
396
	} else {
397
		$array = $full_list;
398
	}
399
	// get groups of current user
400
	$curr_groups = $wb->get_groups_id();
401
	// if current user is in admin-group
402
	if( ($admin_key = array_search('1', $curr_groups)) == true)
403
	{
404
		// remove admin-group from list
405
		// unset($curr_groups[$admin_key]);
406
		// search for all users where the current user is admin from
407
		foreach( $curr_groups as $group)
408
		{
409
			$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
410
			$sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
411
			if( ($res_hf = $database->query($sql)) != null )
412
			{
413
				while( $rec_hf = $res_hf->fetchrow() )
414
				{
415
					$allow_list[] = $rec_hf['home_folder'];
416
				}
417
			}
418
		}
419
	}
420

    
421
	$tmp_array = $full_list;
422
	// create a list for readwrite dir
423
	while( sizeof($tmp_array) > 0)
424
	{
425
        $tmp = array_shift($tmp_array);
426
        $x = 0;
427
		while($x < sizeof($allow_list))
428
		{
429
			if(strpos ($tmp,$allow_list[$x])) {
430
				$array[] = $tmp;
431
			}
432
			$x++;
433
		}
434
	}
435

    
436
	$tmp = array();
437
    $array = array_unique($array);
438
	$full_list = array_merge($tmp,$array);
439
    unset($array);
440
    unset($allow_list);
441

    
442
	return $full_list;
443
}
444

    
445
// Function to create directories
446
function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE)
447
{
448
	if(!is_dir($dir_name))
449
    {
450
		$umask = umask(0);
451
		mkdir($dir_name, $dir_mode);
452
		umask($umask);
453
		return true;
454
	} else {
455
		return false;	
456
	}
457
}
458

    
459
// Function to chmod files and directories
460
function change_mode($name)
461
{
462
	if(OPERATING_SYSTEM != 'windows')
463
    {
464
		// Only chmod if os is not windows
465
		if(is_dir($name))
466
        {
467
			$mode = OCTAL_DIR_MODE;
468
		}
469
        else
470
        {
471
			$mode = OCTAL_FILE_MODE;
472
		}
473

    
474
		if(file_exists($name))
475
        {
476
			$umask = umask(0);
477
			chmod($name, $mode);
478
			umask($umask);
479
			return true;
480
		}
481
        else
482
        {
483
			return false;	
484
		}
485
	}
486
    else
487
    {
488
		return true;
489
	}
490
}
491

    
492
// Function to figure out if a parent exists
493
function is_parent($page_id)
494
{
495
	global $database;
496
	// Get parent
497
	$sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
498
	$parent = $database->get_one($sql);
499
	// If parent isnt 0 return its ID
500
	if(is_null($parent))
501
	{
502
		return false;
503
	}
504
	else
505
	{
506
		return $parent;
507
	}
508
}
509

    
510
// Function to work out level
511
function level_count($page_id)
512
{
513
	global $database;
514
	// Get page parent
515
	$sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
516
	$parent = $database->get_one($sql);
517
	if($parent > 0) 
518
	{	// Get the level of the parent
519
		$sql = 'SELECT `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$parent;
520
		$level = $database->get_one($sql);
521
		return $level+1;
522
	}
523
	else
524
	{
525
		return 0;
526
	}
527
}
528

    
529
// Function to work out root parent
530
function root_parent($page_id)
531
{
532
	global $database;
533
	// Get page details
534
	$sql = 'SELECT `parent`, `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
535
	$query_page = $database->query($sql);
536
	$fetch_page = $query_page->fetchRow();
537
	$parent = $fetch_page['parent'];
538
	$level = $fetch_page['level'];	
539
	if($level == 1)
540
	{
541
		return $parent;
542
	}
543
	elseif($parent == 0)
544
	{
545
		return $page_id;
546
	}
547
	else
548
	{	// Figure out what the root parents id is
549
		$parent_ids = array_reverse(get_parent_ids($page_id));
550
		return $parent_ids[0];
551
	}
552
}
553

    
554
// Function to get page title
555
function get_page_title($id)
556
{
557
	global $database;
558
	// Get title
559
	$sql = 'SELECT `page_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
560
	$page_title = $database->get_one($sql);
561
	return $page_title;
562
}
563

    
564
// Function to get a pages menu title
565
function get_menu_title($id)
566
{
567
	global $database;
568
	// Get title
569
	$sql = 'SELECT `menu_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
570
	$menu_title = $database->get_one($sql);
571
	return $menu_title;
572
}
573

    
574
// Function to get all parent page titles
575
function get_parent_titles($parent_id)
576
{
577
	$titles[] = get_menu_title($parent_id);
578
	if(is_parent($parent_id) != false)
579
	{
580
		$parent_titles = get_parent_titles(is_parent($parent_id));
581
		$titles = array_merge($titles, $parent_titles);
582
	}
583
	return $titles;
584
}
585

    
586
// Function to get all parent page id's
587
function get_parent_ids($parent_id)
588
{
589
	$ids[] = $parent_id;
590
	if(is_parent($parent_id) != false)
591
	{
592
		$parent_ids = get_parent_ids(is_parent($parent_id));
593
		$ids = array_merge($ids, $parent_ids);
594
	}
595
	return $ids;
596
}
597

    
598
// Function to genereate page trail
599
function get_page_trail($page_id) {
600
	return implode(',', array_reverse(get_parent_ids($page_id)));
601
}
602

    
603
// Function to get all sub pages id's
604
function get_subs($parent, $subs)
605
{
606
	// Connect to the database
607
	global $database;
608
	// Get id's
609
	$sql = 'SELECT `page_id` FROM `'.TABLE_PREFIX.'pages` WHERE `parent` = '.$parent;
610
	$query = $database->query($sql);
611
	if($query->numRows() > 0)
612
	{
613
		while($fetch = $query->fetchRow())
614
		{
615
			$subs[] = $fetch['page_id'];
616
			// Get subs of this sub
617
			$subs = get_subs($fetch['page_id'], $subs);
618
		}
619
	}
620
	// Return subs array
621
	return $subs;
622
}
623

    
624
// Function as replacement for php's htmlspecialchars()
625
// Will not mangle HTML-entities
626
function my_htmlspecialchars($string)
627
{
628
	$string = preg_replace('/&(?=[#a-z0-9]+;)/i', '__amp;_', $string);
629
	$string = strtr($string, array('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;', '\''=>'&#39;'));
630
	$string = preg_replace('/__amp;_(?=[#a-z0-9]+;)/i', '&', $string);
631
	return($string);
632
}
633

    
634
// Convert a string from mixed html-entities/umlauts to pure $charset_out-umlauts
635
// Will replace all numeric and named entities except &gt; &lt; &apos; &quot; &#039; &nbsp;
636
// In case of error the returned string is unchanged, and a message is emitted.
637
function entities_to_umlauts($string, $charset_out=DEFAULT_CHARSET)
638
{
639
	require_once(WB_PATH.'/framework/functions-utf8.php');
640
	return entities_to_umlauts2($string, $charset_out);
641
}
642

    
643
// Will convert a string in $charset_in encoding to a pure ASCII string with HTML-entities.
644
// In case of error the returned string is unchanged, and a message is emitted.
645
function umlauts_to_entities($string, $charset_in=DEFAULT_CHARSET)
646
{
647
	require_once(WB_PATH.'/framework/functions-utf8.php');
648
	return umlauts_to_entities2($string, $charset_in);
649
}
650

    
651
// Function to convert a page title to a page filename
652
function page_filename($string)
653
{
654
	require_once(WB_PATH.'/framework/functions-utf8.php');
655
	$string = entities_to_7bit($string);
656
	// Now remove all bad characters
657
	$bad = array(
658
	'\'', /* /  */ '"', /* " */	'<', /* < */	'>', /* > */
659
	'{', /* { */	'}', /* } */	'[', /* [ */	']', /* ] */	'`', /* ` */
660
	'!', /* ! */	'@', /* @ */	'#', /* # */	'$', /* $ */	'%', /* % */
661
	'^', /* ^ */	'&', /* & */	'*', /* * */	'(', /* ( */	')', /* ) */
662
	'=', /* = */	'+', /* + */	'|', /* | */	'/', /* / */	'\\', /* \ */
663
	';', /* ; */	':', /* : */	',', /* , */	'?' /* ? */
664
	);
665
	$string = str_replace($bad, '', $string);
666
	// replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
667
	$string = preg_replace(array('/\.+/', '/\.+$/'), array('.', ''), $string);
668
	// Now replace spaces with page spcacer
669
	$string = trim($string);
670
	$string = preg_replace('/(\s)+/', PAGE_SPACER, $string);
671
	// Now convert to lower-case
672
	$string = strtolower($string);
673
	// If there are any weird language characters, this will protect us against possible problems they could cause
674
	$string = str_replace(array('%2F', '%'), array('/', ''), urlencode($string));
675
	// Finally, return the cleaned string
676
	return $string;
677
}
678

    
679
// Function to convert a desired media filename to a clean mediafilename
680
function media_filename($string)
681
{
682
	require_once(WB_PATH.'/framework/functions-utf8.php');
683
	$string = entities_to_7bit($string);
684
	// Now remove all bad characters
685
	$bad = array('\'','"','`','!','@','#','$','%','^','&','*','=','+','|','/','\\',';',':',',','?');
686
	$string = str_replace($bad, '', $string);
687
	// replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
688
	$string = preg_replace(array('/\.+/', '/\.+$/', '/\s/'), array('.', '', '_'), $string);
689
	// Clean any page spacers at the end of string
690
	$string = trim($string);
691
	// Finally, return the cleaned string
692
	return $string;
693
}
694

    
695
// Function to work out a page link
696
if(!function_exists('page_link'))
697
{
698
	function page_link($link)
699
	{
700
		global $admin;
701
		return $admin->page_link($link);
702
	}
703
}
704

    
705
// Create a new directory and/or protected file in the given directory
706
function createFolderProtectFile($relative='',$make_dir=true)
707
{
708
	global $admin, $MESSAGE;
709
	$retVal = array();
710
    if($relative=='') { return $retVal;}
711

    
712
	if ( $make_dir==true ) {
713
		// Check to see if the folder already exists
714
		if(file_exists($relative)) {
715
			// $admin->print_error($MESSAGE['MEDIA_DIR_EXISTS']);
716
			$retVal[] = basename($relative).'::'.$MESSAGE['MEDIA_DIR_EXISTS'];
717
		}
718
		if ( !make_dir($relative) ) {
719
			// $admin->print_error($MESSAGE['MEDIA_DIR_NOT_MADE']);
720
			$retVal[] = basename($relative).'::'.$MESSAGE['MEDIA_DIR_NOT_MADE'];
721
		}
722
	}
723

    
724
	change_mode($relative);
725
	if( is_writable($relative) )
726
	{
727
        if(file_exists($relative.'/index.php')) { unlink($relative.'/index.php'); }
728
	    // Create default "index.php" file
729
		$rel_pages_dir = str_replace(WB_PATH, '', dirname($relative) );
730
		$step_back = str_repeat( '../', substr_count($rel_pages_dir, '/')+1 );
731

    
732
		$sResponse  = $_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently';
733
		$content =
734
			'<?php'."\n".
735
			'// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
736
			'// *** Creation date: '.date('c')."\n".
737
			'// *** Do not modify this file manually'."\n".
738
			'// *** WB will rebuild this file from time to time!!'."\n".
739
			'// *************************************************'."\n".
740
			"\t".'header(\''.$sResponse.'\');'."\n".
741
			"\t".'header(\'Location: '.WB_URL.'/index.php\');'."\n".
742
			'// *************************************************'."\n";
743
		$filename = $relative.'/index.php';
744
		// write content into file
745
		if ($handle = fopen($filename, 'w')) {
746
			fwrite($handle, $content);
747
			fclose($handle);
748
			change_mode($filename, 'file');
749
		}
750
		// $admin->print_success($MESSAGE['MEDIA']['DIR_MADE']);
751
	} else {
752
		// $admin->print_error($MESSAGE['GENERIC_BAD_PERMISSIONS']);
753
			$retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'];
754
	}
755
	return $retVal;
756
}
757

    
758
// Rebuild new protected files in the given directory and subs
759
function rebuildFolderProtectFile($dir='')
760
{
761
	$retVal = array();
762
    try {
763
		$iterator = new RecursiveDirectoryIterator($dir);
764
		foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST) as $file)
765
		{
766
		  if ($file->isDir()) {
767
		     $protect_file = ($file->getPathname());
768
		     $retVal[] = createFolderProtectFile($protect_file,false);
769
		  } else {
770
		     // print ($file->getPathname())."<br />";
771
		  }
772
		}
773
	} catch ( Exception $e ) {
774
		$retVal[] = $MESSAGE['MEDIA_DIR_ACCESS_DENIED'];
775
	}
776

    
777
    $retVal = array_merge($retVal);
778
	return $retVal;
779
}
780

    
781
// Create a new file in the pages directory
782
function create_access_file($filename,$page_id,$level)
783
{
784
	global $admin, $MESSAGE;
785
/*
786
	if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/'))
787
	{
788
		$admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE']);
789
	} else {
790
 	}
791
*/
792
		// First make sure parent folder exists
793
		$parent_folders = explode('/',str_replace(WB_PATH.PAGES_DIRECTORY, '', dirname($filename)));
794
		$parents = '';
795
		foreach($parent_folders AS $parent_folder)
796
		{
797
			if($parent_folder != '/' AND $parent_folder != '')
798
			{
799
				$parents .= '/'.$parent_folder;
800
				$acces_file = WB_PATH.PAGES_DIRECTORY.$parents;
801
				// can only be dirs
802
				if(!file_exists($acces_file)) {
803
					if(!make_dir($acces_file)) {
804
						$admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE_FOLDER']);
805
					}
806
				}
807
			}
808
		}
809
		// The depth of the page directory in the directory hierarchy
810
		// '/pages' is at depth 1
811
		$pages_dir_depth=count(explode('/',PAGES_DIRECTORY))-1;
812
		// Work-out how many ../'s we need to get to the index page
813
		$index_location = '';
814
		for($i = 0; $i < $level + $pages_dir_depth; $i++)
815
		{
816
			$index_location .= '../';
817
		}
818
		$content =
819
			'<?php'."\n".
820
			'// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
821
			'// *** Creation date: '.date('c')."\n".
822
			'// *** Do not modify this file manually'."\n".
823
			'// *** WB will rebuild this file from time to time!!'."\n".
824
			'// *************************************************'."\n".
825
			"\t".'$page_id    = '.$page_id.';'."\n".
826
			"\t".'require(\''.$index_location.'index.php\');'."\n".
827
			'// *************************************************'."\n";
828

    
829
		if ($handle = fopen($filename, 'w')) {
830
			fwrite($handle, $content);
831
			fclose($handle);
832
			// Chmod the file
833
			change_mode($filename);
834
		} else {
835
			$admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE']);
836
		}
837
	return;
838
 }
839

    
840
// Function for working out a file mime type (if the in-built PHP one is not enabled)
841
if(!function_exists('mime_content_type'))
842
{
843
    function mime_content_type($filename)
844
	{
845
	    $mime_types = array(
846
            'txt'	=> 'text/plain',
847
            'htm'	=> 'text/html',
848
            'html'	=> 'text/html',
849
            'php'	=> 'text/html',
850
            'css'	=> 'text/css',
851
            'js'	=> 'application/javascript',
852
            'json'	=> 'application/json',
853
            'xml'	=> 'application/xml',
854
            'swf'	=> 'application/x-shockwave-flash',
855
            'flv'	=> 'video/x-flv',
856

    
857
            // images
858
            'png'	=> 'image/png',
859
            'jpe'	=> 'image/jpeg',
860
            'jpeg'	=> 'image/jpeg',
861
            'jpg'	=> 'image/jpeg',
862
            'gif'	=> 'image/gif',
863
            'bmp'	=> 'image/bmp',
864
            'ico'	=> 'image/vnd.microsoft.icon',
865
            'tiff'	=> 'image/tiff',
866
            'tif'	=> 'image/tiff',
867
            'svg'	=> 'image/svg+xml',
868
            'svgz'	=> 'image/svg+xml',
869

    
870
            // archives
871
            'zip'	=> 'application/zip',
872
            'rar'	=> 'application/x-rar-compressed',
873
            'exe'	=> 'application/x-msdownload',
874
            'msi'	=> 'application/x-msdownload',
875
            'cab'	=> 'application/vnd.ms-cab-compressed',
876

    
877
            // audio/video
878
            'mp3'	=> 'audio/mpeg',
879
            'mp4'	=> 'audio/mpeg',
880
            'qt'	=> 'video/quicktime',
881
            'mov'	=> 'video/quicktime',
882

    
883
            // adobe
884
            'pdf'	=> 'application/pdf',
885
            'psd'	=> 'image/vnd.adobe.photoshop',
886
            'ai'	=> 'application/postscript',
887
            'eps'	=> 'application/postscript',
888
            'ps'	=> 'application/postscript',
889

    
890
            // ms office
891
            'doc'	=> 'application/msword',
892
            'rtf'	=> 'application/rtf',
893
            'xls'	=> 'application/vnd.ms-excel',
894
            'ppt'	=> 'application/vnd.ms-powerpoint',
895

    
896
            // open office
897
            'odt'	=> 'application/vnd.oasis.opendocument.text',
898
            'ods'	=> 'application/vnd.oasis.opendocument.spreadsheet',
899
        );
900

    
901
        $temp = explode('.',$filename);
902
        $ext = strtolower(array_pop($temp));
903

    
904
        if (array_key_exists($ext, $mime_types))
905
		{
906
            return $mime_types[$ext];
907
        }
908
        elseif (function_exists('finfo_open'))
909
		{
910
            $finfo = finfo_open(FILEINFO_MIME);
911
            $mimetype = finfo_file($finfo, $filename);
912
            finfo_close($finfo);
913
            return $mimetype;
914
        }
915
        else
916
		{
917
            return 'application/octet-stream';
918
        }
919
    }
920
}
921

    
922
// Generate a thumbnail from an image
923
function make_thumb($source, $destination, $size)
924
{
925
	// Check if GD is installed
926
	if(extension_loaded('gd') && function_exists('imageCreateFromJpeg'))
927
	{
928
		// First figure out the size of the thumbnail
929
		list($original_x, $original_y) = getimagesize($source);
930
		if ($original_x > $original_y)
931
		{
932
			$thumb_w = $size;
933
			$thumb_h = $original_y*($size/$original_x);
934
		}
935
		if ($original_x < $original_y)
936
		{
937
			$thumb_w = $original_x*($size/$original_y);
938
			$thumb_h = $size;
939
		}
940
		if ($original_x == $original_y)
941
		{
942
			$thumb_w = $size;
943
			$thumb_h = $size;	
944
		}
945
		// Now make the thumbnail
946
		$source = imageCreateFromJpeg($source);
947
		$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
948
		imagecopyresampled($dst_img,$source,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);
949
		imagejpeg($dst_img, $destination);
950
		// Clear memory
951
		imagedestroy($dst_img);
952
		imagedestroy($source);
953
	   // Return true
954
		return true;
955
	} else {
956
		return false;
957
	}
958
}
959

    
960
/*
961
 * Function to work-out a single part of an octal permission value
962
 *
963
 * @param mixed $octal_value: an octal value as string (i.e. '0777') or real octal integer (i.e. 0777 | 777)
964
 * @param string $who: char or string for whom the permission is asked( U[ser] / G[roup] / O[thers] )
965
 * @param string $action: char or string with the requested action( r[ead..] / w[rite..] / e|x[ecute..] )
966
 * @return boolean
967
 */
968
function extract_permission($octal_value, $who, $action)
969
{
970
	// Make sure that all arguments are set and $octal_value is a real octal-integer
971
	if( ($who == '') || ($action == '') || (preg_match( '/[^0-7]/', (string)$octal_value )) )
972
	{
973
		return false; // invalid argument, so return false
974
	}
975
	// convert $octal_value into a decimal-integer to be sure having a valid value
976
	$right_mask = octdec($octal_value);
977
	$action_mask = 0;
978
	// set the $action related bit in $action_mask
979
	switch($action[0]) // get action from first char of $action
980
	{
981
		case 'r':
982
		case 'R':
983
			$action_mask = 4; // set read-bit only (2^2)
984
			break;
985
		case 'w':
986
		case 'W':
987
			$action_mask = 2; // set write-bit only (2^1)
988
			break;
989
		case 'e':
990
		case 'E':
991
		case 'x':
992
		case 'X':
993
			$action_mask = 1; // set execute-bit only (2^0)
994
			break;
995
		default:
996
			return false; // undefined action name, so return false
997
	}
998
	// shift action-mask into the right position
999
	switch($who[0]) // get who from first char of $who
1000
	{
1001
		case 'u':
1002
		case 'U':
1003
			$action_mask <<= 3; // shift left 3 bits
1004
		case 'g':
1005
		case 'G':
1006
			$action_mask <<= 3; // shift left 3 bits
1007
		case 'o':
1008
		case 'O':
1009
			/* NOP */
1010
			break;
1011
		default:
1012
			return false; // undefined who, so return false
1013
	}
1014
	return( ($right_mask & $action_mask) != 0 ); // return result of binary-AND
1015
}
1016

    
1017
// Function to delete a page
1018
	function delete_page($page_id)
1019
	{
1020
		global $admin, $database, $MESSAGE;
1021
		// Find out more about the page
1022
		$sql  = 'SELECT `page_id`, `menu_title`, `page_title`, `level`, `link`, `parent`, `modified_by`, `modified_when` ';
1023
		$sql .= 'FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
1024
		$results = $database->query($sql);
1025
		if($database->is_error())    { $admin->print_error($database->get_error()); }
1026
		if($results->numRows() == 0) { $admin->print_error($MESSAGE['PAGES']['NOT_FOUND']); }
1027
		$results_array = $results->fetchRow();
1028
		$parent     = $results_array['parent'];
1029
		$level      = $results_array['level'];
1030
		$link       = $results_array['link'];
1031
		$page_title = $results_array['page_title'];
1032
		$menu_title = $results_array['menu_title'];
1033

    
1034
		// Get the sections that belong to the page
1035
		$sql = 'SELECT `section_id`, `module` FROM `'.TABLE_PREFIX.'sections` WHERE `page_id` = '.$page_id;
1036
		$query_sections = $database->query($sql);
1037
		if($query_sections->numRows() > 0)
1038
		{
1039
			while($section = $query_sections->fetchRow())
1040
			{
1041
				// Set section id
1042
				$section_id = $section['section_id'];
1043
				// Include the modules delete file if it exists
1044
				if(file_exists(WB_PATH.'/modules/'.$section['module'].'/delete.php'))
1045
				{
1046
					include(WB_PATH.'/modules/'.$section['module'].'/delete.php');
1047
				}
1048
			}
1049
		}
1050
		// Update the pages table
1051
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
1052
		$database->query($sql);
1053
		if($database->is_error())
1054
		{
1055
			$admin->print_error($database->get_error());
1056
		}
1057
		// Update the sections table
1058
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'sections` WHERE `page_id` = '.$page_id;
1059
		$database->query($sql);
1060
		if($database->is_error()) {
1061
			$admin->print_error($database->get_error());
1062
		}
1063
		// Include the ordering class or clean-up ordering
1064
		include_once(WB_PATH.'/framework/class.order.php');
1065
		$order = new order(TABLE_PREFIX.'pages', 'position', 'page_id', 'parent');
1066
		$order->clean($parent);
1067
		// Unlink the page access file and directory
1068
		$directory = WB_PATH.PAGES_DIRECTORY.$link;
1069
		$filename = $directory.PAGE_EXTENSION;
1070
		$directory .= '/';
1071
		if(file_exists($filename))
1072
		{
1073
			if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/'))
1074
			{
1075
				$admin->print_error($MESSAGE['PAGES']['CANNOT_DELETE_ACCESS_FILE']);
1076
			}
1077
			else
1078
			{
1079
				unlink($filename);
1080
				if( file_exists($directory) &&
1081
				   (rtrim($directory,'/') != WB_PATH.PAGES_DIRECTORY) &&
1082
				   (substr($link, 0, 1) != '.'))
1083
				{
1084
					rm_full_dir($directory);
1085
				}
1086
			}
1087
		}
1088
	}
1089

    
1090
/*
1091
 * @param string $file: name of the file to read
1092
 * @param int $size: number of maximum bytes to read (0 = complete file)
1093
 * @return string: the content as string, false on error
1094
 */
1095
	function getFilePart($file, $size = 0)
1096
	{
1097
		$file_content = '';
1098
		if( file_exists($file) && is_file($file) && is_readable($file))
1099
		{
1100
			if($size == 0)
1101
			{
1102
				$size = filesize($file);
1103
			}
1104
			if(($fh = fopen($file, 'rb')))
1105
			{
1106
				if( ($file_content = fread($fh, $size)) !== false )
1107
				{
1108
					return $file_content;
1109
				}
1110
				fclose($fh);
1111
			}
1112
		}
1113
		return false;
1114
	}
1115

    
1116
	/**
1117
	* replace varnames with values in a string
1118
	*
1119
	* @param string $subject: stringvariable with vars placeholder
1120
	* @param array $replace: values to replace vars placeholder
1121
	* @return string
1122
	*/
1123
    function replace_vars($subject = '', &$replace = null )
1124
    {
1125
		if(is_array($replace))
1126
		{
1127
			foreach ($replace  as $key => $value)
1128
			{
1129
				$subject = str_replace("{{".$key."}}", $value, $subject);
1130
			}
1131
		}
1132
		return $subject;
1133
    }
1134

    
1135
// Load module into DB
1136
function load_module($directory, $install = false)
1137
{
1138
	global $database,$admin,$MESSAGE;
1139
	$retVal = false;
1140
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1141
	{
1142
		require($directory.'/info.php');
1143
		if(isset($module_name))
1144
		{
1145
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1146
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1147
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1148
			$module_function = strtolower($module_function);
1149
			// Check that it doesn't already exist
1150
			$sqlwhere = 'WHERE `type` = \'module\' AND `directory` = \''.$module_directory.'\'';
1151
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1152
			if( $database->get_one($sql) )
1153
			{
1154
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1155
			}else{
1156
				// Load into DB
1157
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1158
				$sqlwhere = '';
1159
			}
1160
			$sql .= '`directory` = \''.$module_directory.'\', ';
1161
			$sql .= '`name` = \''.$module_name.'\', ';
1162
			$sql .= '`description`= \''.addslashes($module_description).'\', ';
1163
			$sql .= '`type`= \'module\', ';
1164
			$sql .= '`function` = \''.$module_function.'\', ';
1165
			$sql .= '`version` = \''.$module_version.'\', ';
1166
			$sql .= '`platform` = \''.$module_platform.'\', ';
1167
			$sql .= '`author` = \''.addslashes($module_author).'\', ';
1168
			$sql .= '`license` = \''.addslashes($module_license).'\'';
1169
			$sql .= $sqlwhere;
1170
			$retVal = $database->query($sql);
1171
			// Run installation script
1172
			if($install == true)
1173
			{
1174
				if(file_exists($directory.'/install.php'))
1175
				{
1176
					require($directory.'/install.php');
1177
				}
1178
			}
1179
		}
1180
	}
1181
}
1182

    
1183
// Load template into DB
1184
function load_template($directory)
1185
{
1186
	global $database, $admin;
1187
	$retVal = false;
1188
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1189
	{
1190
		require($directory.'/info.php');
1191
		if(isset($template_name))
1192
		{
1193
			if(!isset($template_license))
1194
            {
1195
              $template_license = 'GNU General Public License';
1196
            }
1197
			if(!isset($template_platform) && isset($template_designed_for))
1198
            {
1199
              $template_platform = $template_designed_for;
1200
            }
1201
			if(!isset($template_function))
1202
            {
1203
              $template_function = 'template';
1204
            }
1205
			// Check that it doesn't already exist
1206
			$sqlwhere = 'WHERE `type` = \'template\' AND `directory` = \''.$template_directory.'\'';
1207
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1208
			if( $database->get_one($sql) )
1209
			{
1210
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1211
			}else{
1212
				// Load into DB
1213
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1214
				$sqlwhere = '';
1215
			}
1216
			$sql .= '`directory` = \''.$template_directory.'\', ';
1217
			$sql .= '`name` = \''.$template_name.'\', ';
1218
			$sql .= '`description`= \''.addslashes($template_description).'\', ';
1219
			$sql .= '`type`= \'template\', ';
1220
			$sql .= '`function` = \''.$template_function.'\', ';
1221
			$sql .= '`version` = \''.$template_version.'\', ';
1222
			$sql .= '`platform` = \''.$template_platform.'\', ';
1223
			$sql .= '`author` = \''.addslashes($template_author).'\', ';
1224
			$sql .= '`license` = \''.addslashes($template_license).'\' ';
1225
			$sql .= $sqlwhere;
1226
			$retVal = $database->query($sql);
1227
		}
1228
	}
1229
	return $retVal;
1230
}
1231

    
1232
// Load language into DB
1233
function load_language($file)
1234
{
1235
	global $database,$admin;
1236
	$retVal = false;
1237
	if (file_exists($file) && preg_match('#^([A-Z]{2}.php)#', basename($file)))
1238
	{
1239
		// require($file);  it's to large
1240
		// read contents of the template language file into string
1241
		$data = @file_get_contents(WB_PATH.'/languages/'.str_replace('.php','',basename($file)).'.php');
1242
		// use regular expressions to fetch the content of the variable from the string
1243
		$language_name = get_variable_content('language_name', $data, false, false);
1244
		$language_code = get_variable_content('language_code', $data, false, false);
1245
		$language_author = get_variable_content('language_author', $data, false, false);
1246
		$language_version = get_variable_content('language_version', $data, false, false);
1247
		$language_platform = get_variable_content('language_platform', $data, false, false);
1248

    
1249
		if(isset($language_name))
1250
		{
1251
			if(!isset($language_license)) { $language_license = 'GNU General Public License'; }
1252
			if(!isset($language_platform) && isset($language_designed_for)) { $language_platform = $language_designed_for; }
1253
			// Check that it doesn't already exist
1254
			$sqlwhere = 'WHERE `type` = \'language\' AND `directory` = \''.$language_code.'\'';
1255
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1256
			if( $database->get_one($sql) )
1257
			{
1258
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1259
			}else{
1260
				// Load into DB
1261
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1262
				$sqlwhere = '';
1263
			}
1264
			$sql .= '`directory` = \''.$language_code.'\', ';
1265
			$sql .= '`name` = \''.$language_name.'\', ';
1266
			$sql .= '`type`= \'language\', ';
1267
			$sql .= '`version` = \''.$language_version.'\', ';
1268
			$sql .= '`platform` = \''.$language_platform.'\', ';
1269
			$sql .= '`author` = \''.addslashes($language_author).'\', ';
1270
			$sql .= '`license` = \''.addslashes($language_license).'\' ';
1271
			$sql .= $sqlwhere;
1272
			$retVal = $database->query($sql);
1273
		}
1274
	}
1275
	return $retVal;
1276
}
1277

    
1278
// Upgrade module info in DB, optionally start upgrade script
1279
function upgrade_module($directory, $upgrade = false)
1280
{
1281
	global $database, $admin, $MESSAGE, $new_module_version;
1282
	$mod_directory = WB_PATH.'/modules/'.$directory;
1283
	if(file_exists($mod_directory.'/info.php'))
1284
	{
1285
		require($mod_directory.'/info.php');
1286
		if(isset($module_name))
1287
		{
1288
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1289
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1290
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1291
			$module_function = strtolower($module_function);
1292
			// Check that it does already exist
1293
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` ';
1294
			$sql .= 'WHERE `directory` = \''.$module_directory.'\'';
1295
			if( $database->get_one($sql) )
1296
			{
1297
				// Update in DB
1298
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1299
				$sql .= '`version` = "'.$module_version.'", ';
1300
				$sql .= '`description` = "'.addslashes($module_description).'", ';
1301
				$sql .= '`platform` = \''.$module_platform.'\', ';
1302
				$sql .= '`author` = \''.addslashes($module_author).'\', ';
1303
				$sql .= '`license` = \''.addslashes($module_license).'\' ';
1304
				$sql .= 'WHERE `directory` = \''.$module_directory.'\' ';
1305
				$database->query($sql);
1306
				if($database->is_error()) {
1307
					$admin->print_error($database->get_error());
1308
				}
1309

    
1310
				// Run upgrade script
1311
				if($upgrade == true)
1312
				{
1313
					if(file_exists($mod_directory.'/upgrade.php'))
1314
					{
1315
						require($mod_directory.'/upgrade.php');
1316
					}
1317
				}
1318
			}
1319
		}
1320
	}
1321
}
1322

    
1323
// extracts the content of a string variable from a string (save alternative to including files)
1324
if(!function_exists('get_variable_content'))
1325
{
1326
	function get_variable_content($search, $data, $striptags=true, $convert_to_entities=true)
1327
	{
1328
		$match = '';
1329
		// search for $variable followed by 0-n whitespace then by = then by 0-n whitespace
1330
		// then either " or ' then 0-n characters then either " or ' followed by 0-n whitespace and ;
1331
		// the variable name is returned in $match[1], the content in $match[3]
1332
		if (preg_match('/(\$' .$search .')\s*=\s*("|\')(.*)\2\s*;/', $data, $match))
1333
		{
1334
			if(strip_tags(trim($match[1])) == '$' .$search)
1335
			{
1336
				// variable name matches, return it's value
1337
				$match[3] = ($striptags == true) ? strip_tags($match[3]) : $match[3];
1338
				$match[3] = ($convert_to_entities == true) ? htmlentities($match[3]) : $match[3];
1339
				return $match[3];
1340
			}
1341
		}
1342
		return false;
1343
	}
1344
}
1345

    
1346
/*
1347
 * @param string $modulname: like saved in addons.directory
1348
 * @param boolean $source: true reads from database, false from info.php
1349
 * @return string:  the version as string, if not found returns null
1350
 */
1351

    
1352
	function get_modul_version($modulname, $source = true)
1353
	{
1354
		global $database;
1355
		$version = null;
1356
		if( $source != true )
1357
		{
1358
			$sql = 'SELECT `version` FROM `'.TABLE_PREFIX.'addons` WHERE `directory`=\''.$modulname.'\'';
1359
			$version = $database->get_one($sql);
1360
		} else {
1361
			$info_file = WB_PATH.'/modules/'.$modulname.'/info.php';
1362
			if(file_exists($info_file))
1363
			{
1364
				if(($info_file = file_get_contents($info_file)))
1365
				{
1366
					$version = get_variable_content('module_version', $info_file, false, false);
1367
					$version = ($version !== false) ? $version : null;
1368
				}
1369
			}
1370
		}
1371
		return $version;
1372
	}
1373

    
1374
/*
1375
 * @param string $varlist: commaseperated list of varnames to move into global space
1376
 * @return bool:  false if one of the vars already exists in global space (error added to msgQueue)
1377
 */
1378
	function vars2globals_wrapper($varlist)
1379
	{
1380
		$retval = true;
1381
		if( $varlist != '')
1382
		{
1383
			$vars = explode(',', $varlist);
1384
			foreach( $vars as $var)
1385
			{
1386
				if( isset($GLOBALS[$var]) )
1387
				{
1388
					ErrorLog::write( 'variabe $'.$var.' already defined in global space!!',__FILE__, __FUNCTION__, __LINE__);
1389
					$retval = false;
1390
				}else
1391
				{
1392
					global $$var;
1393
				}
1394
			}
1395
		}
1396
		return $retval;
1397
	}
1398

    
1399
/*
1400
 * filter directory traversal more thoroughly, thanks to hal 9000
1401
 * @param string $dir: directory relative to MEDIA_DIRECTORY
1402
 * @param bool $with_media_dir: true when to include MEDIA_DIRECTORY
1403
 * @return: false if directory traversal detected, real path if not
1404
 */
1405
	function check_media_path($directory, $with_media_dir = true)
1406
	{
1407
		$md = ($with_media_dir) ? MEDIA_DIRECTORY : ''; 
1408
		$dir = realpath(WB_PATH . $md . '/' . utf8_decode($directory));
1409
		$required = realpath(WB_PATH . MEDIA_DIRECTORY);
1410
		if (strstr($dir, $required)) {
1411
			return $dir;
1412
		} else {
1413
			return false;
1414
		}
1415
	}
1416

    
1417
/*
1418
urlencode function and rawurlencode are mostly based on RFC 1738.
1419
However, since 2005 the current RFC in use for URIs standard is RFC 3986.
1420
Here is a function to encode URLs according to RFC 3986.
1421
*/
1422
if(!function_exists('url_encode')){
1423
	function url_encode($string) {
1424
	    $string = html_entity_decode($string,ENT_QUOTES,'UTF-8');
1425
	    $entities = array('%20', '%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
1426
	    $replacements = array(' ','!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
1427
	    return str_replace($entities, $replacements, rawurlencode($string));
1428
	}
1429
}
(15-15/18)