Project

General

Profile

1
<?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
 *  * @requirements    PHP 5.2.2 and higher
13
 * @version         $Id: functions.php 1373 2011-01-10 12:14:10Z Luisehahne $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/functions.php $
15
 * @lastmodified    $Date: 2011-01-10 13:14:10 +0100 (Mon, 10 Jan 2011) $
16
 *
17
*/
18

    
19
// Stop this file from being accessed directly
20
if(!defined('WB_URL')) {
21
	header('Location: ../index.php');
22
	exit;
23
}
24

    
25
// Define that this file has been loaded
26
define('FUNCTIONS_FILE_LOADED', true);
27

    
28
/**
29
 * @description: recursively delete a non empty directory
30
 * @param string $directory :
31
 * @param bool $empty : true if you want the folder just emptied, but not deleted
32
 *                      false, or just simply leave it out, the given directory will be deleted, as well
33
 * @return boolean: list of ro-dirs
34
 * @from http://www.php.net/manual/de/function.rmdir.php#98499
35
 */
36
function rm_full_dir($directory, $empty = false) {
37

    
38
    if(substr($directory,-1) == "/")
39
	{
40
        $directory = substr($directory,0,-1);
41
    }
42

    
43
    // If suplied dirname is a file then unlink it
44
    if (is_file( $directory ))
45
	{
46
        return unlink($directory);
47
    }
48

    
49
    if(!file_exists($directory) || !is_dir($directory))
50
	{
51
        return false;
52
    } elseif(!is_readable($directory))
53
	{
54
        return false;
55
    } else {
56
        $directoryHandle = opendir($directory);
57

    
58
        while ($contents = readdir($directoryHandle))
59
		{
60
            if($contents != '.' && $contents != '..')
61
			{
62
                $path = $directory . "/" . $contents;
63

    
64
                if(is_dir($path))
65
				{
66
                    rm_full_dir($path);
67
                } else {
68
                    unlink($path);
69
                }
70
            }
71
        }
72

    
73
        closedir($directoryHandle);
74

    
75
        if($empty == false)
76
		{
77
            if(!rmdir($directory))
78
			{
79
                return false;
80
            }
81
        }
82

    
83
        return true;
84
    }
85
}
86

    
87
/*
88
 * returns a recursive list of all subdirectories from a given directory
89
 * @access  public
90
 * @param   string  $directory: from this dir the recursion will start
91
 * @param   bool    $show_hidden:  if set to TRUE also hidden dirs (.dir) will be shown
92
 * @return  array
93
 * example:
94
 *  /srv/www/httpdocs/wb/media/a/b/c/
95
 *  /srv/www/httpdocs/wb/media/a/b/d/
96
 * directory_list('/srv/www/httpdocs/wb/media/') will return:
97
 *  /a
98
 *  /a/b
99
 *  /a/b/c
100
 *  /a/b/d
101
 */
102
 function directory_list($directory, $show_hidden = false)
