Project

General

Profile

1 1352 Luisehahne
<?php
2
/**
3
 *
4
 * @category        frontend
5
 * @package         framework
6 1705 Luisehahne
 * @author          Ryan Djurovich,WebsiteBaker Project
7 1908 Luisehahne
 * @copyright       2009-2013, WebsiteBaker Org. e.V.
8
 * @link            http://www.websitebaker.org/
9 1352 Luisehahne
 * @license         http://www.gnu.org/licenses/gpl.html
10 1908 Luisehahne
 * @platform        WebsiteBaker 2.8.4
11 1374 Luisehahne
 * @requirements    PHP 5.2.2 and higher
12 1352 Luisehahne
 * @version         $Id$
13 1841 Luisehahne
 * @filesource      $HeadURL$
14 1352 Luisehahne
 * @lastmodified    $Date$
15
 *
16 1866 Luisehahne
 */
17 1496 DarkViper
/* -------------------------------------------------------- */
18
// Must include code to stop this file being accessed directly
19 1499 DarkViper
if(!defined('WB_PATH')) {
20
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
21
	throw new IllegalFileException();
22
}
23 1496 DarkViper
/* -------------------------------------------------------- */
24 1352 Luisehahne
// Define that this file has been loaded
25
define('FUNCTIONS_FILE_LOADED', true);
26
27 1977 Luisehahne
28 1365 Luisehahne
/**
29 1977 Luisehahne
 * Delete an Accessfiles Tree
30
 * @param  string  $sDirToDelete
31
 * @return boolean true/false
32
 * @description    Delete all accessfiles and its depending directory tree
33
 *                 inside the given directory.
34
 */
35
36
function DeleteAccessFilesTree($sDirToDelete)
37
{
38
        $sBaseDir = realpath($sDirToDelete);
39
        if( $sBaseDir !== false) {
40
		$sBaseDir = rtrim(str_replace('\\', '/', $sBaseDir), '/') . '/';
41
		// scan start directory for access files
42
		foreach (glob($sBaseDir . '*.php', GLOB_MARK) as $sItem) {
43
            $sItem = str_replace('\\', '/', $sItem);
44
			try{
45
				$oAccFile = new AccessFile($sItem);
46
				$oAccFile->delete();
47
			}catch(AccessFileIsNoAccessfileException $e) {
48
				continue;
49
			}
50
		}
51
		return true;
52
	}
53
	return false;
54
}
55
56
/**
57 1365 Luisehahne
 * @description: recursively delete a non empty directory
58
 * @param string $directory :
59
 * @param bool $empty : true if you want the folder just emptied, but not deleted
60
 *                      false, or just simply leave it out, the given directory will be deleted, as well
61 1977 Luisehahne
 * @param array $aProtectedFiles optional list of protected files, full path needed
62 1676 Luisehahne
 * @return boolean: true/false
63 1365 Luisehahne
 * @from http://www.php.net/manual/de/function.rmdir.php#98499
64
 */
65 1977 Luisehahne
function rm_full_dir($directory, $empty = false, $aProtectedFiles = null)
66 1676 Luisehahne
{
67 1977 Luisehahne
	$directory = rtrim(str_replace('\\','/',$directory),'/');
68
	if($aProtectedFiles == null) {
69
		$aProtectedFiles = array();
70
	}
71 1765 Luisehahne
    $iErrorReporting = error_reporting(0);
72 1977 Luisehahne
73 1676 Luisehahne
    if (is_file( $directory )&& is_writable( $directory )) {
74 1977 Luisehahne
		if(!in_array(($directory), $aProtectedFiles)) {
75
			$retval = unlink($directory);
76
			clearstatcache();
77
			error_reporting($iErrorReporting);
78
			return $retval;
79
		}else {
80
			return true;
81
		}
82 1352 Luisehahne
    }
83 1676 Luisehahne
    if(!is_writable($directory) || !is_dir($directory)) {
84 1765 Luisehahne
        error_reporting($iErrorReporting);
85 1365 Luisehahne
        return false;
86 1495 DarkViper
    } elseif(!is_readable($directory)) {
87 1765 Luisehahne
        error_reporting($iErrorReporting);
88 1365 Luisehahne
        return false;
89
    } else {
90
        $directoryHandle = opendir($directory);
91
        while ($contents = readdir($directoryHandle))
92
		{
93
            if($contents != '.' && $contents != '..')
94 1352 Luisehahne
			{
95 1365 Luisehahne
                $path = $directory . "/" . $contents;
96 1495 DarkViper
                if(is_dir($path)) {
97 1977 Luisehahne
                    rm_full_dir($path, false, $aProtectedFiles);
98 1365 Luisehahne
                } else {
99 1977 Luisehahne
					if(!in_array($path, $aProtectedFiles)) {
100
				        unlink($path);
101
						clearstatcache();
102
					}
103 1365 Luisehahne
                }
104 1352 Luisehahne
            }
105 1365 Luisehahne
        }
106
        closedir($directoryHandle);
107 1495 DarkViper
        if($empty == false) {
108 1676 Luisehahne
            if(is_dir($directory) && is_writable(dirname($directory))) {
109 1765 Luisehahne
                $retval = rmdir($directory);
110
                error_reporting($iErrorReporting);
111
                return $retval;
112 1676 Luisehahne
            } else {
113 1765 Luisehahne
                error_reporting($iErrorReporting);
114 1676 Luisehahne
				return false;
115 1352 Luisehahne
            }
116
        }
117 1765 Luisehahne
        error_reporting($iErrorReporting);
118 1365 Luisehahne
        return true;
119
    }
120 1352 Luisehahne
}
121
122
/*
123
 * returns a recursive list of all subdirectories from a given directory
124
 * @access  public
125
 * @param   string  $directory: from this dir the recursion will start
126
 * @param   bool    $show_hidden:  if set to TRUE also hidden dirs (.dir) will be shown
127
 * @return  array
128
 * example:
129
 *  /srv/www/httpdocs/wb/media/a/b/c/
130
 *  /srv/www/httpdocs/wb/media/a/b/d/
131
 * directory_list('/srv/www/httpdocs/wb/media/') will return:
132
 *  /a
133
 *  /a/b
134
 *  /a/b/c
135
 *  /a/b/d
136
 */
137
 function directory_list($directory, $show_hidden = false)
