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 1978 2013-10-08 01:36:00Z Luisehahne $
13
 * @filesource      $HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
14
 * @lastmodified    $Date: 2013-10-08 03:36:00 +0200 (Tue, 08 Oct 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
/**
29
 * Delete an Accessfiles Tree
30
 * @param  string  $sDirToDelete
31
 * @param  array   &$aReport  returns report if set
32
 * @return boolean true/false
33
 * @description    Delete all accessfiles and its depending directory tree 
34
 *                 inside the given directory.
35
 */
36
function DeleteAccessFilesTree($sDirToDelete, array &$aReport = null)
37
{
38
		$aReport = array();
39
        $sBaseDir = realpath($sDirToDelete);
40
        if( $sBaseDir !== false) {    
41
		$sBaseDir = rtrim(str_replace('\\', '/', $sBaseDir), '/') . '/';
42
		// scan start directory for access files
43
		foreach (glob($sBaseDir . '*.php', GLOB_MARK) as $sItem) {
44
            $sItem = str_replace('\\', '/', $sItem);
45
			try{
46
				$oAccFile = new AccessFile($sItem);
47
				$oAccFile->delete();
48
				$aReport = array_merge($aReport, AccessFileHelper::getDelTreeLog());
49
			}catch(AccessFileIsNoAccessfileException $e) {
50
				continue;
51
			}
52
		}
53
		return true;
54
	}	
55
	return false;
56
}
57

    
58
/**
59
 * @description: recursively delete a non empty directory
60
 * @param string $directory :
61
 * @param bool $empty : true if you want the folder just emptied, but not deleted
62
 *                      false, or just simply leave it out, the given directory will be deleted, as well
63
 * @param array $aProtectedFiles optional list of protected files, full path needed
64
 * @return boolean: true/false
65
 * @from http://www.php.net/manual/de/function.rmdir.php#98499
66
 */
67
function rm_full_dir($directory, $empty = false, $aProtectedFiles = null)
68
{
69
	$directory = rtrim(str_replace('\\','/',$directory),'/');
70
	if($aProtectedFiles == null) {
71
		$aProtectedFiles = array();
72
	}
73
    $iErrorReporting = error_reporting(0);
74

    
75
    if (is_file( $directory )&& is_writable( $directory )) {
76
		if(!in_array(($directory), $aProtectedFiles)) {
77
			$retval = unlink($directory);
78
			clearstatcache();
79
			error_reporting($iErrorReporting);
80
			return $retval;
81
		}else {
82
			return true;
83
		}
84
    }
85
    if(!is_writable($directory) || !is_dir($directory)) {
86
        error_reporting($iErrorReporting);
87
        return false;
88
    } elseif(!is_readable($directory)) {
89
        error_reporting($iErrorReporting);
90
        return false;
91
    } else {
92
        $directoryHandle = opendir($directory);
93
        while ($contents = readdir($directoryHandle))
94
		{
95
            if($contents != '.' && $contents != '..')
96
			{
97
                $path = $directory . "/" . $contents;
98
                if(is_dir($path)) {
99
                    rm_full_dir($path, false, $aProtectedFiles);
100
                } else {
101
					if(!in_array($path, $aProtectedFiles)) {
102
				        unlink($path);
103
						clearstatcache();
104
					}
105
                }
106
            }
107
        }
108
        closedir($directoryHandle);
109
        if($empty == false) {
110
            if(is_dir($directory) && is_writable(dirname($directory))) {
111
                $retval = rmdir($directory);
112
                error_reporting($iErrorReporting);
113
                return $retval;
114
            } else {
115
                error_reporting($iErrorReporting);
116
				return false;
117
            }
118
        }
119
        error_reporting($iErrorReporting);
120
        return true;
121
    }
122
}
123

    
124
/*
125
 * returns a recursive list of all subdirectories from a given directory
126
 * @access  public
127
 * @param   string  $directory: from this dir the recursion will start
128
 * @param   bool    $show_hidden:  if set to TRUE also hidden dirs (.dir) will be shown
129
 * @return  array
130
 * example:
131
 *  /srv/www/httpdocs/wb/media/a/b/c/
132
 *  /srv/www/httpdocs/wb/media/a/b/d/
133
 * directory_list('/srv/www/httpdocs/wb/media/') will return:
134
 *  /a
135
 *  /a/b
136
 *  /a/b/c
137
 *  /a/b/d
138
 */
139
 function directory_list($directory, $show_hidden = false)
140
{
141
	$result_list = array();
142
	if (is_dir($directory))
143
    {
144
    	$dir = dir($directory); // Open the directory
145
    	while (false !== $entry = $dir->read()) // loop through the directory
146
		{
147
			if($entry == '.' || $entry == '..') { continue; } // Skip pointers
148
			if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
149
    		if (is_dir("$directory/$entry")) { // Add dir and contents to list
150
    			$result_list = array_merge($result_list, directory_list("$directory/$entry"));
151
    			$result_list[] = "$directory/$entry";
152
    		}
153
    	}
154
        $dir->close();
155
    }
156
	// sorting
157
	if(natcasesort($result_list)) {
158
		// new indexing
159
		$result_list = array_merge($result_list);
160
	}
161
	return $result_list; // Now return the list
162
}
163

    
164
// Function to open a directory and add to a dir list
165
function chmod_directory_contents($directory, $file_mode)
166
{
167
	if (is_dir($directory))
168
    {
169
    	// Set the umask to 0
170
    	$umask = umask(0);
171
    	// Open the directory then loop through its contents
172
    	$dir = dir($directory);
173
    	while (false !== $entry = $dir->read())
174
		{
175
    		// Skip pointers
176
    		if($entry[0] == '.') { continue; }
177
    		// Chmod the sub-dirs contents
178
    		if(is_dir("$directory/$entry")) {
179
    			chmod_directory_contents($directory.'/'.$entry, $file_mode);
180
    		}
181
    		change_mode($directory.'/'.$entry);
182
    	}
183
        $dir->close();
184
    	// Restore the umask
185
    	umask($umask);
186
    }
187
}
188

    
189
/**
190
* Scan a given directory for dirs and files.
191
*
192
* usage: scan_current_dir ($root = '' )
193
*
194
* @param     $root   set a absolute rootpath as string. if root is empty the current path will be scan
195
* @param     $search set a search pattern for files, empty search brings all files
196
* @access    public
197
* @return    array    returns a natsort array with keys 'path' and 'filename'
198
*
199
*/
200
if(!function_exists('scan_current_dir'))
201
{
202
	function scan_current_dir($root = '', $search = '/.*/')
203
	{
204
	    $FILE = array();
205
		$array = array();
206
	    clearstatcache();
207
	    $root = empty ($root) ? getcwd() : $root;
208
	    if (($handle = opendir($root)))
209
	    {
210
	    // Loop through the files and dirs an add to list  DIRECTORY_SEPARATOR
211
	        while (false !== ($file = readdir($handle)))
212
	        {
213
	            if (substr($file, 0, 1) != '.' && $file != 'index.php')
214
	            {
215
	                if (is_dir($root.'/'.$file)) {
216
	                    $FILE['path'][] = $file;
217
	                } elseif (preg_match($search, $file, $array) ) {
218
	                    $FILE['filename'][] = $array[0];
219
	                }
220
	            }
221
	        }
222
	        $close_verz = closedir($handle);
223
	    }
224
		// sorting
225
	    if (isset ($FILE['path']) && natcasesort($FILE['path'])) {
226
			// new indexing
227
	        $FILE['path'] = array_merge($FILE['path']);
228
	    }
229
		// sorting
230
	    if (isset ($FILE['filename']) && natcasesort($FILE['filename'])) {
231
			// new indexing
232
	        $FILE['filename'] = array_merge($FILE['filename']);
233
	    }
234
	    return $FILE;
235
	}
236
}
237

    
238
// Function to open a directory and add to a file list
239
function file_list($directory, $skip = array(), $show_hidden = false)
240
{
241
	$result_list = array();
242
	if (is_dir($directory))
243
    {
244
    	$dir = dir($directory); // Open the directory
245
		while (false !== ($entry = $dir->read())) // loop through the directory
246
		{
247
			if($entry == '.' || $entry == '..') { continue; } // Skip pointers
248
			if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
249
			if( sizeof($skip) > 0 && in_array($entry, $skip) ) { continue; } // Check if we to skip anything else
250
			if(is_file( $directory.'/'.$entry)) { // Add files to list
251
				$result_list[] = $directory.'/'.$entry;
252
			}
253
		}
254
		$dir->close(); // Now close the folder object
255
	}
256

    
257
    // make the list nice. Not all OS do this itself
258
	if(natcasesort($result_list)) {
259
		$result_list = array_merge($result_list);
260
	}
261
	return $result_list;
262
}
263

    
264
function remove_home_subs($directory = '/', $home_folders = '')
265
{
266
	if( ($handle = opendir(WB_PATH.MEDIA_DIRECTORY.$directory)) )
267
	{
268
		// Loop through the dirs to check the home folders sub-dirs are not shown
269
		while(false !== ($file = readdir($handle)))
270
		{
271
			if($file[0] != '.' && $file != 'index.php')
272
			{
273
				if(is_dir(WB_PATH.MEDIA_DIRECTORY.$directory.'/'.$file))
274
				{
275
					if($directory != '/') {
276
						$file = $directory.'/'.$file;
277
					}else {
278
						$file = '/'.$file;
279
					}
280
					foreach($home_folders AS $hf)
281
					{
282
						$hf_length = strlen($hf);
283
						if($hf_length > 0) {
284
							if(substr($file, 0, $hf_length+1) == $hf) {
285
								$home_folders[$file] = $file;
286
							}
287
						}
288
					}
289
					$home_folders = remove_home_subs($file, $home_folders);
290
				}
291
			}
292
		}
293
	}
294
	return $home_folders;
295
}
296

    
297
// Function to get a list of home folders not to show
298
function get_home_folders()
299
{
300
	global $database, $admin;
301
	$home_folders = array();
302
	// Only return home folders is this feature is enabled
303
	// and user is not admin
304
//	if(HOME_FOLDERS AND ($_SESSION['GROUP_ID']!='1')) {
305
	if(HOME_FOLDERS AND (!in_array('1',explode(',', $_SESSION['GROUPS_ID']))))
306
	{
307
		$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
308
		$sql .= 'WHERE `home_folder`!=\''.$admin->get_home_folder().'\'';
309
		$query_home_folders = $database->query($sql);
310
		if($query_home_folders->numRows() > 0)
311
		{
312
			while($folder = $query_home_folders->fetchRow()) {
313
				$home_folders[$folder['home_folder']] = $folder['home_folder'];
314
			}
315
		}
316
		$home_folders = remove_home_subs('/', $home_folders);
317
	}
318
	return $home_folders;
319
}
320

    
321
/*
322
 * @param object &$wb: $wb from frontend or $admin from backend
323
 * @return array: list of new entries
324
 * @description: callback remove path in files/dirs stored in array
325
 * @example: array_walk($array,'remove_path',PATH);
326
 */
327
//
328
function remove_path(&$path, $key, $vars = '')
329
{
330
	$path = str_replace($vars, '', $path);
331
}
332
/*
333
 * @param object &$wb: $wb from frontend or $admin from backend
334
 * @return array: list of ro-dirs
335
 * @description: returns a list of directories beyound /wb/media which are ReadOnly for current user
336
 */
337
function media_dirs_ro( &$wb )
338
{
339
	global $database;
340
	// if user is admin or home-folders not activated then there are no restrictions
341
	$allow_list = array();
342
	if( $wb->get_user_id() == 1 || !HOME_FOLDERS ) {
343
		return array();
344
	}
345
	// at first read any dir and subdir from /media
346
	$full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
347
	// add own home_folder to allow-list
348
	if( $wb->get_home_folder() ) {
349
		// old: $allow_list[] = get_home_folder();
350
		$allow_list[] = $wb->get_home_folder();
351
	}
352
	// get groups of current user
353
	$curr_groups = $wb->get_groups_id();
354
	// if current user is in admin-group
355
	if( ($admin_key = array_search('1', $curr_groups)) !== false)
356
	{
357
		// remove admin-group from list
358
		unset($curr_groups[$admin_key]);
359
		// search for all users where the current user is admin from
360
		foreach( $curr_groups as $group)
361
		{
362
			$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
363
			$sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
364
			if( ($res_hf = $database->query($sql)) != null ) {
365
				while( $rec_hf = $res_hf->fetchrow() ) {
366
					$allow_list[] = $rec_hf['home_folder'];
367
				}
368
			}
369
		}
370
	}
371
	$tmp_array = $full_list;
372
	// create a list for readonly dir
373
    $array = array();
374
	while( sizeof($tmp_array) > 0)
375
	{
376
        $tmp = array_shift($tmp_array);
377
        $x = 0;
378
		while($x < sizeof($allow_list)) {
379
			if(strpos ($tmp,$allow_list[$x])) {
380
				$array[] = $tmp;
381
			}
382
			$x++;
383
		}
384
	}
385
	$full_list = array_diff( $full_list, $array );
386
	$tmp = array();
387
	$full_list = array_merge($tmp,$full_list);
388
	return $full_list;
389
}
390

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

    
433
	$tmp_array = $full_list;
434
	// create a list for readwrite dir
435
	while( sizeof($tmp_array) > 0)
436
	{
437
        $tmp = array_shift($tmp_array);
438
        $x = 0;
439
		while($x < sizeof($allow_list)) {
440
			if(strpos ($tmp,$allow_list[$x])) {
441
				$array[] = $tmp;
442
			}
443
			$x++;
444
		}
445
	}
446
	$tmp = array();
447
    $array = array_unique($array);
448
	$full_list = array_merge($tmp,$array);
449
    unset($array);
450
    unset($allow_list);
451
	return $full_list;
452
}
453

    
454
// Function to create directories
455
function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE, $recursive=true)
456
{
457
	$bRetval = is_dir($dir_name);
458
	if(!$bRetval)
459
    {
460
		// To create the folder with 0777 permissions, we need to set umask to zero.
461
		$oldumask = umask(0) ;
462
		$bRetval = mkdir($dir_name, $dir_mode|0711, $recursive);
463
		umask( $oldumask ) ;
464
	}
465
	return $bRetval;
466
}
467

    
468
/**
469
 * Function to chmod files and/or directories
470
 * the function also prevents the owner to loose rw-rights
471
 * @param string $sName
472
 * @param int rights in dec-value. 0= use wb-defaults
473
 * @return bool
474
 */
