Project

General

Profile

1
<?php
2
/**
3
 *
4
 * @category        frontend
5
 * @package         framework
6
 * @author          Ryan Djurovich,WebsiteBaker Project
7
 * @copyright       2009-2013, WebsiteBaker Org. e.V.
8
 * @link            http://www.websitebaker.org/
9
 * @license         http://www.gnu.org/licenses/gpl.html
10
 * @platform        WebsiteBaker 2.8.4
11
 * @requirements    PHP 5.2.2 and higher
12
 * @version         $Id: functions.php 1925 2013-06-08 23:03:14Z darkviper $
13
 * @filesource      $HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
14
 * @lastmodified    $Date: 2013-06-09 01:03:14 +0200 (Sun, 09 Jun 2013) $
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
	$bRetval = is_dir($dir_name);
419
	if(!$bRetval)
420
    {
421
		// To create the folder with 0777 permissions, we need to set umask to zero.
422
		$oldumask = umask(0) ;
423
		$bRetval = mkdir($dir_name, $dir_mode|0711, $recursive);
424
		umask( $oldumask ) ;
425
	}
426
	return $bRetval;
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
// Function to get a pages filename in sub
529
function get_sub_filename($id)
530
{
531
	$database = WbDatabase::getInstance();
532
	// Get title
533
	$sql = 'SELECT `link` FROM `'.TABLE_PREFIX.'pages` '
534
	      .'WHERE `page_id` = '.$id.' '
535
	      .  'AND `level`>=0';
536
	$sRetval = basename($database->get_one($sql));
537
	return $sRetval;
538
}
539

    
540
// Function to get all parent page titles
541
function get_parent_titles($parent_id)
542
{
543
	$titles[] = get_sub_filename($parent_id);
544
	if(is_parent($parent_id) != false) {
545
		$parent_titles = get_parent_titles(is_parent($parent_id));
546
		$titles = array_merge($titles, $parent_titles);
547
	}
548
	return $titles;
549
}
550

    
551
// Function to get all parent page id's
552
function get_parent_ids($parent_id)
553
{
554
	$ids[] = $parent_id;
555
	if(is_parent($parent_id) != false) {
556
		$parent_ids = get_parent_ids(is_parent($parent_id));
557
		$ids = array_merge($ids, $parent_ids);
558
	}
559
	return $ids;
560
}
561

    
562
// Function to genereate page trail
563
function get_page_trail($page_id)
564
{
565
	return implode(',', array_reverse(get_parent_ids($page_id)));
566
}
567

    
568
// Function to get all sub pages id's
569
function get_subs($parent, array $subs )
570
{
571
	// Connect to the database
572
	global $database;
573
	// Get id's
574
	$sql = 'SELECT `page_id` FROM `'.TABLE_PREFIX.'pages` WHERE `parent` = '.$parent;
575
	if( ($query = $database->query($sql)) ) {
576
		while($fetch = $query->fetchRow(MYSQL_ASSOC)) {
577
			$subs[] = $fetch['page_id'];
578
			// Get subs of this sub recursive
579
			$subs = get_subs($fetch['page_id'], $subs);
580
		}
581
	}
582
	// Return subs array
583
	return $subs;
584
}
585

    
586
// Function as replacement for php's htmlspecialchars()
587
// Will not mangle HTML-entities
588
function my_htmlspecialchars($string)
589
{
590
	$string = preg_replace('/&(?=[#a-z0-9]+;)/i', '__amp;_', $string);
591
	$string = strtr($string, array('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;', '\''=>'&#39;'));
592
	$string = preg_replace('/__amp;_(?=[#a-z0-9]+;)/i', '&', $string);
593
	return($string);
594
}
595

    
596
// Convert a string from mixed html-entities/umlauts to pure $charset_out-umlauts
597
// Will replace all numeric and named entities except &gt; &lt; &apos; &quot; &#039; &nbsp;
598
// In case of error the returned string is unchanged, and a message is emitted.
599
function entities_to_umlauts($string, $charset_out=DEFAULT_CHARSET)
600
{
601
	require_once(WB_PATH.'/framework/functions-utf8.php');
602
	return entities_to_umlauts2($string, $charset_out);
603
}
604

    
605
// Will convert a string in $charset_in encoding to a pure ASCII string with HTML-entities.
606
// In case of error the returned string is unchanged, and a message is emitted.
607
function umlauts_to_entities($string, $charset_in=DEFAULT_CHARSET)
608
{
609
	require_once(WB_PATH.'/framework/functions-utf8.php');
610
	return umlauts_to_entities2($string, $charset_in);
611
}
612

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

    
641
// Function to convert a desired media filename to a clean mediafilename
642
function media_filename($string)
643
{
644
	require_once(WB_PATH.'/framework/functions-utf8.php');
645
	$string = entities_to_7bit($string);
646
	// Now remove all bad characters
647
	$bad = array('\'','"','`','!','@','#','$','%','^','&','*','=','+','|','/','\\',';',':',',','?');
648
	$string = str_replace($bad, '', $string);
649
	// replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
650
	$string = preg_replace(array('/\.+/', '/\.+$/', '/\s/'), array('.', '', '_'), $string);
651
	// Clean any page spacers at the end of string
652
	$string = trim($string);
653
	// Finally, return the cleaned string
654
	return $string;
655
}
656

    
657
// Function to work out a page link
658
if(!function_exists('page_link'))
659
{
660
	function page_link($link)
661
	{
662
		global $admin;
663
		return $admin->page_link($link);
664
	}
665
}
666

    
667

    
668
// Create a new directory and/or protected file in the given directory
669
function createFolderProtectFile($sAbsDir='',$make_dir=true)
670
{
671
	global $admin, $MESSAGE;
672
	$retVal = array();
673
	$wb_path = rtrim(str_replace('\/\\', '/', WB_PATH), '/');
674
	if( ($sAbsDir=='') || ($sAbsDir == $wb_path) ) { return $retVal;}
675

    
676
	if ( $make_dir==true ) {
677
		// Check to see if the folder already exists
678
		if(is_readable($sAbsDir)) {
679
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_EXISTS'];
680
		}
681
		if (!is_dir($sAbsDir) && !make_dir($sAbsDir) ) {
682
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_NOT_MADE'];
683
		} else {
684
			change_mode($sAbsDir);
685
		}
686
		return $retVal;
687
	}
688

    
689
//$retVal[] = $sAbsDir;
690
//return $retVal;
691

    
692
	if( is_writable($sAbsDir) )
693
	{
694
        // if(file_exists($sAbsDir.'/index.php')) { unlink($sAbsDir.'/index.php'); }
695
	    // Create default "index.php" file
696
		$rel_pages_dir = str_replace($wb_path, '', dirname($sAbsDir) );
697
		$step_back = str_repeat( '../', substr_count($rel_pages_dir, '/')+1 );
698
		$sResponse  = $_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently';
699
		$content =
700
			'<?php'."\n".
701
			'// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
702
			'// *** Creation date: '.date('c')."\n".
703
			'// *** Do not modify this file manually'."\n".
704
			'// *** WB will rebuild this file from time to time!!'."\n".
705
			'// *************************************************'."\n".
706
			"\t".'header(\''.$sResponse.'\');'."\n".
707
			"\t".'header(\'Location: '.WB_URL.'/index.php\');'."\n".
708
			'// *************************************************'."\n";
709
		$filename = $sAbsDir.'/index.php';
710

    
711
		// write content into file
712
		  if(is_writable($filename) || !file_exists($filename)) {
713
		      if(file_put_contents($filename, $content)) {
714
		          $retVal[] = change_mode($filename);
715
		      } else {
716
		    $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'].' :: '.$filename;
717
		   }
718
		  }
719
		 } else {
720
		   $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'];
721
		 }
722
		 return $retVal;
723
}
724

    
725
function rebuildFolderProtectFile($dir='')
726
{
727
	global $MESSAGE;
728
	$retVal = array();
729
	$tmpVal = array();
730
	$dir = rtrim(str_replace('\/\\', '/', $dir), '/');
731
	try {
732
		$files = array();
733
		$files[] = $dir;
734
		foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $fileInfo) {
735
			$files[] = $fileInfo->getPath();
736
		}
737
		$files = array_unique($files);
738
		foreach( $files as $file) {
739
			$protect_file = rtrim(str_replace('\/\\', '/', $file), '/');
740
			$tmpVal['file'][] = createFolderProtectFile($protect_file,false);
741
		}
742
		$retVal = $tmpVal['file'];
743
	} catch ( Exception $e ) {
744
		$retVal[] = $MESSAGE['MEDIA_DIR_ACCESS_DENIED'];
745
	}
746
	return $retVal;
747
}
748

    
749
// Create a new file in the pages directory
750
/**
751
 * createAccessFile()
752
 * 
753
 * @param string The full path and filename to the new accessfile
754
 * @param int    Id of the page for which the file should created
755
 * @param mixed  an array with one or more additional statements to include in accessfile.
756
 * @return bool|string true or error message
757
 * @deprecated this function will be replaced by a core method in next version
758
 * @description: Create a new access file in the pages directory and subdirectory also if needed.<br />
759
 * Example: $aOptionalCommands = array(
760
 *                     '$section_id = '.$section_id,
761
 *                     '$mod_var_int = '.$mod_var_int,
762
 *                     'define(\'MOD_CONSTANT\'', '.$mod_var_int.')'
763
 *          );
764
 * forbidden commands: include|require[_once]
765
 * @deprecated   2013/02/19
766
 */
