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 1824 2012-11-20 17:41:22Z Luisehahne $
13
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
14
 * @lastmodified    $Date: 2012-11-20 18:41:22 +0100 (Tue, 20 Nov 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
    $iErrorReporting = error_reporting(0);
38
	if(substr($directory,-1) == "/") {
39
        $directory = substr($directory,0,-1);
40
    }
41
   // If suplied dirname is a file then unlink it
42
    if (is_file( $directory )&& is_writable( $directory )) {
43
        $retval = unlink($directory);
44
        clearstatcache();
45
        error_reporting($iErrorReporting);
46
        return $retval;
47
    }
48
    if(!is_writable($directory) || !is_dir($directory)) {
49
        error_reporting($iErrorReporting);
50
        return false;
51
    } elseif(!is_readable($directory)) {
52
        error_reporting($iErrorReporting);
53
        return false;
54
    } else {
55
        $directoryHandle = opendir($directory);
56
        while ($contents = readdir($directoryHandle))
57
		{
58
            if($contents != '.' && $contents != '..')
59
			{
60
                $path = $directory . "/" . $contents;
61
                if(is_dir($path)) {
62
                    rm_full_dir($path);
63
                } else {
64
                    unlink($path);
65
					clearstatcache();
66
                }
67
            }
68
        }
69
        closedir($directoryHandle);
70
        if($empty == false) {
71
            if(is_dir($directory) && is_writable(dirname($directory))) {
72
                $retval = rmdir($directory);
73
                error_reporting($iErrorReporting);
74
                return $retval;
75
            } else {
76
                error_reporting($iErrorReporting);
77
				return false;
78
            }
79
        }
80
        error_reporting($iErrorReporting);
81
        return true;
82
    }
83
}
84

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

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

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

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

    
218
    // make the list nice. Not all OS do this itself
219
	if(natcasesort($result_list)) {
220
		$result_list = array_merge($result_list);
221
	}
222
	return $result_list;
223
}
224

    
225
function remove_home_subs($directory = '/', $home_folders = '')
226
{
227
	if( ($handle = opendir(WB_PATH.MEDIA_DIRECTORY.$directory)) )
228
	{
229
		// Loop through the dirs to check the home folders sub-dirs are not shown
230
		while(false !== ($file = readdir($handle)))
231
		{
232
			if($file[0] != '.' && $file != 'index.php')
233
			{
234
				if(is_dir(WB_PATH.MEDIA_DIRECTORY.$directory.'/'.$file))
235
				{
236
					if($directory != '/') {
237
						$file = $directory.'/'.$file;
238
					}else {
239
						$file = '/'.$file;
240
					}
241
					foreach($home_folders AS $hf)
242
					{
243
						$hf_length = strlen($hf);
244
						if($hf_length > 0) {
245
							if(substr($file, 0, $hf_length+1) == $hf) {
246
								$home_folders[$file] = $file;
247
							}
248
						}
249
					}
250
					$home_folders = remove_home_subs($file, $home_folders);
251
				}
252
			}
253
		}
254
	}
255
	return $home_folders;
256
}
257

    
258
// Function to get a list of home folders not to show
259
function get_home_folders()
260
{
261
	global $database, $admin;
262
	$home_folders = array();
263
	// Only return home folders is this feature is enabled
264
	// and user is not admin
265
//	if(HOME_FOLDERS AND ($_SESSION['GROUP_ID']!='1')) {
266
	if(HOME_FOLDERS AND (!in_array('1',explode(',', $_SESSION['GROUPS_ID']))))
267
	{
268
		$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
269
		$sql .= 'WHERE `home_folder`!=\''.$admin->get_home_folder().'\'';
270
		$query_home_folders = $database->query($sql);
271
		if($query_home_folders->numRows() > 0)
272
		{
273
			while($folder = $query_home_folders->fetchRow()) {
274
				$home_folders[$folder['home_folder']] = $folder['home_folder'];
275
			}
276
		}
277
		$home_folders = remove_home_subs('/', $home_folders);
278
	}
279
	return $home_folders;
280
}
281

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

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

    
394
	$tmp_array = $full_list;
395
	// create a list for readwrite dir
396
	while( sizeof($tmp_array) > 0)