475
function change_mode($sName, $iMode = 0 )
476
{
477
	$bRetval = true;
478
    $iErrorReporting = error_reporting(0);
479
	$iMode = intval($iMode) & 0777; // sanitize value
480
	if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
481
	{ // Only chmod if os is not windows
482
		$bRetval = false;
483
		if(!$iMode) {
484
			$iMode = (is_file($sName) ? octdec(STRING_FILE_MODE) : octdec(STRING_DIR_MODE));
485
		}
486
		$iMode |= 0600; // set o+rw
487
		if(is_writable($sName)) {
488
			$bRetval = chmod($sName, $iMode);
489
		}
490
	}
491
    error_reporting($iErrorReporting);
492
	return $bRetval;
493
}
494

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

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

    
527
// Function to work out root parent
528
function root_parent($page_id)
529
{
530
	global $database;
531
	// Get page details
532
	$sql = 'SELECT `parent`, `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
533

    
534
	$query_page = $database->query($sql);
535
	$fetch_page = $query_page->fetchRow(MYSQL_ASSOC);
536
	$parent = $fetch_page['parent'];
537
	$level = $fetch_page['level'];
538
	if($level == 1) {
539
		return $parent;
540
	} elseif($parent == 0) {
541
		return $page_id;
542
	} else {	// Figure out what the root parents id is
543
		$parent_ids = array_reverse(get_parent_ids($page_id));
544
		return $parent_ids[0];
545
	}
546
}
547

    
548
// Function to get page title
549
function get_page_title($id)
550
{
551
	global $database;
552
	// Get title
553
	$sql = 'SELECT `page_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
554
	$page_title = $database->get_one($sql);
555
	return $page_title;
556
}
557

    
558
// Function to get a pages menu title
559
function get_menu_title($id)
560
{
561
	global $database;
562
	// Get title
563
	$sql = 'SELECT `menu_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
564
	$menu_title = $database->get_one($sql);
565
	return $menu_title;
566
}
567
// Function to get a pages filename in sub
568
function get_sub_filename($id)
569
{
570
	$database = WbDatabase::getInstance();
571
	// Get title
572
	$sql = 'SELECT `link` FROM `'.TABLE_PREFIX.'pages` '
573
	      .'WHERE `page_id` = '.$id.' '
574
	      .  'AND `level`>=0';
575
	$sRetval = basename($database->get_one($sql));
576
	return $sRetval;
577
}
578

    
579
// Function to get all parent page titles
580
function get_parent_titles($parent_id)
581
{
582
	$titles[] = get_sub_filename($parent_id);
583
	if(is_parent($parent_id) != false) {
584
		$parent_titles = get_parent_titles(is_parent($parent_id));
585
		$titles = array_merge($titles, $parent_titles);
586
	}
587
	return $titles;
588
}
589

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

    
601
// Function to genereate page trail
602
function get_page_trail($page_id)
603
{
604
	return implode(',', array_reverse(get_parent_ids($page_id)));
605
}
606

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

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

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

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

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

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

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

    
706

    
707
// Create a new directory and/or protected file in the given directory
708
function createFolderProtectFile($sAbsDir='',$make_dir=true)
709
{
710
	global $admin, $MESSAGE;
711
	$retVal = array();
712
	$wb_path   = rtrim(str_replace('\/\\', '/', WB_PATH), '/');
713
	$sAppPath  = rtrim(str_replace('\/\\', '/', WB_PATH), '/').'/';
714
	if( ($sAbsDir=='') || ($sAbsDir == $sAppPath) ) { return $retVal;}
715

    
716
	if ( $make_dir==true ) {
717
		// Check to see if the folder already exists
718
		if(is_readable($sAbsDir)) {
719
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_EXISTS'];
720
		}
721
		if (!make_dir($sAbsDir) && !is_dir($sAbsDir) ) {
722
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_NOT_MADE'];
723
		} else {
724
			change_mode($sAbsDir);
725
		}
726
		return $retVal;
727
	}
728

    
729
//$retVal[] = $sAbsDir;
730
//return $retVal;
731

    
732
	if( is_writable($sAbsDir) )
733
	{
734
        // if(file_exists($sAbsDir.'/index.php')) { unlink($sAbsDir.'/index.php'); }
735
	    // Create default "index.php" file
736
		$iBackSteps = substr_count(str_replace($sAppPath, '', $sAbsDir), '/');
737
		$sIndexFile = str_repeat('../', $iBackSteps).'index.php';
738
		$sResponse  = $_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently';
739
		$content =
740
			'<?php'."\n".
741
			'// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
742
			'// *** Creation date: '.date('c')."\n".
743
			'// *** Do not modify this file manually'."\n".
744
			'// *** WB will rebuild this file from time to time!!'."\n".
745
			'// *************************************************'."\n".
746
			"\t".'header(\''.$sResponse.'\');'."\n".
747
			"\t".'header(\'Location: '.WB_URL.'/index.php\');'."\n".
748
			'// *************************************************'."\n";
749
		$filename = $sAbsDir.'/index.php';
750

    
751
		// write content into file
752
		  if(is_writable($filename) || !file_exists($filename)) {
753
		      if(file_put_contents($filename, $content)) {
754
		          $retVal[] = change_mode($filename);
755
		      } else {
756
		    $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'].' :: '.$filename;
757
		   }
758
		  }
759
		 } else {
760
		   $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'];
761
		 }
762
		 return $retVal;
763
}
764

    
765
function rebuildFolderProtectFile($dir='')
766
{
767
	global $MESSAGE;
768
	$retVal = array();
769
	$tmpVal = array();
770
	$dir = rtrim(str_replace('\/\\', '/', $dir), '/');
771
	try {
772
		$files = array();
773
		$files[] = $dir;
774
		foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $fileInfo) {
775
			$files[] = $fileInfo->getPath();
776
		}
777
		$files = array_unique($files);
778
		foreach( $files as $file) {
779
			$protect_file = rtrim(str_replace('\/\\', '/', $file), '/');
780
			$tmpVal['file'][] = createFolderProtectFile($protect_file,false);
781
		}
782
		$retVal = $tmpVal['file'];
783
	} catch ( Exception $e ) {
784
		$retVal[] = $MESSAGE['MEDIA_DIR_ACCESS_DENIED'];
785
	}
