Website Baker PHP Cross Reference Content Management Systems

Source: /framework/functions.php - 1321 lines - 44445 bytes - Summary - Text - Print

   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 1601 2012-02-07 22:48:27Z Luisehahne $

  14   * @filesource        $HeadURL: svn://isteam.dynxs.de/wb_svn/wb280/tags/2.8.3/wb/framework/functions.php $

  15   * @lastmodified    $Date: 2012-02-07 23:48:27 +0100 (Di, 07. Feb 2012) $

  16   *

  17  */
  18  /* -------------------------------------------------------- */

  19  // Must include code to stop this file being accessed directly

  20  if(!defined('WB_PATH')) {
  21      require_once(dirname(__FILE__).'/globalExceptionHandler.php');
  22      throw new IllegalFileException();
  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          $directory = substr($directory,0,-1);
  40      }
  41     // If suplied dirname is a file then unlink it

  42      if (is_file( $directory )) {
  43        $retval = unlink($directory);
  44        clearstatcache();
  45        return $retval;
  46      }
  47      if(!file_exists($directory) || !is_dir($directory)) {
  48          return false;
  49      } elseif(!is_readable($directory)) {
  50          return false;
  51      } else {
  52          $directoryHandle = opendir($directory);
  53          while ($contents = readdir($directoryHandle))
  54          {
  55              if($contents != '.' && $contents != '..')
  56              {
  57                  $path = $directory . "/" . $contents;
  58                  if(is_dir($path)) {
  59                      rm_full_dir($path);
  60                  } else {
  61                      unlink($path);
  62                      clearstatcache();
  63                  }
  64              }
  65          }
  66          closedir($directoryHandle);
  67          if($empty == false) {
  68              if(!rmdir($directory)) {
  69                  return false;
  70              }
  71          }
  72          return true;
  73      }
  74  }
  75  
  76  /*

  77   * returns a recursive list of all subdirectories from a given directory

  78   * @access  public

  79   * @param   string  $directory: from this dir the recursion will start

  80   * @param   bool    $show_hidden:  if set to TRUE also hidden dirs (.dir) will be shown

  81   * @return  array

  82   * example:

  83   *  /srv/www/httpdocs/wb/media/a/b/c/

  84   *  /srv/www/httpdocs/wb/media/a/b/d/

  85   * directory_list('/srv/www/httpdocs/wb/media/') will return:

  86   *  /a

  87   *  /a/b

  88   *  /a/b/c

  89   *  /a/b/d

  90   */
  91   function directory_list($directory, $show_hidden = false)
  92  {
  93      $result_list = array();
  94      if (is_dir($directory))
  95      {
  96          $dir = dir($directory); // Open the directory

  97          while (false !== $entry = $dir->read()) // loop through the directory
  98          {
  99              if($entry == '.' || $entry == '..') { continue; } // Skip pointers

 100              if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files

 101              if (is_dir("$directory/$entry")) { // Add dir and contents to list
 102                  $result_list = array_merge($result_list, directory_list("$directory/$entry"));
 103                  $result_list[] = "$directory/$entry";
 104              }
 105          }
 106          $dir->close();
 107      }
 108      // sorting

 109      if(natcasesort($result_list)) {
 110          // new indexing

 111          $result_list = array_merge($result_list);
 112      }
 113      return $result_list; // Now return the list

 114  }
 115  
 116  // Function to open a directory and add to a dir list

 117  function chmod_directory_contents($directory, $file_mode)
 118  {
 119      if (is_dir($directory))
 120      {
 121          // Set the umask to 0

 122          $umask = umask(0);
 123          // Open the directory then loop through its contents

 124          $dir = dir($directory);
 125          while (false !== $entry = $dir->read())
 126          {
 127              // Skip pointers

 128              if($entry[0] == '.') { continue; }
 129              // Chmod the sub-dirs contents

 130              if(is_dir("$directory/$entry")) {
 131                  chmod_directory_contents($directory.'/'.$entry, $file_mode);
 132              }
 133              change_mode($directory.'/'.$entry);
 134          }
 135          $dir->close();
 136          // Restore the umask

 137          umask($umask);
 138      }
 139  }
 140  
 141  /**

 142  * Scan a given directory for dirs and files.

 143  *

 144  * usage: scan_current_dir ($root = '' )

 145  *

 146  * @param     $root   set a absolute rootpath as string. if root is empty the current path will be scan

 147  * @param     $search set a search pattern for files, empty search brings all files

 148  * @access    public

 149  * @return    array    returns a natsort array with keys 'path' and 'filename'

 150  *

 151  */
 152  if(!function_exists('scan_current_dir'))
 153  {
 154  	function scan_current_dir($root = '', $search = '/.*/')
 155      {
 156          $FILE = array();
 157          $array = array();
 158          clearstatcache();
 159          $root = empty ($root) ? getcwd() : $root;
 160          if (($handle = opendir($root)))
 161          {
 162          // Loop through the files and dirs an add to list  DIRECTORY_SEPARATOR

 163              while (false !== ($file = readdir($handle)))
 164              {
 165                  if (substr($file, 0, 1) != '.' && $file != 'index.php')
 166                  {
 167                      if (is_dir($root.'/'.$file)) {
 168                          $FILE['path'][] = $file;
 169                      } elseif (preg_match($search, $file, $array) ) {
 170                          $FILE['filename'][] = $array[0];
 171                      }
 172                  }
 173              }
 174              $close_verz = closedir($handle);
 175          }
 176          // sorting

 177          if (isset ($FILE['path']) && natcasesort($FILE['path'])) {
 178              // new indexing

 179              $FILE['path'] = array_merge($FILE['path']);
 180          }
 181          // sorting

 182          if (isset ($FILE['filename']) && natcasesort($FILE['filename'])) {
 183              // new indexing

 184              $FILE['filename'] = array_merge($FILE['filename']);
 185          }
 186          return $FILE;
 187      }
 188  }
 189  
 190  // Function to open a directory and add to a file list

 191  function file_list($directory, $skip = array(), $show_hidden = false)
 192  {
 193      $result_list = array();
 194      if (is_dir($directory))
 195      {
 196          $dir = dir($directory); // Open the directory

 197          while (false !== ($entry = $dir->read())) // loop through the directory
 198          {
 199              if($entry == '.' || $entry == '..') { continue; } // Skip pointers

 200              if($entry[0] == '.' && $show_hidden == false) { continue; } // Skip hidden files

 201              if( sizeof($skip) > 0 && in_array($entry, $skip) ) { continue; } // Check if we to skip anything else

 202              if(is_file( $directory.'/'.$entry)) { // Add files to list
 203                  $result_list[] = $directory.'/'.$entry;
 204              }
 205          }
 206          $dir->close(); // Now close the folder object

 207      }
 208  
 209      // make the list nice. Not all OS do this itself

 210      if(natcasesort($result_list)) {
 211          $result_list = array_merge($result_list);
 212      }
 213      return $result_list;
 214  }
 215  
 216  // Function to get a list of home folders not to show

 217  function get_home_folders()
 218  {
 219      global $database, $admin;
 220      $home_folders = array();
 221      // Only return home folders is this feature is enabled

 222      // and user is not admin

 223  //    if(HOME_FOLDERS AND ($_SESSION['GROUP_ID']!='1')) {

 224      if(HOME_FOLDERS AND (!in_array('1',explode(',', $_SESSION['GROUPS_ID']))))
 225      {
 226          $sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
 227          $sql .= 'WHERE `home_folder`!=\''.$admin->get_home_folder().'\'';
 228          $query_home_folders = $database->query($sql);
 229          if($query_home_folders->numRows() > 0)
 230          {
 231              while($folder = $query_home_folders->fetchRow()) {
 232                  $home_folders[$folder['home_folder']] = $folder['home_folder'];
 233              }
 234          }
 235  		function remove_home_subs($directory = '/', $home_folders = '')
 236          {
 237              if( ($handle = opendir(WB_PATH.MEDIA_DIRECTORY.$directory)) )
 238              {
 239                  // Loop through the dirs to check the home folders sub-dirs are not shown

 240                  while(false !== ($file = readdir($handle)))
 241                  {
 242                      if($file[0] != '.' && $file != 'index.php')
 243                      {
 244                          if(is_dir(WB_PATH.MEDIA_DIRECTORY.$directory.'/'.$file))
 245                          {
 246                              if($directory != '/') {
 247                                  $file = $directory.'/'.$file;
 248                              }else {
 249                                  $file = '/'.$file;
 250                              }
 251                              foreach($home_folders AS $hf)
 252                              {
 253                                  $hf_length = strlen($hf);
 254                                  if($hf_length > 0) {
 255                                      if(substr($file, 0, $hf_length+1) == $hf) {
 256                                          $home_folders[$file] = $file;
 257                                      }
 258                                  }
 259                              }
 260                              $home_folders = remove_home_subs($file, $home_folders);
 261                          }
 262                      }
 263                  }
 264              }
 265              return $home_folders;
 266          }
 267          $home_folders = remove_home_subs('/', $home_folders);
 268      }
 269      return $home_folders;
 270  }
 271  
 272  /*

 273   * @param object &$wb: $wb from frontend or $admin from backend

 274   * @return array: list of new entries

 275   * @description: callback remove path in files/dirs stored in array

 276   * @example: array_walk($array,'remove_path',PATH);

 277   */
 278  //

 279  function remove_path(&$path, $key, $vars = '')
 280  {
 281      $path = str_replace($vars, '', $path);
 282  }
 283  
 284  /*

 285   * @param object &$wb: $wb from frontend or $admin from backend

 286   * @return array: list of ro-dirs

 287   * @description: returns a list of directories beyound /wb/media which are ReadOnly for current user

 288   */
 289  function media_dirs_ro( &$wb )
 290  {
 291      global $database;
 292      // if user is admin or home-folders not activated then there are no restrictions

 293      $allow_list = array();
 294      if( $wb->get_user_id() == 1 || !HOME_FOLDERS ) {
 295          return array();
 296      }
 297      // at first read any dir and subdir from /media

 298      $full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
 299      // add own home_folder to allow-list

 300      if( $wb->get_home_folder() ) {
 301          // old: $allow_list[] = get_home_folder();

 302          $allow_list[] = $wb->get_home_folder();
 303      }
 304      // get groups of current user

 305      $curr_groups = $wb->get_groups_id();
 306      // if current user is in admin-group

 307      if( ($admin_key = array_search('1', $curr_groups)) !== false)
 308      {
 309          // remove admin-group from list

 310          unset($curr_groups[$admin_key]);
 311          // search for all users where the current user is admin from

 312          foreach( $curr_groups as $group)
 313          {
 314              $sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
 315              $sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
 316              if( ($res_hf = $database->query($sql)) != null ) {
 317                  while( $rec_hf = $res_hf->fetchrow() ) {
 318                      $allow_list[] = $rec_hf['home_folder'];
 319                  }
 320              }
 321          }
 322      }
 323      $tmp_array = $full_list;
 324      // create a list for readonly dir

 325      $array = array();
 326      while( sizeof($tmp_array) > 0)
 327      {
 328          $tmp = array_shift($tmp_array);
 329          $x = 0;
 330          while($x < sizeof($allow_list)) {
 331              if(strpos ($tmp,$allow_list[$x])) {
 332                  $array[] = $tmp;
 333              }
 334              $x++;
 335          }
 336      }
 337      $full_list = array_diff( $full_list, $array );
 338      $tmp = array();
 339      $full_list = array_merge($tmp,$full_list);
 340      return $full_list;
 341  }
 342  
 343  /*

 344   * @param object &$wb: $wb from frontend or $admin from backend

 345   * @return array: list of rw-dirs

 346   * @description: returns a list of directories beyound /wb/media which are ReadWrite for current user

 347   */
 348  function media_dirs_rw ( &$wb )
 349  {
 350      global $database;
 351      // if user is admin or home-folders not activated then there are no restrictions

 352      // at first read any dir and subdir from /media

 353      $full_list = directory_list( WB_PATH.MEDIA_DIRECTORY );
 354      $array = array();
 355      $allow_list = array();
 356      if( ($wb->ami_group_member('1')) && !HOME_FOLDERS ) {
 357          return $full_list;
 358      }
 359      // add own home_folder to allow-list

 360      if( $wb->get_home_folder() ) {
 361            $allow_list[] = $wb->get_home_folder();
 362      } else {
 363          $array = $full_list;
 364      }
 365      // get groups of current user

 366      $curr_groups = $wb->get_groups_id();
 367      // if current user is in admin-group

 368      if( ($admin_key = array_search('1', $curr_groups)) == true)
 369      {
 370          // remove admin-group from list

 371          // unset($curr_groups[$admin_key]);

 372          // search for all users where the current user is admin from

 373          foreach( $curr_groups as $group)
 374          {
 375              $sql  = 'SELECT `home_folder` FROM `'.TABLE_PREFIX.'users` ';
 376              $sql .= 'WHERE (FIND_IN_SET(\''.$group.'\', `groups_id`) > 0) AND `home_folder` <> \'\' AND `user_id` <> '.$wb->get_user_id();
 377              if( ($res_hf = $database->query($sql)) != null ) {
 378                  while( $rec_hf = $res_hf->fetchrow() ) {
 379                      $allow_list[] = $rec_hf['home_folder'];
 380                  }
 381              }
 382          }
 383      }
 384  
 385      $tmp_array = $full_list;
 386      // create a list for readwrite dir

 387      while( sizeof($tmp_array) > 0)
 388      {
 389          $tmp = array_shift($tmp_array);
 390          $x = 0;
 391          while($x < sizeof($allow_list)) {
 392              if(strpos ($tmp,$allow_list[$x])) {
 393                  $array[] = $tmp;
 394              }
 395              $x++;
 396          }
 397      }
 398      $tmp = array();
 399      $array = array_unique($array);
 400      $full_list = array_merge($tmp,$array);
 401      unset($array);
 402      unset($allow_list);
 403      return $full_list;
 404  }
 405  
 406  // Function to create directories

 407  function make_dir($dir_name, $dir_mode = OCTAL_DIR_MODE, $recursive=true)
 408  {
 409      $retVal = false;
 410      if(!is_dir($dir_name))
 411      {
 412          $retVal = mkdir($dir_name, $dir_mode,$recursive);
 413      }
 414      return $retVal;
 415  }
 416  
 417  // Function to chmod files and directories

 418  function change_mode($name)
 419  {
 420      if(OPERATING_SYSTEM != 'windows')
 421      {
 422          // Only chmod if os is not windows

 423          if(is_dir($name)) {
 424              $mode = OCTAL_DIR_MODE;
 425          }else {
 426              $mode = OCTAL_FILE_MODE;
 427          }
 428          if(file_exists($name)) {
 429              $umask = umask(0);
 430              chmod($name, $mode);
 431              umask($umask);
 432              return true;
 433          }else {
 434              return false;
 435          }
 436      }else {
 437          return true;
 438      }
 439  }
 440  
 441  // Function to figure out if a parent exists

 442  function is_parent($page_id)
 443  {
 444      global $database;
 445      // Get parent

 446      $sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
 447      $parent = $database->get_one($sql);
 448      // If parent isnt 0 return its ID

 449      if(is_null($parent)) {
 450          return false;
 451      }else {
 452          return $parent;
 453      }
 454  }
 455  
 456  // Function to work out level

 457  function level_count($page_id)
 458  {
 459      global $database;
 460      // Get page parent

 461      $sql = 'SELECT `parent` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
 462      $parent = $database->get_one($sql);
 463      if($parent > 0)
 464      {    // Get the level of the parent
 465          $sql = 'SELECT `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$parent;
 466          $level = $database->get_one($sql);
 467          return $level+1;
 468      }else {
 469          return 0;
 470      }
 471  }
 472  
 473  // Function to work out root parent

 474  function root_parent($page_id)
 475  {
 476      global $database;
 477      // Get page details

 478      $sql = 'SELECT `parent`, `level` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$page_id;
 479      $query_page = $database->query($sql);
 480      $fetch_page = $query_page->fetchRow();
 481      $parent = $fetch_page['parent'];
 482      $level = $fetch_page['level'];
 483      if($level == 1) {
 484          return $parent;
 485      }elseif($parent == 0) {
 486          return $page_id;
 487      }else {    // Figure out what the root parents id is
 488          $parent_ids = array_reverse(get_parent_ids($page_id));
 489          return $parent_ids[0];
 490      }
 491  }
 492  
 493  // Function to get page title

 494  function get_page_title($id)
 495  {
 496      global $database;
 497      // Get title

 498      $sql = 'SELECT `page_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
 499      $page_title = $database->get_one($sql);
 500      return $page_title;
 501  }
 502  
 503  // Function to get a pages menu title

 504  function get_menu_title($id)
 505  {
 506      global $database;
 507      // Get title

 508      $sql = 'SELECT `menu_title` FROM `'.TABLE_PREFIX.'pages` WHERE `page_id` = '.$id;
 509      $menu_title = $database->get_one($sql);
 510      return $menu_title;
 511  }
 512  
 513  // Function to get all parent page titles

 514  function get_parent_titles($parent_id)
 515  {
 516      $titles[] = get_menu_title($parent_id);
 517      if(is_parent($parent_id) != false) {
 518          $parent_titles = get_parent_titles(is_parent($parent_id));
 519          $titles = array_merge($titles, $parent_titles);
 520      }
 521      return $titles;
 522  }
 523  
 524  // Function to get all parent page id's

 525  function get_parent_ids($parent_id)
 526  {
 527      $ids[] = $parent_id;
 528      if(is_parent($parent_id) != false) {
 529          $parent_ids = get_parent_ids(is_parent($parent_id));
 530          $ids = array_merge($ids, $parent_ids);
 531      }
 532      return $ids;
 533  }
 534  
 535  // Function to genereate page trail

 536  function get_page_trail($page_id)
 537  {
 538      return implode(',', array_reverse(get_parent_ids($page_id)));
 539  }
 540  
 541  // Function to get all sub pages id's

 542  function get_subs($parent, array $subs )
 543  {
 544      // Connect to the database

 545      global $database;
 546      // Get id's

 547      $sql = 'SELECT `page_id` FROM `'.TABLE_PREFIX.'pages` WHERE `parent` = '.$parent;
 548      if( ($query = $database->query($sql)) ) {
 549          while($fetch = $query->fetchRow()) {
 550              $subs[] = $fetch['page_id'];
 551              // Get subs of this sub recursive

 552              $subs = get_subs($fetch['page_id'], $subs);
 553          }
 554      }
 555      // Return subs array

 556      return $subs;
 557  }
 558  
 559  // Function as replacement for php's htmlspecialchars()

 560  // Will not mangle HTML-entities

 561  function my_htmlspecialchars($string)
 562  {
 563      $string = preg_replace('/&(?=[#a-z0-9]+;)/i', '__amp;_', $string);
 564      $string = strtr($string, array('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;', '\''=>'&#39;'));
 565      $string = preg_replace('/__amp;_(?=[#a-z0-9]+;)/i', '&', $string);
 566      return($string);
 567  }
 568  
 569  // Convert a string from mixed html-entities/umlauts to pure $charset_out-umlauts

 570  // Will replace all numeric and named entities except &gt; &lt; &apos; &quot; &#039; &nbsp;

 571  // In case of error the returned string is unchanged, and a message is emitted.

 572  function entities_to_umlauts($string, $charset_out=DEFAULT_CHARSET)
 573  {
 574      require_once (WB_PATH.'/framework/functions-utf8.php');
 575      return entities_to_umlauts2($string, $charset_out);
 576  }
 577  
 578  // Will convert a string in $charset_in encoding to a pure ASCII string with HTML-entities.

 579  // In case of error the returned string is unchanged, and a message is emitted.

 580  function umlauts_to_entities($string, $charset_in=DEFAULT_CHARSET)
 581  {
 582      require_once (WB_PATH.'/framework/functions-utf8.php');
 583      return umlauts_to_entities2($string, $charset_in);
 584  }
 585  
 586  // Function to convert a page title to a page filename

 587  function page_filename($string)
 588  {
 589      require_once (WB_PATH.'/framework/functions-utf8.php');
 590      $string = entities_to_7bit($string);
 591      // Now remove all bad characters

 592      $bad = array(
 593      '\'', /* /  */ '"', /* " */    '<', /* < */    '>', /* > */
 594      '{', /* { */    '}', /* } */    '[', /* [ */    ']', /* ] */    '`', /* ` */
 595      '!', /* ! */    '@', /* @ */    '#', /* # */    '$', /* $ */    '%', /* % */
 596      '^', /* ^ */    '&', /* & */    '*', /* * */    '(', /* ( */    ')', /* ) */
 597      '=', /* = */    '+', /* + */    '|', /* | */    '/', /* / */    '\\', /* \ */
 598      ';', /* ; */    ':', /* : */    ',', /* , */    '?' /* ? */
 599      );
 600      $string = str_replace($bad, '', $string);
 601      // replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing

 602      $string = preg_replace(array('/\.+/', '/\.+$/'), array('.', ''), $string);
 603      // Now replace spaces with page spcacer

 604      $string = trim($string);
 605      $string = preg_replace('/(\s)+/', PAGE_SPACER, $string);
 606      // Now convert to lower-case

 607      $string = strtolower($string);
 608      // If there are any weird language characters, this will protect us against possible problems they could cause

 609      $string = str_replace(array('%2F', '%'), array('/', ''), urlencode($string));
 610      // Finally, return the cleaned string

 611      return $string;
 612  }
 613  
 614  // Function to convert a desired media filename to a clean mediafilename

 615  function media_filename($string)
 616  {
 617      require_once (WB_PATH.'/framework/functions-utf8.php');
 618      $string = entities_to_7bit($string);
 619      // Now remove all bad characters

 620      $bad = array('\'','"','`','!','@','#','$','%','^','&','*','=','+','|','/','\\',';',':',',','?');
 621      $string = str_replace($bad, '', $string);
 622      // replace multiple dots in filename to single dot and (multiple) dots at the end of the filename to nothing

 623      $string = preg_replace(array('/\.+/', '/\.+$/', '/\s/'), array('.', '', '_'), $string);
 624      // Clean any page spacers at the end of string

 625      $string = trim($string);
 626      // Finally, return the cleaned string

 627      return $string;
 628  }
 629  
 630  // Function to work out a page link

 631  if(!function_exists('page_link'))
 632  {
 633  	function page_link($link)
 634      {
 635          global $admin;
 636          return $admin->page_link($link);
 637      }
 638  }
 639  
 640  // Create a new directory and/or protected file in the given directory

 641  function createFolderProtectFile($sAbsDir='',$make_dir=true)
 642  {
 643      global $admin, $MESSAGE;
 644      $retVal = array();
 645      $wb_path = rtrim(str_replace('\/\\', '/', WB_PATH), '/');
 646      if( ($sAbsDir=='') || ($sAbsDir == $wb_path) ) { return $retVal;}
 647  
 648      if ( $make_dir==true ) {
 649          // Check to see if the folder already exists

 650          if(file_exists($sAbsDir)) {
 651              // $admin->print_error($MESSAGE['MEDIA_DIR_EXISTS']);

 652              $retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_EXISTS'];
 653          }
 654          if (!is_dir($sAbsDir) && !make_dir($sAbsDir) ) {
 655              // $admin->print_error($MESSAGE['MEDIA_DIR_NOT_MADE']);

 656              $retVal[] = basename($sAbsDir).'::'.$MESSAGE['MEDIA_DIR_NOT_MADE'];
 657          } else {
 658              change_mode($sAbsDir);
 659          }
 660      }
 661  
 662      if( is_writable($sAbsDir) )
 663      {
 664          // if(file_exists($sAbsDir.'/index.php')) { unlink($sAbsDir.'/index.php'); }

 665          // Create default "index.php" file

 666          $rel_pages_dir = str_replace($wb_path, '', dirname($sAbsDir) );
 667          $step_back = str_repeat( '../', substr_count($rel_pages_dir, '/')+1 );
 668  
 669          $sResponse  = $_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently';
 670          $content =
 671              '<?php'."\n".
 672              '// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
 673              '// *** Creation date: '.date('c')."\n".
 674              '// *** Do not modify this file manually'."\n".
 675              '// *** WB will rebuild this file from time to time!!'."\n".
 676              '// *************************************************'."\n".
 677              "\t".'header(\''.$sResponse.'\');'."\n".
 678              "\t".'header(\'Location: '.WB_URL.'/index.php\');'."\n".
 679              '// *************************************************'."\n";
 680          $filename = $sAbsDir.'/index.php';
 681  
 682          // write content into file

 683            if(is_writable($filename) || !file_exists($filename)) {
 684                if(file_put_contents($filename, $content)) {
 685          //    print 'create => '.str_replace( $wb_path,'',$filename).'<br />';

 686                    change_mode($filename, 'file');
 687                }else {
 688              $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'].' :: '.$filename;
 689             }
 690            }
 691           } else {
 692             $retVal[] = $MESSAGE['GENERIC_BAD_PERMISSIONS'];
 693           }
 694           return $retVal;
 695  }
 696  
 697  function rebuildFolderProtectFile($dir='')
 698  {
 699      $retVal = array();
 700      $dir = rtrim(str_replace('\/\\', '/', $dir), '/');
 701      try {
 702          $files = array();
 703          $files[] = $dir;
 704          foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $fileInfo) {
 705              $files[] = $fileInfo->getPath();
 706          }
 707          $files = array_unique($files);
 708          foreach( $files as $file) {
 709              $protect_file = rtrim(str_replace('\/\\', '/', $file), '/');
 710              $retVal[] = createFolderProtectFile($protect_file,false);
 711          }
 712      } catch ( Exception $e ) {
 713          $retVal[] = $MESSAGE['MEDIA_DIR_ACCESS_DENIED'];
 714      }
 715      return $retVal;
 716  }
 717  
 718  // Create a new file in the pages directory

 719  function create_access_file($filename,$page_id,$level)
 720  {
 721      global $admin, $MESSAGE;
 722      // First make sure parent folder exists

 723      $parent_folders = explode('/',str_replace(WB_PATH.PAGES_DIRECTORY, '', dirname($filename)));
 724      $parents = '';
 725      foreach($parent_folders AS $parent_folder)
 726      {
 727          if($parent_folder != '/' AND $parent_folder != '')
 728          {
 729              $parents .= '/'.$parent_folder;
 730              $acces_file = WB_PATH.PAGES_DIRECTORY.$parents;
 731              // can only be dirs

 732              if(!file_exists($acces_file)) {
 733                  if(!make_dir($acces_file)) {
 734                      $admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE_FOLDER']);
 735                  }
 736              }
 737          }
 738      }
 739      // The depth of the page directory in the directory hierarchy

 740      // '/pages' is at depth 1

 741      $pages_dir_depth = count(explode('/',PAGES_DIRECTORY))-1;
 742      // Work-out how many ../'s we need to get to the index page

 743      $index_location = '';
 744      for($i = 0; $i < $level + $pages_dir_depth; $i++) {
 745          $index_location .= '../';
 746      }
 747      $content =
 748          '<?php'."\n".
 749          '// *** This file is generated by WebsiteBaker Ver.'.VERSION."\n".
 750          '// *** Creation date: '.date('c')."\n".
 751          '// *** Do not modify this file manually'."\n".
 752          '// *** WB will rebuild this file from time to time!!'."\n".
 753          '// *************************************************'."\n".
 754          "\t".'$page_id    = '.$page_id.';'."\n".
 755          "\t".'require(\''.$index_location.'index.php\');'."\n".
 756          '// *************************************************'."\n";
 757  
 758      if( ($handle = fopen($filename, 'w')) ) {
 759          fwrite($handle, $content);
 760          fclose($handle);
 761          // Chmod the file

 762          change_mode($filename);
 763      } else {
 764          $admin->print_error($MESSAGE['PAGES']['CANNOT_CREATE_ACCESS_FILE']);
 765      }
 766      return;
 767   }
 768  
 769  // Function for working out a file mime type (if the in-built PHP one is not enabled)

 770  if(!function_exists('mime_content_type'))
 771  {
 772      function mime_content_type($filename)
 773      {
 774          $mime_types = array(
 775              'txt'    => 'text/plain',
 776              'htm'    => 'text/html',
 777              'html'    => 'text/html',
 778              'php'    => 'text/html',
 779              'css'    => 'text/css',
 780              'js'    => 'application/javascript',
 781              'json'    => 'application/json',
 782              'xml'    => 'application/xml',
 783              'swf'    => 'application/x-shockwave-flash',
 784              'flv'    => 'video/x-flv',
 785  
 786              // images

 787              'png'    => 'image/png',
 788              'jpe'    => 'image/jpeg',
 789              'jpeg'    => 'image/jpeg',
 790              'jpg'    => 'image/jpeg',
 791              'gif'    => 'image/gif',
 792              'bmp'    => 'image/bmp',
 793              'ico'    => 'image/vnd.microsoft.icon',
 794              'tiff'    => 'image/tiff',
 795              'tif'    => 'image/tiff',
 796              'svg'    => 'image/svg+xml',
 797              'svgz'    => 'image/svg+xml',
 798  
 799              // archives

 800              'zip'    => 'application/zip',
 801              'rar'    => 'application/x-rar-compressed',
 802              'exe'    => 'application/x-msdownload',
 803              'msi'    => 'application/x-msdownload',
 804              'cab'    => 'application/vnd.ms-cab-compressed',
 805  
 806              // audio/video

 807              'mp3'    => 'audio/mpeg',
 808              'mp4'    => 'audio/mpeg',
 809              'qt'    => 'video/quicktime',
 810              'mov'    => 'video/quicktime',
 811  
 812              // adobe

 813              'pdf'    => 'application/pdf',
 814              'psd'    => 'image/vnd.adobe.photoshop',
 815              'ai'    => 'application/postscript',
 816              'eps'    => 'application/postscript',
 817              'ps'    => 'application/postscript',
 818  
 819              // ms office

 820              'doc'    => 'application/msword',
 821              'rtf'    => 'application/rtf',
 822              'xls'    => 'application/vnd.ms-excel',
 823              'ppt'    => 'application/vnd.ms-powerpoint',
 824  
 825              // open office

 826              'odt'    => 'application/vnd.oasis.opendocument.text',
 827              'ods'    => 'application/vnd.oasis.opendocument.spreadsheet',
 828          );
 829          $temp = explode('.',$filename);
 830          $ext = strtolower(array_pop($temp));
 831          if (array_key_exists($ext, $mime_types)) {
 832              return $mime_types[$ext];
 833          }elseif (function_exists('finfo_open')) {
 834              $finfo = finfo_open(FILEINFO_MIME);
 835              $mimetype = finfo_file($finfo, $filename);
 836              finfo_close($finfo);
 837              return $mimetype;
 838          }else {
 839              return 'application/octet-stream';
 840          }
 841      }
 842  }
 843  
 844  // Generate a thumbnail from an image

 845  function make_thumb($source, $destination, $size)
 846  {
 847      // Check if GD is installed

 848      if(extension_loaded('gd') && function_exists('imageCreateFromJpeg'))
 849      {
 850          // First figure out the size of the thumbnail

 851          list($original_x, $original_y) = getimagesize($source);
 852          if ($original_x > $original_y) {
 853              $thumb_w = $size;
 854              $thumb_h = $original_y*($size/$original_x);
 855          }
 856          if ($original_x < $original_y) {
 857              $thumb_w = $original_x*($size/$original_y);
 858              $thumb_h = $size;
 859          }
 860          if ($original_x == $original_y) {
 861              $thumb_w = $size;
 862              $thumb_h = $size;
 863          }
 864          // Now make the thumbnail

 865          $source = imageCreateFromJpeg($source);
 866          $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
 867          imagecopyresampled($dst_img,$source,0,0,0,0,$thumb_w,$thumb_h,$original_x,$original_y);
 868          imagejpeg($dst_img, $destination);
 869          // Clear memory

 870          imagedestroy($dst_img);
 871          imagedestroy($source);
 872         // Return true

 873          return true;
 874      } else {
 875          return false;
 876      }
 877  }
 878  
 879  /*

 880   * Function to work-out a single part of an octal permission value

 881   *

 882   * @param mixed $octal_value: an octal value as string (i.e. '0777') or real octal integer (i.e. 0777 | 777)

 883   * @param string $who: char or string for whom the permission is asked( U[ser] / G[roup] / O[thers] )

 884   * @param string $action: char or string with the requested action( r[ead..] / w[rite..] / e|x[ecute..] )

 885   * @return boolean

 886   */
 887  function extract_permission($octal_value, $who, $action)
 888  {
 889      // Make sure that all arguments are set and $octal_value is a real octal-integer

 890      if(($who == '') || ($action == '') || (preg_match( '/[^0-7]/', (string)$octal_value ))) {
 891          return false; // invalid argument, so return false

 892      }
 893      // convert $octal_value into a decimal-integer to be sure having a valid value

 894      $right_mask = octdec($octal_value);
 895      $action_mask = 0;
 896      // set the $action related bit in $action_mask

 897      switch($action[0]) { // get action from first char of $action
 898          case 'r':
 899          case 'R':
 900              $action_mask = 4; // set read-bit only (2^2)

 901              break;
 902          case 'w':
 903          case 'W':
 904              $action_mask = 2; // set write-bit only (2^1)

 905              break;
 906          case 'e':
 907          case 'E':
 908          case 'x':
 909          case 'X':
 910              $action_mask = 1; // set execute-bit only (2^0)

 911              break;
 912          default:
 913              return false; // undefined action name, so return false

 914      }
 915      // shift action-mask into the right position

 916      switch($who[0]) { // get who from first char of $who
 917          case 'u':
 918          case 'U':
 919              $action_mask <<= 3; // shift left 3 bits

 920          case 'g':
 921          case 'G':
 922              $action_mask <<= 3; // shift left 3 bits

 923          case 'o':
 924          case 'O':
 925              /* NOP */

 926              break;
 927          default:
 928              return false; // undefined who, so return false

 929      }
 930      return( ($right_mask & $action_mask) != 0 ); // return result of binary-AND

 931  }
 932  
 933  // Function to delete a page

 934  	function delete_page($page_id)
 935      {
 936          global $admin, $database, $MESSAGE;
 937          // Find out more about the page

 938          $sql  = 'SELECT `page_id`, `menu_title`, `page_title`, `level`, ';
 939          $sql .=        '`link`, `parent`, `modified_by`, `modified_when` ';
 940          $sql .= 'FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
 941          $results = $database->query($sql);
 942          if($database->is_error())    { $admin->print_error($database->get_error()); }
 943          if($results->numRows() == 0) { $admin->print_error($MESSAGE['PAGES']['NOT_FOUND']); }
 944          $results_array = $results->fetchRow();
 945          $parent     = $results_array['parent'];
 946          $level      = $results_array['level'];
 947          $link       = $results_array['link'];
 948          $page_title = $results_array['page_title'];
 949          $menu_title = $results_array['menu_title'];
 950          // Get the sections that belong to the page

 951          $sql  = 'SELECT `section_id`, `module` FROM `'.TABLE_PREFIX.'sections` ';
 952          $sql .= 'WHERE `page_id`='.$page_id;
 953          $query_sections = $database->query($sql);
 954          if($query_sections->numRows() > 0)
 955          {
 956              while($section = $query_sections->fetchRow()) {
 957                  // Set section id

 958                  $section_id = $section['section_id'];
 959                  // Include the modules delete file if it exists

 960                  if(file_exists(WB_PATH.'/modules/'.$section['module'].'/delete.php')) {
 961                      include(WB_PATH.'/modules/'.$section['module'].'/delete.php');
 962                  }
 963              }
 964          }
 965          // Update the pages table

 966          $sql = 'DELETE FROM `'.TABLE_PREFIX.'pages` WHERE `page_id`='.$page_id;
 967          $database->query($sql);
 968          if($database->is_error()) {
 969              $admin->print_error($database->get_error());
 970          }
 971          // Update the sections table

 972          $sql = 'DELETE FROM `'.TABLE_PREFIX.'sections` WHERE `page_id`='.$page_id;
 973          $database->query($sql);
 974          if($database->is_error()) {
 975              $admin->print_error($database->get_error());
 976          }
 977          // Include the ordering class or clean-up ordering

 978          include_once (WB_PATH.'/framework/class.order.php');
 979          $order = new order(TABLE_PREFIX.'pages', 'position', 'page_id', 'parent');
 980          $order->clean($parent);
 981          // Unlink the page access file and directory

 982          $directory = WB_PATH.PAGES_DIRECTORY.$link;
 983          $filename = $directory.PAGE_EXTENSION;
 984          $directory .= '/';
 985          if(file_exists($filename))
 986          {
 987              if(!is_writable(WB_PATH.PAGES_DIRECTORY.'/')) {
 988                  $admin->print_error($MESSAGE['PAGES']['CANNOT_DELETE_ACCESS_FILE']);
 989              }else {
 990                  unlink($filename);
 991                  if( file_exists($directory) &&
 992                     (rtrim($directory,'/') != WB_PATH.PAGES_DIRECTORY) &&
 993                     (substr($link, 0, 1) != '.'))
 994                  {
 995                      rm_full_dir($directory);
 996                  }
 997              }
 998          }
 999      }
