Project

General

Profile

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