767
  
768
function create_access_file($sFileName, $iPageId, $iLevel = 0, array $aOptionalCommands = array() )
769
{
770
	global $MESSAGE;
771
	$sError = '';
772
// sanitize pathnames for the standard 'trailing slash' scheme
773
	$sAppPath  = rtrim(str_replace('\\', '/', WB_PATH), '/').'/';
774
	$sFileName = str_replace('\\', '/', $sFileName);
775
// try to create the whoole path to the accessfile
776
	$sAccessPath = dirname($sFileName).'/';
777
	if(!($bRetval = is_dir($sAccessPath))) {
778
		$iOldUmask = umask(0) ;
779
		// sanitize directory mode to 'o+rwx/g+x/u+x' and create path
780
		$bRetval = mkdir($sAccessPath, (OCTAL_DIR_MODE |0711), true); 
781
		umask($iOldUmask);
782
	}
783
	if($bRetval) {
784
	// check if accessfile is writeable
785
		if(is_writable($sAccessPath) ||
786
		   (file_exists($sFileName) && is_writable($sFileName)) )
787
		{
788
		// build content for accessfile
789
			$sContent  = '<?php'."\n"
790
			           . '// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n"
791
			           . '// *** Creation date: '.date('c')."\n"
792
			           . '// *** Do not modify this file manually'."\n"
793
			           . '// *** WB will rebuild this file from time to time!!'."\n"
794
			           . '// *************************************************'."\n"
795
			           . "\t".'$page_id = '.$iPageId.';'."\n";
796
		// analyse OptionalCommands and add it to the accessfile
797
			foreach($aOptionalCommands as $sCommand) {
798
			// loop through all available entries
799
			// remove all leading whitespaces and chars less then \x41(A) except \x24 ($)
800
			// also all trailing whitespaces and \x3B(;) too.
801
				$sNewCmd  = rtrim(ltrim($sCommand, "\x00..\x23\x25..\x40"), ';');
802
				if(preg_match('/^include|^require/i', $sNewCmd)) {
803
				// insert forbidden include|require[_once] command and comment it out
804
					$sContent .= "\t".'// *not allowed command >> * '.$sNewCmd.';'."\n";
805
				}elseif(preg_match('/^define/i', $sNewCmd)) {
806
				// insert active define command and comment it as set deprecated
807
					$sContent .= "\t".$sNewCmd.'; // *deprecated command*'."\n";
808
				}else {
809
				// insert allowed active command
810
					$sContent .= "\t".$sNewCmd.';'."\n";
811
				}
812
			}
813
		// calculate the needed backsteps and create the relative link to index.php
814
			$iBackSteps = substr_count(str_replace($sAppPath, '', $sFileName), '/');
815
			$sIndexFile = str_repeat('../', $iBackSteps).'index.php';
816
		// insert needed require command for index.php
817
			$sContent .= "\t".'require(\''.$sIndexFile.'\');'."\n"
818
			           . '// *************************************************'."\n"
819
			           . '// end of file'."\n";
820
		// write new file out. If the file already exists overwrite its content.
821
			if(file_put_contents($sFileName, $sContent) !== false ) {
822
			// if OS is not windows then chmod the new file 
823
				if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
824
				// sanitize filemode to 'o-x/g-x/u-x/o+rw' and chmod the new file
825
					$bRetval = chmod($sFileName, ((OCTAL_FILE_MODE & ~0111)|0600));
826
				}
827
			}else {
828
		        $sError = $MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE'];
829
			}
830
		}else {
831
			$sError = $MESSAGE['UPLOAD_ERR_CANT_WRITE'];
832
		}
833
	}else {
834
		$sError = $MESSAGE['UPLOAD_ERR_CANT_WRITE'];
835
	}