397
	{
398
        $tmp = array_shift($tmp_array);
399
        $x = 0;
400
		while($x < sizeof($allow_list)) {
401
			if(strpos ($tmp,$allow_list[$x])) {
402
				$array[] = $tmp;
403
			}
404
			$x++;
405
		}
406
	}
407
	$tmp = array();
408
    $array = array_unique($array);
409
	$full_list = array_merge($tmp,$array);
410
    unset($array);
411
    unset($allow_list);
412
	return $full_list;
413
}
414

    
415
// Function to create directories
416
function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE, $recursive=true)
417
{
418
	$retVal = is_dir($dir_name);
419
	if(!is_dir($dir_name))
420
    {
421
		// To create the folder with 0777 permissions, we need to set umask to zero.
422
		$oldumask = umask(0) ;
423
		$retVal = mkdir($dir_name, $dir_mode, $recursive);
424
		umask( $oldumask ) ;
425
	}
426
	return $retVal;
427
}
428

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

    
456
// Function to figure out if a parent exists
457
function is_parent($page_id)
458
{
459
	global $database;
460
	// Get parent
461
	$sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
462
	$parent = $database->get_one($sql);
463
	// If parent isnt 0 return its ID
464
	if(is_null($parent)) {
465
		return false;
466
	}else {
467
		return $parent;
468
	}
469
}
470

    
471
// Function to work out level
472
function level_count($page_id)
473
{
474
	global $database;
475
	// Get page parent
476
	$sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
477
	$parent = $database->get_one($sql);
478
	if($parent > 0)
479
	{	// Get the level of the parent
480
		$sql = 'SELECT `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$parent;
481
		$level = $database->get_one($sql);
482
		return $level+1;
483
	}else {
484
		return 0;
485
	}
486
}
487

    
488
// Function to work out root parent
489
function root_parent($page_id)
490
{
491
	global $database;
492
	// Get page details
493
	$sql = 'SELECT `parent`, `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
494

    
495
	$query_page = $database->query($sql);
496
	$fetch_page = $query_page->fetchRow(MYSQL_ASSOC);
497
	$parent = $fetch_page['parent'];
498
	$level = $fetch_page['level'];
499
	if($level == 1) {
500
		return $parent;
501
	} elseif($parent == 0) {
502
		return $page_id;
503
	} else {	// Figure out what the root parents id is
504
		$parent_ids = array_reverse(get_parent_ids($page_id));
505
		return $parent_ids[0];
506
	}
507
}
508

    
509
// Function to get page title
510
function get_page_title($id)
511
{
512
	global $database;
513
	// Get title
514
	$sql = 'SELECT `page_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
515
	$page_title = $database->get_one($sql);
516
	return $page_title;
517
}
518

    
519
// Function to get a pages menu title
520
function get_menu_title($id)
521
{
522
	global $database;
523
	// Get title
524
	$sql = 'SELECT `menu_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
525
	$menu_title = $database->get_one($sql);
526
	return $menu_title;
527
}
528

    
529
// Function to get all parent page titles
530
function get_parent_titles($parent_id)
531
{
532
	$titles[] = get_menu_title($parent_id);
533
	if(is_parent($parent_id) != false) {
534
		$parent_titles = get_parent_titles(is_parent($parent_id));
535
		$titles = array_merge($titles, $parent_titles);
536
	}
537
	return $titles;
538
}
539

    
540
// Function to get all parent page id's
541
function get_parent_ids($parent_id)
542
{
543
	$ids[] = $parent_id;
544
	if(is_parent($parent_id) != false) {
545
		$parent_ids = get_parent_ids(is_parent($parent_id));
546
		$ids = array_merge($ids, $parent_ids);
547
	}
548
	return $ids;
549
}
550

    
551
// Function to genereate page trail
552
function get_page_trail($page_id)
553
{
554
	return implode(',', array_reverse(get_parent_ids($page_id)));
555
}
556

    
557
// Function to get all sub pages id's
558
function get_subs($parent, array $subs )
559
{
560
	// Connect to the database
561
	global $database;
562
	// Get id's
563
	$sql = 'SELECT `page_id` FROM `'.TABLE_PREFIX.'pages` WHERE `parent` = '.$parent;
564
	if( ($query = $database->query($sql)) ) {
565
		while($fetch = $query->fetchRow(MYSQL_ASSOC)) {
566
			$subs[] = $fetch['page_id'];
567
			// Get subs of this sub recursive
568
			$subs = get_subs($fetch['page_id'], $subs);
569
		}
570
	}
571
	// Return subs array
572
	return $subs;
573
}
574

    
575
// Function as replacement for php's htmlspecialchars()
576
// Will not mangle HTML-entities
577
function my_htmlspecialchars($string)
578
{
579
	$string = preg_replace('/&(?=[#a-z0-9]+;)/i', '__amp;_', $string);
580
	$string = strtr($string, array('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;', '\''=>'&#39;'));
581
	$string = preg_replace('/__amp;_(?=[#a-z0-9]+;)/i', '&', $string);
582
	return($string);
583
}
584

    
585
// Convert a string from mixed html-entities/umlauts to pure $charset_out-umlauts
586
// Will replace all numeric and named entities except &gt; &lt; &apos; &quot; &#039; &nbsp;
587
// In case of error the returned string is unchanged, and a message is emitted.
588
function entities_to_umlauts($string, $charset_out=DEFAULT_CHARSET)
589
{
590
	require_once(WB_PATH.'/framework/functions-utf8.php');
591
	return entities_to_umlauts2($string, $charset_out);
592
}
593

    
594
// Will convert a string in $charset_in encoding to a pure ASCII string with HTML-entities.
595
// In case of error the returned string is unchanged, and a message is emitted.
596
function umlauts_to_entities($string, $charset_in=DEFAULT_CHARSET)
597
{
598
	require_once(WB_PATH.'/framework/functions-utf8.php');
599
	return umlauts_to_entities2($string, $charset_in);
600
}
601

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

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

    
646
// Function to work out a page link
647
if(!function_exists('page_link'))
648
{
649
	function page_link($link)
650
	{
651
		global $admin;
652
		return $admin->page_link($link);
653
	}
654
}
655

    
656
// Create a new directory and/or protected file in the given directory
657
function createFolderProtectFile($sAbsDir='',$make_dir=true)
658
{
659
	global $admin, $MESSAGE;
660
	$retVal = array();
661
	$wb_path = rtrim(str_replace('\/\\', '/', WB_PATH), '/');
662
    if( ($sAbsDir=='') || ($sAbsDir == $wb_path) ) { return $retVal;}
663

    
664
	if ( $make_dir==true ) {
665
		// Check to see if the folder already exists
666
		if(file_exists($sAbsDir)) {
667
			// $admin->print_error($MESSAGE['MEDIA_DIR_EXISTS']);
668
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_EXISTS'];
669
		}
670
		if (!is_dir($sAbsDir) && !make_dir($sAbsDir) ) {
671
			// $admin->print_error($MESSAGE['MEDIA_DIR_NOT_MADE']);
672
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_NOT_MADE'];
673
		} else {
674
			change_mode($sAbsDir);
675
		}
676
	}
677

    
678
	if( is_writable($sAbsDir) )
679
	{
680
        // if(file_exists($sAbsDir.'/index.php')) { unlink($sAbsDir.'/index.php'); }
681
	    // Create default "index.php" file
682
		$rel_pages_dir = str_replace($wb_path, '', dirname($sAbsDir) );
683
		$step_back = str_repeat( '../', substr_count($rel_pages_dir, '/')+1 );
684

    
685
		$sResponse  = $_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently';
686
		$content =
687
			'<?php'."\n".
688
			'// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
689
			'// *** Creation date: '.date('c')."\n".
690
			'// *** Do not modify this file manually'."\n".
691
			'// *** WB will rebuild this file from time to time!!'."\n".
692
			'// *************************************************'."\n".
693
			"\t".'header(\''.$sResponse.'\');'."\n".
694
			"\t".'header(\'Location: '.WB_URL.'/index.php\');'."\n".
695
			'// *************************************************'."\n";
696
		$filename = $sAbsDir.'/index.php';
697

    
698
		// write content into file
699
		  if(is_writable($filename) || !file_exists($filename)) {
700
		      if(file_put_contents($filename, $content)) {
701
		//    print 'create => '.str_replace( $wb_path,'',$filename).'<br />';
702
		          change_mode($filename, 'file');
703
		      } else {
704
		    $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'].' :: '.$filename;
705
		   }
706
		  }
707
		 } else {
708
		   $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'];
709
		 }
710
		 return $retVal;
711
}
712

    
713
function rebuildFolderProtectFile($dir='')
714
{
715
	global $MESSAGE;
716
	$retVal = array();
717
	$dir = rtrim(str_replace('\/\\', '/', $dir), '/');
718
	try {
719
		$files = array();
720
		$files[] = $dir;
721
		foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $fileInfo) {
722
			$files[] = $fileInfo->getPath();
723
		}
724
		$files = array_unique($files);
725
		foreach( $files as $file) {
726
			$protect_file = rtrim(str_replace('\/\\', '/', $file), '/');
727
			$retVal[] = createFolderProtectFile($protect_file,false);
728
		}
729
	} catch ( Exception $e ) {
730
		$retVal[] = $MESSAGE['MEDIA_DIR_ACCESS_DENIED'];
731
	}