786
	return $retVal;
787
}
788

    
789
// Create a new file in the pages directory
790
/**
791
 * createAccessFile()
792
 * 
793
 * @param string The full path and filename to the new accessfile
794
 * @param int    Id of the page for which the file should created
795
 * @param mixed  an array with one or more additional statements to include in accessfile.
796
 * @return bool|string true or error message
797
 * @deprecated this function will be replaced by a core method in next version
798
 * @description: Create a new access file in the pages directory and subdirectory also if needed.<br />
799
 * Example: $aOptionalCommands = array(
800
 *                     '$section_id = '.$section_id,
801
 *                     '$mod_var_int = '.$mod_var_int,
802
 *                     'define(\'MOD_CONSTANT\'', '.$mod_var_int.')'
803
 *          );
804
 * forbidden commands: include|require[_once]
805
 * @deprecated   2013/02/19
806
 */
807
  
808
function create_access_file($sFileName, $iPageId, $iLevel = 0, array $aOptionalCommands = array() )
809
{
810
	global $MESSAGE;
811
	$sError = '';
812
// sanitize pathnames for the standard 'trailing slash' scheme
813
	$sAppPath  = rtrim(str_replace('\\', '/', WB_PATH), '/').'/';
814
	$sFileName = str_replace('\\', '/', $sFileName);
815
// try to create the whoole path to the accessfile
816
	$sAccessPath = dirname($sFileName).'/';
817
	if(!($bRetval = is_dir($sAccessPath))) {
818
		$iOldUmask = umask(0) ;
819
		// sanitize directory mode to 'o+rwx/g+x/u+x' and create path
820
		$bRetval = mkdir($sAccessPath, (OCTAL_DIR_MODE |0711), true); 
821
		umask($iOldUmask);
822
	}
823
	if($bRetval) {
824
	// check if accessfile is writeable
825
		if(is_writable($sAccessPath) ||
826
		   (file_exists($sFileName) && is_writable($sFileName)) )
827
		{
828
		// build content for accessfile
829
			$sContent  = '<?php'."\n"
830
			           . '// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n"
831
			           . '// *** Creation date: '.date('c')."\n"
832
			           . '// *** Do not modify this file manually'."\n"
833
			           . '// *** WB will rebuild this file from time to time!!'."\n"
834
			           . '// *************************************************'."\n"
835
			           . "\t".'$page_id = '.$iPageId.';'."\n";
836
		// analyse OptionalCommands and add it to the accessfile
837
			foreach($aOptionalCommands as $sCommand) {
838
			// loop through all available entries
839
			// remove all leading whitespaces and chars less then \x41(A) except \x24 ($)
840
			// also all trailing whitespaces and \x3B(;) too.
841
				$sNewCmd  = rtrim(ltrim($sCommand, "\x00..\x23\x25..\x40"), ';');
842
				if(preg_match('/^include|^require/i', $sNewCmd)) {
843
				// insert forbidden include|require[_once] command and comment it out
844
					$sContent .= "\t".'// *not allowed command >> * '.$sNewCmd.';'."\n";
845
				}elseif(preg_match('/^define/i', $sNewCmd)) {
846
				// insert active define command and comment it as set deprecated
847
					$sContent .= "\t".$sNewCmd.'; // *deprecated command*'."\n";
848
				}else {
849
				// insert allowed active command
850
					$sContent .= "\t".$sNewCmd.';'."\n";
851
				}
852
			}
853
		// calculate the needed backsteps and create the relative link to index.php
854
			$iBackSteps = substr_count(str_replace($sAppPath, '', $sFileName), '/');
855
			$sIndexFile = str_repeat('../', $iBackSteps).'index.php';
856
		// insert needed require command for index.php
857
			$sContent .= "\t".'require(\''.$sIndexFile.'\');'."\n"
858
			           . '// *************************************************'."\n"
859
			           . '// end of file'."\n";
860
		// write new file out. If the file already exists overwrite its content.
861
			if(file_put_contents($sFileName, $sContent) !== false ) {
862
			// if OS is not windows then chmod the new file 
863
				if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
864
				// sanitize filemode to 'o-x/g-x/u-x/o+rw' and chmod the new file
865
					$bRetval = chmod($sFileName, ((OCTAL_FILE_MODE & ~0111)|0600));
866
				}
867
			}else {
868
		        $sError = $MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE'];
869
			}
870
		}else {
871
			$sError = $MESSAGE['UPLOAD_ERR_CANT_WRITE'];
872
		}
873
	}else {
874
		$sError = $MESSAGE['UPLOAD_ERR_CANT_WRITE'];
875
	}