103
{
104
	$result_list = array();
105
	if (is_dir($directory))
106
    {
107
    	$dir = dir($directory); // Open the directory
108
    	while (false !== $entry = $dir->read()) // loop through the directory
109
		{
110
			if($entry == '.' || $entry == '..') { continue; } // Skip pointers
111
			if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
112
    		if (is_dir("$directory/$entry")) // Add dir and contents to list
113
			{
114
    			$result_list = array_merge($result_list, directory_list("$directory/$entry"));
115
    			$result_list[] = "$directory/$entry";
116
    		}
117
    	}
118
        $dir->close();
119
    }
120

    
121
	// sorting
122
	if(natcasesort($result_list))
123
	{
124
		// new indexing
125
		$result_list = array_merge($result_list);
126
	}
127
	return $result_list; // Now return the list
128
}
129

    
130
// Function to open a directory and add to a dir list
131
function chmod_directory_contents($directory, $file_mode)
132
{
133
	if (is_dir($directory))
134
    {
135
    	// Set the umask to 0
136
    	$umask = umask(0);
137
    	// Open the directory then loop through its contents
138
    	$dir = dir($directory);
139
    	while (false !== $entry = $dir->read())
140
		{
141
    		// Skip pointers
142
    		if($entry[0] == '.') { continue; }
143
    		// Chmod the sub-dirs contents
144
    		if(is_dir("$directory/$entry"))
145
			{
146
    			chmod_directory_contents($directory.'/'.$entry, $file_mode);
147
    		}
148
    		change_mode($directory.'/'.$entry);
149
    	}
150
        $dir->close();
151
    	// Restore the umask
152
    	umask($umask);
153
    }
154
}
155

    
156
/**
157
* Scan a given directory for dirs and files.
158
*
159
* usage: scan_current_dir ($root = '' )
160
*
161
* @param     $root   set a absolute rootpath as string. if root is empty the current path will be scan
162
* @param     $search set a search pattern for files, empty search brings all files
163
* @access    public
164
* @return    array    returns a natsort array with keys 'path' and 'filename'
165
*
166
*/
167
if(!function_exists('scan_current_dir'))
168
{
169
	function scan_current_dir($root = '', $search = '/.*/')
170
	{
171
	    $FILE = array();
172
		$array = array();
173
	    clearstatcache();
174
	    $root = empty ($root) ? getcwd() : $root;
175
	    if (($handle = opendir($root)))
176
	    {
177
	    // Loop through the files and dirs an add to list  DIRECTORY_SEPARATOR
178
	        while (false !== ($file = readdir($handle)))
179
	        {
180
	            if (substr($file, 0, 1) != '.' && $file != 'index.php')
181
	            {
182
	                if (is_dir($root.'/'.$file))
183
	                {
184
	                    $FILE['path'][] = $file;
185
	                } elseif (preg_match($search, $file, $array) )
186
                    {
187
	                    $FILE['filename'][] = $array[0];
188
	                }
189
	            }
190
	        }
191
	        $close_verz = closedir($handle);
192
	    }
193

    
194
		// sorting
195
	    if (isset ($FILE['path']) && natcasesort($FILE['path']))
196
	    {
197
			// new indexing
198
	        $FILE['path'] = array_merge($FILE['path']);
199
	    }
200
		// sorting
201
	    if (isset ($FILE['filename']) && natcasesort($FILE['filename']))
202
	    {
203
			// new indexing
204
	        $FILE['filename'] = array_merge($FILE['filename']);
205
	    }
206
	    return $FILE;
207
	}
208
}
209

    
210
// Function to open a directory and add to a file list
211
function file_list($directory, $skip = array(), $show_hidden = false)
212
{
213
	$result_list = array();
214
	if (is_dir($directory))
215
    {
216
    	$dir = dir($directory); // Open the directory
217
		while (false !== ($entry = $dir->read())) // loop through the directory
218
		{
219
			if($entry == '.' || $entry == '..') { continue; } // Skip pointers
220
			if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
221
			if( sizeof($skip) > 0 && in_array($entry, $skip) ) { continue; } // Check if we to skip anything else
222
			if(is_file( $directory.'/'.$entry)) // Add files to list
223
			{
224
				$result_list[] = $directory.'/'.$entry;
225
			}
226
		}
227
		$dir->close(); // Now close the folder object
228
	}
229

    
230
    // make the list nice. Not all OS do this itself
231
   if(natcasesort($result_list))
232
   {
233
		$result_list = array_merge($result_list);
234
   }
235

    
236
	return $result_list;
237
}
238

    
239
// Function to get a list of home folders not to show
240
function get_home_folders()
241
{
242
	global $database, $admin;
243
	$home_folders = array();
244
	// Only return home folders is this feature is enabled
245
	// and user is not admin
246
//	if(HOME_FOLDERS AND ($_SESSION['GROUP_ID']!='1')) {
247
	if(HOME_FOLDERS AND (!in_array('1',explode(',', $_SESSION['GROUPS_ID']))))
248
	{
249
		$sql = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` WHERE `home_folder` != "'.$admin->get_home_folder().'"';
250
		$query_home_folders = $database->query($sql);
251
		if($query_home_folders->numRows() > 0)
252
		{
253
			while($folder = $query_home_folders->fetchRow())
254
			{
255
				$home_folders[$folder['home_folder']] = $folder['home_folder'];
256
			}
257
		}
258
		function remove_home_subs($directory = '/', $home_folders = '')
259
		{
260
			if( ($handle = opendir(WB_PATH.MEDIA_DIRECTORY.$directory)) )
261
			{
262
				// Loop through the dirs to check the home folders sub-dirs are not shown
263
				while(false !== ($file = readdir($handle)))
264
				{
265
					if($file[0] != '.' && $file != 'index.php')
266
					{
267
						if(is_dir(WB_PATH.MEDIA_DIRECTORY.$directory.'/'.$file))
268
						{
269
							if($directory != '/')
270
							{
271
								$file = $directory.'/'.$file;
272
							}
273
							else
274
							{
275
								$file = '/'.$file;
276
							}
277
							foreach($home_folders AS $hf)
278
							{
279
								$hf_length = strlen($hf);
280
								if($hf_length > 0)
281
								{
282
									if(substr($file, 0, $hf_length+1) == $hf)
283
									{
284
										$home_folders[$file] = $file;
285
									}
286
								}
287
							}
288
							$home_folders = remove_home_subs($file, $home_folders);
289
						}
290
					}
291
				}
292
			}
293
			return $home_folders;
294
		}
295
		$home_folders = remove_home_subs('/', $home_folders);
296
	}
297
	return $home_folders;
298
}
299

    
300
/*
301
 * @param object &$wb: $wb from frontend or $admin from backend
302
 * @return array: list of new entries
303
 * @description: callback remove path in files/dirs stored in array
304
 * @example: array_walk($array,'remove_path',PATH);
305
 */
306
//
307
function remove_path(&$path, $key, $vars = '')
308
{
309
	$path = str_replace($vars, '', $path);
310
}
311

    
312
/*
313
 * @param object &$wb: $wb from frontend or $admin from backend
314
 * @return array: list of ro-dirs
315
 * @description: returns a list of directories beyound /wb/media which are ReadOnly for current user
316
 */
317
function media_dirs_ro( &$wb )
318
{
319
	global $database;
320
	// if user is admin or home-folders not activated then there are no restrictions
321
	$allow_list = array();
322
	if( $wb->get_user_id() == 1 || !HOME_FOLDERS )
323
	{
324
		return array();
325
	}
326
	// at first read any dir and subdir from /media
327
	$full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
328
	// add own home_folder to allow-list
329
	if( $wb->get_home_folder() )
330
	{
331
		// old: $allow_list[] = get_home_folder();
332
		$allow_list[] = $wb->get_home_folder();
333
	}
334
	// get groups of current user
335
	$curr_groups = $wb->get_groups_id();
336
	// if current user is in admin-group
337
	 if( ($admin_key = array_search('1', $curr_groups)) !== false)
338
	{
339
		// remove admin-group from list
340
		unset($curr_groups[$admin_key]);
341
		// search for all users where the current user is admin from
342
		foreach( $curr_groups as $group)
343
		{
344
			$sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
345
			$sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
346
			if( ($res_hf = $database->query($sql)) != null )
347
			{
348
				while( $rec_hf = $res_hf->fetchrow() )
349
				{
350
					$allow_list[] = $rec_hf['home_folder'];
351
				}
352
			}
353
		}
354
	}
355
	$tmp_array = $full_list;
356
	// create a list for readonly dir
357
    $array = array();
358
	while( sizeof($tmp_array) > 0)
359
	{
360
        $tmp = array_shift($tmp_array);
361
        $x = 0;
362
		while($x < sizeof($allow_list))
363
		{
364
			if(strpos ($tmp,$allow_list[$x])) {
365
				$array[] = $tmp;
366
			}
367
			$x++;
368
		}
369
	}
370

    
371
	$full_list = array_diff( $full_list, $array );
372
	$tmp = array();
373
	$full_list = array_merge($tmp,$full_list);
374

    
375
	return $full_list;
376
}
377

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

    
424
	$tmp_array = $full_list;
425
	// create a list for readwrite dir
426
	while( sizeof($tmp_array) > 0)
427
	{
428
        $tmp = array_shift($tmp_array);
429
        $x = 0;
430
		while($x < sizeof($allow_list))
431
		{
432
			if(strpos ($tmp,$allow_list[$x])) {
433
				$array[] = $tmp;
434
			}
435
			$x++;
436
		}
437
	}
438

    
439
	$tmp = array();
440
    $array = array_unique($array);
441
	$full_list = array_merge($tmp,$array);
442
    unset($array);
443
    unset($allow_list);
444

    
445
	return $full_list;
446
}
447

    
448
// Function to create directories
449
function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE)
450
{
451
	if(!is_dir($dir_name))
452
    {
453
		$umask = umask(0);
454
		mkdir($dir_name, $dir_mode);
455
		umask($umask);
456
		return true;
457
	} else {
458
		return false;	
459
	}
460
}
461

    
462
// Function to chmod files and directories
463
function change_mode($name)
464
{
465
	if(OPERATING_SYSTEM != 'windows')
466
    {
467
		// Only chmod if os is not windows
468
		if(is_dir($name))
469
        {
470
			$mode = OCTAL_DIR_MODE;
471
		}
472
        else
473
        {
474
			$mode = OCTAL_FILE_MODE;
475
		}
476

    
477
		if(file_exists($name))
478
        {
479
			$umask = umask(0);
480
			chmod($name, $mode);
481
			umask($umask);
482
			return true;
483
		}
484
        else
485
        {
486
			return false;	
487
		}
488
	}
489
    else
490
    {
491
		return true;
492
	}
493
}
494

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

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

    
532
// Function to work out root parent
533
function root_parent($page_id)
534
{
535
	global $database;
536
	// Get page details
537
	$sql = 'SELECT `parent`, `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
538
	$query_page = $database->query($sql);
539
	$fetch_page = $query_page->fetchRow();
540
	$parent = $fetch_page['parent'];
541
	$level = $fetch_page['level'];	
542
	if($level == 1)
543
	{
544
		return $parent;
545
	}
546
	elseif($parent == 0)
547
	{
548
		return $page_id;
549
	}
550
	else
551
	{	// Figure out what the root parents id is
552
		$parent_ids = array_reverse(get_parent_ids($page_id));
553
		return $parent_ids[0];
554
	}
555
}
556

    
557
// Function to get page title
558
function get_page_title($id)
559
{
560
	global $database;
561
	// Get title
562
	$sql = 'SELECT `page_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
563
	$page_title = $database->get_one($sql);
564
	return $page_title;
565
}
566

    
567
// Function to get a pages menu title
568
function get_menu_title($id)
569
{
570
	global $database;
571
	// Get title
572
	$sql = 'SELECT `menu_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
573
	$menu_title = $database->get_one($sql);
574
	return $menu_title;
575
}
576

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

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

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

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

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

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

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

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

    
682
// Function to convert a desired media filename to a clean filename
683
function media_filename($string)
684
{
685
	require_once(WB_PATH.'/framework/functions-utf8.php');
686
	$string = entities_to_7bit($string);
687
	// Now remove all bad characters
688
	$bad = array(
689
	'\'', // '
690
	'"', // "
691
	'`', // `
692
	'!', // !
693
	'@', // @
694
	'#', // #
695
	'$', // $
696
	'%', // %
697
	'^', // ^
698
	'&', // &
699
	'*', // *
700
	'=', // =
701
	'+', // +
702
	'|', // |
703
	'/', // /
704
	'\\', // \
705
	';', // ;
706
	':', // :
707
	',', // ,
708
	'?' // ?
709
	);
710
	$string = str_replace($bad, '', $string);
711
	// replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
712
	$string = preg_replace(array('/\.+/', '/\.+$/'), array('.', ''), $string);
713
	// Clean any page spacers at the end of string
714
	$string = trim($string);
715
	// Finally, return the cleaned string
716
	return $string;
717
}
718

    
719
// Function to work out a page link
720
if(!function_exists('page_link'))
721
{
722
	function page_link($link)
723
	{
724
		global $admin;
725
		return $admin->page_link($link);
726
	}
727
}
728

    
729
// Create a new file in the pages directory
730
function create_access_file($filename,$page_id,$level)
731
{
732
	global $admin, $MESSAGE;
733
	if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/'))
734
	{
735
		$admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE']);
736
	}
737
	else
738
	{
739
		// First make sure parent folder exists
740
		$parent_folders = explode('/',str_replace(WB_PATH.PAGES_DIRECTORY, '', dirname($filename)));
741
		$parents = '';
742
		foreach($parent_folders AS $parent_folder)
743
		{
744
			if($parent_folder != '/' AND $parent_folder != '')
745
			{
746
				$parents .= '/'.$parent_folder;
747
				if(!file_exists(WB_PATH.PAGES_DIRECTORY.$parents))
748
				{
749
					make_dir(WB_PATH.PAGES_DIRECTORY.$parents);
750
				}
751
			}	
752
		}
753
		// The depth of the page directory in the directory hierarchy
754
		// '/pages' is at depth 1
755
		$pages_dir_depth=count(explode('/',PAGES_DIRECTORY))-1;
756
		// Work-out how many ../'s we need to get to the index page
757
		$index_location = '';
758
		for($i = 0; $i < $level + $pages_dir_depth; $i++)
759
		{
760
			$index_location .= '../';
761
		}
762
		$content = ''.
763
'<?php
764
$page_id = '.$page_id.';
765
require("'.$index_location.'config.php");
766
require(WB_PATH."/index.php");
767
?>';
768
		$handle = fopen($filename, 'w');
769
		fwrite($handle, $content);
770
		fclose($handle);
771
		// Chmod the file
772
		change_mode($filename);
773
	}
774
}
775

    
776
// Function for working out a file mime type (if the in-built PHP one is not enabled)
777
if(!function_exists('mime_content_type'))
778
{
779
    function mime_content_type($filename) 
780
	{
781
	    $mime_types = array(
782
            'txt'	=> 'text/plain',
783
            'htm'	=> 'text/html',
784
            'html'	=> 'text/html',
785
            'php'	=> 'text/html',
786
            'css'	=> 'text/css',
787
            'js'	=> 'application/javascript',
788
            'json'	=> 'application/json',
789
            'xml'	=> 'application/xml',
790
            'swf'	=> 'application/x-shockwave-flash',
791
            'flv'	=> 'video/x-flv',
792

    
793
            // images
794
            'png'	=> 'image/png',
795
            'jpe'	=> 'image/jpeg',
796
            'jpeg'	=> 'image/jpeg',
797
            'jpg'	=> 'image/jpeg',
798
            'gif'	=> 'image/gif',
799
            'bmp'	=> 'image/bmp',
800
            'ico'	=> 'image/vnd.microsoft.icon',
801
            'tiff'	=> 'image/tiff',
802
            'tif'	=> 'image/tiff',
803
            'svg'	=> 'image/svg+xml',
804
            'svgz'	=> 'image/svg+xml',
805

    
806
            // archives
807
            'zip'	=> 'application/zip',
808
            'rar'	=> 'application/x-rar-compressed',
809
            'exe'	=> 'application/x-msdownload',
810
            'msi'	=> 'application/x-msdownload',
811
            'cab'	=> 'application/vnd.ms-cab-compressed',
812

    
813
            // audio/video
814
            'mp3'	=> 'audio/mpeg',
815
            'mp4'	=> 'audio/mpeg',
816
            'qt'	=> 'video/quicktime',
817
            'mov'	=> 'video/quicktime',
818

    
819
            // adobe
820
            'pdf'	=> 'application/pdf',
821
            'psd'	=> 'image/vnd.adobe.photoshop',
822
            'ai'	=> 'application/postscript',
823
            'eps'	=> 'application/postscript',
824
            'ps'	=> 'application/postscript',
825

    
826
            // ms office
827
            'doc'	=> 'application/msword',
828
            'rtf'	=> 'application/rtf',
829
            'xls'	=> 'application/vnd.ms-excel',
830
            'ppt'	=> 'application/vnd.ms-powerpoint',
831

    
832
            // open office
833
            'odt'	=> 'application/vnd.oasis.opendocument.text',
834
            'ods'	=> 'application/vnd.oasis.opendocument.spreadsheet',
835
        );
836

    
837
        $temp = explode('.',$filename);
838
        $ext = strtolower(array_pop($temp));
839

    
840
        if (array_key_exists($ext, $mime_types))
841
		{
842
            return $mime_types[$ext];
843
        }
844
        elseif (function_exists('finfo_open'))
845
		{
846
            $finfo = finfo_open(FILEINFO_MIME);
847
            $mimetype = finfo_file($finfo, $filename);
848
            finfo_close($finfo);
849
            return $mimetype;
850
        }
851
        else
852
		{
853
            return 'application/octet-stream';
854
        }
855
    }
856
}
857

    
858
// Generate a thumbnail from an image
859
function make_thumb($source, $destination, $size)
860
{
861
	// Check if GD is installed
862
	if(extension_loaded('gd') && function_exists('imageCreateFromJpeg'))
863
	{
864
		// First figure out the size of the thumbnail
865
		list($original_x, $original_y) = getimagesize($source);
866
		if ($original_x > $original_y)
867
		{
868
			$thumb_w = $size;
869
			$thumb_h = $original_y*($size/$original_x);
870
		}
871
		if ($original_x < $original_y)
872
		{
873
			$thumb_w = $original_x*($size/$original_y);
874
			$thumb_h = $size;
875
		}
876
		if ($original_x == $original_y)
877
		{
878
			$thumb_w = $size;
879
			$thumb_h = $size;	
880
		}
881
		// Now make the thumbnail
882
		$source = imageCreateFromJpeg($source);
883
		$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
884
		imagecopyresampled($dst_img,$source,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);
885
		imagejpeg($dst_img, $destination);
886
		// Clear memory
887
		imagedestroy($dst_img);
888
		imagedestroy($source);
889
	   // Return true
890
		return true;
891
	} else {
892
		return false;
893
	}
894
}
895

    
896
/*
897
 * Function to work-out a single part of an octal permission value
898
 *
899
 * @param mixed $octal_value: an octal value as string (i.e. '0777') or real octal integer (i.e. 0777 | 777)
900
 * @param string $who: char or string for whom the permission is asked( U[ser] / G[roup] / O[thers] )
901
 * @param string $action: char or string with the requested action( r[ead..] / w[rite..] / e|x[ecute..] )
902
 * @return boolean
903
 */
904
function extract_permission($octal_value, $who, $action)
905
{
906
	// Make sure that all arguments are set and $octal_value is a real octal-integer
907
	if( ($who == '') || ($action == '') || (preg_match( '/[^0-7]/', (string)$octal_value )) )
908
	{
909
		return false; // invalid argument, so return false
910
	}
911
	// convert $octal_value into a decimal-integer to be sure having a valid value
912
	$right_mask = octdec($octal_value);
913
	$action_mask = 0;
914
	// set the $action related bit in $action_mask
915
	switch($action[0]) // get action from first char of $action
916
	{
917
		case 'r':
918
		case 'R':
919
			$action_mask = 4; // set read-bit only (2^2)
920
			break;
921
		case 'w':
922
		case 'W':
923
			$action_mask = 2; // set write-bit only (2^1)
924
			break;
925
		case 'e':
926
		case 'E':
927
		case 'x':
928
		case 'X':
929
			$action_mask = 1; // set execute-bit only (2^0)
930
			break;
931
		default:
932
			return false; // undefined action name, so return false
933
	}
934
	// shift action-mask into the right position
935
	switch($who[0]) // get who from first char of $who
936
	{
937
		case 'u':
938
		case 'U':
939
			$action_mask <<= 3; // shift left 3 bits
940
		case 'g':
941
		case 'G':
942
			$action_mask <<= 3; // shift left 3 bits
943
		case 'o':
944
		case 'O':
945
			/* NOP */
946
			break;
947
		default:
948
			return false; // undefined who, so return false
949
	}
950
	return( ($right_mask & $action_mask) != 0 ); // return result of binary-AND
951
}
952

    
953
// Function to delete a page
954
	function delete_page($page_id)
955
	{
956
		global $admin, $database, $MESSAGE;
957
		// Find out more about the page
958
		$sql  = 'SELECT `page_id`, `menu_title`, `page_title`, `level`, `link`, `parent`, `modified_by`, `modified_when` ';
959
		$sql .= 'FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
960
		$results = $database->query($sql);
961
		if($database->is_error())    { $admin->print_error($database->get_error()); }
962
		if($results->numRows() == 0) { $admin->print_error($MESSAGE['PAGES']['NOT_FOUND']); }
963
		$results_array = $results->fetchRow();
964
		$parent     = $results_array['parent'];
965
		$level      = $results_array['level'];
966
		$link       = $results_array['link'];
967
		$page_title = $results_array['page_title'];
968
		$menu_title = $results_array['menu_title'];
969

    
970
		// Get the sections that belong to the page
971
		$sql = 'SELECT `section_id`, `module` FROM `'.TABLE_PREFIX.'sections` WHERE `page_id` = '.$page_id;
972
		$query_sections = $database->query($sql);
973
		if($query_sections->numRows() > 0)
974
		{
975
			while($section = $query_sections->fetchRow())
976
			{
977
				// Set section id
978
				$section_id = $section['section_id'];
979
				// Include the modules delete file if it exists
980
				if(file_exists(WB_PATH.'/modules/'.$section['module'].'/delete.php'))
981
				{
982
					include(WB_PATH.'/modules/'.$section['module'].'/delete.php');
983
				}
984
			}
985
		}
986
		// Update the pages table
987
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
988
		$database->query($sql);
989
		if($database->is_error())
990
		{
991
			$admin->print_error($database->get_error());
992
		}
993
		// Update the sections table
994
		$sql = 'DELETE FROM `'.TABLE_PREFIX.'sections` WHERE `page_id` = '.$page_id;
995
		$database->query($sql);
996
		if($database->is_error()) {
997
			$admin->print_error($database->get_error());
998
		}
999
		// Include the ordering class or clean-up ordering
1000
		include_once(WB_PATH.'/framework/class.order.php');
1001
		$order = new order(TABLE_PREFIX.'pages', 'position', 'page_id', 'parent');
1002
		$order->clean($parent);
1003
		// Unlink the page access file and directory
1004
		$directory = WB_PATH.PAGES_DIRECTORY.$link;
1005
		$filename = $directory.PAGE_EXTENSION;
1006
		$directory .= '/';
1007
		if(file_exists($filename))
1008
		{
1009
			if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/'))
1010
			{
1011
				$admin->print_error($MESSAGE['PAGES']['CANNOT_DELETE_ACCESS_FILE']);
1012
			}
1013
			else
1014
			{
1015
				unlink($filename);
1016
				if( file_exists($directory) &&
1017
				   (rtrim($directory,'/') != WB_PATH.PAGES_DIRECTORY) &&
1018
				   (substr($link, 0, 1) != '.'))
1019
				{
1020
					rm_full_dir($directory);
1021
				}
1022
			}
1023
		}
1024
	}
1025

    
1026
/*
1027
 * @param string $file: name of the file to read
1028
 * @param int $size: number of maximum bytes to read (0 = complete file)
1029
 * @return string: the content as string, false on error
1030
 */
1031
	function getFilePart($file, $size = 0)
1032
	{
1033
		$file_content = '';
1034
		if( file_exists($file) && is_file($file) && is_readable($file))
1035
		{
1036
			if($size == 0)
1037
			{
1038
				$size = filesize($file);
1039
			}
1040
			if(($fh = fopen($file, 'rb')))
1041
			{
1042
				if( ($file_content = fread($fh, $size)) !== false )
1043
				{
1044
					return $file_content;
1045
				}
1046
				fclose($fh);
1047
			}
1048
		}
1049
		return false;
1050
	}
1051

    
1052
	/**
1053
	* replace varnames with values in a string
1054
	*
1055
	* @param string $subject: stringvariable with vars placeholder
1056
	* @param array $replace: values to replace vars placeholder
1057
	* @return string
1058
	*/
1059
    function replace_vars($subject = '', &$replace = null )
1060
    {
1061
		if(is_array($replace))
1062
		{
1063
			foreach ($replace  as $key => $value)
1064
			{
1065
				$subject = str_replace("{{".$key."}}", $value, $subject);
1066
			}
1067
		}
1068
		return $subject;
1069
    }
1070

    
1071
// Load module into DB
1072
function load_module($directory, $install = false)
1073
{
1074
	global $database,$admin,$MESSAGE;
1075
	$retVal = false;
1076
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1077
	{
1078
		require($directory.'/info.php');
1079
		if(isset($module_name))
1080
		{
1081
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1082
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1083
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1084
			$module_function = strtolower($module_function);
1085
			// Check that it doesn't already exist
1086
			$sqlwhere = 'WHERE `type` = \'module\' AND `directory` = \''.$module_directory.'\'';
1087
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1088
			if( $database->get_one($sql) )
1089
			{
1090
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1091
			}else{
1092
				// Load into DB
1093
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1094
				$sqlwhere = '';
1095
			}
1096
			$sql .= '`directory` = \''.$module_directory.'\', ';
1097
			$sql .= '`name` = \''.$module_name.'\', ';
1098
			$sql .= '`description`= \''.addslashes($module_description).'\', ';
1099
			$sql .= '`type`= \'module\', ';
1100
			$sql .= '`function` = \''.$module_function.'\', ';
1101
			$sql .= '`version` = \''.$module_version.'\', ';
1102
			$sql .= '`platform` = \''.$module_platform.'\', ';
1103
			$sql .= '`author` = \''.addslashes($module_author).'\', ';
1104
			$sql .= '`license` = \''.addslashes($module_license).'\'';
1105
			$sql .= $sqlwhere;
1106
			$retVal = $database->query($sql);
1107
			// Run installation script
1108
			if($install == true)
1109
			{
1110
				if(file_exists($directory.'/install.php'))
1111
				{
1112
					require($directory.'/install.php');
1113
				}
1114
			}
1115
		}
1116
	}
1117
}
1118

    
1119
// Load template into DB
1120
function load_template($directory)
1121
{
1122
	global $database, $admin;
1123
	$retVal = false;
1124
	if(is_dir($directory) && file_exists($directory.'/info.php'))
1125
	{
1126
		require($directory.'/info.php');
1127
		if(isset($template_name))
1128
		{
1129
			if(!isset($template_license))
1130
            {
1131
              $template_license = 'GNU General Public License';
1132
            }
1133
			if(!isset($template_platform) && isset($template_designed_for))
1134
            {
1135
              $template_platform = $template_designed_for;
1136
            }
1137
			if(!isset($template_function))
1138
            {
1139
              $template_function = 'template';
1140
            }
1141
			// Check that it doesn't already exist
1142
			$sqlwhere = 'WHERE `type` = \'template\' AND `directory` = \''.$template_directory.'\'';
1143
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1144
			if( $database->get_one($sql) )
1145
			{
1146
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1147
			}else{
1148
				// Load into DB
1149
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1150
				$sqlwhere = '';
1151
			}
1152
			$sql .= '`directory` = \''.$template_directory.'\', ';
1153
			$sql .= '`name` = \''.$template_name.'\', ';
1154
			$sql .= '`description`= \''.addslashes($template_description).'\', ';
1155
			$sql .= '`type`= \'template\', ';
1156
			$sql .= '`function` = \''.$template_function.'\', ';
1157
			$sql .= '`version` = \''.$template_version.'\', ';
1158
			$sql .= '`platform` = \''.$template_platform.'\', ';
1159
			$sql .= '`author` = \''.addslashes($template_author).'\', ';
1160
			$sql .= '`license` = \''.addslashes($template_license).'\' ';
1161
			$sql .= $sqlwhere;
1162
			$retVal = $database->query($sql);
1163
		}
1164
	}
1165
	return $retVal;
1166
}
1167

    
1168
// Load language into DB
1169
function load_language($file)
1170
{
1171
	global $database,$admin;
1172
	$retVal = false;
1173
	if (file_exists($file) && preg_match('#^([A-Z]{2}.php)#', basename($file)))
1174
	{
1175
		// require($file);  it's to large
1176
		// read contents of the template language file into string
1177
		$data = @file_get_contents(WB_PATH.'/languages/'.str_replace('.php','',basename($file)).'.php');
1178
		// use regular expressions to fetch the content of the variable from the string
1179
		$language_name = get_variable_content('language_name', $data, false);
1180
		$language_code = get_variable_content('language_code', $data, false);
1181
		$language_author = get_variable_content('language_author', $data);
1182
		$language_version = get_variable_content('language_version', $data, false);
1183
		$language_platform = get_variable_content('language_platform', $data, false);
1184

    
1185
		if(isset($language_name))
1186
		{
1187
			if(!isset($language_license)) { $language_license = 'GNU General Public License'; }
1188
			if(!isset($language_platform) && isset($language_designed_for)) { $language_platform = $language_designed_for; }
1189
			// Check that it doesn't already exist
1190
			$sqlwhere = 'WHERE `type` = \'language\' AND `directory` = \''.$language_code.'\'';
1191
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1192
			if( $database->get_one($sql) )
1193
			{
1194
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1195
			}else{
1196
				// Load into DB
1197
				$sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1198
				$sqlwhere = '';
1199
			}
1200
			$sql .= '`directory` = \''.$language_code.'\', ';
1201
			$sql .= '`name` = \''.$language_name.'\', ';
1202
			$sql .= '`type`= \'language\', ';
1203
			$sql .= '`version` = \''.$language_version.'\', ';
1204
			$sql .= '`platform` = \''.$language_platform.'\', ';
1205
			$sql .= '`author` = \''.addslashes($language_author).'\', ';
1206
			$sql .= '`license` = \''.addslashes($language_license).'\' ';
1207
			$sql .= $sqlwhere;
1208
			$retVal = $database->query($sql);
1209
		}
1210
	}
1211
	return $retVal;
1212
}
1213

    
1214
// Upgrade module info in DB, optionally start upgrade script
1215
function upgrade_module($directory, $upgrade = false)
1216
{
1217
	global $database, $admin, $MESSAGE, $new_module_version;
1218
	$mod_directory = WB_PATH.'/modules/'.$directory;
1219
	if(file_exists($mod_directory.'/info.php'))
1220
	{
1221
		require($mod_directory.'/info.php');
1222
		if(isset($module_name))
1223
		{
1224
			if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1225
			if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1226
			if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1227
			$module_function = strtolower($module_function);
1228
			// Check that it does already exist
1229
			$sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` ';
1230
			$sql .= 'WHERE `directory` = \''.$module_directory.'\'';
1231
			if( $database->get_one($sql) )
1232
			{
1233
				// Update in DB
1234
				$sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1235
				$sql .= '`version` = "'.$module_version.'", ';
1236
				$sql .= '`description` = "'.addslashes($module_description).'", ';
1237
				$sql .= '`platform` = \''.$module_platform.'\', ';
1238
				$sql .= '`author` = \''.addslashes($module_author).'\', ';
1239
				$sql .= '`license` = \''.addslashes($module_license).'\' ';
1240
				$sql .= 'WHERE `directory` = \''.$module_directory.'\' ';
1241
				$database->query($sql);
1242
				if($database->is_error()) {
1243
					$admin->print_error($database->get_error());
1244
				}
1245

    
1246
				// Run upgrade script
1247
				if($upgrade == true)
1248
				{
1249
					if(file_exists($mod_directory.'/upgrade.php'))
1250
					{
1251
						require($mod_directory.'/upgrade.php');
1252
					}
1253
				}
1254
			}
1255
		}
1256
	}
1257
}
1258

    
1259
// extracts the content of a string variable from a string (save alternative to including files)
1260
if(!function_exists('get_variable_content'))
1261
{
1262
	function get_variable_content($search, $data, $striptags=true, $convert_to_entities=true)
1263
	{
1264
		$match = '';
1265
		// search for $variable followed by 0-n whitespace then by = then by 0-n whitespace
1266
		// then either " or ' then 0-n characters then either " or ' followed by 0-n whitespace and ;
1267
		// the variable name is returned in $match[1], the content in $match[3]
1268
		if (preg_match('/(\$' .$search .')\s*=\s*("|\')(.*)\2\s*;/', $data, $match))
1269
		{
1270
			if(strip_tags(trim($match[1])) == '$' .$search)
1271
			{
1272
				// variable name matches, return it's value
1273
				$match[3] = ($striptags == true) ? strip_tags($match[3]) : $match[3];
1274
				$match[3] = ($convert_to_entities == true) ? htmlentities($match[3]) : $match[3];
1275
				return $match[3];
1276
			}
1277
		}
1278
		return false;
1279
	}
1280
}
1281

    
1282
/*
1283
 * @param string $modulname: like saved in addons.directory
1284
 * @param boolean $source: true reads from database, false from info.php
1285
 * @return string:  the version as string, if not found returns null
1286
 */
1287

    
1288
	function get_modul_version($modulname, $source = true)
1289
	{
1290
		global $database;
1291
		$version = null;
1292
		if( $source != true )
1293
		{
1294
			$sql = 'SELECT `version` FROM `'.TABLE_PREFIX.'addons` WHERE `directory`=\''.$modulname.'\'';
1295
			$version = $database->get_one($sql);
1296
		} else {
1297
			$info_file = WB_PATH.'/modules/'.$modulname.'/info.php';
1298
			if(file_exists($info_file))
1299
			{
1300
				if(($info_file = file_get_contents($info_file)))
1301
				{
1302
					$version = get_variable_content('module_version', $info_file, false, false);
1303
					$version = ($version !== false) ? $version : null;
1304
				}
1305
			}
1306
		}
1307
		return $version;
1308
	}
1309

    
1310
/*
1311
 * @param string $varlist: commaseperated list of varnames to move into global space
1312
 * @return bool:  false if one of the vars already exists in global space (error added to msgQueue)
1313
 */
1314
	function vars2globals_wrapper($varlist)
1315
	{
1316
		$retval = true;
1317
		if( $varlist != '')
1318
		{
1319
			$vars = explode(',', $varlist);
1320
			foreach( $vars as $var)
1321
			{
1322
				if( isset($GLOBALS[$var]) )
1323
				{
1324
					ErrorLog::write( 'variabe $'.$var.' already defined in global space!!',__FILE__, __FUNCTION__, __LINE__);
1325
					$retval = false;
1326
				}else
1327
				{
1328
					global $$var;
1329
				}
1330
			}
1331
		}
1332
		return $retval;
1333
	}
1334

    
1335

    
(13-13/16)