138
{
139
	$result_list = array();
140
	if (is_dir($directory))
141
    {
142
    	$dir = dir($directory); // Open the directory
143
    	while (false !== $entry = $dir->read()) // loop through the directory
144
		{
145
			if($entry == '.' || $entry == '..') { continue; } // Skip pointers
146
			if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
147 1495 DarkViper
    		if (is_dir("$directory/$entry")) { // Add dir and contents to list
148 1352 Luisehahne
    			$result_list = array_merge($result_list, directory_list("$directory/$entry"));
149
    			$result_list[] = "$directory/$entry";
150
    		}
151
    	}
152
        $dir->close();
153
    }
154 1365 Luisehahne
	// sorting
155 1495 DarkViper
	if(natcasesort($result_list)) {
156 1365 Luisehahne
		// new indexing
157
		$result_list = array_merge($result_list);
158
	}
159 1352 Luisehahne
	return $result_list; // Now return the list
160
}
161
162
// Function to open a directory and add to a dir list
163
function chmod_directory_contents($directory, $file_mode)
164
{
165
	if (is_dir($directory))
166
    {
167
    	// Set the umask to 0
168
    	$umask = umask(0);
169
    	// Open the directory then loop through its contents
170
    	$dir = dir($directory);
171
    	while (false !== $entry = $dir->read())
172
		{
173
    		// Skip pointers
174
    		if($entry[0] == '.') { continue; }
175
    		// Chmod the sub-dirs contents
176 1495 DarkViper
    		if(is_dir("$directory/$entry")) {
177 1352 Luisehahne
    			chmod_directory_contents($directory.'/'.$entry, $file_mode);
178
    		}
179
    		change_mode($directory.'/'.$entry);
180
    	}
181
        $dir->close();
182
    	// Restore the umask
183
    	umask($umask);
184
    }
185
}
186
187 1365 Luisehahne
/**
188
* Scan a given directory for dirs and files.
189
*
190
* usage: scan_current_dir ($root = '' )
191
*
192
* @param     $root   set a absolute rootpath as string. if root is empty the current path will be scan
193
* @param     $search set a search pattern for files, empty search brings all files
194
* @access    public
195
* @return    array    returns a natsort array with keys 'path' and 'filename'
196
*
197
*/
198
if(!function_exists('scan_current_dir'))
199
{
200
	function scan_current_dir($root = '', $search = '/.*/')
201
	{
202
	    $FILE = array();
203
		$array = array();
204
	    clearstatcache();
205
	    $root = empty ($root) ? getcwd() : $root;
206
	    if (($handle = opendir($root)))
207
	    {
208
	    // Loop through the files and dirs an add to list  DIRECTORY_SEPARATOR
209
	        while (false !== ($file = readdir($handle)))
210
	        {
211
	            if (substr($file, 0, 1) != '.' && $file != 'index.php')
212
	            {
213 1495 DarkViper
	                if (is_dir($root.'/'.$file)) {
214 1365 Luisehahne
	                    $FILE['path'][] = $file;
215 1495 DarkViper
	                } elseif (preg_match($search, $file, $array) ) {
216 1365 Luisehahne
	                    $FILE['filename'][] = $array[0];
217
	                }
218
	            }
219
	        }
220
	        $close_verz = closedir($handle);
221
	    }
222
		// sorting
223 1495 DarkViper
	    if (isset ($FILE['path']) && natcasesort($FILE['path'])) {
224 1365 Luisehahne
			// new indexing
225
	        $FILE['path'] = array_merge($FILE['path']);
226
	    }
227
		// sorting
228 1495 DarkViper
	    if (isset ($FILE['filename']) && natcasesort($FILE['filename'])) {
229 1365 Luisehahne
			// new indexing
230
	        $FILE['filename'] = array_merge($FILE['filename']);
231
	    }
232
	    return $FILE;
233
	}
234
}
235
236 1352 Luisehahne
// Function to open a directory and add to a file list
237
function file_list($directory, $skip = array(), $show_hidden = false)
238
{
239
	$result_list = array();
240
	if (is_dir($directory))
241
    {
242
    	$dir = dir($directory); // Open the directory
243
		while (false !== ($entry = $dir->read())) // loop through the directory
244
		{
245
			if($entry == '.' || $entry == '..') { continue; } // Skip pointers
246
			if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
247
			if( sizeof($skip) > 0 && in_array($entry, $skip) ) { continue; } // Check if we to skip anything else
248 1495 DarkViper
			if(is_file( $directory.'/'.$entry)) { // Add files to list
249 1352 Luisehahne
				$result_list[] = $directory.'/'.$entry;
250
			}
251
		}
252
		$dir->close(); // Now close the folder object
253
	}
254 1365 Luisehahne
255
    // make the list nice. Not all OS do this itself
256 1495 DarkViper
	if(natcasesort($result_list)) {
257 1365 Luisehahne
		$result_list = array_merge($result_list);
258 1495 DarkViper
	}
259 1352 Luisehahne
	return $result_list;
260
}
261
262 1824 Luisehahne
function remove_home_subs($directory = '/', $home_folders = '')
263
{
264
	if( ($handle = opendir(WB_PATH.MEDIA_DIRECTORY.$directory)) )
265
	{
266
		// Loop through the dirs to check the home folders sub-dirs are not shown
267
		while(false !== ($file = readdir($handle)))
268
		{
269
			if($file[0] != '.' && $file != 'index.php')
270
			{
271
				if(is_dir(WB_PATH.MEDIA_DIRECTORY.$directory.'/'.$file))
272
				{
273
					if($directory != '/') {
274
						$file = $directory.'/'.$file;
275
					}else {
276
						$file = '/'.$file;
277
					}
278
					foreach($home_folders AS $hf)
279
					{
280
						$hf_length = strlen($hf);
281
						if($hf_length > 0) {
282
							if(substr($file, 0, $hf_length+1) == $hf) {
283
								$home_folders[$file] = $file;
284
							}
285
						}
286
					}
287
					$home_folders = remove_home_subs($file, $home_folders);
288
				}
289
			}
290
		}
291
	}
292
	return $home_folders;
293
}
294
295 1352 Luisehahne
// Function to get a list of home folders not to show
296
function get_home_folders()
297
{
298
	global $database, $admin;
299
	$home_folders = array();
300
	// Only return home folders is this feature is enabled
301
	// and user is not admin
302
//	if(HOME_FOLDERS AND ($_SESSION['GROUP_ID']!='1')) {
303
	if(HOME_FOLDERS AND (!in_array('1',explode(',', $_SESSION['GROUPS_ID']))))
304
	{
305 1495 DarkViper
		$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
306
		$sql .= 'WHERE `home_folder`!=\''.$admin->get_home_folder().'\'';
307 1352 Luisehahne
		$query_home_folders = $database->query($sql);
308
		if($query_home_folders->numRows() > 0)
309
		{
310 1495 DarkViper
			while($folder = $query_home_folders->fetchRow()) {
311 1352 Luisehahne
				$home_folders[$folder['home_folder']] = $folder['home_folder'];
312
			}
313
		}
314
		$home_folders = remove_home_subs('/', $home_folders);
315
	}
316
	return $home_folders;
317
}
318
319 1365 Luisehahne
/*
320
 * @param object &$wb: $wb from frontend or $admin from backend
321
 * @return array: list of new entries
322
 * @description: callback remove path in files/dirs stored in array
323
 * @example: array_walk($array,'remove_path',PATH);
324
 */
325
//
326
function remove_path(&$path, $key, $vars = '')
327
{
328
	$path = str_replace($vars, '', $path);
329
}
330
/*
331
 * @param object &$wb: $wb from frontend or $admin from backend
332
 * @return array: list of ro-dirs
333
 * @description: returns a list of directories beyound /wb/media which are ReadOnly for current user
334
 */
335
function media_dirs_ro( &$wb )
336
{
337
	global $database;
338
	// if user is admin or home-folders not activated then there are no restrictions
339
	$allow_list = array();
340 1495 DarkViper
	if( $wb->get_user_id() == 1 || !HOME_FOLDERS ) {
341 1365 Luisehahne
		return array();
342
	}
343
	// at first read any dir and subdir from /media
344
	$full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
345
	// add own home_folder to allow-list
346 1495 DarkViper
	if( $wb->get_home_folder() ) {
347 1365 Luisehahne
		// old: $allow_list[] = get_home_folder();
348
		$allow_list[] = $wb->get_home_folder();
349
	}
350
	// get groups of current user
351
	$curr_groups = $wb->get_groups_id();
352
	// if current user is in admin-group
353 1495 DarkViper
	if( ($admin_key = array_search('1', $curr_groups)) !== false)
354 1365 Luisehahne
	{
355
		// remove admin-group from list
356
		unset($curr_groups[$admin_key]);
357
		// search for all users where the current user is admin from
358
		foreach( $curr_groups as $group)
359
		{
360
			$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
361
			$sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
362 1495 DarkViper
			if( ($res_hf = $database->query($sql)) != null ) {
363
				while( $rec_hf = $res_hf->fetchrow() ) {
364 1365 Luisehahne
					$allow_list[] = $rec_hf['home_folder'];
365
				}
366
			}
367
		}
368
	}
369
	$tmp_array = $full_list;
370
	// create a list for readonly dir
371
    $array = array();
372
	while( sizeof($tmp_array) > 0)
373
	{
374
        $tmp = array_shift($tmp_array);
375
        $x = 0;
376 1495 DarkViper
		while($x < sizeof($allow_list)) {
377 1365 Luisehahne
			if(strpos ($tmp,$allow_list[$x])) {
378
				$array[] = $tmp;
379
			}
380
			$x++;
381
		}
382
	}
383
	$full_list = array_diff( $full_list, $array );
384
	$tmp = array();
385
	$full_list = array_merge($tmp,$full_list);
386
	return $full_list;
387
}
388
389
/*
390
 * @param object &$wb: $wb from frontend or $admin from backend
391
 * @return array: list of rw-dirs
392
 * @description: returns a list of directories beyound /wb/media which are ReadWrite for current user
393
 */
