Project

General

Profile

wb-2_10_x / branches / main / framework / functions.php @ 10

1
<?php
2
/**
3
 *
4
 * @category        frontend
5
 * @package         framework
6
 * @author          WebsiteBaker Project
7
 * @copyright       Ryan Djurovich
8
 * @copyright       WebsiteBaker Org. e.V.
9
 * @link            http://websitebaker.org/
10
 * @license         http://www.gnu.org/licenses/gpl.html
11
 * @platform        WebsiteBaker 2.8.3
12
 * @requirements    PHP 5.3.6 and higher
13
 * @version         $Id: functions.php 2 2017-07-02 15:14:29Z Manuela $
14
 * @filesource      $HeadURL: svn://isteam.dynxs.de/wb/2.10.x/branches/main/framework/functions.php $
15
 * @lastmodified    $Date: 2017-07-02 17:14:29 +0200 (Sun, 02 Jul 2017) $
16
 *
17
 */
18

    
19
// Define that this file has been loaded
20
define('FUNCTIONS_FILE_LOADED', true);
21

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

    
32
    if(substr($directory,-1) == "/") {
33
        $directory = substr($directory,0,-1);
34
    }
35
   // If suplied dirname is a file then unlink it
36
    if (is_file( $directory )) {
37
      $retval = unlink($directory);
38
      clearstatcache();
39
      return $retval;
40
    }
41
    if(!file_exists($directory) || !is_dir($directory)) {
42
        return false;
43
    } elseif(!is_readable($directory)) {
44
        return false;
45
    } else {
46
        $directoryHandle = opendir($directory);
47
        while ($contents = readdir($directoryHandle))
48
        {
49
            if($contents != '.' && $contents != '..')
50
            {
51
                $path = $directory . "/" . $contents;
52
                if(is_dir($path)) {
53
                    rm_full_dir($path);
54
                } else {
55
                    unlink($path);
56
                    clearstatcache();
57
                }
58
            }
59
        }
60
        closedir($directoryHandle);
61
        if($empty == false) {
62
            if(!rmdir($directory)) {
63
                return false;
64
            }
65
        }
66
        return true;
67
    }
68
}
69

    
70
/*
71
 * returns a recursive list of all subdirectories from a given directory
72
 * @access  public
73
 * @param   string  $directory: from this dir the recursion will start
74
 * @param   bool    $show_hidden:  if set to TRUE also hidden dirs (.dir) will be shown
75
 * @return  array
76
 * example:
77
 *  /srv/www/httpdocs/wb/media/a/b/c/
78
 *  /srv/www/httpdocs/wb/media/a/b/d/
79
 * directory_list('/srv/www/httpdocs/wb/media/') will return:
80
 *  /a
81
 *  /a/b
82
 *  /a/b/c
83
 *  /a/b/d
84
 */
85
 function directory_list($directory, $show_hidden = false)
