Browse Source

Remove unused code.

Julio Montoya 10 years ago
parent
commit
c670521de3

+ 0 - 44
main/inc/global.inc.php

@@ -54,18 +54,6 @@ if (!isset($GLOBALS['_configuration'])) {
     $GLOBALS['_configuration'] = $_configuration;
 }
 
-// Code for trnasitional purposes, it can be removed right before the 1.8.7 release.
-if (empty($_configuration['system_version'])) {
-    $_configuration['system_version']   = $_configuration['dokeos_version'];
-    $_configuration['system_stable']    = $_configuration['dokeos_stable'];
-    $_configuration['software_url']     = 'http://www.chamilo.org/';
-}
-
-// For backward compatibility.
-$_configuration['dokeos_version']   = $_configuration['system_version'];
-$_configuration['dokeos_stable']    = $_configuration['system_stable'];
-$userPasswordCrypted                = $_configuration['password_encryption'];
-
 // Include the main Chamilo platform library file.
 require_once $includePath.'/lib/api.lib.php';
 
@@ -130,19 +118,8 @@ $params = array(
     'client_flags' => $dbFlags,
 );
 
-if (!$_configuration['db_host']) {
-    $global_error_code = 4;
-    // A configuration option about database server is missing.
-    require $includePath.'/global_error_message.inc.php';
-    die();
-}
-
 // Doctrine ORM configuration
 
-use Doctrine\ORM\Tools\Setup;
-use Doctrine\ORM\EntityManager;
-
-// the connection configuration
 $dbParams = array(
     'driver' => 'pdo_mysql',
     'host' => $_configuration['db_host'],
@@ -204,16 +181,6 @@ if (!empty($_configuration['multiple_access_urls'])) {
     $_configuration['access_url'] = 1;
 }
 
-// The system has not been designed to use special SQL modes that were introduced since MySQL 5.
-Database::query("set session sql_mode='';");
-
-/*if (!Database::select_db($_configuration['main_database'], $database_connection)) {
-    $global_error_code = 5;
-    // Connection to the main Chamilo database is impossible, it might be missing or restricted or its configuration option might be incorrect.
-    require $includePath.'/global_error_message.inc.php';
-    die();
-}*/
-
 /* Initialization of the default encodings */
 // The platform's character set must be retrieved at this early moment.
 $sql = "SELECT selected_value FROM settings_current WHERE variable = 'platform_charset';";
@@ -232,17 +199,6 @@ api_initialize_internationalization();
 // Initialization of the default encoding that will be used by the multibyte string routines in the internationalization library.
 api_set_internationalization_default_encoding($charset);
 
-// Initialization of the database encoding to be used.
-Database::query("SET SESSION character_set_server='utf8';");
-Database::query("SET SESSION collation_server='utf8_general_ci';");
-
-if (api_is_utf8($charset)) {
-    // See Bug #1802: For UTF-8 systems we prefer to use "SET NAMES 'utf8'" statement in order to avoid a bizarre problem with Chinese language.
-    Database::query("SET NAMES 'utf8';");
-} else {
-    Database::query("SET CHARACTER SET '" . Database::to_db_encoding($charset) . "';");
-}
-
 // Start session after the internationalization library has been initialized.
 Chamilo::session()->start($already_installed);
 

+ 42 - 579
main/inc/lib/database.lib.php

@@ -53,7 +53,7 @@ class Database
      * Please, define table names as constants in this library and use them
      * instead of directly using magic words in your tool code.
      *
-     * @param string $short_table_name, the name of the table
+     * @param string $table, the name of the table
      */
     public static function get_main_table($table)
     {
@@ -67,37 +67,23 @@ class Database
      * Please, define table names as constants in this library and use them
      * instead of directly using magic words in your tool code.
      *
-     * @param string $short_table_name, the name of the table
-     * @param string $database_name, optional, name of the course database
-     * - if you don't specify this, you work on the current course.
+     * @param string $table, the name of the table
      */
-    public static function get_course_table($table, $extra = null)
+    public static function get_course_table($table)
     {
         return DB_COURSE_PREFIX.$table;
-        /*
-        //forces fatal errors so we can debug more easily
-        if (!empty($extra)) {
-            var_dump($extra);
-            //@todo remove this
-            echo "<h3>Dev Message: get_course_table() doesn't have a 2nd parameter</h3>";
-            //exit;
-        }
-        return self::format_table_name(self::get_main_database(), DB_COURSE_PREFIX.$short_table_name);*/
     }
 
-    /*
-        Query methods
-        These methods execute a query and return the result(s).
-    */
-
     /**
      * Counts the number of rows in a table
      * @param string $table The table of which the rows should be counted
      * @return int The number of rows in the given table.
      * @deprecated
      */
-    public static function count_rows($table) {
+    public static function count_rows($table)
+    {
         $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table"));
+
         return $obj->n;
     }
 
@@ -107,29 +93,21 @@ class Database
 
     /**
      * Returns the number of affected rows in the last database operation.
-     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
-     * @return int                              Returns the number of affected rows on success, and -1 if the last query failed.
+     * @param Statement $result
+     *
+     * @return int
      */
     public static function affected_rows(Statement $result)
     {
         return $result->rowCount();
-        //return self::use_default_connection($connection) ? mysql_affected_rows() : mysql_affected_rows($connection);
-    }
-
-    /**
-     * Closes non-persistent database connection.
-     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
-     * @return bool                             Returns TRUE on success or FALSE on failure.
-     */
-    public static function close($connection = null) {
-        return self::use_default_connection($connection) ? mysql_close() : mysql_close($connection);
     }
 
     /**
      * @param array $params
+     *
      * @throws \Doctrine\ORM\ORMException
      */
-    public function connect($params = array())
+    public function connect($params = [])
     {
         $config = self::getDoctrineConfig();
         $config->setEntityNamespaces(
@@ -140,6 +118,7 @@ class Database
             )
         );
 
+        $params['charset'] = 'utf8';
         $entityManager = EntityManager::create($params, $config);
 
         // Registering Constraints
@@ -192,16 +171,6 @@ class Database
             : mysql_connect($server, $username, $password, $new_link, $client_flags);*/
     }
 
-    /**
-     * Returns error number from the last operation done on the database server.
-     * @param resource $connection (optional)   The database server connection,
-     * for detailed description see the method query().
-     * @return int Returns the error number from the last database (operation, or 0 (zero) if no error occurred.
-     */
-    public static function errno($connection = null) {
-        return self::use_default_connection($connection) ? mysql_errno() : mysql_errno($connection);
-    }
-
     /**
      * Returns error text from the last operation done on the database server.
      * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
@@ -226,28 +195,17 @@ class Database
 
     /**
      * Escapes a string to insert into the database as text
-     * @param string    $string The string to escape
-     * @param resource  $connection (optional)   The database server connection, for detailed description see the method query().
-     * @param bool $addFix
-     * @return string   he escaped string
-     * @author Yannick Warnier <yannick.warnier@beeznest.com>
-     * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+     * @param $string
+     *
+     * @return string
      */
-    public static function escape_string($string, $connection = null, $addFix = true)
+    public static function escape_string($string)
     {
         $string = self::getManager()->getConnection()->quote($string);
-        return trim($string, "'");
 
-        /*return get_magic_quotes_gpc()
-            ? (self::use_default_connection($connection)
-                ? mysql_real_escape_string(stripslashes($string))
-                : mysql_real_escape_string(stripslashes($string), $connection))
-            : (self::use_default_connection($connection)
-                ? mysql_real_escape_string($string)
-                : mysql_real_escape_string($string, $connection));-*/
+        return trim($string, "'");
     }
 
-
     /**
      * Gets the array from a SQL result (as returned by Database::query) - help achieving database independence
      * @param resource      The result from a call to sql_query (e.g. Database::query)
@@ -260,9 +218,8 @@ class Database
         if ($result === false) {
             return array();
         }
+
         return $result->fetch(self::customOptionToDoctrineOption($option));
-        //if ($result === false) { return array(); }
-        //return $option == 'ASSOC' ? mysql_fetch_array($result, MYSQL_ASSOC) : ($option == 'NUM' ? mysql_fetch_array($result, MYSQL_NUM) : mysql_fetch_array($result));
     }
 
     /**
@@ -274,33 +231,28 @@ class Database
     public static function fetch_assoc(Statement $result)
     {
         return $result->fetch(PDO::FETCH_ASSOC);
-        //return mysql_fetch_assoc($result);
     }
 
     /**
      * Gets the next row of the result of the SQL query (as returned by Database::query) in an object form
-     * @param   resource    The result from a call to sql_query (e.g. Database::query)
-     * @param   string      Optional class name to instanciate
-     * @param   array       Optional array of parameters
-     * @return  object      Object of class StdClass or the required class, containing the query result row
-     * @author  Yannick Warnier <yannick.warnier@beeznest.com>
+     *
+     * @param Statement $result
+     * @return mixed
      */
-    //public static function fetch_object($result, $class = null, $params = null) {
     public static function fetch_object(Statement $result)
     {
         return $result->fetch(PDO::FETCH_OBJ);
-        //return !empty($class) ? (is_array($params) ? mysql_fetch_object($result, $class, $params) : mysql_fetch_object($result, $class)) : mysql_fetch_object($result);
     }
 
     /**
      * Gets the array from a SQL result (as returned by Database::query) - help achieving database independence
-     * @param resource      The result from a call to sql_query (see Database::query()).
-     * @return array        Array of results as returned by php (mysql_fetch_row)
+     * @param Statement $result
+     *
+     * @return mixed
      */
     public static function fetch_row(Statement $result)
     {
         return $result->fetch(PDO::FETCH_NUM);
-        //return mysql_fetch_row($result);
     }
 
     /**
@@ -312,288 +264,62 @@ class Database
     public static function free_result(Statement $result)
     {
         $result->closeCursor();
-        //return mysql_free_result($result);
-    }
-
-    /**
-     * Returns the database client library version.
-     * @return strung       Returns a string that represents the client library version.
-     */
-    public static function get_client_info() {
-        return mysql_get_client_info();
-    }
-
-    /**
-     * Returns a list of databases created on the server. The list may contain all of the
-     * available database names or filtered database names by using a pattern.
-     * @param string $pattern (optional)        A pattern for filtering database names as if it was needed for the SQL's LIKE clause, for example 'chamilo_%'.
-     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
-     * @return array                            Returns in an array the retrieved list of database names.
-     */
-    public static function get_databases($pattern = '', $connection = null) {
-        $result = array();
-        $query_result = Database::query(!empty($pattern) ? "SHOW DATABASES LIKE '".self::escape_string($pattern, $connection)."'" : "SHOW DATABASES", $connection);
-        while ($row = Database::fetch_row($query_result)) {
-            $result[] = $row[0];
-        }
-        return $result;
-    }
-
-    /**
-     * Returns information about the type of the current connection and the server host name.
-     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
-     * @return string/boolean                   Returns string data on success or FALSE on failure.
-     */
-    public static function get_host_info($connection = null) {
-        return self::use_default_connection($connection) ? mysql_get_host_info() : mysql_get_host_info($connection);
-    }
-
-    /**
-     * Retrieves database client/server protocol version.
-     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
-     * @return int/boolean                      Returns the protocol version on success or FALSE on failure.
-     */
-    public static function get_proto_info($connection = null) {
-        return self::use_default_connection($connection) ? mysql_get_proto_info() : mysql_get_proto_info($connection);
-    }
-
-    /**
-     * Retrieves the database server version.
-     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
-     * @return string/boolean                   Returns the MySQL server version on success or FALSE on failure.
-     */
-    public static function get_server_info($connection = null) {
-        return self::use_default_connection($connection) ? mysql_get_server_info() : mysql_get_server_info($connection);
-    }
-
-    /**
-     * Returns a list of tables within a database. The list may contain all of the
-     * available table names or filtered table names by using a pattern.
-     * @param string $database (optional)       The name of the examined database. If it is omited, the current database is assumed, see Database::select_db().
-     * @param string $pattern (optional)        A pattern for filtering table names as if it was needed for the SQL's LIKE clause, for example 'access_%'.
-     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
-     * @return array                            Returns in an array the retrieved list of table names.
-     */
-    public static function get_tables($database = '', $pattern = '', $connection = null) {
-        $result = array();
-        $query = "SHOW TABLES";
-        if (!empty($database)) {
-            $query .= " FROM `".self::escape_string($database, $connection)."`";
-        }
-        if (!empty($pattern)) {
-            $query .= " LIKE '".self::escape_string($pattern, $connection)."'";
-        }
-        $query_result = Database::query($query, $connection);
-        while ($row = Database::fetch_row($query_result)) {
-            $result[] = $row[0];
-        }
-        return $result;
     }
 
     /**
      * Gets the ID of the last item inserted into the database
-     * This should be updated to use ADODB at some point
-     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
-     * @return int                              The last ID as returned by the DB function
+     * @return string
      */
     public static function insert_id()
     {
         return self::getManager()->getConnection()->lastInsertId();
-        //return self::use_default_connection($connection) ? mysql_insert_id() : mysql_insert_id($connection);
     }
 
     /**
-     * Gets the number of rows from the last query result - help achieving database independence
-     * @param resource      The result
-     * @return integer      The number of rows contained in this result
-     * @author Yannick Warnier <yannick.warnier@beeznest.com>
-     **/
+     * @param Statement $result
+     *
+     * @return int
+     */
     public static function num_rows(Statement $result)
     {
         return $result->rowCount();
-        //return is_resource($result) ? mysql_num_rows($result) : false;
     }
 
     /**
      * Acts as the relative *_result() function of most DB drivers and fetches a
      * specific line and a field
-     * @param   resource    The database resource to get data from
-     * @param   integer     The row number
-     * @param   string      Optional field name or number
-     * @return  mixed       One cell of the result, or FALSE on error
+     *
+     * @param Statement $resource
+     * @param int $row
+     * @param string $field
+     *
+     * @return mixed
      */
     public static function result(Statement $resource, $row, $field = '')
     {
         if ($resource->rowCount() > 0) {
             $result = $resource->fetchAll(PDO::FETCH_BOTH);
+
             return $result[$row][$field];
         }
-        //return self::num_rows($resource) > 0 ? (!empty($field) ? mysql_result($resource, $row, $field) : mysql_result($resource, $row)) : null;
     }
 
     /**
-     * This method returns a resource
-     * Documentation has been added by Arthur Portugal
-     * Some adaptations have been implemented by Ivan Tcholakov, 2009, 2010
-     * @author Olivier Brouckaert
-     * @param string $query                     The SQL query
-     * @param resource $connection (optional)   The database server (MySQL) connection.
-     * If it is not specified, the connection opened by mysql_connect() is assumed.
-     * If no connection is found, the server will try to create one as if mysql_connect() was called with no arguments.
-     * If no connection is found or established, an E_WARNING level error is generated.
-     * @param string $file (optional)           On error it shows the file in which the error has been trigerred (use the "magic" constant __FILE__ as input parameter)
-     * @param string $line (optional)           On error it shows the line in which the error has been trigerred (use the "magic" constant __LINE__ as input parameter)
+     * @param $query
+     * @return Statement
      *
-     * @return Statement                         The returned result from the query
-     *
-     * Note: The parameter $connection could be skipped. Here are examples of this method usage:
-     * Database::query($query);
-     * $result = Database::query($query);
-     * Database::query($query, $connection);
-     * $result = Database::query($query, $connection);
-     * The following ways for calling this method are obsolete:
-     * Database::query($query, __FILE__, __LINE__);
-     * $result = Database::query($query, __FILE__, __LINE__);
-     * Database::query($query, $connection, __FILE__, __LINE__);
-     * $result = Database::query($query, $connection, __FILE__, __LINE__);
+     * @throws \Doctrine\DBAL\DBALException
      */
-    public static function query($query, $connection = null, $file = null, $line = null)
+    public static function query($query)
     {
         $result = self::getManager()->getConnection()->executeQuery($query);
 
         return $result;
-
-        $use_default_connection = self::use_default_connection($connection);
-        if ($use_default_connection) {
-            // Let us do parameter shifting, thus the method would be similar
-            // (in regard to parameter order) to the original function mysql_query().
-            $line = $file;
-            $file = $connection;
-            $connection = null;
-        }
-
-        // Check if the table contains a c_ (means a course id)
-        if (api_get_setting('server_type') === 'test' && strpos($query, 'c_')) {
-            //Check if the table contains inner joins
-            if (
-                strpos($query, 'assoc_handle') === false &&
-                strpos($query, 'olpc_peru_filter') === false &&
-                strpos($query, 'allow_public_certificates') === false &&
-                strpos($query, 'DROP TABLE IF EXISTS') === false &&
-                strpos($query, 'thematic_advance') === false &&
-                strpos($query, 'thematic_plan') === false &&
-                strpos($query, 'track_c_countries') === false &&
-                strpos($query, 'track_c_os') === false &&
-                strpos($query, 'track_c_providers') === false &&
-                strpos($query, 'track_c_referers') === false &&
-                strpos($query, 'track_c_browsers') === false &&
-                strpos($query, 'settings_current') === false &&
-                strpos($query, 'dokeos_classic_2D') === false &&
-                strpos($query, 'cosmic_campus') === false &&
-                strpos($query, 'static_') === false &&
-                strpos($query, 'public_admin') === false &&
-                strpos($query, 'chamilo_electric_blue') === false &&
-                strpos($query, 'specific_field') === false &&
-                strpos($query, 'down_doc_path') === false &&
-                strpos($query, 'INNER JOIN') === false &&
-                strpos($query, 'inner join') === false &&
-                strpos($query, 'left join') === false &&
-                strpos($query, 'LEFT JOIN') === false &&
-                strpos($query, 'insert') === false &&
-                strpos($query, 'INSERT') === false &&
-                strpos($query, 'ALTER') === false &&
-                strpos($query, 'alter') === false &&
-                strpos($query, 'c_id') === false &&
-                strpos($query, 'create table') === false &&
-                strpos($query, 'CREATE TABLE') === false &&
-                strpos($query, 'AUTO_INCREMENT') === false
-            ) {
-                //@todo remove this
-                echo '<pre>';
-                $message = '<h4>Dev message: please add the c_id field in this query or report this error in support.chamilo.org </h4>';
-                $message .= $query;
-                echo $message;
-                echo '</pre>';
-                //error_log($message);
-            }
-        }
-
-        if (!($result = $use_default_connection ? mysql_query($query) : mysql_query($query, $connection))) {
-            $backtrace = debug_backtrace(); // Retrieving information about the caller statement.
-            if (isset($backtrace[0])) {
-                $caller = & $backtrace[0];
-            } else {
-                $caller = array();
-            }
-            if (isset($backtrace[1])) {
-                $owner = & $backtrace[1];
-            } else {
-                $owner = array();
-            }
-            if (empty($file)) {
-                $file = $caller['file'];
-            }
-            if (empty($line) && $line !== false) {
-                $line = $caller['line'];
-            }
-            $type = isset($owner['type']) ? $owner['type'] : null;
-            $function = $owner['function'];
-            $class = isset($owner['class']) ? $owner['class'] : null;
-            $server_type = api_get_setting('server_type');
-            if (!empty($line) && !empty($server_type) && $server_type != 'production') {
-                $info = '<pre>' .
-                    '<strong>DATABASE ERROR #'.self::errno($connection).':</strong><br /> ' .
-                    self::remove_XSS(self::error($connection)) . '<br />' .
-                    '<strong>QUERY       :</strong><br /> ' .
-                    self::remove_XSS($query) . '<br />' .
-                    '<strong>FILE        :</strong><br /> ' .
-                    (empty($file) ? ' unknown ' : $file) . '<br />' .
-                    '<strong>LINE        :</strong><br /> ' .
-                    (empty($line) ? ' unknown ' : $line) . '<br />';
-                if (empty($type)) {
-                    if (!empty($function)) {
-                        $info .= '<strong>FUNCTION    :</strong><br /> ' . $function;
-                    }
-                } else {
-                    if (!empty($class) && !empty($function)) {
-                        $info .= '<strong>CLASS       :</strong><br /> ' . $class . '<br />';
-                        $info .= '<strong>METHOD      :</strong><br /> ' . $function;
-                    }
-                }
-                $info .= '</pre>';
-                echo $info;
-            }
-
-            if (isset(self::$log_queries) && self::$log_queries) {
-                error_log("----------------  SQL error ---------------- ");
-                error_log($query);
-
-                error_log('error #'.self::errno($connection));
-                error_log('error: '.self::error($connection));
-
-                $info = 'FILE: ' .(empty($file) ? ' unknown ' : $file);
-                $info .= ' +'.(empty($line) ? ' unknown ' : $line);
-                error_log($info);
-
-                if (empty($type)) {
-                    if (!empty($function)) {
-                        $info = 'FUNCTION: ' . $function;
-                        error_log($info);
-                    }
-                } else {
-                    if (!empty($class) && !empty($function)) {
-                        $info = 'CLASS: ' . $class.' METHOD: '.$function;
-                        error_log($info);
-                    }
-                }
-                error_log("---------------- end ----------------");
-            }
-        }
-        return $result;
     }
 
     /**
      * @param string $option
+     *
      * @return int
      */
     public static function customOptionToDoctrineOption($option)
@@ -612,16 +338,6 @@ class Database
         }
     }
 