394
function media_dirs_rw ( &$wb )
395
{
396
	global $database;
397
	// if user is admin or home-folders not activated then there are no restrictions
398
	// at first read any dir and subdir from /media
399
	$full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
400
    $array = array();
401
	$allow_list = array();
402 1495 DarkViper
	if( ($wb->ami_group_member('1')) && !HOME_FOLDERS ) {
403 1365 Luisehahne
		return $full_list;
404
	}
405
	// add own home_folder to allow-list
406 1495 DarkViper
	if( $wb->get_home_folder() ) {
407 1365 Luisehahne
	  	$allow_list[] = $wb->get_home_folder();
408
	} else {
409
		$array = $full_list;
410
	}
411
	// get groups of current user
412
	$curr_groups = $wb->get_groups_id();
413
	// if current user is in admin-group
414
	if( ($admin_key = array_search('1', $curr_groups)) == true)
415
	{
416
		// remove admin-group from list
417
		// unset($curr_groups[$admin_key]);
418
		// search for all users where the current user is admin from
419
		foreach( $curr_groups as $group)
420
		{
421
			$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
422
			$sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
423 1495 DarkViper
			if( ($res_hf = $database->query($sql)) != null ) {
424
				while( $rec_hf = $res_hf->fetchrow() ) {
425 1365 Luisehahne
					$allow_list[] = $rec_hf['home_folder'];
426
				}
427
			}
428
		}
429
	}
430
431
	$tmp_array = $full_list;
432
	// create a list for readwrite dir
433
	while( sizeof($tmp_array) > 0)
434
	{
435
        $tmp = array_shift($tmp_array);
436
        $x = 0;
437 1495 DarkViper
		while($x < sizeof($allow_list)) {
438 1365 Luisehahne
			if(strpos ($tmp,$allow_list[$x])) {
439
				$array[] = $tmp;
440
			}
441
			$x++;
442
		}
443
	}
444
	$tmp = array();
445
    $array = array_unique($array);
446
	$full_list = array_merge($tmp,$array);
447
    unset($array);
448
    unset($allow_list);
449
	return $full_list;
450
}
451
452 1352 Luisehahne
// Function to create directories
453 1556 Luisehahne
function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE, $recursive=true)
454 1352 Luisehahne
{
455 1866 Luisehahne
	$bRetval = is_dir($dir_name);
456
	if(!$bRetval)
457 1352 Luisehahne
    {
458 1759 Luisehahne
		// To create the folder with 0777 permissions, we need to set umask to zero.
459
		$oldumask = umask(0) ;
460 1866 Luisehahne
		$bRetval = mkdir($dir_name, $dir_mode|0711, $recursive);
461 1759 Luisehahne
		umask( $oldumask ) ;
462 1352 Luisehahne
	}
463 1866 Luisehahne
	return $bRetval;
464 1352 Luisehahne
}
465
466 1651 darkviper
/**
467
 * Function to chmod files and/or directories
468 1653 darkviper
 * the function also prevents the owner to loose rw-rights
469 1651 darkviper
 * @param string $sName
470
 * @param int rights in dec-value. 0= use wb-defaults
471 1676 Luisehahne
 * @return bool
472 1651 darkviper
 */