876
	// return boolean true if ok, on error return a message
877
	return ($sError == '' ? true : $sError);
878
 }
879

    
880
// Function for working out a file mime type (if the in-built PHP one is not enabled)
881
if(!function_exists('mime_content_type'))
882
{
883
    function mime_content_type($filename)
884
	{
885
	    $mime_types = array(
886
            'txt'	=> 'text/plain',
887
            'htm'	=> 'text/html',
888
            'html'	=> 'text/html',
889
            'php'	=> 'text/html',
890
            'css'	=> 'text/css',
891
            'js'	=> 'application/javascript',
892
            'json'	=> 'application/json',
893
            'xml'	=> 'application/xml',
894
            'swf'	=> 'application/x-shockwave-flash',
895
            'flv'	=> 'video/x-flv',
896

    
897
            // images
898
            'png'	=> 'image/png',
899
            'jpe'	=> 'image/jpeg',
900
            'jpeg'	=> 'image/jpeg',
901
            'jpg'	=> 'image/jpeg',
902
            'gif'	=> 'image/gif',
903
            'bmp'	=> 'image/bmp',
904
            'ico'	=> 'image/vnd.microsoft.icon',
905
            'tiff'	=> 'image/tiff',
906
            'tif'	=> 'image/tiff',
907
            'svg'	=> 'image/svg+xml',
908
            'svgz'	=> 'image/svg+xml',
909

    
910
            // archives
911
            'zip'	=> 'application/zip',
912
            'rar'	=> 'application/x-rar-compressed',
913
            'exe'	=> 'application/x-msdownload',
914
            'msi'	=> 'application/x-msdownload',
915
            'cab'	=> 'application/vnd.ms-cab-compressed',
916

    
917
            // audio/video
918
            'mp3'	=> 'audio/mpeg',
919
            'mp4'	=> 'audio/mpeg',
920
            'qt'	=> 'video/quicktime',
921
            'mov'	=> 'video/quicktime',
922

    
923
            // adobe
924
            'pdf'	=> 'application/pdf',
925
            'psd'	=> 'image/vnd.adobe.photoshop',
926
            'ai'	=> 'application/postscript',
927
            'eps'	=> 'application/postscript',
928
            'ps'	=> 'application/postscript',
929

    
930
            // ms office
931
            'doc'	=> 'application/msword',
932
            'rtf'	=> 'application/rtf',
933
            'xls'	=> 'application/vnd.ms-excel',
934
            'ppt'	=> 'application/vnd.ms-powerpoint',
935

    
936
            // open office
937
            'odt'	=> 'application/vnd.oasis.opendocument.text',
938
            'ods'	=> 'application/vnd.oasis.opendocument.spreadsheet',
939
        );
940
        $temp = explode('.',$filename);
941
        $ext = strtolower(array_pop($temp));
942
        if (array_key_exists($ext, $mime_types)) {
943
            return $mime_types[$ext];
944
        }elseif (function_exists('finfo_open')) {
945
            $finfo = finfo_open(FILEINFO_MIME);
946
            $mimetype = finfo_file($finfo, $filename);
947
            finfo_close($finfo);
948
            return $mimetype;
949
        }else {
950
            return 'application/octet-stream';
951
        }
952
    }
953
}
954

    
955
// Generate a thumbnail from an image
956
function make_thumb($source, $destination, $size)
957
{
958
	// Check if GD is installed
959
	if(extension_loaded('gd') && function_exists('imageCreateFromJpeg'))
960
	{
961
		// First figure out the size of the thumbnail
962
		list($original_x, $original_y) = getimagesize($source);
963
		if ($original_x > $original_y) {
964
			$thumb_w = $size;
965
			$thumb_h = $original_y*($size/$original_x);
966
		}
967
		if ($original_x < $original_y) {
968
			$thumb_w = $original_x*($size/$original_y);
969
			$thumb_h = $size;
970
		}
971
		if ($original_x == $original_y) {
972
			$thumb_w = $size;
973
			$thumb_h = $size;
974
		}
975
		// Now make the thumbnail
976
		$source = imageCreateFromJpeg($source);
977
		$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
978
		imagecopyresampled($dst_img,$source,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);
979
		imagejpeg($dst_img, $destination);
980
		// Clear memory
981
		imagedestroy($dst_img);
982
		imagedestroy($source);
983
	   // Return true
984
		return true;
985
	} else {
986
		return false;
987
	}
988
}
989

    
990
/*
991
 * Function to work-out a single part of an octal permission value
992
 *
993
 * @param mixed $octal_value: an octal value as string (i.e. '0777') or real octal integer (i.e. 0777 | 777)
994
 * @param string $who: char or string for whom the permission is asked( U[ser] / G[roup] / O[thers] )
995
 * @param string $action: char or string with the requested action( r[ead..] / w[rite..] / e|x[ecute..] )
996
 * @return boolean
997
 */