1000  
1001  /*

1002   * @param string $file: name of the file to read

1003   * @param int $size: number of maximum bytes to read (0 = complete file)

1004   * @return string: the content as string, false on error

1005   */
1006  	function getFilePart($file, $size = 0)
1007      {
1008          $file_content = '';
1009          if( file_exists($file) && is_file($file) && is_readable($file))
1010          {
1011              if($size == 0) {
1012                  $size = filesize($file);
1013              }
1014              if(($fh = fopen($file, 'rb'))) {
1015                  if( ($file_content = fread($fh, $size)) !== false ) {
1016                      return $file_content;
1017                  }
1018                  fclose($fh);
1019              }
1020          }
1021          return false;
1022      }
1023  
1024      /**

1025      * replace varnames with values in a string

1026      *

1027      * @param string $subject: stringvariable with vars placeholder

1028      * @param array $replace: values to replace vars placeholder

1029      * @return string

1030      */
1031      function replace_vars($subject = '', &$replace = null )
1032      {
1033          if(is_array($replace))
1034          {
1035              foreach ($replace  as $key => $value) {
1036                  $subject = str_replace("{{".$key."}}", $value, $subject);
1037              }
1038          }
1039          return $subject;
1040      }
1041  
1042  // Load module into DB

1043  function load_module($directory, $install = false)
1044  {
1045      global $database,$admin,$MESSAGE;
1046      $retVal = false;
1047      if(is_dir($directory) && file_exists($directory.'/info.php'))
1048      {
1049          require($directory.'/info.php');
1050          if(isset($module_name))
1051          {
1052              if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1053              if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1054              if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1055              $module_function = strtolower($module_function);
1056              // Check that it doesn't already exist

1057              $sqlwhere = 'WHERE `type` = \'module\' AND `directory` = \''.$module_directory.'\'';
1058              $sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1059              if( $database->get_one($sql) ) {
1060                  $sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1061              }else{
1062                  // Load into DB

1063                  $sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1064                  $sqlwhere = '';
1065              }
1066              $sql .= '`directory`=\''.$module_directory.'\', ';
1067              $sql .= '`name`=\''.$module_name.'\', ';
1068              $sql .= '`description`=\''.addslashes($module_description).'\', ';
1069              $sql .= '`type`=\'module\', ';
1070              $sql .= '`function`=\''.$module_function.'\', ';
1071              $sql .= '`version`=\''.$module_version.'\', ';
1072              $sql .= '`platform`=\''.$module_platform.'\', ';
1073              $sql .= '`author`=\''.addslashes($module_author).'\', ';
1074              $sql .= '`license`=\''.addslashes($module_license).'\'';
1075              $sql .= $sqlwhere;
1076              $retVal = $database->query($sql);
1077              // Run installation script

1078              if($install == true) {
1079                  if(file_exists($directory.'/install.php')) {
1080                      require($directory.'/install.php');
1081                  }
1082              }
1083          }
1084      }
1085  }
1086  
1087  // Load template into DB