836
	// return boolean true if ok, on error return a message
837
	return ($sError == '' ? true : $sError);
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
        $temp = explode('.',$filename);
901
        $ext = strtolower(array_pop($temp));
902
        if (array_key_exists($ext, $mime_types)) {
903
            return $mime_types[$ext];
904
        }elseif (function_exists('finfo_open')) {
905
            $finfo = finfo_open(FILEINFO_MIME);
906
            $mimetype = finfo_file($finfo, $filename);
907
            finfo_close($finfo);
908
            return $mimetype;
909
        }else {
910
            return 'application/octet-stream';
911
        }
912
    }
913
}
914

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

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

    
1004
// Function to delete a page
1005
	function delete_page($page_id)
1006
	{
1007
		global $admin, $database, $MESSAGE;
1008
		// Find out more about the page
1009
		$sql  = 'SELECT `page_id`, `menu_title`, `page_title`, `level`, ';
1010
		$sql .=        '`link`, `parent`, `modified_by`, `modified_when` ';
1011
		$sql .= 'FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
1012
		$results = $database->query($sql);
1013
		if($database->is_error())    { $admin->print_error($database->get_error()); }
1014
		if($results->numRows() == 0) { $admin->print_error($MESSAGE['PAGES_NOT_FOUND']); }
1015
		$results_array = $results->fetchRow(MYSQL_ASSOC);
1016
		$parent     = $results_array['parent'];
1017
		$level      = $results_array['level'];
1018
		$sPageLink       = $results_array['link'];
1019
		$page_title = $results_array['page_title'];
1020
		$menu_title = $results_array['menu_title'];
1021
		// Get the sections that belong to the page
1022
		$sql  = 'SELECT `section_id`, `module` FROM `'.TABLE_PREFIX.'sections` ';
1023
		$sql .= 'WHERE `page_id`='.$page_id;
1024
		$query_sections = $database->query($sql);
1025
		if($query_sections->numRows() > 0)
1026
		{
1027
			while($section = $query_sections->fetchRow()) {
1028
				// Set section id
1029
				$section_id = $section['section_id'];
1030
				// Include the modules delete file if it exists
1031
				if(file_exists(WB_PATH.'/modules/'.$section['module'].'/delete.php')) {
1032
					include(WB_PATH.'/modules/'.$section['module'].'/delete.php');
1033
				}
1034
			}
1035
		}
1036
		// Update the sections table
1037
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'sections` WHERE `page_id`='.$page_id;
1038
		$database->query($sql);
1039
		if($database->is_error()) {
1040
			$admin->print_error($database->get_error());
1041
		}
1042
		// Include the ordering class or clean-up ordering
1043
		include_once(WB_PATH.'/framework/class.order.php');
1044
		$order = new order(TABLE_PREFIX.'pages', 'position', 'page_id', 'parent');
1045
		$order->clean($parent);
1046
		// Unlink the page access file and directory
1047
		$directory = WB_PATH.PAGES_DIRECTORY.$sPageLink;
1048
		$filename = $directory.PAGE_EXTENSION;
1049
		$directory .= '/';
1050
		if(is_writable($filename))
1051
		{
1052
			if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/')) {
1053
				$admin->print_error($MESSAGE['PAGES_CANNOT_DELETE_ACCESS_FILE']);
1054
			} else {
1055
				unlink($filename);
1056
				if( is_writable($directory) && (rtrim($directory,'/') != WB_PATH.PAGES_DIRECTORY ) && (substr($sPageLink, 0, 1) != '.') )
1057
				{
1058
					rm_full_dir($directory);
1059
				}
1060
			}
1061
		}
