Project

General

Profile

1
<?php
2
/**
3
 *
4
 * @category        frontend
5
 * @package         framework
6
 * @author          Ryan Djurovich,WebsiteBaker Project
7
 * @copyright       2009-2013, WebsiteBaker Org. e.V.
8
 * @link            http://www.websitebaker.org/
9
 * @license         http://www.gnu.org/licenses/gpl.html
10
 * @platform        WebsiteBaker 2.8.4
11
 * @requirements    PHP 5.2.2 and higher
12
 * @version         $Id: functions.php 1983 2013-10-19 00:42:27Z Luisehahne $
13
 * @filesource      $HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
14
 * @lastmodified    $Date: 2013-10-19 02:42:27 +0200 (Sat, 19 Oct 2013) $
15
 *
16
 */
17
/* -------------------------------------------------------- */
18
// Must include code to stop this file being accessed directly
19
if(!defined('WB_PATH')) {
20
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
21
	throw new IllegalFileException();
22
}
23
/* -------------------------------------------------------- */
24
// Define that this file has been loaded
25
define('FUNCTIONS_FILE_LOADED', true);
26

    
27

    
28
/**
29
 * Delete an Accessfiles Tree
30
 * @param  string  $sDirToDelete
31
 * @param  array   &$aReport  returns report if set
32
 * @return boolean true/false
33
 * @description    Delete all accessfiles and its depending directory tree 
34
 *                 inside the given directory.
35
 */
36
function DeleteAccessFilesTree($sDirToDelete, array &$aReport = null)
37
{
38
		$aReport = array();
39
        $sBaseDir = realpath($sDirToDelete);
40
        if( $sBaseDir !== false) {    
41
		$sBaseDir = rtrim(str_replace('\\', '/', $sBaseDir), '/') . '/';
42
		// scan start directory for access files
43
		foreach (glob($sBaseDir . '*.php', GLOB_MARK) as $sItem) {
44
            $sItem = str_replace('\\', '/', $sItem);
45
			try{
46
				$oAccFile = new AccessFile($sItem);
47
				$oAccFile->delete();
48
				$aReport = array_merge($aReport, AccessFileHelper::getDelTreeLog());
49
			}catch(AccessFileIsNoAccessfileException $e) {
50
				continue;
51
			}
52
		}
53
        clearstatcache();
54
		return true;
55
	}	
56
	return false;
57
}
58

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
707

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1450
if(!function_exists('rebuild_all_accessfiles'))
1451
{
1452
	function rebuild_all_accessfiles($bShowDetails=false ) 
1453
	{
1454
		$oDb = WbDatabase::getInstance();
1455
		$oReg = WbAdaptor::getInstance();
1456
		$aRetval = array();
1457
	// try to remove access files and build new folder protect files
1458
        $sTreeToDelete = $oReg->AppPath.$oReg->PagesDir;
1459

    
1460
    	if(($sTreeToDelete!='') && is_writeable($sTreeToDelete)==true)
1461
		{
1462
			$aDeleteLog = array();
1463
            DeleteAccessFilesTree($sTreeToDelete, $aDeleteLog);
1464
		// show details if debug is set
1465
            if($bShowDetails) { $aRetval = $aDeleteLog; }
1466
    	}
1467
	// Reformat/rebuild all existing access files
1468
		$sql  = 'SELECT `page_id`,`root_parent`,`parent`,`link`,`level`,`page_trail` '
1469
		      . 'FROM `'.$oDb->TablePrefix.'pages` '
1470
		      . 'WHERE `link` != \'\' '
1471
		      . 'ORDER BY `link`';
1472
        if (($oPage = $oDb->query($sql)))
1473
        {
1474
            $iFileCounter = 0;
1475
		// iterate over all existing page records
1476
            while (($aPageRecord = $oPage->fetchRow(MYSQL_ASSOC)))
1477
            {
1478
		// --- begin reorg tree structure ------------------------------------------------
1479
			// rebuild level entries
1480
				$sql = 'SELECT `level`+1 AS `level`, `page_trail` '
1481
				     . 'FROM `'.$oDb->TablePrefix.'pages` '
1482
					 . 'WHERE `page_id`='.$aPageRecord['parent'];
1483
			// search for parent record
1484
				$oParent = $oDb->query($sql);
1485
				if(($aParentRecord = $oParent->fetchRow(MYSQLI_ASSOC)))
1486
				{
1487
				// get values from existing parent record
1488
					$aPageRecord['level'] = intval($aParentRecord['level']);
1489
					$aPageRecord['root_parent'] = intval($aParentRecord['page_trail']);
1490
					$aPageRecord['page_trail'] = (string)$aParentRecord['page_trail'].','.(string)$aPageRecord['page_id'];
1491
				}else
1492
				{
1493
				// set as root record if no parentrecord exists
1494
					$aPageRecord['level'] = 0;
1495
					$aPageRecord['root_parent'] = $aPageRecord['page_id'];
1496
					$aPageRecord['page_trail'] = (string)$aPageRecord['page_id'];
1497
				}
1498
			// update current record with regenerated values
1499
                $sql  = 'UPDATE `'.$oDb->TablePrefix.'pages` '
1500
				      . 'SET `root_parent`='.$aPageRecord['root_parent'].', '
1501
				      .     '`level`='.$aPageRecord['level'].', '
1502
				      .     '`page_trail`=\''.$aPageRecord['page_trail'].'\' '
1503
				      . 'WHERE `page_id`='.$aPageRecord['page_id'];
1504
				$oDb->query($sql);
1505
		// --- end reorg tree structure --------------------------------------------------
1506
                $sFilename = $oReg->AppPath.$oReg->PagesDir.ltrim($aPageRecord['link'],'/').$oReg->PageExtension;
1507
				$oAccessFile = new AccessFile($sFilename, $aPageRecord['page_id']);
1508
				$oAccessFile->write();
1509
				unset($oAccessFile);
1510
                $iFileCounter++;
1511
            }
1512
            $aRetval[] = 'Number of new formated access files: '.$iFileCounter;
1513
        }
1514
		return $aRetval;
1515
	} // end of function rebuild_all_accessfiles()
1516
} // endif
1517

    
1518
if(!function_exists('upgrade_modules')){
1519
	function upgrade_modules($aModuleList) {
1520
        global $database;
1521
    	foreach($aModuleList as $sModul) {
1522
    		if(file_exists(WB_PATH.'/modules/'.$sModul.'/upgrade.php')) {
1523
    			$currModulVersion = get_modul_version ($sModul, false);
1524
    			$newModulVersion =  get_modul_version ($sModul, true);
1525
    			if((version_compare($currModulVersion, $newModulVersion) <= 0)) {
1526
    				require(WB_PATH.'/modules/'.$sModul.'/upgrade.php');
1527
    			}
1528
    		}
1529
    	}
1530
    }
1531
}
1532

    
(31-31/36)