86
{
87
    $result_list = array();
88
    if (is_dir($directory))
89
    {
90
        $dir = dir($directory); // Open the directory
91
        while (false !== $entry = $dir->read()) // loop through the directory
92
        {
93
            if($entry == '.' || $entry == '..') { continue; } // Skip pointers
94
            if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
95
            if (is_dir("$directory/$entry")) { // Add dir and contents to list
96
                $result_list = array_merge($result_list, directory_list("$directory/$entry"));
97
                $result_list[] = "$directory/$entry";
98
            }
99
        }
100
        $dir->close();
101
    }
102
    // sorting
103
    if(natcasesort($result_list)) {
104
        // new indexing
105
        $result_list = array_merge($result_list);
106
    }
107
    return $result_list; // Now return the list
108
}
109

    
110
// Function to open a directory and add to a dir list
111
function chmod_directory_contents($directory, $file_mode)
112
{
113
    if (is_dir($directory))
114
    {
115
        // Set the umask to 0
116
        $umask = umask(0);
117
        // Open the directory then loop through its contents
118
        $dir = dir($directory);
119
        while (false !== $entry = $dir->read())
120
        {
121
            // Skip pointers
122
            if($entry[0] == '.') { continue; }
123
            // Chmod the sub-dirs contents
124
            if(is_dir("$directory/$entry")) {
125
                chmod_directory_contents($directory.'/'.$entry, $file_mode);
126
            }
127
            change_mode($directory.'/'.$entry);
128
        }
129
        $dir->close();
130
        // Restore the umask
131
        umask($umask);
132
    }
133
}
134

    
135
/**
136
* Scan a given directory for dirs and files.
137
*
138
* usage: scan_current_dir ($root = '' )
139
*
140
* @param     $root   set a absolute rootpath as string. if root is empty the current path will be scan
141
* @param     $search set a search pattern for files, empty search brings all files
142
* @access    public
143
* @return    array    returns a natsort array with keys 'path' and 'filename'
144
*
145
*/
146
if(!function_exists('scan_current_dir'))
147
{
148
    function scan_current_dir($root = '', $search = '/.*/')
149
    {
150
        $FILE = array();
151
        $array = array();
152
        clearstatcache();
153
        $root = empty ($root) ? getcwd() : $root;
154
        if (($handle = opendir($root)))
155
        {
156
        // Loop through the files and dirs an add to list  DIRECTORY_SEPARATOR
157
            while (false !== ($file = readdir($handle)))
158
            {
159
                if (substr($file, 0, 1) != '.' && $file != 'index.php')
160
                {
161
                    if (is_dir($root.'/'.$file)) {
162
                        $FILE['path'][] = $file;
163
                    } elseif (preg_match($search, $file, $array) ) {
164
                        $FILE['filename'][] = $array[0];
165
                    }
166
                }
167
            }
168
            $close_verz = closedir($handle);
169
        }
170
        // sorting
171
        if (isset ($FILE['path']) && natcasesort($FILE['path'])) {
172
            // new indexing
173
            $FILE['path'] = array_merge($FILE['path']);
174
        }
175
        // sorting
176
        if (isset ($FILE['filename']) && natcasesort($FILE['filename'])) {
177
            // new indexing
178
            $FILE['filename'] = array_merge($FILE['filename']);
179
        }
180
        return $FILE;
181
    }
182
}
183

    
184
// Function to open a directory and add to a file list
185
function file_list($directory, $skip = array(), $show_hidden = false)
186
{
187
    $result_list = array();
188
    if (is_dir($directory))
189
    {
190
        $dir = dir($directory); // Open the directory
191
        while (false !== ($entry = $dir->read())) // loop through the directory
192
        {
193
            if($entry == '.' || $entry == '..') { continue; } // Skip pointers
194
            if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files
195
            if( sizeof($skip) > 0 && in_array($entry, $skip) ) { continue; } // Check if we to skip anything else
196
            if(is_file( $directory.'/'.$entry)) { // Add files to list
197
                $result_list[] = $directory.'/'.$entry;
198
            }
199
        }
200
        $dir->close(); // Now close the folder object
201
    }
202

    
203
    // make the list nice. Not all OS do this itself
204
    if(natcasesort($result_list)) {
205
        $result_list = array_merge($result_list);
206
    }
207
    return $result_list;
208
}
209

    
210
// Function to get a list of home folders not to show
211
function get_home_folders()
212
{
213
    global $database, $admin;
214
    $home_folders = array();
215
    // Only return home folders is this feature is enabled
216
    // and user is not admin
217
//    if(HOME_FOLDERS AND ($_SESSION['GROUP_ID']!='1')) {
218
    if(HOME_FOLDERS AND (!in_array('1',explode(',', $_SESSION['GROUPS_ID']))))
219
    {
220
        $sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
221
        $sql .= 'WHERE `home_folder`!=\''.$admin->get_home_folder().'\'';
222
        $query_home_folders = $database->query($sql);
223
        if($query_home_folders->numRows() > 0)
224
        {
225
            while($folder = $query_home_folders->fetchRow()) {
226
                $home_folders[$folder['home_folder']] = $folder['home_folder'];
227
            }
228
        }
229
        function remove_home_subs($directory = '/', $home_folders = '')
230
        {
231
            if( ($handle = opendir(WB_PATH.MEDIA_DIRECTORY.$directory)) )
232
            {
233
                // Loop through the dirs to check the home folders sub-dirs are not shown
234
                while(false !== ($file = readdir($handle)))
235
                {
236
                    if($file[0] != '.' && $file != 'index.php')
237
                    {
238
                        if(is_dir(WB_PATH.MEDIA_DIRECTORY.$directory.'/'.$file))
239
                        {
240
                            if($directory != '/') {
241
                                $file = $directory.'/'.$file;
242
                            }else {
243
                                $file = '/'.$file;
244
                            }
245
                            foreach($home_folders AS $hf)
246
                            {
247
                                $hf_length = strlen($hf);
248
                                if($hf_length > 0) {
249
                                    if(substr($file, 0, $hf_length+1) == $hf) {
250
                                        $home_folders[$file] = $file;
251
                                    }
252
                                }
253
                            }
254
                            $home_folders = remove_home_subs($file, $home_folders);
255
                        }
256
                    }
257
                }
258
            }
259
            return $home_folders;
260
        }
261
        $home_folders = remove_home_subs('/', $home_folders);
262
    }
263
    return $home_folders;
264
}
265

    
266
/*
267
 * @param object &$wb: $wb from frontend or $admin from backend
268
 * @return array: list of new entries
269
 * @description: callback remove path in files/dirs stored in array
270
 * @example: array_walk($array,'remove_path',PATH);
271
 */
272
//
273
function remove_path(&$path, $key, $vars = '')
274
{
275
    $path = str_replace($vars, '', $path);
276
}
277

    
278
/*
279
 * @param object &$wb: $wb from frontend or $admin from backend
280
 * @return array: list of ro-dirs
281
 * @description: returns a list of directories beyound /wb/media which are ReadOnly for current user
282
 */
283
function media_dirs_ro( &$wb )
284
{
285
    global $database;
286
    // if user is admin or home-folders not activated then there are no restrictions
287
    $allow_list = array();
288
    if( $wb->get_user_id() == 1 || !HOME_FOLDERS ) {
289
        return array();
290
    }
291
    // at first read any dir and subdir from /media
292
    $full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
293
    // add own home_folder to allow-list
294
    if( $wb->get_home_folder() ) {
295
        // old: $allow_list[] = get_home_folder();
296
        $allow_list[] = $wb->get_home_folder();
297
    }
298
    // get groups of current user
299
    $curr_groups = $wb->get_groups_id();
300
    // if current user is in admin-group
301
    if( ($admin_key = array_search('1', $curr_groups)) !== false)
302
    {
303
        // remove admin-group from list
304
        unset($curr_groups[$admin_key]);
305
        // search for all users where the current user is admin from
306
        foreach( $curr_groups as $group)
307
        {
308
            $sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
309
            $sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
310
            if( ($res_hf = $database->query($sql)) != null ) {
311
                while( $rec_hf = $res_hf->fetchrow() ) {
312
                    $allow_list[] = $rec_hf['home_folder'];
313
                }
314
            }
315
        }
316
    }
317
    $tmp_array = $full_list;
318
    // create a list for readonly dir
319
    $array = array();
320
    while( sizeof($tmp_array) > 0)
321
    {
322
        $tmp = array_shift($tmp_array);
323
        $x = 0;
324
        while($x < sizeof($allow_list)) {
325
            if(strpos ($tmp,$allow_list[$x])) {
326
                $array[] = $tmp;
327
            }
328
            $x++;
329
        }
330
    }
331
    $full_list = array_diff( $full_list, $array );
332
    $tmp = array();
333
    $full_list = array_merge($tmp,$full_list);
334
    return $full_list;
335
}
336

    
337
/*
338
 * @param object &$wb: $wb from frontend or $admin from backend
339
 * @return array: list of rw-dirs
340
 * @description: returns a list of directories beyound /wb/media which are ReadWrite for current user
341
 */
