Replacing database calls with Doctrine

1.10.x
Julio Montoya 11 years ago
parent 82a63e9dac
commit 822d785142
  1. 43
      main/install/index.php
  2. 165
      main/install/install.lib.php
  3. 65
      main/install/install_db.inc.php
  4. 124
      main/install/update-db-1.9.0-1.10.0.inc.php

@ -107,7 +107,6 @@ error_reporting(E_ALL);
$update_from_version_8 = array('1.9.0', '1.9.2','1.9.4','1.9.6', '1.9.6.1', '1.9.8', '1.9.8.1', '1.9.8.2', '1.9.10'); $update_from_version_8 = array('1.9.0', '1.9.2','1.9.4','1.9.6', '1.9.6.1', '1.9.8', '1.9.8.1', '1.9.8.2', '1.9.10');
$my_old_version = ''; $my_old_version = '';
$tmp_version = get_config_param('dokeos_version');
if (empty($tmp_version)) { if (empty($tmp_version)) {
$tmp_version = get_config_param('system_version'); $tmp_version = get_config_param('system_version');
} }
@ -115,8 +114,6 @@ if (!empty($_POST['old_version'])) {
$my_old_version = $_POST['old_version']; $my_old_version = $_POST['old_version'];
} elseif (!empty($tmp_version)) { } elseif (!empty($tmp_version)) {
$my_old_version = $tmp_version; $my_old_version = $tmp_version;
} elseif (!empty($dokeos_version)) { //variable coming from installedVersion, normally
$my_old_version = $dokeos_version;
} }
require_once __DIR__.'/version.php'; require_once __DIR__.'/version.php';
@ -720,7 +717,6 @@ if (@$_POST['step2']) {
if ($installType == 'update') { if ($installType == 'update') {
remove_memory_and_time_limits(); remove_memory_and_time_limits();
//database_server_connect();
$manager = testDbConnect( $manager = testDbConnect(
$dbHostForm, $dbHostForm,
$dbUsernameForm, $dbUsernameForm,
@ -728,32 +724,11 @@ if (@$_POST['step2']) {
$dbNameForm $dbNameForm
); );
// Initialization of the database connection encoding intentionaly is not done.
// This is the old style for connecting to the database server, that is implemented here.
$perm = api_get_permissions_for_new_directories(); $perm = api_get_permissions_for_new_directories();
$perm_file = api_get_permissions_for_new_files(); $perm_file = api_get_permissions_for_new_files();
if (empty($my_old_version)) { $my_old_version = '1.8.6.2'; } //we guess
$_configuration['main_database'] = $dbNameForm;
Log::notice('Starting migration process from '.$my_old_version.' ('.time().')'); Log::notice('Starting migration process from '.$my_old_version.' ('.time().')');
if ($userPasswordCrypted == '1') {
$userPasswordCrypted = 'md5';
} elseif ($userPasswordCrypted == '0') {
$userPasswordCrypted = 'none';
}
Database::query("SET storage_engine = MYISAM;");
if (version_compare($my_old_version, '1.8.7', '>=')) {
Database::query("SET SESSION character_set_server='utf8';");
Database::query("SET SESSION collation_server='utf8_general_ci';");
//Database::query("SET CHARACTER SET 'utf8';"); // See task #1802.
Database::query("SET NAMES 'utf8';");
}
switch ($my_old_version) { switch ($my_old_version) {
case '1.9.0': case '1.9.0':
case '1.9.2': case '1.9.2':
@ -764,6 +739,7 @@ if (@$_POST['step2']) {
case '1.9.8.1': case '1.9.8.1':
case '1.9.8.2': case '1.9.8.2':
case '1.9.10': case '1.9.10':
case '1.9.10.2':
include 'update-db-1.9.0-1.10.0.inc.php'; include 'update-db-1.9.0-1.10.0.inc.php';
include 'update-files-1.9.0-1.10.0.inc.php'; include 'update-files-1.9.0-1.10.0.inc.php';
//Only updates the configuration.inc.php with the new version //Only updates the configuration.inc.php with the new version
@ -775,23 +751,8 @@ if (@$_POST['step2']) {
} else { } else {
set_file_folder_permissions(); set_file_folder_permissions();
$manager = testDbConnect( $manager = require 'install_db.inc.php';
$dbHostForm,
$dbUsernameForm,
$dbPassForm,
$dbNameForm
);
// Initialization of the database encoding to be used.
Database::query("SET storage_engine = INNODB;");
//Database::query("SET SESSION character_set_server='utf8';");
//Database::query("SET SESSION collation_server='utf8_general_ci';");
//Database::query("SET CHARACTER SET 'utf8';"); // See task #1802.
//Database::query("SET NAMES 'utf8';");
include 'install_db.inc.php';
include 'install_files.inc.php'; include 'install_files.inc.php';
} }
display_after_install_message($installType); display_after_install_message($installType);
//Hide the "please wait" message sent previously //Hide the "please wait" message sent previously

@ -614,29 +614,6 @@ function get_config_param_from_db($host, $login, $pass, $dbName, $param = '')
return null; return null;
} }
/**
* Connects to the database server.
*/
function database_server_connect()
{
global $dbHostForm, $dbUsernameForm, $dbPassForm;
if (($res = @Database::connect(array('server' => $dbHostForm, 'username' => $dbUsernameForm, 'password' => $dbPassForm))) === false) {
$no = Database::errno();
$msg = Database::error();
echo '<hr />#'.$no.': '.$msg.'<hr />';
echo get_lang('DBServerDoesntWorkOrLoginPassIsWrong').'.<br /><br />'.
get_lang('PleaseCheckTheseValues').' :<br /><br />'.
'<strong>'.get_lang('DBHost').'</strong> : '.$dbHostForm.'<br />'.
'<strong>'.get_lang('DBLogin').'</strong> : '.$dbUsernameForm.'<br />'.
'<strong>'.get_lang('DBPassword').'</strong> : '.$dbPassForm.'<br /><br />'.
get_lang('PleaseGoBackToStep').' '. (defined('SYSTEM_INSTALLATION') ? '3' : '1').'.'.
'<p><button type="submit" class="btn btn-default" name="step'. (defined('SYSTEM_INSTALLATION') ? '3' : '1').'" value="&lt; '.get_lang('Back').'"><i class="fa fa-backward"> </i>'.get_lang('Back').'</button></p>'.
'</td></tr></table></form></body></html>';
exit ();
}
@Database::query("set session sql_mode='';"); // Disabling special SQL modes (MySQL 5)
}
/** /**
* In step 3. Tests establishing connection to the database server. * In step 3. Tests establishing connection to the database server.
* If it's a single database environment the function checks if the database exist. * If it's a single database environment the function checks if the database exist.
@ -662,23 +639,6 @@ function testDbConnect($dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm)
return $database->getManager(); return $database->getManager();
} }
/**
* Fills the countries table with a list of countries.
* @param string $trackCountriesTable Table name
*/
function fill_track_countries_table($trackCountriesTable)
{
$file_path = dirname(__FILE__).'/'.COUNTRY_DATA_FILENAME;
$countries = file($file_path);
$addCountrySql = "INSERT INTO $trackCountriesTable (id, code, country, counter) VALUES ";
foreach ($countries as $line) {
$elems = explode(',', $line);
$addCountrySql .= '('.intval($elems[0]).',\''.Database::escape_string($elems[1]).'\',\''.Database::escape_string($elems[2]).'\','.intval($elems[3]).'),';
}
$addCountrySql = substr($addCountrySql, 0, -1);
@Database::query($addCountrySql);
}
/** /**
* Creates the structure of the main database and fills it * Creates the structure of the main database and fills it
* with data. Placeholder symbols in the main database file * with data. Placeholder symbols in the main database file
@ -688,7 +648,7 @@ function fill_track_countries_table($trackCountriesTable)
* @param string $dbScript optional path about the script for database * @param string $dbScript optional path about the script for database
* @return void * @return void
*/ */
function load_main_database($installation_settings, $dbScript = '') function createSchema($manager, $installation_settings, $dbScript = '')
{ {
$sql_text = null; $sql_text = null;
if (!empty($dbScript)) { if (!empty($dbScript)) {
@ -702,122 +662,15 @@ function load_main_database($installation_settings, $dbScript = '')
} }
} }
//replace symbolic parameters with user-specified values //replace symbolic parameters with user-specified values
foreach ($installation_settings as $key => $value) { foreach ($installation_settings as $key => $value) {
$sql_text = str_replace($key, Database::escape_string($value), $sql_text); $sql_text = str_replace($key, Database::escape_string($value), $sql_text);
} }
global $manager;
$result = $manager->getConnection()->prepare($sql_text); $result = $manager->getConnection()->prepare($sql_text);
$result->execute(); $result->execute();
} }
/**
* Get an SQL file's contents
*
* This function bases its parsing on the pre-set format of the specific SQL files in
* the install/upgrade procedure:
* Lines starting with "--" are comments (but need to be taken into account as they also hold sections names)
* Other lines are considered to be one-line-per-query lines (this is checked quickly by this function)
* @param string File to parse (in the current directory)
* @param string Section to return
* @param boolean Print (true) or hide (false) error texts when they occur
* @return array Array of SQL statements
*/
function get_sql_file_contents($file, $section, $print_errors = true)
{
//check given parameters
if (empty($file)) {
$error = "Missing name of file to parse in get_sql_file_contents()";
if ($print_errors) {
echo $error;
}
return false;
}
if (!in_array($section, array('main', 'user', 'stats', 'scorm', 'course'))) {
$error = "Section '$section' is not authorized in get_sql_file_contents()";
if ($print_errors) {
echo $error;
}
return false;
}
$filePath = getcwd().'/'.$file;
if (!is_file($filePath) or !is_readable($filePath)) {
$error = "File $filePath not found or not readable in get_sql_file_contents()";
if ($print_errors) {
echo $error;
}
return false;
}
//read the file in an array
// Empty lines should not be executed as SQL statements, because errors occur, see Task #2167.
$fileContents = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (!is_array($fileContents) or count($fileContents) < 1) {
$error = "File $filePath looks empty in get_sql_file_contents()";
if ($print_errors) {
echo $error;
}
return false;
}
//prepare the resulting array
$section_contents = array();
$record = false;
foreach ($fileContents as $index => $line) {
if (substr($line, 0, 2) == '--') {
//This is a comment. Check if section name, otherwise ignore
$result = array();
if (preg_match('/^-- xx([A-Z]*)xx/', $line, $result)) { //we got a section name here
if ($result[1] == strtoupper($section)) {
//we have the section we are looking for, start recording
$record = true;
} else {
//we have another section's header. If we were recording, stop now and exit loop
if ($record) {
break;
}
$record = false;
}
}
} else {
if ($record) {
if (!empty($line)) {
$section_contents[] = $line;
}
}
}
}
//now we have our section's SQL statements group ready, return
return $section_contents;
}
/**
* Adds a new document to the database - specific to version 1.8.0
*
* @param array $_course
* @param string $path
* @param string $fileType
* @param int $fileSize
* @param string $title
* @return id if inserted document
*/
function add_document_180($_course, $path, $fileType, $fileSize, $title, $comment = null)
{
$table_document = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
$sql = "INSERT INTO $table_document
(`path`,`filetype`,`size`,`title`, `comment`)
VALUES ('$path','$fileType','$fileSize','".
Database::escape_string($title)."', '$comment')";
if (Database::query($sql)) {
//display_message("Added to database (id ".Database::insert_id().")!");
return Database::insert_id();
} else {
//display_error("The uploaded file could not be added to the database (".Database::error().")!");
return false;
}
}
/* DISPLAY FUNCTIONS */ /* DISPLAY FUNCTIONS */
/** /**
@ -1368,10 +1221,8 @@ function display_requirements(
echo '<li>'.$value.'</li>'; echo '<li>'.$value.'</li>';
} }
echo '</ul>'; echo '</ul>';
} } elseif (file_exists(api_get_path(CONFIGURATION_PATH).'configuration.php')) {
// Check wether a Chamilo configuration file already exists. // Check wether a Chamilo configuration file already exists.
elseif (file_exists(api_get_path(CONFIGURATION_PATH).'configuration.php')) {
echo '<div class="warning-message"><h4><center>'; echo '<div class="warning-message"><h4><center>';
echo get_lang('WarningExistingLMSInstallationDetected'); echo get_lang('WarningExistingLMSInstallationDetected');
echo '</center></h4></div>'; echo '</center></h4></div>';
@ -1713,7 +1564,6 @@ function display_database_settings_form(
$database_exists_text = ''; $database_exists_text = '';
$manager = null; $manager = null;
try { try {
$manager = testDbConnect( $manager = testDbConnect(
$dbHostForm, $dbHostForm,
$dbUsernameForm, $dbUsernameForm,
@ -1721,13 +1571,8 @@ function display_database_settings_form(
null null
); );
$databases = $manager->getConnection()->getSchemaManager()->listDatabases(); $databases = $manager->getConnection()->getSchemaManager()->listDatabases();
if (in_array($dbNameForm, $databases)) { if (in_array($dbNameForm, $databases)) {
$database_exists_text = '<div class="warning-message">'.get_lang('ADatabaseWithTheSameNameAlreadyExists').'</div>'; $database_exists_text = '<div class="warning-message">'.get_lang('ADatabaseWithTheSameNameAlreadyExists').'</div>';
} else {
$manager->getConnection()->getSchemaManager()->createDatabase(
$dbNameForm
);
} }
} catch (Exception $e) { } catch (Exception $e) {
$database_exists_text = $e->getMessage(); $database_exists_text = $e->getMessage();
@ -1988,7 +1833,9 @@ function display_after_install_message($installType)
echo '</div>'; echo '</div>';
?></form> ?></form>
<br /> <br />
<a class="btn btn-success btn-large btn-install" href="../../index.php"><?php echo get_lang('GoToYourNewlyCreatedPortal'); ?></a> <a class="btn btn-success btn-large btn-install" href="../../index.php">
<?php echo get_lang('GoToYourNewlyCreatedPortal'); ?>
</a>
<?php <?php
} }
@ -2043,7 +1890,7 @@ function get_countries_list_from_array($combo = false)
/** /**
* Lock settings that can't be changed in other portals * Lock settings that can't be changed in other portals
*/ */
function locking_settings() function lockSettings()
{ {
$access_url_locked_settings = api_get_locked_settings(); $access_url_locked_settings = api_get_locked_settings();
$table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT); $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);

@ -32,51 +32,35 @@ switch ($encryptPassForm) {
break; break;
} }
$dbPrefixForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbPrefixForm); $manager = testDbConnect(
$dbHostForm,
$dbUsernameForm,
$dbPassForm,
null
);
$dbNameForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbNameForm); $dbNameForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbNameForm);
if (!empty($dbPrefixForm) && strpos($dbNameForm, $dbPrefixForm) !== 0) {
$dbNameForm = $dbPrefixForm . $dbNameForm;
}
$dbStatsForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbStatsForm);
if (!empty($dbPrefixForm) && strpos($dbStatsForm, $dbPrefixForm) !== 0) {
$dbStatsForm = $dbPrefixForm . $dbStatsForm;
}
$dbUserForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbUserForm);
if (!empty($dbPrefixForm) && strpos($dbUserForm, $dbPrefixForm) !== 0) {
$dbUserForm = $dbPrefixForm . $dbUserForm;
}
$mysqlMainDb = $dbNameForm;
if (empty($mysqlMainDb) || $mysqlMainDb == 'mysql' || $mysqlMainDb == $dbPrefixForm) {
$mysqlMainDb = $dbPrefixForm . 'main';
}
//This parameter is needed to run a command line to install Chamilo using BNPanel + ISPConfig see #1799 //This parameter is needed to run a command line to install Chamilo using BNPanel + ISPConfig see #1799
if (!defined('CLI_INSTALLATION')) { if (!defined('CLI_INSTALLATION')) {
$createDatabase = true;
$result = Database::query("SHOW VARIABLES LIKE 'datadir'") or die(Database::error());
$mysqlRepositorySys = Database::fetch_array($result);
$mysqlRepositorySys = $mysqlRepositorySys['Value'];
$create_database = true;
/** @var \Doctrine\ORM\EntityManager $manager */
global $manager;
$databases = $manager->getConnection()->getSchemaManager()->listDatabases(); $databases = $manager->getConnection()->getSchemaManager()->listDatabases();
if (in_array($mysqlMainDb, $databases)) { if (in_array($dbNameForm, $databases)) {
$create_database = false; $createDatabase = false;
} }
// Create database // Create database
if ($create_database) { if ($createDatabase) {
$manager->getConnection()->getSchemaManager()->createDatabase($mysqlMainDb); $manager->getConnection()->getSchemaManager()->createDatabase($dbNameForm);
/*$sql = "CREATE DATABASE IF NOT EXISTS `$mysqlMainDb`";
Database::query($sql) or die(Database::error());*/
} }
$manager = testDbConnect(
$dbHostForm,
$dbUsernameForm,
$dbPassForm,
$dbNameForm
);
} }
// This parameter is needed to run a command line install of Chamilo (needed for Phing) // This parameter is needed to run a command line install of Chamilo (needed for Phing)
@ -107,8 +91,17 @@ $installation_settings['{HASHFUNCTIONMODE}'] = $encryptPassForm;
AddCourse::drop_course_tables(); AddCourse::drop_course_tables();
load_main_database($installation_settings); // Initialization of the database encoding to be used.
Database::query("SET storage_engine = INNODB;");
Database::query("SET SESSION character_set_server='utf8';");
Database::query("SET SESSION collation_server='utf8_general_ci';");
Database::query("SET CHARACTER SET 'utf8';"); // See task #1802.
//Database::query("SET NAMES 'utf8';");
createSchema($manager, $installation_settings);
locking_settings(); lockSettings();
update_dir_and_files_permissions(); update_dir_and_files_permissions();
return $manager;

