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 2095 2014-02-03 11:56:36Z darkviper $
13
 * @filesource      $HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
14
 * @lastmodified    $Date: 2014-02-03 12:56:36 +0100 (Mon, 03 Feb 2014) $
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($sBaseDir, basename($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
	$retVal   = array();
712
	$oReg     = WbAdaptor::getInstance();
713
	$oTrans   = Translate::getInstance();
714
	$sAbsDir  = rtrim(str_replace('\\', '/', trim($sAbsDir)), '/').'/';
715
	if(($sAbsDir=='/') || ($sAbsDir == $oReg->AppPath))
716
	{
717
		return $retVal;
718
	}
719
	if($make_dir==true)
720
	{
721
		// Check to see if the folder already exists
722
		if(is_readable($sAbsDir)) {
723
			$retVal[] = basename($sAbsDir).'::'.$oTrans->MESSAGE_MEDIA_DIR_EXISTS;
724
		}
725
		if(!make_dir($sAbsDir) && !is_dir($sAbsDir))
726
		{
727
			$retVal[] = basename($sAbsDir).'::'.$oTrans->MESSAGE_MEDIA_DIR_NOT_MADE;
728
		}else
729
		{
730
			change_mode($sAbsDir);
731
		}
732
		return $retVal;
733
	}
734
	if(is_writable($sAbsDir))
735
	{
736
		$sResponse  = $_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently';
737
	// build file content
738
		$content =
739
			'<?php'."\n".
740
			'// *** This file is generated by WebsiteBaker Ver.'.$oReg->AppVersion."\n".
741
			'// *** Creation date: '.date('c')."\n".
742
			'// *** Do not modify this file manually'."\n".
743
			'// *** WB will rebuild this file from time to time!!'."\n".
744
			'// *************************************************'."\n".
745
			"\t".'header(\''.$sResponse.'\');'."\n".
746
			"\t".'header(\'Location: '.$oReg->AppUrl.'index.php\');'."\n".
747
			'// *************************************************'."\n";
748
		$filename = $sAbsDir.'/index.php';
749
	// write content into file
750
		if(is_writable($filename) || !file_exists($filename))
751
		{
752
			if(file_put_contents($filename, $content))
753
			{
754
				$retVal[] = change_mode($filename);
755
			}else
756
			{
757
				$retVal[] = $oTrans->MESSAGE_GENERIC_BAD_PERMISSIONS.' :: '.$filename;
758
			}
759
		}
760
	}else
761
	{
762
		$retVal[] = $oTrans->MESSAGE_GENERIC_BAD_PERMISSIONS;
763
	}
764
	return $retVal;
765
}
766

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1451
if(!function_exists('rebuild_all_accessfiles'))
1452
{
1453
	function rebuild_all_accessfiles($bShowDetails=false )
1454
	{
1455
		$oDb = WbDatabase::getInstance();
1456
		$oReg = WbAdaptor::getInstance();
1457
	// try to remove access files and build new folder protect files
1458
        $sTreeToDelete = $oReg->AppPath.$oReg->PagesDir;
1459
    	if(($sTreeToDelete!='') && is_writeable($sTreeToDelete)==true)
1460
		{
1461
			$aDeleteLog = array();
1462
            DeleteAccessFilesTree($sTreeToDelete, $aDeleteLog);
1463
		// show details if debug is set
1464
            if($bShowDetails) { $aRetval = $aDeleteLog; }
1465
    	}
1466
	// set logging informations
1467
		$aRetval = array_merge((isset($aRetval) ? $aRetval : array()),
1468
		                       createFolderProtectFile(rtrim( $oReg->AppPath.$oReg->PagesDir, '/') ));
1469
	// Reformat/rebuild all existing access files
1470
		$sql  = 'SELECT `page_id`,`root_parent`,`parent`,`link`,`level`,`page_trail` '
1471
		      . 'FROM `'.$oDb->TablePrefix.'pages` '
1472
		      . 'WHERE `link` != \'\' '
1473
		      . 'ORDER BY `link`';
1474
        if (($oPage = $oDb->query($sql)))
1475
        {
1476
            $iFileCounter = 0;
1477
            while (($aPageRecord = $oPage->fetchRow(MYSQL_ASSOC)))
1478
            {
1479
		// --- begin reorg tree structure ------------------------------------------------
1480
			// rebuild level entries
1481
				$sql = 'SELECT `level`+1 AS `level`, `page_trail` '
1482
				     . 'FROM `'.$oDb->TablePrefix.'pages` '
1483
					 . 'WHERE `page_id`='.$aPageRecord['parent'];
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
				$sPageTreeRoot = $oReg->AppPath.$oReg->PagesDir;
1507
                $sFilename = ($aPageRecord['link']).$oReg->PageExtension;
1508
				$oAccessFile = new AccessFile($sPageTreeRoot, $sFilename, $aPageRecord['page_id']);
1509
				$oAccessFile->write();
1510
				unset($oAccessFile);
1511
                $iFileCounter++;
1512
            }
1513
            $aRetval[] = 'Number of new formated access files: '.$iFileCounter;
1514
        }
1515
		return $aRetval;
1516
	} // end of function rebuild_all_accessfiles()
1517
} // endif
1518

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

    
(34-34/39)