1062
		// Update the pages table
1063
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
1064
		$database->query($sql);
1065
		if($database->is_error()) {
1066
			$admin->print_error($database->get_error());
1067
		}
1068
	}
1069

    
1070
/*
1071
 * @param string $file: name of the file to read
1072
 * @param int $size: number of maximum bytes to read (0 = complete file)
1073
 * @return string: the content as string, false on error
1074
 */
1075
	function getFilePart($file, $size = 0)
1076
	{
1077
		$file_content = '';
1078
		if( file_exists($file) && is_file($file) && is_readable($file))
1079
		{
1080
			if($size == 0) {
1081
				$size = filesize($file);
1082
			}
1083
			if(($fh = fopen($file, 'rb'))) {
1084
				if( ($file_content = fread($fh, $size)) !== false ) {
1085
					return $file_content;
1086
				}
1087
				fclose($fh);
1088
			}
1089
		}
1090
		return false;
1091
	}
1092

    
1093
	/**
1094
	* replace varnames with values in a string
1095
	*
1096
	* @param string $subject: stringvariable with vars placeholder
1097
	* @param array $replace: values to replace vars placeholder
1098
	* @return string
1099
	*/
1100
    function replace_vars($subject = '', &$replace = null )
1101
    {
1102
		if(is_array($replace))
1103
		{
1104
			foreach ($replace  as $key => $value) {
1105
				$subject = str_replace("{{".$key."}}", $value, $subject);
1106
			}
1107
		}
1108
		return $subject;
1109
    }