342
function media_dirs_rw ( &$wb )
343
{
344
    global $database;
345
    // if user is admin or home-folders not activated then there are no restrictions
346
    // at first read any dir and subdir from /media
347
    $full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
348
    $array = array();
349
    $allow_list = array();
350
    if( ($wb->ami_group_member('1')) && !HOME_FOLDERS ) {
351
        return $full_list;
352
    }
353
    // add own home_folder to allow-list
354
    if( $wb->get_home_folder() ) {
355
          $allow_list[] = $wb->get_home_folder();
356
    } else {
357
        $array = $full_list;
358
    }
359
    // get groups of current user
360
    $curr_groups = $wb->get_groups_id();
361
    // if current user is in admin-group
362
    if( ($admin_key = array_search('1', $curr_groups)) == true)
363
    {
364
        // remove admin-group from list
365
        // unset($curr_groups[$admin_key]);
366
        // search for all users where the current user is admin from
367
        foreach( $curr_groups as $group)
368
        {
369
            $sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
370
            $sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
371
            if( ($res_hf = $database->query($sql)) != null ) {
372
                while( $rec_hf = $res_hf->fetchrow() ) {
373
                    $allow_list[] = $rec_hf['home_folder'];
374
                }
375
            }
376
        }
377
    }
378

    
379
    $tmp_array = $full_list;
380
    // create a list for readwrite dir
381
    while( sizeof($tmp_array) > 0)
382
    {
383
        $tmp = array_shift($tmp_array);
384
        $x = 0;
385
        while($x < sizeof($allow_list)) {
386
            if(strpos ($tmp,$allow_list[$x])) {
387
                $array[] = $tmp;
388
            }
389
            $x++;
390
        }
391
    }
392
    $tmp = array();
393
    $array = array_unique($array);
394
    $full_list = array_merge($tmp,$array);
395
    unset($array);
396
    unset($allow_list);
397
    return $full_list;
398
}
399

    
400
// Function to create directories
401
function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE, $recursive=true)
402
{
403
    $retVal = false;
404
    if(!is_dir($dir_name))
405
    {
406
        $retVal = mkdir($dir_name, $dir_mode,$recursive);
407
    }
408
    return $retVal;
409
}
410

    
411
// Function to chmod files and directories
412
function change_mode($name)
413
{
414
    if(OPERATING_SYSTEM != 'windows')
415
    {
416
        // Only chmod if os is not windows
417
        if(is_dir($name)) {
418
            $mode = OCTAL_DIR_MODE;
419
        }else {
420
            $mode = OCTAL_FILE_MODE;
421
        }
422
        if(file_exists($name)) {
423
            $umask = umask(0);
424
            chmod($name, $mode);
425
            umask($umask);
426
            return true;
427
        }else {
428
            return false;
429
        }
430
    }else {
431
        return true;
432
    }
433
}
434

    
435
// Function to figure out if a parent exists
436
function is_parent($page_id)
437
{
438
    global $database;
439
    // Get parent
440
    $sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.intval($page_id);
441
    $parent = $database->get_one($sql);
442
    // If parent isnt 0 return its ID
443
    if(is_null($parent)) {
444
        return false;
445
    }else {
446
        return $parent;
447
    }
448
}
449

    
450
// Function to work out level
451
function level_count($page_id)
452
{
453
    global $database;
454
    // Get page parent
455
    $sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.intval($page_id);
456
    $parent = $database->get_one($sql);
457
    if($parent > 0)
458
    {    // Get the level of the parent
459
        $sql = 'SELECT `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.intval($parent);
460
        $level = intval($database->get_one($sql));
461
        return $level+1;
462
    }else {
463
        return 0;
464
    }
465
}
466

    
467
// Function to work out root parent
468
function root_parent($page_id)
469
{
470
    global $database;
471
    // Get page details
472
    $sql = 'SELECT `parent`, `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.intval($page_id);
473
    $query_page = $database->query($sql);
474
    $fetch_page = $query_page->fetchRow();
475
    $parent = intval($fetch_page['parent']);
476
    $level = intval($fetch_page['level']);
477
    if($level == 1) {
478
        return $parent;
479
    }elseif($parent == 0) {
480
        return $page_id;
481
    }else {    // Figure out what the root parents id is
482
        $parent_ids = array_reverse(get_parent_ids($page_id));
483
        return $parent_ids[0];
484
    }
485
}
486

    
487
// Function to get page title
488
function get_page_title($id)
489
{
490
    global $database;
491
    // Get title
492
    $sql = 'SELECT `page_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.intval($id);
493
    $page_title = $database->get_one($sql);
494
    return $page_title;
495
}
496

    
497
// Function to get a pages menu title
498
function get_menu_title($id)
499
{
500
    global $database;
501
    // Get title
502
    $sql = 'SELECT `menu_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.intval($id);
503
    $menu_title = $database->get_one($sql);
504
    return $menu_title;
505
}
506

    
507
// Function to get all parent page titles
508
function get_parent_titles($parent_id)
509
{
510
    $titles[] = get_menu_title($parent_id);
511
    if(is_parent($parent_id) != false) {
512
        $parent_titles = get_parent_titles(is_parent($parent_id));
513
        $titles = array_merge($titles, $parent_titles);
514
    }
515
    return $titles;
516
}
517

    
518
// Function to get all parent page id's
519
function get_parent_ids($parent_id)
520
{
521
    $ids[] = intval($parent_id);
522
    if(is_parent($parent_id) != false) {
523
        $parent_ids = get_parent_ids(is_parent($parent_id));
524
        $ids = array_merge($ids, $parent_ids);
525
    }
526
    return $ids;
527
}
528

    
529
// Function to genereate page trail
530
function get_page_trail($page_id)
531
{
532
    return implode(',', array_reverse(get_parent_ids($page_id)));
533
}
534

    
535
// Function to get all sub pages id's
536
function get_subs($parent, array $subs )
537
{
538
    // Connect to the database
539
    global $database;
540
    // Get id's
541
    $sql = 'SELECT `page_id` FROM `'.TABLE_PREFIX.'pages` WHERE `parent` = '.intval($parent);
542
    if( ($query = $database->query($sql)) ) {
543
        while($fetch = $query->fetchRow( MYSQLI_ASSOC )) {
544
            $subs[] = intval($fetch['page_id']);
545
            // Get subs of this sub recursive
546
            $subs = get_subs($fetch['page_id'], $subs);
547
        }
548
    }
549
    // Return subs array
550
    return $subs;
551
}
552

    
553
// Function as replacement for php's htmlspecialchars()
554
// Will not mangle HTML-entities
555
function my_htmlspecialchars($string)
556
{
557
    $string = preg_replace('/&(?=[#a-z0-9]+;)/i', '__amp;_', $string);
558
    $string = strtr($string, array('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;', '\''=>'&#39;'));
559
    $string = preg_replace('/__amp;_(?=[#a-z0-9]+;)/i', '&', $string);
560
    return($string);
561
}
562

    
563
// Convert a string from mixed html-entities/umlauts to pure $charset_out-umlauts
564
// Will replace all numeric and named entities except &gt; &lt; &apos; &quot; &#039; &nbsp;
565
// In case of error the returned string is unchanged, and a message is emitted.
566
function entities_to_umlauts($string, $charset_out=DEFAULT_CHARSET)
567
{
568
    require_once(WB_PATH.'/framework/functions-utf8.php');
569
    return entities_to_umlauts2($string, $charset_out);
570
}
571

    
572
// Will convert a string in $charset_in encoding to a pure ASCII string with HTML-entities.
573
// In case of error the returned string is unchanged, and a message is emitted.
574
function umlauts_to_entities($string, $charset_in=DEFAULT_CHARSET)
575
{
576
    require_once(WB_PATH.'/framework/functions-utf8.php');
577
    return umlauts_to_entities2($string, $charset_in);
578
}
579

    
580
// Function to convert a page title to a page filename
581
function page_filename($string)
582
{
583
    require_once(WB_PATH.'/framework/functions-utf8.php');
584
    $string = entities_to_7bit($string);
585
    // Now remove all bad characters
586
    $bad = array(
587
    '\'', /* /  */ '"', /* " */    '<', /* < */    '>', /* > */
588
    '{', /* { */    '}', /* } */    '[', /* [ */    ']', /* ] */    '`', /* ` */
589
    '!', /* ! */    '@', /* @ */    '#', /* # */    '$', /* $ */    '%', /* % */
590
    '^', /* ^ */    '&', /* & */    '*', /* * */    '(', /* ( */    ')', /* ) */
591
    '=', /* = */    '+', /* + */    '|', /* | */    '/', /* / */    '\\', /* \ */
592
    ';', /* ; */    ':', /* : */    ',', /* , */    '?' /* ? */
593
    );
594
    $string = str_replace($bad, '', $string);
595
    // replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
596
    $string = preg_replace(array('/\.+/', '/\.+$/'), array('.', ''), $string);
597
    // Now replace spaces with page spcacer
598
    $string = trim($string);
599
    $string = preg_replace('/(\s)+/', PAGE_SPACER, $string);
600
    // Now convert to lower-case
601
    $string = strtolower($string);
602
    // If there are any weird language characters, this will protect us against possible problems they could cause
603
    $string = str_replace(array('%2F', '%'), array('/', ''), urlencode($string));
604
    // Finally, return the cleaned string
605
    return $string;
606
}
607

    
608
// Function to convert a desired media filename to a clean mediafilename
609
function media_filename($string)
610
{
611
    require_once(WB_PATH.'/framework/functions-utf8.php');
612
    $string = entities_to_7bit($string);
613
    // Now remove all bad characters
614
    $bad = array('\'','"','`','!','@','#','$','%','^','&','*','=','+','|','/','\\',';',':',',','?');
615
    $string = str_replace($bad, '', $string);
616
    // replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing
617
    $string = preg_replace(array('/\.+/', '/\.+$/', '/\s/'), array('.', '', '_'), $string);
618
    // Clean any page spacers at the end of string
619
    $string = trim($string);
620
    // Finally, return the cleaned string
621
    return $string;
622
}
623

    
624
// Function to work out a page link
625
if(!function_exists('page_link'))
626
{
627
    function page_link($link)
628
    {
629
        global $admin;
630
        return $admin->page_link($link);
631
    }
632
}
633

    
634
// Create a new directory and/or protected file in the given directory
635
function createFolderProtectFile($sAbsDir='',$make_dir=true)
636
{
637
    trigger_error('Deprecated function call: '.basename(__DIR__).'/'.basename(__FILE__).'::'.__FUNCTION__, E_USER_DEPRECATED );
638
    return array();
639
}
640

    
641
function rebuildFolderProtectFile($dir='')
642
{
643
    trigger_error('Deprecated function call: '.basename(__DIR__).'/'.basename(__FILE__).'::'.__FUNCTION__, E_USER_DEPRECATED );
644
    return array();
645
}
646

    
647
// Create a new file in the pages directory
648
function create_access_file($filename,$page_id,$level)
649
{
650
    global $admin, $MESSAGE;
651
    // First make sure parent folder exists
652
    $parent_folders = explode('/',str_replace(WB_PATH.PAGES_DIRECTORY, '', dirname($filename)));
653
    $parents = '';
654
    foreach($parent_folders AS $parent_folder)
655
    {
656
        if($parent_folder != '/' AND $parent_folder != '')
657
        {
658
            $parents .= '/'.$parent_folder;
659
            $acces_file = WB_PATH.PAGES_DIRECTORY.$parents;
660
            // can only be dirs
661
            if(!file_exists($acces_file)) {
662
                if(!make_dir($acces_file)) {
663
                    $admin->print_error($MESSAGE['MEDIA_DIR_NOT_MADE']);
664
                }
665
            }
666
        }
667
    }
668
    // The depth of the page directory in the directory hierarchy
669
    // '/pages' is at depth 1
670
    $pages_dir_depth = count(explode('/',PAGES_DIRECTORY))-1;
671
    // Work-out how many ../'s we need to get to the index page
672
    $index_location = '';
673
    for($i = 0; $i < $level + $pages_dir_depth; $i++) {
674
        $index_location .= '../';
675
    }
676

    
677
    $content =
678
        '<?php'."\n".
679
        '// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
680
        '// *** Creation date: '.date('c')."\n".
681
        '// *** Do not modify this file manually'."\n".
682
        '// *** WB will rebuild this file from time to time!!'."\n".
683
        '// *************************************************'."\n".
684
        "\t".'$page_id    = '.$page_id.';'."\n".
685
        "\t".'require(\''.$index_location.'index.php\');'."\n".
686
        '// *************************************************'."\n";
687

    
688
    if( ($handle = fopen($filename, 'w')) ) {
689
        fwrite($handle, $content);
690
        fclose($handle);
691
        // Chmod the file
692
        change_mode($filename);
693
    } else {
694
        $admin->print_error($MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE']);
695
    }
696
    return;
697
 }
698

    
699
// Function for working out a file mime type (if the in-built PHP one is not enabled)
700
if(!function_exists('mime_content_type'))
701
{
702
    function mime_content_type($filename)
703
    {
704
        $mime_types = array(
705
            'txt'    => 'text/plain',
706
            'htm'    => 'text/html',
707
            'html'    => 'text/html',
708
            'php'    => 'text/html',
709
            'css'    => 'text/css',
710
            'js'    => 'application/javascript',
711
            'json'    => 'application/json',
712
            'xml'    => 'application/xml',
713
            'swf'    => 'application/x-shockwave-flash',
714
            'flv'    => 'video/x-flv',
715

    
716
            // images
717
            'png'    => 'image/png',
718
            'jpe'    => 'image/jpeg',
719
            'jpeg'    => 'image/jpeg',
720
            'jpg'    => 'image/jpeg',
721
            'gif'    => 'image/gif',
722
            'bmp'    => 'image/bmp',
723
            'ico'    => 'image/vnd.microsoft.icon',
724
            'tiff'    => 'image/tiff',
725
            'tif'    => 'image/tiff',
726
            'svg'    => 'image/svg+xml',
727
            'svgz'    => 'image/svg+xml',
728

    
729
            // archives
730
            'zip'    => 'application/zip',
731
            'rar'    => 'application/x-rar-compressed',
732
            'exe'    => 'application/x-msdownload',
733
            'msi'    => 'application/x-msdownload',
734
            'cab'    => 'application/vnd.ms-cab-compressed',
735

    
736
            // audio/video
737
            'mp3'    => 'audio/mpeg',
738
            'mp4'    => 'audio/mpeg',
739
            'qt'    => 'video/quicktime',
740
            'mov'    => 'video/quicktime',
741

    
742
            // adobe
743
            'pdf'    => 'application/pdf',
744
            'psd'    => 'image/vnd.adobe.photoshop',
745
            'ai'    => 'application/postscript',
746
            'eps'    => 'application/postscript',
747
            'ps'    => 'application/postscript',
748

    
749
            // ms office
750
            'doc'    => 'application/msword',
751
            'rtf'    => 'application/rtf',
752
            'xls'    => 'application/vnd.ms-excel',
753
            'ppt'    => 'application/vnd.ms-powerpoint',
754

    
755
            // open office
756
            'odt'    => 'application/vnd.oasis.opendocument.text',
757
            'ods'    => 'application/vnd.oasis.opendocument.spreadsheet',
758
        );
759
        $temp = explode('.',$filename);
760
        $ext = strtolower(array_pop($temp));
761
        if (array_key_exists($ext, $mime_types)) {
762
            return $mime_types[$ext];
763
        }elseif (function_exists('finfo_open')) {
764
            $finfo = finfo_open(FILEINFO_MIME);
765
            $mimetype = finfo_file($finfo, $filename);
766
            finfo_close($finfo);
767
            return $mimetype;
768
        }else {
769
            return 'application/octet-stream';
770
        }
771
    }
772
}
773

    
774
// Generate a thumbnail from an image
775
function make_thumb($source, $destination, $size)
776
{
777
    // Check if GD is installed
778
    if(extension_loaded('gd') && function_exists('imageCreateFromJpeg'))
779
    {
780
        // First figure out the size of the thumbnail
781
        list($original_x, $original_y) = getimagesize($source);
782
        if ($original_x > $original_y) {
783
            $thumb_w = $size;
784
            $thumb_h = $original_y*($size/$original_x);
785
        }
786
        if ($original_x < $original_y) {
787
            $thumb_w = $original_x*($size/$original_y);
788
            $thumb_h = $size;
789
        }
790
        if ($original_x == $original_y) {
791
            $thumb_w = $size;
792
            $thumb_h = $size;
793
        }
794
        // Now make the thumbnail
795
        $source = imageCreateFromJpeg($source);
796
        $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
797
        imagecopyresampled($dst_img,$source,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);
798
        imagejpeg($dst_img, $destination);
799
        // Clear memory
800
        imagedestroy($dst_img);
801
        imagedestroy($source);
802
       // Return true
803
        return true;
804
    } else {
805
        return false;
806
    }
807
}
808

    
809
/*
810
 * Function to work-out a single part of an octal permission value
811
 *
812
 * @param mixed $octal_value: an octal value as string (i.e. '0777') or real octal integer (i.e. 0777 | 777)
813
 * @param string $who: char or string for whom the permission is asked( U[ser] / G[roup] / O[thers] )
814
 * @param string $action: char or string with the requested action( r[ead..] / w[rite..] / e|x[ecute..] )
815
 * @return boolean
816
 */
817
function extract_permission($octal_value, $who, $action)
818
{
819
    // Make sure that all arguments are set and $octal_value is a real octal-integer
820
    if(($who == '') || ($action == '') || (preg_match( '/[^0-7]/', (string)$octal_value ))) {
821
        return false; // invalid argument, so return false
822
    }
823

    
824
    // convert $octal_value into a decimal-integer to be sure having a valid value
825
    $right_mask = octdec($octal_value);
826
    $action_mask = 0;
827
    // set the $action related bit in $action_mask
828
    switch($action[0]) { // get action from first char of $action
829
        case 'r':
830
        case 'R':
831
            $action_mask = 4; // set read-bit only (2^2)
832
            break;
833
        case 'w':
834
        case 'W':
835
            $action_mask = 2; // set write-bit only (2^1)
836
            break;
837
        case 'e':
838
        case 'E':
839
        case 'x':
840
        case 'X':
841
            $action_mask = 1; // set execute-bit only (2^0)
842
            break;
843
        default:
844
            return false; // undefined action name, so return false
845
    }
846
//print '<pre  class="mod-pre rounded">function <span>'.__FUNCTION__.'( '.$who[0].'_'.$action[0].' );</span>  filename: <span>'.basename(__FILE__).'</span>  line: '.__LINE__.' -> <br />';
847
//print_r( $right_mask & $action_mask ); print '</pre>'; flush (); //  ob_flush();;sleep(10); die();
848
    // shift action-mask into the right position
849
    switch($who[0]) { // get who from first char of $who
850
        case 'u':
851
        case 'U':
852
            $action_mask <<= 3; // shift left 3 bits
853
        case 'g':
854
        case 'G':
855
            $action_mask <<= 3; // shift left 3 bits
856
        case 'o':
857
        case 'O':
858
            /* NOP */
859
            break;
860
        default:
861
            return false; // undefined who, so return false
862
    }
863
    return( ($right_mask & $action_mask) != 0 ); // return result of binary-AND
864
}
865

    
866
// Function to delete a page
867
    function delete_page($page_id)
868
    {
869
        global $admin, $database, $MESSAGE;
870
        // Find out more about the page
871
        $sql  = 'SELECT `page_id`, `menu_title`, `page_title`, `level`, ';
872
        $sql .=        '`link`, `parent`, `modified_by`, `modified_when` ';
873
        $sql .= 'FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
874
        $results = $database->query($sql);
875
        if($database->is_error())    { $admin->print_error($database->get_error()); }
876
        if($results->numRows() == 0) { $admin->print_error($MESSAGE['PAGES']['NOT_FOUND']); }
877
        $results_array = $results->fetchRow();
878
        $parent     = $results_array['parent'];
879
        $level      = $results_array['level'];
880
        $link       = $results_array['link'];
881
        $page_title = $results_array['page_title'];
882
        $menu_title = $results_array['menu_title'];
883
        // Get the sections that belong to the page
884
        $sql  = 'SELECT `section_id`, `module` FROM `'.TABLE_PREFIX.'sections` ';
885
        $sql .= 'WHERE `page_id`='.$page_id;
886
        $query_sections = $database->query($sql);
887
        if($query_sections->numRows() > 0)
888
        {
889
            while($section = $query_sections->fetchRow()) {
890
                // Set section id
891
                $section_id = $section['section_id'];
892
                // Include the modules delete file if it exists
893
                if(file_exists(WB_PATH.'/modules/'.$section['module'].'/delete.php')) {
894
                    include(WB_PATH.'/modules/'.$section['module'].'/delete.php');
895
                }
896
            }
897
        }
898
        // Update the pages table
899
        $sql = 'DELETE FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
900
        $database->query($sql);
901
        if($database->is_error()) {
902
            $admin->print_error($database->get_error());
903
        }
904
        // Update the sections table
905
        $sql = 'DELETE FROM `'.TABLE_PREFIX.'sections` WHERE `page_id`='.$page_id;
906
        $database->query($sql);
907
        if($database->is_error()) {
908
            $admin->print_error($database->get_error());
909
        }
910
        // Include the ordering class or clean-up ordering
911
        include_once(WB_PATH.'/framework/class.order.php');
912
        $order = new order(TABLE_PREFIX.'pages', 'position', 'page_id', 'parent');
913
        $order->clean($parent);
914
        // Unlink the page access file and directory
915
        $directory = WB_PATH.PAGES_DIRECTORY.$link;
916
        $filename = $directory.PAGE_EXTENSION;
917
        $directory .= '/';
918
        if(file_exists($filename))
919
        {
920
            if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/')) {
921
                $admin->print_error($MESSAGE['PAGES']['CANNOT_DELETE_ACCESS_FILE']);
922
            }else {
923
                unlink($filename);
924
                if( file_exists($directory) &&
925
                   (rtrim($directory,'/') != WB_PATH.PAGES_DIRECTORY) &&
926
                   (substr($link, 0, 1) != '.'))
927
                {
928
                    rm_full_dir($directory);
929
                }
930
            }
931
        }
932
    }