998
function extract_permission($octal_value, $who, $action)
999
{
1000
	// Make sure that all arguments are set and $octal_value is a real octal-integer
1001
	if(($who == '') || ($action == '') || (preg_match( '/[^0-7]/', (string)$octal_value ))) {
1002
		return false; // invalid argument, so return false
1003
	}
1004
	// convert $octal_value into a decimal-integer to be sure having a valid value
1005
	$right_mask = octdec($octal_value);
1006
	$action_mask = 0;
1007
	// set the $action related bit in $action_mask
1008
	switch($action[0]) { // get action from first char of $action
1009
		case 'r':
1010
		case 'R':
1011
			$action_mask = 4; // set read-bit only (2^2)
1012
			break;
1013
		case 'w':
1014
		case 'W':
1015
			$action_mask = 2; // set write-bit only (2^1)
1016
			break;
1017
		case 'e':
1018
		case 'E':
1019
		case 'x':
1020
		case 'X':
1021
			$action_mask = 1; // set execute-bit only (2^0)
1022
			break;
1023
		default:
1024
			return false; // undefined action name, so return false
1025
	}
1026
	// shift action-mask into the right position
1027
	switch($who[0]) { // get who from first char of $who
1028
		case 'u':
1029
		case 'U':
1030
			$action_mask <<= 3; // shift left 3 bits
1031
		case 'g':
1032
		case 'G':
1033
			$action_mask <<= 3; // shift left 3 bits
1034
		case 'o':
1035
		case 'O':
1036
			/* NOP */
1037
			break;
1038
		default:
1039
			return false; // undefined who, so return false
1040
	}
1041
	return( ($right_mask & $action_mask) != 0 ); // return result of binary-AND
1042
}
1043

    
1044
// Function to delete a page
1045
	function delete_page($page_id)