732
	return $retVal;
733
}
734

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

    
777
	if( ($handle = fopen($filename, 'w')) ) {
778
		fwrite($handle, $content);
779
		fclose($handle);
780
		// Chmod the file
781
		change_mode($filename);
782
	} else {
783
//		$admin->print_error($MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE']);
784
        $retVal[] = $MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE'];
785
	}
786
	return $retVal;
787
 }
788

    
789
// Function for working out a file mime type (if the in-built PHP one is not enabled)
790
if(!function_exists('mime_content_type'))
791
{
792
    function mime_content_type($filename)
793
	{
794
	    $mime_types = array(
795
            'txt'	=> 'text/plain',
796
            'htm'	=> 'text/html',
797
            'html'	=> 'text/html',
798
            'php'	=> 'text/html',
799
            'css'	=> 'text/css',
800
            'js'	=> 'application/javascript',
801
            'json'	=> 'application/json',
802
            'xml'	=> 'application/xml',
803
            'swf'	=> 'application/x-shockwave-flash',
804
            'flv'	=> 'video/x-flv',
805

    
806
            // images
807
            'png'	=> 'image/png',
808
            'jpe'	=> 'image/jpeg',
809
            'jpeg'	=> 'image/jpeg',
810
            'jpg'	=> 'image/jpeg',
811
            'gif'	=> 'image/gif',
812
            'bmp'	=> 'image/bmp',
813
            'ico'	=> 'image/vnd.microsoft.icon',
814
            'tiff'	=> 'image/tiff',
815
            'tif'	=> 'image/tiff',
816
            'svg'	=> 'image/svg+xml',
817
            'svgz'	=> 'image/svg+xml',
818

    
819
            // archives
820
            'zip'	=> 'application/zip',
821
            'rar'	=> 'application/x-rar-compressed',
822
            'exe'	=> 'application/x-msdownload',
823
            'msi'	=> 'application/x-msdownload',
824
            'cab'	=> 'application/vnd.ms-cab-compressed',
825

    
826
            // audio/video
827
            'mp3'	=> 'audio/mpeg',
828
            'mp4'	=> 'audio/mpeg',
829
            'qt'	=> 'video/quicktime',
830
            'mov'	=> 'video/quicktime',
831

    
832
            // adobe
833
            'pdf'	=> 'application/pdf',
834
            'psd'	=> 'image/vnd.adobe.photoshop',
835
            'ai'	=> 'application/postscript',
836
            'eps'	=> 'application/postscript',
837
            'ps'	=> 'application/postscript',
838

    
839
            // ms office
840
            'doc'	=> 'application/msword',
841
            'rtf'	=> 'application/rtf',
842
            'xls'	=> 'application/vnd.ms-excel',
843
            'ppt'	=> 'application/vnd.ms-powerpoint',
844

    
845
            // open office
846
            'odt'	=> 'application/vnd.oasis.opendocument.text',
847
            'ods'	=> 'application/vnd.oasis.opendocument.spreadsheet',
848
        );
849
        $temp = explode('.',$filename);
850
        $ext = strtolower(array_pop($temp));
851
        if (array_key_exists($ext, $mime_types)) {
852
            return $mime_types[$ext];
853
        }elseif (function_exists('finfo_open')) {
854
            $finfo = finfo_open(FILEINFO_MIME);
855
            $mimetype = finfo_file($finfo, $filename);
856
            finfo_close($finfo);
857
            return $mimetype;
858
        }else {
859
            return 'application/octet-stream';
860
        }
861
    }
862
}
863

    
864
// Generate a thumbnail from an image
865
function make_thumb($source, $destination, $size)
866
{
867
	// Check if GD is installed
868
	if(extension_loaded('gd') && function_exists('imageCreateFromJpeg'))
869
	{
870
		// First figure out the size of the thumbnail
871
		list($original_x, $original_y) = getimagesize($source);
872
		if ($original_x > $original_y) {
873
			$thumb_w = $size;
874
			$thumb_h = $original_y*($size/$original_x);
875
		}
876
		if ($original_x < $original_y) {
877
			$thumb_w = $original_x*($size/$original_y);
878
			$thumb_h = $size;
879
		}
880
		if ($original_x == $original_y) {
881
			$thumb_w = $size;
882
			$thumb_h = $size;
883
		}
884
		// Now make the thumbnail
885
		$source = imageCreateFromJpeg($source);
886
		$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
887
		imagecopyresampled($dst_img,$source,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);
888
		imagejpeg($dst_img, $destination);
889
		// Clear memory
890
		imagedestroy($dst_img);
891
		imagedestroy($source);
892
	   // Return true
893
		return true;
894
	} else {
895
		return false;
896
	}
897
}
898

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

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

    
1021
/*
1022
 * @param string $file: name of the file to read
1023
 * @param int $size: number of maximum bytes to read (0 = complete file)
1024
 * @return string: the content as string, false on error
1025
 */