473 1866 Luisehahne
function change_mode($sName, $iMode = 0 )
474 1352 Luisehahne
{
475 1651 darkviper
	$bRetval = true;
476 1759 Luisehahne
    $iErrorReporting = error_reporting(0);
477 1653 darkviper
	$iMode = intval($iMode) & 0777; // sanitize value
478 1705 Luisehahne
	if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
479 1651 darkviper
	{ // Only chmod if os is not windows
480
		$bRetval = false;
481
		if(!$iMode) {
482
			$iMode = (is_file($sName) ? octdec(STRING_FILE_MODE) : octdec(STRING_DIR_MODE));
483 1352 Luisehahne
		}
484 1653 darkviper
		$iMode |= 0600; // set o+rw
485 1651 darkviper
		if(is_writable($sName)) {
486
			$bRetval = chmod($sName, $iMode);
487 1352 Luisehahne
		}
488
	}
489 1759 Luisehahne
    error_reporting($iErrorReporting);
490 1651 darkviper
	return $bRetval;
491 1352 Luisehahne
}
492
493
// Function to figure out if a parent exists
494
function is_parent($page_id)
495
{
496
	global $database;
497
	// Get parent
498
	$sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
499
	$parent = $database->get_one($sql);
500
	// If parent isnt 0 return its ID
501 1495 DarkViper
	if(is_null($parent)) {
502 1352 Luisehahne
		return false;
503 1495 DarkViper
	}else {
504 1352 Luisehahne
		return $parent;
505
	}
506
}
507
508
// Function to work out level
509
function level_count($page_id)
510
{
511
	global $database;
512
	// Get page parent
513
	$sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
514
	$parent = $database->get_one($sql);
515 1495 DarkViper
	if($parent > 0)
516 1352 Luisehahne
	{	// Get the level of the parent
517
		$sql = 'SELECT `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$parent;
518
		$level = $database->get_one($sql);
519
		return $level+1;
520 1495 DarkViper
	}else {
521 1352 Luisehahne
		return 0;
522
	}
523
}
524
525
// Function to work out root parent
526
function root_parent($page_id)
527
{
528
	global $database;
529
	// Get page details
530
	$sql = 'SELECT `parent`, `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
531 1754 Luisehahne
532 1352 Luisehahne
	$query_page = $database->query($sql);
533 1759 Luisehahne
	$fetch_page = $query_page->fetchRow(MYSQL_ASSOC);
534 1352 Luisehahne
	$parent = $fetch_page['parent'];
535 1495 DarkViper
	$level = $fetch_page['level'];
536
	if($level == 1) {
537 1352 Luisehahne
		return $parent;
538 1754 Luisehahne
	} elseif($parent == 0) {
539 1352 Luisehahne
		return $page_id;
540 1754 Luisehahne
	} else {	// Figure out what the root parents id is
541 1352 Luisehahne
		$parent_ids = array_reverse(get_parent_ids($page_id));
542
		return $parent_ids[0];
543
	}
544
}
545
546
// Function to get page title
547
function get_page_title($id)
548
{
549
	global $database;
550
	// Get title
551
	$sql = 'SELECT `page_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
552
	$page_title = $database->get_one($sql);
553
	return $page_title;
554
}
555
556
// Function to get a pages menu title
557
function get_menu_title($id)
558
{
559
	global $database;
560
	// Get title
561
	$sql = 'SELECT `menu_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
562
	$menu_title = $database->get_one($sql);
563
	return $menu_title;
564
}
565 1908 Luisehahne
// Function to get a pages filename in sub
566
function get_sub_filename($id)
567
{
568
	$database = WbDatabase::getInstance();
569
	// Get title
570
	$sql = 'SELECT `link` FROM `'.TABLE_PREFIX.'pages` '
571
	      .'WHERE `page_id` = '.$id.' '
572
	      .  'AND `level`>=0';
573
	$sRetval = basename($database->get_one($sql));
574
	return $sRetval;
575
}
576 1352 Luisehahne
577
// Function to get all parent page titles
578
function get_parent_titles($parent_id)
579
{
580 1908 Luisehahne
	$titles[] = get_sub_filename($parent_id);
581 1495 DarkViper
	if(is_parent($parent_id) != false) {
582 1352 Luisehahne
		$parent_titles = get_parent_titles(is_parent($parent_id));
583
		$titles = array_merge($titles, $parent_titles);
584
	}
585
	return $titles;
586
}
587
588
// Function to get all parent page id's
589
function get_parent_ids($parent_id)
590
{
591
	$ids[] = $parent_id;
592 1495 DarkViper
	if(is_parent($parent_id) != false) {
593 1352 Luisehahne
		$parent_ids = get_parent_ids(is_parent($parent_id));
594
		$ids = array_merge($ids, $parent_ids);
595
	}
596
	return $ids;
597
}
598
599
// Function to genereate page trail
600 1495 DarkViper
function get_page_trail($page_id)
601
{
602 1352 Luisehahne
	return implode(',', array_reverse(get_parent_ids($page_id)));
603
}
604
605
// Function to get all sub pages id's
606 1514 Luisehahne
function get_subs($parent, array $subs )
607 1352 Luisehahne
{
608
	// Connect to the database
609
	global $database;
610
	// Get id's
611
	$sql = 'SELECT `page_id` FROM `'.TABLE_PREFIX.'pages` WHERE `parent` = '.$parent;
612 1514 Luisehahne
	if( ($query = $database->query($sql)) ) {
613 1759 Luisehahne
		while($fetch = $query->fetchRow(MYSQL_ASSOC)) {
614 1352 Luisehahne
			$subs[] = $fetch['page_id'];
615 1514 Luisehahne
			// Get subs of this sub recursive
616 1352 Luisehahne
			$subs = get_subs($fetch['page_id'], $subs);
617
		}
618
	}
619
	// Return subs array
620
	return $subs;
621
}
622
623
// Function as replacement for php's htmlspecialchars()
624
// Will not mangle HTML-entities
625
function my_htmlspecialchars($string)
626
{
627
	$string = preg_replace('/&(?=[#a-z0-9]+;)/i', '__amp;_', $string);
628
	$string = strtr($string, array('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;', '\''=>'&#39;'));
629
	$string = preg_replace('/__amp;_(?=[#a-z0-9]+;)/i', '&', $string);
630
	return($string);
631
}
632
633
// Convert a string from mixed html-entities/umlauts to pure $charset_out-umlauts
634
// Will replace all numeric and named entities except &gt; &lt; &apos; &quot; &#039; &nbsp;
635
// In case of error the returned string is unchanged, and a message is emitted.
636
function entities_to_umlauts($string, $charset_out=DEFAULT_CHARSET)
637
{
638
	require_once(WB_PATH.'/framework/functions-utf8.php');
639
	return entities_to_umlauts2($string, $charset_out);
640
}
641
642
// Will convert a string in $charset_in encoding to a pure ASCII string with HTML-entities.
643
// In case of error the returned string is unchanged, and a message is emitted.
644
function umlauts_to_entities($string, $charset_in=DEFAULT_CHARSET)
645
{
646
	require_once(WB_PATH.'/framework/functions-utf8.php');
647
	return umlauts_to_entities2($string, $charset_in);
648
}
649
650
// Function to convert a page title to a page filename
651
function page_filename($string)
652
{
653
	require_once(WB_PATH.'/framework/functions-utf8.php');
654
	$string = entities_to_7bit($string);
655
	// Now remove all bad characters
656
	$bad = array(
657
	'\'', /* /  */ '"', /* " */	'<', /* < */	'>', /* > */
658
	'{', /* { */	'}', /* } */	'[', /* [ */	']', /* ] */	'`', /* ` */
659
	'!', /* ! */	'@', /* @ */	'#', /* # */	'$', /* $ */	'%', /* % */
660
	'^', /* ^ */	'&', /* & */	'*', /* * */	'(', /* ( */	')', /* ) */
661
	'=', /* = */	'+', /* + */	'|', /* | */	'/', /* / */	'\\', /* \ */
662
	';', /* ; */	':', /* : */	',', /* , */	'?' /* ? */
663
	);
664
	$string = str_replace($bad, '', $string);
665
	// replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
666
	$string = preg_replace(array('/\.+/', '/\.+$/'), array('.', ''), $string);
667
	// Now replace spaces with page spcacer
668
	$string = trim($string);
669
	$string = preg_replace('/(\s)+/', PAGE_SPACER, $string);
670
	// Now convert to lower-case
671
	$string = strtolower($string);
672
	// If there are any weird language characters, this will protect us against possible problems they could cause
673
	$string = str_replace(array('%2F', '%'), array('/', ''), urlencode($string));
674
	// Finally, return the cleaned string
675
	return $string;
676
}
677
678 1457 Luisehahne
// Function to convert a desired media filename to a clean mediafilename
679 1352 Luisehahne
function media_filename($string)
680
{
681
	require_once(WB_PATH.'/framework/functions-utf8.php');
682
	$string = entities_to_7bit($string);
683
	// Now remove all bad characters
684 1454 DarkViper
	$bad = array('\'','"','`','!','@','#','$','%','^','&','*','=','+','|','/','\\',';',':',',','?');
685 1352 Luisehahne
	$string = str_replace($bad, '', $string);
686
	// replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
687 1454 DarkViper
	$string = preg_replace(array('/\.+/', '/\.+$/', '/\s/'), array('.', '', '_'), $string);
688 1352 Luisehahne
	// Clean any page spacers at the end of string
689
	$string = trim($string);
690
	// Finally, return the cleaned string
691
	return $string;
692
}
693
694
// Function to work out a page link
695
if(!function_exists('page_link'))
696
{
697
	function page_link($link)
698
	{
699
		global $admin;
700
		return $admin->page_link($link);
701
	}
702
}
703
704 1866 Luisehahne
705 1468 Luisehahne
// Create a new directory and/or protected file in the given directory
706 1477 Luisehahne
function createFolderProtectFile($sAbsDir='',$make_dir=true)
707 1457 Luisehahne
{
708
	global $admin, $MESSAGE;
709
	$retVal = array();
710 1977 Luisehahne
	$wb_path   = rtrim(str_replace('\/\\', '/', WB_PATH), '/');
711
	$sAppPath  = rtrim(str_replace('\/\\', '/', WB_PATH), '/').'/';
712
	if( ($sAbsDir=='') || ($sAbsDir == $sAppPath) ) { return $retVal;}
713 1457 Luisehahne
714
	if ( $make_dir==true ) {
715
		// Check to see if the folder already exists
716 1866 Luisehahne
		if(is_readable($sAbsDir)) {
717 1477 Luisehahne
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_EXISTS'];
718 1457 Luisehahne
		}
719 1977 Luisehahne
		if (!make_dir($sAbsDir) && !is_dir($sAbsDir) ) {
720 1477 Luisehahne
			$retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_NOT_MADE'];
721
		} else {
722
			change_mode($sAbsDir);
723 1457 Luisehahne
		}
724 1866 Luisehahne
		return $retVal;
725 1457 Luisehahne
	}
726
727 1908 Luisehahne
//$retVal[] = $sAbsDir;
728
//return $retVal;
729
730 1477 Luisehahne
	if( is_writable($sAbsDir) )
731 1457 Luisehahne
	{
732 1477 Luisehahne
        // if(file_exists($sAbsDir.'/index.php')) { unlink($sAbsDir.'/index.php'); }
733 1457 Luisehahne
	    // Create default "index.php" file
734 1977 Luisehahne
		$iBackSteps = substr_count(str_replace($sAppPath, '', $sAbsDir), '/');
735
		$sIndexFile = str_repeat('../', $iBackSteps).'index.php';
736 1457 Luisehahne
		$sResponse  = $_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently';
737
		$content =
738
			'<?php'."\n".
739
			'// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
740
			'// *** Creation date: '.date('c')."\n".
741
			'// *** Do not modify this file manually'."\n".
742
			'// *** WB will rebuild this file from time to time!!'."\n".
743
			'// *************************************************'."\n".
744
			"\t".'header(\''.$sResponse.'\');'."\n".
745
			"\t".'header(\'Location: '.WB_URL.'/index.php\');'."\n".
746
			'// *************************************************'."\n";
747 1477 Luisehahne
		$filename = $sAbsDir.'/index.php';
748 1484 Luisehahne
749 1457 Luisehahne
		// write content into file
750 1551 Luisehahne
		  if(is_writable($filename) || !file_exists($filename)) {
751
		      if(file_put_contents($filename, $content)) {
752 1866 Luisehahne
		          $retVal[] = change_mode($filename);
753 1765 Luisehahne
		      } else {
754 1551 Luisehahne
		    $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'].' :: '.$filename;
755
		   }
756
		  }
757
		 } else {
758
		   $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'];
759
		 }
760
		 return $retVal;
761 1457 Luisehahne
}
762
763
function rebuildFolderProtectFile($dir='')
764
{
765 1675 Luisehahne
	global $MESSAGE;
766 1495 DarkViper
	$retVal = array();
767 1866 Luisehahne
	$tmpVal = array();
768 1495 DarkViper
	$dir = rtrim(str_replace('\/\\', '/', $dir), '/');
769
	try {
770
		$files = array();
771
		$files[] = $dir;
772
		foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $fileInfo) {
773
			$files[] = $fileInfo->getPath();
774
		}
775
		$files = array_unique($files);
776
		foreach( $files as $file) {
777
			$protect_file = rtrim(str_replace('\/\\', '/', $file), '/');
778 1866 Luisehahne
			$tmpVal['file'][] = createFolderProtectFile($protect_file,false);
779 1495 DarkViper
		}
780 1866 Luisehahne
		$retVal = $tmpVal['file'];
781 1495 DarkViper
	} catch ( Exception $e ) {
782
		$retVal[] = $MESSAGE['MEDIA_DIR_ACCESS_DENIED'];
783
	}
784
	return $retVal;
785 1457 Luisehahne
}
786
787
// Create a new file in the pages directory
788 1866 Luisehahne
/**
789
 * createAccessFile()
790
 *
791
 * @param string The full path and filename to the new accessfile
792
 * @param int    Id of the page for which the file should created
793
 * @param mixed  an array with one or more additional statements to include in accessfile.
794
 * @return bool|string true or error message
795
 * @deprecated this function will be replaced by a core method in next version
796
 * @description: Create a new access file in the pages directory and subdirectory also if needed.<br />
797
 * Example: $aOptionalCommands = array(
798
 *                     '$section_id = '.$section_id,
799
 *                     '$mod_var_int = '.$mod_var_int,
800
 *                     'define(\'MOD_CONSTANT\'', '.$mod_var_int.')'
801
 *          );
802
 * forbidden commands: include|require[_once]
803
 * @deprecated   2013/02/19
804
 */
