[ Index ]

PHP Cross Reference of Joomla 1.5.26 DE

title

Body

[close]

/installation/installer/ -> helper.php (source)

   1  <?php
   2  
   3  /**
   4   * @version        $Id: helper.php 16385 2010-04-23 10:44:15Z ian $
   5   * @package        Joomla
   6   * @subpackage    Installation
   7   * @copyright    Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
   8   * @license        GNU/GPL, see LICENSE.php
   9   * Joomla! is free software. This version may have been modified pursuant
  10   * to the GNU General Public License, and as distributed it includes or
  11   * is derivative of works licensed under the GNU General Public License or
  12   * other free or open source software licenses.
  13   * See COPYRIGHT.php for copyright notices and details.
  14   */
  15  
  16  // no direct access
  17  defined('_JEXEC') or die('Restricted access');
  18  
  19  /**
  20   * @package        Joomla
  21   * @subpackage    Installation
  22   */
  23  class JInstallationHelper
  24  {
  25      /**
  26       * @return string A guess at the db required
  27       */
  28  	function detectDB()
  29      {
  30          $map = array ('mysql_connect' => 'mysql', 'mysqli_connect' => 'mysqli', 'mssql_connect' => 'mssql');
  31          foreach ($map as $f => $db)
  32          {
  33              if (function_exists($f))
  34              {
  35                  return $db;
  36              }
  37          }
  38          return 'mysql';
  39      }
  40  
  41      /**
  42       * @param array
  43       * @return string
  44       */
  45  	function errors2string(& $errors)
  46      {
  47          $buffer = '';
  48          foreach ($errors as $error)
  49          {
  50              $buffer .= 'SQL='.$error['msg'].":\n- - - - - - - - - -\n".$error['sql']."\n= = = = = = = = = =\n\n";
  51          }
  52          return $buffer;
  53      }
  54      /**
  55       * Creates a new database
  56       * @param object Database connector
  57       * @param string Database name
  58       * @param boolean utf-8 support
  59       * @param string Selected collation
  60       * @return boolean success
  61       */
  62  	function createDatabase(& $db, $DBname, $DButfSupport)
  63      {
  64          if ($DButfSupport)
  65          {
  66              $sql = "CREATE DATABASE `$DBname` CHARACTER SET `utf8`";
  67          }
  68          else
  69          {
  70              $sql = "CREATE DATABASE `$DBname`";
  71          }
  72  
  73          $db->setQuery($sql);
  74          $db->query();
  75          $result = $db->getErrorNum();
  76  
  77          if ($result != 0)
  78          {
  79              return false;
  80          }
  81  
  82          return true;
  83      }
  84  
  85      /**
  86       * Sets character set of the database to utf-8 with selected collation
  87       * Used in instances of pre-existing database
  88       * @param object Database object
  89       * @param string Database name
  90       * @param string Selected collation
  91       * @return boolean success
  92       */
  93  	function setDBCharset(& $db, $DBname)
  94      {
  95          if ($db->hasUTF())
  96          {
  97              $sql = "ALTER DATABASE `$DBname` CHARACTER SET `utf8`";
  98              $db->setQuery($sql);
  99              $db->query();
 100              $result = $db->getErrorNum();
 101              if ($result != 0) {
 102                  return false;
 103              }
 104          }
 105          return true;
 106      }
 107  
 108      /**
 109       * Backs up existing tables
 110       * @param object Database connector
 111       * @param array An array of errors encountered
 112       */
 113  	function backupDatabase(& $db, $DBname, $DBPrefix, & $errors)
 114      {
 115          // Initialize backup prefix variable
 116          // TODO: Should this be user-defined?
 117          $BUPrefix = 'bak_';
 118  
 119          $query = "SHOW TABLES FROM `$DBname`";
 120          $db->setQuery($query);
 121          $errors = array ();
 122          if ($tables = $db->loadResultArray())
 123          {
 124              foreach ($tables as $table)
 125              {
 126                  if (strpos($table, $DBPrefix) === 0)
 127                  {
 128                      $butable = str_replace($DBPrefix, $BUPrefix, $table);
 129                      $query = "DROP TABLE IF EXISTS `$butable`";
 130                      $db->setQuery($query);
 131                      $db->query();
 132                      if ($db->getErrorNum())
 133                      {
 134                          $errors[$db->getQuery()] = $db->getErrorMsg();
 135                      }
 136                      $query = "RENAME TABLE `$table` TO `$butable`";
 137                      $db->setQuery($query);
 138                      $db->query();
 139                      if ($db->getErrorNum())
 140                      {
 141                          $errors[$db->getQuery()] = $db->getErrorMsg();
 142                      }
 143                  }
 144              }
 145          }
 146  
 147          return count($errors);
 148      }
 149      /**
 150       * Deletes all database tables
 151       * @param object Database connector
 152       * @param array An array of errors encountered
 153       */
 154  	function deleteDatabase(& $db, $DBname, $DBPrefix, & $errors)
 155      {
 156          $query = "SHOW TABLES FROM `$DBname`";
 157          $db->setQuery($query);
 158          $errors = array ();
 159          if ($tables = $db->loadResultArray())
 160          {
 161              foreach ($tables as $table)
 162              {
 163                  if (strpos($table, $DBPrefix) === 0)
 164                  {
 165                      $query = "DROP TABLE IF EXISTS `$table`";
 166                      $db->setQuery($query);
 167                      $db->query();
 168                      if ($db->getErrorNum())
 169                      {
 170                          $errors[$db->getQuery()] = $db->getErrorMsg();
 171                      }
 172                  }
 173              }
 174          }
 175  
 176          return count($errors);
 177      }
 178  
 179      /**
 180       *
 181       */
 182  	function populateDatabase(& $db, $sqlfile, & $errors, $nexttask='mainconfig')
 183      {
 184          if( !($buffer = file_get_contents($sqlfile)) )
 185          {
 186              return -1;
 187          }
 188  
 189          $queries = JInstallationHelper::splitSql($buffer);
 190  
 191          foreach ($queries as $query)
 192          {
 193              $query = trim($query);
 194              if ($query != '' && $query {0} != '#')
 195              {
 196                  $db->setQuery($query);
 197                  //echo $query .'<br />';
 198                  $db->query() or die($db->getErrorMsg());
 199  
 200                  JInstallationHelper::getDBErrors($errors, $db );
 201              }
 202          }
 203          return count($errors);
 204      }
 205  
 206      /**
 207       * @param string
 208       * @return array
 209       */
 210  	function splitSql($sql)
 211      {
 212          $sql = trim($sql);
 213          $sql = preg_replace("/\n\#[^\n]*/", '', "\n".$sql);
 214          $buffer = array ();
 215          $ret = array ();
 216          $in_string = false;
 217  
 218          for ($i = 0; $i < strlen($sql) - 1; $i ++) {
 219              if ($sql[$i] == ";" && !$in_string)
 220              {
 221                  $ret[] = substr($sql, 0, $i);
 222                  $sql = substr($sql, $i +1);
 223                  $i = 0;
 224              }
 225  
 226              if ($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\")
 227              {
 228                  $in_string = false;
 229              }
 230              elseif (!$in_string && ($sql[$i] == '"' || $sql[$i] == "'") && (!isset ($buffer[0]) || $buffer[0] != "\\"))
 231              {
 232                  $in_string = $sql[$i];
 233              }
 234              if (isset ($buffer[1]))
 235              {
 236                  $buffer[0] = $buffer[1];
 237              }
 238              $buffer[1] = $sql[$i];
 239          }
 240  
 241          if (!empty ($sql))
 242          {
 243              $ret[] = $sql;
 244          }
 245          return ($ret);
 246      }
 247  
 248      /**
 249       * Calculates the file/dir permissions mask
 250       */
 251  	function getFilePerms($input, $type = 'file')
 252      {
 253          $perms = '';
 254          if (JArrayHelper::getValue($input, $type.'PermsMode', 0))
 255          {
 256              $action = ($type == 'dir') ? 'Search' : 'Execute';
 257              $perms = '0'. (JArrayHelper::getValue($input, $type.'PermsUserRead', 0) * 4 + JArrayHelper::getValue($input, $type.'PermsUserWrite', 0) * 2 + JArrayHelper::getValue($input, $type.'PermsUser'.$action, 0)). (JArrayHelper::getValue($input, $type.'PermsGroupRead', 0) * 4 + JArrayHelper::getValue($input, $type.'PermsGroupWrite', 0) * 2 + JArrayHelper::getValue($input, $type.'PermsGroup'.$action, 0)). (JArrayHelper::getValue($input, $type.'PermsWorldRead', 0) * 4 + JArrayHelper::getValue($input, $type.'PermsWorldWrite', 0) * 2 + JArrayHelper::getValue($input, $type.'PermsWorld'.$action, 0));
 258          }
 259          return $perms;
 260      }
 261  
 262      /**
 263       * Creates the admin user
 264       */
 265  	function createAdminUser(& $vars)
 266      {
 267          $DBtype        = JArrayHelper::getValue($vars, 'DBtype', 'mysql');
 268          $DBhostname    = JArrayHelper::getValue($vars, 'DBhostname', '');
 269          $DBuserName    = JArrayHelper::getValue($vars, 'DBuserName', '');
 270          $DBpassword    = JArrayHelper::getValue($vars, 'DBpassword', '');
 271          $DBname        = JArrayHelper::getValue($vars, 'DBname', '');
 272          $DBPrefix    = JArrayHelper::getValue($vars, 'DBPrefix', '');
 273  
 274          $adminPassword    = JArrayHelper::getValue($vars, 'adminPassword', '');
 275          $adminEmail        = JArrayHelper::getValue($vars, 'adminEmail', '');
 276  
 277          jimport('joomla.user.helper');
 278  
 279          // Create random salt/password for the admin user
 280          $salt = JUserHelper::genRandomPassword(32);
 281          $crypt = JUserHelper::getCryptedPassword($adminPassword, $salt);
 282          $cryptpass = $crypt.':'.$salt;
 283  
 284          $vars['adminLogin'] = 'admin';
 285  
 286          $db = & JInstallationHelper::getDBO($DBtype, $DBhostname, $DBuserName, $DBpassword, $DBname, $DBPrefix);
 287  
 288          // create the admin user
 289          $installdate     = date('Y-m-d H:i:s');
 290          $nullDate         = $db->getNullDate();
 291          $query = "INSERT INTO #__users VALUES (62, 'Administrator', 'admin', ".$db->Quote($adminEmail).", ".$db->Quote($cryptpass).", 'Super Administrator', 0, 1, 25, '$installdate', '$nullDate', '', '')";
 292          $db->setQuery($query);
 293          if (!$db->query())
 294          {
 295              // is there already and existing admin in migrated data
 296              if ( $db->getErrorNum() == 1062 )
 297              {
 298                  $vars['adminLogin'] = JText::_('Admin login in migrated content was kept');
 299                  $vars['adminPassword'] = JText::_('Admin password in migrated content was kept');
 300                  return;
 301              }
 302              else
 303              {
 304                  echo $db->getErrorMsg();
 305                  return;
 306              }
 307          }
 308  
 309          // add the ARO (Access Request Object)
 310          $query = "INSERT INTO #__core_acl_aro VALUES (10,'users','62',0,'Administrator',0)";
 311          $db->setQuery($query);
 312          if (!$db->query())
 313          {
 314              echo $db->getErrorMsg();
 315              return;
 316          }
 317  
 318          // add the map between the ARO and the Group
 319          $query = "INSERT INTO #__core_acl_groups_aro_map VALUES (25,'',10)";
 320          $db->setQuery($query);
 321          if (!$db->query())
 322          {
 323              echo $db->getErrorMsg();
 324              return;
 325          }
 326      }
 327  
 328      function & getDBO($driver, $host, $user, $password, $database, $prefix, $select = true)
 329      {
 330          static $db;
 331  
 332          if ( ! $db )
 333          {
 334              jimport('joomla.database.database');
 335              $options    = array ( 'driver' => $driver, 'host' => $host, 'user' => $user, 'password' => $password, 'database' => $database, 'prefix' => $prefix, 'select' => $select    );
 336              $db = & JDatabase::getInstance( $options );
 337          }
 338  
 339          return $db;
 340      }
 341  
 342      /**
 343       * Check the webserver user permissions for writing files/folders
 344       *
 345       * @static
 346       * @return    boolean    True if correct permissions exist
 347       * @since    1.5
 348       */
 349  	function fsPermissionsCheck()
 350      {
 351          if(!is_writable(JPATH_ROOT.DS.'tmp')) {
 352              return false;
 353          }
 354          if(!mkdir(JPATH_ROOT.DS.'tmp'.DS.'test', 0755)) {
 355              return false;
 356          }
 357          if(!copy(JPATH_ROOT.DS.'tmp'.DS.'index.html', JPATH_ROOT.DS.'tmp'.DS.'test'.DS.'index.html')) {
 358              return false;
 359          }
 360          if(!chmod(JPATH_ROOT.DS.'tmp'.DS.'test'.DS.'index.html', 0777)) {
 361              return false;
 362          }
 363          if(!unlink(JPATH_ROOT.DS.'tmp'.DS.'test'.DS.'index.html')) {
 364              return false;
 365          }
 366          if(!rmdir(JPATH_ROOT.DS.'tmp'.DS.'test')) {
 367              return false;
 368          }
 369          return true;
 370      }
 371  
 372      /**
 373       * Find the ftp filesystem root for a given user/pass pair
 374       *
 375       * @static
 376       * @param    string    $user    Username of the ftp user to determine root for
 377       * @param    string    $pass    Password of the ftp user to determine root for
 378       * @return    string    Filesystem root for given FTP user
 379       * @since 1.5
 380       */
 381  	function findFtpRoot($user, $pass, $host='127.0.0.1', $port='21')
 382      {
 383          jimport('joomla.client.ftp');
 384          $ftpPaths = array();
 385  
 386          // Connect and login to the FTP server (using binary transfer mode to be able to compare files)
 387          $ftp =& JFTP::getInstance($host, $port, array('type'=>FTP_BINARY));
 388          if (!$ftp->isConnected()) {
 389              return JError::raiseError('31', 'NOCONNECT');
 390          }
 391          if (!$ftp->login($user, $pass)) {
 392              return JError::raiseError('31', 'NOLOGIN');
 393          }
 394  
 395          // Get the FTP CWD, in case it is not the FTP root
 396          $cwd = $ftp->pwd();
 397          if ($cwd === false) {
 398              return JError::raiseError('SOME_ERROR_CODE', 'NOPWD');
 399          }
 400          $cwd = rtrim($cwd, '/');
 401  
 402          // Get list of folders in the CWD
 403          $ftpFolders = $ftp->listDetails(null, 'folders');
 404          if ($ftpFolders === false || count($ftpFolders) == 0) {
 405              return JError::raiseError('SOME_ERROR_CODE', 'NODIRECTORYLISTING');
 406          }
 407          for ($i=0, $n=count($ftpFolders); $i<$n; $i++) {
 408              $ftpFolders[$i] = $ftpFolders[$i]['name'];
 409          }
 410  
 411          // Check if Joomla! is installed at the FTP CWD
 412          $dirList = array('administrator', 'components', 'installation', 'language', 'libraries', 'plugins');
 413          if (count(array_diff($dirList, $ftpFolders)) == 0) {
 414              $ftpPaths[] = $cwd.'/';
 415          }
 416  
 417          // Process the list: cycle through all parts of JPATH_SITE, beginning from the end
 418          $parts        = explode(DS, JPATH_SITE);
 419          $tmpPath    = '';
 420          for ($i=count($parts)-1; $i>=0; $i--)
 421          {
 422              $tmpPath = '/'.$parts[$i].$tmpPath;
 423              if (in_array($parts[$i], $ftpFolders)) {
 424                  $ftpPaths[] = $cwd.$tmpPath;
 425              }
 426          }
 427  
 428          // Check all possible paths for the real Joomla! installation
 429          $checkValue = file_get_contents(JPATH_LIBRARIES.DS.'joomla'.DS.'version.php');
 430          foreach ($ftpPaths as $tmpPath)
 431          {
 432              $filePath = rtrim($tmpPath, '/').'/libraries/joomla/version.php';
 433              $buffer = null;
 434              @$ftp->read($filePath, $buffer);
 435              if ($buffer == $checkValue)
 436              {
 437                  $ftpPath = $tmpPath;
 438                  break;
 439              }
 440          }
 441  
 442          // Close the FTP connection
 443          $ftp->quit();
 444  
 445          // Return the FTP root path
 446          if (isset($ftpPath)) {
 447              return $ftpPath;
 448          } else {
 449              return JError::raiseError('SOME_ERROR_CODE', 'Unable to autodetect the FTP root folder');
 450          }
 451      }
 452  
 453      /**
 454       * Verify the FTP configuration values are valid
 455       *
 456       * @static
 457       * @param    string    $user    Username of the ftp user to determine root for
 458       * @param    string    $pass    Password of the ftp user to determine root for
 459       * @return    mixed    Boolean true on success or JError object on fail
 460       * @since    1.5
 461       */
 462  	function FTPVerify($user, $pass, $root, $host='127.0.0.1', $port='21')
 463      {
 464          jimport('joomla.client.ftp');
 465          $ftp = & JFTP::getInstance($host, $port);
 466  
 467          // Since the root path will be trimmed when it gets saved to configuration.php, we want to test with the same value as well
 468          $root = rtrim($root, '/');
 469  
 470          // Verify connection
 471          if (!$ftp->isConnected()) {
 472              return JError::raiseWarning('31', 'NOCONNECT');
 473          }
 474  
 475          // Verify username and password
 476          if (!$ftp->login($user, $pass)) {
 477              return JError::raiseWarning('31', 'NOLOGIN');
 478          }
 479  
 480          // Verify PWD function
 481          if ($ftp->pwd() === false) {
 482              return JError::raiseError('SOME_ERROR_CODE', 'NOPWD');
 483          }
 484  
 485          // Verify root path exists
 486          if (!$ftp->chdir($root)) {
 487              return JError::raiseWarning('31', 'NOROOT');
 488          }
 489  
 490          // Verify NLST function
 491          if (($rootList = $ftp->listNames()) === false) {
 492              return JError::raiseError('SOME_ERROR_CODE', 'NONLST');
 493          }
 494  
 495          // Verify LIST function
 496          if ($ftp->listDetails() === false) {
 497              return JError::raiseError('SOME_ERROR_CODE', 'NOLIST');
 498          }
 499  
 500          // Verify SYST function
 501          if ($ftp->syst() === false) {
 502              return JError::raiseError('SOME_ERROR_CODE', 'NOSYST');
 503          }
 504  
 505          // Verify valid root path, part one
 506          $checkList = array('CHANGELOG.php', 'COPYRIGHT.php', 'index.php', 'INSTALL.php', 'LICENSE.php');
 507          if (count(array_diff($checkList, $rootList))) {
 508              return JError::raiseWarning('31', 'INVALIDROOT');
 509          }
 510  
 511          // Verify RETR function
 512          $buffer = null;
 513          if ($ftp->read($root.'/libraries/joomla/version.php', $buffer) === false) {
 514              return JError::raiseError('SOME_ERROR_CODE', 'NORETR');
 515          }
 516  
 517          // Verify valid root path, part two
 518          $checkValue = file_get_contents(JPATH_LIBRARIES.DS.'joomla'.DS.'version.php');
 519          if ($buffer !== $checkValue) {
 520              return JError::raiseWarning('31', 'INVALIDROOT');
 521          }
 522  
 523          // Verify STOR function
 524          if ($ftp->create($root.'/ftp_testfile') === false) {
 525              return JError::raiseError('SOME_ERROR_CODE', 'NOSTOR');
 526          }
 527  
 528          // Verify DELE function
 529          if ($ftp->delete($root.'/ftp_testfile') === false) {
 530              return JError::raiseError('SOME_ERROR_CODE', 'NODELE');
 531          }
 532  
 533          // Verify MKD function
 534          if ($ftp->mkdir($root.'/ftp_testdir') === false) {
 535              return JError::raiseError('SOME_ERROR_CODE', 'NOMKD');
 536          }
 537  
 538          // Verify RMD function
 539          if ($ftp->delete($root.'/ftp_testdir') === false) {
 540              return JError::raiseError('SOME_ERROR_CODE', 'NORMD');
 541          }
 542  
 543          $ftp->quit();
 544          return true;
 545      }
 546  
 547      /**
 548       * Set default folder permissions
 549       *
 550       * @param string $path The full file path
 551       * @param string $buffer The buffer to write
 552       * @return boolean True on success
 553       * @since 1.5
 554       */
 555  	function setDirPerms($dir, &$srv)
 556      {
 557          jimport('joomla.filesystem.path');
 558  
 559          /*
 560           * Initialize variables
 561           */
 562          $ftpFlag = false;
 563          $ftpRoot = $srv['ftpRoot'];
 564  
 565          /*
 566           * First we need to determine if the path is chmodable
 567           */
 568          if (!JPath::canChmod(JPath::clean(JPATH_SITE.DS.$dir)))
 569          {
 570              $ftpFlag = true;
 571          }
 572  
 573          // Do NOT use ftp if it is not enabled
 574          if (!$srv['ftpEnable'])
 575          {
 576              $ftpFlag = false;
 577          }
 578  
 579          if ($ftpFlag == true)
 580          {
 581              // Connect the FTP client
 582              jimport('joomla.client.ftp');
 583              $ftp = & JFTP::getInstance($srv['ftpHost'], $srv['ftpPort']);
 584              $ftp->login($srv['ftpUser'],$srv['ftpPassword']);
 585  
 586              //Translate path for the FTP account
 587              $path = JPath::clean($ftpRoot."/".$dir);
 588  
 589              /*
 590               * chmod using ftp
 591               */
 592              if (!$ftp->chmod($path, '0755'))
 593              {
 594                  $ret = false;
 595              }
 596  
 597              $ftp->quit();
 598              $ret = true;
 599          }
 600          else
 601          {
 602  
 603              $path = JPath::clean(JPATH_SITE.DS.$dir);
 604  
 605              if (!@ chmod($path, octdec('0755')))
 606              {
 607                  $ret = false;
 608              }
 609              else
 610              {
 611                  $ret = true;
 612              }
 613          }
 614  
 615          return $ret;
 616      }
 617  
 618  	function findMigration( &$args ) {
 619          print_r($args); jexit();
 620      }
 621  
 622      /**
 623       * Uploads a sql script and executes it. Script can be text file or zip/gz packed
 624       *
 625       * @static
 626       * @param array The installation variables
 627       * @param boolean true if the script is a migration script
 628       * @return string Success or error messages
 629       * @since 1.5
 630       */
 631  	function uploadSql( &$args, $migration = false, $preconverted = false )
 632      {
 633          global $mainframe;
 634          $archive = '';
 635          $script = '';
 636  
 637          /*
 638           * Check for iconv
 639           */
 640          if ($migration && !$preconverted && !function_exists( 'iconv' ) ) {
 641              return JText::_( 'WARNICONV' );
 642          }
 643  
 644  
 645          /*
 646           * Get the uploaded file information
 647           */
 648          if( $migration )
 649          {
 650              $sqlFile    = JRequest::getVar('migrationFile', '', 'files', 'array');
 651          }
 652          else
 653          {
 654              $sqlFile    = JRequest::getVar('sqlFile', '', 'files', 'array');
 655          }
 656  
 657          /*
 658           * Make sure that file uploads are enabled in php
 659           */
 660          if (!(bool) ini_get('file_uploads'))
 661          {
 662              return JText::_('WARNINSTALLFILE');
 663          }
 664  
 665          /*
 666           * Make sure that zlib is loaded so that the package can be unpacked
 667           */
 668          if (!extension_loaded('zlib'))
 669          {
 670              return JText::_('WARNINSTALLZLIB');
 671          }
 672  
 673          /*
 674           * If there is no uploaded file, we have a problem...
 675           */
 676          if (!is_array($sqlFile) || $sqlFile['size'] < 1)
 677          {
 678              return JText::_('WARNNOFILE');
 679          }
 680  
 681          /*
 682           * Move uploaded file
 683           */
 684          // Set permissions for tmp dir
 685          JInstallationHelper::_chmod(JPATH_SITE.DS.'tmp', 0777);
 686          jimport('joomla.filesystem.file');
 687          $uploaded = JFile::upload($sqlFile['tmp_name'], JPATH_SITE.DS.'tmp'.DS.$sqlFile['name']);
 688          if(!$uploaded) {
 689              return JText::_('WARNUPLOADFAILURE');
 690          }
 691  
 692          if( !preg_match('#\.sql$#i', $sqlFile['name']) )
 693          {
 694              $archive = JPATH_SITE.DS.'tmp'.DS.$sqlFile['name'];
 695          }
 696          else
 697          {
 698              $script = JPATH_SITE.DS.'tmp'.DS.$sqlFile['name'];
 699          }
 700  
 701          // unpack archived sql files
 702          if ($archive )
 703          {
 704              $package = JInstallationHelper::unpack( $archive, $args );
 705              if ( $package === false )
 706              {
 707                  return JText::_('WARNUNPACK');
 708              }
 709              $script = $package['folder'].DS.$package['script'];
 710          }
 711  
 712          $db = & JInstallationHelper::getDBO($args['DBtype'], $args['DBhostname'], $args['DBuserName'], $args['DBpassword'], $args['DBname'], $args['DBPrefix']);
 713  
 714          /*
 715           * If migration perform manipulations on script file before population
 716           */
 717          if ( $migration )
 718          {
 719              $script = JInstallationHelper::preMigrate($script, $args, $db);
 720              if ( $script == false )
 721              {
 722                  return JText::_( 'Script operations failed' );
 723              }
 724          }
 725  
 726          $errors = null;
 727          $msg = '';
 728          $result = JInstallationHelper::populateDatabase($db, $script, $errors);
 729  
 730          /*
 731           * If migration, perform post population manipulations (menu table construction)
 732           */
 733          $migErrors = null;
 734          if ( $migration )
 735          {
 736              $migResult = JInstallationHelper::postMigrate( $db, $migErrors, $args );
 737  
 738              if ( $migResult != 0 )
 739              {
 740                  /*
 741                   * Merge populate and migrate processing errors
 742                   */
 743                  if( $result == 0 )
 744                  {
 745                      $result = $migResult;
 746                      $errors = $migErrors;
 747                  }
 748                  else
 749                  {
 750                      $result += $migResult;
 751                      $errors = array_merge( $errors, $migErrors );
 752                  }
 753              }
 754          }
 755  
 756  
 757          /*
 758           * prepare sql error messages if returned from populate and migrate
 759           */
 760          if (!is_null($errors))
 761          {
 762              foreach($errors as $error)
 763              {
 764                  $msg .= stripslashes( $error['msg'] );
 765                  $msg .= chr(13)."-------------".chr(13);
 766                  $txt = '<textarea cols="40" rows="4" name="instDefault" readonly="readonly" >'.JText::_("Database Errors Reported").chr(13).$msg.'</textarea>';
 767              }
 768          }
 769          else
 770          {
 771              // consider other possible errors from populate
 772              $msg = $result == 0 ? JText::_('SQL script installed successfully') : JText::_('Error installing SQL script') ;
 773              $txt = '<input size="50" value="'.$msg.'" readonly="readonly" />';
 774          }
 775  
 776          /*
 777           * Clean up
 778           */
 779          if ($archive)
 780          {
 781              JFile::delete( $archive );
 782              JFolder::delete( $package['folder'] );
 783          }
 784          else
 785          {
 786              JFile::delete( $script );
 787          }
 788  
 789          return $txt;
 790      }
 791  
 792      /**
 793       * Unpacks a compressed script file either as zip or gz/ Assumes single file in archive
 794       *
 795       * @static
 796       * @param string $p_filename The uploaded package filename or install directory
 797       * @return unpacked filename on success, False on error
 798       * @since 1.5
 799       */
 800  	function unpack($p_filename, &$vars) {
 801  
 802          /*
 803           * Initialize variables
 804           */
 805          // Path to the archive
 806          $archivename = $p_filename;
 807          // Temporary folder to extract the archive into
 808          $tmpdir = uniqid('install_');
 809  
 810  
 811          // Clean the paths to use for archive extraction
 812          $extractdir = JPath::clean(dirname($p_filename).DS.$tmpdir);
 813          $archivename = JPath::clean($archivename);
 814          jimport('joomla.filesystem.archive');
 815          $result = JArchive::extract( $archivename, $extractdir);
 816  
 817          if ( $result === false ) {
 818              return false;
 819          }
 820  
 821  
 822          /*
 823           * return the file found in the extract folder and also folder name
 824           */
 825          if ($handle = opendir( $extractdir ))
 826          {
 827              while (false !== ($file = readdir($handle)))
 828              {
 829                  if ($file != "." && $file != "..")
 830                  {
 831                      $script = $file;
 832                      continue;
 833                  }
 834              }
 835              closedir($handle);
 836          }
 837          $retval['script'] = $script;
 838          $retval['folder'] = $extractdir;
 839          return $retval;
 840  
 841      }
 842  
 843  	function return_bytes($val) {
 844          $val = trim($val);
 845          $last = strtolower($val{strlen($val)-1});
 846          switch($last) {
 847              // The 'G' modifier is available since PHP 5.1.0
 848              case 'g':
 849                  $val *= 1024;
 850              case 'm':
 851                  $val *= 1024;
 852              case 'k':
 853                  $val *= 1024;
 854          }
 855  
 856          return $val;
 857      }
 858  
 859  	function replaceBuffer(&$buffer, $oldPrefix, $newPrefix, $srcEncoding) {
 860  
 861              $buffer = str_replace( $oldPrefix, $newPrefix, $buffer );
 862  
 863              /*
 864               * give temp name to menu and modules tables
 865               */
 866              $buffer = str_replace ( $newPrefix.'modules', $newPrefix.'modules_migration', $buffer );
 867              $buffer = str_replace ( $newPrefix.'menu', $newPrefix.'menu_migration', $buffer );
 868  
 869              /*
 870               * convert to utf-8
 871               */
 872              if(function_exists('iconv')) {
 873                  $buffer = iconv( $srcEncoding, 'utf-8//TRANSLIT', $buffer );
 874              }
 875      }
 876  
 877  	function appendFile(&$buffer, $filename) {
 878          $fh = fopen($filename, 'a');
 879          fwrite($fh, $buffer);
 880          fclose($fh);
 881      }
 882  
 883      /**
 884       * Performs pre-populate conversions on a migration script
 885       *
 886       * @static
 887       * @param string $scriptName The uploaded / unpacked script file
 888       * $param array $args The installation varibables
 889       * @return converted filename on success, False on error
 890       * @since 1.5
 891       */
 892  	function preMigrate( $scriptName, &$args, $db )
 893      {
 894          $maxread = 0;
 895          jimport('joomla.filesystem.file');
 896          if(function_exists('memory_get_usage')) {
 897              $memlimit = JInstallationHelper::return_bytes(ini_get('memory_limit'));
 898              $maxread = $memlimit / 16;     // Read only a eigth of our max amount of memory, we could be up to a lot by now
 899                                          // By default this pegs us at 0.5MB
 900          }
 901          $buffer = '';
 902          $newPrefix = $args['DBPrefix'];
 903          /*
 904           * search and replace table prefixes
 905           */
 906          $oldPrefix = trim( $args['oldPrefix']);
 907          $oldPrefix = rtrim( $oldPrefix, '_' ) . '_';
 908          $srcEncoding = $args['srcEncoding'];
 909          if(!is_file($scriptName)) return false; // not a file?
 910          $newFile = dirname( $scriptName ).DS.'converted.sql';
 911          $tfilesize = filesize($scriptName);
 912          if($maxread > 0 && $tfilesize > 0 && $maxread < $tfilesize)
 913          {
 914              $parts = ceil($tfilesize / $maxread);
 915              file_put_contents( $newFile, '' ); // cleanse the file first
 916              for($i = 0; $i < $parts; $i++) {
 917                  $buffer = JFile::read($scriptName, false, $maxread, $maxread,($i * $maxread));
 918                  // Lets try and read a portion of the file
 919                  JInstallationHelper::replaceBuffer($buffer, $oldPrefix, $newPrefix, $srcEncoding);
 920                  JInstallationHelper::appendFile($buffer, $newFile);
 921                  unset($buffer);
 922              }
 923              JFile::delete( $scriptName );
 924          } else {
 925              /*
 926               * read script file into buffer
 927               */
 928              if(is_file($scriptName)) {
 929                  $buffer = file_get_contents( $scriptName );
 930              } else return false;
 931  
 932              if(  $buffer == false ) return false;
 933              JInstallationHelper::replaceBuffer($buffer, $oldPrefix, $newPrefix, $srcEncoding);
 934  
 935              /*
 936               * write to file
 937               */
 938              //$newFile = dirname( $scriptName ).DS.'converted.sql';
 939              $ret = file_put_contents( $newFile, $buffer );
 940              unset($buffer); // Release the memory used by the buffer
 941              jimport('joomla.filesystem.file');
 942              JFile::delete( $scriptName );
 943          }
 944  
 945          /*
 946           * Create two empty temporary tables
 947           */
 948  
 949          $query = 'DROP TABLE IF EXISTS '.$newPrefix.'modules_migration';
 950          $db->setQuery( $query );
 951          $db->query();
 952  
 953          $query = 'DROP TABLE IF EXISTS '.$newPrefix.'menu_migration';
 954          $db->setQuery( $query );
 955          $db->query();
 956  
 957          $query = 'CREATE TABLE '.$newPrefix.'modules_migration SELECT * FROM '.$newPrefix.'modules WHERE 0';
 958          $db->setQuery( $query );
 959          $db->query();
 960  
 961          $query = 'CREATE TABLE '.$newPrefix.'modules_migration_menu SELECT * FROM '.$newPrefix.'modules_menu WHERE 0';
 962          $db->setQuery( $query );
 963          $db->Query();
 964  
 965          $query = 'CREATE TABLE '.$newPrefix.'menu_migration SELECT * FROM '.$newPrefix.'menu WHERE 0';
 966          $db->setQuery( $query );
 967          $db->query();
 968  
 969          return $newFile;
 970      }
 971  
 972      /**
 973       * Performs post-populate conversions after importing a migration script
 974       * These include constructing an appropriate menu table for core content items
 975       * and adding core modules from old site to the modules table
 976       *
 977       * @static
 978       * @param JDatabase
 979       * @param array errors (by ref)
 980       * @return error count
 981       * @since 1.5
 982       */
 983  	function postMigrate( $db, & $errors, & $args ) {
 984  
 985          $newPrefix = $args['DBPrefix'];
 986  
 987          /*
 988           * Check to see if migration is from 4.5.1
 989           */
 990          $query = 'SELECT id FROM '.$newPrefix.'users WHERE usertype = "superadministrator"';
 991          $db->setQuery($query);
 992          $rows = $db->loadRowList(  );
 993          JInstallationHelper::getDBErrors($errors, $db );
 994  
 995          /*
 996           * if it is, then fill usertype field with correct values from aro_group
 997           */
 998          if ( count($rows) > 0 )
 999          {
1000              $query = 'UPDATE '.$newPrefix.'users AS u, '.$newPrefix.'core_acl_aro_groups AS g' .
1001              ' SET u.usertype = g.value' .
1002              ' WHERE u.gid = g.id';
1003              $db->setQuery($query);
1004              $db->query();
1005              JInstallationHelper::getDBErrors($errors, $db );
1006          }
1007  
1008          /*
1009           * Construct the menu table based on old table references to core items
1010           */
1011          // Component - change all
1012          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `type` = "component" WHERE `type` = "components";';
1013          $db->setQuery( $query );
1014          $db->query();
1015          JInstallationHelper::getDBErrors($errors, $db );
1016  
1017          // Component Item Link
1018          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = SUBSTRING(link, 1, LOCATE("&Itemid=", link) -1), `type` = "component" WHERE `type` = "component_item_link";';
1019          $db->setQuery( $query );
1020          $db->query();
1021          JInstallationHelper::getDBErrors($errors, $db );
1022  
1023          // get com_contact id
1024          $query = 'SELECT `id` FROM `'.$newPrefix.'components` WHERE `option`="com_contact" AND `parent` = 0';
1025          $db->setQuery( $query );
1026          JInstallationHelper::getDBErrors($errors, $db );
1027          $compId = $db->loadResult();
1028  
1029          // contact category table
1030          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET  `link` = INSERT(link, LOCATE("catid=", link), 0, "view=category&"), `type` = "component", `componentid` = '.$compId.' WHERE `type` = "contact_category_table"';
1031          $db->setQuery( $query );
1032          $db->query();
1033          JInstallationHelper::getDBErrors($errors, $db );
1034  
1035          // contact item link
1036          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET  `link` = INSERT(link, LOCATE("task=view", link), 20, "view=contact&id"), `type` = "component", `componentid` = '.$compId.' WHERE `type` = "contact_item_link"';
1037          $db->setQuery( $query );
1038          $db->query();
1039          JInstallationHelper::getDBErrors($errors, $db );
1040  
1041          // fix up standalone contact
1042          $query = 'UPDATE `'. $newPrefix.'menu_migration` SET `link` = "index.php?option=com_contact&view=category" WHERE `link` = "index.php?option=com_contact"';
1043          $db->setQuery( $query );
1044          $db->query();
1045          JInstallationHelper::getDBErrors($errors, $db );
1046  
1047          // get com_content id
1048          $query = 'SELECT `id` FROM `'.$newPrefix.'components` WHERE `option`="com_content" AND `parent` = 0';
1049          $db->setQuery( $query );
1050  
1051          $compId = $db->loadResult();
1052          JInstallationHelper::getDBErrors($errors, $db );
1053  
1054          // front page
1055          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = "index.php?option=com_content&view=frontpage", `type` = "component", `componentid` = '.$compId.' WHERE `link` LIKE "%option=com_frontpage%"';
1056          $db->setQuery( $query );
1057          $db->query();
1058          JInstallationHelper::getDBErrors($errors, $db );
1059  
1060          // content archive category or section
1061          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET  `link` = "index.php?option=com_content&view=archive", `type` = "component", `componentid` = '.$compId.' WHERE (`type` = "content_archive_category" OR `type` = "content_archive_section")';
1062          $db->setQuery( $query );
1063          $db->query();
1064          JInstallationHelper::getDBErrors($errors, $db );
1065  
1066          // content blog category
1067          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET  `link` = INSERT(link, LOCATE("task=blogcat", link), 17, "view=category&layout=blog"), `type` = "component", `componentid` = '.$compId.' WHERE `type` = "content_blog_category"';
1068          $db->setQuery( $query );
1069          $db->query();
1070          JInstallationHelper::getDBErrors($errors, $db );
1071  
1072          // content blog section
1073          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = INSERT(link, LOCATE("task=blogsec", link), 16, "view=section&layout=blog"), `type` = "component", `componentid` = '.$compId.' WHERE `type` = "content_blog_section";';
1074          $db->setQuery( $query );
1075          $db->query();
1076          JInstallationHelper::getDBErrors($errors, $db );
1077  
1078          // content category
1079          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = INSERT(link, LOCATE("task=", link), LOCATE("&id=", link) - LOCATE("task=", link), "view=category"), `type` = "component", `componentid` = '.$compId.' WHERE `type` = "content_category"';
1080          $db->setQuery( $query );
1081          $db->query();
1082          JInstallationHelper::getDBErrors($errors, $db );
1083  
1084          // content item link and typed content
1085          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET  `link` = INSERT(link, LOCATE("task=", link), 9, "view=article"), `type` = "component", `componentid` = '.$compId.' WHERE (`type` = "content_item_link" OR `type` = "content_typed")';
1086          $db->setQuery( $query );
1087          $db->query();
1088          JInstallationHelper::getDBErrors($errors, $db );
1089  
1090          // content section
1091          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET  `link` = INSERT(link, LOCATE("task=", link), 12, "view=section"), `type` = "component", `componentid` = '.$compId.' WHERE `type` = "content_section"';
1092          $db->setQuery( $query );
1093          $db->query();
1094          JInstallationHelper::getDBErrors($errors, $db );
1095  
1096          // get com_newsfeeds id
1097          $query = 'SELECT `id` FROM `'.$newPrefix.'components` WHERE `option`="com_newsfeeds" AND `parent` = 0';
1098          $db->setQuery( $query );
1099          $compId = $db->loadResult();
1100          JInstallationHelper::getDBErrors($errors, $db );
1101  
1102  
1103          // newsfeed categories
1104          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = CONCAT(link, "&view=categories"), `componentid` = '.$compId.' WHERE `type` = "component" AND link LIKE "%option=com_newsfeeds%"';
1105          $db->setQuery( $query );
1106          $db->query();
1107          JInstallationHelper::getDBErrors($errors, $db );
1108  
1109          // newsfeed category table
1110          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = INSERT(link, LOCATE("catid=", link), 5, "view=category&catid"), `type` = "component", `componentid` = '.$compId.' WHERE `type` = "newsfeed_category_table"';
1111          $db->setQuery( $query );
1112          $db->query();
1113          JInstallationHelper::getDBErrors($errors, $db );
1114  
1115          // newsfeed link
1116          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = INSERT(link, LOCATE("task=", link), 9, "view=newsfeed"), `type` = "component", `componentid` = '.$compId.' WHERE `type` = "newsfeed_link"';
1117          $db->setQuery( $query );
1118          $db->query();
1119          JInstallationHelper::getDBErrors($errors, $db );
1120  
1121          // user checkin items
1122          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = INSERT(link, LOCATE("CheckIn", link), 7, "checkin") WHERE `type` = "url" AND link LIKE "%option=com_user&task=CheckIn%"';
1123          $db->setQuery( $query );
1124          $db->query();
1125          JInstallationHelper::getDBErrors($errors, $db );
1126  
1127          // user edit details
1128          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = INSERT(link, LOCATE("UserDetails", link), 11, "edit") WHERE `type` = "url" AND link LIKE "%option=com_user&task=UserDetails%"';
1129          $db->setQuery( $query );
1130          $db->query();
1131          JInstallationHelper::getDBErrors($errors, $db );
1132  
1133          // get com_weblinks id
1134          $query = 'SELECT `id` FROM `'.$newPrefix.'components` WHERE `option`="com_weblinks" AND `parent` = 0';
1135          $db->setQuery( $query );
1136          $compId = $db->loadResult();
1137          JInstallationHelper::getDBErrors($errors, $db );
1138  
1139          // weblinks categories
1140          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = CONCAT(link, "&view=categories"), `componentid` = '.$compId.' WHERE `type` = "component" AND link LIKE "%option=com_weblinks%"';
1141          $db->setQuery( $query );
1142          $db->query();
1143          JInstallationHelper::getDBErrors($errors, $db );
1144  
1145          // weblinks category table
1146          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = INSERT(link, LOCATE("catid=", link), 5, "view=category&catid"), `type` = "component", `componentid` = '.$compId.' WHERE `type` = "weblink_category_table"';
1147          $db->setQuery( $query );
1148          $db->query();
1149          JInstallationHelper::getDBErrors($errors, $db );
1150  
1151          // weblinks submit new item
1152          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = INSERT(link, LOCATE("task=", link), 8, "view=weblink&layout=form") WHERE `type` = "url" AND link LIKE "%option=com_weblinks%"';
1153          $db->setQuery( $query );
1154          $db->query();
1155          JInstallationHelper::getDBErrors($errors, $db );
1156  
1157          // get com_wrapper id
1158          $query = 'SELECT `id` FROM `'.$newPrefix.'components` WHERE `option`="com_wrapper" AND `parent` = 0';
1159          $db->setQuery( $query );
1160          JInstallationHelper::getDBErrors($errors, $db );
1161          $compId = $db->loadResult();
1162  
1163          // wrapper
1164          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = CONCAT(link, "&view=wrapper"), `type` = "component", `componentid` = '.$compId.' WHERE `type` = "wrapper"';
1165          $db->setQuery( $query );
1166          $db->query();
1167          JInstallationHelper::getDBErrors($errors, $db );
1168  
1169          // set default to lowest ordering published on mainmenu
1170          $query = 'SELECT MIN( `ordering` ) FROM `'.$newPrefix.'menu_migration` WHERE `published` = 1 AND `parent` = 0 AND `menutype` = "mainmenu"';
1171          $db->setQuery( $query );
1172          $minorder = $db->loadResult();
1173          if(!$minorder) $minorder = 0;
1174          JInstallationHelper::getDBErrors($errors, $db );
1175          $query = 'SELECT `id` FROM `'.$newPrefix.'menu_migration` WHERE `published` = 1 AND `parent` = 0 AND `menutype` = "mainmenu" AND `ordering` = '.$minorder;
1176          $db->setQuery( $query );
1177          $menuitemid = $db->loadResult();
1178          JInstallationHelper::getDBErrors($errors, $db );
1179          if(!$menuitemid) $menuitemid = 1;
1180          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `home` = 1 WHERE `id` = '.$menuitemid;
1181          $db->setQuery( $query );
1182          $db->query();
1183          JInstallationHelper::getDBErrors($errors, $db );
1184  
1185          // login and log out; component id and link update
1186          $query = 'SELECT id FROM `'.$newPrefix.'components` WHERE link like "option=com_user"';
1187          $db->setQuery($query);
1188          $componentid = $db->loadResult();
1189          JInstallationHelper::getDBErrors($errors, $db );
1190          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET componentid = '.$componentid .' WHERE link = "index.php?option=com_login"';
1191          $db->setQuery($query);
1192          $db->query();
1193          JInstallationHelper::getDBErrors($errors, $db );
1194  
1195          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET link = "index.php?option=com_user&view=login" WHERE link = "index.php?option=com_login"';
1196          $db->setQuery($query);
1197          $db->query();
1198          JInstallationHelper::getDBErrors($errors, $db );
1199  
1200  
1201          // Search - Component ID Update
1202          $query = 'SELECT id FROM `'.$newPrefix.'components` WHERE link like "option=com_search"';
1203          $db->setQuery($query);
1204          $componentid = $db->loadResult();
1205          JInstallationHelper::getDBErrors($errors, $db );
1206          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET componentid = '.$componentid .' WHERE link like "index.php?option=com_search%"';
1207          $db->setQuery($query);
1208          $db->query();
1209          JInstallationHelper::getDBErrors($errors, $db );
1210  
1211          // tidy up urls with Itemids
1212          $query = 'UPDATE `'.$newPrefix.'menu_migration` SET `link` = SUBSTRING(`link`,1,LOCATE("&Itemid",`link`)-1) WHERE `type` = "url" AND `link` LIKE "%&Itemid=%"';
1213          $db->setQuery( $query );
1214          $db->query();
1215          JInstallationHelper::getDBErrors($errors, $db );
1216          $query = 'SELECT DISTINCT `option` FROM '.$newPrefix.'components WHERE `option` != ""';
1217          $db->setQuery( $query );
1218          $lookup = $db->loadResultArray();
1219          JInstallationHelper::getDBErrors($errors, $db );
1220          $lookup[] = 'com_user&';
1221  
1222          // prepare to copy across
1223          $query = 'SELECT * FROM '.$newPrefix.'menu_migration';
1224          $db->setQuery( $query );
1225          $oldMenuItems = $db->loadObjectList();
1226          JInstallationHelper::getDBErrors($errors, $db );
1227  
1228  
1229          $query = 'DELETE FROM '.$newPrefix.'menu WHERE 1';
1230          $db->setQuery( $query );
1231          $db->query();
1232          JInstallationHelper::getDBErrors($errors, $db );
1233          $query = 'SELECT * FROM '.$newPrefix.'menu';
1234          $db->setQuery( $query );
1235  
1236          $newMenuItems = $db->loadObjectList();
1237          JInstallationHelper::getDBErrors($errors, $db );
1238  
1239          // filter out links to 3pd components
1240          foreach( $oldMenuItems as $item )
1241          {
1242              if ( $item->type == 'url' && !strpos( $item->link, 'com_') )
1243              {
1244                  $newMenuItems[] = $item;
1245              }
1246              else if ( $item->type == 'url' && JInstallationHelper::isValidItem( $item->link, $lookup ) )
1247              {
1248                  $newMenuItems[] = $item;
1249              }
1250              else if ( $item->type == 'component' ) //&& JInstallationHelper::isValidItem( $item->link, $lookup ))
1251              {
1252                  // unpublish components that don't exist yet
1253                  if(!JInstallationHelper::isValidItem( $item->link, $lookup )) $item->published = 0;
1254                  $newMenuItems[] = $item;
1255              }
1256          }
1257  
1258          // build the menu table
1259          foreach ( $newMenuItems as $item )
1260          {
1261              $db->insertObject( $newPrefix.'menu', $item );
1262              JInstallationHelper::getDBErrors($errors, $db );
1263          }
1264  
1265          // fix possible orphaned sub menu items
1266          $query = 'UPDATE  `'.$newPrefix.'menu` AS c LEFT OUTER JOIN `'.$newPrefix.'menu` AS p ON c.parent = p.id SET c.parent = 0 WHERE c.parent <> 0 AND p.id IS NULL';
1267          $db->setQuery( $query );
1268          $db->query();
1269          JInstallationHelper::getDBErrors($errors, $db );
1270  
1271          /*
1272           * Construct the menu_type table base on new menu table types
1273           */
1274          $query = 'SELECT DISTINCT `menutype` FROM '.$newPrefix.'menu WHERE 1';
1275          $db->setQuery( $query );
1276          JInstallationHelper::getDBErrors($errors, $db );
1277          $menuTypes = $db->loadResultArray();
1278          $query = 'TRUNCATE TABLE '.$newPrefix.'menu_types';
1279          $db->setQuery($query);
1280  
1281          $db->query();
1282          JInstallationHelper::getDBErrors($errors, $db );
1283  
1284          foreach( $menuTypes as $mType )
1285          {
1286              $query = 'INSERT INTO '.$newPrefix.'menu_types ( menutype, title ) VALUES ("'.$mType.'", "'.$mType.'");';
1287              $db->setQuery($query);
1288              $db->query();
1289              JInstallationHelper::getDBErrors($errors, $db );
1290          }
1291  
1292          /*
1293           * Add core client modules from old site to modules table as unpublished
1294           */
1295          $query = 'SELECT id FROM '.$newPrefix.'modules_migration WHERE client_id = 0 ';
1296          $db->setQuery( $query );
1297          $lookup = $db->loadResultArray();
1298          JInstallationHelper::getDBErrors($errors, $db );
1299  
1300          $query = 'SELECT MAX(id) FROM '.$newPrefix.'modules ';
1301          $db->setQuery( $query );
1302          $nextId = $db->loadResult();
1303          JInstallationHelper::getDBErrors($errors, $db );
1304          jimport('joomla.filesystem.folder');
1305          jimport('joomla.filesystem.file');
1306          foreach( $lookup as $module )
1307          {
1308              $qry = 'SELECT * FROM '.$newPrefix.'modules_migration WHERE id = "'.$module.'" AND client_id = 0';
1309              $db->setQuery( $qry );
1310              if ( $row = $db->loadObject() ) {
1311                  if($row->module == '') { $row->module = 'mod_custom'; }
1312                  if(JFolder::exists(JPATH_SITE.DS.'modules'.DS.$row->module)) {
1313                      $nextId++;
1314                      $oldid = $row->id;
1315                      $row->id = $nextId;
1316                      $row->published = 0;
1317                      if($db->insertObject( $newPrefix.'modules', $row )) {
1318                          // Grab the old modules menu links and put them in too!
1319                          $qry = 'SELECT * FROM '. $newPrefix .'modules_migration_menu WHERE moduleid = '. $oldid;
1320                          $db->setQuery($qry);
1321                          $entries = $db->loadObjectList();
1322                          JInstallationHelper::getDBErrors($errors, $db );
1323  
1324                          foreach($entries as $entry) {
1325                              $entry->moduleid = $nextId;
1326                              $db->insertObject($newPrefix.'modules_menu', $entry);
1327                              JInstallationHelper::getDBErrors($errors, $db );
1328                          }
1329                      } else JInstallationHelper::getDBErrors($errors, $db );
1330                  } // else the module doesn't exist?
1331              } else JInstallationHelper::getDBErrors($errors, $db );
1332          }
1333  
1334          // Put in breadcrumb module as per sample data
1335          $query = "INSERT INTO `".$newPrefix ."modules` VALUES (0, 'Breadcrumbs', '', 1, 'breadcrumb', 0, '0000-00-00 00:00:00', 1, 'mod_breadcrumbs', 0, 0, 1, 'moduleclass_sfx=\ncache=0\nshowHome=1\nhomeText=Home\nshowComponent=1\nseparator=\n\n', 1, 0, '');";
1336          $db->setQuery($query);
1337          $db->Query();
1338          JInstallationHelper::getDBErrors($errors, $db);
1339  
1340          /*
1341           * Clean up
1342           */
1343  
1344          $query = 'DROP TABLE IF EXISTS '.$newPrefix.'modules_migration';
1345          $db->setQuery( $query );
1346          $db->query();
1347          JInstallationHelper::getDBErrors($errors, $db );
1348  
1349          $query = 'DROP TABLE IF EXISTS '.$newPrefix.'modules_migration_menu';
1350          $db->setQuery( $query );
1351          $db->query();
1352          JInstallationHelper::getDBErrors($errors, $db );
1353  
1354          $query = 'DROP TABLE IF EXISTS '.$newPrefix.'menu_migration';
1355          $db->setQuery( $query );
1356          $db->query();
1357          JInstallationHelper::getDBErrors($errors, $db );
1358  
1359          return count( $errors );
1360      }
1361  
1362  	function isValidItem ( $link, $lookup )
1363      {
1364          foreach( $lookup as $component )
1365          {
1366              if ( strpos( $link, $component ) != false )
1367              {
1368                  return true;
1369              }
1370          }
1371          return false;
1372      }
1373  
1374  	function getDBErrors( & $errors, $db )
1375      {
1376          if ($db->getErrorNum() > 0)
1377          {
1378              $errors[] = array('msg' => $db->getErrorMsg(), 'sql' => $db->_sql);
1379          }
1380      }
1381  
1382      /**
1383       * Inserts ftp variables to mainframe registry
1384       * Needed to activate ftp layer for file operations in safe mode
1385       *
1386       * @param array The post values
1387       */
1388  	function setFTPCfg( $vars )
1389      {
1390          global $mainframe;
1391          $arr = array();
1392          $arr['ftp_enable'] = $vars['ftpEnable'];
1393          $arr['ftp_user'] = $vars['ftpUser'];
1394          $arr['ftp_pass'] = $vars['ftpPassword'];
1395          $arr['ftp_root'] = $vars['ftpRoot'];
1396          $arr['ftp_host'] = $vars['ftpHost'];
1397          $arr['ftp_port'] = $vars['ftpPort'];
1398  
1399          $mainframe->setCfg( $arr, 'config' );
1400      }
1401  
1402  	function _chmod( $path, $mode )
1403      {
1404          global $mainframe;
1405          $ret = false;
1406  
1407          // Initialize variables
1408          $ftpFlag    = true;
1409          $ftpRoot    = $mainframe->getCfg('ftp_root');
1410  
1411          // Do NOT use ftp if it is not enabled
1412          if ($mainframe->getCfg('ftp_enable') != 1) {
1413              $ftpFlag = false;
1414          }
1415  
1416          if ($ftpFlag == true)
1417          {
1418              // Connect the FTP client
1419              jimport('joomla.client.ftp');
1420              $ftp = & JFTP::getInstance($mainframe->getCfg('ftp_host'), $mainframe->getCfg('ftp_port'));
1421              $ftp->login($mainframe->getCfg('ftp_user'), $mainframe->getCfg('ftp_pass'));
1422  
1423              //Translate the destination path for the FTP account
1424              $path = JPath::clean(str_replace(JPATH_SITE, $ftpRoot, $path), '/');
1425  
1426              // do the ftp chmod
1427              if (!$ftp->chmod($path, $mode))
1428              {
1429                  // FTP connector throws an error
1430                  return false;
1431              }
1432              $ftp->quit();
1433              $ret = true;
1434          }
1435          else
1436          {
1437              $ret = @ chmod($path, $mode);
1438          }
1439  
1440          return $ret;
1441      }
1442  
1443      /** Borrowed from http://au.php.net/manual/en/ini.core.php comments */
1444  	function let_to_num($v){ //This function transforms the php.ini notation for numbers (like '2M') to an integer (2*1024*1024 in this case)
1445          $l = substr($v, -1);
1446          $ret = substr($v, 0, -1);
1447          switch(strtoupper($l)){
1448          case 'P':
1449              $ret *= 1024;
1450          case 'T':
1451              $ret *= 1024;
1452          case 'G':
1453              $ret *= 1024;
1454          case 'M':
1455              $ret *= 1024;
1456          case 'K':
1457              $ret *= 1024;
1458              break;
1459          }
1460          return $ret;
1461      }
1462  }
1463  ?>


Generated: Wed Mar 28 15:54:07 2012 Cross-referenced by PHPXref 0.7.1