1046
	{
1047
		global $admin, $database, $MESSAGE;
1048
		// Find out more about the page
1049
		$sql  = 'SELECT `page_id`, `menu_title`, `page_title`, `level`, ';
1050
		$sql .=        '`link`, `parent`, `modified_by`, `modified_when` ';
1051
		$sql .= 'FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
1052
		$results = $database->query($sql);
1053
		if($database->is_error())    { $admin->print_error($database->get_error()); }
1054
		if($results->numRows() == 0) { $admin->print_error($MESSAGE['PAGES_NOT_FOUND']); }
1055
		$results_array = $results->fetchRow(MYSQL_ASSOC);
1056
		$parent     = $results_array['parent'];
1057
		$level      = $results_array['level'];
1058
		$sPageLink       = $results_array['link'];
1059
		$page_title = $results_array['page_title'];
1060
		$menu_title = $results_array['menu_title'];
1061
		// Get the sections that belong to the page
1062
		$sql  = 'SELECT `section_id`, `module` FROM `'.TABLE_PREFIX.'sections` ';
1063
		$sql .= 'WHERE `page_id`='.$page_id;
1064
		$query_sections = $database->query($sql);
1065
		if($query_sections->numRows() > 0)
1066
		{
1067
			while($section = $query_sections->fetchRow()) {
1068
				// Set section id
1069
				$section_id = $section['section_id'];
1070
				// Include the modules delete file if it exists
1071
				if(file_exists(WB_PATH.'/modules/'.$section['module'].'/delete.php')) {
1072
					include(WB_PATH.'/modules/'.$section['module'].'/delete.php');
1073
				}
1074
			}
1075
		}
1076
		// Update the sections table
1077
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'sections` WHERE `page_id`='.$page_id;
1078
		$database->query($sql);
1079
		if($database->is_error()) {
1080
			$admin->print_error($database->get_error());
1081
		}
1082
		// Include the ordering class or clean-up ordering
1083
		include_once(WB_PATH.'/framework/class.order.php');
1084
		$order = new order(TABLE_PREFIX.'pages', 'position', 'page_id', 'parent');
1085
		$order->clean($parent);
1086
		// Unlink the page access file and directory
1087
		$directory = WB_PATH.PAGES_DIRECTORY.$sPageLink;
1088
		$filename = $directory.PAGE_EXTENSION;
1089
		$directory .= '/';
1090
		if(is_writable($filename))
1091
		{
1092
			if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/')) {
1093
				$admin->print_error($MESSAGE['PAGES_CANNOT_DELETE_ACCESS_FILE']);
1094
			} else {
1095
				unlink($filename);
1096
				if( is_writable($directory) && (rtrim($directory,'/') != WB_PATH.PAGES_DIRECTORY ) && (substr($sPageLink, 0, 1) != '.') )
1097
				{
1098
					rm_full_dir($directory);
1099
				}
1100
			}
1101
		}
1102
		// Update the pages table
1103
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
1104
		$database->query($sql);
1105
		if($database->is_error()) {
1106
			$admin->print_error($database->get_error());
1107
		}
1108
	}
1109

    
1110
/*
1111
 * @param string $file: name of the file to read
1112
 * @param int $size: number of maximum bytes to read (0 = complete file)
1113
 * @return string: the content as string, false on error
1114
 */
1115
	function getFilePart($file, $size = 0)
1116
	{
1117
		$file_content = '';
1118
		if( file_exists($file) && is_file($file) && is_readable($file))
1119
		{
1120
			if($size == 0) {
1121
				$size = filesize($file);
1122
			}
1123
			if(($fh = fopen($file, 'rb'))) {
1124
				if( ($file_content = fread($fh, $size)) !== false ) {
1125
					return $file_content;
1126
				}
1127
				fclose($fh);
1128
			}
1129
		}
1130
		return false;
1131
	}
1132

    
1133
	/**
1134
	* replace varnames with values in a string
1135
	*
1136
	* @param string $subject: stringvariable with vars placeholder
1137
	* @param array $replace: values to replace vars placeholder
1138
	* @return string
1139
	*/
1140
    function replace_vars($subject = '', &$replace = null )
1141
    {
1142
		if(is_array($replace))
1143
		{
1144
			foreach ($replace  as $key => $value) {
1145
				$subject = str_replace("{{".$key."}}", $value, $subject);
1146
			}
1147
		}
1148
		return $subject;
1149
    }
1150

    
1151
function setAccessDeniedToNewTools($sModulName)
1152
{
1153
	$oDb = WbDatabase::getInstance();
1154
	$sql = 'UPDATE `'.$oDb->getTablePrefix.'groups` '
1155
		 . 'SET `module_permissions`= TRIM(LEADING \',\' FROM (CONCAT(`module_permissions`, \','.$sModulName.'\'))) '
1156
	     . 'WHERE `group_id`<>1 AND NOT FIND_IN_SET(\''.$sModulName.'\', `module_permissions`)';
1157
	$oDb->query($sql);
1158
}
1159
	
