[*] IN : the installer can now attempt to create the database for you

This commit is contained in:
Damien Metzger
2013-07-03 11:04:34 +02:00
parent 92959311d9
commit bfa2f33c65
6 changed files with 380 additions and 313 deletions
+14 -1
View File
@@ -52,6 +52,18 @@ class DbMySQLiCore extends Db
return $this->link; return $this->link;
} }
public static function createDatabase($host, $user, $password, $dbname)
{
if (strpos($host, ':') !== false)
{
list($host, $port) = explode(':', $host);
$link = @new mysqli($host, $this->user, $this->password, null, $port);
}
else
$link = @new mysqli($host, $user, $password);
return $link->query('CREATE DATABASE `'.bqSQL($dbname).'`');
}
/** /**
* @see DbCore::disconnect() * @see DbCore::disconnect()
@@ -169,7 +181,8 @@ class DbMySQLiCore extends Db
if (!$link->options(MYSQLI_OPT_CONNECT_TIMEOUT, $timeout)) if (!$link->options(MYSQLI_OPT_CONNECT_TIMEOUT, $timeout))
return 1; return 1;
if (!$link->real_connect($server, $user, $pwd, $db)) // There is an @ because mysqli throw a warning when the database does not exists
if (!@$link->real_connect($server, $user, $pwd, $db))
return (mysqli_connect_errno() == 1049) ? 2 : 1; return (mysqli_connect_errno() == 1049) ? 2 : 1;
$link->close(); $link->close();
+263 -253
View File
@@ -1,253 +1,263 @@
<?php <?php
/* /*
* 2007-2013 PrestaShop * 2007-2013 PrestaShop
* *
* NOTICE OF LICENSE * NOTICE OF LICENSE
* *
* This source file is subject to the Open Software License (OSL 3.0) * This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt. * that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL: * It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php * http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to * If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email * obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately. * to license@prestashop.com so we can send you a copy immediately.
* *
* DISCLAIMER * DISCLAIMER
* *
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your * versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information. * needs please refer to http://www.prestashop.com for more information.
* *
* @author PrestaShop SA <contact@prestashop.com> * @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2013 PrestaShop SA * @copyright 2007-2013 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA * International Registered Trademark & Property of PrestaShop SA
*/ */
/** /**
* This class is currently only here for tests * This class is currently only here for tests
* *
* @since 1.5.0 * @since 1.5.0
*/ */
class DbPDOCore extends Db class DbPDOCore extends Db
{ {
protected static function _getPDO($host, $user, $password, $dbname, $timeout = 5) protected static function _getPDO($host, $user, $password, $dbname, $timeout = 5)
{ {
$dsn = 'mysql:'; $dsn = 'mysql:';
if ($dbname) if ($dbname)
$dsn .= 'dbname='.$dbname.';'; $dsn .= 'dbname='.$dbname.';';
if (preg_match('/^(.*):([0-9]+)$/', $host, $matches)) if (preg_match('/^(.*):([0-9]+)$/', $host, $matches))
$dsn .= 'host='.$matches[1].';port='.$matches[2]; $dsn .= 'host='.$matches[1].';port='.$matches[2];
elseif (preg_match('#^.*:(/.*)$#', $host, $matches)) elseif (preg_match('#^.*:(/.*)$#', $host, $matches))
$dsn .= 'unix_socket='.$matches[1]; $dsn .= 'unix_socket='.$matches[1];
else else
$dsn .= 'host='.$host; $dsn .= 'host='.$host;
return new PDO($dsn, $user, $password, array(PDO::ATTR_TIMEOUT => $timeout, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true)); return new PDO($dsn, $user, $password, array(PDO::ATTR_TIMEOUT => $timeout, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
} }
/** public static function createDatabase($host, $user, $password, $dbname)
* @see DbCore::connect() {
*/ try {
public function connect() $link = DbPDO::_getPDO($host, $user, $password, false);
{ return $link->exec('CREATE DATABASE `'.bqSQL($dbname).'`');
try { } catch (PDOException $e) {
$this->link = $this->_getPDO($this->server, $this->user, $this->password, $this->database, 5); return false;
} catch (PDOException $e) { }
die(sprintf(Tools::displayError('Link to database cannot be established: %s'), utf8_encode($e->getMessage()))); }
}
/**
// UTF-8 support * @see DbCore::connect()
if ($this->link->exec('SET NAMES \'utf8\'') === false) */
die(Tools::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.')); public function connect()
{
return $this->link; try {
} $this->link = $this->_getPDO($this->server, $this->user, $this->password, $this->database, 5);
} catch (PDOException $e) {
/** die(sprintf(Tools::displayError('Link to database cannot be established: %s'), utf8_encode($e->getMessage())));
* @see DbCore::disconnect() }
*/
public function disconnect() // UTF-8 support
{ if ($this->link->exec('SET NAMES \'utf8\'') === false)
unset($this->link); die(Tools::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.'));
}
return $this->link;
/** }
* @see DbCore::_query()
*/ /**
protected function _query($sql) * @see DbCore::disconnect()
{ */
return $this->link->query($sql); public function disconnect()
} {
unset($this->link);
/** }
* @see DbCore::nextRow()
*/ /**
public function nextRow($result = false) * @see DbCore::_query()
{ */
if (!$result) protected function _query($sql)
$result = $this->result; {
return $result->fetch(PDO::FETCH_ASSOC); return $this->link->query($sql);
} }
/** /**
* @see DbCore::_numRows() * @see DbCore::nextRow()
*/ */
protected function _numRows($result) public function nextRow($result = false)
{ {
return $result->rowCount(); if (!$result)
} $result = $this->result;
return $result->fetch(PDO::FETCH_ASSOC);
/** }
* @see DbCore::Insert_ID()
*/ /**
public function Insert_ID() * @see DbCore::_numRows()
{ */
return $this->link->lastInsertId(); protected function _numRows($result)
} {
return $result->rowCount();
/** }
* @see DbCore::Affected_Rows()
*/ /**
public function Affected_Rows() * @see DbCore::Insert_ID()
{ */
return $this->result->rowCount(); public function Insert_ID()
} {
return $this->link->lastInsertId();
/** }
* @see DbCore::getMsgError()
*/ /**
public function getMsgError($query = false) * @see DbCore::Affected_Rows()
{ */
$error = $this->link->errorInfo(); public function Affected_Rows()
return ($error[0] == '00000') ? '' : $error[2]; {
} return $this->result->rowCount();
}
/**
* @see DbCore::getNumberError() /**
*/ * @see DbCore::getMsgError()
public function getNumberError() */
{ public function getMsgError($query = false)
$error = $this->link->errorInfo(); {
return isset($error[1]) ? $error[1] : 0; $error = $this->link->errorInfo();
} return ($error[0] == '00000') ? '' : $error[2];
}
/**
* @see DbCore::getVersion() /**
*/ * @see DbCore::getNumberError()
public function getVersion() */
{ public function getNumberError()
return $this->getValue('SELECT VERSION()'); {
} $error = $this->link->errorInfo();
return isset($error[1]) ? $error[1] : 0;
/** }
* @see DbCore::_escape()
*/ /**
public function _escape($str) * @see DbCore::getVersion()
{ */
$search = array("\\", "\0", "\n", "\r", "\x1a", "'", '"'); public function getVersion()
$replace = array("\\\\", "\\0", "\\n", "\\r", "\Z", "\'", '\"'); {
return str_replace($search, $replace, $str); return $this->getValue('SELECT VERSION()');
} }
/** /**
* @see DbCore::set_db() * @see DbCore::_escape()
*/ */
public function set_db($db_name) public function _escape($str)
{ {
return $this->link->exec('USE '.pSQL($db_name)); $search = array("\\", "\0", "\n", "\r", "\x1a", "'", '"');
} $replace = array("\\\\", "\\0", "\\n", "\\r", "\Z", "\'", '\"');
return str_replace($search, $replace, $str);
/** }
* @see Db::hasTableWithSamePrefix()
*/ /**
public static function hasTableWithSamePrefix($server, $user, $pwd, $db, $prefix) * @see DbCore::set_db()
{ */
try { public function set_db($db_name)
$link = DbPDO::_getPDO($server, $user, $pwd, $db, 5); {
} catch (PDOException $e) { return $this->link->exec('USE '.pSQL($db_name));
return false; }
}
/**
$sql = 'SHOW TABLES LIKE \''.$prefix.'%\''; * @see Db::hasTableWithSamePrefix()
$result = $link->query($sql); */
return (bool)$result->fetch(); public static function hasTableWithSamePrefix($server, $user, $pwd, $db, $prefix)
} {
try {
public static function checkCreatePrivilege($server, $user, $pwd, $db, $prefix, $engine = null) $link = DbPDO::_getPDO($server, $user, $pwd, $db, 5);
{ } catch (PDOException $e) {
try { return false;
$link = DbPDO::_getPDO($server, $user, $pwd, $db, 5); }
} catch (PDOException $e) {
return false; $sql = 'SHOW TABLES LIKE \''.$prefix.'%\'';
} $result = $link->query($sql);
return (bool)$result->fetch();
$sql = ' }
CREATE TABLE `'.$prefix.'test` (
`test` tinyint(1) unsigned NOT NULL public static function checkCreatePrivilege($server, $user, $pwd, $db, $prefix, $engine = null)
) ENGINE=MyISAM'; {
$result = $link->query($sql); try {
if (!$result) $link = DbPDO::_getPDO($server, $user, $pwd, $db, 5);
{ } catch (PDOException $e) {
$error = $link->errorInfo(); return false;
return $error[2]; }
}
$link->query('DROP TABLE `'.$prefix.'test`'); $sql = '
return true; CREATE TABLE `'.$prefix.'test` (
} `test` tinyint(1) unsigned NOT NULL
) ENGINE=MyISAM';
/** $result = $link->query($sql);
* @see Db::checkConnection() if (!$result)
*/ {
public static function tryToConnect($server, $user, $pwd, $db, $newDbLink = true, $engine = null, $timeout = 5) $error = $link->errorInfo();
{ return $error[2];
try { }
$link = DbPDO::_getPDO($server, $user, $pwd, $db, $timeout); $link->query('DROP TABLE `'.$prefix.'test`');
} catch (PDOException $e) { return true;
return ($e->getCode() == 1049) ? 2 : 1; }
}
unset($link); /**
return 0; * @see Db::checkConnection()
} */
public static function tryToConnect($server, $user, $pwd, $db, $newDbLink = true, $engine = null, $timeout = 5)
public function getBestEngine() {
{ try {
$value = 'InnoDB'; $link = DbPDO::_getPDO($server, $user, $pwd, $db, $timeout);
} catch (PDOException $e) {
$sql = 'SHOW VARIABLES WHERE Variable_name = \'have_innodb\''; return ($e->getCode() == 1049) ? 2 : 1;
$result = $this->link->query($sql); }
if (!$result) unset($link);
$value = 'MyISAM'; return 0;
$row = $result->fetch(); }
if (!$row || strtolower($row['Value']) != 'yes')
$value = 'MyISAM'; public function getBestEngine()
{
/* MySQL >= 5.6 */ $value = 'InnoDB';
$sql = 'SHOW ENGINES';
$result = $this->link->query($sql); $sql = 'SHOW VARIABLES WHERE Variable_name = \'have_innodb\'';
while ($row = $result->fetch()) $result = $this->link->query($sql);
if ($row['Engine'] == 'InnoDB') if (!$result)
{ $value = 'MyISAM';
if (in_array($row['Support'], array('DEFAULT', 'YES'))) $row = $result->fetch();
$value = 'InnoDB'; if (!$row || strtolower($row['Value']) != 'yes')
break; $value = 'MyISAM';
}
return $value; /* MySQL >= 5.6 */
} $sql = 'SHOW ENGINES';
$result = $this->link->query($sql);
/** while ($row = $result->fetch())
* @see Db::checkEncoding() if ($row['Engine'] == 'InnoDB')
*/ {
public static function tryUTF8($server, $user, $pwd) if (in_array($row['Support'], array('DEFAULT', 'YES')))
{ $value = 'InnoDB';
try { break;
$link = DbPDO::_getPDO($server, $user, $pwd, false, 5); }
} catch (PDOException $e) { return $value;
return false; }
}
$result = $link->exec('SET NAMES \'utf8\''); /**
unset($link); * @see Db::checkEncoding()
*/
return ($result === false) ? false : true; public static function tryUTF8($server, $user, $pwd)
} {
} try {
$link = DbPDO::_getPDO($server, $user, $pwd, false, 5);
} catch (PDOException $e) {
return false;
}
$result = $link->exec('SET NAMES \'utf8\'');
unset($link);
return ($result === false) ? false : true;
}
}
+6
View File
@@ -46,6 +46,12 @@ class MySQLCore extends Db
return $this->link; return $this->link;
} }
public static function createDatabase($host, $user, $password, $dbname)
{
$link = mysql_connect($host, $user, $password);
return mysql_query('CREATE DATABASE `'.bqSQL($dbname).'`');
}
/** /**
* @see DbCore::disconnect() * @see DbCore::disconnect()
+11 -19
View File
@@ -95,8 +95,8 @@ class InstallControllerHttpDatabase extends InstallControllerHttp
{ {
if (Tools::getValue('checkDb')) if (Tools::getValue('checkDb'))
$this->processCheckDb(); $this->processCheckDb();
else if (Tools::getValue('sendMail')) elseif (Tools::getValue('createDb'))
$this->processSendMail(); $this->processCreateDb();
} }
/** /**
@@ -120,28 +120,20 @@ class InstallControllerHttpDatabase extends InstallControllerHttp
} }
/** /**
* Send a test email * Attempt to create the database
*/ */
public function processSendMail() public function processCreateDb()
{ {
$smtp_checked = (Tools::getValue('smtpChecked') == 'true'); $server = Tools::getValue('dbServer');
$server = Tools::getValue('smtpSrv'); $database = Tools::getValue('dbName');
$encryption = Tools::getValue('smtpEnc'); $login = Tools::getValue('dbLogin');
$port = Tools::getValue('smtpPort'); $password = Tools::getValue('dbPassword');
$login = Tools::getValue('smtpLogin');
$password = Tools::getValue('smtpPassword');
$email = Tools::getValue('testEmail');
require_once _PS_INSTALL_MODELS_PATH_.'mail.php'; $success = $this->model_database->createDatabase($server, $database, $login, $password);
$this->model_mail = new InstallModelMail($smtp_checked, $server, $login, $password, $port, $encryption, $email);
$result = $this->model_mail->send(
$this->l('Test message from PrestaShop'),
$this->l('This is a test message, your server is now available to send email')
);
$this->ajaxJsonAnswer( $this->ajaxJsonAnswer(
$result === false, $success,
($result === false) ? $this->l('A test e-mail has been sent to %s', $email) : $this->l('An error occurred while sending email, please verify your parameters') $success ? $this->l('Database is created') : $this->l('Cannot create the database automatically')
); );
} }
+10 -1
View File
@@ -81,7 +81,10 @@ class InstallModelDatabase extends InstallAbstractModel
break; break;
case 2: case 2:
$errors[] = $this->language->l('Connection to MySQL server succeeded, but database "%s" not found', $database).$dbtype; $errors[] = $this->language->l('Connection to MySQL server succeeded, but database "%s" not found', $database).$dbtype.'<br /><br />
'.sprintf('<input type="button" value="%s" class="button" id="btCreateDB">
<script type="text/javascript">bindCreateDB();</script>',
$this->language->l('Attempt to create the database automatically'));
break; break;
} }
} }
@@ -89,6 +92,12 @@ class InstallModelDatabase extends InstallAbstractModel
return $errors; return $errors;
} }
public function createDatabase($server, $database, $login, $password)
{
$class = Db::getClass();
return $class::createDatabase($server, $login, $password, $database);
}
public function getBestEngine($server, $database, $login, $password) public function getBestEngine($server, $database, $login, $password)
{ {
$class = Db::getClass(); $class = Db::getClass();
+76 -39
View File
@@ -1,39 +1,76 @@
$(document).ready(function() $(document).ready(function()
{ {
// Check database configuration // Check database configuration
$('#btTestDB').click(function() $('#btTestDB').click(function()
{ {
$("#dbResultCheck").slideUp('slow'); $("#dbResultCheck").slideUp('slow');
$.ajax({ $.ajax({
url: 'index.php', url: 'index.php',
data: { data: {
'checkDb': 'true', 'checkDb': 'true',
'dbServer': $('#dbServer').val(), 'dbServer': $('#dbServer').val(),
'dbName': $('#dbName').val(), 'dbName': $('#dbName').val(),
'dbLogin': $('#dbLogin').val(), 'dbLogin': $('#dbLogin').val(),
'dbPassword': $('#dbPassword').val(), 'dbPassword': $('#dbPassword').val(),
'dbEngine': $('#dbEngine').val(), 'dbEngine': $('#dbEngine').val(),
'db_prefix': $('#db_prefix').val(), 'db_prefix': $('#db_prefix').val(),
'clear': $('#db_clear').prop('checked') ? '1' : '0' 'clear': $('#db_clear').prop('checked') ? '1' : '0'
}, },
dataType: 'json', dataType: 'json',
cache: false, cache: false,
success: function(json) success: function(json)
{ {
$("#dbResultCheck") $("#dbResultCheck")
.addClass((json.success) ? 'okBlock' : 'errorBlock') .addClass((json.success) ? 'okBlock' : 'errorBlock')
.removeClass((json.success) ? 'errorBlock' : 'okBlock') .removeClass((json.success) ? 'errorBlock' : 'okBlock')
.html(json.message) .html(json.message)
.slideDown('slow'); .slideDown('slow');
}, },
error: function(xhr) error: function(xhr)
{ {
$("#dbResultCheck") $("#dbResultCheck")
.addClass('errorBlock') .addClass('errorBlock')
.removeClass('okBlock') .removeClass('okBlock')
.html('An error occurred:<br /><br />'+xhr.responseText) .html('An error occurred:<br /><br />' + xhr.responseText)
.slideDown('slow'); .slideDown('slow');
} }
}); });
}); });
}); });
function bindCreateDB()
{
// Attempt to create the database
$('#btCreateDB').click(function()
{
$("#dbResultCheck").slideUp('fast');
$.ajax({
url: 'index.php',
data: {
'createDb': 'true',
'dbServer': $('#dbServer').val(),
'dbName': $('#dbName').val(),
'dbLogin': $('#dbLogin').val(),
'dbPassword': $('#dbPassword').val()
},
dataType: 'json',
cache: false,
success: function(json)
{
$("#dbResultCheck")
.addClass((json.success) ? 'okBlock' : 'errorBlock')
.removeClass((json.success) ? 'errorBlock' : 'okBlock')
.html(json.message)
.slideDown('slow');
},
error: function(xhr)
{
$("#dbResultCheck")
.addClass('errorBlock')
.removeClass('okBlock')
.html('An error occurred:<br /><br />' + xhr.responseText)
.slideDown('slow');
}
});
});
}