1088  function load_template($directory)
1089  {
1090      global $database, $admin;
1091      $retVal = false;
1092      if(is_dir($directory) && file_exists($directory.'/info.php'))
1093      {
1094          require($directory.'/info.php');
1095          if(isset($template_name))
1096          {
1097              if(!isset($template_license)) {
1098                $template_license = 'GNU General Public License';
1099              }
1100              if(!isset($template_platform) && isset($template_designed_for)) {
1101                $template_platform = $template_designed_for;
1102              }
1103              if(!isset($template_function)) {
1104                $template_function = 'template';
1105              }
1106              // Check that it doesn't already exist

1107              $sqlwhere = 'WHERE `type`=\'template\' AND `directory`=\''.$template_directory.'\'';
1108              $sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1109              if( $database->get_one($sql) ) {
1110                  $sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1111              }else{
1112                  // Load into DB

1113                  $sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1114                  $sqlwhere = '';
1115              }
1116              $sql .= '`directory`=\''.$template_directory.'\', ';
1117              $sql .= '`name`=\''.$template_name.'\', ';
1118              $sql .= '`description`=\''.addslashes($template_description).'\', ';
1119              $sql .= '`type`=\'template\', ';
1120              $sql .= '`function`=\''.$template_function.'\', ';
1121              $sql .= '`version`=\''.$template_version.'\', ';
1122              $sql .= '`platform`=\''.$template_platform.'\', ';
1123              $sql .= '`author`=\''.addslashes($template_author).'\', ';
1124              $sql .= '`license`=\''.addslashes($template_license).'\' ';
1125              $sql .= $sqlwhere;
1126              $retVal = $database->query($sql);
1127          }
1128      }
1129      return $retVal;
1130  }
1131  
1132  // Load language into DB

