PageRenderTime 56ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/installation/installer/helper.php

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