iTx Technologies offre gratuitement
cet espace pour SugarCRM !

title

Body

[fermer]

/install/ -> install_utils.php (source)

   1  <?php
   2  if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
   3  /*********************************************************************************
   4   * SugarCRM is a customer relationship management program developed by
   5   * SugarCRM, Inc. Copyright (C) 2004 - 2009 SugarCRM Inc.
   6   * 
   7   * This program is free software; you can redistribute it and/or modify it under
   8   * the terms of the GNU General Public License version 3 as published by the
   9   * Free Software Foundation with the addition of the following permission added
  10   * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
  11   * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
  12   * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
  13   * 
  14   * This program is distributed in the hope that it will be useful, but WITHOUT
  15   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  16   * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
  17   * details.
  18   * 
  19   * You should have received a copy of the GNU General Public License along with
  20   * this program; if not, see http://www.gnu.org/licenses or write to the Free
  21   * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  22   * 02110-1301 USA.
  23   * 
  24   * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
  25   * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
  26   * 
  27   * The interactive user interfaces in modified source and object code versions
  28   * of this program must display Appropriate Legal Notices, as required under
  29   * Section 5 of the GNU General Public License version 3.
  30   * 
  31   * In accordance with Section 7(b) of the GNU General Public License version 3,
  32   * these Appropriate Legal Notices must retain the display of the "Powered by
  33   * SugarCRM" logo. If the display of the logo is not reasonably feasible for
  34   * technical reasons, the Appropriate Legal Notices must display the words
  35   * "Powered by SugarCRM".
  36   ********************************************************************************/
  37  /*********************************************************************************
  38  
  39   * $Description: TODO: To be written. Portions created by SugarCRM are Copyright
  40   * (C) SugarCRM, Inc. All Rights Reserved. Contributor(s):
  41   * ______________________________________..
  42   * *******************************************************************************/
  43  
  44  require_once ('include/utils/zip_utils.php');
  45  
  46  require_once ('include/upload_file.php');
  47  
  48  
  49  
  50  ///////////////////////////////////////////////////////////////////////////////
  51  ////    FROM welcome.php
  52  /**
  53   * returns lowercase lang encoding
  54   * @return string   encoding or blank on false
  55   */
  56  function parseAcceptLanguage() {
  57      $lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  58      if(strpos($lang, ';')) {
  59          $exLang = explode(';', $lang);
  60          return strtolower(str_replace('-','_',$exLang[0]));
  61      } else {
  62          $match = array();
  63          if(preg_match("#\w{2}\-?\_?\w{2}#", $lang, $match)) {
  64              return strtolower(str_replace('-','_',$match[0]));
  65          }
  66      }
  67      return '';
  68  }
  69  
  70  
  71  ///////////////////////////////////////////////////////////////////////////////
  72  ////    FROM localization.php
  73  /**
  74   * copies the temporary unzip'd files to their final destination
  75   * removes unzip'd files from system if $uninstall=true
  76   * @param bool uninstall true if uninstalling a language pack
  77   * @return array sugar_config
  78   */
  79  function commitLanguagePack($uninstall=false) {
  80      global $sugar_config;
  81      global $mod_strings;
  82      global $base_upgrade_dir;
  83      global $base_tmp_upgrade_dir;
  84  
  85      $errors         = array();
  86      $manifest       = urldecode($_REQUEST['manifest']);
  87      $zipFile        = urldecode($_REQUEST['zipFile']);
  88      $version        = "";
  89      $show_files     = true;
  90      $unzip_dir      = mk_temp_dir( $base_tmp_upgrade_dir );
  91      $zip_from_dir   = ".";
  92      $zip_to_dir     = ".";
  93      $zip_force_copy = array();
  94  
  95      if($uninstall == false && isset($_SESSION['INSTALLED_LANG_PACKS']) && in_array($zipFile, $_SESSION['INSTALLED_LANG_PACKS'])) {
  96          return;
  97      }
  98  
  99      // unzip lang pack to temp dir
 100      if(isset($zipFile) && !empty($zipFile)) {
 101          if(is_file($zipFile)) {
 102              unzip( $zipFile, $unzip_dir );
 103          } else {
 104              echo $mod_strings['ERR_LANG_MISSING_FILE'].$zipFile;
 105              die(); // no point going any further
 106          }
 107      }
 108  
 109      // filter for special to/from dir conditions (langpacks generally don't have them)
 110      if(isset($manifest) && !empty($manifest)) {
 111          if(is_file($manifest)) {
 112              include($manifest);
 113              if( isset( $manifest['copy_files']['from_dir'] ) && $manifest['copy_files']['from_dir'] != "" ){
 114                  $zip_from_dir   = $manifest['copy_files']['from_dir'];
 115              }
 116              if( isset( $manifest['copy_files']['to_dir'] ) && $manifest['copy_files']['to_dir'] != "" ){
 117                  $zip_to_dir     = $manifest['copy_files']['to_dir'];
 118              }
 119              if( isset( $manifest['copy_files']['force_copy'] ) && $manifest['copy_files']['force_copy'] != "" ){
 120                  $zip_force_copy     = $manifest['copy_files']['force_copy'];
 121              }
 122              if( isset( $manifest['version'] ) ){
 123                  $version    = $manifest['version'];
 124              }
 125          } else {
 126              $errors[] = $mod_strings['ERR_LANG_MISSING_FILE'].$manifest;
 127          }
 128      }
 129  
 130  
 131      // find name of language pack: find single file in include/language/xx_xx.lang.php
 132      $d = dir( "$unzip_dir/$zip_from_dir/include/language" );
 133      while( $f = $d->read() ){
 134          if( $f == "." || $f == ".." ){
 135              continue;
 136          }
 137          else if( preg_match("/(.*)\.lang\.php\$/", $f, $match) ){
 138              $new_lang_name = $match[1];
 139          }
 140      }
 141      if( $new_lang_name == "" ){
 142          die( $mod_strings['ERR_LANG_NO_LANG_FILE'].$zipFile );
 143      }
 144      $new_lang_desc = getLanguagePackName( "$unzip_dir/$zip_from_dir/include/language/$new_lang_name.lang.php" );
 145      if( $new_lang_desc == "" ){
 146          die( "No language pack description found at include/language/$new_lang_name.lang.php inside $install_file." );
 147      }
 148      // add language to available languages
 149      $sugar_config['languages'][$new_lang_name] = ($new_lang_desc);
 150  
 151      // get an array of all files to be moved
 152      $filesFrom = array();
 153      $filesFrom = findAllFiles($unzip_dir, $filesFrom);
 154  
 155  
 156  
 157      ///////////////////////////////////////////////////////////////////////////
 158      ////    FINALIZE
 159      if($uninstall) {
 160          // unlink all pack files
 161          foreach($filesFrom as $fileFrom) {
 162              //echo "deleting: ".getcwd().substr($fileFrom, strlen($unzip_dir), strlen($fileFrom))."<br>";
 163              @unlink(getcwd().substr($fileFrom, strlen($unzip_dir), strlen($fileFrom)));
 164          }
 165  
 166          // remove session entry
 167          if(isset($_SESSION['INSTALLED_LANG_PACKS']) && is_array($_SESSION['INSTALLED_LANG_PACKS'])) {
 168              foreach($_SESSION['INSTALLED_LANG_PACKS'] as $k => $langPack) {
 169                  if($langPack == $zipFile) {
 170                      unset($_SESSION['INSTALLED_LANG_PACKS'][$k]);
 171                      unset($_SESSION['INSTALLED_LANG_PACKS_VERSION'][$k]);
 172                      unset($_SESSION['INSTALLED_LANG_PACKS_MANIFEST'][$k]);
 173                      $removedLang = $k;
 174                  }
 175              }
 176  
 177              // remove language from config
 178              $new_langs = array();
 179              $old_langs = $sugar_config['languages'];
 180              foreach( $old_langs as $key => $value ){
 181                  if( $key != $removedLang ){
 182                      $new_langs += array( $key => $value );
 183                  }
 184              }
 185              $sugar_config['languages'] = $new_langs;
 186          }
 187      } else {
 188          // copy filesFrom to filesTo
 189          foreach($filesFrom as $fileFrom) {
 190              @copy($fileFrom, getcwd().substr($fileFrom, strlen($unzip_dir), strlen($fileFrom)));
 191          }
 192  
 193          $_SESSION['INSTALLED_LANG_PACKS'][$new_lang_name] = $zipFile;
 194          $_SESSION['INSTALLED_LANG_PACKS_VERSION'][$new_lang_name] = $version;
 195          $serial_manifest = array();
 196          $serial_manifest['manifest'] = (isset($manifest) ? $manifest : '');
 197          $serial_manifest['installdefs'] = (isset($installdefs) ? $installdefs : '');
 198          $serial_manifest['upgrade_manifest'] = (isset($upgrade_manifest) ? $upgrade_manifest : '');
 199          $_SESSION['INSTALLED_LANG_PACKS_MANIFEST'][$new_lang_name] = base64_encode(serialize($serial_manifest));
 200      }
 201  
 202      writeSugarConfig($sugar_config);
 203  
 204      return $sugar_config;
 205  }
 206  
 207  function commitPatch($unlink = false, $type = 'patch'){
 208      require_once ('ModuleInstall/ModuleInstaller.php');
 209      require_once ('include/entryPoint.php');
 210      
 211  
 212      global $mod_strings;
 213      global $base_upgrade_dir;
 214      global $base_tmp_upgrade_dir;
 215      global $db;
 216      $GLOBALS['db'] = $db;
 217      $errors = array();
 218      $files = array();
 219       global $current_user;
 220      $current_user = new User();
 221      $current_user->is_admin = '1';
 222      $old_mod_strings = $mod_strings;
 223      if(is_dir(getcwd()."/cache/upload/upgrades")) {
 224              $files = findAllFiles(getcwd()."/cache/upload/upgrades/$type", $files);
 225              $mi = new ModuleInstaller();
 226              $mi->silent = true;
 227              $mod_strings = return_module_language('en', "Administration");
 228  
 229              foreach($files as $file) {
 230                  if(!preg_match("#.*\.zip\$#", $file)) {
 231                      continue;
 232                  }
 233                  // handle manifest.php
 234                  $target_manifest = remove_file_extension( $file ) . '-manifest.php';
 235  
 236                  include($target_manifest);
 237  
 238                  $unzip_dir = mk_temp_dir( $base_tmp_upgrade_dir );
 239                  unzip($file, $unzip_dir );
 240                  if(file_exists("$unzip_dir/scripts/pre_install.php")){
 241                      require_once("$unzip_dir/scripts/pre_install.php");
 242                      pre_install();
 243                  }
 244                  if( isset( $manifest['copy_files']['from_dir'] ) && $manifest['copy_files']['from_dir'] != "" ){
 245                      $zip_from_dir   = $manifest['copy_files']['from_dir'];
 246                  }
 247                  $source = "$unzip_dir/$zip_from_dir";
 248                  $dest = getcwd();
 249                  copy_recursive($source, $dest);
 250  
 251                  if(file_exists("$unzip_dir/scripts/post_install.php")){
 252                      require_once("$unzip_dir/scripts/post_install.php");
 253                      post_install();
 254                  }
 255                  $new_upgrade = new UpgradeHistory();
 256                  $new_upgrade->filename      = $file;
 257                  $new_upgrade->md5sum        = md5_file($file);
 258                  $new_upgrade->type          = $manifest['type'];
 259                  $new_upgrade->version       = $manifest['version'];
 260                  $new_upgrade->status        = "installed";
 261                  //$new_upgrade->author        = $manifest['author'];
 262                  $new_upgrade->name          = $manifest['name'];
 263                  $new_upgrade->description   = $manifest['description'];
 264                  $serial_manifest = array();
 265                  $serial_manifest['manifest'] = (isset($manifest) ? $manifest : '');
 266                  $serial_manifest['installdefs'] = (isset($installdefs) ? $installdefs : '');
 267                  $serial_manifest['upgrade_manifest'] = (isset($upgrade_manifest) ? $upgrade_manifest : '');
 268                  $new_upgrade->manifest   = base64_encode(serialize($serial_manifest));
 269                  $new_upgrade->save();
 270                  unlink($file);
 271              }//rof
 272      }//fi
 273      $mod_strings = $old_mod_strings;
 274  }
 275  
 276  function commitModules($unlink = false, $type = 'module'){
 277      require_once ('ModuleInstall/ModuleInstaller.php');
 278      require_once ('include/entryPoint.php');
 279      
 280  
 281      global $mod_strings;
 282      global $base_upgrade_dir;
 283      global $base_tmp_upgrade_dir;
 284      global $db;
 285      $GLOBALS['db'] = $db;
 286      $errors = array();
 287      $files = array();
 288       global $current_user;
 289      $current_user = new User();
 290      $current_user->is_admin = '1';
 291      $old_mod_strings = $mod_strings;
 292      if(is_dir(getcwd()."/cache/upload/upgrades")) {
 293              $files = findAllFiles(getcwd()."/cache/upload/upgrades/$type", $files);
 294              $mi = new ModuleInstaller();
 295              $mi->silent = true;
 296              $mod_strings = return_module_language('en', "Administration");
 297  
 298              foreach($files as $file) {
 299                  if(!preg_match("#.*\.zip\$#", $file)) {
 300                      continue;
 301                  }
 302                  $lic_name = 'accept_lic_'.str_replace('.', '_', urlencode(basename($file)));
 303  
 304                  $can_install = true;
 305                  if(isset($_REQUEST[$lic_name])){
 306                      if($_REQUEST[$lic_name] == 'yes'){
 307                          $can_install = true;
 308                      }else{
 309                          $can_install = false;
 310                      }
 311                  }
 312                  if($can_install){
 313                      // handle manifest.php
 314                      $target_manifest = remove_file_extension( $file ) . '-manifest.php';
 315                      if($type == 'langpack'){
 316                          $_REQUEST['manifest'] = $target_manifest;
 317                          $_REQUEST['zipFile'] = $file;
 318                          commitLanguagePack();
 319                          continue;
 320                      }
 321                      include($target_manifest);
 322  
 323                      $unzip_dir = mk_temp_dir( $base_tmp_upgrade_dir );
 324                      unzip($file, $unzip_dir );
 325                      $_REQUEST['install_file'] = $file;
 326                      $mi->install($unzip_dir);
 327                      $new_upgrade = new UpgradeHistory();
 328                      $new_upgrade->filename      = $file;
 329                      $new_upgrade->md5sum        = md5_file($file);
 330                      $new_upgrade->type          = $manifest['type'];
 331                      $new_upgrade->version       = $manifest['version'];
 332                      $new_upgrade->status        = "installed";
 333                     // $new_upgrade->author        = $manifest['author'];
 334                      $new_upgrade->name          = $manifest['name'];
 335                      $new_upgrade->description   = $manifest['description'];
 336                      $new_upgrade->id_name       = (isset($installdefs['id_name'])) ? $installdefs['id_name'] : '';
 337                      $serial_manifest = array();
 338                      $serial_manifest['manifest'] = (isset($manifest) ? $manifest : '');
 339                      $serial_manifest['installdefs'] = (isset($installdefs) ? $installdefs : '');
 340                      $serial_manifest['upgrade_manifest'] = (isset($upgrade_manifest) ? $upgrade_manifest : '');
 341                      $new_upgrade->manifest   = base64_encode(serialize($serial_manifest));
 342                      $new_upgrade->save();
 343                      //unlink($file);
 344                  }//fi
 345              }//rof
 346      }//fi
 347      $mod_strings = $old_mod_strings;
 348  }
 349  
 350  /**
 351   * creates UpgradeHistory entries
 352   * @param mode string Install or Uninstall
 353   */
 354  function updateUpgradeHistory() {
 355      if(isset($_SESSION['INSTALLED_LANG_PACKS']) && count($_SESSION['INSTALLED_LANG_PACKS']) > 0) {
 356          foreach($_SESSION['INSTALLED_LANG_PACKS'] as $k => $zipFile) {
 357              $new_upgrade = new UpgradeHistory();
 358              $new_upgrade->filename      = $zipFile;
 359              $new_upgrade->md5sum        = md5_file($zipFile);
 360              $new_upgrade->type          = 'langpack';
 361              $new_upgrade->version       = $_SESSION['INSTALLED_LANG_PACKS_VERSION'][$k];
 362              $new_upgrade->status        = "installed";
 363              $new_upgrade->manifest      = $_SESSION['INSTALLED_LANG_PACKS_MANIFEST'][$k];
 364              $new_upgrade->save();
 365          }
 366      }
 367  }
 368  
 369  
 370  /**
 371   * removes the installed language pack, but the zip is still in the cache dir
 372   */
 373  function removeLanguagePack() {
 374      global $mod_strings;
 375      global $sugar_config;
 376  
 377      $errors = array();
 378      $manifest = urldecode($_REQUEST['manifest']);
 379      $zipFile = urldecode($_REQUEST['zipFile']);
 380  
 381      if(isset($manifest) && !empty($manifest)) {
 382          if(is_file($manifest)) {
 383              if(!unlink($manifest)) {
 384                  $errors[] = $mod_strings['ERR_LANG_CANNOT_DELETE_FILE'].$manifest;
 385              }
 386          } else {
 387              $errors[] = $mod_strings['ERR_LANG_MISSING_FILE'].$manifest;
 388          }
 389          unset($_SESSION['packages_to_install'][$manifest]);
 390      }
 391      if(isset($zipFile) && !empty($zipFile)) {
 392          if(is_file($zipFile)) {
 393              if(!unlink($zipFile)) {
 394                  $errors[] = $mod_strings['ERR_LANG_CANNOT_DELETE_FILE'].$zipFile;
 395              }
 396          } else {
 397              $errors[] = $mod_strings['ERR_LANG_MISSING_FILE'].$zipFile;
 398          }
 399      }
 400      if(count($errors > 0)) {
 401          echo "<p class='error'>";
 402          foreach($errors as $error) {
 403              echo "{$error}<br>";
 404          }
 405          echo "</p>";
 406      }
 407  
 408      unlinkTempFiles($manifest, $zipFile);
 409  }
 410  
 411  
 412  
 413  /**
 414   * takes the current value of $sugar_config and writes it out to config.php (sorta the same as the final step)
 415   * @param array sugar_config
 416   */
 417  function writeSugarConfig($sugar_config) {
 418      ksort($sugar_config);
 419      $sugar_config_string = "<?php\n" .
 420          '// created: ' . date('Y-m-d H:i:s') . "\n" .
 421          '$sugar_config = ' .
 422          var_export($sugar_config, true) .
 423          ";\n?>\n";
 424      if(is_writable('config.php') && write_array_to_file( "sugar_config", $sugar_config, "config.php")) {
 425      }
 426  }
 427  
 428  
 429  /**
 430   * uninstalls the Language pack
 431   */
 432  function uninstallLangPack() {
 433      global $sugar_config;
 434  
 435      // remove language from config
 436      $new_langs = array();
 437      $old_langs = $sugar_config['languages'];
 438      foreach( $old_langs as $key => $value ){
 439          if( $key != $_REQUEST['new_lang_name'] ){
 440              $new_langs += array( $key => $value );
 441          }
 442      }
 443      $sugar_config['languages'] = $new_langs;
 444  
 445      writeSugarConfig($sugar_config);
 446  }
 447  
 448  /**
 449   * retrieves the name of the language
 450   */
 451  if ( !function_exists('getLanguagePackName') ) {
 452  function getLanguagePackName($the_file) {
 453      require_once( "$the_file" );
 454      if( isset( $app_list_strings["language_pack_name"] ) ){
 455          return( $app_list_strings["language_pack_name"] );
 456      }
 457      return( "" );
 458  }
 459  }
 460  
 461  function getInstalledLangPacks($showButtons=true) {
 462      global $mod_strings;
 463      global $next_step;
 464  
 465      $ret  = "<tr><td colspan=7 align=left>{$mod_strings['LBL_LANG_PACK_INSTALLED']}</td></tr>";
 466      //$ret .="<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
 467      $ret .= "<tr>
 468                  <td width='15%' ><b>{$mod_strings['LBL_ML_NAME']}</b></td>
 469                  <td width='15%' ><b>{$mod_strings['LBL_ML_VERSION']}</b></td>
 470                  <td width='15%' ><b>{$mod_strings['LBL_ML_PUBLISHED']}</b></td>
 471                  <td width='15%' ><b>{$mod_strings['LBL_ML_UNINSTALLABLE']}</b></td>
 472                  <td width='15%' ><b>{$mod_strings['LBL_ML_DESCRIPTION']}</b></td>
 473                  <td width='15%' ></td>
 474                  <td width='15%' ></td>
 475              </tr>\n";
 476      $files = array();
 477      $files = findAllFiles(getcwd()."/cache/upload/upgrades", $files);
 478  
 479      if(isset($_SESSION['INSTALLED_LANG_PACKS']) && !empty($_SESSION['INSTALLED_LANG_PACKS'])){
 480          if(count($_SESSION['INSTALLED_LANG_PACKS'] > 0)) {
 481              foreach($_SESSION['INSTALLED_LANG_PACKS'] as $file) {
 482                  // handle manifest.php
 483                  $target_manifest = remove_file_extension( $file ) . '-manifest.php';
 484                  include($target_manifest);
 485  
 486                  $name = empty($manifest['name']) ? $file : $manifest['name'];
 487                  $version = empty($manifest['version']) ? '' : $manifest['version'];
 488                  $published_date = empty($manifest['published_date']) ? '' : $manifest['published_date'];
 489                  $icon = '';
 490                  $description = empty($manifest['description']) ? 'None' : $manifest['description'];
 491                  $uninstallable = empty($manifest['is_uninstallable']) ? 'No' : 'Yes';
 492                  $manifest_type = $manifest['type'];
 493  
 494                  $deletePackage = getPackButton('uninstall', $target_manifest, $file, $next_step, $uninstallable, $showButtons);
 495                  //$ret .="<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
 496                  $ret .= "<tr>";
 497                  $ret .= "<td width='15%' >".$name."</td>";
 498                  $ret .= "<td width='15%' >".$version."</td>";
 499                  $ret .= "<td width='15%' >".$published_date."</td>";
 500                  $ret .= "<td width='15%' >".$uninstallable."</td>";
 501                  $ret .= "<td width='15%' >".$description."</td>";
 502                  $ret .= "<td width='15%' ></td>";
 503                  $ret .= "<td width='15%' >{$deletePackage}</td>";
 504                  $ret .= "</tr>";
 505              }
 506          } else {
 507              $ret .= "</tr><td colspan=7><i>{$mod_strings['LBL_LANG_NO_PACKS']}</i></td></tr>";
 508          }
 509      } else {
 510          $ret .= "</tr><td colspan=7><i>{$mod_strings['LBL_LANG_NO_PACKS']}</i></td></tr>";
 511      }
 512      return $ret;
 513  }
 514  
 515  
 516  function uninstallLanguagePack() {
 517      return commitLanguagePack(true);
 518  }
 519  
 520  
 521  function getSugarConfigLanguageArray($langZip) {
 522      global $sugar_config;
 523  
 524      include(remove_file_extension($langZip)."-manifest.php");
 525      $ret = '';
 526      if(isset($installdefs['id']) && isset($manifest['name'])) {
 527          $ret = $installdefs['id']."::".$manifest['name']."::".$manifest['version'];
 528      }
 529  
 530      return $ret;
 531  }
 532  
 533  
 534  
 535  ///////////////////////////////////////////////////////////////////////////////
 536  ////    FROM performSetup.php
 537  /**
 538   * creates the Sugar DB user (if not admin)
 539   */
 540  function handleDbCreateSugarUser() {
 541      global $mod_strings;
 542      global $setup_db_database_name;
 543      global $setup_db_host_name;
 544      global $setup_db_host_instance;
 545      global $setup_db_admin_user_name;
 546      global $setup_db_admin_password;
 547      global $sugar_config;
 548      global $setup_db_sugarsales_user;
 549      global $setup_site_host_name;
 550      global $setup_db_sugarsales_password;
 551  
 552      echo $mod_strings['LBL_PERFORM_CREATE_DB_USER'];
 553      $errno = '';
 554      switch($_SESSION['setup_db_type']) {
 555          case "mysql":
 556              if(isset($_SESSION['mysql_type'])){
 557                  $host_name = getHostPortFromString($setup_db_host_name);
 558                  if(empty($host_name)){
 559                      $link = @mysqli_connect($setup_db_host_name, $setup_db_admin_user_name, $setup_db_admin_password);
 560                  }else{
 561                      $link = @mysqli_connect($host_name[0], $setup_db_admin_user_name, $setup_db_admin_password,null,$host_name[1]);
 562                  }
 563                  $query  = "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX
 564                              ON `{$setup_db_database_name}`.*
 565                              TO \"{$setup_db_sugarsales_user}\"@\"{$setup_site_host_name}\"
 566                              IDENTIFIED BY '{$setup_db_sugarsales_password}';";
 567  
 568                  if(!@mysqli_query($link, $query)) {
 569                      $errno = mysqli_errno($link);
 570                      $error = mysqli_error($link);
 571                  }
 572  
 573                  $query  = "SET PASSWORD FOR \"{$setup_db_sugarsales_user}\"@\"{$setup_site_host_name}\" = old_password('{$setup_db_sugarsales_password}');";
 574  
 575                  if(!@mysqli_query($link, $query)) {
 576                       $errno = mysqli_errno($link);
 577                       $error = mysqli_error($link);
 578                  }
 579  
 580                  if($setup_site_host_name != 'localhost') {
 581                      echo $mod_strings['LBL_PERFORM_CREATE_LOCALHOST'];
 582  
 583                      $host_name = getHostPortFromString($setup_db_host_name);
 584                      if(empty($host_name)){
 585                          $link   = @mysqli_connect($setup_db_host_name, $setup_db_admin_user_name, $setup_db_admin_password);
 586                      }else{
 587                          $link   = @mysqli_connect($host_name[0], $setup_db_admin_user_name, $setup_db_admin_password,null,$host_name[1]);
 588                      }
 589  
 590                      $query  = "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX
 591                                  ON `{$setup_db_database_name}`.*
 592                                  TO \"{$setup_db_sugarsales_user}\"@\"localhost\"
 593                                  IDENTIFIED BY '{$setup_db_sugarsales_password}';";
 594                      if(!@mysqli_query($link, $query)) {
 595                          $errno = mysqli_errno($link);
 596                          $error = mysqli_error($link);
 597                      }
 598  
 599                      $query = "SET PASSWORD FOR \"{$setup_db_sugarsales_user}\"@\"localhost\"\ = old_password('{$setup_db_sugarsales_password}');";
 600  
 601                      if(!@mysqli_query($link, $query)) {
 602                          $errno = mysqli_errno($link);
 603                          $error = mysqli_error($link);
 604                      }
 605                  } // end LOCALHOST
 606  
 607                  mysqli_close($link);
 608  
 609              }else{
 610                  $link   = @mysql_connect($setup_db_host_name, $setup_db_admin_user_name, $setup_db_admin_password);
 611                  $query  = "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX
 612                              ON `{$setup_db_database_name}`.*
 613                              TO \"{$setup_db_sugarsales_user}\"@\"{$setup_site_host_name}\"
 614                              IDENTIFIED BY '{$setup_db_sugarsales_password}';";
 615  
 616                  if(!@mysql_query($query, $link)) {
 617                      $errno = mysql_errno();
 618                      $error = mysql_error();
 619                  }
 620  
 621                  $query  = "SET PASSWORD FOR \"{$setup_db_sugarsales_user}\"@\"{$setup_site_host_name}\" = old_password('{$setup_db_sugarsales_password}');";
 622  
 623                  if(!@mysql_query($query, $link)) {
 624                       $errno = mysql_errno();
 625                       $error = mysql_error();
 626                  }
 627  
 628                  if($setup_site_host_name != 'localhost') {
 629                      echo $mod_strings['LBL_PERFORM_CREATE_LOCALHOST'];
 630  
 631                      $link   = @mysql_connect($setup_db_host_name, $setup_db_admin_user_name, $setup_db_admin_password);
 632                      $query  = "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX
 633                                  ON `{$setup_db_database_name}`.*
 634                                  TO \"{$setup_db_sugarsales_user}\"@\"localhost\"
 635                                  IDENTIFIED BY '{$setup_db_sugarsales_password}';";
 636                      if(!@mysql_query($query, $link)) {
 637                          $errno = mysql_errno();
 638                          $error = mysql_error();
 639                      }
 640  
 641                      $query = "SET PASSWORD FOR \"{$setup_db_sugarsales_user}\"@\"localhost\"\ = old_password('{$setup_db_sugarsales_password}');";
 642  
 643                      if(!@mysql_query($query, $link)) {
 644                          $errno = mysql_errno();
 645                          $error = mysql_error();
 646                      }
 647                  } // end LOCALHOST
 648  
 649                  mysql_close($link);
 650  
 651              }
 652          break;
 653  
 654          case 'mssql':
 655          $setup_db_host_instance = trim($setup_db_host_instance);
 656  
 657          $connect_host = "";
 658          if (empty($setup_db_host_instance)){
 659              $connect_host = $setup_db_host_name ;
 660          }else{
 661              $connect_host = $setup_db_host_name . "\\" . $setup_db_host_instance;
 662          }
 663          if(isset($_SESSION['mssql_type'])){
 664              $link = sqlsrv_connect($connect_host , array( 'UID' => $setup_db_admin_user_name, 'PWD' => $setup_db_admin_password));
 665              $query = "USE " . $setup_db_database_name . ";";
 666              @sqlsrv_query($link,$query);
 667  
 668              $query = "CREATE LOGIN $setup_db_sugarsales_user WITH PASSWORD = '$setup_db_sugarsales_password'";
 669              if(!sqlsrv_query($link,$query)) {
 670                  $errno = 9999;
 671                  displayMssqlErrors('mssqlsrv', $query);
 672                  break;
 673              }
 674  
 675              $query = "CREATE USER $setup_db_sugarsales_user  FOR LOGIN $setup_db_sugarsales_user ";
 676              if(!sqlsrv_query($link,$query)) {
 677                  $errno = 9999;
 678                  displayMssqlErrors('mssqlsrv', $query);
 679                  break;
 680              }
 681  
 682              $query = "EXEC sp_addRoleMember 'db_ddladmin ', '$setup_db_sugarsales_user'";
 683              if(!sqlsrv_query($link,$query)) {
 684                  $errno = 9999;
 685                  displayMssqlErrors('mssqlsrv', $query);
 686                  break;
 687              }
 688  
 689              $query = "EXEC sp_addRoleMember 'db_datareader','$setup_db_sugarsales_user'";
 690              if(!sqlsrv_query($link,$query)) {
 691                  $errno = 9999;
 692                  displayMssqlErrors('mssqlsrv', $query);
 693                  break;
 694              }
 695  
 696              $query = "EXEC sp_addRoleMember 'db_datawriter','$setup_db_sugarsales_user'";
 697              if(!sqlsrv_query($link,$query)) {
 698                  $errno = 9999;
 699                  displayMssqlErrors('mssqlsrv', $query);
 700                  break;
 701              }
 702          }
 703          else {
 704              $link = mssql_connect($connect_host , $setup_db_admin_user_name, $setup_db_admin_password);
 705              $query = "USE " . $setup_db_database_name . ";";
 706              @mssql_query($query);
 707  
 708              $query = "CREATE LOGIN $setup_db_sugarsales_user WITH PASSWORD = '$setup_db_sugarsales_password'";
 709              if(!@mssql_query($query)) {
 710                  $errno = 9999;
 711                  $error = "Error Adding Login. SQL Query: $query";
 712                  displayMssqlErrors('mssql', $query);
 713                  break;
 714              }
 715  
 716              $query = "CREATE USER $setup_db_sugarsales_user  FOR LOGIN $setup_db_sugarsales_user ";
 717              if(!@mssql_query($query)) {
 718                  $errno = 9999;
 719                  $error = "Error Granting Access. SQL Query: $query";
 720                  displayMssqlErrors('mssql', $query);
 721                  break;
 722              }
 723  
 724              $query = "EXEC sp_addRoleMember 'db_ddladmin ', '$setup_db_sugarsales_user'";
 725              if(!@mssql_query($query)) {
 726                  $errno = 9999;
 727                  $error = "Error Adding Role db_owner. SQL Query: $query";
 728                  displayMssqlErrors('mssql', $query);
 729                  break;
 730              }
 731  
 732              $query = "EXEC sp_addRoleMember 'db_datareader','$setup_db_sugarsales_user'";
 733              if(!@mssql_query($query)) {
 734                  $errno = 9999;
 735                  $error = "Error Adding Role db_datareader. SQL Query: $query";
 736                  displayMssqlErrors('mssql', $query);
 737                  break;
 738              }
 739  
 740              $query = "EXEC sp_addRoleMember 'db_datawriter','$setup_db_sugarsales_user'";
 741              if(!@mssql_query($query)) {
 742                  $errno = 9999;
 743                  $error = "Error Adding Role db_datawriter. SQL Query: $query";
 744                  displayMssqlErrors('mssql', $query);
 745                  break;
 746              }
 747          }
 748          break;
 749      } // end switch()
 750      if($errno == '')
 751      echo $mod_strings['LBL_PERFORM_DONE'];
 752  }
 753  
 754  function displayMssqlErrors($driver_type, $query) {
 755      global $sugar_config;
 756      if($driver_type =='mssqlsrv' && ($errors = sqlsrv_errors(SQLSRV_ERR_ALL) ) != null)
 757      {         
 758         foreach( $errors as $error)
 759         {
 760          
 761            echo "<div style='color:red;'>";
 762            echo "An error occured when performing the folloing query:<br>";
 763            echo "$query<br>";
 764            echo "</div>";    
 765            installLog("An error occured when performing the query:".$query." SQLSTATE: ".$error[ 'SQLSTATE']." message: ".$error[ 'message']);    
 766         }
 767      }
 768      if($driver_type =='mssql')
 769      {         
 770            echo "<div style='color:red;'>";
 771            echo "An error occured when performing the folloing query:<br>";
 772            echo "$query<br>";
 773            echo "</div>";    
 774            installLog("An error occured when performing the query:".$query." message: ".mssql_get_last_message());    
 775      }
 776  }
 777  /**
 778   * ensures that the charset and collation for a given database is set
 779   * MYSQL ONLY
 780   */
 781  function handleDbCharsetCollation() {
 782      global $mod_strings;
 783      global $setup_db_database_name;
 784      global $setup_db_host_name;
 785      global $setup_db_admin_user_name;
 786      global $setup_db_admin_password;
 787      global $sugar_config;
 788  
 789      if($_SESSION['setup_db_type'] == 'mysql') {
 790          if(isset($_SESSION['mysql_type'])){
 791             $host_name = getHostPortFromString($setup_db_host_name);
 792              if(empty($host_name)){
 793                  $link = @mysqli_connect($setup_db_host_name, $setup_db_admin_user_name, $setup_db_admin_password);
 794                      
 795              }else{
 796                      $link   = @mysqli_connect($host_name[0], $setup_db_admin_user_name, $setup_db_admin_password,null,$host_name[1]);
 797              }
 798                  
 799              $q1 = "ALTER DATABASE `{$setup_db_database_name}` DEFAULT CHARACTER SET utf8";
 800              $q2 = "ALTER DATABASE `{$setup_db_database_name}` DEFAULT COLLATE utf8_general_ci";
 801              @mysqli_query($link, $q1);
 802              @mysqli_query($link, $q2);
 803  
 804          }else{
 805              $link = @mysql_connect($setup_db_host_name, $setup_db_admin_user_name, $setup_db_admin_password);
 806              $q1 = "ALTER DATABASE `{$setup_db_database_name}` DEFAULT CHARACTER SET utf8";
 807              $q2 = "ALTER DATABASE `{$setup_db_database_name}` DEFAULT COLLATE utf8_general_ci";
 808              @mysql_query($q1, $link);
 809              @mysql_query($q2, $link);
 810          }
 811      }
 812  }
 813  
 814  
 815  /**
 816   * creates the new database
 817   */
 818  function handleDbCreateDatabase() {
 819      global $mod_strings;
 820      global $setup_db_database_name;
 821      global $setup_db_host_name;
 822      global $setup_db_host_instance;
 823      global $setup_db_admin_user_name;
 824      global $setup_db_admin_password;
 825      global $sugar_config;
 826  
 827      echo "{$mod_strings['LBL_PERFORM_CREATE_DB_1']} {$setup_db_database_name} {$mod_strings['LBL_PERFORM_CREATE_DB_2']} {$setup_db_host_name}...";
 828  
 829      switch($_SESSION['setup_db_type']) {
 830          case 'mysql':
 831              if(isset($_SESSION['mysql_type'])){
 832                  $host_name = getHostPortFromString($setup_db_host_name);
 833                  if(empty($host_name)){
 834                      $link = @mysqli_connect($setup_db_host_name, $setup_db_admin_user_name, $setup_db_admin_password);
 835                  }else{                
 836                      $link   = @mysqli_connect($host_name[0], $setup_db_admin_user_name, $setup_db_admin_password,null,$host_name[1]);                    
 837                  }
 838                  $drop = 'DROP DATABASE IF EXISTS '.$setup_db_database_name;
 839                  @mysqli_query($link, $drop);
 840  
 841                  $query = 'CREATE DATABASE `' . $setup_db_database_name . '` CHARACTER SET utf8 COLLATE utf8_general_ci';
 842                  @mysqli_query($link, $query);
 843                  mysqli_close($link);
 844  
 845              }else{
 846                  $link = @mysql_connect($setup_db_host_name, $setup_db_admin_user_name, $setup_db_admin_password);
 847                  $drop = 'DROP DATABASE IF EXISTS '.$setup_db_database_name;
 848                  @mysql_query($drop, $link);
 849  
 850                  $query = 'CREATE DATABASE `' . $setup_db_database_name . '` CHARACTER SET utf8 COLLATE utf8_general_ci';
 851                  @mysql_query($query, $link);
 852                  mysql_close($link);
 853  
 854              }
 855          break;
 856  
 857          case 'mssql':
 858          $connect_host = "";
 859          $setup_db_host_instance = trim($setup_db_host_instance);
 860          if (empty($setup_db_host_instance)){
 861              $connect_host = $setup_db_host_name ;
 862          }else{
 863              $connect_host = $setup_db_host_name . "\\" . $setup_db_host_instance;
 864          }
 865          if(isset($_SESSION['mssql_type'])){
 866              $link = sqlsrv_connect($connect_host , array( 'UID' => $setup_db_admin_user_name, 'PWD' => $setup_db_admin_password));
 867              $setup_db_database_name = str_replace(' ', '_', $setup_db_database_name);  // remove space
 868  
 869              //create check to see if this is existing db
 870              $check = "SELECT count(name) num FROM master..sysdatabases WHERE name = N'".$setup_db_database_name."'";
 871              $tableCntRes = sqlsrv_query($link,$check);
 872              $tableCnt= sqlsrv_fetch_array($tableCntRes);
 873  
 874              //if this db already exists, then drop it
 875              if($tableCnt[0]>0){
 876                  $drop = "DROP DATABASE $setup_db_database_name";
 877                 @ sqlsrv_query($link,$drop);
 878              }
 879  
 880              //create db
 881              $query = 'create database '.$setup_db_database_name;
 882              @sqlsrv_query($link,$query);
 883              @sqlsrv_close($link);
 884          }
 885          else {
 886              $link = @mssql_connect($connect_host, $setup_db_admin_user_name, $setup_db_admin_password);
 887              $setup_db_database_name = str_replace(' ', '_', $setup_db_database_name);  // remove space
 888  
 889              //create check to see if this is existing db
 890              $check = "SELECT count(name) num FROM master..sysdatabases WHERE name = N'".$setup_db_database_name."'";
 891              $tableCntRes = mssql_query($check);
 892              $tableCnt= mssql_fetch_row($tableCntRes);
 893  
 894              //if this db already exists, then drop it
 895              if($tableCnt[0]>0){
 896                  $drop = "DROP DATABASE $setup_db_database_name";
 897                 @ mssql_query($drop);
 898              }
 899  
 900              //create db
 901              $query = 'create database '.$setup_db_database_name;
 902              @mssql_query($query);
 903              @mssql_close($link);
 904          }
 905          break;
 906  
 907      }
 908      echo $mod_strings['LBL_PERFORM_DONE'];
 909  }
 910  
 911  
 912  /**
 913   * handles creation of Log4PHP properties file
 914   * This function has been deprecated.  Use SugarLogger.
 915   */
 916  function handleLog4Php() {
 917      return;
 918  /*    global $setup_site_log_dir;
 919      global $setup_site_log_file;
 920  
 921      if(is_writable("log4php.properties") && ($fh = @ sugar_fopen("log4php.properties", "r+"))) {
 922          $props = fread($fh, filesize("log4php.properties"));
 923          $props = preg_replace('/(log4php.appender.A2.File=).*\n/', "$1" . $setup_site_log_dir . "/" . $setup_site_log_file . "\n", $props);
 924          rewind( $fh );
 925          fwrite( $fh, $props );
 926          ftruncate( $fh, ftell($fh) );
 927          fclose( $fh );
 928      }
 929      */
 930  }
 931  
 932  function installLog($entry) {
 933      global $mod_strings;
 934      $nl = '
 935  '.gmdate("Y-m-d H:i:s").'...';
 936      $log = clean_path(getcwd().'/install.log');
 937  
 938      // create if not exists
 939      if(!file_exists($log)) {
 940          $fp = @sugar_fopen($log, 'w+'); // attempts to create file
 941          if(!is_resource($fp)) {
 942              $GLOBALS['log']->fatal('could not create the install.log file');
 943          }
 944      } else {
 945          $fp = @sugar_fopen($log, 'a+'); // write pointer at end of file
 946          if(!is_resource($fp)) {
 947              $GLOBALS['log']->fatal('could not open/lock install.log file');
 948          }
 949      }
 950  
 951  
 952  
 953      if(@fwrite($fp, $nl.$entry) === false) {
 954          $GLOBALS['log']->fatal('could not write to install.log: '.$entry);
 955      }
 956  
 957      if(is_resource($fp)) {
 958          fclose($fp);
 959      }
 960  }
 961  
 962  
 963  
 964  /**
 965   * takes session vars and creates config.php
 966   * @return array bottle collection of error messages
 967   */
 968  function handleSugarConfig() {
 969      global $bottle;
 970      global $cache_dir;
 971      global $mod_strings;
 972      global $setup_db_host_name;
 973      global $setup_db_host_instance;
 974      global $setup_db_sugarsales_user;
 975      global $setup_db_sugarsales_password;
 976      global $setup_db_database_name;
 977      global $setup_site_host_name;
 978      global $setup_site_log_dir;
 979      global $setup_site_log_file;
 980      global $setup_site_session_path;
 981      global $setup_site_guid;
 982      global $setup_site_url;
 983      global $setup_sugar_version;
 984      global $sugar_config;
 985      global $setup_site_log_level;
 986  
 987      echo "<b>{$mod_strings['LBL_PERFORM_CONFIG_PHP']} (config.php)</b><br>";
 988      ///////////////////////////////////////////////////////////////////////////////
 989      ////    $sugar_config SETTINGS
 990      if( is_file('config.php') ){
 991          $is_writable = is_writable('config.php');
 992          // require is needed here (config.php is sometimes require'd from install.php)
 993          require ('config.php');
 994      } else {
 995          $is_writable = is_writable('.');
 996      }
 997  
 998      // build default sugar_config and merge with new values
 999      $sugar_config = sugarArrayMerge(get_sugar_config_defaults(), $sugar_config);
1000      // always lock the installer
1001      $sugar_config['installer_locked'] = true;
1002      // we're setting these since the user was given a fair chance to change them
1003      $sugar_config['dbconfig']['db_host_name']       = $setup_db_host_name;
1004      $sugar_config['dbconfig']['db_host_instance']   = $setup_db_host_instance;
1005      $sugar_config['dbconfig']['db_user_name']       = $setup_db_sugarsales_user;
1006      $sugar_config['dbconfig']['db_password']        = $setup_db_sugarsales_password;
1007      $sugar_config['dbconfig']['db_name']            = $setup_db_database_name;
1008      $sugar_config['dbconfig']['db_type']            = $_SESSION['setup_db_type'];
1009      if(isset($_SESSION['setup_db_port_num'])){
1010          $sugar_config['dbconfig']['db_port'] = $_SESSION['setup_db_port_num'];
1011      }
1012      $sugar_config['cache_dir']                      = $cache_dir;
1013      $sugar_config['default_charset']                = $mod_strings['DEFAULT_CHARSET'];
1014      $sugar_config['default_email_client']           = 'sugar';
1015      $sugar_config['default_email_editor']           = 'html';
1016      $sugar_config['host_name']                      = $setup_site_host_name;
1017      $sugar_config['import_dir']                 = $cache_dir.'import/';
1018      $sugar_config['js_custom_version']              = '';
1019  
1020      $sugar_config['log_dir']                        = $setup_site_log_dir;
1021      $sugar_config['log_file']                       = $setup_site_log_file;
1022  
1023      /*nsingh(bug 22402): Consolidate logger settings under $config['logger'] as liked by the new logger! If log4pphp exists,
1024          these settings will be overwritten by those in log4php.properties when the user access admin->system settings.*/
1025      $sugar_config['logger']    =
1026          array ('level'=>$setup_site_log_level,
1027           'file' => array(
1028              'ext' => '.log',
1029              'name' => 'sugarcrm',
1030              'dateFormat' => '%c',
1031              'maxSize' => '10MB',
1032              'maxLogs' => 10,
1033              'suffix' => '%m_%Y'),
1034        );
1035      $sugar_config['session_dir']                    = $setup_site_session_path;
1036      $sugar_config['site_url']                       = $setup_site_url;
1037      $sugar_config['sugar_version']                  = $setup_sugar_version;
1038      $sugar_config['tmp_dir']                        = $cache_dir.'xml/';
1039      $sugar_config['upload_dir']                 = $cache_dir.'upload/';
1040      $sugar_config['use_php_code_json']              = returnPhpJsonStatus(); // true on error
1041      if( isset($_SESSION['setup_site_sugarbeet_anonymous_stats']) ){
1042          $sugar_config['sugarbeet']      = $_SESSION['setup_site_sugarbeet_anonymous_stats'];
1043      }
1044      $sugar_config['demoData'] = $_SESSION['demoData'];
1045      if( isset( $sugar_config['unique_key'] ) ){
1046          $sugar_config['unique_key'] = $setup_site_guid;
1047      }
1048      if(empty($sugar_config['unique_key'])){
1049          $sugar_config['unique_key'] = md5( create_guid() );
1050      }
1051      // add installed langs to config
1052      // entry in upgrade_history comes AFTER table creation
1053      if(isset($_SESSION['INSTALLED_LANG_PACKS']) && is_array($_SESSION['INSTALLED_LANG_PACKS']) && !empty($_SESSION['INSTALLED_LANG_PACKS'])) {
1054          foreach($_SESSION['INSTALLED_LANG_PACKS'] as $langZip) {
1055              $lang = getSugarConfigLanguageArray($langZip);
1056              if(!empty($lang)) {
1057                  $exLang = explode('::', $lang);
1058                  if(is_array($exLang) && count($exLang) == 3) {
1059                      $sugar_config['languages'][$exLang[0]] = $exLang[1];
1060                  }
1061              }
1062          }
1063      }
1064      // handle localization defaults
1065      $sugar_config['default_date_format'] = $_SESSION["default_date_format"];
1066      $sugar_config['default_time_format'] = $_SESSION["default_time_format"];
1067      $sugar_config['default_language'] = $_SESSION["default_language"];
1068      $sugar_config['default_locale_name_format'] = $_SESSION["default_locale_name_format"];
1069      $sugar_config['default_email_charset'] = $_SESSION["default_email_charset"];
1070      $sugar_config['default_export_charset'] = $_SESSION["default_export_charset"];
1071      $sugar_config['export_delimiter'] = $_SESSION["export_delimiter"];
1072      $sugar_config['default_currency_name'] = $_SESSION["default_currency_name"];
1073      $sugar_config['default_currency_symbol'] = $_SESSION["default_currency_symbol"];
1074      $sugar_config['default_currency_iso4217'] = $_SESSION["default_currency_iso4217"];
1075      $sugar_config['default_currency_significant_digits'] = $_SESSION["default_currency_significant_digits"];
1076      $sugar_config['default_number_grouping_seperator'] = $_SESSION["default_number_grouping_seperator"];
1077      $sugar_config['default_decimal_seperator'] = $_SESSION["default_decimal_seperator"];
1078  
1079      ksort($sugar_config);
1080      $sugar_config_string = "<?php\n" .
1081          '// created: ' . date('Y-m-d H:i:s') . "\n" .
1082          '$sugar_config = ' .
1083          var_export($sugar_config, true) .
1084          ";\n?>\n";
1085      if($is_writable && write_array_to_file( "sugar_config", $sugar_config, "config.php")) {
1086          // was 'Done'
1087      } else {
1088          echo 'failed<br>';
1089          echo "<p>{$mod_strings['ERR_PERFORM_CONFIG_PHP_1']}</p>\n";
1090          echo "<p>{$mod_strings['ERR_PERFORM_CONFIG_PHP_2']}</p>\n";
1091          echo "<TEXTAREA  rows=\"15\" cols=\"80\">".$sugar_config_string."</TEXTAREA>";
1092          echo "<p>{$mod_strings['ERR_PERFORM_CONFIG_PHP_3']}</p>";
1093  
1094          $bottle[] = $mod_strings['ERR_PERFORM_CONFIG_PHP_4'];
1095      }
1096  
1097      ////    END $sugar_config
1098      ///////////////////////////////////////////////////////////////////////////////
1099      return $bottle;
1100  }
1101  /**
1102   * (re)write the .htaccess file to prevent browser access to the log file
1103   */
1104  function handleHtaccess(){
1105  global $mod_strings;
1106  $ignoreCase = (substr_count(strtolower($_SERVER['SERVER_SOFTWARE']), 'apache/2') > 0)?'(?i)':'';
1107  $htaccess_file   = getcwd() . "/.htaccess";    
1108  $contents = '';
1109  $restrict_str = <<<EOQ
1110  
1111  # BEGIN SUGARCRM RESTRICTIONS    
1112  RedirectMatch 403 {$ignoreCase}.*\.log$
1113  RedirectMatch 403 {$ignoreCase}/+not_imported_.*\.txt
1114  RedirectMatch 403 {$ignoreCase}/+(soap|cache|xtemplate|data|examples|include|log4php|metadata|modules)/+.*\.(php|tpl)
1115  RedirectMatch 403 {$ignoreCase}/+emailmandelivery\.php
1116  RedirectMatch 403 {$ignoreCase}/+cache/+upload
1117  RedirectMatch 403 {$ignoreCase}/+files\.md5$
1118  # END SUGARCRM RESTRICTIONS
1119  EOQ;
1120      if(file_exists($htaccess_file)){
1121           $fp = fopen($htaccess_file, 'r');
1122           $skip = false;
1123           while($line = fgets($fp)){
1124  
1125               if(preg_match("/\s*#\s*BEGIN\s*SUGARCRM\s*RESTRICTIONS/i", $line))$skip = true;
1126               if(!$skip)$contents .= $line;
1127               if(preg_match("/\s*#\s*END\s*SUGARCRM\s*RESTRICTIONS/i", $line))$skip = false;
1128           }
1129      }
1130      $status =  file_put_contents($htaccess_file, $contents . $restrict_str);    
1131      if( !$status ) {
1132          echo "<p>{$mod_strings['ERR_PERFORM_HTACCESS_1']}<span class=stop>{$htaccess_file}</span> {$mod_strings['ERR_PERFORM_HTACCESS_2']}</p>\n";
1133          echo "<p>{$mod_strings['ERR_PERFORM_HTACCESS_3']}</p>\n";
1134          echo $restrict_str;
1135      }
1136      return $status;
1137  }
1138  
1139  /**
1140   * (re)write the web.config file to prevent browser access to the log file
1141   */
1142  function handleWebConfig() {
1143      global $setup_site_log_dir;
1144      global $setup_site_log_file;
1145      require_once ('include/domit/xml_domit_include.php');
1146          
1147      $prefix = $setup_site_log_dir.empty($setup_site_log_dir)?'':'/';
1148      
1149      $config_array = array(
1150      array('1'=> $prefix.str_replace('.','\\.',$setup_site_log_file).'\\.*' ,'2'=>'log_file_restricted.html'),
1151      array('1'=> $prefix.'install.log' ,'2'=>'log_file_restricted.html'),
1152      array('1'=> $prefix.'upgradeWizard.log' ,'2'=>'log_file_restricted.html'),
1153      array('1'=> $prefix.'emailman.log' ,'2'=>'log_file_restricted.html'),
1154      array('1'=>'not_imported_.*.txt' ,'2'=>'log_file_restricted.html'),
1155      array('1'=>'XTemplate/(.*)/(.*).php' ,'2'=>'index.php'),
1156      array('1'=>'data/(.*).php' ,'2'=>'index.php'),
1157      array('1'=>'examples/(.*).php' ,'2'=>'index.php'),
1158      array('1'=>'include/(.*).php' ,'2'=>'index.php'),
1159      array('1'=>'include/(.*)/(.*).php' ,'2'=>'index.php'),
1160      array('1'=>'log4php/(.*).php' ,'2'=>'index.php'),
1161      array('1'=>'log4php/(.*)/(.*)' ,'2'=>'index.php'),
1162      array('1'=>'metadata/(.*)/(.*).php' ,'2'=>'index.php'),
1163      array('1'=>'modules/(.*)/(.*).php' ,'2'=>'index.php'),
1164      array('1'=>'soap/(.*).php' ,'2'=>'index.php'),
1165      array('1'=>'emailmandelivery.php' ,'2'=>'index.php'),
1166      array('1'=>'cron.php' ,'2'=>'index.php'),
1167      );      
1168      
1169          
1170      $xmldoc = new DOMIT_Document(); 
1171  
1172  //create XML declaration
1173      $xmlDecl = $xmldoc->createProcessingInstruction('xml', 'version="1.0" encoding="UTF-8"');
1174      $xmldoc->appendChild($xmlDecl);
1175      $rootElement = $xmldoc->createElement('configuration');
1176      $xmldoc->appendChild($rootElement);
1177      
1178      $system_webserver = $xmldoc->createElement('system.webServer');   
1179      $rewrite = $xmldoc->createElement('rewrite');
1180      $rules = $xmldoc->createElement('rules');
1181      for($i=0; $i<count($config_array); $i++) {
1182          $rule[$i] = $xmldoc->createElement('rule');
1183          $rule[$i]->setAttribute('name', $i);
1184          $rule[$i]->setAttribute('stopProcessing', 'true');
1185          $match[$i] =  $xmldoc->createElement('match');
1186          $match[$i]->setAttribute('url', $config_array[$i]['1']);   
1187              $rule[$i]->appendChild($match[$i]);  
1188          $action[$i] =  $xmldoc->createElement('action');
1189          $action[$i]->setAttribute('type', 'Redirect');
1190          $action[$i]->setAttribute('url', $config_array[$i]['2']);
1191              $rule[$i]->appendChild($action[$i]);  
1192          $rules->appendChild($rule[$i]);   
1193      }
1194      $rewrite->appendChild($rules);    
1195      $system_webserver->appendChild($rewrite);
1196      $rootElement->appendChild($system_webserver);
1197      
1198  //    echo $xmldoc->documentElement->toNormalizedString(true);
1199      
1200      $xmldoc->saveXML('web.config', true);
1201  }
1202  
1203  /**
1204   * Drop old tables if table exists and told to drop it
1205   */
1206  function drop_table_install( &$focus ){
1207      global $db;
1208      global $dictionary;
1209  
1210      $result = $db->tableExists($focus->table_name);
1211  
1212      if( $result ){
1213          $focus->drop_tables();
1214          $GLOBALS['log']->info("Dropped old ".$focus->table_name." table.");
1215          return 1;
1216      }
1217      else {
1218          $GLOBALS['log']->info("Did not need to drop old ".$focus->table_name." table.  It doesn't exist.");
1219          return 0;
1220      }
1221  }
1222  
1223  // Creating new tables if they don't exist.
1224  function create_table_if_not_exist( &$focus ){
1225      global  $db;
1226      $table_created = false;
1227  
1228      // normal code follows
1229      $result = $db->tableExists($focus->table_name);
1230      if($result){
1231          $GLOBALS['log']->info("Table ".$focus->table_name." already exists.");
1232      } else {
1233          $focus->create_tables();
1234          $GLOBALS['log']->info("Created ".$focus->table_name." table.");
1235          $table_created = true;
1236      }
1237      return $table_created;
1238  }
1239  
1240  
1241  
1242  function create_default_users(){
1243      global $db;
1244      global $setup_site_admin_password;
1245      global $create_default_user;
1246      global $sugar_config;
1247  
1248      //Create default admin user
1249      $user = new User();
1250      $user->id = 1;
1251      $user->new_with_id = true;
1252      $user->last_name = 'Administrator';
1253      $user->user_name = 'admin';
1254      $user->title = "Administrator";
1255      $user->status = 'Active';
1256      $user->is_admin = true;
1257      $user->employee_status = 'Active';
1258      //$user->user_password = $user->encrypt_password($setup_site_admin_password);
1259      $user->user_hash = strtolower(md5($setup_site_admin_password));
1260      $user->email = '';
1261      $user->save();
1262  
1263      // echo 'Creating RSS Feeds';
1264      $feed = new Feed();
1265      $feed->createRSSHomePage($user->id);
1266  
1267  
1268      // We need to change the admin user to a fixed id of 1.
1269      // $query = "update users set id='1' where user_name='$user->user_name'";
1270      // $result = $db->query($query, true, "Error updating admin user ID: ");
1271  
1272      $GLOBALS['log']->info("Created ".$user->table_name." table. for user $user->id");
1273  
1274      if( $create_default_user ){
1275          $default_user = new User();
1276          $default_user->last_name = $sugar_config['default_user_name'];
1277          $default_user->user_name = $sugar_config['default_user_name'];
1278          $default_user->status = 'Active';
1279          if( isset($sugar_config['default_user_is_admin']) && $sugar_config['default_user_is_admin'] ){
1280              $default_user->is_admin = true;
1281          }
1282          //$default_user->user_password = $default_user->encrypt_password($sugar_config['default_password']);
1283          $default_user->user_hash = strtolower(md5($sugar_config['default_password']));
1284          $default_user->save();
1285          $feed->createRSSHomePage($user->id);
1286      }
1287  }
1288  
1289  function set_admin_password( $password ) {
1290      global $db;
1291  
1292      $user = new User();
1293      $encrypted_password = $user->encrypt_password($password);
1294      $user_hash = strtolower(md5($password));
1295  
1296      //$query = "update users set user_password='$encrypted_password', user_hash='$user_hash' where id='1'";
1297      $query = "update users set user_hash='$user_hash' where id='1'";
1298  
1299      $db->query($query);
1300  }
1301  
1302  function insert_default_settings(){
1303      global $db;
1304      global $setup_sugar_version;
1305      global $sugar_db_version;
1306  
1307  
1308      $db->query("INSERT INTO config (category, name, value) VALUES ('notify', 'fromaddress', 'do_not_reply@example.com')");
1309      $db->query("INSERT INTO config (category, name, value) VALUES ('notify', 'fromname', 'SugarCRM')");
1310      $db->query("INSERT INTO config (category, name, value) VALUES ('notify', 'send_by_default', '1')");
1311      $db->query("INSERT INTO config (category, name, value) VALUES ('notify', 'on', '0')");
1312      $db->query("INSERT INTO config (category, name, value) VALUES ('notify', 'send_from_assigning_user', '0')");
1313      /* cn: moved to OutboundEmail class
1314      $db->query("INSERT INTO config (category, name, value) VALUES ('mail', 'smtpserver', 'localhost')");
1315      $db->query("INSERT INTO config (category, name, value) VALUES ('mail', 'smtpport', '25')");
1316      $db->query("INSERT INTO config (category, name, value) VALUES ('mail', 'sendtype', 'sendmail')");
1317      $db->query("INSERT INTO config (category, name, value) VALUES ('mail', 'smtpuser', '')");
1318      $db->query("INSERT INTO config (category, name, value) VALUES ('mail', 'smtppass', '')");
1319      $db->query("INSERT INTO config (category, name, value) VALUES ('mail', 'smtpauth_req', '0')");
1320      */
1321      $db->query("INSERT INTO config (category, name, value) VALUES ('info', 'sugar_version', '" . $sugar_db_version . "')");
1322      $db->query("INSERT INTO config (category, name, value) VALUES ('MySettings', 'tab', '')");
1323      $db->query("INSERT INTO config (category, name, value) VALUES ('portal', 'on', '0')");
1324  
1325  
1326  
1327      
1328      //insert default tracker settings    
1329      $db->query("INSERT INTO config (category, name, value) VALUES ('tracker', 'Tracker', '1')");
1330      
1331  
1332  
1333  
1334  
1335  
1336  
1337  
1338  
1339  
1340  
1341  
1342  
1343  
1344  
1345  
1346  
1347  
1348  }
1349  
1350  
1351  
1352  
1353  
1354  
1355  
1356  
1357  // Returns true if the given file/dir has been made writable (or is already
1358  // writable).
1359  function make_writable($file)
1360  {
1361  
1362  
1363  
1364  
1365  
1366  
1367  
1368  
1369      $ret_val = false;
1370      if(is_file($file) || is_dir($file))
1371      {
1372          if(is_writable($file))
1373          {
1374              $ret_val = true;
1375          }
1376          else
1377          {
1378              $original_fileperms = fileperms($file);
1379  
1380              // add user writable permission
1381              $new_fileperms = $original_fileperms | 0x0080;
1382              @sugar_chmod($file, $new_fileperms);
1383  
1384              if(is_writable($file))
1385              {
1386                  $ret_val = true;
1387              }
1388              else
1389              {
1390                  // add group writable permission
1391                  $new_fileperms = $original_fileperms | 0x0010;
1392                  @chmod($file, $new_fileperms);
1393  
1394                  if(is_writable($file))
1395                  {
1396                      $ret_val = true;
1397                  }
1398                  else
1399                  {
1400                      // add world writable permission
1401                      $new_fileperms = $original_fileperms | 0x0002;
1402                      @chmod($file, $new_fileperms);
1403  
1404                      if(is_writable($file))
1405                      {
1406                          $ret_val = true;
1407                      }
1408                  }
1409              }
1410          }
1411      }
1412  
1413      return $ret_val;
1414  }
1415  
1416  
1417  
1418  
1419  
1420  
1421  
1422  
1423  
1424  
1425  
1426  
1427  function recursive_make_writable($start_file)
1428      {
1429      $ret_val = make_writable($start_file);
1430  
1431      if($ret_val && is_dir($start_file))
1432      {
1433          // PHP 4 alternative to scandir()
1434          $files = array();
1435          $dh = opendir($start_file);
1436          $filename = readdir($dh);
1437          while(!empty($filename))
1438          {
1439              if($filename != '.' && $filename != '..' && $filename != '.svn')
1440              {
1441                  $files[] = $filename;
1442              }
1443  
1444              $filename = readdir($dh);
1445          }
1446  
1447          foreach($files as $file)
1448          {
1449              $ret_val = recursive_make_writable($start_file . '/' . $file);
1450  
1451              if(!$ret_val)
1452              {
1453                  $_SESSION['unwriteable_module_files'][dirname($file)] = dirname($file);
1454                  $fnl_ret_val = false;
1455                  //break;
1456              }
1457          }
1458      }
1459              if(!$ret_val)
1460              {
1461                  $unwriteable_directory = is_dir($start_file) ? $start_file : dirname($start_file);
1462                  if($unwriteable_directory[0] == '.'){$unwriteable_directory = substr($unwriteable_directory,1);}
1463                  $_SESSION['unwriteable_module_files'][$unwriteable_directory] = $unwriteable_directory;
1464                  $_SESSION['unwriteable_module_files']['failed'] = true;
1465              }
1466  
1467      return $ret_val;
1468  }
1469  
1470  
1471  
1472  
1473  
1474  
1475  function recursive_is_writable($start_file)
1476  {
1477      $ret_val = is_writable($start_file);
1478  
1479      if($ret_val && is_dir($start_file))
1480      {
1481          // PHP 4 alternative to scandir()
1482          $files = array();
1483          $dh = opendir($start_file);
1484          $filename = readdir($dh);
1485          while(!empty($filename))
1486          {
1487              if($filename != '.' && $filename != '..' && $filename != '.svn')
1488              {
1489                  $files[] = $filename;
1490              }
1491  
1492              $filename = readdir($dh);
1493          }
1494  
1495          foreach($files as $file)
1496          {
1497              $ret_val = recursive_is_writable($start_file . '/' . $file);
1498  
1499              if(!$ret_val)
1500              {
1501                  break;
1502              }
1503          }
1504      }
1505  
1506      return $ret_val;
1507  }
1508  
1509  
1510  
1511  
1512  function getMysqlVersion($link) {
1513      if($link) {
1514          if(isset($_SESSION['mysql_type'])){
1515              $version = mysqli_get_server_info($link);
1516          }else{
1517              if(is_resource($link)) {
1518                  $version = mysql_get_server_info($link);
1519              }
1520          }
1521          return preg_replace('/[A-Za-z\-]/','',$version);
1522      }
1523      return 0;
1524  }
1525  
1526  
1527  
1528  
1529  // one place for form validation/conversion to boolean
1530  function get_boolean_from_request( $field ){
1531      if( !isset($_REQUEST[$field]) ){
1532          return( false );
1533      }
1534  
1535      if( ($_REQUEST[$field] == 'on') || ($_REQUEST[$field] == 'yes') ){
1536          return(true);
1537      }
1538      else {
1539          return(false);
1540      }
1541  }
1542  
1543  function stripslashes_checkstrings($value){
1544     if(is_string($value)){
1545        return stripslashes($value);
1546     }
1547     return $value;
1548  }
1549  
1550  
1551  function print_debug_array( $name, $debug_array ){
1552      ksort( $debug_array );
1553  
1554      print( "$name vars:\n" );
1555      print( "(\n" );
1556  
1557      foreach( $debug_array as $key => $value ){
1558          if( stristr( $key, "password" ) ){
1559              $value = "WAS SET";
1560          }
1561          print( "    [$key] => $value\n" );
1562      }
1563  
1564      print( ")\n" );
1565  }
1566  
1567  function print_debug_comment(){
1568      if( !empty($_REQUEST['debug']) ){
1569          $_SESSION['debug'] = $_REQUEST['debug'];
1570      }
1571  
1572      if( !empty($_SESSION['debug']) && ($_SESSION['debug'] == 'true') ){
1573          print( "<!-- debug is on (to turn off, hit any page with 'debug=false' as a URL parameter.\n" );
1574  
1575          print_debug_array( "Session",   $_SESSION );
1576          print_debug_array( "Request",   $_REQUEST );
1577          print_debug_array( "Post",      $_POST );
1578          print_debug_array( "Get",       $_GET );
1579  
1580          print_r( "-->\n" );
1581      }
1582  }
1583  
1584  function validate_systemOptions() {
1585      global $mod_strings;
1586      $errors = array();
1587      switch( $_SESSION['setup_db_type'] ){
1588          case "mysql":
1589          case "mssql":
1590          case "oci8":
1591              break;
1592          default:
1593              $errors[] = "<span class='error'>".$mod_strings['ERR_DB_INVALID']."</span>";
1594              break;
1595      }
1596      return $errors;
1597  }
1598  
1599  
1600  function validate_localization() {
1601      global $mod_strings;
1602  
1603      $errors = array();
1604  
1605      foreach($_REQUEST as $k => $v) {
1606          if($v == "'") {
1607              $errors[] = "<span class='error'>{$mod_strings['ERR_NO_SINGLE_QUOTE']}{$k}</span>";
1608          }
1609      }
1610      return $errors;
1611  }
1612  
1613  
1614  function validate_dbConfig() {
1615      global $mod_strings;
1616      require_once ('install/checkDBSettings.php');
1617      return checkDBSettings(true);
1618  
1619  }
1620  
1621  function validate_siteConfig($type){
1622      global $mod_strings;
1623     $errors = array();
1624  
1625     if($type=='a'){
1626         if(empty($_SESSION['setup_system_name'])){
1627              $errors[] = "<span class='error'>".$mod_strings['LBL_REQUIRED_SYSTEM_NAME']."</span>";
1628         }
1629         if($_SESSION['setup_site_url'] == ''){
1630            $errors[] = "<span class='error'>".$mod_strings['ERR_URL_BLANK']."</span>";
1631         }
1632  
1633         if($_SESSION['setup_site_admin_password'] == ''){
1634            $errors[] = "<span class='error'>".$mod_strings['ERR_ADMIN_PASS_BLANK']."</span>";
1635         }
1636  
1637         if($_SESSION['setup_site_admin_password'] != $_SESSION['setup_site_admin_password_retype']){
1638            $errors[] = "<span class='error'>".$mod_strings['ERR_PASSWORD_MISMATCH']."</span>";
1639         }
1640     }else{
1641         if(!empty($_SESSION['setup_site_custom_session_path']) && $_SESSION['setup_site_session_path'] == ''){
1642            $errors[] = "<span class='error'>".$mod_strings['ERR_SESSION_PATH']."</span>";
1643         }
1644  
1645         if(!empty($_SESSION['setup_site_custom_session_path']) && $_SESSION['setup_site_session_path'] != ''){
1646            if(is_dir($_SESSION['setup_site_session_path'])){
1647               if(!is_writable($_SESSION['setup_site_session_path'])){
1648                  $errors[] = "<span class='error'>".$mod_strings['ERR_SESSION_DIRECTORY']."</span>";
1649               }
1650            }
1651            else {
1652               $errors[] = "<span class='error'>".$mod_strings['ERR_SESSION_DIRECTORY_NOT_EXISTS']."</span>";
1653            }
1654         }
1655  
1656         if(!empty($_SESSION['setup_site_custom_log_dir']) && $_SESSION['setup_site_log_dir'] == ''){
1657            $errors[] = "<span class='error'>".$mod_strings['ERR_LOG_DIRECTORY_NOT_EXISTS']."</span>";
1658         }
1659  
1660         if(!empty($_SESSION['setup_site_custom_log_dir']) && $_SESSION['setup_site_log_dir'] != ''){
1661            if(is_dir($_SESSION['setup_site_log_dir'])){
1662               if(!is_writable($_SESSION['setup_site_log_dir'])) {
1663                  $errors[] = "<span class='error'>".$mod_strings['ERR_LOG_DIRECTORY_NOT_WRITABLE']."</span>";
1664               }
1665            }
1666            else {
1667               $errors[] = "<span class='error'>".$mod_strings['ERR_LOG_DIRECTORY_NOT_EXISTS']."</span>";
1668            }
1669         }
1670  
1671         if(!empty($_SESSION['setup_site_specify_guid']) && $_SESSION['setup_site_guid'] == ''){
1672            $errors[] = "<span class='error'>".$mod_strings['ERR_SITE_GUID']."</span>";
1673         }
1674     }
1675  
1676     return $errors;
1677  }
1678  
1679  
1680  function pullSilentInstallVarsIntoSession() {
1681      global $mod_strings;
1682      global $sugar_config;
1683  
1684      
1685      if( file_exists('config_si.php') ){
1686          require_once('config_si.php');
1687      }
1688      else if( empty($sugar_config_si) ){
1689          die( $mod_strings['ERR_SI_NO_CONFIG'] );
1690      }
1691  
1692      $config_subset = array (
1693          'setup_site_url'                => isset($sugar_config['site_url']) ? $sugar_config['site_url'] : '',
1694          'setup_db_host_name'            => isset($sugar_config['dbconfig']['db_host_name']) ? $sugar_config['dbconfig']['db_host_name'] : '',
1695          'setup_db_sugarsales_user'      => isset($sugar_config['dbconfig']['db_user_name']) ? $sugar_config['dbconfig']['db_user_name'] : '',
1696          'setup_db_sugarsales_password'  => isset($sugar_config['dbconfig']['db_password']) ? $sugar_config['dbconfig']['db_password'] : '',
1697          'setup_db_database_name'        => isset($sugar_config['dbconfig']['db_name']) ? $sugar_config['dbconfig']['db_name'] : '',
1698          'setup_db_type'                 => isset($sugar_config['dbconfig']['db_type']) ? $sugar_config['dbconfig']['db_type'] : '',
1699      );
1700      // third array of values derived from above values
1701      $derived = array (
1702          'setup_site_admin_password_retype'      => $sugar_config_si['setup_site_admin_password'],
1703          'setup_db_sugarsales_password_retype'   => $config_subset['setup_db_sugarsales_password'],
1704  
1705  
1706  
1707      );
1708  
1709  
1710  
1711  
1712  
1713  
1714  
1715  
1716  
1717  
1718  
1719      $needles = array('setup_license_key_users','setup_license_key_expire_date','setup_license_key', 'setup_num_lic_oc',
1720                       'default_currency_iso4217', 'default_currency_name', 'default_currency_significant_digits',
1721                       'default_currency_symbol',  'default_date_format', 'default_time_format', 'default_decimal_seperator',
1722                       'default_export_charset', 'default_language', 'default_locale_name_format', 'default_number_grouping_seperator',
1723                       'export_delimiter');
1724      copyFromArray($sugar_config_si, $needles, $derived);
1725      $all_config_vars = array_merge( $config_subset, $sugar_config_si, $derived );
1726  
1727      // bug 16860 tyoung -  trim leading and trailing whitespace from license_key
1728      if (isset($all_config_vars['setup_license_key'])) {
1729          $all_config_vars['setup_license_key'] = trim($all_config_vars['setup_license_key']);
1730      }
1731  
1732      foreach( $all_config_vars as $key => $value ){
1733          $_SESSION[$key] = $value;
1734      }
1735  }
1736  
1737  /**
1738   * given an array it will check to determine if the key exists in the array, if so
1739   * it will addd to the return array
1740   *
1741   * @param intput_array haystack to check
1742   * @param needles list of needles to search for
1743   * @param output_array the array to add the keys to
1744   */
1745  function copyFromArray($input_array, $needles, $output_array){
1746      foreach($needles as $needle){
1747           if(isset($input_array[$needle])){
1748              $output_array[$needle]  = $input_array[$needle];
1749           }
1750      }
1751  }
1752  
1753  
1754  
1755  
1756  
1757  
1758  
1759  
1760  
1761  
1762  
1763  
1764  
1765  
1766  
1767  
1768  
1769  
1770  
1771  /**
1772   * handles language pack uploads - code based off of upload_file->final_move()
1773   * puts it into the cache/upload dir to be handed off to langPackUnpack();
1774   *
1775   * @param object file UploadFile object
1776   * @return bool true if successful
1777   */
1778  function langPackFinalMove($file) {
1779      global $sugar_config;
1780      //."upgrades/langpack/"
1781      $destination = $sugar_config['upload_dir'].$file->stored_file_name;
1782      if(!move_uploaded_file($_FILES[$file->field_name]['tmp_name'], $destination)) {
1783          die ("ERROR: can't move_uploaded_file to $destination. You should try making the directory writable by the webserver");
1784      }
1785      return true;
1786  }
1787  
1788  function getLicenseDisplay($type, $manifest, $zipFile, $next_step, $license_file, $clean_file) {
1789      return PackageManagerDisplay::getLicenseDisplay($license_file, 'install.php', $next_step, $zipFile, $type, $manifest, $clean_file);
1790  }
1791  
1792  
1793  /**
1794   * creates the remove/delete form for langpack page
1795   * @param string type commit/remove
1796   * @param string manifest path to manifest file
1797   * @param string zipFile path to uploaded zip file
1798   * @param int nextstep current step
1799   * @return string ret <form> for this package
1800   */
1801  function getPackButton($type, $manifest, $zipFile, $next_step, $uninstallable='Yes', $showButtons=true) {
1802      global $mod_strings;
1803  
1804      $button = $mod_strings['LBL_LANG_BUTTON_COMMIT'];
1805      if($type == 'remove') {
1806          $button = $mod_strings['LBL_LANG_BUTTON_REMOVE'];
1807      } elseif($type == 'uninstall') {
1808          $button = $mod_strings['LBL_LANG_BUTTON_UNINSTALL'];
1809      }
1810  
1811      $disabled = ($uninstallable == 'Yes') ? false : true;
1812  
1813      $ret = "<form name='delete{$zipFile}' action='install.php' method='POST'>
1814                  <input type='hidden' name='current_step' value='{$next_step}'>
1815                  <input type='hidden' name='goto' value='{$mod_strings['LBL_CHECKSYS_RECHECK']}'>
1816                  <input type='hidden' name='languagePackAction' value='{$type}'>
1817                  <input type='hidden' name='manifest' value='".urlencode($manifest)."'>
1818                  <input type='hidden' name='zipFile' value='".urlencode($zipFile)."'>
1819                  <input type='hidden' name='install_type' value='custom'>";
1820      if(!$disabled && $showButtons) {
1821          $ret .= "<input type='submit' value='{$button}' class='button'>";
1822      }
1823      $ret .= "</form>";
1824      return $ret;
1825  }
1826  
1827  /**
1828   * finds all installed languages and returns an array with the names
1829   * @return array langs array of installed languages
1830   */
1831  function getInstalledLanguages() {
1832      $langDir = 'include/language/';
1833      $dh = opendir($langDir);
1834  
1835      $langs = array();
1836      while($file = readdir($dh)) {
1837          if(substr($file, -3) == 'php') {
1838  
1839          }
1840      }
1841  }
1842  
1843  
1844  
1845  /**
1846   * searches upgrade dir for lang pack files.
1847   *
1848   * @return string HTML of available lang packs
1849   */
1850  function getLangPacks($display_commit = true, $types = array('langpack'), $notice_text = '') {
1851      global $mod_strings;
1852      global $next_step;
1853      global $base_upgrade_dir;
1854  
1855      if(empty($notice_text)){
1856          $notice_text =  $mod_strings['LBL_LANG_PACK_READY'];
1857      }
1858      $ret = "<tr><td colspan=7 align=left>{$notice_text}</td></tr>";
1859      //$ret .="<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
1860      $ret .= "<tr>
1861                  <td width='20%' ><b>{$mod_strings['LBL_ML_NAME']}</b></td>
1862                  <td width='15%' ><b>{$mod_strings['LBL_ML_VERSION']}</b></td>
1863                  <td width='15%' ><b>{$mod_strings['LBL_ML_PUBLISHED']}</b></td>
1864                  <td width='15%' ><b>{$mod_strings['LBL_ML_UNINSTALLABLE']}</b></td>
1865                  <td width='20%' ><b>{$mod_strings['LBL_ML_DESCRIPTION']}</b></td>
1866                  <td width='7%' ></td>
1867                  <td width='1%' ></td>
1868                  <td width='7%' ></td>
1869              </tr>\n";
1870      $files = array();
1871  
1872      // duh, new installs won't have the upgrade folders
1873     if(!is_dir(getcwd()."/cache/upload/upgrades")) {
1874          mkdir_recursive( "$base_upgrade_dir");
1875      }
1876      $subdirs = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
1877      foreach( $subdirs as $subdir ){
1878          mkdir_recursive( "$base_upgrade_dir/$subdir" );
1879      }
1880  
1881      $files = findAllFiles(getcwd()."/cache/upload/upgrades", $files);
1882      $hidden_input = '';
1883      unset($_SESSION['hidden_input']);
1884  
1885      foreach($files as $file) {
1886          if(!preg_match("#.*\.zip\$#", $file)) {
1887              continue;
1888          }
1889  
1890          // skip installed lang packs
1891          if(isset($_SESSION['INSTALLED_LANG_PACKS']) && in_array($file, $_SESSION['INSTALLED_LANG_PACKS'])) {
1892              continue;
1893          }
1894  
1895          // handle manifest.php
1896          $target_manifest = remove_file_extension( $file ) . '-manifest.php';
1897          $license_file = remove_file_extension( $file ) . '-license.txt';
1898          include($target_manifest);
1899  
1900          if(!empty($types)){
1901              if(!in_array(strtolower($manifest['type']), $types))
1902                  continue;
1903          }
1904  
1905          $md5_matches = array();
1906          if($manifest['type'] == 'module'){
1907              $uh = new UpgradeHistory();
1908              $upgrade_content = clean_path($file);
1909              $the_base = basename($upgrade_content);
1910              $the_md5 = md5_file($upgrade_content);
1911              $md5_matches = $uh->findByMd5($the_md5);
1912          }
1913  
1914          if($manifest['type']!= 'module' || 0 == sizeof($md5_matches)){
1915              $name = empty($manifest['name']) ? $file : $manifest['name'];
1916              $version = empty($manifest['version']) ? '' : $manifest['version'];
1917              $published_date = empty($manifest['published_date']) ? '' : $manifest['published_date'];
1918              $icon = '';
1919              $description = empty($manifest['description']) ? 'None' : $manifest['description'];
1920              $uninstallable = empty($manifest['is_uninstallable']) ? 'No' : 'Yes';
1921              $manifest_type = $manifest['type'];
1922              $commitPackage = getPackButton('commit', $target_manifest, $file, $next_step);
1923              $deletePackage = getPackButton('remove', $target_manifest, $file, $next_step);
1924              //$ret .="<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
1925              $ret .= "<tr>";
1926              $ret .= "<td width='20%' >".$name."</td>";
1927              $ret .= "<td width='15%' >".$version."</td>";
1928              $ret .= "<td width='15%' >".$published_date."</td>";
1929              $ret .= "<td width='15%' >".$uninstallable."</td>";
1930              $ret .= "<td width='20%' >".$description."</td>";
1931  
1932              if($display_commit)
1933                  $ret .= "<td width='7%'>{$commitPackage}</td>";
1934              $ret .= "<td width='1%'></td>";
1935              $ret .= "<td width='7%'>{$deletePackage}</td>";
1936              $ret .= "</td></tr>";
1937  
1938              $clean_field_name = "accept_lic_".str_replace('.', '_', urlencode(basename($file)));
1939  
1940              if(is_file($license_file)){
1941                  //rrs
1942                  $ret .= "<tr><td colspan=6>";
1943                  $ret .= getLicenseDisplay('commit', $target_manifest, $file, $next_step, $license_file, $clean_field_name);
1944                  $ret .= "</td></tr>";
1945                  $hidden_input .= "<input type='hidden' name='$clean_field_name' id='$clean_field_name' value='no'>";
1946              }else{
1947                  $hidden_input .= "<input type='hidden' name='$clean_field_name' id='$clean_field_name' value='yes'>";
1948              }
1949          }//fi
1950      }//rof
1951      $_SESSION['hidden_input'] = $hidden_input;
1952  
1953      if(count($files) > 0 ) {
1954          $ret .= "</tr><td colspan=7>";
1955          $ret .= "<form name='commit' action='install.php' method='POST'>
1956                      <input type='hidden' name='current_step' value='{$next_step}'>
1957                      <input type='hidden' name='goto' value='Re-check'>
1958                      <input type='hidden' name='languagePackAction' value='commit'>
1959                      <input type='hidden' name='install_type' value='custom'>
1960                   </form>
1961                  ";
1962          $ret .= "</td></tr>";
1963      } else {
1964          $ret .= "</tr><td colspan=7><i>{$mod_strings['LBL_LANG_NO_PACKS']}</i></td></tr>";
1965      }
1966      return $ret;
1967  }
1968  
1969  if ( !function_exists('extractFile') ) {
1970  function extractFile( $zip_file, $file_in_zip, $base_tmp_upgrade_dir){
1971      $my_zip_dir = mk_temp_dir( $base_tmp_upgrade_dir );
1972      unzip_file( $zip_file, $file_in_zip, $my_zip_dir );
1973      return( "$my_zip_dir/$file_in_zip" );
1974  }
1975  }
1976  
1977  if ( !function_exists('extractManifest') ) {
1978  function extractManifest( $zip_file,$base_tmp_upgrade_dir ) {
1979      return( extractFile( $zip_file, "manifest.php",$base_tmp_upgrade_dir ) );
1980  }
1981  }
1982  
1983  if ( !function_exists('unlinkTempFiles') ) {
1984  function unlinkTempFiles($manifest, $zipFile) {
1985      global $sugar_config;
1986  
1987      @unlink($_FILES['language_pack']['tmp_name']);
1988      if(!empty($manifest))
1989          @unlink($manifest);
1990      if(!empty($zipFile)) {
1991          //@unlink($zipFile);
1992          $tmpZipFile = substr($zipFile, strpos($zipFile, 'langpack/') + 9, strlen($zipFile));
1993          @unlink(getcwd()."/".$sugar_config['upload_dir'].$tmpZipFile);
1994      }
1995  
1996      rmdir_recursive(getcwd()."/".$sugar_config['upload_dir']."upgrades/temp");
1997      sugar_mkdir(getcwd()."/".$sugar_config['upload_dir']."upgrades/temp");
1998  }
1999  }
2000  
2001  function langPackUnpack($unpack_type = 'langpack', $full_file = '') {
2002      global $sugar_config;
2003      global $base_upgrade_dir;
2004      global $base_tmp_upgrade_dir;
2005  
2006      $manifest = array();
2007      if(!empty($full_file)){
2008          $tempFile = $full_file;
2009          $base_filename = urldecode($tempFile);
2010          $base_filename = preg_replace( "#\\\\#", "/", $base_filename );
2011          $base_filename = basename( $base_filename );
2012      }else{
2013          $tempFile = getcwd().'/'.$sugar_config['upload_dir'].$_FILES['language_pack']['name'];
2014          $base_filename = $_FILES['language_pack']['name'];
2015      }
2016      $manifest_file = extractManifest($tempFile, $base_tmp_upgrade_dir);
2017      if($unpack_type == 'module')
2018          $license_file = extractFile($tempFile, 'LICENSE.txt', $base_tmp_upgrade_dir);
2019  
2020      if(is_file($manifest_file)) {
2021  
2022          if($unpack_type == 'module' && is_file($license_file)){
2023              copy($license_file, getcwd().'/'.$sugar_config['upload_dir'].'upgrades/'.$unpack_type.'/'.remove_file_extension($base_filename)."-license.txt");
2024          }
2025          copy($manifest_file, getcwd().'/'.$sugar_config['upload_dir'].'upgrades/'.$unpack_type.'/'.remove_file_extension($base_filename)."-manifest.php");
2026  
2027          require_once( $manifest_file );
2028          validate_manifest( $manifest );
2029          $upgrade_zip_type = $manifest['type'];
2030  
2031          // exclude the bad permutations
2032          /*if($upgrade_zip_type != "langpack") {
2033              unlinkTempFiles($manifest_file, $tempFile);
2034              die( "You can only upload module packs, theme packs, and language packs on this page." );
2035          }*/
2036  
2037          //$base