1026
	function getFilePart($file, $size = 0)
1027
	{
1028
		$file_content = '';
1029
		if( file_exists($file) && is_file($file) && is_readable($file))
1030
		{
1031
			if($size == 0) {
1032
				$size = filesize($file);
1033
			}
1034
			if(($fh = fopen($file, 'rb'))) {
1035
				if( ($file_content = fread($fh, $size)) !== false ) {
1036
					return $file_content;
1037
				}
1038
				fclose($fh);
1039
			}
1040
		}
1041
		return false;
1042
	}
1043

    
1044
	/**
1045
	* replace varnames with values in a string
1046
	*
1047
	* @param string $subject: stringvariable with vars placeholder
1048
	* @param array $replace: values to replace vars placeholder
1049
	* @return string
1050
	*/
1051
    function replace_vars($subject = '', &$replace = null )
1052
    {
1053
		if(is_array($replace))
1054
		{
1055
			foreach ($replace  as $key => $value) {
1056
				$subject = str_replace("{{".$key."}}", $value, $subject);
1057
			}
1058
		}
1059
		return $subject;
1060
    }
1061

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

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

    
1153
// Load language into DB
1154
function load_language($file)
1155
{
1156
	global $database,$admin;
1157
	$retVal = false;
1158
	if (file_exists($file) && preg_match('#^([A-Z]{2}.php)#', basename($file)))
1159
	{
1160
		// require($file);  it's to large
1161
		// read contents of the template language file into string
1162
		$data = @file_get_contents(WB_PATH.'/languages/'.str_replace('.php','',basename($file)).'.php');
1163
		// use regular expressions to fetch the content of the variable from the string
1164
		$language_name = get_variable_content('language_name', $data, false, false);
1165
		$language_code = get_variable_content('language_code', $data, false, false);
1166
		$language_author = get_variable_content('language_author', $data, false, false);
1167
		$language_version = get_variable_content('language_version', $data, false, false);
1168
		$language_platform = get_variable_content('language_platform', $data, false, false);
1169

    
1170
		if(isset($language_name))
1171
		{
1172
			if(!isset($language_license)) { $language_license = 'GNU General Public License'; }
1173
			if(!isset($language_platform) && isset($language_designed_for)) { $language_platform = $language_designed_for; }
1174
			// Check that it doesn't already exist
1175
			$sqlwhere = 'WHERE `type`=\'language\' AND `directory`=\''.$language_code.'\'';
1176
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1177
			if( $database->get_one($sql) ) {
1178
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1179
			}else{
1180
				// Load into DB
1181
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1182
				$sqlwhere = '';
1183
			}
1184
			$sql .= '`directory`=\''.$language_code.'\', ';
1185
			$sql .= '`name`=\''.$language_name.'\', ';
1186
            $sql .= '`description`=\'\', ';
1187
			$sql .= '`function`=\'\', ';
1188
			$sql .= '`type`=\'language\', ';
1189
			$sql .= '`version`=\''.$language_version.'\', ';
1190
			$sql .= '`platform`=\''.$language_platform.'\', ';
1191
			$sql .= '`author`=\''.addslashes($language_author).'\', ';
1192
			$sql .= '`license`=\''.addslashes($language_license).'\' ';
1193
			$sql .= $sqlwhere;
1194
			$retVal = intval($database->query($sql) ? true : false);
1195
		}
1196
	}
1197
	return $retVal;
1198
}
1199

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

    
1242
// extracts the content of a string variable from a string (save alternative to including files)
1243
if(!function_exists('get_variable_content'))
1244
{
1245
	function get_variable_content($search, $data, $striptags=true, $convert_to_entities=true)
1246
	{
1247
		$match = '';
1248
		// search for $variable followed by 0-n whitespace then by = then by 0-n whitespace
1249
		// then either " or ' then 0-n characters then either " or ' followed by 0-n whitespace and ;
1250
		// the variable name is returned in $match[1], the content in $match[3]
1251
		if (preg_match('/(\$' .$search .')\s*=\s*("|\')(.*)\2\s*;/', $data, $match))
1252
		{
1253
			if(strip_tags(trim($match[1])) == '$' .$search) {
1254
				// variable name matches, return it's value
1255
				$match[3] = ($striptags == true) ? strip_tags($match[3]) : $match[3];
1256
				$match[3] = ($convert_to_entities == true) ? htmlentities($match[3]) : $match[3];
1257
				return $match[3];
1258
			}
1259
		}
1260
		return false;
1261
	}
1262
}
1263

    
1264
/*
1265
 * @param string $modulname: like saved in addons.directory
1266
 * @param boolean $source: true reads from database, false from info.php
1267
 * @return string:  the version as string, if not found returns null
1268
 */