-    /**
-     * Selects a database.
-     * @param string $database_name             The name of the database that is to be selected.
-     * @param resource $connection (optional)   The database server connection, for detailed description see the method query().
-     * @return bool                             Returns TRUE on success or FALSE on failure.
-     */
-    public static function select_db($database_name, $connection = null) {
-        return self::use_default_connection($connection) ? mysql_select_db($database_name) : mysql_select_db($database_name, $connection);
-    }
-
     /**
      * Stores a query result into an array.
      *
@@ -633,238 +349,6 @@ class Database
     public static function store_result(Statement $result, $option = 'BOTH')
     {
         return $result->fetchAll(self::customOptionToDoctrineOption($option));
-
-        $array = array();
-        if ($result !== false) { // For isolation from database engine's behaviour.
-            while ($row = self::fetch_array($result, $option)) {
-                $array[] = $row;
-            }
-        }
-        return $array;
-    }
-
-    /*
-        Encodings and collations supported by MySQL database server
-    */
-
-    /**
-     * Checks whether a given encoding is supported by the database server.
-     * @param string $encoding  The encoding (a system conventional id, for example 'UTF-8') to be checked.
-     * @return bool             Returns a boolean value as a check-result.
-     * @author Ivan Tcholakov
-     */
-    public static function is_encoding_supported($encoding) {
-        static $supported = array();
-        if (!isset($supported[$encoding])) {
-            $supported[$encoding] = false;
-            if (strlen($db_encoding = self::to_db_encoding($encoding)) > 0) {
-                if (self::num_rows(self::query("SHOW CHARACTER SET WHERE Charset =  '".self::escape_string($db_encoding)."';")) > 0) {
-                    $supported[$encoding] = true;
-                }
-            }
-        }
-        return $supported[$encoding];
-    }
-
-    /**
-     * Constructs a SQL clause about default character set and default collation for newly created databases and tables.
-     * Example: Database::make_charset_clause('UTF-8', 'bulgarian') returns
-     *  DEFAULT CHARACTER SET `utf8` DEFAULT COLLATE `utf8_general_ci`
-     * @param string $encoding (optional)   The default database/table encoding (a system conventional id) to be used.
-     * @param string $language (optional)   Language (a system conventional id) used for choosing language sensitive collation (if it is possible).
-     * @return string                       Returns the constructed SQL clause or empty string if $encoding is not correct or is not supported.
-     * @author Ivan Tcholakov
-     */
-    public static function make_charset_clause($encoding = null, $language = null) {
-        if (empty($encoding)) {
-            $encoding = api_get_system_encoding();
-        }
-        if (empty($language)) {
-            $language = api_get_interface_language();
-        }
-        $charset_clause = '';
-        if (self::is_encoding_supported($encoding)) {
-            $db_encoding = Database::to_db_encoding($encoding);
-            $charset_clause .= " DEFAULT CHARACTER SET `".$db_encoding."`";
-            $db_collation = Database::to_db_collation($encoding, $language);
-            if (!empty($db_collation)) {
-                $charset_clause .= " DEFAULT COLLATE `".$db_collation."`";
-            }
-        }
-        return $charset_clause;
-    }
-
-    /**
-     * Converts an encoding identificator to MySQL-specific encoding identifictor,
-     * i.e. 'UTF-8' --> 'utf8'.
-     * @param string $encoding  The conventional encoding identificator.
-     * @return string           Returns the corresponding MySQL-specific encoding identificator if any, otherwise returns NULL.
-     * @author Ivan Tcholakov
-     */
-    public static function to_db_encoding($encoding) {
-        static $result = array();
-        if (!isset($result[$encoding])) {
-            $result[$encoding] = null;
-            $encoding_map = & self::get_db_encoding_map();
-            foreach ($encoding_map as $key => $value) {
-                if (api_equal_encodings($encoding, $key)) {
-                    $result[$encoding] = $value;
-                    break;
-                }
-            }
-        }
-        return $result[$encoding];
-    }
-
-    /**
-     * Converts a MySQL-specific encoding identifictor to conventional encoding identificator,
-     * i.e. 'utf8' --> 'UTF-8'.
-     * @param string $encoding  The MySQL-specific encoding identificator.
-     * @return string           Returns the corresponding conventional encoding identificator if any, otherwise returns NULL.
-     * @author Ivan Tcholakov
-     */
-    public static function from_db_encoding($db_encoding) {
-        static $result = array();
-        if (!isset($result[$db_encoding])) {
-            $result[$db_encoding] = null;
-            $encoding_map = & self::get_db_encoding_map();
-            foreach ($encoding_map as $key => $value) {
-                if (strtolower($db_encoding) == $value) {
-                    $result[$db_encoding] = $key;
-                    break;
-                }
-            }
-        }
-        return $result[$db_encoding];
-    }
-
-    /**
-     * Chooses the default MySQL-specific collation from given encoding and language.
-     * @param string $encoding              A conventional encoding id, i.e. 'UTF-8'
-     * @param string $language (optional)   A conventional for the system language id, i.e. 'bulgarian'. If it is empty, the chosen collation is the default server value corresponding to the given encoding.
-     * @return string                       Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
-     * @author Ivan Tcholakov
-     */
-    public static function to_db_collation($encoding, $language = null) {
-        static $result = array();
-        if (!isset($result[$encoding][$language])) {
-            $result[$encoding][$language] = null;
-            if (self::is_encoding_supported($encoding)) {
-                $db_encoding = self::to_db_encoding($encoding);
-                if (!empty($language)) {
-                    $lang = api_purify_language_id($language);
-                    $res = self::check_db_collation($db_encoding, $lang);
-                    if (empty($res)) {
-                        $db_collation_map = & self::get_db_collation_map();
-                        if (isset($db_collation_map[$lang])) {
-                            $res = self::check_db_collation($db_encoding, $db_collation_map[$lang]);
-                        }
-                    }
-                    if (empty($res)) {
-                        $res = self::check_db_collation($db_encoding, null);
-                    }
-                    $result[$encoding][$language] = $res;
-                } else {
-                    $result[$encoding][$language] = self::check_db_collation($db_encoding, null);
-                }
-            }
-        }
-        return $result[$encoding][$language];
-    }
-
-    /*
-        Private methods
-        You should not access these from outside the class
-        No effort is made to keep the names / results the same.
-    */
-
-    /**
-     * This private method is to be used by the other methods in this class for
-     * checking whether the input parameter $connection actually has been provided.
-     * If the input parameter connection is not a resource or if it is not FALSE (in case of error)
-     * then the default opened connection should be used by the called method.
-     * @param resource/boolean $connection  The checked parameter $connection.
-     * @return boolean                      TRUE means that calling method should use the default connection.
-     *                                      FALSE means that (valid) parameter $connection has been provided and it should be used.
-     */
-    private static function use_default_connection($connection) {
-        return !is_resource($connection) && $connection !== false;
-    }
-
-    /**
-     * This private method encapsulates a table with relations between
-     * conventional and MuSQL-specific encoding identificators.
-     * @author Ivan Tcholakov
-     */
-    private static function & get_db_encoding_map() {
-        static $encoding_map = array(
-            'ARMSCII-8'    => 'armscii8',
-            'BIG5'         => 'big5',
-            'BINARY'       => 'binary',
-            'CP866'        => 'cp866',
-            'EUC-JP'       => 'ujis',
-            'EUC-KR'       => 'euckr',
-            'GB2312'       => 'gb2312',
-            'GBK'          => 'gbk',
-            'ISO-8859-1'   => 'latin1',
-            'ISO-8859-2'   => 'latin2',
-            'ISO-8859-7'   => 'greek',
-            'ISO-8859-8'   => 'hebrew',
-            'ISO-8859-9'   => 'latin5',
-            'ISO-8859-13'  => 'latin7',
-            'ISO-8859-15'  => 'latin1',
-            'KOI8-R'       => 'koi8r',
-            'KOI8-U'       => 'koi8u',
-            'SHIFT-JIS'    => 'sjis',
-            'TIS-620'      => 'tis620',
-            'US-ASCII'     => 'ascii',
-            'UTF-8'        => 'utf8',
-            'WINDOWS-1250' => 'cp1250',
-            'WINDOWS-1251' => 'cp1251',
-            'WINDOWS-1252' => 'latin1',
-            'WINDOWS-1256' => 'cp1256',
-            'WINDOWS-1257' => 'cp1257'
-        );
-        return $encoding_map;
-    }
-
-    /**
-     * A helper language id translation table for choosing some collations.
-     * @author Ivan Tcholakov
-     */
-    private static function & get_db_collation_map() {
-        static $db_collation_map = array(
-            'german' => 'german2',
-            'simpl_chinese' => 'chinese',
-            'trad_chinese' => 'chinese',
-            'turkce' => 'turkish'
-        );
-        return $db_collation_map;
-    }
-
-    /**
-     * Constructs a MySQL-specific collation and checks whether it is supported by the database server.
-     * @param string $db_encoding   A MySQL-specific encoding id, i.e. 'utf8'
-     * @param string $language      A MySQL-compatible language id, i.e. 'bulgarian'
-     * @return string               Returns a suitable default collation, for example 'utf8_general_ci', or NULL if collation was not found.
-     * @author Ivan Tcholakov
-     */
-    private static function check_db_collation($db_encoding, $language) {
-        if (empty($db_encoding)) {
-            return null;
-        }
-        if (empty($language)) {
-            $result = self::fetch_array(self::query("SHOW COLLATION WHERE Charset = '".self::escape_string($db_encoding)."' AND  `Default` = 'Yes';"), 'NUM');
-            return $result ? $result[0] : null;
-        }
-        $collation = $db_encoding.'_'.$language.'_ci';
-        $query_result = self::query("SHOW COLLATION WHERE Charset = '".self::escape_string($db_encoding)."';");
-        while ($result = self::fetch_array($query_result, 'NUM')) {
-            if ($result[0] == $collation) {
-                return $collation;
-            }
-        }
-        return null;
     }
 
     /**
@@ -878,31 +362,9 @@ class Database
     {
         $result = self::getManager()->getConnection()->insert($table_name, $attributes);
         if ($result) {
-            return self::insert_id();
-        }
-        return false;
 
-        if (empty($attributes) || empty($table_name)) {
-            return false;
-        }
-        $filtred_attributes = array();
-        foreach($attributes as $key => $value) {
-            $filtred_attributes[$key] = "'".self::escape_string($value)."'";
-        }
-
-        //@todo check if the field exists in the table we should use a describe of that table
-        $params = array_keys($filtred_attributes);
-        $values = array_values($filtred_attributes);
-        if (!empty($params) && !empty($values)) {
-            $sql    = 'INSERT INTO '.$table_name.' ('.implode(',',$params).') VALUES ('.implode(',',$values).')';
-            self::query($sql);
-            if ($show_query) {
-                var_dump($sql);
-                error_log($sql);
-            }
             return self::insert_id();
         }
-        return false;
     }
 
     /**
@@ -943,6 +405,7 @@ class Database
         } else {
             $array = self::fetch_array($result, $option);
         }
+
         return $array;
     }
 

+ 3 - 3
main/inc/lib/diagnoser.lib.php

@@ -225,13 +225,13 @@ class Diagnoser
 
         // A note: Maybe it would be better if all "MySQL"-like variable names and words on the page to be replaced with "Database"-like ones.
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_host_info()', 'http://www.php.net/manual/en/function.mysql-get-host-info.php', Database::get_host_info(), null, null, get_lang('MysqlHostInfo'));
-
+        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'host', 'http://www.php.net/manual/en/function.mysql-get-host-info.php', Database::get_host_info(), null, null, get_lang('MysqlHostInfo'));
+        /*
         $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_server_info()', 'http://www.php.net/manual/en/function.mysql-get-server-info.php', Database::get_server_info(), null, null, get_lang('MysqlServerInfo'));
 
         $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_proto_info()', 'http://www.php.net/manual/en/function.mysql-get-proto-info.php', Database::get_proto_info(), null, null, get_lang('MysqlProtoInfo'));
 
-        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_client_info()', 'http://www.php.net/manual/en/function.mysql-get-client-info.php', Database::get_client_info(), null, null, get_lang('MysqlClientInfo'));
+        $array[] = $this->build_setting(self :: STATUS_INFORMATION, '[MySQL]', 'mysql_get_client_info()', 'http://www.php.net/manual/en/function.mysql-get-client-info.php', Database::get_client_info(), null, null, get_lang('MysqlClientInfo'));*/
 
         return $array;
     }