805
806
function create_access_file($sFileName, $iPageId, $iLevel = 0, array $aOptionalCommands = array() )
807 1352 Luisehahne
{
808 1866 Luisehahne
	global $MESSAGE;
809
	$sError = '';
810
// sanitize pathnames for the standard 'trailing slash' scheme
811
	$sAppPath  = rtrim(str_replace('\\', '/', WB_PATH), '/').'/';
812
	$sFileName = str_replace('\\', '/', $sFileName);
813
// try to create the whoole path to the accessfile
814
	$sAccessPath = dirname($sFileName).'/';
815
	if(!($bRetval = is_dir($sAccessPath))) {
816
		$iOldUmask = umask(0) ;
817
		// sanitize directory mode to 'o+rwx/g+x/u+x' and create path
818
		$bRetval = mkdir($sAccessPath, (OCTAL_DIR_MODE |0711), true);
819
		umask($iOldUmask);
820
	}
821
	if($bRetval) {
822
	// check if accessfile is writeable
823
		if(is_writable($sAccessPath) ||
824
		   (file_exists($sFileName) && is_writable($sFileName)) )
825 1352 Luisehahne
		{
826 1866 Luisehahne
		// build content for accessfile
827
			$sContent  = '<?php'."\n"
828
			           . '// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n"
829
			           . '// *** Creation date: '.date('c')."\n"
830
			           . '// *** Do not modify this file manually'."\n"
831
			           . '// *** WB will rebuild this file from time to time!!'."\n"
832
			           . '// *************************************************'."\n"
833
			           . "\t".'$page_id = '.$iPageId.';'."\n";
834
		// analyse OptionalCommands and add it to the accessfile
835
			foreach($aOptionalCommands as $sCommand) {
836
			// loop through all available entries
837
			// remove all leading whitespaces and chars less then \x41(A) except \x24 ($)
838
			// also all trailing whitespaces and \x3B(;) too.
839
				$sNewCmd  = rtrim(ltrim($sCommand, "\x00..\x23\x25..\x40"), ';');
840
				if(preg_match('/^include|^require/i', $sNewCmd)) {
841
				// insert forbidden include|require[_once] command and comment it out
842
					$sContent .= "\t".'// *not allowed command >> * '.$sNewCmd.';'."\n";
843
				}elseif(preg_match('/^define/i', $sNewCmd)) {
844
				// insert active define command and comment it as set deprecated
845
					$sContent .= "\t".$sNewCmd.'; // *deprecated command*'."\n";
846
				}else {
847
				// insert allowed active command
848
					$sContent .= "\t".$sNewCmd.';'."\n";
849 1352 Luisehahne
				}
850 1457 Luisehahne
			}
851 1866 Luisehahne
		// calculate the needed backsteps and create the relative link to index.php
852
			$iBackSteps = substr_count(str_replace($sAppPath, '', $sFileName), '/');
853
			$sIndexFile = str_repeat('../', $iBackSteps).'index.php';
854
		// insert needed require command for index.php
855
			$sContent .= "\t".'require(\''.$sIndexFile.'\');'."\n"
856
			           . '// *************************************************'."\n"
857
			           . '// end of file'."\n";
858
		// write new file out. If the file already exists overwrite its content.
859
			if(file_put_contents($sFileName, $sContent) !== false ) {
860
			// if OS is not windows then chmod the new file
861
				if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
862
				// sanitize filemode to 'o-x/g-x/u-x/o+rw' and chmod the new file
863 1871 Luisehahne
					$bRetval = chmod($sFileName, ((OCTAL_FILE_MODE & ~0111)|0600));
864 1866 Luisehahne
				}
865
			}else {
866
		        $sError = $MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE'];
867
			}
868
		}else {
869
			$sError = $MESSAGE['UPLOAD_ERR_CANT_WRITE'];
870 1352 Luisehahne
		}
871 1866 Luisehahne
	}else {
872
		$sError = $MESSAGE['UPLOAD_ERR_CANT_WRITE'];
873 1495 DarkViper
	}
874 1866 Luisehahne
	// return boolean true if ok, on error return a message
875
	return ($sError == '' ? true : $sError);
876 1457 Luisehahne
 }
877
878 1352 Luisehahne
// Function for working out a file mime type (if the in-built PHP one is not enabled)
879
if(!function_exists('mime_content_type'))
880
{
881 1457 Luisehahne
    function mime_content_type($filename)
882 1352 Luisehahne
	{
883
	    $mime_types = array(
884
            'txt'	=> 'text/plain',
885
            'htm'	=> 'text/html',
886
            'html'	=> 'text/html',
887
            'php'	=> 'text/html',
888
            'css'	=> 'text/css',
889
            'js'	=> 'application/javascript',
890
            'json'	=> 'application/json',
891
            'xml'	=> 'application/xml',
892
            'swf'	=> 'application/x-shockwave-flash',
893
            'flv'	=> 'video/x-flv',
894
895
            // images
896
            'png'	=> 'image/png',
897
            'jpe'	=> 'image/jpeg',
898
            'jpeg'	=> 'image/jpeg',
899
            'jpg'	=> 'image/jpeg',
900
            'gif'	=> 'image/gif',
901
            'bmp'	=> 'image/bmp',
902
            'ico'	=> 'image/vnd.microsoft.icon',
903
            'tiff'	=> 'image/tiff',
904
            'tif'	=> 'image/tiff',
905
            'svg'	=> 'image/svg+xml',
906
            'svgz'	=> 'image/svg+xml',
907
908
            // archives
909
            'zip'	=> 'application/zip',
910
            'rar'	=> 'application/x-rar-compressed',
911
            'exe'	=> 'application/x-msdownload',
912
            'msi'	=> 'application/x-msdownload',
913
            'cab'	=> 'application/vnd.ms-cab-compressed',
914
915
            // audio/video
916
            'mp3'	=> 'audio/mpeg',
917
            'mp4'	=> 'audio/mpeg',
918
            'qt'	=> 'video/quicktime',
919
            'mov'	=> 'video/quicktime',
920
921
            // adobe
922
            'pdf'	=> 'application/pdf',
923
            'psd'	=> 'image/vnd.adobe.photoshop',
924
            'ai'	=> 'application/postscript',
925
            'eps'	=> 'application/postscript',
926
            'ps'	=> 'application/postscript',
927
928
            // ms office
929
            'doc'	=> 'application/msword',
930
            'rtf'	=> 'application/rtf',
931
            'xls'	=> 'application/vnd.ms-excel',
932
            'ppt'	=> 'application/vnd.ms-powerpoint',
933
934
            // open office
935
            'odt'	=> 'application/vnd.oasis.opendocument.text',
936
            'ods'	=> 'application/vnd.oasis.opendocument.spreadsheet',
937
        );
938
        $temp = explode('.',$filename);
939
        $ext = strtolower(array_pop($temp));
940 1495 DarkViper
        if (array_key_exists($ext, $mime_types)) {
941 1352 Luisehahne
            return $mime_types[$ext];
942 1495 DarkViper
        }elseif (function_exists('finfo_open')) {
943 1352 Luisehahne
            $finfo = finfo_open(FILEINFO_MIME);
944
            $mimetype = finfo_file($finfo, $filename);
945
            finfo_close($finfo);
946
            return $mimetype;
947 1495 DarkViper
        }else {
948 1352 Luisehahne
            return 'application/octet-stream';
949
        }
950
    }
951
}
952
953
// Generate a thumbnail from an image
954
function make_thumb($source, $destination, $size)
955
{
956
	// Check if GD is installed
957 1365 Luisehahne
	if(extension_loaded('gd') && function_exists('imageCreateFromJpeg'))
958 1352 Luisehahne
	{
959
		// First figure out the size of the thumbnail
960
		list($original_x, $original_y) = getimagesize($source);
961 1495 DarkViper
		if ($original_x > $original_y) {
962 1352 Luisehahne
			$thumb_w = $size;
963
			$thumb_h = $original_y*($size/$original_x);
964
		}
965 1495 DarkViper
		if ($original_x < $original_y) {
966 1352 Luisehahne
			$thumb_w = $original_x*($size/$original_y);
967
			$thumb_h = $size;
968
		}
969 1495 DarkViper
		if ($original_x == $original_y) {
970 1352 Luisehahne
			$thumb_w = $size;
971 1495 DarkViper
			$thumb_h = $size;
972 1352 Luisehahne
		}
973
		// Now make the thumbnail
974
		$source = imageCreateFromJpeg($source);
975
		$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
976
		imagecopyresampled($dst_img,$source,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);
977
		imagejpeg($dst_img, $destination);
978
		// Clear memory
979
		imagedestroy($dst_img);
980
		imagedestroy($source);
981
	   // Return true
982
		return true;
983
	} else {
984
		return false;
985
	}
986
}
987
988
/*
989
 * Function to work-out a single part of an octal permission value
990
 *
991
 * @param mixed $octal_value: an octal value as string (i.e. '0777') or real octal integer (i.e. 0777 | 777)
992
 * @param string $who: char or string for whom the permission is asked( U[ser] / G[roup] / O[thers] )
993
 * @param string $action: char or string with the requested action( r[ead..] / w[rite..] / e|x[ecute..] )
994
 * @return boolean
995
 */