1160
// Load module into DB
1161
function load_module($directory, $install = false)
1162
{
1163
	global $database,$admin,$MESSAGE;
1164
	$retVal = false;
1165
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1166
	{
1167
		require($directory.'/info.php');
1168
		if(isset($module_name))
1169
		{
1170
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1171
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1172
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1173
			$module_function = strtolower($module_function);
1174
			// Check that it doesn't already exist
1175
			$sqlwhere = 'WHERE `type` = \'module\' AND `directory` = \''.$module_directory.'\'';
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`=\''.$module_directory.'\', ';
1185
			$sql .= '`name`=\''.$module_name.'\', ';
1186
			$sql .= '`description`=\''.addslashes($module_description).'\', ';
1187
			$sql .= '`type`=\'module\', ';
1188
			$sql .= '`function`=\''.$module_function.'\', ';
1189
			$sql .= '`version`=\''.$module_version.'\', ';
1190
			$sql .= '`platform`=\''.$module_platform.'\', ';
1191
			$sql .= '`author`=\''.addslashes($module_author).'\', ';
1192
			$sql .= '`license`=\''.addslashes($module_license).'\'';
1193
			$sql .= $sqlwhere;
1194
			$retVal = intval($database->query($sql) ? true : false);
1195
			if($retVal && !$sqlwhere &&
1196
			   ($module_function == 'tool' || $module_function == 'page' || $module_function == 'wysiwyg')
1197
			  ) {
1198
				setAccessDeniedToNewTools($module_directory);
1199
			}
1200
			// Run installation script
1201
			if($install == true) {
1202
				if(file_exists($directory.'/install.php')) {
1203
					require($directory.'/install.php');
1204
				}
1205
			}
1206
		}
1207
        return $retVal;
1208
	}
1209
}
1210

    
1211
// Load template into DB
1212
function load_template($directory)
1213
{
1214
	global $database, $admin;
1215
	$retVal = false;
1216
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1217
	{
1218
		require($directory.'/info.php');
1219
		if(isset($template_name))
1220
		{
1221
			if(!isset($template_license)) {
1222
              $template_license = 'GNU General Public License';
1223
            }
1224
			if(!isset($template_platform) && isset($template_designed_for)) {
1225
              $template_platform = $template_designed_for;
1226
            }
1227
			if(!isset($template_function)) {
1228
              $template_function = 'template';
1229
            }
1230
			// Check that it doesn't already exist
1231
			$sqlwhere = 'WHERE `type`=\'template\' AND `directory`=\''.$template_directory.'\'';
1232
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1233
			if( $database->get_one($sql) ) {
1234
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1235
			}else{
1236
				// Load into DB
1237
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1238
				$sqlwhere = '';
1239
			}
1240
			$sql .= '`directory`=\''.$template_directory.'\', ';
1241
			$sql .= '`name`=\''.$template_name.'\', ';
1242
			$sql .= '`description`=\''.addslashes($template_description).'\', ';
1243
			$sql .= '`type`=\'template\', ';
1244
			$sql .= '`function`=\''.$template_function.'\', ';
1245
			$sql .= '`version`=\''.$template_version.'\', ';
1246
			$sql .= '`platform`=\''.$template_platform.'\', ';
1247
			$sql .= '`author`=\''.addslashes($template_author).'\', ';
1248
			$sql .= '`license`=\''.addslashes($template_license).'\' ';
1249
			$sql .= $sqlwhere;
1250
			$retVal = intval($database->query($sql) ? true : false);
1251
		}
1252
	}
1253
	return $retVal;
1254
}
1255

    
1256
// Load language into DB
1257
function load_language($file)
1258
{
1259
	global $database,$admin;
1260
	$retVal = false;
1261
	if (file_exists($file) && preg_match('#^([A-Z]{2}.php)#', basename($file)))
1262
	{
1263
		// require($file);  it's to large
1264
		// read contents of the template language file into string
1265
		$data = @file_get_contents(WB_PATH.'/languages/'.str_replace('.php','',basename($file)).'.php');
1266
		// use regular expressions to fetch the content of the variable from the string
1267
		$language_name = get_variable_content('language_name', $data, false, false);
1268
		$language_code = get_variable_content('language_code', $data, false, false);
1269
		$language_author = get_variable_content('language_author', $data, false, false);
1270
		$language_version = get_variable_content('language_version', $data, false, false);
1271
		$language_platform = get_variable_content('language_platform', $data, false, false);
1272

    
1273
		if(isset($language_name))
1274
		{
1275
			if(!isset($language_license)) { $language_license = 'GNU General Public License'; }
1276
			if(!isset($language_platform) && isset($language_designed_for)) { $language_platform = $language_designed_for; }
1277
			// Check that it doesn't already exist
1278
			$sqlwhere = 'WHERE `type`=\'language\' AND `directory`=\''.$language_code.'\'';
1279
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1280
			if( $database->get_one($sql) ) {
1281
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1282
			}else{
1283
				// Load into DB
1284
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1285
				$sqlwhere = '';
1286
			}
1287
			$sql .= '`directory`=\''.$language_code.'\', ';
1288
			$sql .= '`name`=\''.$language_name.'\', ';
1289
            $sql .= '`description`=\'\', ';
1290
			$sql .= '`function`=\'\', ';
1291
			$sql .= '`type`=\'language\', ';
1292
			$sql .= '`version`=\''.$language_version.'\', ';
1293
			$sql .= '`platform`=\''.$language_platform.'\', ';
1294
			$sql .= '`author`=\''.addslashes($language_author).'\', ';
1295
			$sql .= '`license`=\''.addslashes($language_license).'\' ';
1296
			$sql .= $sqlwhere;
1297
			$retVal = intval($database->query($sql) ? true : false);
1298
		}
1299
	}
1300
	return $retVal;
1301
}
1302

    
1303
// Upgrade module info in DB, optionally start upgrade script
1304
function upgrade_module($directory, $upgrade = false)
1305
{
1306
	global $database, $admin, $MESSAGE, $new_module_version;
1307
	$mod_directory = WB_PATH.'/modules/'.$directory;
1308
	if(file_exists($mod_directory.'/info.php'))
1309
	{
1310
		require($mod_directory.'/info.php');
1311
		if(isset($module_name))
1312
		{
1313
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1314
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1315
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1316
			$module_function = strtolower($module_function);
1317
			// Check that it does already exist
1318
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` ';
1319
			$sql .= 'WHERE `directory`=\''.$module_directory.'\'';
1320
			if( $database->get_one($sql) )
1321
			{
1322
				// Update in DB
1323
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1324
				$sql .= '`version`=\''.$module_version.'\', ';
1325
				$sql .= '`description`=\''.addslashes($module_description).'\', ';
1326
				$sql .= '`platform`=\''.$module_platform.'\', ';
1327
				$sql .= '`author`=\''.addslashes($module_author).'\', ';
1328
				$sql .= '`license`=\''.addslashes($module_license).'\' ';
1329
				$sql .= 'WHERE `directory`=\''.$module_directory.'\' ';
1330
				$database->query($sql);
1331
				if($database->is_error()) {
1332
					$admin->print_error($database->get_error());
1333
				}
1334
				// Run upgrade script
1335
				if($upgrade == true) {
1336
					if(file_exists($mod_directory.'/upgrade.php')) {
1337
						require($mod_directory.'/upgrade.php');
1338
					}
1339
				}
1340
			}
1341
		}
1342
	}
1343
}
1344

    
1345
// extracts the content of a string variable from a string (save alternative to including files)
1346
if(!function_exists('get_variable_content'))
1347
{
1348
	function get_variable_content($search, $data, $striptags=true, $convert_to_entities=true)
1349
	{
1350
		$match = '';
1351
		// search for $variable followed by 0-n whitespace then by = then by 0-n whitespace
1352
		// then either " or ' then 0-n characters then either " or ' followed by 0-n whitespace and ;
1353
		// the variable name is returned in $match[1], the content in $match[3]
1354
		if (preg_match('/(\$' .$search .')\s*=\s*("|\')(.*)\2\s*;/', $data, $match))
1355
		{
1356
			if(strip_tags(trim($match[1])) == '$' .$search) {
1357
				// variable name matches, return it's value
1358
				$match[3] = ($striptags == true) ? strip_tags($match[3]) : $match[3];
1359
				$match[3] = ($convert_to_entities == true) ? htmlentities($match[3]) : $match[3];
1360
				return $match[3];
1361
			}
1362
		}
1363
		return false;
1364
	}
1365
}
1366

    
1367
/*
1368
 * @param string $modulname: like saved in addons.directory
1369
 * @param boolean $source: true reads from database, false from info.php
1370
 * @return string:  the version as string, if not found returns null
1371
 */
1372

    
1373
	function get_modul_version($modulname, $source = true)