1133  function load_language($file)
1134  {
1135      global $database,$admin;
1136      $retVal = false;
1137      if (file_exists($file) && preg_match('#^([A-Z]{2}.php)#', basename($file)))
1138      {
1139          // require($file);  it's to large

1140          // read contents of the template language file into string

1141          $data = @file_get_contents(WB_PATH.'/languages/'.str_replace('.php','',basename($file)).'.php');
1142          // use regular expressions to fetch the content of the variable from the string

1143          $language_name = get_variable_content('language_name', $data, false, false);
1144          $language_code = get_variable_content('language_code', $data, false, false);
1145          $language_author = get_variable_content('language_author', $data, false, false);
1146          $language_version = get_variable_content('language_version', $data, false, false);
1147          $language_platform = get_variable_content('language_platform', $data, false, false);
1148  
1149          if(isset($language_name))
1150          {
1151              if(!isset($language_license)) { $language_license = 'GNU General Public License'; }
1152              if(!isset($language_platform) && isset($language_designed_for)) { $language_platform = $language_designed_for; }
1153              // Check that it doesn't already exist

1154              $sqlwhere = 'WHERE `type`=\'language\' AND `directory`=\''.$language_code.'\'';
1155              $sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` '.$sqlwhere;
1156              if( $database->get_one($sql) ) {
1157                  $sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1158              }else{
1159                  // Load into DB

1160                  $sql  = 'INSERT INTO `'.TABLE_PREFIX.'addons` SET ';
1161                  $sqlwhere = '';
1162              }
1163              $sql .= '`directory`=\''.$language_code.'\', ';
1164              $sql .= '`name`=\''.$language_name.'\', ';
1165              $sql .= '`type`=\'language\', ';
1166              $sql .= '`version`=\''.$language_version.'\', ';
1167              $sql .= '`platform`=\''.$language_platform.'\', ';
1168              $sql .= '`author`=\''.addslashes($language_author).'\', ';
1169              $sql .= '`license`=\''.addslashes($language_license).'\' ';
1170              $sql .= $sqlwhere;
1171              $retVal = $database->query($sql);
1172          }
1173      }
1174      return $retVal;
1175  }
1176  
1177  // Upgrade module info in DB, optionally start upgrade script

1178  function upgrade_module($directory, $upgrade = false)
1179  {
1180      global $database, $admin, $MESSAGE, $new_module_version;
1181      $mod_directory = WB_PATH.'/modules/'.$directory;
1182      if(file_exists($mod_directory.'/info.php'))
1183      {
1184          require($mod_directory.'/info.php');
1185          if(isset($module_name))
1186          {
1187              if(!isset($module_license)) { $module_license = 'GNU General Public License'; }
1188              if(!isset($module_platform) && isset($module_designed_for)) { $module_platform = $module_designed_for; }
1189              if(!isset($module_function) && isset($module_type)) { $module_function = $module_type; }
1190              $module_function = strtolower($module_function);
1191              // Check that it does already exist

1192              $sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'addons` ';
1193              $sql .= 'WHERE `directory`=\''.$module_directory.'\'';
1194              if( $database->get_one($sql) )
1195              {
1196                  // Update in DB

1197                  $sql  = 'UPDATE `'.TABLE_PREFIX.'addons` SET ';
1198                  $sql .= '`version`=\''.$module_version.'\', ';
1199                  $sql .= '`description`=\''.addslashes($module_description).'\', ';
1200                  $sql .= '`platform`=\''.$module_platform.'\', ';
1201                  $sql .= '`author`=\''.addslashes($module_author).'\', ';
1202                  $sql .= '`license`=\''.addslashes($module_license).'\' ';
1203                  $sql .= 'WHERE `directory`=\''.$module_directory.'\' ';
1204                  $database->query($sql);
1205                  if($database->is_error()) {
1206                      $admin->print_error($database->get_error());
1207                  }
1208                  // Run upgrade script

1209                  if($upgrade == true) {
1210                      if(file_exists($mod_directory.'/upgrade.php')) {
1211                          require($mod_directory.'/upgrade.php');
1212                      }
1213                  }
1214              }
1215          }
1216      }
1217  }
1218  
1219  // extracts the content of a string variable from a string (save alternative to including files)