996
function extract_permission($octal_value, $who, $action)
997
{
998
	// Make sure that all arguments are set and $octal_value is a real octal-integer
999 1495 DarkViper
	if(($who == '') || ($action == '') || (preg_match( '/[^0-7]/', (string)$octal_value ))) {
1000 1352 Luisehahne
		return false; // invalid argument, so return false
1001
	}
1002
	// convert $octal_value into a decimal-integer to be sure having a valid value
1003
	$right_mask = octdec($octal_value);
1004
	$action_mask = 0;
1005
	// set the $action related bit in $action_mask
1006 1495 DarkViper
	switch($action[0]) { // get action from first char of $action
1007 1352 Luisehahne
		case 'r':
1008
		case 'R':
1009
			$action_mask = 4; // set read-bit only (2^2)
1010
			break;
1011
		case 'w':
1012
		case 'W':
1013
			$action_mask = 2; // set write-bit only (2^1)
1014
			break;
1015
		case 'e':
1016
		case 'E':
1017
		case 'x':
1018
		case 'X':
1019
			$action_mask = 1; // set execute-bit only (2^0)
1020
			break;
1021
		default:
1022
			return false; // undefined action name, so return false
1023
	}
1024
	// shift action-mask into the right position
1025 1495 DarkViper
	switch($who[0]) { // get who from first char of $who
1026 1352 Luisehahne
		case 'u':
1027
		case 'U':
1028
			$action_mask <<= 3; // shift left 3 bits
1029
		case 'g':
1030
		case 'G':
1031
			$action_mask <<= 3; // shift left 3 bits
1032
		case 'o':
1033
		case 'O':
1034
			/* NOP */
1035
			break;
1036
		default:
1037
			return false; // undefined who, so return false
1038
	}
1039
	return( ($right_mask & $action_mask) != 0 ); // return result of binary-AND
1040
}
1041
1042
// Function to delete a page
1043 1365 Luisehahne
	function delete_page($page_id)
1044 1352 Luisehahne
	{
1045 1365 Luisehahne
		global $admin, $database, $MESSAGE;
1046
		// Find out more about the page
1047 1495 DarkViper
		$sql  = 'SELECT `page_id`, `menu_title`, `page_title`, `level`, ';
1048
		$sql .=        '`link`, `parent`, `modified_by`, `modified_when` ';
1049
		$sql .= 'FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
1050 1365 Luisehahne
		$results = $database->query($sql);
1051
		if($database->is_error())    { $admin->print_error($database->get_error()); }
1052 1759 Luisehahne
		if($results->numRows() == 0) { $admin->print_error($MESSAGE['PAGES_NOT_FOUND']); }
1053
		$results_array = $results->fetchRow(MYSQL_ASSOC);
1054 1365 Luisehahne
		$parent     = $results_array['parent'];
1055
		$level      = $results_array['level'];
1056 1859 Luisehahne
		$sPageLink       = $results_array['link'];
1057 1365 Luisehahne
		$page_title = $results_array['page_title'];
1058
		$menu_title = $results_array['menu_title'];
1059
		// Get the sections that belong to the page
1060 1495 DarkViper
		$sql  = 'SELECT `section_id`, `module` FROM `'.TABLE_PREFIX.'sections` ';
1061
		$sql .= 'WHERE `page_id`='.$page_id;
1062 1365 Luisehahne
		$query_sections = $database->query($sql);
1063
		if($query_sections->numRows() > 0)
1064 1352 Luisehahne
		{
1065 1495 DarkViper
			while($section = $query_sections->fetchRow()) {
1066 1365 Luisehahne
				// Set section id
1067
				$section_id = $section['section_id'];
1068
				// Include the modules delete file if it exists
1069 1495 DarkViper
				if(file_exists(WB_PATH.'/modules/'.$section['module'].'/delete.php')) {
1070 1365 Luisehahne
					include(WB_PATH.'/modules/'.$section['module'].'/delete.php');
1071
				}
1072 1352 Luisehahne
			}
1073
		}
1074 1365 Luisehahne
		// Update the sections table
1075 1495 DarkViper
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'sections` WHERE `page_id`='.$page_id;
1076 1365 Luisehahne
		$database->query($sql);
1077
		if($database->is_error()) {
1078
			$admin->print_error($database->get_error());
1079
		}
1080
		// Include the ordering class or clean-up ordering
1081
		include_once(WB_PATH.'/framework/class.order.php');
1082
		$order = new order(TABLE_PREFIX.'pages', 'position', 'page_id', 'parent');
1083
		$order->clean($parent);
1084
		// Unlink the page access file and directory
1085 1859 Luisehahne
		$directory = WB_PATH.PAGES_DIRECTORY.$sPageLink;
1086 1365 Luisehahne
		$filename = $directory.PAGE_EXTENSION;
1087
		$directory .= '/';
1088 1859 Luisehahne
		if(is_writable($filename))
1089 1365 Luisehahne
		{
1090 1495 DarkViper
			if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/')) {
1091 1759 Luisehahne
				$admin->print_error($MESSAGE['PAGES_CANNOT_DELETE_ACCESS_FILE']);
1092 1859 Luisehahne
			} else {
1093 1365 Luisehahne
				unlink($filename);
1094 1859 Luisehahne
				if( is_writable($directory) && (rtrim($directory,'/') != WB_PATH.PAGES_DIRECTORY ) && (substr($sPageLink, 0, 1) != '.') )
1095 1365 Luisehahne
				{
1096
					rm_full_dir($directory);
1097
				}
1098
			}
1099
		}
1100 1859 Luisehahne
		// Update the pages table
1101
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
1102
		$database->query($sql);
1103
		if($database->is_error()) {
1104
			$admin->print_error($database->get_error());
1105
		}
1106 1352 Luisehahne
	}
1107 1365 Luisehahne
1108
/*
1109
 * @param string $file: name of the file to read
1110
 * @param int $size: number of maximum bytes to read (0 = complete file)
1111
 * @return string: the content as string, false on error
1112
 */
1113
	function getFilePart($file, $size = 0)
1114 1352 Luisehahne
	{
1115 1365 Luisehahne
		$file_content = '';
1116
		if( file_exists($file) && is_file($file) && is_readable($file))
1117 1352 Luisehahne
		{
1118 1495 DarkViper
			if($size == 0) {
1119 1365 Luisehahne
				$size = filesize($file);
1120
			}
1121 1495 DarkViper
			if(($fh = fopen($file, 'rb'))) {
1122
				if( ($file_content = fread($fh, $size)) !== false ) {
1123 1365 Luisehahne
					return $file_content;
1124
				}
1125
				fclose($fh);
1126
			}
1127 1352 Luisehahne
		}
1128 1365 Luisehahne
		return false;
1129
	}
1130
1131
	/**
1132
	* replace varnames with values in a string
1133
	*
1134
	* @param string $subject: stringvariable with vars placeholder
1135
	* @param array $replace: values to replace vars placeholder
1136
	* @return string
1137
	*/
1138
    function replace_vars($subject = '', &$replace = null )
1139
    {
1140
		if(is_array($replace))
1141 1352 Luisehahne
		{
1142 1495 DarkViper
			foreach ($replace  as $key => $value) {
1143 1365 Luisehahne
				$subject = str_replace("{{".$key."}}", $value, $subject);
1144 1352 Luisehahne
			}
1145
		}
1146 1365 Luisehahne
		return $subject;
1147
    }