1374
	{
1375
		global $database;
1376
		$version = null;
1377
		if( $source != true )
1378
		{
1379
			$sql  = 'SELECT `version` FROM `'.TABLE_PREFIX.'addons` ';
1380
			$sql .= 'WHERE `directory`=\''.$modulname.'\'';
1381
			$version = $database->get_one($sql);
1382
		} else {
1383
			$info_file = WB_PATH.'/modules/'.$modulname.'/info.php';
1384
			if(file_exists($info_file)) {
1385
				if(($info_file = file_get_contents($info_file))) {
1386
					$version = get_variable_content('module_version', $info_file, false, false);
1387
					$version = ($version !== false) ? $version : null;
1388
				}
1389
			}
1390
		}
1391
		return $version;
1392
	}
1393

    
1394
/*
1395
 * @param string $varlist: commaseperated list of varnames to move into global space
1396
 * @return bool:  false if one of the vars already exists in global space (error added to msgQueue)
1397
 */
1398
	function vars2globals_wrapper($varlist)
1399
	{
1400
		$retval = true;
1401
		if( $varlist != '')
1402
		{
1403
			$vars = explode(',', $varlist);
1404
			foreach( $vars as $var)
1405
			{
1406
				if( isset($GLOBALS[$var]) ){
1407
					ErrorLog::write( 'variabe $'.$var.' already defined in global space!!',__FILE__, __FUNCTION__, __LINE__);
1408
					$retval = false;
1409
				}else {
1410
					global $$var;
1411
				}
1412
			}
1413
		}
1414
		return $retval;
1415
	}
1416

    
1417
/*
1418
 * filter directory traversal more thoroughly, thanks to hal 9000
1419
 * @param string $dir: directory relative to MEDIA_DIRECTORY
1420
 * @param bool $with_media_dir: true when to include MEDIA_DIRECTORY
1421
 * @return: false if directory traversal detected, real path if not
1422
 */
1423
	function check_media_path($directory, $with_media_dir = true)
1424
	{
1425
		$md = ($with_media_dir) ? MEDIA_DIRECTORY : '';
1426
		$dir = realpath(WB_PATH . $md . '/' . utf8_decode($directory));
1427
		$required = realpath(WB_PATH . MEDIA_DIRECTORY);
1428
		if (strstr($dir, $required)) {
1429
			return $dir;
1430
		} else {
1431
			return false;
1432
		}
1433
	}
1434

    
1435
/*
1436
urlencode function and rawurlencode are mostly based on RFC 1738.
1437
However, since 2005 the current RFC in use for URIs standard is RFC 3986.
1438
Here is a function to encode URLs according to RFC 3986.
1439
*/
1440
if(!function_exists('url_encode')){
1441
	function url_encode($string) {
1442
	    $string = html_entity_decode($string,ENT_QUOTES,'UTF-8');
1443
	    $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
1444
	    $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
1445
	    return str_replace($entities,$replacements, rawurlencode($string));
1446
	}
1447
}
1448

    
1449
if(!function_exists('rebuild_all_accessfiles')){
1450
	function rebuild_all_accessfiles($bShowDetails=false ) {
1451
        global $database;
1452
    	$aRetval = array();
1453
    	/**
1454
    	 * try to remove access files and build new folder protect files
1455
    	 */
1456
//   	$sTempDir = (defined('PAGES_DIRECTORY') && (PAGES_DIRECTORY != '') ? PAGES_DIRECTORY : '').'/';
1457
        $sTreeToDelete = WbAdaptor::getInstance()->AppPath.WbAdaptor::getInstance()->PagesDir;
1458
    	if(($sTreeToDelete!='') && is_writeable($sTreeToDelete)==true) {
1459
//    	 	if(rm_full_dir (WB_PATH.$sTempDir, true, $aProtectedFiles )==false) {
1460
//    			$aRetval[] = 'Could not delete existing access files';
1461
//    	 	}
1462
			$aDeleteLog = array();	// <<< ge?ndert
1463
            DeleteAccessFilesTree($sTreeToDelete, $aDeleteLog);	// <<< ge?ndert
1464
            if($bShowDetails) {
1465
                $aRetval = array_merge($aRetval, $aDeleteLog);	// <<< ge?ndert
1466
            }
1467
    	}
1468

    
1469
		$aRetval = array_merge($aRetval,createFolderProtectFile(rtrim( WB_PATH.PAGES_DIRECTORY,'/') ));
1470

    
1471
    	/**
1472
    	 * Reformat/rebuild all existing access files
1473
    	 */
1474
//        $sql = 'SELECT `page_id`,`root_parent`,`link`, `level` FROM `'.TABLE_PREFIX.'pages` ORDER BY `link`';
1475
		$sql  = 'SELECT `page_id`,`root_parent`,`link`, `level` ';
1476
		$sql .= 'FROM `'.TABLE_PREFIX.'pages` ';
1477
		$sql .= 'WHERE `link` != \'\' ORDER BY `link` ';
1478
        if (($oPage = $database->query($sql)))
1479
        {
1480
            $x = 0;
1481
            while (($page = $oPage->fetchRow(MYSQL_ASSOC)))
1482
            {
1483
                // Work out level
1484
                $level = level_count($page['page_id']);
1485
                // Work out root parent
1486
                $root_parent = root_parent($page['page_id']);
1487
                // Work out page trail
1488
                $page_trail = get_page_trail($page['page_id']);
1489
                // Update page with new level and link
1490
                $sql  = 'UPDATE `'.TABLE_PREFIX.'pages` SET ';
1491
                $sql .= '`root_parent` = '.$root_parent.', ';
1492
                $sql .= '`level` = '.$level.', ';
1493
                $sql .= '`page_trail` = "'.$page_trail.'" ';
1494
                $sql .= 'WHERE `page_id` = '.$page['page_id'];
1495

    
1496
                if(!$database->query($sql)) {}
1497
                $filename = WB_PATH.PAGES_DIRECTORY.$page['link'].PAGE_EXTENSION;
1498
                create_access_file($filename, $page['page_id'], $page['level']);
1499
                $x++;
1500
            }
1501
            $aRetval[] = 'Number of new formated access files: '.$x.'';
1502
        }
1503
    return $aRetval;
1504
	}
1505
}
1506

    
1507
if(!function_exists('upgrade_modules')){
1508
	function upgrade_modules($aModuleList) {
1509
        global $database;
1510
    	foreach($aModuleList as $sModul) {
1511
    		if(file_exists(WB_PATH.'/modules/'.$sModul.'/upgrade.php')) {
1512
    			$currModulVersion = get_modul_version ($sModul, false);
1513
    			$newModulVersion =  get_modul_version ($sModul, true);
1514
    			if((version_compare($currModulVersion, $newModulVersion) <= 0)) {
1515
    				require(WB_PATH.'/modules/'.$sModul.'/upgrade.php');
1516
    			}
1517
    		}
1518
    	}
1519
    }
1520
}
1521

    
(29-29/34)