1110

    
1111
function setAccessDeniedToNewTools($sModulName)
1112
{
1113
	$oDb = WbDatabase::getInstance();
1114
	$sql = 'UPDATE `'.$oDb->getTablePrefix.'groups` '
1115
		 . 'SET `module_permissions`= TRIM(LEADING \',\' FROM (CONCAT(`module_permissions`, \','.$sModulName.'\'))) '
1116
	     . 'WHERE `group_id`<>1 AND NOT FIND_IN_SET(\''.$sModulName.'\', `module_permissions`)';
1117
	$oDb->query($sql);
1118
}
1119
	
1120
// Load module into DB
1121
function load_module($directory, $install = false)
1122
{
1123
	global $database,$admin,$MESSAGE;
1124
	$retVal = false;
1125
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1126
	{
1127
		require($directory.'/info.php');
1128
		if(isset($module_name))
1129
		{
1130
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1131
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1132
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1133
			$module_function = strtolower($module_function);
1134
			// Check that it doesn't already exist
1135
			$sqlwhere = 'WHERE `type` = \'module\' AND `directory` = \''.$module_directory.'\'';
1136
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1137
			if( $database->get_one($sql) ) {
1138
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1139
			}else{
1140
				// Load into DB
1141
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1142
				$sqlwhere = '';
1143
			}
1144
			$sql .= '`directory`=\''.$module_directory.'\', ';
1145
			$sql .= '`name`=\''.$module_name.'\', ';
1146
			$sql .= '`description`=\''.addslashes($module_description).'\', ';
1147
			$sql .= '`type`=\'module\', ';
1148
			$sql .= '`function`=\''.$module_function.'\', ';
1149
			$sql .= '`version`=\''.$module_version.'\', ';
1150
			$sql .= '`platform`=\''.$module_platform.'\', ';
1151
			$sql .= '`author`=\''.addslashes($module_author).'\', ';
1152
			$sql .= '`license`=\''.addslashes($module_license).'\'';
1153
			$sql .= $sqlwhere;
1154
			$retVal = intval($database->query($sql) ? true : false);
1155
			if($retVal && !$sqlwhere &&
1156
			   ($module_function == 'tool' || $module_function == 'page' || $module_function == 'wysiwyg')
1157
			  ) {
1158
				setAccessDeniedToNewTools($module_directory);
1159
			}
1160
			// Run installation script
1161
			if($install == true) {
1162
				if(file_exists($directory.'/install.php')) {
1163
					require($directory.'/install.php');
1164
				}
1165
			}
1166
		}
1167
        return $retVal;
1168
	}
1169
}
1170

    
1171
// Load template into DB
1172
function load_template($directory)
1173
{
1174
	global $database, $admin;
1175
	$retVal = false;
1176
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1177
	{
1178
		require($directory.'/info.php');
1179
		if(isset($template_name))
1180
		{
1181
			if(!isset($template_license)) {
1182
              $template_license = 'GNU General Public License';
1183
            }
1184
			if(!isset($template_platform) && isset($template_designed_for)) {
1185
              $template_platform = $template_designed_for;
1186
            }
1187
			if(!isset($template_function)) {
1188
              $template_function = 'template';
1189
            }
1190
			// Check that it doesn't already exist
1191
			$sqlwhere = 'WHERE `type`=\'template\' AND `directory`=\''.$template_directory.'\'';
1192
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1193
			if( $database->get_one($sql) ) {
1194
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1195
			}else{
1196
				// Load into DB
1197
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1198
				$sqlwhere = '';
1199
			}
1200
			$sql .= '`directory`=\''.$template_directory.'\', ';
1201
			$sql .= '`name`=\''.$template_name.'\', ';
1202
			$sql .= '`description`=\''.addslashes($template_description).'\', ';
1203
			$sql .= '`type`=\'template\', ';
1204
			$sql .= '`function`=\''.$template_function.'\', ';
1205
			$sql .= '`version`=\''.$template_version.'\', ';
1206
			$sql .= '`platform`=\''.$template_platform.'\', ';
1207
			$sql .= '`author`=\''.addslashes($template_author).'\', ';
1208
			$sql .= '`license`=\''.addslashes($template_license).'\' ';
1209
			$sql .= $sqlwhere;
1210
			$retVal = intval($database->query($sql) ? true : false);
1211
		}
1212
	}
1213
	return $retVal;
1214
}
1215

    
1216
// Load language into DB
1217
function load_language($file)
1218
{
1219
	global $database,$admin;
1220
	$retVal = false;
1221
	if (file_exists($file) && preg_match('#^([A-Z]{2}.php)#', basename($file)))
1222
	{
1223
		// require($file);  it's to large
1224
		// read contents of the template language file into string
1225
		$data = @file_get_contents(WB_PATH.'/languages/'.str_replace('.php','',basename($file)).'.php');
1226
		// use regular expressions to fetch the content of the variable from the string
1227
		$language_name = get_variable_content('language_name', $data, false, false);
1228
		$language_code = get_variable_content('language_code', $data, false, false);
1229
		$language_author = get_variable_content('language_author', $data, false, false);
1230
		$language_version = get_variable_content('language_version', $data, false, false);
1231
		$language_platform = get_variable_content('language_platform', $data, false, false);
1232

    
1233
		if(isset($language_name))
1234
		{
1235
			if(!isset($language_license)) { $language_license = 'GNU General Public License'; }
1236
			if(!isset($language_platform) && isset($language_designed_for)) { $language_platform = $language_designed_for; }
1237
			// Check that it doesn't already exist
1238
			$sqlwhere = 'WHERE `type`=\'language\' AND `directory`=\''.$language_code.'\'';
1239
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1240
			if( $database->get_one($sql) ) {
1241
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1242
			}else{
1243
				// Load into DB
1244
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1245
				$sqlwhere = '';
1246
			}
1247
			$sql .= '`directory`=\''.$language_code.'\', ';
1248
			$sql .= '`name`=\''.$language_name.'\', ';
1249
            $sql .= '`description`=\'\', ';
1250
			$sql .= '`function`=\'\', ';
1251
			$sql .= '`type`=\'language\', ';
1252
			$sql .= '`version`=\''.$language_version.'\', ';
1253
			$sql .= '`platform`=\''.$language_platform.'\', ';
1254
			$sql .= '`author`=\''.addslashes($language_author).'\', ';
1255
			$sql .= '`license`=\''.addslashes($language_license).'\' ';
1256
			$sql .= $sqlwhere;
1257
			$retVal = intval($database->query($sql) ? true : false);
1258
		}
1259
	}
1260
	return $retVal;
1261
}
1262

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

    
1305
// extracts the content of a string variable from a string (save alternative to including files)
1306
if(!function_exists('get_variable_content'))
1307
{
1308
	function get_variable_content($search, $data, $striptags=true, $convert_to_entities=true)
1309
	{
1310
		$match = '';
1311
		// search for $variable followed by 0-n whitespace then by = then by 0-n whitespace
1312
		// then either " or ' then 0-n characters then either " or ' followed by 0-n whitespace and ;
1313
		// the variable name is returned in $match[1], the content in $match[3]
1314
		if (preg_match('/(\$' .$search .')\s*=\s*("|\')(.*)\2\s*;/', $data, $match))
1315
		{
1316
			if(strip_tags(trim($match[1])) == '$' .$search) {
1317
				// variable name matches, return it's value
1318
				$match[3] = ($striptags == true) ? strip_tags($match[3]) : $match[3];
1319
				$match[3] = ($convert_to_entities == true) ? htmlentities($match[3]) : $match[3];
1320
				return $match[3];
1321
			}
1322
		}
1323
		return false;
1324
	}
1325
}
1326

    
1327
/*
1328
 * @param string $modulname: like saved in addons.directory
1329
 * @param boolean $source: true reads from database, false from info.php
1330
 * @return string:  the version as string, if not found returns null
1331
 */