+ 4 - 0
main/inc/lib/session_handler.class.php

@@ -31,6 +31,10 @@ class SessionHandlerDatabase {
 		$this->connection_handler = false;
 	}
 
+	/**
+	 * @deprecated don't use
+	 * @return bool
+	 */
 	public function sqlConnect() {
 
 		if (!$this->connection_handler) {

+ 3 - 0
main/inc/lib/session_handler_memcache.class.php

@@ -45,6 +45,9 @@ class SessionHandlerMemcache
         $this->connection_handler = false;
     }
 
+    /**
+     *@deprecated
+     * */
     public function sqlConnect()
     {
         if (!$this->connection_handler) {

+ 3 - 10
main/install/i_database.class.php

@@ -1,8 +1,8 @@
 <?php
 
 /**
- * Install database. Provides access to the Database class and allows to add 
- * hooks for logging, testing, etc during installation. 
+ * Install database. Provides access to the Database class and allows to add
+ * hooks for logging, testing, etc during installation.
  *
  * @license see /license.txt
  * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
@@ -22,13 +22,6 @@ class iDatabase extends Database
         self::$is_logging = $value;
     }
 
-    static function select_db($database_name, $connection = null)
-    {
-        if (self::is_logging()) {
-            Log::notice(__FUNCTION__ . ' ' . $database_name, Log::frame(1));
-        }
-        return parent::select_db($database_name, $connection);
-    }
 
     static function query($query, $connection = null, $file = null, $line = null)
     {
@@ -54,7 +47,7 @@ class iDatabase extends Database
      * Returns true if the table exists in the database, false otherwise.
      * @param string $database
      * @param string table
-     * @return boolean 
+     * @return boolean
      */
     static
 

+ 0 - 2
main/install/index.php

@@ -768,8 +768,6 @@ if (@$_POST['step2']) {
 		// 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.
 
-		// Inializing global variables that are to be used by the included scripts.
-		$dblist = Database::get_databases();
 		$perm = api_get_permissions_for_new_directories();
 		$perm_file = api_get_permissions_for_new_files();
 

+ 2 - 6
main/install/install.lib.php

@@ -604,7 +604,6 @@ function get_config_param_from_db($host, $login, $pass, $dbName, $param = '')
 {
     Database::connect(array('server' => $host, 'username' => $login, 'password' => $pass));
     Database::query("set session sql_mode='';"); // Disabling special SQL modes (MySQL 5)
-    Database::select_db($dbName);
 
     if (($res = Database::query("SELECT * FROM settings_current WHERE variable = '$param'")) !== false) {
         if (Database::num_rows($res) > 0) {
@@ -1932,9 +1931,8 @@ function display_database_settings_form(
             <?php echo $database_exists_text ?>
             <div id="db_status" class="confirmation-message">
                 Database host: <strong><?php echo $manager->getConnection()->getHost(); ?></strong><br />
-                Database server version: <strong><?php //echo Database::get_server_info(); ?></strong><br />
-                Database client version: <strong><?php //echo Database::get_client_info(); ?></strong><br />
-                Database protocol version: <strong><?php //echo Database::get_proto_info(); ?></strong>
+                Database port: <strong><?php echo $manager->getConnection()->getPort(); ?></strong><br />
+                Database platform: <strong><?php echo $manager->getConnection()->getDatabasePlatform()->getName(); ?></strong><br />
                 <div style="clear:both;"></div>
             </div>
         </td>
@@ -1944,8 +1942,6 @@ function display_database_settings_form(
             <div id="db_status" style="float:left;" class="error-message">
                 <div style="float:left;">
                     <strong><?php echo get_lang('FailedConectionDatabase'); ?></strong><br />
-                    <strong>Database error: <?php echo Database::errno(); ?></strong><br />
-                    <?php echo Database::error().'<br />'; ?>
                 </div>
             </div>
         </td>

+ 0 - 2
main/install/install_db.inc.php

@@ -101,8 +101,6 @@ if (!defined('CLI_INSTALLATION')) {
     }
 }
 
-//Database::select_db($mysqlMainDb) or die(Database::error());
-
 $installation_settings = array();
 $installation_settings['{ORGANISATIONNAME}'] = $institutionForm;
 $installation_settings['{ORGANISATIONURL}'] = $institutionUrlForm;

+ 0 - 6
main/install/update-db-1.9.0-1.10.0.inc.php

@@ -71,7 +71,6 @@ if (defined('SYSTEM_INSTALLATION')) {
             } elseif (!in_array($dbNameForm, $dblist)) {
                 Log::error('Database ' . $dbNameForm . ' was not found, skipping');
             } else {
-                iDatabase::select_db($dbNameForm);
                 foreach ($mainQueriesList as $query) {
                     if ($onlyTest) {
                         Log::notice("iDatabase::query($dbNameForm,$query)");
@@ -104,7 +103,6 @@ if (defined('SYSTEM_INSTALLATION')) {
         } elseif (!in_array($dbNameForm, $dblist)) {
             Log::error('Database '.$dbNameForm.' was not found, skipping');
         } else {
-            iDatabase::select_db($dbNameForm);
             $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"
@@ -124,9 +122,6 @@ if (defined('SYSTEM_INSTALLATION')) {
                 }
 
                 foreach ($list as $rowCourse) {
-                    if (!$singleDbForm) { // otherwise just use the main one
-                        iDatabase::select_db($rowCourse['db_name']);
-                    }
                     Log::notice('Course db ' . $rowCourse['db_name']);
 
                     // Now use the $c_q_list
@@ -165,7 +160,6 @@ if (defined('SYSTEM_INSTALLATION')) {
         } elseif (!in_array($dbNameForm, $dblist)) {
             Log::error('Database ' . $dbNameForm . ' was not found, skipping');
         } else {
-            iDatabase::select_db($dbNameForm);
             foreach ($mainQueriesList as $query) {
                 if ($onlyTest) {
                     Log::notice("iDatabase::query($dbNameForm,$query)");

+ 0 - 1289
main/install/update-db-scorm-1.6.x-1.8.0.inc.php

@@ -1,1289 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- * Script handling the migration between an old Dokeos platform (<1.8.0) to
- * setup the new database system (4 scorm tables inside the course's database)
- * @package chamilo.scorm
- * @author Yannick Warnier <ywarnier@beeznest.org>
- */
-
-/**
- * Include mandatory libraries
- */
-Log::notice('Entering file');
-
-if (!defined('SYSTEM_INSTALLATION')) {
-    echo 'You are not allowed here !' . __FILE__;
-    return;
-}
-
-require_once api_get_path(LIBRARY_PATH).'document.lib.php';
-require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php'; //check_name_exists()
-require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
-require_once api_get_path(SYS_CODE_PATH).'newscorm/scorm.class.php';
-
-$loglevel = 0;
-
-// Get table prefix from $prefix variable declared in update-db-....inc.php
-$table_prefix = $prefix;
-$sys_course_path = $pathForm.'courses/';
-$upd_course_path = $proposedUpdatePath.'courses/';
-
-function my_get_time($time) {
-    $matches = array();
-    if (preg_match('/(\d{1,4}):(\d{2})(:(\d{2})(\.\d*)?)?/', $time, $matches)) {
-        if (count($matches) == 3) {
-            return ($matches[1] * 60) + ($matches[2]);
-        } else {
-            return ($matches[1] * 3600) + ($matches[2] * 60) + ($matches[4]);
-        }
-    }
-    else return 0;
-}
-
-// Open log file
-$fh = fopen(api_get_path(SYS_ARCHIVE_PATH).'newscorm_'.time().'.log', 'w');
-$fh_revert = fopen(api_get_path(SYS_ARCHIVE_PATH).'newscorm_'.time().'_revert.log', 'w');
-$fh_res = fopen(api_get_path(SYS_ARCHIVE_PATH).'newscorm_'.time().'_res.log', 'w');
-fwrite($fh, "-- Recording course homepages links changes to enable reverting\n");
-fwrite($fh_revert, "-- Recording reverted course homepages links changes to enable reverting\n");
-fwrite($fh_res, "-- Recording resulting course homepages links changes\n");
-
-//echo "<html><body>";
-
-/**
- * New tables definition:
- */
-$new_lp = 'lp';
-$new_lp_view = 'lp_view';
-$new_lp_item = 'lp_item';
-$new_lp_item_view = 'lp_item_view';
-$new_lp_type = 'lp_type';
-
-$max_dsp_lp = 0;
-$courses_list = array();
-$courses_id_list = array();
-$courses_id_full_table_prefix_list = array();
-$courses_dir_list = array();
-
-Database::select_db($dbNameForm);
-
-$sql = "SELECT * FROM course";
-$res = Database::query($sql);
-
-while ($row = Database::fetch_array($res)) {
-    $course_pref = $table_prefix;
-    if ($singleDbForm) {
-        $dbname = $_configuration['main_database'].'.'.$course_pref.$row['db_name'].'_';
-    } else {
-        $dbname = $row['db_name'].'.'.$course_pref;
-    }
-    $courses_list[] = $row['db_name'];
-    $courses_id_list[$row['code']] = $row['db_name'];
-    $courses_id_full_table_prefix_list[$row['code']] = $dbname;
-    $courses_dir_list[$row['code']] = $row['directory'];
-}
-
-if ($loglevel > 0) { Log::notice("Tables created/deleted for all courses"); }
-
-/**
- * The migration needs to take all data from the original learnpath tables and add them to the new
- * lp, lp_view, lp_item and lp_item_view tables
- */
-// MIGRATING LEARNPATHS
-// Test only one course
-foreach ($courses_id_full_table_prefix_list as $course_code => $db) {
-    if (strlen($courses_id_list[$course_code]) > 40) {
-        Log::error('Database '.$courses_id_list[$course_code].' is too long, skipping');
-        continue;
-    }
-
-    $incoherences = 0;
-    if ($loglevel > 0) { Log::notice("Now starting migration of learnpath tables from $db database..."); }
-    $lp_doc = $db.TABLE_DOCUMENT;
-    $lp_main = $db.TABLE_LEARNPATH_MAIN;
-    $lp_ids = array();
-    $lp_user = $db.TABLE_LEARNPATH_USER;
-    $lp_users = array();
-    $lp_chap = $db.TABLE_LEARNPATH_CHAPTER;
-    $parent_chaps = array();
-    $lp_chap_items = array();
-    $ordered_chaps = array();
-    $lp_item = $db.TABLE_LEARNPATH_ITEM;
-    $lp_items = array();
-    $lp_ordered_items = array();
-    $parent_lps = array(); //keeps a track of chapter's learnpath ids
-    $my_new_lp = $db.$new_lp;
-    $my_new_lp_item = $db.$new_lp_item;
-    $my_new_lp_view = $db.$new_lp_view;
-    $my_new_lp_item_view = $db.$new_lp_item_view;
-
-    // Migrate learnpaths
-    $sql_test = "SELECT * FROM $my_new_lp";
-    $res_test = Database::query($sql_test);
-    $sql_lp = "SELECT * FROM $lp_main";
-    if ($loglevel > 1) { Log::notice("$sql_lp"); }
-    $res_lp = Database::query($sql_lp);
-    if (!$res_lp or !$res_test) {
-        if ($loglevel > 1) {
-            Log::error("+++Problem querying DB $lp_main+++ skipping (".Database::error().")");
-            if (!$res_test) {
-                Log::error("This might be due to no existing table in the destination course");
-            }
-        }
-        continue;
-    }
-    $dsp_ord = 1;
-    while ($row = Database::fetch_array($res_lp)) {
-        //echo "Treating lp id : ".$row['learnpath_id']."<br />\n";
-        $ins_lp_sql = "INSERT INTO $my_new_lp (lp_type,name,description,display_order,content_maker) " .
-                "VALUES (1," .
-                        "'".Database::escape_string($row['learnpath_name'])."'," .
-                        "'".Database::escape_string($row['learnpath_description'])."',$dsp_ord,'Dokeos')";
-        $ins_lp_res = Database::query($ins_lp_sql);
-        $in_id = Database::insert_id();
-        if (!$in_id) die('Could not insert lp: '.$ins_lp_sql);
-        $lp_ids[$row['learnpath_id']] = $in_id;
-        $dsp_ord++;
-        $max_dsp_lp = $dsp_ord;
-    }
-    //echo "<pre>lp_ids:".print_r($lp_ids,true)."</pre>\n";
-
-
-    // MIGRATING LEARNPATH CHAPTERS
-    $sql_lp_chap = "ALTER TABLE $lp_chap ADD INDEX ( parent_chapter_id, display_order )";
-    $res_lp_chap = Database::query($sql_lp_chap);
-
-    $sql_lp_chap = "SELECT * FROM $lp_chap ORDER BY parent_chapter_id, display_order";
-    //echo "$sql_lp_chap<br />\n";
-    $res_lp_chap = Database::query($sql_lp_chap);
-    while ($row = Database::fetch_array($res_lp_chap)) {
-        //echo "Treating chapter id : ".$row['id']."<br />\n";
-
-        //TODO: Build path for this chapter (although there is no real path for any chapter)
-        //TODO: Find out how to calculate the "next_item_id" with the "ordre" field
-        $my_lp_item = $my_new_lp_item;
-        $myname = Database::escape_string($row['chapter_name']);
-        $mydesc = Database::escape_string($row['chapter_description']);
-        $ins_lp_sql = "INSERT INTO $my_new_lp_item (" .
-                "lp_id," .
-                "item_type," .
-                "title," .
-                "description," .
-                "path, " .
-                "display_order, " .
-                "next_item_id) " .
-                "VALUES (" .
-                "'".$lp_ids[$row['learnpath_id']]."'," . //insert new learnpath ID
-                "'dokeos_chapter'," .
-                "'".$myname."'," .
-                "'".$mydesc."'," .
-                "''," .
-                $row['display_order'].", " .
-                "123456" .
-                ")";
-        //echo $ins_lp_sql."<br />\n";
-        $ins_res = Database::query($ins_lp_sql);
-        $in_id = Database::insert_id();
-        //echo "&nbsp;&nbsp;Inserted item $in_id<br />\n";
-        if (!$in_id) die('Could not insert lp: '.$ins_sql);
-        $parent_chaps[$row['id']] = $row['parent_chapter_id'];
-        $lp_chap_items[$row['id']] = $in_id;
-        $parent_lps[$row['id']] = $row['learnpath_id'];
-        $ordered_chaps[$row['parent_chapter_id']][$row['display_order']] = $in_id;
-        $lp_chaps_list[$row['learnpath_id']][] = $in_id;
-    }
-    //echo "<pre>parent_lps:".print_r($parent_lps,true)."</pre>\n";
-
-    // Now one loop to update the parent_chapter_ids
-    foreach ($parent_chaps as $old_chap => $old_parent_chap) {
-        if ($old_parent_chap != 0) {
-            $new_chap = $lp_chap_items[$old_chap];
-            $new_parent = $lp_chap_items[$old_parent_chap];
-            if (isset($new_chap) && $new_chap != '' && isset($new_parent) && $new_parent != '') {
-                $sql_par_chap = "UPDATE $my_new_lp_item " .
-                    "SET parent_item_id = $new_parent " .
-                    "WHERE id = $new_chap";
-                $res_par_chap = Database::query($sql_par_chap);
-            }
-        }
-    }
-    unset($parent_chaps);
-
-    // Now one loop to set the next_item_id and the previous_item_id
-    foreach ($ordered_chaps as $parent_chap) {
-        $last = 0;
-        foreach ($ordered_chaps[$parent_chap] as $order => $new_id) {
-            $sql_upd_chaps = "UPDATE $my_new_lp_item " .
-                    "SET previous_item_id = $last " .
-                    "WHERE id = $new_id";
-            $res_upd_chaps = Database::query($sql_upd_chaps);
-
-            $next = 0;
-            if (!empty($ordered_chaps[$parent_chap][$order + 1])) {
-                $next = $ordered_chaps[$parent_chap][$order + 1];
-            }
-            $sql_upd_chaps = "UPDATE $my_new_lp_item " .
-                    "SET next_item_id = $next " .
-                    "WHERE id = $new_id";
-            $res_upd_chaps = Database::query($sql_upd_chaps);
-            $last = $new_id;
-        }
-    }
-    unset($ordered_chaps);
-
-    // Migrate learnpath_items
-    // TODO: Define this array thanks to types defined in the learnpath_building scripts
-    // TODO: Set order correctly
-    $type_trans = array(
-        'document'  => TOOL_DOCUMENT,
-        'exercise'  => TOOL_QUIZ,
-        'forum'     => TOOL_FORUM,
-        'Agenda'    => TOOL_CALENDAR_EVENT,
-        'Ad_Valvas' => TOOL_ANNOUNCEMENT,
-        'Link'      => TOOL_LINK,
-        'Link _blank' => TOOL_LINK,
-        'Exercise'  => TOOL_QUIZ,
-        'HotPotatoes'=> 'HotPotatoes',
-        'Forum'     => TOOL_FORUM,
-        'Thread'    => TOOL_THREAD,
-        'Topic'     => TOOL_THREAD,
-        'Post'      => TOOL_POST,
-        'Document'  => TOOL_DOCUMENT,
-        'Assignments'=> 'Assignments',
-        'Dropbox'   => TOOL_DROPBOX,
-        'Introduction_text'=> 'Introduction_text',
-        'Course_description' => TOOL_COURSE_DESCRIPTION,
-        'Groups'    => TOOL_GROUP,
-        'Users'     => TOOL_USER,
-
-        //'chapter' => 'dokeos_chapter', Chapters should all be in learnpath_chapter, no matter the nesting level
-
-    );
-
-    // MIGRATING LEARNPATH ITEMS
-    $sql_lp_item = "ALTER TABLE $lp_item ADD INDEX ( chapter_id, display_order)";
-    $res_lp_item = Database::query($sql_lp_item);
-    $sql_lp_item = "SELECT * FROM $lp_item ORDER BY chapter_id, display_order";
-    //echo "$sql_lp_item<br />\n";
-    $res_lp_item = Database::query($sql_lp_item);
-    while ($row = Database::fetch_array($res_lp_item)) {
-        //echo "Treating chapter ".$row['chapter_id'].", item ".$row['id']."<br />\n";
-        $type = $type_trans[$row['item_type']];
-        $ref = $row['item_id'];
-        //TODO: Build item path
-        //TODO: Calculate "next_item_id" with the "ordre" field
-        // Prepare prereqs
-        // Prerequisites in Dokeos 1.6 is only authorised on previous items, so
-        // We know that we are gonna talk about an item that has already been passed
-        // through here - if none found, print message
-        $prereq_id = '';
-        if (!empty($row['prereq_id'])) {
-            switch ($row['prereq_type']) {
-                case 'c':
-                    // chapter-type prereq
-                    $prereq_id = $lp_chap_items[$row['prereq_id']];
-                    if (empty($prereq_id) && $loglevel > 1) { Log::error("Could not find prereq chapter ".$row['prereq_id']); }
-                    break;
-                case 'i':
-                default:
-                    // item type prereq
-                    $prereq_id = $lp_items[$parent_lps[$row['chapter_id']]][$row['prereq_id']];
-                    if (empty($prereq_id) && $loglevel > 1) { Log::error("Could not find prereq item ".$row['prereq_id']); }
-                    break;
-            }
-        }
-        $my_parent_id = 0;
-        if (isset($lp_chap_items[$row['chapter_id']])) {
-            $my_parent_id = $lp_chap_items[$row['chapter_id']];
-        }
-        $title = '';
-        if (empty($row['title']) && $type == 'Document' && !empty($row['item_id'])) {
-            $my_sql_doctitle = "SELECT title FROM $lp_doc WHERE id = ".$row['item_id'];
-            $my_res_doctitle = Database::query($my_sql_doctitle);
-            if ($row_doctitle = Database::fetch_array($my_res_doctitle)) {
-                $title = $row_doctitle['title'];
-            } else  {
-                $title = '-';
-            }
-        } else {
-            $title = $row['title'];
-        }
-        if (isset($lp_ids[$parent_lps[$row['chapter_id']]])) {
-        	// If there is a parent learnpath
-            $ins_lp_sql = "INSERT INTO $my_new_lp_item (" .
-                    "lp_id," .
-                    "item_type," .
-                    "ref, " .
-                    "title," .
-                    "description," .
-                    "path, " .
-                    "parent_item_id," .
-                    "prerequisite," .
-                    "display_order" .
-                    ") VALUES (" .
-                    "'".$lp_ids[$parent_lps[$row['chapter_id']]]."'," . // Insert new learnpath ID
-                    "'$type'," .
-                    "'$ref', " .
-                    "'".Database::escape_string($row['title'])."'," .
-                    "'".Database::escape_string($row['description'])."'," .
-                    "'$ref'," .
-                    "".$my_parent_id."," .
-                    "'$prereq_id'," .
-                    $row['display_order']." " .
-                    ")";
-            $ins_res = Database::query($ins_lp_sql);
-            $in_id = Database::insert_id();
-            //echo "&nbsp;&nbsp;Inserted item $in_id (".$row['title'].")<br />\n";
-            if (!$in_id) die('Could not insert lp_item: '.$ins_sql);
-            $lp_items[$parent_lps[$row['chapter_id']]][$row['id']] = $in_id;
-            $lp_ordered_items[$parent_lps[$row['chapter_id']]][$row['chapter_id']][] = $in_id;
-        }
-    }
-    //echo "<pre>lp_items:".print_r($lp_items,true)."</pre>\n";
-    // Complete next_item_id field by going through the new table and looking at parent_id and display_order
-    $order_sql = "ALTER TABLE $my_new_lp_item ADD INDEX (lp_id, parent_item_id, display_order)";
-    $order_res = Database::query($order_sql);
-    $order_sql = "SELECT * FROM $my_new_lp_item ORDER by lp_id ASC, parent_item_id ASC, display_order ASC";
-    //echo "$order_sql<br />\n";
-    $order_res = Database::query($order_sql);
-    $order_item = array(); //this will contain a sequential list of item_id's, thus allowing to give a simple way to get next id...
-    $lp_id = 0;
-    //echo "<pre>";
-    while ($row = Database::fetch_array($order_res)) {
-        //print_r($row);
-        if ($row['lp_id'] != $lp_id) {
-            // Apply changes to the database and clean tool arrays
-            $last = 0;
-            foreach ($order_item as $order_id => $item_id) {
-                $next = 0;
-                if (!empty($order_item[$order_id+1])) {
-                    $next = $order_item[$order_id+1];
-                }
-                $upd = "UPDATE $my_new_lp_item " .
-                        "SET next_item_id = ".$next."," .
-                        "    previous_item_id = ".$last." " .
-                        "WHERE id = ".$item_id;
-                //echo "$upd<br />\n";
-                Database::query($upd);
-                $last = $item_id;
-            }
-            $order_item = array();
-            $lp_id = $row['lp_id'];
-            $order_item[] = $row['id'];
-        } else {
-            $order_item[] = $row['id'];
-        }
-    }
-    // Process the last LP stack
-    $last = 0;
-    foreach ($order_item as $order_id => $item_id) {
-        $next = 0;
-        if (!empty($order_item[$order_id + 1])) {
-            $next = $order_item[$order_id + 1];
-        }
-        $upd = "UPDATE $my_new_lp_item " .
-                "SET next_item_id = ".$next."," .
-                "    previous_item_id = ".$last." " .
-                "WHERE id = ".$item_id;
-        //echo "$upd<br />\n";
-        Database::query($upd);
-        $last = $item_id;
-    }
-
-    //echo "</pre>\n";
-
-    // MIGRATING THE learnpath_user TABLE (results)
-    $mysql = "ALTER TABLE $my_new_lp_item_view ADD INDEX (lp_view_id)";
-    $myres = Database::query($mysql);
-    $sql_lp_user = "ALTER TABLE $lp_user ADD INDEX (user_id, learnpath_id, learnpath_item_id)";
-    $res_lp_user = Database::query($sql_lp_user);
-    $sql_lp_user = "SELECT * FROM $lp_user ORDER BY user_id, learnpath_id, learnpath_item_id";
-    //echo "$sql_lp_user<br />\n";
-    $res_lp_user = Database::query($sql_lp_user);
-    $user_id = 0;
-    $learnpath_id = 0;
-    $lp_view = 0;
-    while ($row = Database::fetch_array($res_lp_user)) {
-        if ($row['user_id']!=$user_id  OR $row['learnpath_id']!=$learnpath_id) {  //the user has changed or this is the first
-            // Insert a new lp_view
-            $last = 0;
-            if (!empty($lp_chaps_list[$row['learnpath_id']][0])) {
-                $last = $lp_chaps_list[$row['learnpath_id']][0];
-            }
-            if (empty($lp_ids[$row['learnpath_id']])) {
-                // This can be ignored as it means there was an LP before, this user
-                // used it, but now it's been removed
-                //echo "Somehow we also miss a lp_ids[".$row['learnpath_id']."] here<br />\n";
-                $incoherences ++;
-            } else {
-                $mylpid = $lp_ids[$row['learnpath_id']];
-                $sql_ins_view = "INSERT INTO $my_new_lp_view(" .
-                        "lp_id," .
-                        "user_id," .
-                        "view_count," .
-                        "last_item" .
-                        ")VALUES(" .
-                        "".$mylpid."," . // new learnpath id
-                        "".$row['user_id']."," . // user IDs stay the same
-                        "1," .
-                        "".$last."" . // Use the first chapter from this learnpath
-                        ")";
-                //echo $sql_ins_view;
-                $res_ins_view = Database::query($sql_ins_view);
-                $in_id = Database::insert_id();
-                $user_id = $row['user_id'];
-                $learnpath_id = $row['learnpath_id'];
-                $lp_view = $in_id;
-            }
-        }
-        // Insert the record into lp_item_view
-        // TODO: fix the whole in here (missing one item at least)
-        $my_new_lp_item_id = $lp_items[$learnpath_id][$row['learnpath_item_id']];
-        if (empty($my_new_lp_item_id)) {
-            // This can be ignored safely as it just means a user used a learnpath_item
-            // before it was removed from items - maybe fix that in Dokeos?
-            //echo "Somehow we miss lp_items[".$learnpath_id."][".$row['learnpath_item_id']."] here...<br />";
-            $incoherences ++;
-        } else {
-            $start_time = 0;
-            $my_time = my_get_time($row['time']);
-            if ($my_time > 0) {
-                $start_time = time() - $my_time;
-            }
-            $sql_ins_iv = "INSERT INTO $my_new_lp_item_view(" .
-                    "lp_item_id," .
-                "lp_view_id," .
-                "view_count," .
-                "start_time," .
-                "total_time," .
-                "score," .
-                "status" .
-                ")VALUES(" .
-                "".$lp_items[$learnpath_id][$row['learnpath_item_id']]."," .
-                "".$lp_view."," .
-                "1," .
-                "$start_time," .
-                "".$my_time."," .
-                "".$row['score']."," .
-                "'".$row['status']."'" .
-                ")";
-            //echo $sql_ins_iv;
-            $res_ins_iv = Database::query($sql_ins_iv);
-        }
-        // UPDATE THE LP_VIEW progress
-        $mysql = "SELECT count(distinct(lp_item_id)) FROM $my_new_lp_item_view WHERE lp_view_id = ".$lp_view." AND status IN ('passed','completed','succeeded','browsed','failed')";
-        $myres = Database::query($mysql);
-        $myrow = Database::fetch_array($myres);
-        $completed = $myrow[0];
-        $mylpid = $lp_ids[$row['learnpath_id']];
-        $sql = "SELECT count(*) FROM $my_new_lp_item WHERE lp_id = '".$mylpid."'";
-        $myres = Database::query($sql);
-        $myrow = Database::fetch_array($myres);
-        $total = $myrow[0];
-        $progress = ((float)$completed / (float)$total) * 100;
-        $progress = number_format($progress, 0);
-        $sql = "UPDATE $my_new_lp_view SET progress = '$progress' WHERE id = '$lp_view'";
-        $myres = Database::query($sql);
-    }
-
-    /**
-     * Move prerequisites
-     * TODO: Integrate prerequisites migration into learnpath_item migration
-     */
-
-    $msg = '';
-    if ($incoherences > 0) {
-        $msg = "(found $incoherences incoherences between views and items - ignored)";
-    }
-    /**
-     * Migrate links on the homepage as well now (look into the TABLE_TOOL_LIST table and
-     * update the links to newscorm/lp_controller.php?action=view&lp_id=x)
-     * Only normal learnpaths were visible from the homepage so we only need to update here
-     */
-    // MIGRATING LEARNPATH LINKS ON COURSES HOMEPAGES
-    $tbl_tool = $db.TABLE_TOOL_LIST;
-    $sql_tool = "SELECT * FROM $tbl_tool WHERE image='scormbuilder.gif' AND link LIKE '%learnpath_handler%'";
-    $res_tool = Database::query($sql_tool);
-    while ($row_tool = Database::fetch_array($res_tool)) {
-        $name = $row_tool['name'];
-        $link = $row_tool['link'];
-        // Get old lp_id from there
-        $matches = array();
-        if (preg_match('/learnpath_id=(\d+)$/', $link,$matches)) {
-            $old_lp_id = $matches[1];
-            $new_lp_id = $lp_ids[$old_lp_id];
-            $sql_tool_upd = "UPDATE $tbl_tool " .
-                    "SET link='newscorm/lp_controller.php?action=view&lp_id=$new_lp_id' " .
-                    "WHERE id = ".$row_tool['id'];
-            Log::notice('New LP - Migration - Updating tool table: '.$sql_tool_upd);
-            // Make sure there is a way of retrieving which links were updated (to revert)
-            fwrite($fh,$sql_tool_upd." AND link ='$link'");
-            fwrite($fh_revert, "UPDATE $tbl_tool SET link='$link' WHERE id=".$row_tool['id']." AND link ='newscorm/lp_controller.php?action=view&lp_id=$new_lp_id';\n");
-            //echo $sql_tool_upd." (and link='$link')<br />\n";
-            $res_tool_upd = Database::query($sql_tool_upd);
-        }
-    }
-
-    $tbl_tool = $db.TABLE_TOOL_LIST;
-    $sql_tool = "SELECT * FROM $tbl_tool";
-    $res_tool = Database::query($sql_tool);
-    while ($row_tool = Database::fetch_array($res_tool)) {
-        $link = $row_tool['link'];
-        $matches = array();
-        $pattern = '@scorm/showinframes\.php([^\s"\'&]*)(&|&amp;)file=([^\s"\'&]*)@';
-        if (preg_match($pattern, $link, $matches)) {
-            //echo "Found match for scorm link in $tbl_tool: $link<br />";
-            if (!empty($matches[3]) && (strtolower(substr($matches[3], -15)) == 'imsmanifest.xml') && !is_file(realpath(urldecode($matches[3])))) {
-                //echo "Removing link $link from tools<br />";
-                $sql_tool_upd = "DELETE FROM $tbl_tool WHERE id = ".$row_tool['id'];
-                Log::notice('New LP - Migration - Updating tool table (dead link): '.$sql_tool_upd);
-                // Make sure there is a way of retrieving which links were updated (to revert)
-                fwrite($fh, $sql_tool_upd." AND link ='$link'");
-                fwrite($fh_revert, "INSERT INTO $tbl_tool (link) VALUES ('$link');\n");
-                //echo $sql_tool_upd." (and link='$link')<br />\n";
-                $res_tool_upd = Database::query($sql_tool_upd);
-            }
-        } else {
-            //echo "No scorm link found in tool link $link<br />";
-        }
-        //flush();
-    }
-    /**
-     * Update course description (intro page) to use new links instead of learnpath/learnpath_handler.php
-     */
-    $tbl_intro = $db.TABLE_TOOL_INTRO;
-    $sql_i = "SELECT * FROM $tbl_intro WHERE id='course_homepage'";
-    $res_i = Database::query($sql_i);
-    //$link_to_course1 = 'scorm/scormdocument.php';
-    while ($row_i = Database::fetch_array($res_i)) {
-        $intro = $row_i['intro_text'];
-        $update = 0;
-        $out = array();
-        if (preg_match_all('/claroline\/learnpath\/showinframes\.php([^\s"\']*)learnpath_id=(\d*)/', $intro, $out, PREG_SET_ORDER)) {
-            foreach ($out as $results) {
-                //echo "---> replace ".'/learnpath\/showinframes\.php([^\s"\']*)learnpath_id='.$results[2].'/ by newscorm/lp_controller.php'.$results[1].'action=view&lp_id='.$lp_ids[$results[2]];
-                $intro = preg_replace('/claroline\/learnpath\/showinframes\.php([^\s"\']*)learnpath_id='.$results[2].'/','main/newscorm/lp_controller.php'.$results[1].'action=view&lp_id='.$lp_ids[$results[2]], $intro);
-            }
-        }
-        if (preg_match_all('/claroline\/phpbb\/index.php/', $intro, $out, PREG_SET_ORDER)) {
-            foreach ($out as $results) {
-                $intro = preg_replace('/claroline\/phpbb\/index\.php([^\s"\']*)/','main/forum/index.php'.$results[1], $intro);
-            }
-        }
-        if ($intrp != $row_i['intro_text']) {
-            //echo "<pre>Replacing ".$row_i['intro_text']."\n by \n ".$intro."</pre><br />\n";
-            $sql_upd = "update $tbl_intro set intro_text = '".Database::escape_string($intro)."' WHERE id = 'course_homepage' AND intro_text = '".Database::escape_string($row_i['intro_text'])."'";
-            //echo $sql_upd."<br />\n";
-            fwrite($fh,"$sql_upd\n");
-            fwrite($fh_revert,"UPDATE $tbl_intro set intro_text = '".$row_i['intro_text']."' WHERE id = 'course_homepage' AND intro_text = '$intro';\n");
-            fwrite($fh_res,"$intro\n");
-            Database::query($sql_upd);
-        }
-    }
-
-    if ($loglevel > 0) { Log::notice("Done!".$msg); }
-    //flush();
-    //ob_flush();
-}
-
-unset($lp_ids);
-unset($lp_users);
-unset($parent_chaps);
-unset($lp_chap_items);
-unset($ordered_chaps);
-unset($lp_items);
-unset($lp_ordered_items);
-unset($parent_lps);
-
-fwrite($fh, "-- Recording course homepages links changes for SCORM to enable reverting\n");
-fwrite($fh_revert, "-- Recording reverted course homepages links changes for SCORM to enable reverting\n");
-fwrite($fh_res, "-- Recording resulting course homepages links changes for SCORM\n");
-
-/**
- * SCORM
- * The migration needs to take all data from the scorm.scorm_main and scorm.scorm_sco_data tables
- * and add them to the new lp, lp_view, lp_item and lp_item_view tables.
- */
-if ($loglevel > 0) { Log::notice("Now starting migration of scorm tables from global SCORM database"); }
-
-$scorm_main = $dbScormForm.'.'.TABLE_SCORM_MAIN;
-$scorm_item = $dbScormForm.'.'.TABLE_SCORM_SCO_DATA;
-//$lp_main = Database::get_course_table(TABLE_LEARNPATH_MAIN,$db);
-$course_pref = $table_prefix;
-$lp_ids = array();
-$lp_item_ids = array();
-$lp_item_refs = array();
-$lp_course = array();
-$lp_course_code = array();
-$scorm_lp_paths = array();
-
-// Avoid empty dokeosCourse fields as they potentially break the rest
-Database::select_db($dbNameForm);
-$course_main = TABLE_MAIN_COURSE;
-$sql_crs = "SELECT * FROM $course_main WHERE target_course_code IS NULL";
-if ($loglevel > 0) { Log::notice("$sql_crs"); }
-$res_crs = Database::query($sql_crs);
-$num = Database::num_rows($res_crs);
-
-// Prepare an array that will contain course codes and for each course code a list of lps [by path prefixed by '/']
-$scorms = array();
-$course_code_swap = '';
-$scormdocuments_lps = array();
-while ($course_row = Database::fetch_array($res_crs)) {
-
-    if ($loglevel > 0) { Log::notice("Now dealing with course ".$course_row['code']."..."); }
-    // Check the validity of this new course
-    $my_course_code = $course_row['code'];
-
-    // Reinit the scormdocuments list
-    //$scormdocuments_lps = array();
-    $db_name = $courses_id_full_table_prefix_list[$my_course_code];
-    if (strlen($courses_id_list[$course_code]) > 40) {
-        Log::notice('Database '.$courses_id_list[$course_code].' is too long, skipping');
-        continue;
-    }
-
-    //echo "Now processing database $db_name<br />";
-    $tblscodoc = $db_name.TABLE_SCORMDOC;
-    $sql_scodoc = "SELECT path FROM $tblscodoc WHERE path IS NOT NULL AND path != ''";
-    if ($loglevel > 1) { Log::notice("$sql_scodoc"); }
-    $res_scodoc = Database::query($sql_scodoc);
-    while ($row_scodoc = Database::fetch_array($res_scodoc)) {
-
-        // Check if there's more than one slash in total
-        if (strpos($row_scodoc['path'], '/', 1) === false) {
-            $tmp_path = $row_scodoc['path'];
-            if ($loglevel > 1) { Log::notice("++Now opening $tmp_path"); }
-
-            // Add a prefixing slash if there is none
-            if (substr($tmp_path, 0, 1) != '/') {
-                $tmp_path = '/'.$tmp_path;
-            }
-
-            // If the path is just a slash, empty it
-            if ($tmp_path == '/') {
-                $tmp_path = '';
-            }
-
-            // There is only one 'slash' sign at the beginning, or none at all, so we assume
-            // it is a main directory that should be taken as path.
-            $courses_dir = $sys_course_path.''.$courses_dir_list[$my_course_code].'/scorm'.$tmp_path;
-            if (!is_dir($courses_dir)) {
-                //echo "Scormdocument path $my_content_id: $tmp_path doesn't exist in ".$sys_course_path.$courses_dir_list[$my_course_code]."/scorm, skipping<br />\n";
-                continue;
-                // Avoid if contentTitle is not the name of an existing directory
-            } elseif (!is_file($courses_dir."/imsmanifest.xml")) {
-                // If the imsmanifest file was not found there
-                if ($loglevel > 2) { Log::error("  !!imsmanifest.xml  not found at scormdocument's $courses_dir/imsmanifest.xml, skipping"); }
-                // Try subdirectories on one level depth
-                if ($loglevel > 2) { Log::notice("  Trying subdirectories..."); }
-                $dh = opendir($courses_dir);
-                while ($entry = readdir($dh)) {
-                    if (substr($entry, 0, 1) != '.') {
-                        if (is_dir($courses_dir."/".$entry)) {
-                            if (is_file($courses_dir."/".$entry."/imsmanifest.xml")) {
-                                if ($loglevel > 2) { Log::notice(".  .. and found $courses_dir/$entry/imsmanifest.xml!"); }
-                                if (!in_array($tmp_path."/".$entry."/imsmanifest.xml",$scormdocuments_lps)) {
-                                    if ($loglevel > 2){ Log::notice("  Recording.<br />"); }
-                                    $scormdocuments_lps[] = $tmp_path."/".$entry;
-                                }
-                            }
-                        }
-                    }
-                }
-            } else {
-                if ($loglevel > 2) { Log::notice("  Found scormdocument $tmp_path in ".$sys_course_path.$courses_dir_list[$my_course_code]."/scorm, treating it."); }
-                $scormdocuments_lps[] = $tmp_path;
-            }
-        }
-    }
-
-
-    // Because certain people with no admin skills had fun adding direct links to SCORM
-    // from the courses introductions, we have to check for SCORM packages from there too...
-    $tbl_intro = $db_name.TABLE_TOOL_INTRO;
-    $sql_i = "SELECT * FROM $tbl_intro WHERE id='course_homepage'";
-    //echo $sql_i;
-    $res_i = Database::query($sql_i);
-    //$link_to_course1 = 'scorm/scormdocument.php';
-    while ($row_scodoc = Database::fetch_array($res_i)) {
-        $intro = $row_scodoc['intro_text'];
-        //echo $intro."<br />\n";
-        $matches = array();
-        $pattern = '@scorm/showinframes\.php([^\s"\']*)file=([^\s"\'&]*)@';
-        if (preg_match_all($pattern, $intro, $matches, PREG_SET_ORDER)) {
-            if (count($matches) < 1) {
-                // Skip
-            } else {
-                //echo "Found matches in $tbl_intro<br />";
-                foreach ($matches as $match) {
-                    //echo "Found match ".print_r($match,true)."<br />";
-                    $mymatch = urldecode($match[2]);
-                    $mymatch = str_replace($sys_course_path, $upd_course_path, $mymatch);
-                    if (!empty($mymatch) && (strtolower(substr($mymatch, -15)) == 'imsmanifest.xml') && is_file(realpath(urldecode($mymatch)))) {
-
-                        //echo $mymatch." seems ok<br />";
-                        // Found a new scorm course in the old directory
-                        $courses_dir = $upd_course_path.''.$courses_dir_list[$my_course_code].'/scorm';
-                        // Check if the file is in the current course path, otherwise just forget about it
-                        // as it would be too difficult to migrate
-                        //echo "Comparing $mymatch with $courses_dir<br />";
-                        if (strpos($mymatch, $courses_dir) !== false) {
-                            // Remove the course dir up to /scorm from this path
-                            $entry = substr($mymatch, strlen($courses_dir));
-                            // Remove the /imsmanifest.xml from the end of the path
-                            $entry = substr($entry, 0, -16);
-                            // If $entry was /var/www/dokeos/courses/ABC/scorm/tralala/imsmanifest.xml,
-                            // $entry is now /tralala
-                            //echo "Checking if manifest exists in ".$courses_dir.$entry."/imsmanifest.xml<br />";
-                            if (is_file($courses_dir.$entry."/imsmanifest.xml")) {
-                                //echo "found $courses_dir/$entry/imsmanifest.xml!<br />";
-                                if ($loglevel > 2) { Log::notice(".  .. and found $courses_dir/$entry/imsmanifest.xml!"); }
-                                if (!in_array($entry."/imsmanifest.xml", $scormdocuments_lps)) {
-                                    if ($loglevel > 2) { Log::notice("  Recording.<br />"); }
-                                    //echo "Recording $entry<br />";
-                                    $scormdocuments_lps[] = $entry;
-                                }
-                            } else {
-                                //echo "Manifest does not exist in ".$courses_dir.$entry."/imsmanifest.xml<br />";
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-
-    // Prepare the new course's space in the scorms array
-    $scorms[$my_course_code] = array();
-
-    $sql_paths = "SELECT * FROM $scorm_main WHERE dokeosCourse = '".$my_course_code."'";
-    if ($loglevel > 0) { Log::notice("$sql_paths"); }
-    $res_paths = Database::query($sql_paths);
-    $num = Database::num_rows($res_paths);
-    while ($scorm_row = Database::fetch_array($res_paths)) {
-        // Check if this is a new course
-        $my_content_id = $scorm_row['contentId'];
-        $my_path = $scorm_row['contentTitle'];
-        if (substr($my_path, 0, 1) != '/') {
-            $my_path = '/'.$my_path;
-        }
-        if ($my_path == '/') {
-            $my_path = '';
-        }
-        if ($loglevel > 1) { Log::notice("++++Now opening $my_path"); }
-        if (!is_dir($courses_dir = $sys_course_path.''.$courses_dir_list[$my_course_code].'/scorm'.$my_path)) {
-            if ($loglevel > 1) { Log::notice("Path $my_content_id: $my_path doesn't exist in ".$sys_course_path.$courses_dir_list[$my_course_code]."/scorm, skipping"); }
-            continue;
-            // Avoid if contentTitle is not the name of an existing directory
-        } elseif (!is_file($sys_course_path.$courses_dir_list[$my_course_code].'/scorm'.$my_path."/imsmanifest.xml")) {
-            if ($loglevel > 1) { Log::notice("!!imsmanifest.xml not found at ".$sys_course_path.$courses_dir_list[$my_course_code].'/scorm'.$my_path."/imsmanifest.xml, skipping"); }
-            continue;
-        } else {
-            if ($loglevel > 1) { Log::notice("Found $my_path in ".$sys_course_path.$courses_dir_list[$my_course_code]."/scorm".$mypath."/imsmanifest.xml, keeping it."); }
-            $scorms[$my_course_code][$my_path] = $my_content_id;
-        }
-    }
-    // Check if all the lps from scormdocuments_lps are already in the course array,
-    // otherwise add them (and set ID of 0 so no tracking will be available)
-    foreach ($scormdocuments_lps as $path) {
-        if (!in_array($path,array_keys($scorms[$my_course_code]))) {
-            // Add it (-1 means no ID)
-            if ($loglevel > 1) { Log::notice("** Scormdocument path $path wasn't recorded yet. Added."); }
-            $scorms[$my_course_code][$path] = -1;
-        }
-    }
-    $course_code_swap = $my_course_code;
-    unset($scormdocuments_lps);
-}
-
-//echo "<pre>courses_id_list: ".print_r($courses_id_list,true)."</pre>\n";
-
-$my_count = 0;
-foreach ($scorms as $mycourse => $my_paths) {
-    $my_count += count($my_paths);
-}
-if ($loglevel > 0) { Log::notice("---- Scorms array now contains ".$mycount." paths to migrate. Starting migration..."); }
-
-/**
- * Looping through the SCO_MAIN table for SCORM learnpath attached to courses
- * Order by course to try and reuse the maximum data
- */
-$i_count = 0;
-foreach ($scorms as $my_course_code => $paths_list) {
-  $max_dsp_lp = 0;
-  $course_lp_done = array();
-  $db_name = $courses_id_full_table_prefix_list[$my_course_code];
-  foreach ($paths_list as $my_path => $old_id) {
-    if ($loglevel > 1) { Log::notice("Migrating lp $my_path from course $my_course_code..."); }
-    $i_count ++;
-    //Log::notice('New LP - Migration script - Content '.$i_count.' on '.$num.' (course '.$scorm['dokeosCourse'].')');
-    // Check whether there is no embedded learnpaths into other learnpaths (one root-level and another embedded)
-    $embedded = false;
-    foreach ($course_lp_done as $tmp_lp) {
-        if (empty($tmp_lp)) {
-            $tmp_lp = '/'; // Allows finding the lp as a subitem, otherwise strstr returns false
-        }
-        if (strstr($my_path, $tmp_lp) === false) {
-            // Let it be
-        } else {
-            // This lp is embedded inside another lp who's imsmanifest exists, so prevent from parsing
-            if ($loglevel > 1) { Log::notice("LP $my_path is embedded into $tmp_lp, ignoring..."); }
-            $embedded = true;
-            continue;
-        }
-    }
-    if ($embedded) {
-        continue;
-    }
-    $course_lp_done[] = $my_path;
-    //echo "<pre>scorm row: ".print_r($scorm,true)."</pre>\n";
-    $my_content_id = $old_id;
-    $my_path = $my_path;
-    $my_name = basename($my_path);
-
-    if ($loglevel > 1) { Log::notice("Try importing LP $my_path from imsmanifest first as it is more reliable"); }
-
-    // Setup the ims path (path to the imsmanifest.xml file)
-    //echo "Looking for course with code ".$lp_course_code[$my_content_id]." (using $my_content_id)<br />\n";
-    //$courses_dir = $sys_course_path.$courses_dir_list[$my_course_code];
-    $courses_dir = $upd_course_path.$courses_dir_list[$my_course_code];
-    $sco_path_temp = ($my_path == '/') ? '' : $my_path;
-    $sco_middle_path = (empty($sco_path_temp) ? '' : (substr($sco_path_temp, 0, 1) == '/') ? substr($sco_path_temp, 1).'/' : $sco_path_temp.'/'); //same thing as sco_path_temp but with reversed slashes
-    $ims = $courses_dir.'/scorm'.$sco_path_temp.'/imsmanifest.xml';
-
-    if (is_file($ims)){
-        //echo "Path $ims exists, importing...(line ".__LINE__.")<br />";
-        $oScorm = new scorm();
-        // Check whether imsmanifest.xml exists at this location. If not, ignore the imsmanifest.
-        // That should have been done before already, now.
-        if ($loglevel > 1) { Log::notice("Found imsmanifest ($ims), importing..."); }
-        if (!empty($sco_middle_path)) { $oScorm->subdir = $sco_middle_path; } //this sets the subdir for the scorm package inside the scorm dir
-        // Parse manifest file
-        $manifest = $oScorm->parse_manifest($ims);
-        // The title is already escaped in the method
-        $oScorm->import_manifest($my_course_code);
-        //TODO: Add code to update the path in that new lp created, as it probably uses / where
-        // $sco_path_temp should be used...
-        $lp_ids[$my_content_id] = $oScorm->lp_id; // Contains the old LP ID => the new LP ID
-        if ($loglevel > 1) { Log::notice(" @@@ Created scorm lp ".$oScorm->lp_id." from imsmanifest [".$ims."] in course $my_course_code"); }
-        $lp_course[$my_content_id] = $courses_id_list[$my_course_code]; // Contains the old learnpath ID => the course DB name
-        $lp_course_code[$my_content_id] = $my_course_code;
-        $max_dsp_lp++;
-
-        /*
-         * QUERY SCORM ITEMS FROM SCORM_SCO_DATA
-         * The danger here is that we might have several users for the same data, and so
-         * we have to avoid entering the same elements twice
-         */
-        $sql_items = "SELECT * FROM $scorm_item WHERE contentId = '".$my_content_id."' ORDER BY scoId";
-        //echo "$sql_items<br />\n";
-        $res_items = Database::query($sql_items);
-        while ($scormItem = Database::fetch_array($res_items)) {
-            $my_sco_id      = $scormItem['scoId']; //the index for display??? (check that)
-            $my_identifier  = $scormItem['scoIdentifier']; //the scorm item path/name
-            $my_title       = Database::escape_string($scormItem['scoTitle']);
-            $my_status      = $scormItem['status'];
-            $my_student     = $scormItem['studentId'];
-            $my_score       = $scormItem['score'];
-            $my_time        = my_get_time($scormItem['time']);
-            $my_type        = 'sco';
-            //$my_item_path = $scorm_lp_paths[$my_content_id]['path'];
-            $my_item_path   = '';
-
-            //echo "&nbsp;&nbsp;FOUND item belonging to old learnpath num $my_content_id so belongs to course ".$lp_course[$my_content_id]."<br />\n";
-            $my_new_lp_item = $db_name.$new_lp_item;
-            $my_new_lp_view = $db_name.$new_lp_view;
-            $my_new_lp_item_view = $db_name.$new_lp_item_view;
-
-            /*
-             * Check if a view is needed
-             */
-            if ($my_score != '' and $my_status != 'not attempted') {
-                // It is worth creating an lp_view and an lp_item_view - otherwise not
-                $sel_sqlb = "SELECT * FROM $my_new_lp_view " .
-                        "WHERE lp_id = ".$lp_ids[$my_content_id]." AND user_id = $my_student";
-                $sel_resb = Database::query($sel_sqlb);
-                if (Database::num_rows($sel_resb) > 0) {
-                    // Don't insert
-                    $rowb = Database::fetch_array($sel_resb);
-                    $view_insert_id = $rowb['id'];
-                } else {
-                    $ins_sql = "INSERT INTO $my_new_lp_view (" .
-                        "lp_id," .
-                        "user_id," .
-                        "view_count" .
-                        ") VALUES (" .
-                        $lp_ids[$my_content_id].", " .
-                        $my_student.", " .
-                        "1" .
-                        ")";
-                    //echo "$ins_sql<br />";
-                    $ins_res = Database::query($ins_sql);
-                    $view_insert_id = Database::insert_id();
-                }
-                $sel_sqlc = "SELECT * FROM $my_new_lp_item " .
-                        "WHERE lp_id = ".$lp_ids[$my_content_id]." AND ref = '$my_identifier'";
-                $sel_resc = Database::query($sel_sqlc);
-                if (Database::num_rows($sel_resc) > 0) {
-                    $my_item_id_row = Database::fetch_array($sel_resc);
-                    $item_insert_id = $my_item_id_row['id'];
-                    $ins_sql = "INSERT INTO $my_new_lp_item_view (" .
-                            "lp_item_id, lp_view_id, view_count," .
-                            "start_time, total_time, score," .
-                            "status" .
-                            ") VALUES (" .
-                            "$item_insert_id, $view_insert_id, 1," .
-                            "0, $my_time, $my_score," .
-                            "'$my_status'" .
-                            ")";
-                    //echo "$ins_sql<br />";
-                    $ins_res = Database::query($ins_sql);
-                } else {
-                    //echo "  Didn't find corresponding item for $my_identifier in new tables<br />\n";
-                }
-            }
-        }
-
-    } else {
-        //echo "Could not find $ims... Proceeding from database...(line ".__LINE__.")<br />";
-        if ($loglevel > 1) { Log::notice("This is a normal SCORM path"); }
-        $scorm_lp_paths[$my_content_id]['path'] = $my_path;
-        //$scorm_lp_paths[$my_content_id]['ims'] = '';
-        $table_name = $db_name.$new_lp;
-        $sql_ins = "INSERT INTO $table_name (" .
-                "lp_type," .
-                "name," .
-                "description," .
-                "path," .
-                "force_commit, " .
-                "default_encoding," .
-                "display_order," .
-                "content_maker," .
-                "content_local," .
-                "js_lib" .
-                ") VALUES (" .
-                "2," .
-                "'$my_name'," .
-                "''," .
-                "'$my_path'," .
-                "0," .
-                "'UTF-8'," .
-                "".$max_dsp_lp."," .
-                "'Unknown'," .
-                "'Unknown'," .
-                "'scorm_api.php'" .
-                ")";
-        if ($loglevel > 1) { Log::notice("$sql_ins"); }
-        $sql_res = Database::query($sql_ins);
-        $in_id = Database::insert_id();
-        if (!$in_id) die('Could not insert scorm lp: '.$sql_ins);
-        //echo "&nbsp;&nbsp;Inserted item $in_id<br />\n";
-        $lp_ids[$my_content_id] = $in_id; //contains the old LP ID => the new LP ID
-        $lp_course[$my_content_id] = $courses_id_list[$my_course_code]; // Contains the old learnpath ID => the course DB name
-        $lp_course_code[$my_content_id] = $my_course_code;
-        $max_dsp_lp++;
-
-        // Setup the ims path (path to the imsmanifest.xml file)
-        //echo "Looking for course with code ".$lp_course_code[$my_content_id]." (using $my_content_id)<br />\n";
-        $courses_dir = $sys_course_path.$courses_dir_list[$lp_course_code[$my_content_id]];
-        //$scorm_lp_paths[$my_content_id]['path'] = str_replace(' ', '\\ ', $scorm_lp_paths[$my_content_id]['path']);
-        $sco_path_temp = ($scorm_lp_paths[$my_content_id]['path'] == '/') ? '' : $scorm_lp_paths[$my_content_id]['path'];
-        $scorm_lp_paths[$my_content_id]['ims'] = $courses_dir.'/scorm'.$sco_path_temp.'/imsmanifest.xml';
-
-        // Generate an imsmanifest object to get more info about the learnpath from the file
-        $oScorm = new scorm();
-        // Check whether imsmanifest.xml exists at this location. If not, ignore the imsmanifest.
-        // That should have been done before already, now.
-        if (!is_file($scorm_lp_paths[$my_content_id]['ims'])) {
-            if ($loglevel > 1) { Log::notice("!!! imsmanifest file not found at ".$scorm_lp_paths[$my_content_id]['ims'].' for old lp '.$my_content_id.' and new '.$lp_ids[$my_content_id]); }
-            $manifest = false;
-        } else {
-            //echo "Parsing ".$scorm_lp_paths[$my_content_id]['ims']."<br />\n";
-            // Parse manifest file
-            $manifest = $oScorm->parse_manifest($scorm_lp_paths[$my_content_id]['ims']);
-            // The title is already escaped in the method
-            //$my_lp_title = api_convert_encoding($oScorm->get_title(),'ISO-8859-1',$oScorm->manifest_encoding);
-            $my_lp_title = api_convert_encoding($oScorm->get_title(), 'ISO-8859-1', 'UTF-8');  // TODO: This "magic" conversion to be checked.
-            if (!empty($my_lp_title)) {
-                $my_new_lp = $db_name.$new_lp;
-                $my_sql = "UPDATE $my_new_lp " .
-                        "SET name = '$my_lp_title', " .
-                        "default_encoding = '".strtoupper($oScorm->manifest_encoding)."' " .
-                        "WHERE id = ".$lp_ids[$my_content_id];
-                if ($loglevel > 1) { Log::notice("Updating title and encoding: ".$my_sql); }
-                $my_res = Database::query($my_sql);
-            }
-        }
-
-        /*
-         * QUERY SCORM ITEMS FROM SCORM_SCO_DATA
-         * The danger here is that we might have several users for the same data, and so
-         * we have to avoid entering the same elements twice
-         */
-        $sql_items = "SELECT * FROM $scorm_item WHERE contentId = '".$my_content_id."' ORDER BY scoId";
-        //echo "$sql_items<br />\n";
-        $res_items = Database::query($sql_items);
-        while ($scormItem = Database::fetch_array($res_items)) {
-            $my_sco_id      = $scormItem['scoId']; // The index for display??? (check that)
-            $my_identifier  = $scormItem['scoIdentifier']; //the scorm item path/name
-            $my_title       = Database::escape_string($scormItem['scoTitle']);
-            $my_status      = $scormItem['status'];
-            $my_student     = $scormItem['studentId'];
-            $my_score       = $scormItem['score'];
-            $my_time        = my_get_time($scormItem['time']);
-            $my_type        = 'sco';
-            //$my_item_path = $scorm_lp_paths[$my_content_id]['path'];
-            $my_item_path   = '';
-
-            //echo "&nbsp;&nbsp;FOUND item belonging to old learnpath num $my_content_id so belongs to course ".$lp_course[$my_content_id]."<br />\n";
-            $my_new_lp_item = $db_name.$new_lp_item;
-            $my_new_lp_view = $db_name.$new_lp_view;
-            $my_new_lp_item_view = $db_name.$new_lp_item_view;
-
-            /*
-             * Query items from the new table to check if it doesn't exist already
-             * Otherwise insert it
-             */
-            $sel_sql = "SELECT * FROM $my_new_lp_item " .
-                    "WHERE ref = '$my_identifier' " .
-                    "AND lp_id = ".$lp_ids[$my_content_id]."";
-            //echo $sel_sql."<br />\n";
-            $sel_res = Database::query($sel_sql);
-            if (Database::num_rows($sel_res) > 0) {
-                // This item already exists, reuse
-                $row = Database::fetch_array($sel_res);
-                $item_insert_id = $row['lp_id'];
-            } else {
-                $ins_sql = "INSERT INTO $my_new_lp_item (" .
-                    "lp_id," .
-                    "item_type," .
-                    "ref," .
-                    "title," .
-                    "path" .
-                    ") " .
-                    "VALUES (" .
-                    "'".$lp_ids[$my_content_id]."'," . //insert new learnpath ID
-                    "'$my_type'," .
-                    "'".$my_identifier."'," .
-                    "'".$my_title."'," .
-                    "'$my_item_path'" .
-                    ")";
-                $ins_res = Database::query($ins_sql);
-                $item_insert_id = Database::insert_id();
-                $lp_item_ids[$lp_ids[$my_content_id]][$my_sco_id] = $item_insert_id;
-                $lp_item_refs[$lp_ids[$my_content_id]][$my_identifier] = $item_insert_id;
-            }
-            /*
-             * Check if a view is needed
-             */
-            if ($my_score != '' and $my_status != 'not attempted') {
-                // It is worth creating an lp_view and an lp_item_view - otherwise not
-                $sel_sqlb = "SELECT * FROM $my_new_lp_view " .
-                        "WHERE lp_id = ".$lp_ids[$my_content_id]." AND user_id = $my_student";
-                $sel_resb = Database::query($sel_sqlb);
-                if (Database::num_rows($sel_resb) > 0) {
-                    // Don't insert
-                    $rowb = Database::fetch_array($sel_resb);
-                    $view_insert_id = $rowb['id'];
-                } else {
-                    $ins_sql = "INSERT INTO $my_new_lp_view (" .
-                        "lp_id," .
-                        "user_id," .
-                        "view_count" .
-                        ") VALUES (" .
-                        $lp_ids[$my_content_id].", " .
-                        $my_student.", " .
-                        "1" .
-                        ")";
-                    $ins_res = Database::query($ins_sql);
-                    $view_insert_id = Database::insert_id();
-                }
-                $ins_sql = "INSERT INTO $my_new_lp_item_view (" .
-                        "lp_item_id, lp_view_id, view_count," .
-                        "start_time, total_time, score," .
-                        "status" .
-                        ") VALUES (" .
-                        "$item_insert_id, $view_insert_id, 1," .
-                        "0, $my_time, $my_score," .
-                        "'$my_status'" .
-                        ")";
-                $ins_res = Database::query($ins_sql);
-            }
-        }
-        // UPDATE THE LP_VIEW progress
-        if (!empty($view_insert_id)) {
-            $sql = "SELECT count(distinct(lp_item_id)) FROM $my_new_lp_item_view WHERE lp_view_id = ".$view_insert_id." AND status IN ('passed','completed','succeeded','browsed','failed')";
-            $myres = Database::query($sql);
-            $myrow = Database::fetch_array($myres);
-            $completed = $myrow[0];
-            $mylpid = $lp_ids[$my_content_id];
-            $sql = "SELECT count(*) FROM $my_new_lp_item WHERE lp_id = '".$mylpid."'";
-            $myres = Database::query($sql);
-            $myrow = Database::fetch_array($myres);
-            $total = $myrow[0];
-            $progress = ((float)$completed / (float)$total) * 100;
-            $progress = number_format($progress, 0);
-            $sql = "UPDATE $my_new_lp_view SET progress = '$progress' WHERE id = '$view_insert_id'";
-            $myres = Database::query($sql);
-        }
-
-        /*
-         * Set all information that might be more correct coming from imsmanifest
-         */
-
-        //$my_new_lp = $db_name.$new_lp;
-        //$my_new_lp_item = $db_name.$new_lp_item;
-        //$my_new_lp_view = $db_name.$new_lp_view;
-        //$my_new_lp_item_view = $db_name.$new_lp_item_view;
-        //$sel_sql = "SELECT * FROM $my_new_lp WHERE id = $in_id";
-        //$res = @Database::query($sel_sql);
-        //if (!$res) {
-        //  echo "Error selecting lp: $sel_sql - ".Database::error()."<br />\n";
-        //}
-        $lp_details = array();
-        //while ($row = Database::fetch_array($res)) {
-            $ordered_list = array();
-            $mylist = array();
-            foreach ($oScorm->organizations as $org) {
-                // There should be only one organization (generally)
-                // and if there are more, we are not supposed to have been
-                // able to manage them before the new tool, so ignore
-                if (count($ordered_list) > 0) {
-                    break;
-                }
-                $ordered_list = $org->get_flat_items_list();
-            }
-            $previous = 0;
-            $stock = array(0);
-            $level = 0;
-            $parent_id = 0;
-            foreach ($ordered_list as $index => $subarray) {
-                // $subarray is an array representing one item and that contains info like
-                // identifier, level, rel_order, prerequisites, title, masteryscore, etc.
-                //echo "<pre>Lookin for ".$subarray['identifier']." ".print_r($lp_item_refs,true)."</pre>\n";
-                if (!empty($lp_item_refs[$in_id][$subarray['identifier']])) {
-                    $new_id = $lp_item_refs[$in_id][$subarray['identifier']];
-                    $next = 0;
-                    $dsp = $subarray['rel_order'];
-                    if ($subarray['level'] > $level) {
-                        // Getting one level deeper, just consult
-                        $parent_id = $previous;
-                        array_push($stock,$previous);
-                        $level = $subarray['level'];
-                    } elseif ($subarray['level'] == $level) {
-                        // We are on the same level, going to the next id
-                        //array_pop($stock);
-                        //array_push($stock, $new_id);
-                    } else {
-                        // Getting back from one level deeper
-                        array_pop($stock);
-                        $parent_id = array_pop($stock);
-                        array_push($stock, $parent_id);
-                        $level = $subarray['level'];
-                    }
-                    if (!empty($ordered_list[$index + 1]['identifier']) && !empty($lp_item_refs[$in_id][$ordered_list[$index + 1]['identifier']])){
-                        $next = $lp_item_refs[$in_id][$ordered_list[$index + 1]['identifier']];
-                    }
-                    $path = $oScorm->get_res_path($subarray['identifierref']);
-                    $update_path = '';
-                    if (!empty($path)) {
-                        // If new path is not empty, update
-                        $update_path = "path = '$path', ";
-                    }
-                    $type = $oScorm->get_res_type($subarray['identifierref']);
-                    $update_type = '';
-                    if (!empty($type)) {
-                        // If type is defined, update
-                        $update_type = "item_type = '$type', ";
-                    }
-                    if (empty($path)) {
-                        // If path is empty, it is a dir anyway
-                        $update_type = "item_type = 'dir', ";
-                    }
-                    $prereq = $subarray['prerequisites'];
-                    $update_prereq = '';
-                    if (!empty($prereq)) {
-                        $update_prereq = "prerequisite = '$prereq', ";
-                    }
-
-                    // We had previous data about this element, update
-                    $sql2 = "UPDATE $my_new_lp_item " .
-                            "SET parent_item_id = $parent_id, " .
-                            "previous_item_id = $previous, " .
-                            "next_item_id = $next, " .
-                            $update_path.
-                            $update_type.
-                            $update_prereq.
-                            "display_order = $dsp " .
-                            "WHERE lp_id = ".$in_id." AND id = ".$new_id;
-                    //echo "$sql2<br />\n";
-                    $res2 = Database::query($sql2);
-                    $previous = $new_id;
-                }
-            }
-            /**
-             * Migrate links on the homepage as well now (look into the TABLE_TOOL_LIST table and
-             * update the links to newscorm/lp_controller.php?action=view&lp_id=x)
-             * See scorm_migrate_hometools.php
-             */
-        //}
-    // end of case where $my_content_id != -1
-
-    }
-
-    /**
-     * Update course description (intro page) to use new links instead of learnpath/learnpath_handler.php
-     */
-    $tbl_intro = $db_name.TABLE_TOOL_INTRO;
-    $sql_i = "SELECT * FROM $tbl_intro WHERE id='course_homepage'";
-    $res_i = Database::query($sql_i);
-    //$link_to_course1 = 'scorm/scormdocument.php';
-    while ($row_i = Database::fetch_array($res_i)) {
-        $intro = $row_i['intro_text'];
-        $out = array();
-        $enc_path = str_replace('/', '%2F', $my_path);
-        $enc_path = str_replace(' ', '\+', $enc_path);
-        //echo "Looking for path ".$enc_path."<br />\n";
-        $pattern = '@claroline/scorm/scormdocument\.php([^\s"\']*)openDir='.$enc_path.'([\\"\'\s&]*)@';
-        if (preg_match_all($pattern, $intro, $out, PREG_SET_ORDER)) {
-            foreach ($out as $results) {
-                //echo "---> replace ".'/'.$results[0].'/ by newscorm/lp_controller.php'.$results[1].'action=view&lp_id='.$lp_ids[$my_content_id];
-                //$intro = preg_replace('/scorm\/scormdocument\.php([^\s"\']*)openDir='.$enc_path.'([\\"\'\s&])/', 'newscorm/lp_controller.php'.$results[1].'action=view&lp_id='.$lp_ids[$my_content_id], $intro);
-                $intro = preg_replace('@claroline/scorm/scormdocument\.php([^\s"\']*)openDir='.$enc_path.'([^\s"\']*)@','main/newscorm/lp_controller.php'.$results[1].'action=view&lp_id='.$lp_ids[$my_content_id], $intro);
-            }
-        } else {
-            //echo "No scorm link found in intro text<br />";
-        }
-        $pattern = '@claroline/scorm/showinframes\.php([^\s"\']*)file=([^\s"\'&]*)'.$enc_path.'@';
-        if (preg_match_all($pattern, $intro, $out, PREG_SET_ORDER)) {
-            foreach ($out as $results) {
-                //echo "---> replace ".'/'.$results[0].'/ by newscorm/lp_controller.php'.$results[1].'action=view&lp_id='.$lp_ids[$my_content_id];
-                //$intro = preg_replace('/scorm\/showinframes\.php([^\s"\']*)file=([^\s"\']*)'.$enc_path.'/', 'newscorm/lp_controller.php'.$results[1].'action=view&lp_id='.$lp_ids[$my_content_id], $intro);
-                $intro = preg_replace('@claroline/scorm/showinframes\.php([^\s"\']*)file=([^\s"\'&]*)'.$enc_path.'([^\s"\']*)@','main/newscorm/lp_controller.php'.$results[1].'action=view&lp_id='.$lp_ids[$my_content_id], $intro);
-            }
-        } else {
-            //echo "No scorm link found in intro text<br />";
-        }
-        if ($intro != $row_i['intro_text']) {
-            //echo "<pre>Replacing ".$row_i['intro_text']."\n by \n ".$intro."</pre><br />\n";
-            $sql_upd = "update $tbl_intro set intro_text = '".Database::escape_string($intro)."' WHERE id = 'course_homepage' AND intro_text = '".Database::escape_string($row_i['intro_text'])."'";
-            //echo $sql_upd."<br />\n";
-            fwrite($fh, $sql_upd."\n");
-            fwrite($fh_revert, "UPDATE $tbl_intro set intro_text = '".$row_i['intro_text']."' WHERE id = 'course_homepage' AND intro_text = '$intro';\n");
-            fwrite($fh_res, $intro."\n");
-            Database::query($sql_upd);
-        }
-    }
-
-    flush();
-  }
-}
-fclose($fh);
-fclose($fh_revert);
-fclose($fh_res);
-if ($loglevel > 0) { Log::notice("All done!"); }
-//echo "</body></html>";