@ -45,10 +45,6 @@ if (defined('SYSTEM_INSTALLATION')) {
// that we want to change the main databases as well... // that we want to change the main databases as well...
$onlyTest = false; $onlyTest = false;
if (defined('SYSTEM_INSTALLATION')) { if (defined('SYSTEM_INSTALLATION')) {
/**
* Update the databases "pre" migration
*/
include_once '../lang/english/trad4all.inc.php'; include_once '../lang/english/trad4all.inc.php';
if ($languageForm != 'english') { if ($languageForm != 'english') {
@ -56,123 +52,21 @@ if (defined('SYSTEM_INSTALLATION')) {
include_once '../lang/' . $languageForm . '/trad4all.inc.php'; include_once '../lang/' . $languageForm . '/trad4all.inc.php';
} }
// Get the main queries list (m_q_list) // PRE
$sqlFile = 'migrate-db-' . $oldFileVersion . '-' . $newFileVersion . '-pre.sql';
$mainQueriesList = get_sql_file_contents($sqlFile, 'main');
if (count($mainQueriesList) > 0) {
// Now use the $mainQueriesList
/**
* We connect to the right DB first to make sure we can use the queries
* without a database name
*/
if (strlen($dbNameForm) > 40) {
Log::error('Database name ' . $dbNameForm . ' is too long, skipping');
} elseif (!in_array($dbNameForm, $dblist)) {
Log::error('Database ' . $dbNameForm . ' was not found, skipping');
} else {
foreach ($mainQueriesList as $query) {
if ($onlyTest) {
Log::notice("iDatabase::query($dbNameForm,$query)");
} else {
$res = iDatabase::query($query);
if ($res === false) {
Log::error('Error in ' . $query . ': ' . iDatabase::error());
}
}
}
}
}
if (INSTALL_TYPE_UPDATE == 'update') {
// Updating track tables with c_id -> moved to migrate-db
}
}
// Get the courses databases queries list (c_q_list)
$sqlFile = 'migrate-db-' . $oldFileVersion . '-' . $newFileVersion . '-pre.sql'; $sqlFile = 'migrate-db-' . $oldFileVersion . '-' . $newFileVersion . '-pre.sql';
$courseQueriesList = get_sql_file_contents($sqlFile, 'course');
Log::notice('Starting migration: '.$oldFileVersion.' - '.$newFileVersion); Log::notice('Starting migration: '.$oldFileVersion.' - '.$newFileVersion);
$sql = file_get_contents($sqlFile);
$result = $manager->getConnection()->prepare($sql);
$result->execute();
if (count($courseQueriesList) > 0) { // Do something in between
// Get the courses list
if (strlen($dbNameForm) > 40) {
Log::error('Database name '.$dbNameForm.' is too long, skipping');
} elseif (!in_array($dbNameForm, $dblist)) {
Log::error('Database '.$dbNameForm.' was not found, skipping');
} else {
$res = iDatabase::query(
"SELECT id, code, db_name, directory, course_language, id as real_id "
." FROM course WHERE target_course_code IS NULL ORDER BY code"
);
if ($res === false) {
die('Error while querying the courses list in update_db-1.9.0-1.10.0.inc.php');
}
$errors = array();
if (iDatabase::num_rows($res) > 0) { // POST
$i = 0;
$list = array();
while ($row = iDatabase::fetch_array($res)) {
$list[] = $row;
$i++;
}
foreach ($list as $rowCourse) {
Log::notice('Course db ' . $rowCourse['db_name']);
// Now use the $c_q_list
foreach ($courseQueriesList as $query) {
if ($singleDbForm) {
$query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$rowCourse['db_name']}_$2$3", $query);
}
if ($onlyTest) {
Log::notice("iDatabase::query(".$rowCourse['db_name'].",$query)");
} else {
$res = iDatabase::query($query);
if ($res === false) {
Log::error('Error in '.$query.': '.iDatabase::error());
}
}
}
Log::notice('<<<------- end -------->>');
}
}
}
}
// Get the main queries *POST* list (m_q_list)
$sqlFile = 'migrate-db-' . $oldFileVersion . '-' . $newFileVersion . '-post.sql'; $sqlFile = 'migrate-db-' . $oldFileVersion . '-' . $newFileVersion . '-post.sql';
$mainQueriesList = get_sql_file_contents($sqlFile, 'main'); $sql = file_get_contents($sqlFile);
$result = $manager->getConnection()->prepare($sql);
if (count($mainQueriesList) > 0) { $result->execute();
// Now use the $mainQueriesList
/**
* We connect to the right DB first to make sure we can use the queries
* without a database name
*/
if (strlen($dbNameForm) > 40) {
Log::error('Database name ' . $dbNameForm . ' is too long, skipping');
} elseif (!in_array($dbNameForm, $dblist)) {
Log::error('Database ' . $dbNameForm . ' was not found, skipping');
} else {
foreach ($mainQueriesList as $query) {
if ($onlyTest) {
Log::notice("iDatabase::query($dbNameForm,$query)");
} else {
$res = iDatabase::query($query);
if ($res === false) {
Log::error('Error in ' . $query . ': ' . iDatabase::error());
} }
}
}
}
}
} else { } else {
echo 'You are not allowed here !' . __FILE__; echo 'You are not allowed here !' . __FILE__;
} }

Loading…
Cancel
Save