1332

    
1333
	function get_modul_version($modulname, $source = true)
1334
	{
1335
		global $database;
1336
		$version = null;
1337
		if( $source != true )
1338
		{
1339
			$sql  = 'SELECT `version` FROM `'.TABLE_PREFIX.'addons` ';
1340
			$sql .= 'WHERE `directory`=\''.$modulname.'\'';
1341
			$version = $database->get_one($sql);
1342
		} else {
1343
			$info_file = WB_PATH.'/modules/'.$modulname.'/info.php';
1344
			if(file_exists($info_file)) {
1345
				if(($info_file = file_get_contents($info_file))) {
1346
					$version = get_variable_content('module_version', $info_file, false, false);
1347
					$version = ($version !== false) ? $version : null;
1348
				}
1349
			}
1350
		}
1351
		return $version;
1352
	}
1353

    
1354
/*
1355
 * @param string $varlist: commaseperated list of varnames to move into global space
1356
 * @return bool:  false if one of the vars already exists in global space (error added to msgQueue)
1357
 */
1358
	function vars2globals_wrapper($varlist)
1359
	{
1360
		$retval = true;
1361
		if( $varlist != '')
1362
		{
1363
			$vars = explode(',', $varlist);
1364
			foreach( $vars as $var)
1365
			{
1366
				if( isset($GLOBALS[$var]) ){
1367
					ErrorLog::write( 'variabe $'.$var.' already defined in global space!!',__FILE__, __FUNCTION__, __LINE__);
1368
					$retval = false;
1369
				}else {
1370
					global $$var;
1371
				}
1372
			}
1373
		}
1374
		return $retval;
1375
	}