1220  if(!function_exists('get_variable_content'))
1221  {
1222  	function get_variable_content($search, $data, $striptags=true, $convert_to_entities=true)
1223      {
1224          $match = '';
1225          // search for $variable followed by 0-n whitespace then by = then by 0-n whitespace

1226          // then either " or ' then 0-n characters then either " or ' followed by 0-n whitespace and ;

1227          // the variable name is returned in $match[1], the content in $match[3]

1228          if (preg_match('/(\$' .$search .')\s*=\s*("|\')(.*)\2\s*;/', $data, $match))
1229          {
1230              if(strip_tags(trim($match[1])) == '$' .$search) {
1231                  // variable name matches, return it's value

1232                  $match[3] = ($striptags == true) ? strip_tags($match[3]) : $match[3];
1233                  $match[3] = ($convert_to_entities == true) ? htmlentities($match[3]) : $match[3];
1234                  return $match[3];
1235              }
1236          }
1237          return false;
1238      }
1239  }
1240  
1241  /*

1242   * @param string $modulname: like saved in addons.directory

1243   * @param boolean $source: true reads from database, false from info.php

1244   * @return string:  the version as string, if not found returns null

1245   */
1246  
1247  	function get_modul_version($modulname, $source = true)
1248      {
1249          global $database;
1250          $version = null;
1251          if( $source != true )
1252          {
1253              $sql  = 'SELECT `version` FROM `'.TABLE_PREFIX.'addons` ';
1254              $sql .= 'WHERE `directory`=\''.$modulname.'\'';
1255              $version = $database->get_one($sql);
1256          } else {
1257              $info_file = WB_PATH.'/modules/'.$modulname.'/info.php';
1258              if(file_exists($info_file)) {
1259                  if(($info_file = file_get_contents($info_file))) {
1260                      $version = get_variable_content('module_version', $info_file, false, false);
1261                      $version = ($version !== false) ? $version : null;
1262                  }
1263              }
1264          }
1265          return $version;
1266      }
1267  
1268  /*

1269   * @param string $varlist: commaseperated list of varnames to move into global space

1270   * @return bool:  false if one of the vars already exists in global space (error added to msgQueue)

1271   */
1272  	function vars2globals_wrapper($varlist)
1273      {
1274          $retval = true;
1275          if( $varlist != '')
1276          {
1277              $vars = explode(',', $varlist);
1278              foreach( $vars as $var)
1279              {
1280                  if( isset($GLOBALS[$var]) ){
1281                      ErrorLog::write( 'variabe $'.$var.' already defined in global space!!',__FILE__, __FUNCTION__, __LINE__);
1282                      $retval = false;
1283                  }else {
1284                      global $$var;
1285                  }
1286              }
1287          }
1288          return $retval;
1289      }
1290  
1291  /*

1292   * filter directory traversal more thoroughly, thanks to hal 9000

1293   * @param string $dir: directory relative to MEDIA_DIRECTORY

1294   * @param bool $with_media_dir: true when to include MEDIA_DIRECTORY

1295   * @return: false if directory traversal detected, real path if not

1296   */
1297  	function check_media_path($directory, $with_media_dir = true)
1298      {
1299          $md = ($with_media_dir) ? MEDIA_DIRECTORY : '';
1300          $dir = realpath(WB_PATH . $md . '/' . utf8_decode($directory));
1301          $required = realpath(WB_PATH . MEDIA_DIRECTORY);
1302          if (strstr($dir, $required)) {
1303              return $dir;
1304          } else {
1305              return false;
1306          }
1307      }
1308  
1309  /*

1310  urlencode function and rawurlencode are mostly based on RFC 1738.

1311  However, since 2005 the current RFC in use for URIs standard is RFC 3986.

1312  Here is a function to encode URLs according to RFC 3986.

1313  */
1314  if(!function_exists('url_encode')){
1315  	function url_encode($string) {
1316          $string = html_entity_decode($string,ENT_QUOTES,'UTF-8');
1317          $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
1318          $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
1319          return str_replace($entities,$replacements, rawurlencode($string));
1320      }
1321  }

title

Description

title

Description

title

Description

title

title

Body