Project

General

Profile

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