933

    
934
/*
935
 * @param string $file: name of the file to read
936
 * @param int $size: number of maximum bytes to read (0 = complete file)
937
 * @return string: the content as string, false on error
938
 */
939
    function getFilePart($file, $size = 0)
940
    {
941
        $file_content = '';
942
        if( file_exists($file) && is_file($file) && is_readable($file))
943
        {
944
            if($size == 0) {
945
                $size = filesize($file);
946
            }
947
            if(($fh = fopen($file, 'rb'))) {
948
                if( ($file_content = fread($fh, $size)) !== false ) {
949
                    return $file_content;
950
                }
951
                fclose($fh);
952
            }
953
        }
954
        return false;
955
    }
956

    
957
    /**
958
    * replace varnames with values in a string
959
    *
960
    * @param string $subject: stringvariable with vars placeholder
961
    * @param array $replace: values to replace vars placeholder
962
    * @return string
963
    */
964
    function replace_vars($subject = '', &$replace = null )
965
    {
966
        if(is_array($replace))
967
        {
968
            foreach ($replace  as $key => $value) {
969
                $subject = str_replace("{{".$key."}}", $value, $subject);
970
            }
971
        }
972
        return $subject;
973
    }
974

    
975
// Load template into DB
976
function load_template($directory)
977
{
978
    global $database, $admin;
979
    $retVal = false;
980
    if (is_dir($directory) && file_exists($directory.'/info.php'))
981
    {
982
        require($directory.'/info.php');
983
        if (isset($template_name))
984
        {
985
            if(!isset($template_license)) {
986
              $template_license = 'GNU General Public License';
987
            }
988
            if(!isset($template_platform) && isset($template_designed_for)) {
989
              $template_platform = $template_designed_for;
990
            }
991
            if(!isset($template_function)) {
992
              $template_function = 'template';
993
            }
994
            // Check that it doesn't already exist
995
            $sqlwhere = 'WHERE `type`=\'template\' AND `directory`=\''.$template_directory.'\'';
996
            $sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
997
            if ($database->get_one($sql) ) {
998
                $sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
999
            }else{
1000
                // Load into DB
1001
                $sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1002
                $sqlwhere = '';
1003
            }
1004
            $sql .= '`directory`=\''.$database->escapeString($template_directory).'\', '
1005
                  . '`name`=\''.$database->escapeString($template_name).'\', '
1006
                  . '`description`=\''.$database->escapeString($template_description).'\', '
1007
                  . '`type`=\'template\', '
1008
                  . '`function`=\''.$database->escapeString($template_function).'\', '
1009
                  . '`version`=\''.$database->escapeString($template_version).'\', '
1010
                  . '`platform`=\''.$database->escapeString($template_platform).'\', '
1011
                  . '`author`=\''.$database->escapeString($template_author).'\', '
1012
                  . '`license`=\''.$database->escapeString($template_license).'\' '
1013
                  . $sqlwhere;
1014
            if ($database->query($sql)){
1015
                $retVal = true;
1016
            } else {
1017
              $retVal = $database->get_errno();
1018
            }
1019
        }
1020
    }
1021
    return $retVal;
1022
}
1023

    
1024
// Load language into DB
1025
function load_language($file)
1026
{
1027
    global $database,$admin;
1028
    $retVal = false;
1029
    if (file_exists($file) && preg_match('#^([A-Z]{2}.php)#', basename($file)))
1030
    {
1031
        // require($file);  it's to large
1032
        // read contents of the template language file into string
1033
        $data = @file_get_contents(WB_PATH.'/languages/'.str_replace('.php','',basename($file)).'.php');
1034
        // use regular expressions to fetch the content of the variable from the string
1035
        $language_name = get_variable_content('language_name', $data, false, false);
1036
        $language_code = preg_replace('/^.*([a-zA-Z]{2})\.php$/si', '\1', $file);
1037
        $language_author = get_variable_content('language_author', $data, false, false);
1038
        $language_version = get_variable_content('language_version', $data, false, false);
1039
        $language_platform = get_variable_content('language_platform', $data, false, false);
1040
        $language_description = get_variable_content('language_description', $data, false, false);
1041
        if(isset($language_name))
1042
        {
1043
            if(!isset($language_license)) { $language_license = 'GNU General Public License'; }
1044
            if(!isset($language_platform) && isset($language_designed_for)) { $language_platform = $language_designed_for; }
1045
            // Check that it doesn't already exist
1046
            $sqlwhere = 'WHERE `type`=\'language\' AND `directory`=\''.$language_code.'\'';
1047
            $sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1048
            if( $database->get_one($sql) ) {
1049
                $sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1050
            }else{
1051
                // Load into DB
1052
                $sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1053
                $sqlwhere = '';
1054
            }
1055
            $sql .= '`directory`=\''.$language_code.'\', '
1056
                  . '`name`=\''.$database->escapeString($language_name).'\', '
1057
                  . '`type`=\'language\', '
1058
                  . '`version`=\''.$database->escapeString($language_version).'\', '
1059
                  . '`platform`=\''.$database->escapeString($language_platform).'\', '
1060
                  . '`author`=\''.$database->escapeString($language_author).'\', '
1061
                  . '`description`=\'\', '
1062
                  . '`license`=\''.$database->escapeString($language_license).'\' '
1063
                  . $sqlwhere;
1064
            $retVal = $database->query($sql);
1065
        }
1066
    }
1067
    return $retVal;
1068
}
1069

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

    
1117
// Upgrade module info in DB, optionally start upgrade script
1118
function upgrade_module($directory, $upgrade = false)
1119
{
1120
    global $database, $admin, $MESSAGE, $new_module_version;
1121
    $mod_directory = WB_PATH.'/modules/'.$directory;
1122
    if(file_exists($mod_directory.'/info.php'))
1123
    {
1124
        require($mod_directory.'/info.php');
1125
        if(isset($module_name))
1126
        {
1127
            if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1128
            if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1129
            if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1130
            $module_function = strtolower($module_function);
1131
            // Check that it does already exist
1132
            $sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` ';
1133
            $sql .= 'WHERE `directory`=\''.$module_directory.'\'';
1134
            if( $database->get_one($sql) )
1135
            {
1136
                // Update in DB
1137
                $sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET '
1138
                      . '`name`=\''.$database->escapeString($module_name).'\', '
1139
                      . '`version`=\''.$database->escapeString($module_version).'\', '
1140
                      . '`description`=\''.$database->escapeString($module_description).'\', '
1141
                      . '`platform`=\''.$database->escapeString($module_platform).'\', '
1142
                      . '`author`=\''.$database->escapeString($module_author).'\', '
1143
                      . '`license`=\''.$database->escapeString($module_license).'\' '
1144
                      . 'WHERE `directory`=\''.$database->escapeString($module_directory).'\' ';
1145
                $database->query($sql);
1146
                if($database->is_error()) {
1147
                    $admin->print_error($database->get_error());
1148
                }
1149
                // Run upgrade script
1150
                if($upgrade == true) {
1151
                    if(file_exists($mod_directory.'/upgrade.php')) {
1152
                        require($mod_directory.'/upgrade.php');
1153
                    }
1154
                }
1155
            }
1156
        }
1157
    }
1158
}
1159

    
1160
// extracts the content of a string variable from a string (save alternative to including files)
1161
if(!function_exists('get_variable_content'))
1162
{
1163
    function get_variable_content($search, $data, $striptags=true, $convert_to_entities=true)
1164
    {
1165
        $match = '';
1166
        // search for $variable followed by 0-n whitespace then by = then by 0-n whitespace
1167
        // then either " or ' then 0-n characters then either " or ' followed by 0-n whitespace and ;
1168
        // the variable name is returned in $match[1], the content in $match[3]
1169
        if (preg_match('/(\$' .$search .')\s*=\s*("|\')(.*)\2\s*;/', $data, $match))
1170
        {
1171
            if(strip_tags(trim($match[1])) == '$' .$search) {
1172
                // variable name matches, return it's value
1173
                $match[3] = ($striptags == true) ? strip_tags($match[3]) : $match[3];
1174
                $match[3] = ($convert_to_entities == true) ? htmlentities($match[3]) : $match[3];
1175
                return $match[3];
1176
            }
1177
        }
1178
        return false;
1179
    }
1180
}
1181

    
1182
/*
1183
 * @param string $modulname: like saved in addons.directory
1184
 * @param boolean $source: true reads from database, false from info.php
1185
 * @return string:  the version as string, if not found returns null
1186
 */
1187

    
1188
    function get_modul_version($modulname, $source = true)
1189
    {
1190
        global $database;
1191
        $version = null;
1192
        if( $source != true )
1193
        {
1194
            $sql  = 'SELECT `version` FROM `'.TABLE_PREFIX.'addons` ';
1195
            $sql .= 'WHERE `directory`=\''.$modulname.'\'';
1196
            $version = $database->get_one($sql);
1197
        } else {
1198
            $info_file = WB_PATH.'/modules/'.$modulname.'/info.php';
1199
            if(file_exists($info_file)) {
1200
                if(($info_file = file_get_contents($info_file))) {
1201
                    $version = get_variable_content('module_version', $info_file, false, false);
1202
                    $version = ($version !== false) ? $version : null;
1203
                }
1204
            }
1205
        }
1206
        return $version;
1207
    }
1208

    
1209
/*
1210
 * @param string $varlist: commaseperated list of varnames to move into global space
1211
 * @return bool:  false if one of the vars already exists in global space (error added to msgQueue)
1212
 */
1213
    function vars2globals_wrapper($varlist)
1214
    {
1215
        $retval = true;
1216
        if( $varlist != '')
1217
        {
1218
            $vars = explode(',', $varlist);
1219
            foreach( $vars as $var)
1220
            {
1221
                if( isset($GLOBALS[$var]) ){
1222
                    ErrorLog::write( 'variabe $'.$var.' already defined in global space!!',__FILE__, __FUNCTION__, __LINE__);
1223
                    $retval = false;
1224
                }else {
1225
                    global $$var;
1226
                }
1227
            }
1228
        }
1229
        return $retval;
1230
    }
1231

    
1232
/*
1233
 * filter directory traversal more thoroughly, thanks to hal 9000
1234
 * @param string $dir: directory relative to MEDIA_DIRECTORY
1235
 * @param bool $with_media_dir: true when to include MEDIA_DIRECTORY
1236
 * @return: false if directory traversal detected, real path if not
1237
 */
1238
    function check_media_path($directory, $with_media_dir = true)
1239
    {
1240
        $md = ($with_media_dir) ? MEDIA_DIRECTORY : '';
1241
        $dir = realpath(WB_PATH . $md . '/' . utf8_decode($directory));
1242
        $required = realpath(WB_PATH . MEDIA_DIRECTORY);
1243
        if (strstr($dir, $required)) {
1244
            return $dir;
1245
        } else {
1246
            return false;
1247
        }
1248
    }
1249

    
1250
/*
1251
urlencode function and rawurlencode are mostly based on RFC 1738.
1252
However, since 2005 the current RFC in use for URIs standard is RFC 3986.
1253
Here is a function to encode URLs according to RFC 3986.
1254
*/
1255
if(!function_exists('url_encode')){
1256
    function url_encode($string) {
1257
        $string = html_entity_decode($string,ENT_QUOTES,'UTF-8');
1258
        $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
1259
        $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
1260
        return str_replace($entities,$replacements, rawurlencode($string));
1261
    }
1262
}