1376

    
1377
/*
1378
 * filter directory traversal more thoroughly, thanks to hal 9000
1379
 * @param string $dir: directory relative to MEDIA_DIRECTORY
1380
 * @param bool $with_media_dir: true when to include MEDIA_DIRECTORY
1381
 * @return: false if directory traversal detected, real path if not
1382
 */
1383
	function check_media_path($directory, $with_media_dir = true)
1384
	{
1385
		$md = ($with_media_dir) ? MEDIA_DIRECTORY : '';
1386
		$dir = realpath(WB_PATH . $md . '/' . utf8_decode($directory));
1387
		$required = realpath(WB_PATH . MEDIA_DIRECTORY);
1388
		if (strstr($dir, $required)) {
1389
			return $dir;
1390
		} else {
1391
			return false;
1392
		}
1393
	}
1394

    
1395
/*
1396
urlencode function and rawurlencode are mostly based on RFC 1738.
1397
However, since 2005 the current RFC in use for URIs standard is RFC 3986.
1398
Here is a function to encode URLs according to RFC 3986.
1399
*/
1400
if(!function_exists('url_encode')){
1401
	function url_encode($string) {
1402
	    $string = html_entity_decode($string,ENT_QUOTES,'UTF-8');
1403
	    $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
1404
	    $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
1405
	    return str_replace($entities,$replacements, rawurlencode($string));
1406
	}
1407
}
1408

    
1409
if(!function_exists('rebuild_all_accessfiles')){
1410
	function rebuild_all_accessfiles() {
1411
        global $database;
1412
    	$retVal = array();
1413
    	/**
1414
    	 * try to remove access files and build new folder protect files
1415
    	 */
1416
    	$sTempDir = (defined('PAGES_DIRECTORY') && (PAGES_DIRECTORY != '') ? PAGES_DIRECTORY : '');
1417
    	if(($sTempDir!='') && is_writeable(WB_PATH.$sTempDir)==true) {
1418
    	 	if(rm_full_dir (WB_PATH.$sTempDir, true )==false) {
1419
    			$retVal[] = 'Could not delete existing access files';
1420
    	 	}
1421
    	}
1422
		$retVal = createFolderProtectFile(rtrim( WB_PATH.PAGES_DIRECTORY,'/') );
1423
    	/**
1424
    	 * Reformat/rebuild all existing access files
1425
    	 */
1426
//        $sql = 'SELECT `page_id`,`root_parent`,`link`, `level` FROM `'.TABLE_PREFIX.'pages` ORDER BY `link`';
1427
		$sql  = 'SELECT `page_id`,`root_parent`,`link`, `level` ';
1428
		$sql .= 'FROM `'.TABLE_PREFIX.'pages` ';
1429
		$sql .= 'WHERE `link` != \'\' ORDER BY `link` ';
1430
        if (($oPage = $database->query($sql)))
1431
        {
1432
            $x = 0;
1433
            while (($page = $oPage->fetchRow(MYSQL_ASSOC)))
1434
            {
1435
                // Work out level
1436
                $level = level_count($page['page_id']);
1437
                // Work out root parent
1438
                $root_parent = root_parent($page['page_id']);
1439
                // Work out page trail
1440
                $page_trail = get_page_trail($page['page_id']);
1441
                // Update page with new level and link
1442
                $sql  = 'UPDATE `'.TABLE_PREFIX.'pages` SET ';
1443
                $sql .= '`root_parent` = '.$root_parent.', ';
1444
                $sql .= '`level` = '.$level.', ';
1445
                $sql .= '`page_trail` = "'.$page_trail.'" ';
1446
                $sql .= 'WHERE `page_id` = '.$page['page_id'];
1447

    
1448
                if(!$database->query($sql)) {}
1449
                $filename = WB_PATH.PAGES_DIRECTORY.$page['link'].PAGE_EXTENSION;
1450
                create_access_file($filename, $page['page_id'], $page['level']);
1451
                $x++;
1452
            }
1453
            $retVal[] = 'Number of new formated access files: '.$x.'';
1454
        }
1455
    return $retVal;
1456
	}
1457
}
1458

    
1459
if(!function_exists('upgrade_modules')){
1460
	function upgrade_modules($aModuleList) {
1461
        global $database;
1462
    	foreach($aModuleList as $sModul) {
1463
    		if(file_exists(WB_PATH.'/modules/'.$sModul.'/upgrade.php')) {
1464
    			$currModulVersion = get_modul_version ($sModul, false);
1465
    			$newModulVersion =  get_modul_version ($sModul, true);
1466
    			if((version_compare($currModulVersion, $newModulVersion) <= 0)) {
1467
    				require(WB_PATH.'/modules/'.$sModul.'/upgrade.php');
1468
    			}
1469
    		}
1470
    	}
1471
    }
1472
}
1473

    
(29-29/34)