1269

    
1270
	function get_modul_version($modulname, $source = true)
1271
	{
1272
		global $database;
1273
		$version = null;
1274
		if( $source != true )
1275
		{
1276
			$sql  = 'SELECT `version` FROM `'.TABLE_PREFIX.'addons` ';
1277
			$sql .= 'WHERE `directory`=\''.$modulname.'\'';
1278
			$version = $database->get_one($sql);
1279
		} else {
1280
			$info_file = WB_PATH.'/modules/'.$modulname.'/info.php';
1281
			if(file_exists($info_file)) {
1282
				if(($info_file = file_get_contents($info_file))) {
1283
					$version = get_variable_content('module_version', $info_file, false, false);
1284
					$version = ($version !== false) ? $version : null;
1285
				}
1286
			}
1287
		}
1288
		return $version;
1289
	}
1290

    
1291
/*
1292
 * @param string $varlist: commaseperated list of varnames to move into global space
1293
 * @return bool:  false if one of the vars already exists in global space (error added to msgQueue)
1294
 */
1295
	function vars2globals_wrapper($varlist)
1296
	{
1297
		$retval = true;
1298
		if( $varlist != '')
1299
		{
1300
			$vars = explode(',', $varlist);
1301
			foreach( $vars as $var)
1302
			{
1303
				if( isset($GLOBALS[$var]) ){
1304
					ErrorLog::write( 'variabe $'.$var.' already defined in global space!!',__FILE__, __FUNCTION__, __LINE__);
1305
					$retval = false;
1306
				}else {
1307
					global $$var;
1308
				}
1309
			}
1310
		}
1311
		return $retval;
1312
	}