1148 1352 Luisehahne
1149 1925 darkviper
function setAccessDeniedToNewTools($sModulName)
1150
{
1151
	$oDb = WbDatabase::getInstance();
1152
	$sql = 'UPDATE `'.$oDb->getTablePrefix.'groups` '
1153
		 . 'SET `module_permissions`= TRIM(LEADING \',\' FROM (CONCAT(`module_permissions`, \','.$sModulName.'\'))) '
1154
	     . 'WHERE `group_id`<>1 AND NOT FIND_IN_SET(\''.$sModulName.'\', `module_permissions`)';
1155
	$oDb->query($sql);
1156
}
1157
1158 1352 Luisehahne
// Load module into DB
1159
function load_module($directory, $install = false)
1160
{
1161
	global $database,$admin,$MESSAGE;
1162 1365 Luisehahne
	$retVal = false;
1163
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1164 1352 Luisehahne
	{
1165
		require($directory.'/info.php');
1166
		if(isset($module_name))
1167
		{
1168 1365 Luisehahne
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1169
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1170
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1171 1352 Luisehahne
			$module_function = strtolower($module_function);
1172
			// Check that it doesn't already exist
1173 1365 Luisehahne
			$sqlwhere = 'WHERE `type` = \'module\' AND `directory` = \''.$module_directory.'\'';
1174
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1175 1495 DarkViper
			if( $database->get_one($sql) ) {
1176 1365 Luisehahne
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1177
			}else{
1178 1352 Luisehahne
				// Load into DB
1179
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1180 1365 Luisehahne
				$sqlwhere = '';
1181
			}
1182 1495 DarkViper
			$sql .= '`directory`=\''.$module_directory.'\', ';
1183
			$sql .= '`name`=\''.$module_name.'\', ';
1184
			$sql .= '`description`=\''.addslashes($module_description).'\', ';
1185
			$sql .= '`type`=\'module\', ';
1186
			$sql .= '`function`=\''.$module_function.'\', ';
1187
			$sql .= '`version`=\''.$module_version.'\', ';
1188
			$sql .= '`platform`=\''.$module_platform.'\', ';
1189
			$sql .= '`author`=\''.addslashes($module_author).'\', ';
1190
			$sql .= '`license`=\''.addslashes($module_license).'\'';
1191 1365 Luisehahne
			$sql .= $sqlwhere;
1192 1765 Luisehahne
			$retVal = intval($database->query($sql) ? true : false);
1193 1925 darkviper
			if($retVal && !$sqlwhere &&
1194
			   ($module_function == 'tool' || $module_function == 'page' || $module_function == 'wysiwyg')
1195
			  ) {
1196
				setAccessDeniedToNewTools($module_directory);
1197
			}
1198 1365 Luisehahne
			// Run installation script
1199 1495 DarkViper
			if($install == true) {
1200
				if(file_exists($directory.'/install.php')) {
1201 1365 Luisehahne
					require($directory.'/install.php');
1202 1352 Luisehahne
				}
1203
			}
1204
		}
1205 1765 Luisehahne
        return $retVal;
1206 1352 Luisehahne
	}
1207
}
1208
1209
// Load template into DB
1210
function load_template($directory)
1211
{
1212
	global $database, $admin;
1213 1365 Luisehahne
	$retVal = false;
1214
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1215 1352 Luisehahne
	{
1216
		require($directory.'/info.php');
1217
		if(isset($template_name))
1218
		{
1219 1495 DarkViper
			if(!isset($template_license)) {
1220 1352 Luisehahne
              $template_license = 'GNU General Public License';
1221
            }
1222 1495 DarkViper
			if(!isset($template_platform) && isset($template_designed_for)) {
1223 1352 Luisehahne
              $template_platform = $template_designed_for;
1224
            }
1225 1495 DarkViper
			if(!isset($template_function)) {
1226 1352 Luisehahne
              $template_function = 'template';
1227
            }
1228
			// Check that it doesn't already exist
1229 1495 DarkViper
			$sqlwhere = 'WHERE `type`=\'template\' AND `directory`=\''.$template_directory.'\'';
1230 1365 Luisehahne
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1231 1495 DarkViper
			if( $database->get_one($sql) ) {
1232 1365 Luisehahne
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1233
			}else{
1234 1352 Luisehahne
				// Load into DB
1235
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1236 1365 Luisehahne
				$sqlwhere = '';
1237 1352 Luisehahne
			}
1238 1495 DarkViper
			$sql .= '`directory`=\''.$template_directory.'\', ';
1239
			$sql .= '`name`=\''.$template_name.'\', ';
1240
			$sql .= '`description`=\''.addslashes($template_description).'\', ';
1241
			$sql .= '`type`=\'template\', ';
1242
			$sql .= '`function`=\''.$template_function.'\', ';
1243
			$sql .= '`version`=\''.$template_version.'\', ';
1244
			$sql .= '`platform`=\''.$template_platform.'\', ';
1245
			$sql .= '`author`=\''.addslashes($template_author).'\', ';
1246
			$sql .= '`license`=\''.addslashes($template_license).'\' ';
1247 1365 Luisehahne
			$sql .= $sqlwhere;
1248 1765 Luisehahne
			$retVal = intval($database->query($sql) ? true : false);
1249 1352 Luisehahne
		}
1250
	}
1251 1365 Luisehahne
	return $retVal;
1252 1352 Luisehahne
}
1253
1254
// Load language into DB
1255
function load_language($file)
1256
{
1257
	global $database,$admin;
1258 1365 Luisehahne
	$retVal = false;
1259 1352 Luisehahne
	if (file_exists($file) && preg_match('#^([A-Z]{2}.php)#', basename($file)))
1260
	{
1261 1365 Luisehahne
		// require($file);  it's to large
1262
		// read contents of the template language file into string
1263
		$data = @file_get_contents(WB_PATH.'/languages/'.str_replace('.php','',basename($file)).'.php');
1264
		// use regular expressions to fetch the content of the variable from the string
1265 1435 Luisehahne
		$language_name = get_variable_content('language_name', $data, false, false);
1266
		$language_code = get_variable_content('language_code', $data, false, false);
1267
		$language_author = get_variable_content('language_author', $data, false, false);
1268
		$language_version = get_variable_content('language_version', $data, false, false);
1269
		$language_platform = get_variable_content('language_platform', $data, false, false);
1270 1365 Luisehahne
1271 1352 Luisehahne
		if(isset($language_name))
1272
		{
1273 1365 Luisehahne
			if(!isset($language_license)) { $language_license = 'GNU General Public License'; }
1274
			if(!isset($language_platform) && isset($language_designed_for)) { $language_platform = $language_designed_for; }
1275 1352 Luisehahne
			// Check that it doesn't already exist
1276 1495 DarkViper
			$sqlwhere = 'WHERE `type`=\'language\' AND `directory`=\''.$language_code.'\'';
1277 1365 Luisehahne
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1278 1495 DarkViper
			if( $database->get_one($sql) ) {
1279 1365 Luisehahne
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1280
			}else{
1281 1352 Luisehahne
				// Load into DB
1282
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1283 1365 Luisehahne
				$sqlwhere = '';
1284 1352 Luisehahne
			}
1285 1495 DarkViper
			$sql .= '`directory`=\''.$language_code.'\', ';
1286
			$sql .= '`name`=\''.$language_name.'\', ';
1287 1747 Luisehahne
            $sql .= '`description`=\'\', ';
1288
			$sql .= '`function`=\'\', ';
1289 1495 DarkViper
			$sql .= '`type`=\'language\', ';
1290
			$sql .= '`version`=\''.$language_version.'\', ';
1291
			$sql .= '`platform`=\''.$language_platform.'\', ';
1292
			$sql .= '`author`=\''.addslashes($language_author).'\', ';
1293
			$sql .= '`license`=\''.addslashes($language_license).'\' ';
1294 1365 Luisehahne
			$sql .= $sqlwhere;
1295 1765 Luisehahne
			$retVal = intval($database->query($sql) ? true : false);
1296 1352 Luisehahne
		}
1297
	}
1298 1365 Luisehahne
	return $retVal;
1299 1352 Luisehahne
}
1300
1301
// Upgrade module info in DB, optionally start upgrade script
1302
function upgrade_module($directory, $upgrade = false)
1303
{
1304
	global $database, $admin, $MESSAGE, $new_module_version;
1305
	$mod_directory = WB_PATH.'/modules/'.$directory;
1306
	if(file_exists($mod_directory.'/info.php'))
1307
	{
1308
		require($mod_directory.'/info.php');
1309
		if(isset($module_name))
1310
		{
1311 1365 Luisehahne
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1312 1352 Luisehahne
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1313 1365 Luisehahne
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1314 1352 Luisehahne
			$module_function = strtolower($module_function);
1315
			// Check that it does already exist
1316
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` ';
1317 1495 DarkViper
			$sql .= 'WHERE `directory`=\''.$module_directory.'\'';
1318 1352 Luisehahne
			if( $database->get_one($sql) )
1319
			{
1320
				// Update in DB
1321
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1322 1495 DarkViper
				$sql .= '`version`=\''.$module_version.'\', ';
1323
				$sql .= '`description`=\''.addslashes($module_description).'\', ';
1324
				$sql .= '`platform`=\''.$module_platform.'\', ';
1325
				$sql .= '`author`=\''.addslashes($module_author).'\', ';
1326
				$sql .= '`license`=\''.addslashes($module_license).'\' ';
1327
				$sql .= 'WHERE `directory`=\''.$module_directory.'\' ';
1328 1352 Luisehahne
				$database->query($sql);
1329
				if($database->is_error()) {
1330
					$admin->print_error($database->get_error());
1331
				}
1332
				// Run upgrade script
1333 1495 DarkViper
				if($upgrade == true) {
1334
					if(file_exists($mod_directory.'/upgrade.php')) {
1335 1352 Luisehahne
						require($mod_directory.'/upgrade.php');
1336
					}
1337
				}
1338
			}
1339
		}
1340
	}
1341
}
1342
1343
// extracts the content of a string variable from a string (save alternative to including files)
1344
if(!function_exists('get_variable_content'))
1345
{
1346
	function get_variable_content($search, $data, $striptags=true, $convert_to_entities=true)
1347
	{
1348
		$match = '';
1349
		// search for $variable followed by 0-n whitespace then by = then by 0-n whitespace
1350
		// then either " or ' then 0-n characters then either " or ' followed by 0-n whitespace and ;
1351
		// the variable name is returned in $match[1], the content in $match[3]
1352
		if (preg_match('/(\$' .$search .')\s*=\s*("|\')(.*)\2\s*;/', $data, $match))
1353
		{
1354 1495 DarkViper
			if(strip_tags(trim($match[1])) == '$' .$search) {
1355 1352 Luisehahne
				// variable name matches, return it's value
1356
				$match[3] = ($striptags == true) ? strip_tags($match[3]) : $match[3];
1357
				$match[3] = ($convert_to_entities == true) ? htmlentities($match[3]) : $match[3];
1358
				return $match[3];
1359
			}
1360
		}
1361
		return false;
1362
	}
1363
}
1364
1365 1365 Luisehahne
/*
1366
 * @param string $modulname: like saved in addons.directory
1367
 * @param boolean $source: true reads from database, false from info.php
1368
 * @return string:  the version as string, if not found returns null
1369
 */
1370
1371
	function get_modul_version($modulname, $source = true)
1372
	{
1373
		global $database;
1374
		$version = null;
1375
		if( $source != true )
1376
		{
1377 1495 DarkViper
			$sql  = 'SELECT `version` FROM `'.TABLE_PREFIX.'addons` ';
1378
			$sql .= 'WHERE `directory`=\''.$modulname.'\'';
1379 1365 Luisehahne
			$version = $database->get_one($sql);
1380
		} else {
1381
			$info_file = WB_PATH.'/modules/'.$modulname.'/info.php';
1382 1495 DarkViper
			if(file_exists($info_file)) {
1383
				if(($info_file = file_get_contents($info_file))) {
1384 1365 Luisehahne
					$version = get_variable_content('module_version', $info_file, false, false);
1385
					$version = ($version !== false) ? $version : null;
1386
				}
1387
			}
1388
		}
1389
		return $version;
1390
	}
1391
1392
/*
1393
 * @param string $varlist: commaseperated list of varnames to move into global space
1394
 * @return bool:  false if one of the vars already exists in global space (error added to msgQueue)
1395
 */
1396
	function vars2globals_wrapper($varlist)
1397
	{
1398
		$retval = true;
1399
		if( $varlist != '')
1400
		{
1401
			$vars = explode(',', $varlist);
1402
			foreach( $vars as $var)
1403
			{
1404 1495 DarkViper
				if( isset($GLOBALS[$var]) ){
1405 1365 Luisehahne
					ErrorLog::write( 'variabe $'.$var.' already defined in global space!!',__FILE__, __FUNCTION__, __LINE__);
1406
					$retval = false;
1407 1495 DarkViper
				}else {
1408 1365 Luisehahne
					global $$var;
1409
				}
1410
			}
1411
		}
1412
		return $retval;
1413
	}
1414
1415 1400 FrankH
/*
1416
 * filter directory traversal more thoroughly, thanks to hal 9000
1417
 * @param string $dir: directory relative to MEDIA_DIRECTORY
1418
 * @param bool $with_media_dir: true when to include MEDIA_DIRECTORY
1419
 * @return: false if directory traversal detected, real path if not
1420
 */
1421
	function check_media_path($directory, $with_media_dir = true)
1422
	{
1423 1495 DarkViper
		$md = ($with_media_dir) ? MEDIA_DIRECTORY : '';
1424 1400 FrankH
		$dir = realpath(WB_PATH . $md . '/' . utf8_decode($directory));
1425
		$required = realpath(WB_PATH . MEDIA_DIRECTORY);
1426
		if (strstr($dir, $required)) {
1427
			return $dir;
1428
		} else {
1429
			return false;
1430
		}
1431
	}
1432 1475 Luisehahne
1433
/*
1434
urlencode function and rawurlencode are mostly based on RFC 1738.
1435
However, since 2005 the current RFC in use for URIs standard is RFC 3986.
1436
Here is a function to encode URLs according to RFC 3986.
1437
*/
1438
if(!function_exists('url_encode')){
1439
	function url_encode($string) {
1440
	    $string = html_entity_decode($string,ENT_QUOTES,'UTF-8');
1441 1477 Luisehahne
	    $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
1442
	    $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
1443
	    return str_replace($entities,$replacements, rawurlencode($string));
1444 1475 Luisehahne
	}
1445 1705 Luisehahne
}
1446 1765 Luisehahne
1447
if(!function_exists('rebuild_all_accessfiles')){
1448 1977 Luisehahne
	function rebuild_all_accessfiles($bShowDetails=false ) {
1449 1765 Luisehahne
        global $database;
1450 1977 Luisehahne
    	$aRetval = array();
1451 1765 Luisehahne
    	/**
1452
    	 * try to remove access files and build new folder protect files
1453
    	 */
1454 1977 Luisehahne
 //   	$sTempDir = (defined('PAGES_DIRECTORY') && (PAGES_DIRECTORY != '') ? PAGES_DIRECTORY : '').'/';
1455
        $sTreeToDelete = WbAdaptor::getInstance()->AppPath.WbAdaptor::getInstance()->PagesDir;
1456
    	if(($sTreeToDelete!='') && is_writeable($sTreeToDelete)==true) {
1457
//    	 	if(rm_full_dir (WB_PATH.$sTempDir, true, $aProtectedFiles )==false) {
1458
//    			$aRetval[] = 'Could not delete existing access files';
1459
//    	 	}
1460
            DeleteAccessFilesTree($sTreeToDelete);
1461
            if($bShowDetails) {
1462
                $aRetval = array_merge($aRetval, AccessFileHelper::getDelTreeLog());
1463
            }
1464 1908 Luisehahne
    	}
1465 1977 Luisehahne
1466
		$aRetval = array_merge($aRetval,createFolderProtectFile(rtrim( WB_PATH.PAGES_DIRECTORY,'/') ));
1467
1468 1765 Luisehahne
    	/**
1469
    	 * Reformat/rebuild all existing access files
1470
    	 */
1471 1866 Luisehahne
//        $sql = 'SELECT `page_id`,`root_parent`,`link`, `level` FROM `'.TABLE_PREFIX.'pages` ORDER BY `link`';
1472
		$sql  = 'SELECT `page_id`,`root_parent`,`link`, `level` ';
1473
		$sql .= 'FROM `'.TABLE_PREFIX.'pages` ';
1474
		$sql .= 'WHERE `link` != \'\' ORDER BY `link` ';
1475 1765 Luisehahne
        if (($oPage = $database->query($sql)))
1476
        {
1477
            $x = 0;
1478
            while (($page = $oPage->fetchRow(MYSQL_ASSOC)))
1479
            {
1480
                // Work out level
1481
                $level = level_count($page['page_id']);
1482
                // Work out root parent
1483
                $root_parent = root_parent($page['page_id']);
1484
                // Work out page trail
1485
                $page_trail = get_page_trail($page['page_id']);
1486
                // Update page with new level and link
1487
                $sql  = 'UPDATE `'.TABLE_PREFIX.'pages` SET ';
1488
                $sql .= '`root_parent` = '.$root_parent.', ';
1489
                $sql .= '`level` = '.$level.', ';
1490
                $sql .= '`page_trail` = "'.$page_trail.'" ';
1491
                $sql .= 'WHERE `page_id` = '.$page['page_id'];
1492
1493
                if(!$database->query($sql)) {}
1494
                $filename = WB_PATH.PAGES_DIRECTORY.$page['link'].PAGE_EXTENSION;
1495 1866 Luisehahne
                create_access_file($filename, $page['page_id'], $page['level']);
1496 1765 Luisehahne
                $x++;
1497
            }
1498 1977 Luisehahne
            $aRetval[] = 'Number of new formated access files: '.$x.'';
1499 1765 Luisehahne
        }
1500 1977 Luisehahne
    return $aRetval;
1501 1765 Luisehahne
	}
1502
}
1503
1504
if(!function_exists('upgrade_modules')){
1505
	function upgrade_modules($aModuleList) {
1506
        global $database;
1507
    	foreach($aModuleList as $sModul) {
1508
    		if(file_exists(WB_PATH.'/modules/'.$sModul.'/upgrade.php')) {
1509
    			$currModulVersion = get_modul_version ($sModul, false);
1510
    			$newModulVersion =  get_modul_version ($sModul, true);
1511
    			if((version_compare($currModulVersion, $newModulVersion) <= 0)) {
1512 1866 Luisehahne
    				require(WB_PATH.'/modules/'.$sModul.'/upgrade.php');
1513 1765 Luisehahne
    			}
1514
    		}
1515
    	}
1516
    }
1517
}