1313

    
1314
/*
1315
 * filter directory traversal more thoroughly, thanks to hal 9000
1316
 * @param string $dir: directory relative to MEDIA_DIRECTORY
1317
 * @param bool $with_media_dir: true when to include MEDIA_DIRECTORY
1318
 * @return: false if directory traversal detected, real path if not
1319
 */
1320
	function check_media_path($directory, $with_media_dir = true)
1321
	{
1322
		$md = ($with_media_dir) ? MEDIA_DIRECTORY : '';
1323
		$dir = realpath(WB_PATH . $md . '/' . utf8_decode($directory));
1324
		$required = realpath(WB_PATH . MEDIA_DIRECTORY);
1325
		if (strstr($dir, $required)) {
1326
			return $dir;
1327
		} else {
1328
			return false;
1329
		}
1330
	}
1331

    
1332
/*
1333
urlencode function and rawurlencode are mostly based on RFC 1738.
1334
However, since 2005 the current RFC in use for URIs standard is RFC 3986.
1335
Here is a function to encode URLs according to RFC 3986.
1336
*/
1337
if(!function_exists('url_encode')){
1338
	function url_encode($string) {
1339
	    $string = html_entity_decode($string,ENT_QUOTES,'UTF-8');
1340
	    $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
1341
	    $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
1342
	    return str_replace($entities,$replacements, rawurlencode($string));
1343
	}
1344
}
1345

    
1346
if(!function_exists('rebuild_all_accessfiles')){
1347
	function rebuild_all_accessfiles() {
1348
        global $database;
1349
    	$retVal = array();
1350
    	/**
1351
    	 * try to remove access files and build new folder protect files
1352
    	 */
1353
    	$sTempDir = (defined('PAGES_DIRECTORY') && (PAGES_DIRECTORY != '') ? PAGES_DIRECTORY : '');
1354
    	if(($sTempDir!='') && is_writeable(WB_PATH.$sTempDir)==true) {
1355
    	 	if(rm_full_dir (WB_PATH.$sTempDir, true )==false) {
1356
    			$retVal[] = '<span><strong>Could not delete existing access files</strong></span>';
1357
    	 	}
1358
    	}
1359
		$retVal[] = createFolderProtectFile(rtrim( WB_PATH.PAGES_DIRECTORY,'/') );
1360
    	/**
1361
    	 * Reformat/rebuild all existing access files
1362
    	 */
1363
        $sql = 'SELECT `page_id`,`root_parent`,`link`, `level` FROM `'.TABLE_PREFIX.'pages` ORDER BY `link`';
1364
        if (($oPage = $database->query($sql)))
1365
        {
1366
            $x = 0;
1367
            while (($page = $oPage->fetchRow(MYSQL_ASSOC)))
1368
            {
1369
                // Work out level
1370
                $level = level_count($page['page_id']);
1371
                // Work out root parent
1372
                $root_parent = root_parent($page['page_id']);
1373
                // Work out page trail
1374
                $page_trail = get_page_trail($page['page_id']);
1375
                // Update page with new level and link
1376
                $sql  = 'UPDATE `'.TABLE_PREFIX.'pages` SET ';
1377
                $sql .= '`root_parent` = '.$root_parent.', ';
1378
                $sql .= '`level` = '.$level.', ';
1379
                $sql .= '`page_trail` = "'.$page_trail.'" ';
1380
                $sql .= 'WHERE `page_id` = '.$page['page_id'];
1381

    
1382
                if(!$database->query($sql)) {}
1383
                $filename = WB_PATH.PAGES_DIRECTORY.$page['link'].PAGE_EXTENSION;
1384
                $retVal = create_access_file($filename, $page['page_id'], $page['level']);
1385
                $x++;
1386
            }
1387
            $retVal[] = '<span><strong>Number of new formated access files: '.$x.'</strong></span>';
1388
        }
1389
    return $retVal;
1390
	}
1391
}
1392

    
1393
if(!function_exists('upgrade_modules')){
1394
	function upgrade_modules($aModuleList) {
1395
        global $database;
1396
    	foreach($aModuleList as $sModul) {
1397
    		if(file_exists(WB_PATH.'/modules/'.$sModul.'/upgrade.php')) {
1398
    			$currModulVersion = get_modul_version ($sModul, false);
1399
    			$newModulVersion =  get_modul_version ($sModul, true);
1400
    			if((version_compare($currModulVersion, $newModulVersion) <= 0)) {
1401
    				require_once(WB_PATH.'/modules/'.$sModul.'/upgrade.php');
1402
    			}
1403
    		}
1404
    	}
1405
    }
1406
}
1407

    
(20-20/25)