From 9558ee30f86c98d35bc252ecca49a54fa16a7504 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 26 Mar 2015 11:54:46 +0100 Subject: [PATCH 001/159] Remove database.mysqli.lib.php replace to use Doctrine. --- main/inc/lib/database.constants.inc.php | 2 +- main/inc/lib/database.lib.php | 248 ++--- main/inc/lib/database.mysqli.lib.php | 1098 ---------------------- main/inc/lib/databaseDoctrine.php | 1126 ----------------------- 4 files changed, 99 insertions(+), 2375 deletions(-) delete mode 100755 main/inc/lib/database.mysqli.lib.php delete mode 100644 main/inc/lib/databaseDoctrine.php diff --git a/main/inc/lib/database.constants.inc.php b/main/inc/lib/database.constants.inc.php index e94c0c6624..432662be50 100755 --- a/main/inc/lib/database.constants.inc.php +++ b/main/inc/lib/database.constants.inc.php @@ -2,7 +2,7 @@ /* For licensing terms, see /license.txt */ /** * This is the database constants definition for Chamilo - * This file is called by database.lib.php and database.mysqli.lib.php + * This file is called by database.lib.php * * @todo the table constants have all to start with TABLE_ * This is because of the analogy with the tool constants TOOL_ diff --git a/main/inc/lib/database.lib.php b/main/inc/lib/database.lib.php index 66250435e1..4dc5fa24f6 100755 --- a/main/inc/lib/database.lib.php +++ b/main/inc/lib/database.lib.php @@ -7,17 +7,6 @@ use Doctrine\DBAL\Driver\Statement; /** * Class Database - * This is the main database library for Chamilo. - * Include/require it in your code to use its functionality. - * Because this library contains all the basic database calls, it could be - * replaced by another library for say, PostgreSQL, to actually use Chamilo - * with another database (this is not ready yet because a lot of code still - * uses the MySQL database functions extensively). - * - * If trying to replicate the database layer, don't forget to look for "sql" - * named functions in main_api.lib.php - * - * @package chamilo.library */ class Database { @@ -51,77 +40,11 @@ class Database */ public static function get_main_database() { - global $_configuration; - return $_configuration['main_database']; + return self::getManager()->getConnection()->getDatabase(); + /*global $_configuration; + return $_configuration['main_database'];*/ } - /** - * Returns the glued name of the current course database. - * @return mixed Glued database name of false if undefined - */ - public static function get_current_course_glued_database() - { - $course_info = api_get_course_info(); - if (empty($course_info['dbNameGlu'])) { - return false; - } - return $course_info['dbNameGlu']; - } - - /** - * The glue is the string needed between database and table. - * The trick is: in multiple databases, this is a period (with backticks). - * In single database, this can be e.g. an underscore so we just fake - * there are multiple databases and the code can be written independent - * of the single / multiple database setting. - */ - public static function get_database_glue() - { - global $_configuration; - return $_configuration['db_glue']; - } - - /** - * Returns the database prefix. - * All created COURSE databases are prefixed with this string. - * - * TIP: This can be convenient if you have multiple system installations - * on the same physical server. - */ - public static function get_database_name_prefix() - { - global $_configuration; - return $_configuration['db_prefix']; - } - - /** - * Returns the course table prefix for single database. - * Not certain exactly when this is used. - * Do research. - * It's used in local.inc.php. - */ - public static function get_course_table_prefix() - { - global $_configuration; - return $_configuration['table_prefix']; - } - - /* - Table name methods - Use these methods to get table names for queries, - instead of constructing them yourself. - - Backticks automatically surround the result, - e.g. COURSE_NAME.link - so the queries can look cleaner. - - Example: - $table = Database::get_course_table(TABLE_DOCUMENT); - $sql_query = "SELECT * FROM $table WHERE $condition"; - $sql_result = Database::query($sql_query); - $result = Database::fetch_array($sql_result); - */ - /** * A more generic method than the other get_main_xxx_table methods, * This one returns the correct complete name of any table of the main @@ -133,9 +56,11 @@ class Database */ public static function get_main_table($short_table_name) { + return $short_table_name; + /* return self::format_table_name( - self::get_main_database(), - $short_table_name); + self::get_main_database(), + $short_table_name);*/ } /** @@ -151,6 +76,8 @@ class Database */ public static function get_course_table($short_table_name, $extra = null) { + return DB_COURSE_PREFIX.$short_table_name; + /* //forces fatal errors so we can debug more easily if (!empty($extra)) { var_dump($extra); @@ -158,7 +85,7 @@ class Database echo "

Dev Message: get_course_table() doesn't have a 2nd parameter

"; //exit; } - return self::format_table_name(self::get_main_database(), DB_COURSE_PREFIX.$short_table_name); + return self::format_table_name(self::get_main_database(), DB_COURSE_PREFIX.$short_table_name);*/ } /* @@ -173,7 +100,7 @@ class Database * @deprecated */ public static function count_rows($table) { - $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table")); // + $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table")); return $obj->n; } @@ -186,8 +113,10 @@ class Database * @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. */ - public static function affected_rows($connection = null) { - return self::use_default_connection($connection) ? mysql_affected_rows() : mysql_affected_rows($connection); + public static function affected_rows(Statement $result) + { + return $result->rowCount(); + //return self::use_default_connection($connection) ? mysql_affected_rows() : mysql_affected_rows($connection); } /** @@ -286,13 +215,16 @@ class Database */ public static function escape_string($string, $connection = null, $addFix = true) { - return get_magic_quotes_gpc() + $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)); + : mysql_real_escape_string($string, $connection));-*/ } @@ -303,10 +235,14 @@ class Database * @return array Array of results as returned by php * @author Yannick Warnier */ - public static function fetch_array($result, $option = 'BOTH') + public static function fetch_array(Statement $result, $option = 'BOTH') { - 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)); + 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)); } /** @@ -315,8 +251,10 @@ class Database * @param resource $result The result from a call to sql_query (e.g. Database::query). * @return array Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. */ - public static function fetch_assoc($result) { - return mysql_fetch_assoc($result); + public static function fetch_assoc(Statement $result) + { + return $result->fetch(PDO::FETCH_ASSOC); + //return mysql_fetch_assoc($result); } /** @@ -327,8 +265,11 @@ class Database * @return object Object of class StdClass or the required class, containing the query result row * @author Yannick Warnier */ - public static function fetch_object($result, $class = null, $params = null) { - return !empty($class) ? (is_array($params) ? mysql_fetch_object($result, $class, $params) : mysql_fetch_object($result, $class)) : mysql_fetch_object($result); + //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); } /** @@ -336,8 +277,10 @@ class Database * @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) */ - public static function fetch_row($result) { - return mysql_fetch_row($result); + public static function fetch_row(Statement $result) + { + return $result->fetch(PDO::FETCH_NUM); + //return mysql_fetch_row($result); } /** @@ -346,8 +289,10 @@ class Database * Notes: Use this method if you are concerned about how much memory is being used for queries that return large result sets. * Anyway, all associated result memory is automatically freed at the end of the script's execution. */ - public static function free_result($result) { - return mysql_free_result($result); + public static function free_result(Statement $result) + { + $result->closeCursor(); + //return mysql_free_result($result); } /** @@ -431,8 +376,10 @@ class Database * @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 */ - public static function insert_id($connection = null) { - return self::use_default_connection($connection) ? mysql_insert_id() : mysql_insert_id($connection); + public static function insert_id() + { + return self::getManager()->getConnection()->lastInsertId(); + //return self::use_default_connection($connection) ? mysql_insert_id() : mysql_insert_id($connection); } /** @@ -441,8 +388,10 @@ class Database * @return integer The number of rows contained in this result * @author Yannick Warnier **/ - public static function num_rows($result) { - return is_resource($result) ? mysql_num_rows($result) : false; + public static function num_rows(Statement $result) + { + return $result->rowCount(); + //return is_resource($result) ? mysql_num_rows($result) : false; } /** @@ -453,8 +402,13 @@ class Database * @param string Optional field name or number * @return mixed One cell of the result, or FALSE on error */ - public static function result($resource, $row, $field = '') { - return self::num_rows($resource) > 0 ? (!empty($field) ? mysql_result($resource, $row, $field) : mysql_result($resource, $row)) : null; + 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; } /** @@ -470,7 +424,7 @@ class Database * @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) * - * @return resource The returned result from the query + * @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); @@ -485,6 +439,10 @@ class Database */ public static function query($query, $connection = null, $file = null, $line = null) { + $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 @@ -614,6 +572,26 @@ class Database return $result; } + /** + * @param string $option + * @return int + */ + public static function customOptionToDoctrineOption($option) + { + switch($option) { + case 'ASSOC': + return PDO::FETCH_ASSOC; + break; + case 'NUM': + return PDO::FETCH_NUM; + break; + case 'BOTH': + default: + return PDO::FETCH_BOTH; + break; + } + } + /** * Selects a database. * @param string $database_name The name of the database that is to be selected. @@ -632,7 +610,10 @@ class Database * @param option BOTH, ASSOC, or NUM * @return array - the value returned by the query */ - public static function store_result($result, $option = 'BOTH') { + 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)) { @@ -777,21 +758,6 @@ class Database No effort is made to keep the names / results the same. */ - /** - * Structures a database and table name to ready them - * for querying. The database parameter is considered not glued, - * just plain e.g. COURSE001 - */ - private static function format_table_name($database, $table) { - global $_configuration; - if ($_configuration['single_database']) { - $table_name = '`'.$database.'`.`'.$table.'`'; - } else { - $table_name = '`'.$database.$_configuration['db_glue'].$table.'`'; - } - return $table_name; - } - /** * 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. @@ -805,16 +771,6 @@ class Database return !is_resource($connection) && $connection !== false; } - /** - * This private method tackles the XSS injections. It is similar to Security::remove_XSS() and works always, - * including the time of initialization when the class Security has not been loaded yet. - * @param string The input variable to be filtered from XSS, in this class it is expected to be a string. - * @return string Returns the filtered string as a result. - */ - private static function remove_XSS(& $var) { - return class_exists('Security') ? Security::remove_XSS($var) : @htmlspecialchars($var, ENT_QUOTES, api_get_system_encoding()); - } - /** * This private method encapsulates a table with relations between * conventional and MuSQL-specific encoding identificators. @@ -900,6 +856,12 @@ class Database */ public static function insert($table_name, $attributes, $show_query = false) { + $result = self::getManager()->getConnection()->insert($table_name, $attributes); + if ($result) { + return self::insert_id(); + } + return false; + if (empty($attributes) || empty($table_name)) { return false; } @@ -1082,8 +1044,8 @@ class Database $where_return = self::parse_where_conditions($where_conditions); $sql = "DELETE FROM $table_name $where_return "; if ($show_query) { echo $sql; echo '
'; } - self::query($sql); - $affected_rows = self::affected_rows(); + $result = self::query($sql); + $affected_rows = self::affected_rows($result); //@todo should return affected_rows for return $affected_rows; } @@ -1123,28 +1085,14 @@ class Database if ($show_query) { var_dump($sql); } - self::query($sql); - $affected_rows = self::affected_rows(); + $result = self::query($sql); + $affected_rows = self::affected_rows($result); return $affected_rows; } } return false; } - /** - * @deprecated Use api_get_language_isocode($language) instead. - */ - public static function get_language_isocode($language) { - return api_get_language_isocode($language); - } - - /** - * @deprecated Use Database::insert_id() instead. - */ - public static function get_last_insert_id() { - return mysql_insert_id(); - } - /** * @return \Doctrine\ORM\Configuration */ diff --git a/main/inc/lib/database.mysqli.lib.php b/main/inc/lib/database.mysqli.lib.php deleted file mode 100755 index 17acd04e4a..0000000000 --- a/main/inc/lib/database.mysqli.lib.php +++ /dev/null @@ -1,1098 +0,0 @@ -n; - } - - /* - An intermediate API-layer between the system and the dabase server. - */ - - /** - * Returns the number of affected rows in the last database operation. - * @param resource $connection 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. - */ - public static function affected_rows($connection = null) - { - global $database_connection; - return $database_connection->affected_rows; - } - - /** - * 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) ? mysqli::close() : mysqli::close($connection); - } - - /** - * Opens a connection to a database server. - * @param array $parameters (optional) An array that contains the necessary parameters for accessing the server. - * @return resource/boolean Returns a database connection on success or FALSE on failure. - * Note: Currently the array could contain MySQL-specific parameters: - * $parameters['server'], $parameters['username'], $parameters['password'], - * $parameters['new_link'], $parameters['client_flags'], $parameters['persistent']. - * For details see documentation about the functions mysql_connect() and mysql_pconnect(). - * @link http://php.net/manual/en/function.mysql-connect.php - * @link http://php.net/manual/en/function.mysql-pconnect.php - */ - public static function connect($parameters = array()) - { - global $database_connection; - // A MySQL-specific implementation. - if (!isset($parameters['server'])) { - $parameters['server'] = @ini_get('mysqli.default_host'); - if (empty($parameters['server'])) { - $parameters['server'] = 'localhost:3306'; - } - } - if (!isset($parameters['username'])) { - $parameters['username'] = @ini_get('mysqli.default_user'); - } - if (!isset($parameters['password'])) { - $parameters['password'] = @ini_get('mysqli.default_pw'); - } - $database_connection = $parameters['persistent'] - ? new mysqli('p:'.$parameters['server'], $parameters['username'], $parameters['password']) - : new mysqli($parameters['server'], $parameters['username'], $parameters['password']); - if ($database_connection->connect_errno) { - error_log($database_connection->connect_errno()); - return false; - } else { - return true; - } - } - - /** - * Returns the 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) ? mysqli::mysqli_errno() : mysqli::mysqli_errno($connection); - } - - /** - * Returns the 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(). - * @return string Returns the error text from the last database operation, or '' (empty string) if no error occurred. - */ - public static function error($connection = null) - { - return self::use_default_connection($connection) ? mysqli::mysqli_error() : mysqli::mysqli_error($connection); - } - - /** - * Escapes a string to insert into the database as text - * @param string The string to escape - * @param resource $connection (optional) The database server connection, for detailed description see the method query(). - * @return string The escaped string - * @author Yannick Warnier - * @author Patrick Cool , Ghent University - */ - public static function escape_string($string, $connection = null) - { - global $database_connection; - return get_magic_quotes_gpc() - ? ( $database_connection->escape_string(stripslashes($string))) - : ( $database_connection->escape_string($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) - * @param string Optional: "ASSOC","NUM" or "BOTH", as the constant used in mysqli_fetch_array. - * @return array Array of results as returned by php - * @author Yannick Warnier - */ - public static function fetch_array($result, $option = 'BOTH') - { - return ($option == 'ASSOC') ? $result->fetch_array(MYSQLI_ASSOC) : ($option == 'NUM' ? $result->fetch_array(MYSQLI_NUM) : $result->fetch_array()); - } - - /** - * Gets an associative array from a SQL result (as returned by Database::query). - * This method is equivalent to calling Database::fetch_array() with 'ASSOC' value for the optional second parameter. - * @param resource $result The result from a call to sql_query (e.g. Database::query). - * @return array Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. - */ - public static function fetch_assoc($result) - { - return $result->fetch_assoc(); - } - - /** - * Gets the next row of the result of the SQL query (as returned by Database::query) in an object form - * @param mysqli $result The result from a call to sql_query (e.g. Database::query) - * @param string $class Optional class name to instantiate - * @param array $params Optional array of parameters - * @return resource Object of class StdClass or the required class, containing the query result row - * @author Yannick Warnier - */ - public static function fetch_object($result, $class = null, $params = null) - { - return !empty($class) ? (is_array($params) ? $result->fetch_object($class, $params) : $result->fetch_object($class)) : $result->fetch_object(); - } - - /** - * 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) - */ - public static function fetch_row($result) - { - return $result->fetch_row(); - } - - /** - * Frees all the memory associated with the provided result identifier. - * @return bool Returns TRUE on success or FALSE on failure. - * Notes: Use this method if you are concerned about how much memory is being used for queries that return large result sets. - * Anyway, all associated result memory is automatically freed at the end of the script's execution. - */ - public static function free_result($result) - { - return $result->free_result(); - } - - /** - * Returns the database client library version. - * @return string String that represents the client library version. - */ - public function get_client_info() - { - return mysqli_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 A pattern for filtering database names as if it was needed for the SQL's LIKE clause, for example 'chamilo_%'. - * @param resource $connection 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 function get_host_info($connection = null) - { - return self::use_default_connection($connection) ? mysqli::mysqli_get_host_info() : mysqli::mysqli_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 function get_proto_info($connection = null) - { - return self::use_default_connection($connection) ? mysqli::mysqli_get_proto_info() : mysqli::mysqli_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 function get_server_info($connection = null) - { - return self::use_default_connection($connection) ? mysqli::mysqli_get_server_info() : mysqli::mysqli_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 omitted, 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 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 - * @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 - * @comment This should be updated to use ADODB at some point - */ - public static function insert_id($connection = null) - { - global $database_connection; - return $database_connection->insert_id; - } - - /** - * 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 - **/ - public static function num_rows($result) - { - return is_a($result,'mysqli_result') ? $result->num_rows : 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 - * @result mixed One cell of the result, or FALSE on error - */ - public static function result(&$resource, $row, $field = '') - { - if (self::num_rows($resource) > 0) { - if (!empty($field)) { - $r = mysqli_data_seek($resource, $row); - return $r[$field]; - } else { - return mysqli_data_seek($resource, $row); - } - } else { return 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 triggered (use the "magic" constant __FILE__ as input parameter) - * @param string $line (optional) On error it shows the line in which the error has been triggered (use the "magic" constant __LINE__ as input parameter) - * @return resource 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__); - */ - public static function query($query, $connection = null, $file = null, $line = null) - { - global $database_connection; - - $result = @$database_connection->query($query); - if ($database_connection->errno) { - $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 = $owner['type']; - $function = $owner['function']; - $class = $owner['class']; - $server_type = api_get_setting('server_type'); - if (!empty($line) && !empty($server_type) && $server_type != 'production') { - $info = '
' .
-                    'DATABASE ERROR #'.self::errno($connection).':
' . - self::remove_XSS(self::error($connection)) . '
' . - 'QUERY :
' . - self::remove_XSS($query) . '
' . - 'FILE :
' . - (empty($file) ? ' unknown ' : $file) . '
' . - 'LINE :
' . - (empty($line) ? ' unknown ' : $line) . '
'; - if (empty($type)) { - if (!empty($function)) { - $info .= 'FUNCTION :
' . $function; - } - } else { - if (!empty($class) && !empty($function)) { - $info .= 'CLASS :
' . $class . '
'; - $info .= 'METHOD :
' . $function; - } - } - $info .= '
'; - 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); - error_log($info); - $info = 'LINE: '.(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; - error_log($info); - $info .= 'METHOD: ' . $function; - error_log($info); - } - } - error_log("---------------- end ----------------"); - } - - } - return $result; - } - - /** - * 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) - { - global $database_connection; - $database_connection->select_db($database_name); - return !$database_connection->errno; - //return self::use_default_connection($connection) ? mysqli_select_db($connection, $database_name) : mysqli_select_db($connection, $database_name); - } - - /** - * Stores a query result into an array. - * - * @author Olivier Brouckaert - * @param resource $result - the return value of the query - * @param option BOTH, ASSOC, or NUM - * @return array - the value returned by the query - */ - public static function store_result($result, $option = 'BOTH') - { - $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 identifier, - * i.e. 'UTF-8' --> 'utf8'. - * @param string $encoding The conventional encoding identifier. - * @return string Returns the corresponding MySQL-specific encoding identifier 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 identifier to conventional encoding identifier, - * i.e. 'utf8' --> 'UTF-8'. - * @param string $encoding The MySQL-specific encoding identifier. - * @return string Returns the corresponding conventional encoding identifier 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. - */ - - /** - * Glues a course database. - * glue format from local.inc.php. - */ - private static function glue_course_database_name($database_name) - { - return self::get_course_table_prefix().$database_name.self::get_database_glue(); - } - - /** - * @param string $database_name, can be empty to use current course db - * - * @return the glued parameter if it is not empty, - * or the current course database (glued) if the parameter is empty. - */ - private static function fix_database_parameter($database_name) - { - if (empty($database_name)) { - $course_info = api_get_course_info(); - return $course_info['dbNameGlu']; - } - return self::glue_course_database_name($database_name); - } - - /** - * Structures a course database and table name to ready them - * for querying. The course database parameter is considered glued: - * e.g. COURSE001`.` - */ - private static function format_glued_course_table_name($database_name_with_glue, $table) - { - return '`'.$database_name_with_glue.$table.'`'; - } - - /** - * Structures a database and table name to ready them - * for querying. The database parameter is considered not glued, - * just plain e.g. COURSE001 - */ - private static function format_table_name($database, $table) - { - return '`'.$database.'`.`'.$table.'`'; - } - - /** - * 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 tackles the XSS injections. It is similar to Security::remove_XSS() and works always, - * including the time of initialization when the class Security has not been loaded yet. - * @param string The input variable to be filtered from XSS, in this class it is expected to be a string. - * @return string Returns the filtered string as a result. - */ - private static function remove_XSS(& $var) - { - return class_exists('Security') ? Security::remove_XSS($var) : @htmlspecialchars($var, ENT_QUOTES, api_get_system_encoding()); - } - - /** - * 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; - } - - /* - New useful DB functions - */ - - /** - * Experimental useful database insert - * @todo lot of stuff to do here - */ - public static function insert($table_name, $attributes) - { - if (empty($attributes) || empty($table_name)) { - return false; - } - $filtred_attributes = array(); - foreach($attributes as $key => $value) { - $filtred_attributes[$key] = "'".self::escape_string($value)."'"; - } - $params = array_keys($filtred_attributes); //@todo check if the field exists in the table we should use a describe of that table - $values = array_values($filtred_attributes); - if (!empty($params) && !empty($values)) { - $sql = 'INSERT INTO '.$table_name.' ('.implode(',',$params).') VALUES ('.implode(',',$values).')'; - $result = self::query($sql); - return self::get_last_insert_id(); - } - return false; - } - - /** - * Experimental useful database finder - * @todo lot of stuff to do here - */ - - public static function select($columns, $table_name, $conditions = array(), $type_result = 'all', $option = 'ASSOC') - { - $conditions = self::parse_conditions($conditions); - - //@todo we could do a describe here to check the columns ... - $clean_columns = ''; - if (is_array($columns)) { - $clean_columns = implode(',', $columns); - } else { - if ($columns == '*') { - $clean_columns = '*'; - } else { - $clean_columns = (string)$columns; - } - } - - - $sql = "SELECT $clean_columns FROM $table_name $conditions"; - - $result = self::query($sql); - $array = array(); - //if (self::num_rows($result) > 0 ) { - if ($type_result == 'all') { - while ($row = self::fetch_array($result, $option)) { - if (isset($row['id'])) { - $array[$row['id']] = $row; - } else { - $array[] = $row; - } - } - } else { - $array = self::fetch_array($result, $option); - } - return $array; - } - - /** - * Parses WHERE/ORDER conditions i.e array('where'=>array('id = ?' =>'4'), 'order'=>'id DESC')) - * @param array - * @todo lot of stuff to do here - */ - static function parse_conditions($conditions) - { - if (empty($conditions)) { - return ''; - } - $return_value = ''; - foreach ($conditions as $type_condition => $condition_data) { - $type_condition = strtolower($type_condition); - switch($type_condition) { - case 'where': - $where_return = ''; - foreach ($condition_data as $condition => $value_array) { - if (is_array($value_array)) { - $clean_values = array(); - foreach($value_array as $item) { - $item = Database::escape_string($item); - $clean_values[]= $item; - } - } else { - $value_array = Database::escape_string($value_array); - $clean_values = $value_array; - } - if (!empty($condition) && $clean_values != '') { - $condition = str_replace('%',"'@percentage@'", $condition); //replace "%" - $condition = str_replace("'?'","%s", $condition); - $condition = str_replace("?","%s", $condition); - - $condition = str_replace("@%s@","@-@", $condition); - $condition = str_replace("%s","'%s'", $condition); - $condition = str_replace("@-@","@%s@", $condition); - - //Treat conditons as string - $condition = vsprintf($condition, $clean_values); - $condition = str_replace('@percentage@','%', $condition); //replace "%" - $where_return .= $condition; - } - } - if (!empty($where_return)) { - $return_value = " WHERE $where_return" ; - } - break; - case 'order': - $order_array = $condition_data; - - if (!empty($order_array)) { - // 'order' => 'id desc, name desc' - $order_array = self::escape_string($order_array); - $new_order_array = explode(',', $order_array); - $temp_value = array(); - - foreach($new_order_array as $element) { - $element = explode(' ', $element); - $element = array_filter($element); - $element = array_values($element); - - if (!empty($element[1])) { - $element[1] = strtolower($element[1]); - $order = 'DESC'; - if (in_array($element[1], array('desc', 'asc'))) { - $order = $element[1]; - } - $temp_value[]= $element[0].' '.$order.' '; - } else { - //by default DESC - $temp_value[]= $element[0].' DESC '; - } - } - if (!empty($temp_value)) { - $return_value .= ' ORDER BY '.implode(', ', $temp_value); - } else { - //$return_value .= ''; - } - } - break; - - case 'limit': - $limit_array = explode(',', $condition_data); - if (!empty($limit_array)) { - if (count($limit_array) > 1) { - $return_value .= ' LIMIT '.intval($limit_array[0]).' , '.intval($limit_array[1]); - } else { - $return_value .= ' LIMIT '.intval($limit_array[0]); - } - } - break; - - } - } - return $return_value; - } - - public static function parse_where_conditions($coditions) - { - return self::parse_conditions(array('where'=>$coditions)); - } - - /** - * Experimental useful database update - * @todo lot of stuff to do here - */ - public static function delete($table_name, $where_conditions) - { - $result = false; - $where_return = self::parse_where_conditions($where_conditions); - $sql = "DELETE FROM $table_name $where_return "; - $result = self::query($sql); - $affected_rows = self::affected_rows(); - //@todo should return affected_rows for - return $affected_rows; - } - - - /** - * Experimental useful database update - * @todo lot of stuff to do here - */ - public static function update($table_name, $attributes, $where_conditions = array()) - { - - if (!empty($table_name) && !empty($attributes)) { - $update_sql = ''; - //Cleaning attributes - $count = 1; - foreach ($attributes as $key=>$value) { - $value = self::escape_string($value); - $update_sql .= "$key = '$value' "; - if ($count < count($attributes)) { - $update_sql.=', '; - } - $count++; - } - if (!empty($update_sql)) { - //Parsing and cleaning the where conditions - $where_return = self::parse_where_conditions($where_conditions); - $sql = "UPDATE $table_name SET $update_sql $where_return "; - //echo $sql; exit; - $result = self::query($sql); - $affected_rows = self::affected_rows(); - return $affected_rows; - } - } - return false; - } -} diff --git a/main/inc/lib/databaseDoctrine.php b/main/inc/lib/databaseDoctrine.php deleted file mode 100644 index 4d92dd58c7..0000000000 --- a/main/inc/lib/databaseDoctrine.php +++ /dev/null @@ -1,1126 +0,0 @@ -getConnection()->getDatabase(); - /*global $_configuration; - return $_configuration['main_database'];*/ - } - - /** - * A more generic method than the other get_main_xxx_table methods, - * This one returns the correct complete name of any table of the main - * database of which you pass the short name as a parameter. - * 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 - */ - public static function get_main_table($short_table_name) - { - return $short_table_name; - /* - return self::format_table_name( - self::get_main_database(), - $short_table_name);*/ - } - - /** - * A more generic method than the older get_course_xxx_table methods, - * This one can return the correct complete name of any course table of - * which you pass the short name as a parameter. - * 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. - */ - public static function get_course_table($short_table_name, $extra = null) - { - return DB_COURSE_PREFIX.$short_table_name; - /* - //forces fatal errors so we can debug more easily - if (!empty($extra)) { - var_dump($extra); - //@todo remove this - echo "

Dev Message: get_course_table() doesn't have a 2nd parameter

"; - //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) { - $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table")); - return $obj->n; - } - - /* - An intermediate API-layer between the system and the database server. - */ - - /** - * 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. - */ - 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); - } - - /** - * Opens a connection to a database server. - * @param array $parameters (optional) An array that contains the necessary parameters for accessing the server. - * @return resource/boolean Returns a database connection on success or FALSE on failure. - * Note: Currently the array could contain MySQL-specific parameters: - * $parameters['server'], $parameters['username'], $parameters['password'], - * $parameters['new_link'], $parameters['client_flags'], $parameters['persistent']. - * For details see documentation about the functions mysql_connect() and mysql_pconnect(). - * @link http://php.net/manual/en/function.mysql-connect.php - * @link http://php.net/manual/en/function.mysql-pconnect.php - */ - public static function connect($parameters = array()) { - // A MySQL-specific implementation. - if (!isset($parameters['server'])) { - $parameters['server'] = @ini_get('mysql.default_host'); - if (empty($parameters['server'])) { - $parameters['server'] = 'localhost:3306'; - } - } - if (!isset($parameters['username'])) { - $parameters['username'] = @ini_get('mysql.default_user'); - } - if (!isset($parameters['password'])) { - $parameters['password'] = @ini_get('mysql.default_password'); - } - if (!isset($parameters['new_link'])) { - $parameters['new_link'] = false; - } - if (!isset($parameters['client_flags']) || empty($parameters['client_flags'])) { - $parameters['client_flags'] = 0; - } - - $persistent = isset($parameters['persistent']) ? $parameters['persistent'] : null; - $server = isset($parameters['server']) ? $parameters['server'] : null; - $username = isset($parameters['username']) ? $parameters['username'] : null; - $password = isset($parameters['password']) ? $parameters['password'] : null; - $client_flag = isset($parameters['client_flags']) ? $parameters['client_flags'] : null; - $new_link = isset($parameters['new_link']) ? $parameters['new_link'] : null; - $client_flags = isset($parameters['client_flags']) ? $parameters['client_flags'] : null; - return $persistent - ? mysql_pconnect($server, $username, $password, $client_flags) - : 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(). - * @return string Returns the error text from the last database operation, or '' (empty string) if no error occurred. - */ - public static function error($connection = null) { - return self::use_default_connection($connection) ? mysql_error() : mysql_error($connection); - } - - /** - * Escape MySQL wildchars _ and % in LIKE search - * @param string The string to escape - * @return string The escaped string - */ - public static function escape_sql_wildcards($in_txt) - { - $out_txt = api_preg_replace("/_/", "\_", $in_txt); - $out_txt = api_preg_replace("/%/", "\%", $out_txt); - - return $out_txt; - } - - /** - * 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 - * @author Patrick Cool , Ghent University - */ - public static function escape_string($string, $connection = null, $addFix = true) - { - $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));-*/ - } - - - /** - * 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) - * @param string Optional: "ASSOC","NUM" or "BOTH", as the constant used in mysql_fetch_array. - * @return array Array of results as returned by php - * @author Yannick Warnier - */ - public static function fetch_array(Statement $result, $option = 'BOTH') - { - 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)); - } - - /** - * Gets an associative array from a SQL result (as returned by Database::query). - * This method is equivalent to calling Database::fetch_array() with 'ASSOC' value for the optional second parameter. - * @param resource $result The result from a call to sql_query (e.g. Database::query). - * @return array Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. - */ - 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 - */ - //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) - */ - public static function fetch_row(Statement $result) - { - return $result->fetch(PDO::FETCH_NUM); - //return mysql_fetch_row($result); - } - - /** - * Frees all the memory associated with the provided result identifier. - * @return bool Returns TRUE on success or FALSE on failure. - * Notes: Use this method if you are concerned about how much memory is being used for queries that return large result sets. - * Anyway, all associated result memory is automatically freed at the end of the script's execution. - */ - 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 - */ - 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 - **/ - 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 - */ - 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) - * - * @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__); - */ - public static function query($query, $connection = null, $file = null, $line = null) - { - $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 '
';
-                $message = '

Dev message: please add the c_id field in this query or report this error in support.chamilo.org

'; - $message .= $query; - echo $message; - echo '
'; - //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 = '
' .
-                    'DATABASE ERROR #'.self::errno($connection).':
' . - self::remove_XSS(self::error($connection)) . '
' . - 'QUERY :
' . - self::remove_XSS($query) . '
' . - 'FILE :
' . - (empty($file) ? ' unknown ' : $file) . '
' . - 'LINE :
' . - (empty($line) ? ' unknown ' : $line) . '
'; - if (empty($type)) { - if (!empty($function)) { - $info .= 'FUNCTION :
' . $function; - } - } else { - if (!empty($class) && !empty($function)) { - $info .= 'CLASS :
' . $class . '
'; - $info .= 'METHOD :
' . $function; - } - } - $info .= '
'; - 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) - { - switch($option) { - case 'ASSOC': - return PDO::FETCH_ASSOC; - break; - case 'NUM': - return PDO::FETCH_NUM; - break; - case 'BOTH': - default: - return PDO::FETCH_BOTH; - break; - } - } - - /** - * 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. - * - * @author Olivier Brouckaert - * @param resource $result - the return value of the query - * @param option BOTH, ASSOC, or NUM - * @return array - the value returned by the query - */ - 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; - } - - /** - * Database insert - * @param string $table_name - * @param array $attributes - * @param bool $show_query - * @return bool|int - */ - public static function insert($table_name, $attributes, $show_query = false) - { - $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; - } - - /** - * Experimental useful database finder - * @todo lot of stuff to do here - * @todo known issues, it doesn't work when using LIKE conditions - * @example array('where'=> array('course_code LIKE "?%"')) - * @example array('where'=> array('type = ? AND category = ?' => array('setting', 'Plugins')) - * @example array('where'=> array('name = "Julio" AND lastname = "montoya"')) - */ - public static function select($columns, $table_name, $conditions = array(), $type_result = 'all', $option = 'ASSOC') - { - $conditions = self::parse_conditions($conditions); - - //@todo we could do a describe here to check the columns ... - if (is_array($columns)) { - $clean_columns = implode(',', $columns); - } else { - if ($columns == '*') { - $clean_columns = '*'; - } else { - $clean_columns = (string)$columns; - } - } - - $sql = "SELECT $clean_columns FROM $table_name $conditions"; - $result = self::query($sql); - $array = array(); - - if ($type_result == 'all') { - while ($row = self::fetch_array($result, $option)) { - if (isset($row['id'])) { - $array[$row['id']] = $row; - } else { - $array[] = $row; - } - } - } else { - $array = self::fetch_array($result, $option); - } - return $array; - } - - /** - * Parses WHERE/ORDER conditions i.e array('where'=>array('id = ?' =>'4'), 'order'=>'id DESC')) - * @todo known issues, it doesn't work when using - * LIKE conditions example: array('where'=>array('course_code LIKE "?%"')) - * @param array $conditions - */ - public static function parse_conditions($conditions) - { - if (empty($conditions)) { - return ''; - } - $return_value = $where_return = ''; - foreach ($conditions as $type_condition => $condition_data) { - if ($condition_data == false) { - continue; - } - $type_condition = strtolower($type_condition); - switch ($type_condition) { - case 'where': - foreach ($condition_data as $condition => $value_array) { - if (is_array($value_array)) { - $clean_values = array(); - foreach($value_array as $item) { - $item = Database::escape_string($item); - $clean_values[]= $item; - } - } else { - $value_array = Database::escape_string($value_array); - $clean_values = $value_array; - } - - if (!empty($condition) && $clean_values != '') { - $condition = str_replace('%',"'@percentage@'", $condition); //replace "%" - $condition = str_replace("'?'","%s", $condition); - $condition = str_replace("?","%s", $condition); - - $condition = str_replace("@%s@","@-@", $condition); - $condition = str_replace("%s","'%s'", $condition); - $condition = str_replace("@-@","@%s@", $condition); - - // Treat conditions as string - $condition = vsprintf($condition, $clean_values); - $condition = str_replace('@percentage@','%', $condition); //replace "%" - $where_return .= $condition; - } - } - - if (!empty($where_return)) { - $return_value = " WHERE $where_return" ; - } - break; - case 'order': - $order_array = $condition_data; - - if (!empty($order_array)) { - // 'order' => 'id desc, name desc' - $order_array = self::escape_string($order_array, null, false); - $new_order_array = explode(',', $order_array); - $temp_value = array(); - - foreach($new_order_array as $element) { - $element = explode(' ', $element); - $element = array_filter($element); - $element = array_values($element); - - if (!empty($element[1])) { - $element[1] = strtolower($element[1]); - $order = 'DESC'; - if (in_array($element[1], array('desc', 'asc'))) { - $order = $element[1]; - } - $temp_value[]= $element[0].' '.$order.' '; - } else { - //by default DESC - $temp_value[]= $element[0].' DESC '; - } - } - if (!empty($temp_value)) { - $return_value .= ' ORDER BY '.implode(', ', $temp_value); - } else { - //$return_value .= ''; - } - } - break; - case 'limit': - $limit_array = explode(',', $condition_data); - if (!empty($limit_array)) { - if (count($limit_array) > 1) { - $return_value .= ' LIMIT '.intval($limit_array[0]).' , '.intval($limit_array[1]); - } else { - $return_value .= ' LIMIT '.intval($limit_array[0]); - } - } - break; - } - } - - return $return_value; - } - - /** - * @param array $conditions - * @return string - */ - public static function parse_where_conditions($conditions) - { - return self::parse_conditions(array('where' => $conditions)); - } - - /** - * Experimental useful database update - * @todo lot of stuff to do here - */ - public static function delete($table_name, $where_conditions, $show_query = false) - { - $where_return = self::parse_where_conditions($where_conditions); - $sql = "DELETE FROM $table_name $where_return "; - if ($show_query) { echo $sql; echo '
'; } - $result = self::query($sql); - $affected_rows = self::affected_rows($result); - //@todo should return affected_rows for - return $affected_rows; - } - - /** - * @param string $table_name use Database::get_main_table - * @param array $attributes Values to updates - * Example: $params['name'] = 'Julio'; $params['lastname'] = 'Montoya'; - * @param array $where_conditions where conditions i.e array('id = ?' =>'4') - * @param bool $show_query - * @return bool|int - */ - public static function update( - $table_name, - $attributes, - $where_conditions = array(), - $show_query = false - ) { - if (!empty($table_name) && !empty($attributes)) { - $update_sql = ''; - //Cleaning attributes - $count = 1; - foreach ($attributes as $key=>$value) { - if (!is_array($value)) { - $value = self::escape_string($value); - } - $update_sql .= "$key = '$value' "; - if ($count < count($attributes)) { - $update_sql.=', '; - } - $count++; - } - if (!empty($update_sql)) { - //Parsing and cleaning the where conditions - $where_return = self::parse_where_conditions($where_conditions); - $sql = "UPDATE $table_name SET $update_sql $where_return "; - if ($show_query) { - var_dump($sql); - } - $result = self::query($sql); - $affected_rows = self::affected_rows($result); - return $affected_rows; - } - } - return false; - } - - /** - * @return \Doctrine\ORM\Configuration - */ - public static function getDoctrineConfig() - { - $isDevMode = true; - $isSimpleMode = false; - $proxyDir = null; - $cache = null; - - $paths = array( - api_get_path(SYS_PATH).'src/Chamilo/CoreBundle/Entity', - api_get_path(SYS_PATH).'src/Chamilo/UserBundle/Entity', - api_get_path(SYS_PATH).'src/Chamilo/CourseBundle/Entity' - ); - - /*$doctrineCache = api_get_path(SYS_ARCHIVE_PATH).'doctrine/'; - - if (!is_dir($doctrineCache)) { - mkdir($doctrineCache, api_get_permissions_for_new_directories(), true); - }*/ - - return \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration( - $paths, - $isDevMode, - $proxyDir, - $cache, - $isSimpleMode - ); - } -} From a40a7f69037861044a1aefc946b862e0d6ba7854 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 26 Mar 2015 12:01:05 +0100 Subject: [PATCH 002/159] Using Doctrine to connect to DB. --- main/inc/global.inc.php | 18 ++---------------- main/install/install.lib.php | 9 +-------- 2 files changed, 3 insertions(+), 24 deletions(-) diff --git a/main/inc/global.inc.php b/main/inc/global.inc.php index 5e46fbb24a..8bba0dbf84 100755 --- a/main/inc/global.inc.php +++ b/main/inc/global.inc.php @@ -144,13 +144,6 @@ if (!$_configuration['db_host']) { die(); } -if (!($conn_return = @Database::connect($params))) { - $global_error_code = 3; - // The database server is not available or credentials are invalid. - require $includePath.'/global_error_message.inc.php'; - die(); -} - // Doctrine ORM configuration use Doctrine\ORM\Tools\Setup; @@ -198,21 +191,14 @@ AnnotationRegistry::registerAutoloadNamespace( $repo = $entityManager->getRepository('ChamiloUserBundle:User'); $repo = $entityManager->getRepository('ChamiloCoreBundle:Course');*/ -if (!($conn_return = @Database::connect($params))) { - $global_error_code = 3; - // The database server is not available or credentials are invalid. - require $includePath.'/global_error_message.inc.php'; - die(); -} - -/*try { +try { $connect = $entityManager->getConnection()->connect(); } catch (Exception $e) { $global_error_code = 3; // The database server is not available or credentials are invalid. require $includePath.'/global_error_message.inc.php'; die(); -}*/ +} $database = new \Database(); $database->setManager($entityManager); diff --git a/main/install/install.lib.php b/main/install/install.lib.php index 0e7a9c6611..d28167a9e7 100755 --- a/main/install/install.lib.php +++ b/main/install/install.lib.php @@ -684,7 +684,7 @@ function database_exists($database_name) */ function testDbConnect($dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm) { - /*$dbParams = array( + $dbParams = array( 'driver' => 'pdo_mysql', 'host' => $dbHostForm, 'user' => $dbUsernameForm, @@ -699,13 +699,6 @@ function testDbConnect($dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm) } catch (Exception $e) { echo $e->getMessage(); $dbConnect = -1; - }*/ - - //Checking user credentials - if (@Database::connect(array('server' => $dbHostForm, 'username' => $dbUsernameForm, 'password' => $dbPassForm)) !== false) { - $dbConnect = 1; - } else { - $dbConnect = -1; } return $dbConnect; //return 1, if no problems, "0" if, in case we can't create a new DB and "-1" if there is no connection. From a91a2fa35f88dbe765b5aaaf9053e6ddae63b8ec Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 26 Mar 2015 13:07:13 +0100 Subject: [PATCH 003/159] Using Doctrine as a DB layer. --- main/inc/global.inc.php | 39 +---- main/inc/lib/database.lib.php | 60 +++++--- main/install/index.php | 252 +++++++++++++------------------- main/install/install.lib.php | 135 +++++++---------- main/install/install_db.inc.php | 15 +- 5 files changed, 204 insertions(+), 297 deletions(-) diff --git a/main/inc/global.inc.php b/main/inc/global.inc.php index 8bba0dbf84..d93e0588cd 100755 --- a/main/inc/global.inc.php +++ b/main/inc/global.inc.php @@ -158,41 +158,9 @@ $dbParams = array( 'dbname' => $_configuration['main_database'], ); -$config = Database::getDoctrineConfig(); - -$config->setEntityNamespaces( - array( - 'ChamiloUserBundle' => 'Chamilo\UserBundle\Entity', - 'ChamiloCoreBundle' => 'Chamilo\CoreBundle\Entity', - 'ChamiloCourseBundle' => 'Chamilo\CourseBundle\Entity' - ) -); - -$entityManager = EntityManager::create($dbParams, $config); - -// Registering Constraints -use Doctrine\Common\Annotations\AnnotationRegistry; -AnnotationRegistry::registerAutoloadNamespace( - 'Symfony\Component\Validator\Constraint', - api_get_path(SYS_PATH)."vendor/symfony/validator" -); - -AnnotationRegistry::registerFile( - api_get_path(SYS_PATH)."vendor/symfony/doctrine-bridge/Symfony/Bridge/Doctrine/Validator/Constraints/UniqueEntity.php" -); - -// Registering gedmo extensions -AnnotationRegistry::registerAutoloadNamespace( - 'Gedmo\Mapping\Annotation', - api_get_path(SYS_PATH)."vendor/gedmo/doctrine-extensions/lib" -); - -/*$repo = $entityManager->getRepository('ChamiloCoreBundle:Session'); -$repo = $entityManager->getRepository('ChamiloUserBundle:User'); -$repo = $entityManager->getRepository('ChamiloCoreBundle:Course');*/ - try { - $connect = $entityManager->getConnection()->connect(); + $database = new \Database(); + $database->connect($dbParams); } catch (Exception $e) { $global_error_code = 3; // The database server is not available or credentials are invalid. @@ -200,9 +168,6 @@ try { die(); } -$database = new \Database(); -$database->setManager($entityManager); - /* RETRIEVING ALL THE CHAMILO CONFIG SETTINGS FOR MULTIPLE URLs FEATURE*/ if (!empty($_configuration['multiple_access_urls'])) { $_configuration['access_url'] = 1; diff --git a/main/inc/lib/database.lib.php b/main/inc/lib/database.lib.php index 4dc5fa24f6..16570af075 100755 --- a/main/inc/lib/database.lib.php +++ b/main/inc/lib/database.lib.php @@ -4,6 +4,7 @@ use Doctrine\DBAL\Connection; use Doctrine\ORM\EntityManager; use Doctrine\DBAL\Driver\Statement; +use Doctrine\Common\Annotations\AnnotationRegistry; /** * Class Database @@ -54,13 +55,9 @@ class Database * * @param string $short_table_name, the name of the table */ - public static function get_main_table($short_table_name) + public static function get_main_table($table) { - return $short_table_name; - /* - return self::format_table_name( - self::get_main_database(), - $short_table_name);*/ + return $table; } /** @@ -74,9 +71,9 @@ class Database * @param string $database_name, optional, name of the course database * - if you don't specify this, you work on the current course. */ - public static function get_course_table($short_table_name, $extra = null) + public static function get_course_table($table, $extra = null) { - return DB_COURSE_PREFIX.$short_table_name; + return DB_COURSE_PREFIX.$table; /* //forces fatal errors so we can debug more easily if (!empty($extra)) { @@ -129,19 +126,42 @@ class Database } /** - * Opens a connection to a database server. - * @param array $parameters (optional) An array that contains the necessary parameters for accessing the server. - * @return resource/boolean Returns a database connection on success or FALSE on failure. - * Note: Currently the array could contain MySQL-specific parameters: - * $parameters['server'], $parameters['username'], $parameters['password'], - * $parameters['new_link'], $parameters['client_flags'], $parameters['persistent']. - * For details see documentation about the functions mysql_connect() and mysql_pconnect(). - * @link http://php.net/manual/en/function.mysql-connect.php - * @link http://php.net/manual/en/function.mysql-pconnect.php + * @param array $params + * @throws \Doctrine\ORM\ORMException */ - public static function connect($parameters = array()) { + public function connect($params = array()) + { + $config = self::getDoctrineConfig(); + $config->setEntityNamespaces( + array( + 'ChamiloUserBundle' => 'Chamilo\UserBundle\Entity', + 'ChamiloCoreBundle' => 'Chamilo\CoreBundle\Entity', + 'ChamiloCourseBundle' => 'Chamilo\CourseBundle\Entity' + ) + ); + + $entityManager = EntityManager::create($params, $config); + + // Registering Constraints + AnnotationRegistry::registerAutoloadNamespace( + 'Symfony\Component\Validator\Constraint', + api_get_path(SYS_PATH)."vendor/symfony/validator" + ); + + AnnotationRegistry::registerFile( + api_get_path(SYS_PATH)."vendor/symfony/doctrine-bridge/Symfony/Bridge/Doctrine/Validator/Constraints/UniqueEntity.php" + ); + + // Registering gedmo extensions + AnnotationRegistry::registerAutoloadNamespace( + 'Gedmo\Mapping\Annotation', + api_get_path(SYS_PATH)."vendor/gedmo/doctrine-extensions/lib" + ); + + $this->setManager($entityManager); + // A MySQL-specific implementation. - if (!isset($parameters['server'])) { + /*if (!isset($parameters['server'])) { $parameters['server'] = @ini_get('mysql.default_host'); if (empty($parameters['server'])) { $parameters['server'] = 'localhost:3306'; @@ -169,7 +189,7 @@ class Database $client_flags = isset($parameters['client_flags']) ? $parameters['client_flags'] : null; return $persistent ? mysql_pconnect($server, $username, $password, $client_flags) - : mysql_connect($server, $username, $password, $new_link, $client_flags); + : mysql_connect($server, $username, $password, $new_link, $client_flags);*/ } /** diff --git a/main/install/index.php b/main/install/index.php index ad1e7ce20e..ea639a8a98 100755 --- a/main/install/index.php +++ b/main/install/index.php @@ -18,11 +18,11 @@ use \ChamiloSession as Session; -define('SYSTEM_INSTALLATION', 1); -define('INSTALL_TYPE_UPDATE', 'update'); -define('FORM_FIELD_DISPLAY_LENGTH', 40); -define('DATABASE_FORM_FIELD_DISPLAY_LENGTH', 25); -define('MAX_FORM_FIELD_LENGTH', 80); +define('SYSTEM_INSTALLATION', 1); +define('INSTALL_TYPE_UPDATE', 'update'); +define('FORM_FIELD_DISPLAY_LENGTH', 40); +define('DATABASE_FORM_FIELD_DISPLAY_LENGTH', 25); +define('MAX_FORM_FIELD_LENGTH', 80); /* PHP VERSION CHECK */ @@ -76,7 +76,6 @@ if (!array_key_exists($install_language, get_language_folder_list())) { // Loading language files. require api_get_path(SYS_LANG_PATH).'english/trad4all.inc.php'; -require api_get_path(SYS_LANG_PATH).'english/admin.inc.php'; require api_get_path(SYS_LANG_PATH).'english/install.inc.php'; if ($install_language != 'english') { include_once api_get_path(SYS_LANG_PATH).$install_language.'/trad4all.inc.php'; @@ -105,10 +104,9 @@ error_reporting(E_ALL); // Overriding the timelimit (for large campusses that have to be migrated). @set_time_limit(0); -// Upgrading from any subversion of 1.6 is just like upgrading from 1.6.5 -$update_from_version_6 = array('1.6', '1.6.1', '1.6.2', '1.6.3', '1.6.4', '1.6.5'); -// Upgrading from any subversion of 1.8 avoids the additional step of upgrading from 1.6 -$update_from_version_8 = array('1.8', '1.8.2', '1.8.3', '1.8.4', '1.8.5', '1.8.6', '1.8.6.1', '1.8.6.2','1.8.7','1.8.7.1','1.8.8','1.8.8.2', '1.8.8.4', '1.8.8.6', '1.9.0', '1.9.2','1.9.4','1.9.6', '1.9.6.1', '1.9.8', '1.9.8.1', '1.9.8.2', '1.9.10'); +$update_from_version_6 = array(); +// Upgrading from any subversion of 1.9 +$update_from_version_8 = array('1.9.0', '1.9.2','1.9.4','1.9.6', '1.9.6.1', '1.9.8', '1.9.8.1', '1.9.8.2', '1.9.10'); $my_old_version = ''; $tmp_version = get_config_param('dokeos_version'); @@ -138,13 +136,13 @@ if (isAlreadyInstalledSystem()) { // Is valid request $is_valid_request = isset($_REQUEST['is_executable']) ? $_REQUEST['is_executable'] : null; -foreach ($_POST as $request_index => $request_value) { +/*foreach ($_POST as $request_index => $request_value) { if (substr($request_index, 0, 4) == 'step') { if ($request_index != $is_valid_request) { unset($_POST[$request_index]); } } -} +}*/ $badUpdatePath = false; $emptyUpdatePath = true; @@ -214,7 +212,6 @@ if (!isset($_GET['running'])) { $dbPassForm = ''; $dbPrefixForm = ''; $dbNameForm = 'chamilo'; - $dbStatsForm = 'chamilo'; $dbScormForm = 'chamilo'; $dbUserForm = 'chamilo'; @@ -223,11 +220,10 @@ if (!isset($_GET['running'])) { $urlAppendPath = api_remove_trailing_slash(api_get_path(REL_PATH)); $urlForm = api_get_path(WEB_PATH); $pathForm = api_get_path(SYS_PATH); - - $emailForm = 'webmaster@localhost'; - if (!empty($_SERVER['SERVER_ADMIN'])) { - $emailForm = $_SERVER['SERVER_ADMIN']; - } + $emailForm = 'webmaster@localhost'; + if (!empty($_SERVER['SERVER_ADMIN'])) { + $emailForm = $_SERVER['SERVER_ADMIN']; + } $email_parts = explode('@', $emailForm); if (isset($email_parts[1]) && $email_parts[1] == 'localhost') { $emailForm .= '.localdomain'; @@ -242,8 +238,6 @@ if (!isset($_GET['running'])) { $adminPhoneForm = '(000) 001 02 03'; $institutionForm = 'My Organisation'; $institutionUrlForm = 'http://www.chamilo.org'; - // TODO: A better choice to be tested: - //$languageForm = 'english'; $languageForm = api_get_interface_language(); $checkEmailByHashSent = 0; @@ -300,6 +294,7 @@ if ($encryptPassForm == '1') { } elseif ($encryptPassForm == '0') { $encryptPassForm = 'none'; } + ?> @@ -320,15 +315,15 @@ if ($encryptPassForm == '1') { //checked if ($('#singleDb1').attr('checked')==false) { - //$('#dbStatsForm').removeAttr('disabled'); - //$('#dbUserForm').removeAttr('disabled'); - $('#dbStatsForm').attr('value','chamilo_main'); - $('#dbUserForm').attr('value','chamilo_main'); + //$('#dbStatsForm').removeAttr('disabled'); + //$('#dbUserForm').removeAttr('disabled'); + $('#dbStatsForm').attr('value','chamilo_main'); + $('#dbUserForm').attr('value','chamilo_main'); } else if($('#singleDb1').attr('checked')==true){ - //$('#dbStatsForm').attr('disabled','disabled'); - //$('#dbUserForm').attr('disabled','disabled'); - $('#dbStatsForm').attr('value','chamilo_main'); - $('#dbUserForm').attr('value','chamilo_main'); + //$('#dbStatsForm').attr('disabled','disabled'); + //$('#dbUserForm').attr('disabled','disabled'); + $('#dbStatsForm').attr('value','chamilo_main'); + $('#dbUserForm').attr('value','chamilo_main'); } $("button").addClass('btn btn-default'); @@ -407,11 +402,11 @@ if ($encryptPassForm == '1') { $(document).ready( function() { $(".advanced_parameters").click(function() { if ($("#id_contact_form").css("display") == "none") { - $("#id_contact_form").css("display","block"); - $("#img_plus_and_minus").html(' <?php echo get_lang('Hide') ?> '); + $("#id_contact_form").css("display","block"); + $("#img_plus_and_minus").html(' <?php echo get_lang('Hide') ?> '); } else { - $("#id_contact_form").css("display","none"); - $("#img_plus_and_minus").html(' <?php echo get_lang('Show') ?> '); + $("#id_contact_form").css("display","none"); + $("#img_plus_and_minus").html(' <?php echo get_lang('Show') ?> '); } }); }); @@ -429,21 +424,21 @@ if ($encryptPassForm == '1') { data_post += "financial_decision="+$("input[@name='financial_decision']:checked").val(); $.ajax({ - contentType: "application/x-www-form-urlencoded", - beforeSend: function(objeto) {}, - type: "POST", - url: "install.ajax.php?a=send_contact_information", - data: data_post, - success: function(datos) { - if (datos == 'required_field_error') { - message = ""; - } else if (datos == '1') { - message = ""; - } else { - message = ""; - } - alert(message); - } + contentType: "application/x-www-form-urlencoded", + beforeSend: function(objeto) {}, + type: "POST", + url: "install.ajax.php?a=send_contact_information", + data: data_post, + success: function(datos) { + if (datos == 'required_field_error') { + message = ""; + } else if (datos == '1') { + message = ""; + } else { + message = ""; + } + alert(message); + } }); } @@ -451,11 +446,11 @@ if ($encryptPassForm == '1') { -
+
-
+
@@ -481,7 +476,7 @@ if ($encryptPassForm == '1') { echo ''; ?>
-
+
  1. >
  2. @@ -500,9 +495,9 @@ if ($encryptPassForm == '1') {
-
+
-
+ " />


- '; ?> '.$dbNameForm; ?> - - '; - echo get_lang('StatDB').' : '.$dbStatsForm.''; - if ($installType == 'new') { - echo ' ('.get_lang('ReadWarningBelow').')'; - } - echo '
'; - echo get_lang('UserDB').' : '.$dbUserForm.''; - if ($installType == 'new') { - echo ' ('.get_lang('ReadWarningBelow').')'; - } - echo '
'; - } - } - - //echo get_lang('EnableTracking').' : '.($enableTrackingForm ? get_lang('Yes') : get_lang('No')); ?> -


- + @@ -732,9 +736,7 @@ if (@$_POST['step2']) { '.get_lang('PleaseWaitThisCouldTakeAWhile').'
'; - // Push the web server to send these strings before we start the real // installation process flush(); @@ -755,9 +756,16 @@ if (@$_POST['step2']) { } if ($installType == 'update') { - remove_memory_and_time_limits(); - database_server_connect(); + + //database_server_connect(); + $manager = testDbConnect( + $dbHostForm, + $dbUsernameForm, + $dbPassForm, + $dbNameForm + ); + // Initialization of the database connection encoding intentionaly is not done. // This is the old style for connecting to the database server, that is implemented here. @@ -778,15 +786,6 @@ if (@$_POST['step2']) { $userPasswordCrypted = 'none'; } - //Setting the single db form - if (in_array($_POST['old_version'], $update_from_version_6)) { - $singleDbForm = get_config_param('singleDbEnabled'); - } else { - $singleDbForm = isset($_configuration['single_database']) ? $_configuration['single_database'] : false; - } - - Log::notice("singledbForm: '$singleDbForm'"); - Database::query("SET storage_engine = MYISAM;"); if (version_compare($my_old_version, '1.8.7', '>=')) { @@ -797,64 +796,6 @@ if (@$_POST['step2']) { } switch ($my_old_version) { - case '1.6': - case '1.6.0': - case '1.6.1': - case '1.6.2': - case '1.6.3': - case '1.6.4': - case '1.6.5': - include 'update-db-1.6.x-1.8.0.inc.php'; - include 'update-files-1.6.x-1.8.0.inc.php'; - //intentionally no break to continue processing - case '1.8': - case '1.8.0': - include 'update-db-1.8.0-1.8.2.inc.php'; - //intentionally no break to continue processing - case '1.8.2': - include 'update-db-1.8.2-1.8.3.inc.php'; - //intentionally no break to continue processing - case '1.8.3': - include 'update-db-1.8.3-1.8.4.inc.php'; - include 'update-files-1.8.3-1.8.4.inc.php'; - case '1.8.4': - include 'update-db-1.8.4-1.8.5.inc.php'; - include 'update-files-1.8.4-1.8.5.inc.php'; - case '1.8.5': - include 'update-db-1.8.5-1.8.6.inc.php'; - include 'update-files-1.8.5-1.8.6.inc.php'; - case '1.8.6': - include 'update-db-1.8.6-1.8.6.1.inc.php'; - include 'update-files-1.8.6-1.8.6.1.inc.php'; - case '1.8.6.1': - include 'update-db-1.8.6.1-1.8.6.2.inc.php'; - include 'update-files-1.8.6.1-1.8.6.2.inc.php'; - case '1.8.6.2': - include 'update-db-1.8.6.2-1.8.7.inc.php'; - include 'update-files-1.8.6.2-1.8.7.inc.php'; - // After database conversion to UTF-8, new encoding initialization is necessary - // to be used for the next upgrade 1.8.7[.1] -> 1.8.8. - Database::query("SET SESSION character_set_server='utf8';"); - Database::query("SET SESSION collation_server='utf8_general_ci';"); - //Database::query("SET CHARACTER SET 'utf8';"); // See task #1802. - Database::query("SET NAMES 'utf8';"); - - case '1.8.7': - case '1.8.7.1': - include 'update-db-1.8.7-1.8.8.inc.php'; - include 'update-files-1.8.7-1.8.8.inc.php'; - case '1.8.8': - case '1.8.8.2': - //Only updates the configuration.inc.php with the new version - include 'update-configuration.inc.php'; - case '1.8.8.4': - case '1.8.8.6': - include 'update-db-1.8.8-1.9.0.inc.php'; - //include 'update-files-1.8.8-1.9.0.inc.php'; - //Only updates the configuration.inc.php with the new version - include 'update-configuration.inc.php'; - - break; case '1.9.0': case '1.9.2': case '1.9.4': @@ -874,7 +815,14 @@ if (@$_POST['step2']) { } } else { set_file_folder_permissions(); - database_server_connect(); + + //database_server_connect(); + $manager = testDbConnect( + $dbHostForm, + $dbUsernameForm, + $dbPassForm, + $dbNameForm + ); // Initialization of the database encoding to be used. Database::query("SET storage_engine = MYISAM;"); @@ -901,7 +849,7 @@ if (@$_POST['step2']) { } ?> -
+
diff --git a/main/install/install.lib.php b/main/install/install.lib.php index d28167a9e7..8de55aaeb6 100755 --- a/main/install/install.lib.php +++ b/main/install/install.lib.php @@ -614,7 +614,6 @@ function get_config_param($param, $updatePath = '') */ 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); @@ -651,26 +650,6 @@ function database_server_connect() @Database::query("set session sql_mode='';"); // Disabling special SQL modes (MySQL 5) } -/** - * Database exists for the MYSQL user - * @param string $database_name The name of the database to check - * @return boolean - */ -function database_exists($database_name) -{ - if (empty($database_name)) { - return false; - } - $select_database = @Database::select_db($database_name); - $show_database = false; - $sql = "SHOW DATABASES LIKE '".addslashes($database_name)."'"; - $result = @Database::query($sql); - if (Database::num_rows($result)) { - $show_database = true; - } - return $select_database || $show_database; -} - /** * In step 3. Tests establishing connection to the database server. * If it's a single database environment the function checks if the database exist. @@ -678,9 +657,7 @@ function database_exists($database_name) * @param string $dbHostForm DB host * @param string $dbUsernameForm DB username * @param string $dbPassForm DB password - * @return int 1 when there is no problem; - * 0 when a new database is impossible to be created, then the single/multiple database configuration is impossible too - * -1 when there is no connection established. + * @return \Doctrine\ORM\EntityManager */ function testDbConnect($dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm) { @@ -689,19 +666,13 @@ function testDbConnect($dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm) 'host' => $dbHostForm, 'user' => $dbUsernameForm, 'password' => $dbPassForm, - '' + 'dbname' => $dbNameForm ); - $config = Database::getDoctrineConfig(); - $entityManager = \Doctrine\ORM\EntityManager::create($dbParams, $config); - $dbConnect = 1; - try { - $entityManager->getConnection()->connect(); - } catch (Exception $e) { - echo $e->getMessage(); - $dbConnect = -1; - } - return $dbConnect; //return 1, if no problems, "0" if, in case we can't create a new DB and "-1" if there is no connection. + $database = new \Database(); + $database->connect($dbParams); + + return $database->getManager(); } /** @@ -1838,35 +1809,19 @@ function display_database_settings_form( $dbScormForm, $dbUserForm ) { - if ($installType == 'update') { - global $_configuration, $update_from_version_6; - - if (in_array($_POST['old_version'], $update_from_version_6)) { - $dbHostForm = get_config_param('dbHost'); - $dbUsernameForm = get_config_param('dbLogin'); - $dbPassForm = get_config_param('dbPass'); - $dbPrefixForm = get_config_param('dbNamePrefix'); - $enableTrackingForm = get_config_param('is_trackingEnabled'); - $singleDbForm = get_config_param('singleDbEnabled'); - $dbHostForm = get_config_param('mainDbName'); - $dbStatsForm = get_config_param('statsDbName'); - $dbScormForm = get_config_param('scormDbName'); - $dbUserForm = get_config_param('user_personal_database'); - $dbScormExists = true; - } else { - $dbHostForm = $_configuration['db_host']; - $dbUsernameForm = $_configuration['db_user']; - $dbPassForm = $_configuration['db_password']; - $dbPrefixForm = $_configuration['db_prefix']; - $enableTrackingForm = $_configuration['tracking_enabled']; - $singleDbForm = $_configuration['single_database']; - $dbNameForm = $_configuration['main_database']; - $dbStatsForm = $_configuration['statistics_database']; - $dbScormForm = $_configuration['scorm_database']; - $dbUserForm = $_configuration['user_personal_database']; - $dbScormExists = true; - } + global $_configuration; + $dbHostForm = $_configuration['db_host']; + $dbUsernameForm = $_configuration['db_user']; + $dbPassForm = $_configuration['db_password']; + $dbPrefixForm = $_configuration['db_prefix']; + $enableTrackingForm = $_configuration['tracking_enabled']; + $singleDbForm = $_configuration['single_database']; + $dbNameForm = $_configuration['main_database']; + $dbStatsForm = $_configuration['statistics_database']; + $dbScormForm = $_configuration['scorm_database']; + $dbUserForm = $_configuration['user_personal_database']; + $dbScormExists = true; if (empty($dbScormForm)) { if ($singleDbForm) { @@ -1932,16 +1887,16 @@ function display_database_settings_form( $dbNameForm = replace_dangerous_char($dbNameForm); } - displayDatabaseParameter($installType, get_lang('MainDB'), 'dbNameForm', $dbNameForm, ' ', null, 'id="optional_param1" '.$style); + displayDatabaseParameter( + $installType, + get_lang('MainDB'), + 'dbNameForm', + $dbNameForm, + ' ', + null, + 'id="optional_param1" '.$style + ); - //Only for updates we show this options - if ($installType == INSTALL_TYPE_UPDATE) { - displayDatabaseParameter($installType, get_lang('StatDB'), 'dbStatsForm', $dbStatsForm, ' ', null, 'id="optional_param2" '.$style); - if ($installType == INSTALL_TYPE_UPDATE && in_array($_POST['old_version'], $update_from_version_6)) { - displayDatabaseParameter($installType, get_lang('ScormDB'), 'dbScormForm', $dbScormForm, ' ', null, 'id="optional_param3" '.$style); - } - displayDatabaseParameter($installType, get_lang('UserDB'), 'dbUserForm', $dbUserForm, ' ', null, 'id="optional_param4" '.$style); - } ?> @@ -1956,17 +1911,31 @@ function display_database_settings_form( getMessage(); + } + + $databases = $manager->getConnection()->getSchemaManager()->listDatabases(); + + if (in_array($dbNameForm, $databases)) { $database_exists_text = '
'.get_lang('ADatabaseWithTheSameNameAlreadyExists').'
'; } else { + if ($dbConnect == -1) { $database_exists_text = '
'.sprintf(get_lang('UserXCantHaveAccessInTheDatabaseX'), $dbUsernameForm, $dbNameForm).'
'; } else { - //Try to create the database + $manager->getConnection()->getSchemaManager()->createDatabase($dbNameForm); + /* + //Try to create the database $user_can_create_databases = false; $multipleDbCheck = @Database::query("CREATE DATABASE ".mysql_real_escape_string($dbNameForm)); if ($multipleDbCheck !== false) { @@ -1979,18 +1948,18 @@ function display_database_settings_form( } else { $dbConnect = 0; $database_exists_text = '
'.sprintf(get_lang('DatabaseXCantBeCreatedUserXDoestHaveEnoughPermissions'), $dbNameForm, $dbUsernameForm).'
'; - } + }*/ } } - if ($dbConnect == 1): ?> + if ($manager): ?>
- Database host:
- Database server version:
- Database client version:
- Database protocol version: + Database host: getConnection()->getHost(); ?>
+ Database server version:
+ Database client version:
+ Database protocol version:
@@ -2016,7 +1985,7 @@ function display_database_settings_form(   - + diff --git a/main/install/install_db.inc.php b/main/install/install_db.inc.php index 80a1f493d2..fc053b203f 100755 --- a/main/install/install_db.inc.php +++ b/main/install/install_db.inc.php @@ -72,14 +72,19 @@ if (!defined('CLI_INSTALLATION')) { $mysqlRepositorySys = $mysqlRepositorySys['Value']; $create_database = true; + /** @var \Doctrine\ORM\EntityManager $manager */ + global $manager; + $databases = $manager->getConnection()->getSchemaManager()->listDatabases(); - if (database_exists($mysqlMainDb)) { + if (in_array($mysqlMainDb, $databases)) { $create_database = false; } - //Create database + + // Create database if ($create_database) { - $sql = "CREATE DATABASE IF NOT EXISTS `$mysqlMainDb`"; - Database::query($sql) or die(Database::error()); + $manager->getConnection()->getSchemaManager()->createDatabase($mysqlMainDb); + /*$sql = "CREATE DATABASE IF NOT EXISTS `$mysqlMainDb`"; + Database::query($sql) or die(Database::error());*/ } } @@ -95,7 +100,7 @@ if (!defined('CLI_INSTALLATION')) { } } -Database::select_db($mysqlMainDb) or die(Database::error()); +//Database::select_db($mysqlMainDb) or die(Database::error()); $installation_settings = array(); $installation_settings['{ORGANISATIONNAME}'] = $institutionForm; From 640ce956a1fb5fd65a12efa5c56150da63e9aa75 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 27 Mar 2015 08:30:58 +0100 Subject: [PATCH 004/159] Install partial fix --- main/install/index.php | 1 + main/install/install.lib.php | 8 ++++++-- main/install/install_db.inc.php | 1 + 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/main/install/index.php b/main/install/index.php index ea639a8a98..d74ed07c75 100755 --- a/main/install/index.php +++ b/main/install/index.php @@ -833,6 +833,7 @@ if (@$_POST['step2']) { include 'install_db.inc.php'; include 'install_files.inc.php'; + } display_after_install_message($installType); //Hide the "please wait" message sent previously diff --git a/main/install/install.lib.php b/main/install/install.lib.php index 8de55aaeb6..418ef24bcb 100755 --- a/main/install/install.lib.php +++ b/main/install/install.lib.php @@ -714,11 +714,15 @@ function load_main_database($installation_settings, $dbScript = '') } } + //replace symbolic parameters with user-specified values foreach ($installation_settings as $key => $value) { $sql_text = str_replace($key, Database::escape_string($value), $sql_text); } - parse_sql_queries($sql_text); + + global $manager; + $manager->getConnection()->prepare($sql_text); + //parse_sql_queries($sql_text); } /** @@ -740,7 +744,6 @@ function load_database_script($dbScript) */ function parse_sql_queries($sql_text) { - //split in array of sql strings $sql_instructions = array(); split_sql_file($sql_instructions, $sql_text); @@ -749,6 +752,7 @@ function parse_sql_queries($sql_text) $count = count($sql_instructions); for ($i = 0; $i < $count; $i++) { $this_sql_query = $sql_instructions[$i]['query']; + Database::query($this_sql_query); //UTF8 fix see #5678 /* diff --git a/main/install/install_db.inc.php b/main/install/install_db.inc.php index fc053b203f..8f3f4f5724 100755 --- a/main/install/install_db.inc.php +++ b/main/install/install_db.inc.php @@ -80,6 +80,7 @@ if (!defined('CLI_INSTALLATION')) { $create_database = false; } + // Create database if ($create_database) { $manager->getConnection()->getSchemaManager()->createDatabase($mysqlMainDb); From 98be672efa8e038702825804db10544eba038ca4 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 27 Mar 2015 16:55:25 +0100 Subject: [PATCH 005/159] Remove unused $_configuration values. --- main/admin/course_request_edit.php | 4 +- main/inc/global.inc.php | 7 --- main/inc/lib/api.lib.php | 1 - main/inc/lib/course.lib.php | 5 --- main/inc/lib/login.lib.php | 1 - main/install/configuration.dist.php | 62 +++++++++----------------- main/install/install.lib.php | 61 +++++++------------------ main/webservices/registration.soap.php | 3 +- tests/test_manager.inc.php | 1 - 9 files changed, 38 insertions(+), 107 deletions(-) diff --git a/main/admin/course_request_edit.php b/main/admin/course_request_edit.php index f4055391b1..a576d4b7f2 100755 --- a/main/admin/course_request_edit.php +++ b/main/admin/course_request_edit.php @@ -31,10 +31,8 @@ if ($course_validation_feature) { $is_error_message = true; } else { - global $_configuration; - $dbnamelength = strlen($_configuration['db_prefix']); // Ensure the database prefix + database name do not get over 40 characters. - $maxlength = 40 - $dbnamelength; + $maxlength = 40; // Build the form. $form = new FormValidator('add_course', 'post', 'course_request_edit.php?id='.$id.'&caller='.$caller); diff --git a/main/inc/global.inc.php b/main/inc/global.inc.php index d93e0588cd..986e0741fc 100755 --- a/main/inc/global.inc.php +++ b/main/inc/global.inc.php @@ -115,13 +115,6 @@ if (!is_dir(_MPDF_TEMP_PATH)) { mkdir(_MPDF_TEMP_PATH, api_get_permissions_for_new_directories(), true); } -/* DATABASE CONNECTION */ - -// @todo: this shouldn't be done here. It should be stored correctly during installation. -if (empty($_configuration['statistics_database']) && $already_installed) { - $_configuration['statistics_database'] = $_configuration['main_database']; -} -global $database_connection; // Connect to the server database and select the main chamilo database. // When $_configuration['db_persistent_connection'] is set, it is expected to be a boolean type. $dbPersistConnection = api_get_configuration_value('db_persistent_connection'); diff --git a/main/inc/lib/api.lib.php b/main/inc/lib/api.lib.php index 3096598c78..c1f8ff8107 100644 --- a/main/inc/lib/api.lib.php +++ b/main/inc/lib/api.lib.php @@ -1783,7 +1783,6 @@ function api_format_course_array($course_data) { $_course['dbName'] = $course_data['db_name']; $_course['db_name'] = $course_data['db_name']; // Use in all queries. - $_course['dbNameGlu'] = $_configuration['table_prefix'] . $course_data['db_name'] . $_configuration['db_glue']; $_course['titular'] = $course_data['tutor_name']; $_course['language'] = $course_data['course_language']; diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php index f4728c04d1..a55d811175 100755 --- a/main/inc/lib/course.lib.php +++ b/main/inc/lib/course.lib.php @@ -2237,11 +2237,6 @@ class CourseManager */ public static function create_database_dump($course_code) { - global $_configuration; - - if ($_configuration['single_database']) { - return; - } $sql_dump = ''; $course_code = Database::escape_string($course_code); $table_course = Database::get_main_table(TABLE_MAIN_COURSE); diff --git a/main/inc/lib/login.lib.php b/main/inc/lib/login.lib.php index 38c2a0ad2c..7eba78ba27 100755 --- a/main/inc/lib/login.lib.php +++ b/main/inc/lib/login.lib.php @@ -357,7 +357,6 @@ class Login $_course['path'] = $course_data['directory']; // use as key in path $_course['dbName'] = $course_data['db_name']; // use as key in db list $_course['db_name'] = $course_data['db_name']; // not needed in Chamilo 1.9 - $_course['dbNameGlu'] = $_configuration['table_prefix'] . $course_data['db_name'] . $_configuration['db_glue']; // use in all queries //not needed in Chamilo 1.9 $_course['titular'] = $course_data['tutor_name']; // this should be deprecated and use the table course_rel_user $_course['language'] = $course_data['course_language']; $_course['extLink']['url'] = $course_data['department_url']; diff --git a/main/install/configuration.dist.php b/main/install/configuration.dist.php index 9547f4f6d8..191794d254 100755 --- a/main/install/configuration.dist.php +++ b/main/install/configuration.dist.php @@ -21,19 +21,19 @@ * contains variables that can be changed and will not break the platform. * These optional settings are defined in the database, now * (table settings_current). - * example: $_configuration['tracking_enabled'] (assuming that the install - * script creates the necessary tables anyway). */ /** - * MYSQL connection settings + * Database connection settings */ // Your MySQL server -$_configuration['db_host'] = '{DATABASE_HOST}'; +$_configuration['db_host'] = '{DATABASE_HOST}'; // Your MySQL username -$_configuration['db_user'] = '{DATABASE_USER}'; +$_configuration['db_user'] = '{DATABASE_USER}'; // Your MySQL password $_configuration['db_password'] = '{DATABASE_PASSWORD}'; +// main Chamilo database +$_configuration['main_database'] = '{DATABASE_MAIN}'; // Persistent connections may have profound effects (not always positive) on // your database server. Use with care. @@ -43,26 +43,6 @@ $_configuration['db_password'] = '{DATABASE_PASSWORD}'; // the following to enable compression. //$_configuration['db_client_flags'] = MYSQL_CLIENT_COMPRESS; -/** - * Database settings - */ -// Is tracking enabled? -$_configuration['tracking_enabled'] = TRACKING_ENABLED; -// Is single database enabled (DO NOT MODIFY THIS) -$_configuration['single_database'] = SINGLE_DATABASE; -// Prefix for course tables (IF NOT EMPTY, can be replaced by another prefix, else leave empty) -$_configuration['table_prefix'] = '{COURSE_TABLE_PREFIX}'; -// Separator between database and table name (DO NOT MODIFY THIS) -$_configuration['db_glue'] = '{DATABASE_GLUE}'; -// prefix all created bases (for courses) with this string -$_configuration['db_prefix'] = '{DATABASE_PREFIX}'; -// main Chamilo database -$_configuration['main_database'] = '{DATABASE_MAIN}'; -// stats Chamilo database -$_configuration['statistics_database'] ='{DATABASE_STATS}'; -// User Personal Database (where all the personal stuff of the user is stored -// (personal agenda items, course sorting) -$_configuration['user_personal_database']='{DATABASE_PERSONAL}'; // Enable access to database management for platform admins. $_configuration['db_manager_enabled'] = false; @@ -70,23 +50,23 @@ $_configuration['db_manager_enabled'] = false; * Directory settings */ // URL to the root of your Chamilo installation, e.g.: http://www.mychamilo.com/ -$_configuration['root_web'] = '{ROOT_WEB}'; +$_configuration['root_web'] = '{ROOT_WEB}'; // Path to the webroot of system, example: /var/www/ -$_configuration['root_sys'] = '{ROOT_SYS}'; +$_configuration['root_sys'] = '{ROOT_SYS}'; // Path from your WWW-root to the root of your Chamilo installation, example: chamilo (this means chamilo is installed in /var/www/chamilo/ -$_configuration['url_append'] = '{URL_APPEND_PATH}'; +$_configuration['url_append'] = '{URL_APPEND_PATH}'; // Directory of the Chamilo code. You could change this but it is not advised since this has not been tested yet. -$_configuration['code_append'] = "main/"; +$_configuration['code_append'] = "main/"; // Directory to store all course-related files. You could change this but it is not advised since this has not been tested yet. -$_configuration['course_folder'] = "courses/"; +$_configuration['course_folder'] = "courses/"; // URL to your phpMyAdmin installation. // If not empty, a link will be available in the Platform Administration -$_configuration['db_admin_path'] = ''; +$_configuration['db_admin_path'] = ''; /** * Login modules settings @@ -154,7 +134,7 @@ $_configuration['cdn'] = array( //You can define several CDNs and split them by extensions //Replace the following by your full CDN URL, which should point to // your Chamilo's root directory. DO NOT INCLUDE a final slash! (won't work) - 'http://cdn.chamilo.org' => array('.css','.js','.jpg','.jpeg','.png','.gif','.avi','.flv'), + 'http://cdn.chamilo.org' => array('.css','.js','.jpg','.jpeg','.png','.gif','.avi','.flv'), // copy the line above and modify following your needs ); @@ -162,24 +142,24 @@ $_configuration['cdn'] = array( * Misc. settings */ // Verbose backup -$_configuration['verbose_backup'] = false; +$_configuration['verbose_backup'] = false; // security word for password recovery -$_configuration['security_key'] = '{SECURITY_KEY}'; +$_configuration['security_key'] = '{SECURITY_KEY}'; // Hash function method -$_configuration['password_encryption'] = '{ENCRYPT_PASSWORD}'; +$_configuration['password_encryption'] = '{ENCRYPT_PASSWORD}'; // You may have to restart your web server if you change this -$_configuration['session_stored_in_db'] = false; +$_configuration['session_stored_in_db'] = false; // Session lifetime -$_configuration['session_lifetime'] = SESSION_LIFETIME; +$_configuration['session_lifetime'] = SESSION_LIFETIME; // Activation for multi-url access //$_configuration['multiple_access_urls'] = true; -$_configuration['software_name'] = 'Chamilo'; -$_configuration['software_url'] = 'http://www.chamilo.org/'; +$_configuration['software_name'] = 'Chamilo'; +$_configuration['software_url'] = 'http://www.chamilo.org/'; //Deny the elimination of users $_configuration['deny_delete_users'] = false; // Version settings -$_configuration['system_version'] = '{NEW_VERSION}'; -$_configuration['system_stable'] = NEW_VERSION_STABLE; +$_configuration['system_version'] = '{NEW_VERSION}'; +$_configuration['system_stable'] = NEW_VERSION_STABLE; /** * Settings to be included as settings_current in future versions diff --git a/main/install/install.lib.php b/main/install/install.lib.php index c6f56052a1..19af20d397 100755 --- a/main/install/install.lib.php +++ b/main/install/install.lib.php @@ -313,11 +313,7 @@ function write_system_config_file($path) global $dbPassForm; global $enableTrackingForm; global $singleDbForm; - global $dbPrefixForm; global $dbNameForm; - global $dbStatsForm; - global $dbScormForm; - global $dbUserForm; global $urlForm; global $pathForm; global $urlAppendPath; @@ -332,29 +328,21 @@ function write_system_config_file($path) $root_sys = api_add_trailing_slash(str_replace('\\', '/', realpath($pathForm))); $content = file_get_contents(dirname(__FILE__).'/'.SYSTEM_CONFIG_FILENAME); - $config['{DATE_GENERATED}'] = date('r'); - $config['{DATABASE_HOST}'] = $dbHostForm; - $config['{DATABASE_USER}'] = $dbUsernameForm; - $config['{DATABASE_PASSWORD}'] = $dbPassForm; - $config['TRACKING_ENABLED'] = trueFalse($enableTrackingForm); - $config['SINGLE_DATABASE'] = trueFalse($singleDbForm); - $config['{COURSE_TABLE_PREFIX}'] = ($singleDbForm ? 'crs_' : ''); - $config['{DATABASE_GLUE}'] = ($singleDbForm ? '_' : '`.`'); - $config['{DATABASE_PREFIX}'] = ''; - $config['{DATABASE_MAIN}'] = $dbNameForm; - $config['{DATABASE_STATS}'] = $dbNameForm; - $config['{DATABASE_SCORM}'] = $dbNameForm; - $config['{DATABASE_PERSONAL}'] = $dbNameForm; - $config['{ROOT_WEB}'] = $urlForm; - $config['{ROOT_SYS}'] = $root_sys; - $config['{URL_APPEND_PATH}'] = $urlAppendPath; - $config['{PLATFORM_LANGUAGE}'] = $languageForm; - $config['{SECURITY_KEY}'] = md5(uniqid(rand().time())); - $config['{ENCRYPT_PASSWORD}'] = $encryptPassForm; - - $config['SESSION_LIFETIME'] = $session_lifetime; - $config['{NEW_VERSION}'] = $new_version; - $config['NEW_VERSION_STABLE'] = trueFalse($new_version_stable); + $config['{DATE_GENERATED}'] = date('r'); + $config['{DATABASE_HOST}'] = $dbHostForm; + $config['{DATABASE_USER}'] = $dbUsernameForm; + $config['{DATABASE_PASSWORD}'] = $dbPassForm; + $config['{DATABASE_MAIN}'] = $dbNameForm; + $config['{ROOT_WEB}'] = $urlForm; + $config['{ROOT_SYS}'] = $root_sys; + $config['{URL_APPEND_PATH}'] = $urlAppendPath; + $config['{PLATFORM_LANGUAGE}'] = $languageForm; + $config['{SECURITY_KEY}'] = md5(uniqid(rand().time())); + $config['{ENCRYPT_PASSWORD}'] = $encryptPassForm; + + $config['SESSION_LIFETIME'] = $session_lifetime; + $config['{NEW_VERSION}'] = $new_version; + $config['NEW_VERSION_STABLE'] = trueFalse($new_version_stable); foreach ($config as $key => $value) { $content = str_replace($key, $value, $content); @@ -1820,27 +1808,8 @@ function display_database_settings_form( $dbHostForm = $_configuration['db_host']; $dbUsernameForm = $_configuration['db_user']; $dbPassForm = $_configuration['db_password']; - $dbPrefixForm = $_configuration['db_prefix']; - $enableTrackingForm = $_configuration['tracking_enabled']; - $singleDbForm = $_configuration['single_database']; $dbNameForm = $_configuration['main_database']; - $dbStatsForm = $_configuration['statistics_database']; - $dbScormForm = $_configuration['scorm_database']; - $dbUserForm = $_configuration['user_personal_database']; - $dbScormExists = true; - - if (empty($dbScormForm)) { - if ($singleDbForm) { - $dbScormForm = $dbNameForm; - } else { - $dbScormForm = $dbPrefixForm.'scorm'; - $dbScormExists = false; - } - } - if (empty($dbUserForm)) { - $dbUserForm = $singleDbForm ? $dbNameForm : $dbPrefixForm.'chamilo_user'; - } echo '

' . display_step_sequence() .get_lang('DBSetting') . '

'; echo '
'; echo get_lang('DBSettingUpgradeIntro'); diff --git a/main/webservices/registration.soap.php b/main/webservices/registration.soap.php index bea69b9d29..587de59993 100755 --- a/main/webservices/registration.soap.php +++ b/main/webservices/registration.soap.php @@ -2541,9 +2541,8 @@ function WSCreateCourseByTitle($params) { $orig_course_id_value[] = $course_param['original_course_id_value']; $extra_list = $course_param['extra']; - $dbnamelength = strlen($_configuration['db_prefix']); // Ensure the database prefix + database name do not get over 40 characters - $maxlength = 40 - $dbnamelength; + $maxlength = 40; if (empty($wanted_code)) { $wanted_code = CourseManager::generate_course_code(substr($title, 0, $maxlength)); diff --git a/tests/test_manager.inc.php b/tests/test_manager.inc.php index f72a6fbdf6..adf49c67a7 100755 --- a/tests/test_manager.inc.php +++ b/tests/test_manager.inc.php @@ -155,7 +155,6 @@ function create_test_course($course_code = 'TESTCOURSE') { $_course['sysCode' ] = $cData['code' ]; // use as key in db $_course['path' ] = $cData['directory' ]; // use as key in path $_course['dbName' ] = $cData['db_name' ]; // use as key in db list - $_course['dbNameGlu' ] = $_configuration['table_prefix'] . $cData['db_name'] . $_configuration['db_glue']; // use in all queries $_course['titular' ] = $cData['tutor_name' ]; $_course['language' ] = $cData['course_language' ]; $_course['extLink' ]['url' ] = $cData['department_url' ]; From 2538b840d78cbd1e318c2c5d203f8b57ece326ce Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 27 Mar 2015 16:56:04 +0100 Subject: [PATCH 006/159] Remove unused files see #7595 --- main/install/migrate-db-1.6.x-1.8.0-post.sql | 65 - main/install/migrate-db-1.6.x-1.8.0-pre.sql | 315 ----- main/install/migrate-db-1.8.0-1.8.2-pre.sql | 78 -- main/install/migrate-db-1.8.2-1.8.3-pre.sql | 25 - main/install/migrate-db-1.8.3-1.8.4-pre.sql | 37 - main/install/migrate-db-1.8.4-1.8.5-pre.sql | 159 --- main/install/migrate-db-1.8.5-1.8.6-pre.sql | 231 ---- main/install/migrate-db-1.8.6-1.8.6.1-pre.sql | 65 - .../migrate-db-1.8.6.1-1.8.6.2-post.sql | 21 - .../migrate-db-1.8.6.1-1.8.6.2-pre.sql | 149 --- .../install/migrate-db-1.8.6.2-1.8.7-post.sql | 38 - main/install/migrate-db-1.8.6.2-1.8.7-pre.sql | 154 --- main/install/migrate-db-1.8.7-1.8.8-pre.sql | 231 ---- main/install/migrate-db-1.8.8-1.9.0-pre.sql | 344 ----- .../migrate-db-1.8.8-1.9.0-pre.sql.optimized | 216 ---- main/install/update-db-1.6.x-1.8.0.inc.php | 538 -------- main/install/update-db-1.8.0-1.8.2.inc.php | 212 --- main/install/update-db-1.8.2-1.8.3.inc.php | 212 --- main/install/update-db-1.8.3-1.8.4.inc.php | 265 ---- main/install/update-db-1.8.4-1.8.5.inc.php | 283 ---- main/install/update-db-1.8.5-1.8.6.inc.php | 1147 ----------------- main/install/update-db-1.8.6-1.8.6.1.inc.php | 264 ---- .../install/update-db-1.8.6.1-1.8.6.2.inc.php | 349 ----- main/install/update-db-1.8.6.2-1.8.7.inc.php | 568 -------- main/install/update-db-1.8.7-1.8.8.inc.php | 409 ------ main/install/update-db-1.8.8-1.9.0.inc.php | 678 ---------- main/install/update-db-1.9.0-1.10.0.inc.php | 15 - main/install/update-files-1.6.x-1.8.0.inc.php | 152 --- main/install/update-files-1.8.3-1.8.4.inc.php | 58 - main/install/update-files-1.8.4-1.8.5.inc.php | 58 - main/install/update-files-1.8.5-1.8.6.inc.php | 121 -- .../update-files-1.8.6-1.8.6.1.inc.php | 66 - .../update-files-1.8.6.1-1.8.6.2.inc.php | 98 -- .../update-files-1.8.6.2-1.8.7.inc.php | 77 -- main/install/update-files-1.8.7-1.8.8.inc.php | 77 -- main/install/update-files-1.8.8-1.9.0.inc.php | 87 -- 36 files changed, 7862 deletions(-) delete mode 100755 main/install/migrate-db-1.6.x-1.8.0-post.sql delete mode 100755 main/install/migrate-db-1.6.x-1.8.0-pre.sql delete mode 100755 main/install/migrate-db-1.8.0-1.8.2-pre.sql delete mode 100755 main/install/migrate-db-1.8.2-1.8.3-pre.sql delete mode 100755 main/install/migrate-db-1.8.3-1.8.4-pre.sql delete mode 100755 main/install/migrate-db-1.8.4-1.8.5-pre.sql delete mode 100755 main/install/migrate-db-1.8.5-1.8.6-pre.sql delete mode 100755 main/install/migrate-db-1.8.6-1.8.6.1-pre.sql delete mode 100755 main/install/migrate-db-1.8.6.1-1.8.6.2-post.sql delete mode 100755 main/install/migrate-db-1.8.6.1-1.8.6.2-pre.sql delete mode 100755 main/install/migrate-db-1.8.6.2-1.8.7-post.sql delete mode 100755 main/install/migrate-db-1.8.6.2-1.8.7-pre.sql delete mode 100755 main/install/migrate-db-1.8.7-1.8.8-pre.sql delete mode 100755 main/install/migrate-db-1.8.8-1.9.0-pre.sql delete mode 100755 main/install/migrate-db-1.8.8-1.9.0-pre.sql.optimized delete mode 100755 main/install/update-db-1.6.x-1.8.0.inc.php delete mode 100755 main/install/update-db-1.8.0-1.8.2.inc.php delete mode 100755 main/install/update-db-1.8.2-1.8.3.inc.php delete mode 100755 main/install/update-db-1.8.3-1.8.4.inc.php delete mode 100755 main/install/update-db-1.8.4-1.8.5.inc.php delete mode 100755 main/install/update-db-1.8.5-1.8.6.inc.php delete mode 100755 main/install/update-db-1.8.6-1.8.6.1.inc.php delete mode 100755 main/install/update-db-1.8.6.1-1.8.6.2.inc.php delete mode 100755 main/install/update-db-1.8.6.2-1.8.7.inc.php delete mode 100755 main/install/update-db-1.8.7-1.8.8.inc.php delete mode 100755 main/install/update-db-1.8.8-1.9.0.inc.php delete mode 100755 main/install/update-files-1.6.x-1.8.0.inc.php delete mode 100755 main/install/update-files-1.8.3-1.8.4.inc.php delete mode 100755 main/install/update-files-1.8.4-1.8.5.inc.php delete mode 100755 main/install/update-files-1.8.5-1.8.6.inc.php delete mode 100755 main/install/update-files-1.8.6-1.8.6.1.inc.php delete mode 100755 main/install/update-files-1.8.6.1-1.8.6.2.inc.php delete mode 100755 main/install/update-files-1.8.6.2-1.8.7.inc.php delete mode 100755 main/install/update-files-1.8.7-1.8.8.inc.php delete mode 100755 main/install/update-files-1.8.8-1.9.0.inc.php diff --git a/main/install/migrate-db-1.6.x-1.8.0-post.sql b/main/install/migrate-db-1.6.x-1.8.0-post.sql deleted file mode 100755 index 3c16283aab..0000000000 --- a/main/install/migrate-db-1.6.x-1.8.0-post.sql +++ /dev/null @@ -1,65 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.6.x to version 1.8.0 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations - --- This first part is for the main database --- xxMAINxx - -ALTER TABLE sys_announcement DROP COLUMN visible_teacher_temp; -ALTER TABLE sys_announcement DROP COLUMN visible_student_temp; -ALTER TABLE sys_announcement DROP COLUMN visible_guest_temp; --- DELETE FROM settings_options WHERE variable='showonline'; - - --- xxSTATSxx - --- xxUSERxx - --- xxSCORMxx -DROP TABLE scorm_main; -DROP TABLE scorm_sco_data; - --- xxCOURSExx -ALTER TABLE quiz DROP COLUMN active_temp; -ALTER TABLE tool DROP COLUMN added_tool_temp; - -ALTER TABLE group_info DROP COLUMN tutor_id; -ALTER TABLE group_info DROP COLUMN forum_state; -ALTER TABLE group_info DROP COLUMN forum_id; -ALTER TABLE group_info DROP COLUMN self_registration_allowed_temp; -ALTER TABLE group_info DROP COLUMN self_unregistration_allowed_temp; -ALTER TABLE group_info DROP COLUMN doc_state_temp; - -ALTER TABLE group_category DROP COLUMN forum_state; -ALTER TABLE group_category DROP COLUMN self_reg_allowed_temp; -ALTER TABLE group_category DROP COLUMN self_unreg_allowed_temp; - -DROP TABLE bb_access; -DROP TABLE bb_banlist; -DROP TABLE bb_categories; -DROP TABLE bb_config; -DROP TABLE bb_disallow; -DROP TABLE bb_forum_access; -DROP TABLE bb_forum_mods; -DROP TABLE bb_forums; -DROP TABLE bb_headermetafooter; -DROP TABLE bb_posts; -DROP TABLE bb_posts_text; -DROP TABLE bb_priv_msgs; -DROP TABLE bb_ranks; -DROP TABLE bb_sessions; -DROP TABLE bb_themes; -DROP TABLE bb_topics; -DROP TABLE bb_users; -DROP TABLE bb_whosonline; -DROP TABLE bb_words; - --- ? DROP TABLE stud_pub_rel_user; \ No newline at end of file diff --git a/main/install/migrate-db-1.6.x-1.8.0-pre.sql b/main/install/migrate-db-1.6.x-1.8.0-pre.sql deleted file mode 100755 index 461da541e8..0000000000 --- a/main/install/migrate-db-1.6.x-1.8.0-pre.sql +++ /dev/null @@ -1,315 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.6.x to version 1.8.0 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database --- xxMAINxx -ALTER TABLE admin CHANGE user_id user_id int unsigned NOT NULL default 0; - -ALTER TABLE class_user CHANGE class_id class_id mediumint unsigned NOT NULL default 0; -ALTER TABLE class_user CHANGE user_id user_id int unsigned NOT NULL default 0; - -ALTER TABLE course ADD registration_code varchar(255) NOT NULL default ''; - -ALTER TABLE course_rel_user CHANGE user_id user_id int unsigned NOT NULL default 0; -ALTER TABLE course_rel_user CHANGE sort sort int default NULL; - -ALTER TABLE user CHANGE auth_source auth_source varchar(50) default 'platform'; -ALTER TABLE user ADD language varchar(40) default NULL; -ALTER TABLE user ADD registration_date datetime NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE user ADD expiration_date datetime NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE user ADD active tinyint unsigned NOT NULL default 1; -UPDATE user SET auth_source='platform' WHERE auth_source='claroline'; -UPDATE user SET registration_date=NOW(); - --- Rename table session into php_session -RENAME TABLE session TO php_session; -ALTER TABLE php_session DROP PRIMARY KEY; -ALTER TABLE php_session CHANGE sess_id session_id varchar(32) NOT NULL default ''; -ALTER TABLE php_session CHANGE sess_name session_name varchar(10) NOT NULL default ''; -ALTER TABLE php_session CHANGE sess_time session_time int NOT NULL default '0'; -ALTER TABLE php_session CHANGE sess_start session_start int NOT NULL default '0'; -ALTER TABLE php_session CHANGE sess_value session_value text NOT NULL; -ALTER TABLE php_session ADD PRIMARY KEY (session_id); - -CREATE TABLE session (id smallint unsigned NOT NULL auto_increment, id_coach int unsigned NOT NULL default '0', name char(50) NOT NULL default '', nbr_courses smallint unsigned NOT NULL default '0', nbr_users mediumint unsigned NOT NULL default '0', nbr_classes mediumint unsigned NOT NULL default '0', date_start date NOT NULL default '0000-00-00', date_end date NOT NULL default '0000-00-00', PRIMARY KEY (id), UNIQUE KEY name (name)); -CREATE TABLE session_rel_course(id_session smallint unsigned NOT NULL default '0', course_code char(40) NOT NULL default '', id_coach int unsigned NOT NULL default '0', nbr_users smallint(5) unsigned NOT NULL default '0', PRIMARY KEY (id_session,course_code), KEY course_code (course_code)); -CREATE TABLE session_rel_course_rel_user(id_session smallint unsigned NOT NULL default '0', course_code char(40) NOT NULL default '', id_user int unsigned NOT NULL default '0', PRIMARY KEY (id_session,course_code,id_user), KEY id_user (id_user), KEY course_code (course_code)); -CREATE TABLE session_rel_user(id_session mediumint unsigned NOT NULL default '0', id_user mediumint unsigned NOT NULL default '0', PRIMARY KEY (id_session,id_user)); - -CREATE TABLE shared_survey (survey_id int unsigned NOT NULL auto_increment, code varchar(20) default NULL,title text default NULL,subtitle text default NULL,author varchar(250) default NULL,lang varchar(20) default NULL,template varchar(20) default NULL,intro text,surveythanks text,creation_date datetime NOT NULL default '0000-00-00 00:00:00',course_code varchar(40) NOT NULL default '',PRIMARY KEY (survey_id)); -CREATE TABLE shared_survey_question (question_id int not null auto_increment,survey_id int not null default 0,survey_question text not null,survey_question_comment text not null,type varchar(250) not null default '',display varchar(10) not null default '',sort int not null default 0,code varchar(40) not null default '', max_value int NOT NULL, primary key (question_id)); -CREATE TABLE shared_survey_question_option (question_option_id int NOT NULL auto_increment,question_id int NOT NULL default 0,survey_id int NOT NULL default 0,option_text text NOT NULL,sort int NOT NULL default 0,primary key (question_option_id)); - -ALTER TABLE sys_announcement CHANGE visible_teacher visible_teacher_temp enum('true','false') NOT NULL DEFAULT 'false'; -ALTER TABLE sys_announcement ADD COLUMN visible_teacher tinyint NOT NULL DEFAULT 0; -UPDATE sys_announcement SET visible_teacher = 0 WHERE visible_teacher_temp = 'false'; -UPDATE sys_announcement SET visible_teacher = 1 WHERE visible_teacher_temp = 'true'; - -ALTER TABLE sys_announcement CHANGE visible_student visible_student_temp enum('true','false') NOT NULL DEFAULT 'false'; -ALTER TABLE sys_announcement ADD COLUMN visible_student tinyint NOT NULL DEFAULT 0; -UPDATE sys_announcement SET visible_student = 0 WHERE visible_student_temp = 'false'; -UPDATE sys_announcement SET visible_student = 1 WHERE visible_student_temp = 'true'; - -ALTER TABLE sys_announcement CHANGE visible_guest visible_guest_temp enum('true','false') NOT NULL DEFAULT 'false'; -ALTER TABLE sys_announcement ADD COLUMN visible_guest tinyint NOT NULL DEFAULT 0; -UPDATE sys_announcement SET visible_guest = 0 WHERE visible_guest_temp = 'false'; -UPDATE sys_announcement SET visible_guest = 1 WHERE visible_guest_temp = 'true'; - -ALTER TABLE sys_announcement ADD lang varchar(70) NULL; - --- update contents of the main db tables -UPDATE settings_current SET selected_value = 'activity' WHERE variable='homepage_view'; -UPDATE settings_current SET subkey = 'world', type = 'checkbox', subkeytext = 'ShowOnlineWorld' WHERE variable='showonline'; -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('showonline','users','checkbox','Platform','true','ShowOnlineTitle','ShowOnlineComment',NULL,'ShowOnlineUsers'); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('showonline','course','checkbox','Platform','true','ShowOnlineTitle','ShowOnlineComment',NULL,'ShowOnlineCourse'); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('profile','language','checkbox','User','true','ProfileChangesTitle','ProfileChangesComment',NULL,'Language'); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('registration','language','checkbox','User','true','RegistrationRequiredFormsTitle','RegistrationRequiredFormsComment',NULL,'Language'); --- UPDATE settings_current SET selected_value = 'true' WHERE variable='course_create_active_tools' AND subkey='announcements'; --- UPDATE settings_current SET selected_value = 'true' WHERE variable='course_create_active_tools' AND subkey='forums'; --- UPDATE settings_current SET selected_value = 'true' WHERE variable='course_create_active_tools' AND subkey='dropbox'; --- UPDATE settings_current SET selected_value = 'true' WHERE variable='course_create_active_tools' AND subkey='quiz'; --- UPDATE settings_current SET selected_value = 'true' WHERE variable='course_create_active_tools' AND subkey='users'; --- UPDATE settings_current SET selected_value = 'true' WHERE variable='course_create_active_tools' AND subkey='groups'; --- UPDATE settings_current SET selected_value = 'true' WHERE variable='course_create_active_tools' AND subkey='chat'; --- UPDATE settings_current SET selected_value = 'true' WHERE variable='course_create_active_tools' AND subkey='online_conference'; --- UPDATE settings_current SET selected_value = 'true' WHERE variable='course_create_active_tools' AND subkey='student_publications'; --- UPDATE settings_current SET selected_value = 'true' WHERE variable='use_document_title'; -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_navigation_menu',NULL,'radio','Course','false','ShowNavigationMenuTitle','ShowNavigationMenuComment',NULL,NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('enable_tool_introduction',NULL,'radio','course','false','EnableToolIntroductionTitle','EnableToolIntroductionComment',NULL,NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('page_after_login', NULL, 'radio','Platform','user_portal.php', 'PageAfterLoginTitle','PageAfterLoginComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('time_limit_whosonline', NULL, 'textfield','Platform','30', 'TimeLimitWhosonlineTitle','TimeLimitWhosonlineComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('breadcrumbs_course_homepage', NULL, 'radio','Course','course_title', 'BreadCrumbsCourseHomepageTitle','BreadCrumbsCourseHomepageComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('example_material_course_creation', NULL, 'radio','Platform','true', 'ExampleMaterialCourseCreationTitle','ExampleMaterialCourseCreationComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('account_valid_duration',NULL, 'textfield','Platform','3660', 'AccountValidDurationTitle','AccountValidDurationComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('use_session_mode', NULL, 'radio','Platform','false', 'UseSessionModeTitle','UseSessionModeComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('allow_email_editor', NULL, 'radio', 'Tools', 'false', 'AllowEmailEditorTitle', 'AllowEmailEditorComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('registered', NULL, 'textfield', NULL, 'false', NULL, NULL, NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('donotlistcampus', NULL, 'textfield', NULL, 'false', NULL, NULL, NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_email_addresses', NULL,'radio','Platform','false','ShowEmailAddresses','ShowEmailAddressesComment',NULL,NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('profile','phone','checkbox','User','true','ProfileChangesTitle','ProfileChangesComment',NULL,'phone'); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_visio', 'active', 'radio',NULL,'false', 'visio_actived','', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_visio', 'url', 'textfield',NULL,'', 'visio_url','', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_ppt2lp', 'active', 'radio',NULL,'false', 'ppt2lp_actived','', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_ppt2lp', 'host', 'textfield', NULL, NULL, 'Host', NULL, NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_ppt2lp', 'user', 'textfield', NULL, NULL, 'UserOnHost', NULL, NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_ppt2lp', 'ftp_password', 'textfield', NULL, NULL, 'FtpPassword', NULL, NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_ppt2lp', 'path_to_lzx', 'textfield', NULL, NULL, '', NULL, NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_ppt2lp', 'size', 'radio', NULL, '720x540', '', NULL, NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('wcag_anysurfer_public_pages', NULL, 'radio','Platform','false','PublicPagesComplyToWAITitle','PublicPagesComplyToWAIComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('stylesheets', NULL, 'textfield','stylesheets','public_admin','',NULL, NULL, NULL); - -UPDATE settings_options SET value = 'activity', display_text='HomepageViewActivity' WHERE variable = 'homepage_view' AND value = 'default'; -UPDATE settings_options SET value = '2column', display_text='HomepageView2column' WHERE variable = 'homepage_view' AND value = 'basic_tools_fixed'; -INSERT INTO settings_options(variable,value,display_text) VALUES ('homepage_view','3column','HomepageView3column'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('allow_registration','approval','AfterApproval'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_navigation_menu','false','No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_navigation_menu','icons','IconsOnly'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_navigation_menu','text','TextOnly'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_navigation_menu','iconstext','IconsText'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('enable_tool_introduction','true','Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('enable_tool_introduction','false','No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('page_after_login', 'index.php', 'CampusHomepage'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('page_after_login', 'user_portal.php', 'MyCourses'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('breadcrumbs_course_homepage', 'get_lang', 'CourseHomepage'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('breadcrumbs_course_homepage', 'course_code', 'CourseCode'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('breadcrumbs_course_homepage', 'course_title', 'CourseTitle'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('example_material_course_creation', 'true', 'Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('example_material_course_creation', 'false', 'No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('use_session_mode', 'true', 'Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('use_session_mode', 'false', 'No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('allow_email_editor', 'true' ,'Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('allow_email_editor', 'false', 'No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_email_addresses','true','Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_email_addresses','false','No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('wcag_anysurfer_public_pages', 'true', 'Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('wcag_anysurfer_public_pages', 'false', 'No'); - -UPDATE course_module SET image = 'links.gif' WHERE image='liens.gif'; -UPDATE course_module SET image = 'members.gif' WHERE image = 'membres.gif'; -UPDATE course_module SET link = 'forum/index.php' WHERE link = 'phpbb/index.php'; -UPDATE course_module SET image = 'statistics.gif' WHERE image = 'statistiques.gif'; -UPDATE course_module SET image = 'reference.gif', column = '1' WHERE image = 'referencement.gif'; -DELETE FROM course_module WHERE link = 'coursecopy/backup.php'; -DELETE FROM course_module WHERE link = 'coursecopy/copy_course.php'; -DELETE FROM course_module WHERE link = 'coursecopy/recycle_course.php'; -UPDATE course_module SET link = 'newscorm/lp_controller.php' WHERE link = 'scorm/scormdocument.php'; -INSERT INTO course_module(name,link,image,row,column,position) VALUES ('blog','blog/blog.php','blog.gif',1,2,'basic'); -INSERT INTO course_module(name,link,image,row,column,position) VALUES ('blog_management','blog/blog_admin.php','blog_admin.gif',1,2,'courseadmin'); -INSERT INTO course_module(name,link,image,row,column,position) VALUES ('course_maintenance','course_info/maintenance.php','backup.gif',2,3,'courseadmin'); -INSERT INTO course_module(name,link,image,row,column,position) VALUES ('survey','survey/survey_list.php','survey.gif',2,1,'courseadmin'); - --- xxSTATSxx -CREATE TABLE track_e_attempt(exe_id int default NULL, user_id int NOT NULL default 0, question_id int NOT NULL default 0, answer text NOT NULL, teacher_comment text NOT NULL, marks int NOT NULL default 0, course_code varchar(40) NOT NULL default '', position int default 0); -CREATE TABLE track_e_course_access(course_access_id int NOT NULL auto_increment, course_code varchar(40) NOT NULL, user_id int NOT NULL, login_course_date datetime NOT NULL default '0000-00-00 00:00:00', logout_course_date datetime default NULL, counter int NOT NULL, PRIMARY KEY (course_access_id)); -ALTER TABLE track_e_access CHANGE access_cours_code access_cours_code varchar(40) NOT NULL default ''; -ALTER TABLE track_e_lastaccess CHANGE access_id access_id bigint NOT NULL auto_increment; -ALTER TABLE track_e_lastaccess CHANGE acces_cours_code access_cours_code varchar(40) NOT NULL default ''; -ALTER TABLE track_e_lastaccess ADD access_session_id int unsigned default NULL; -ALTER TABLE track_e_downloads CHANGE down_cours_id down_cours_id varchar(40) NOT NULL default ''; -ALTER TABLE track_e_downloads CHANGE down_doc_path down_doc_path varchar(255) NOT NULL default ''; -ALTER TABLE track_e_links CHANGE links_cours_id links_cours_id varchar(40) NOT NULL default ''; -ALTER TABLE track_e_login ADD logout_date datetime NULL default NULL; -ALTER TABLE track_e_online ADD course varchar(40) default NULL; -ALTER TABLE track_e_uploads CHANGE upload_cours_id upload_cours_id varchar(40) NOT NULL default ''; - - --- xxUSERxx -ALTER TABLE user_course_category ADD `sort` int; - --- xxCOURSExx --- trying to keep the same order in tables declaration as in add_course.lib.inc.php -CREATE TABLE survey ( survey_id int unsigned NOT NULL auto_increment, code varchar(20) default NULL, title text default NULL, subtitle text default NULL, author varchar(20) default NULL, lang varchar(20) default NULL, avail_from date default NULL, avail_till date default NULL, is_shared char(1) default '1', template varchar(20) default NULL, intro text, surveythanks text, creation_date datetime NOT NULL default '0000-00-00 00:00:00', invited int NOT NULL, answered int NOT NULL, invite_mail text NOT NULL, reminder_mail text NOT NULL, PRIMARY KEY (survey_id)); -CREATE TABLE survey_invitation (survey_invitation_id int unsigned NOT NULL auto_increment, survey_code varchar(20) NOT NULL, user varchar(250) NOT NULL, invitation_code varchar(250) NOT NULL, invitation_date datetime NOT NULL, reminder_date datetime NOT NULL, answered int(2) NOT NULL default '0', PRIMARY KEY (survey_invitation_id)); -CREATE TABLE survey_question ( question_id int unsigned NOT NULL auto_increment, survey_id int unsigned NOT NULL, survey_question text NOT NULL, survey_question_comment text NOT NULL, type varchar(250) NOT NULL, display varchar(10) NOT NULL, sort int NOT NULL, shared_question_id int, max_value int, PRIMARY KEY (question_id) ); -CREATE TABLE survey_question_option ( question_option_id int unsigned NOT NULL auto_increment, question_id int unsigned NOT NULL, survey_id int unsigned NOT NULL, option_text text NOT NULL, sort int NOT NULL, PRIMARY KEY (question_option_id) ); -CREATE TABLE survey_answer (answer_id int unsigned NOT NULL auto_increment, survey_id int unsigned NOT NULL, question_id int NOT NULL, option_id TEXT NOT NULL, value int unsigned not null, user varchar(250) NOT NULL, PRIMARY KEY (answer_id) ); - -ALTER TABLE announcement CHANGE content content mediumtext; -ALTER TABLE announcement ADD email_sent tinyint default 0; - --- resource table --- userinfo_content table --- userinfo_def table - -CREATE TABLE forum_category(cat_id int NOT NULL auto_increment, cat_title varchar(255) NOT NULL default '', cat_comment text, cat_order int NOT NULL default 0, locked int NOT NULL default 0, PRIMARY KEY (cat_id)); -CREATE TABLE forum_forum(forum_id int NOT NULL auto_increment, forum_title varchar(255) NOT NULL default '', forum_comment text, forum_threads int default 0, forum_posts int default 0, forum_last_post int default 0, forum_category int default NULL, allow_anonymous int default NULL, allow_edit int default NULL, approval_direct_post varchar(20) default NULL, allow_attachments int default NULL, allow_new_threads int default NULL, default_view varchar(20) default NULL, forum_of_group varchar(20) default NULL, forum_group_public_private varchar(20) default 'public', forum_order int default NULL, locked int NOT NULL default 0, PRIMARY KEY (forum_id)); -CREATE TABLE forum_thread(thread_id int NOT NULL auto_increment,thread_title varchar(255) default NULL, forum_id int default NULL, thread_replies int default 0, thread_poster_id int default NULL, thread_poster_name varchar(100) default '', thread_views int default 0, thread_last_post int default NULL, thread_date datetime default '0000-00-00 00:00:00', thread_sticky tinyint unsigned default 0, locked int NOT NULL default 0, PRIMARY KEY (thread_id), KEY thread_id (thread_id)); -CREATE TABLE forum_post(post_id int NOT NULL auto_increment, post_title varchar(250) default NULL, post_text text, thread_id int default 0, forum_id int default 0, poster_id int default 0, poster_name varchar(100) default '', post_date datetime default '0000-00-00 00:00:00', post_notification tinyint default 0, post_parent_id int default 0, visible tinyint default 1, PRIMARY KEY (post_id), KEY poster_id (poster_id), KEY forum_id (forum_id)); -CREATE TABLE forum_mailcue(thread_id int default NULL, user_id int default NULL, post_id int default NULL); - --- quiz table -ALTER TABLE quiz CHANGE active active_temp enum('true','false') NOT NULL DEFAULT 'false'; -ALTER TABLE quiz ADD COLUMN active tinyint NOT NULL DEFAULT 0; -UPDATE quiz SET active = 1 WHERE active_temp = 'true'; -UPDATE quiz SET active = 0 WHERE active_temp = 'false'; --- quiz_question table -ALTER TABLE quiz_answer ADD COLUMN hotspot_coordinates tinytext; -ALTER TABLE quiz_answer ADD COLUMN hotspot_type enum('square','circle','poly') default NULL; --- quiz_rel_question table - --- course_description table --- tool table (see insert/update queries after tables alterations) -ALTER TABLE tool CHANGE added_tool added_tool_temp enum('0','1') NOT NULL DEFAULT 1; -ALTER TABLE tool ADD COLUMN added_tool tinyint NOT NULL DEFAULT 1; -UPDATE tool SET added_tool = 0 WHERE added_tool_temp = '0'; -UPDATE tool SET added_tool = 1 WHERE added_tool_temp = '1'; -ALTER TABLE tool ADD COLUMN category enum('authoring','interaction','admin') NOT NULL default 'authoring'; -UPDATE tool SET category = 'authoring' WHERE name IN ('course_description','document','learnpath','link','quiz'); -UPDATE tool SET category = 'interaction' WHERE name IN ('student_publication','chat','group','user','dropbox','forum','announcement','calendar_event'); -UPDATE tool SET category = 'admin' WHERE name IN ('blog_management','tracking','course_setting','survey','course_maintenance'); -UPDATE tool SET name='forum' WHERE name='bb_forum'; --- calendar_event table --- document table --- scorm_document table (deprecated) - -ALTER TABLE student_publication ADD COLUMN post_group_id int DEFAULT 0 NOT NULL; - --- link table --- link_category table --- online_connected table --- online_link table --- chat_connected table - -ALTER TABLE group_info MODIFY secret_directory varchar(255) default NULL; -ALTER TABLE group_info ADD COLUMN calendar_state tinyint unsigned NOT NULL default 0; -ALTER TABLE group_info ADD COLUMN work_state tinyint unsigned NOT NULL default 0; -ALTER TABLE group_info ADD COLUMN announcements_state tinyint unsigned NOT NULL default 0; -ALTER TABLE group_info CHANGE self_registration_allowed self_registration_allowed_temp enum('0','1') NOT NULL default '0'; -ALTER TABLE group_info ADD COLUMN self_registration_allowed tinyint unsigned NOT NULL default 0; -UPDATE group_info SET self_registration_allowed = 0 WHERE self_registration_allowed_temp = '0'; -UPDATE group_info SET self_registration_allowed = 1 WHERE self_registration_allowed_temp = '1'; - -ALTER TABLE group_info CHANGE self_unregistration_allowed self_unregistration_allowed_temp enum('0','1') NOT NULL default '0'; -ALTER TABLE group_info ADD COLUMN self_unregistration_allowed tinyint unsigned NOT NULL default 0; -UPDATE group_info SET self_unregistration_allowed = 0 WHERE self_unregistration_allowed_temp = '0'; -UPDATE group_info SET self_unregistration_allowed = 1 WHERE self_unregistration_allowed_temp = '1'; - -ALTER TABLE group_info CHANGE doc_state doc_state_temp enum('0','1','2') NOT NULL default '1'; -ALTER TABLE group_info ADD COLUMN doc_state tinyint unsigned NOT NULL default 1; -UPDATE group_info SET doc_state = 0 WHERE doc_state_temp = '0'; -UPDATE group_info SET doc_state = 1 WHERE doc_state_temp = '1'; -UPDATE group_info SET doc_state = 2 WHERE doc_state_temp = '2'; - -ALTER TABLE group_category ADD COLUMN calendar_state tinyint unsigned NOT NULL default 1; -ALTER TABLE group_category ADD COLUMN work_state tinyint unsigned NOT NULL default 1; -ALTER TABLE group_category ADD COLUMN announcements_state tinyint unsigned NOT NULL default 1; - -ALTER TABLE group_category CHANGE self_reg_allowed self_reg_allowed_temp enum('0','1') NOT NULL default '0'; -ALTER TABLE group_category ADD COLUMN self_reg_allowed tinyint unsigned NOT NULL default 0; -UPDATE group_category SET self_reg_allowed = 0 WHERE self_reg_allowed_temp = '0'; -UPDATE group_category SET self_reg_allowed = 1 WHERE self_reg_allowed_temp = '1'; - -ALTER TABLE group_category CHANGE self_unreg_allowed self_unreg_allowed_temp enum('0','1') NOT NULL default '0'; -ALTER TABLE group_category ADD COLUMN self_unreg_allowed tinyint unsigned NOT NULL default 0; -UPDATE group_category SET self_unreg_allowed = 0 WHERE self_unreg_allowed_temp = '0'; -UPDATE group_category SET self_unreg_allowed = 1 WHERE self_unreg_allowed_temp = '1'; - --- group_rel_user table - -CREATE TABLE group_rel_tutor(id int NOT NULL auto_increment, user_id int NOT NULL, group_id int NOT NULL default 0, PRIMARY KEY (id)); - --- item_property table --- tool_intro table - --- dropbox_file table -ALTER TABLE dropbox_file ADD cat_id INT NOT NULL ; --- dropbox_post table -ALTER TABLE dropbox_post ADD cat_id INT NOT NULL ; --- dropbox_person table -CREATE TABLE dropbox_category(cat_id int NOT NULL auto_increment, cat_name text NOT NULL, received tinyint unsigned NOT NULL default 0, sent tinyint unsigned NOT NULL default 0, user_id int NOT NULL default 0, PRIMARY KEY (cat_id)); -CREATE TABLE dropbox_feedback(feedback_id int NOT NULL auto_increment, file_id int NOT NULL default 0, author_user_id int NOT NULL default 0, feedback text NOT NULL, feedback_date datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (feedback_id), KEY file_id (file_id), KEY author_user_id (author_user_id)); - -CREATE TABLE lp(id int unsigned primary key auto_increment, lp_type smallint unsigned not null, name tinytext not null, ref tinytext null, description text null, path text not null, force_commit tinyint unsigned not null default 0, default_view_mod char(32) not null default 'embedded', default_encoding char(32) not null default 'ISO-8859-1', display_order int unsigned not null default 0, content_maker tinytext not null default '', content_local varchar(32) not null default 'local', content_license text not null default '', prevent_reinit tinyint unsigned not null default 1, js_lib tinytext not null default '', debug tinyint unsigned not null default 0); -CREATE TABLE lp_view(id int unsigned primary key auto_increment, lp_id int unsigned not null, user_id int unsigned not null, view_count smallint unsigned not null default 0, last_item int unsigned not null default 0, progress int unsigned default 0); -CREATE TABLE lp_item(id int unsigned primary key auto_increment, lp_id int unsigned not null, item_type char(32) not null default 'dokeos_document', ref tinytext not null default '', title tinytext not null, description tinytext not null default '', path text not null, min_score float unsigned not null default 0, max_score float unsigned not null default 100, mastery_score float unsigned null, parent_item_id int unsigned not null default 0, previous_item_id int unsigned not null default 0, next_item_id int unsigned not null default 0, display_order int unsigned not null default 0, prerequisite char(64) null, parameters text null, launch_data text not null default ''); -CREATE TABLE lp_item_view(id bigint unsigned primary key auto_increment, lp_item_id int unsigned not null, lp_view_id int unsigned not null, view_count int unsigned not null default 0, start_time int unsigned not null, total_time int unsigned not null default 0, score float unsigned not null default 0, status char(32) not null default 'Not attempted', suspend_data text null default '', lesson_location text null default ''); -CREATE TABLE lp_iv_interaction(id bigint unsigned primary key auto_increment, order_id smallint unsigned not null default 0, lp_iv_id bigint unsigned not null, interaction_id varchar(255) not null default '', interaction_type varchar(255) not null default '', weighting double not null default 0, completion_time varchar(16) not null default '', correct_responses text not null default '', student_response text not null default '', result varchar(255) not null default '', latency varchar(16) not null default ''); - -CREATE TABLE blog(blog_id smallint NOT NULL AUTO_INCREMENT , blog_name varchar(250) NOT NULL default '', blog_subtitle varchar( 250 ) default NULL , date_creation datetime NOT NULL default '0000-00-00 00:00:00', visibility tinyint unsigned NOT NULL default 0, PRIMARY KEY (blog_id)); -CREATE TABLE blog_comment(comment_id int NOT NULL AUTO_INCREMENT , title varchar(250) NOT NULL default '', comment longtext NOT NULL , author_id int NOT NULL default 0, date_creation datetime NOT NULL default '0000-00-00 00:00:00', blog_id mediumint NOT NULL default 0, post_id int NOT NULL default 0, task_id int default NULL , parent_comment_id int NOT NULL default 0, PRIMARY KEY (comment_id)); -CREATE TABLE blog_post(post_id int NOT NULL AUTO_INCREMENT, title varchar(250) NOT NULL default '', full_text longtext NOT NULL, date_creation datetime NOT NULL default '0000-00-00 00:00:00', blog_id mediumint NOT NULL default 0, author_id int NOT NULL default 0, PRIMARY KEY (post_id)); -CREATE TABLE blog_rating(rating_id int NOT NULL AUTO_INCREMENT, blog_id int NOT NULL default 0, rating_type enum( 'post', 'comment' ) NOT NULL default 'post', item_id int NOT NULL default 0, user_id int NOT NULL default 0, rating mediumint NOT NULL default 0, PRIMARY KEY (rating_id)); -CREATE TABLE blog_rel_user(blog_id int NOT NULL default 0, user_id int NOT NULL default 0, PRIMARY KEY (blog_id,user_id)); -CREATE TABLE blog_task(task_id mediumint NOT NULL AUTO_INCREMENT,blog_id mediumint NOT NULL default 0,title varchar( 250 ) NOT NULL default '',description text NOT NULL ,color varchar( 10 ) NOT NULL default '', system_task tinyint unsigned NOT NULL default 0,PRIMARY KEY (task_id)); -CREATE TABLE blog_task_rel_user(blog_id mediumint NOT NULL default 0,user_id int NOT NULL default 0,task_id mediumint NOT NULL default 0,target_date date NOT NULL default '0000-00-00',PRIMARY KEY (blog_id,user_id,task_id)); - -CREATE TABLE permission_group(id int NOT NULL AUTO_INCREMENT, group_id int NOT NULL default 0, tool varchar( 250 ) NOT NULL default '', action varchar( 250 ) NOT NULL default '', PRIMARY KEY ( id )); -CREATE TABLE permission_user(id int NOT NULL AUTO_INCREMENT, user_id int NOT NULL default 0, tool varchar( 250 ) NOT NULL default '', action varchar( 250 ) NOT NULL default '', PRIMARY KEY ( id )); -CREATE TABLE permission_task(id int NOT NULL AUTO_INCREMENT, task_id int NOT NULL default 0, tool varchar( 250 ) NOT NULL default '', action varchar( 250 ) NOT NULL default '', PRIMARY KEY ( id )); - -CREATE TABLE role(role_id int NOT NULL AUTO_INCREMENT , role_name varchar( 250 ) NOT NULL default '', role_comment text, default_role tinyint default 0, PRIMARY KEY ( role_id )); -CREATE TABLE role_group(role_id int NOT NULL default 0, scope varchar( 20 ) NOT NULL default 'course', group_id int NOT NULL default 0); -CREATE TABLE role_permissions(role_id int NOT NULL default 0, tool varchar( 250 ) NOT NULL default '', action varchar( 50 ) NOT NULL default '', default_perm tinyint NOT NULL default 0); -CREATE TABLE role_user(role_id int NOT NULL default 0, scope varchar( 20 ) NOT NULL default 'course', user_id int NOT NULL default 0); - -CREATE TABLE course_setting(id int unsigned NOT NULL auto_increment, variable varchar(255) NOT NULL default '', subkey varchar(255) default NULL, type varchar(255) default NULL,category varchar(255) default NULL,value varchar(255) NOT NULL default '', title varchar(255) NOT NULL default '',comment varchar(255) default NULL, subkeytext varchar(255) default NULL, PRIMARY KEY (id)); - -UPDATE tool SET image = 'links.gif' WHERE image = 'liens.gif'; -UPDATE tool SET image = 'members.gif' WHERE image = 'membres.gif'; -UPDATE tool SET link = 'forum/index.php' WHERE link = 'phpbb/index.php'; -UPDATE tool SET image = 'statistics.gif', category='admin' WHERE image = 'statistiques.gif'; -UPDATE tool SET image = 'reference.gif' WHERE image = 'referencement.gif'; -UPDATE tool SET address = 'squaregrey.gif' WHERE address = 'pastillegris.gif'; --- UPDATE tool SET column = '1' WHERE image = 'reference.gif'; -DELETE FROM tool WHERE link = 'coursecopy/backup.php'; -DELETE FROM tool WHERE link = 'coursecopy/copy_course.php'; -DELETE FROM tool WHERE link = 'coursecopy/recycle_course.php'; -DELETE FROM tool WHERE link = 'link/link.php?action=addlink'; -UPDATE tool SET link = 'newscorm/lp_controller.php' WHERE link = 'scorm/scormdocument.php'; --- INSERT INTO tool(name,link,image,visibility,admin,address,added_tool,target,category) VALUES ('visio','conf/','visio.gif',0,'0','squaregrey.gif',0,'_self','authoring'); -INSERT INTO tool(name,link,image,visibility,admin,address,added_tool,target,category) VALUES ('blog_management','blog/blog_admin.php','blog_admin.gif',0,'1','squaregrey.gif',0,'_self','admin'); -INSERT INTO tool(name,link,image,visibility,admin,address,added_tool,target,category) VALUES ('survey','survey/survey_list.php','survey.gif',0,'1','',0,'_self','admin'); -INSERT INTO tool(name,link,image,visibility,admin,address,added_tool,target,category) VALUES ('course_maintenance','course_info/maintenance.php','backup.gif',0,'1','',0,'_self', 'admin'); -INSERT INTO course_setting(variable,value,category) VALUES ('email_alert_manager_on_new_doc',0,'work'); -INSERT INTO course_setting(variable,value,category) VALUES ('email_alert_on_new_doc_dropbox',0,'dropbox'); -INSERT INTO course_setting(variable,value,category) VALUES ('allow_user_edit_agenda',0,'agenda'); -INSERT INTO course_setting(variable,value,category) VALUES ('allow_user_edit_announcement',0,'announcement'); diff --git a/main/install/migrate-db-1.8.0-1.8.2-pre.sql b/main/install/migrate-db-1.8.0-1.8.2-pre.sql deleted file mode 100755 index d1f57f4ca1..0000000000 --- a/main/install/migrate-db-1.8.0-1.8.2-pre.sql +++ /dev/null @@ -1,78 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.0 to version 1.8.2 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database --- xxMAINxx -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('upload_extensions_list_type', NULL, 'radio', 'Security', 'blacklist', 'UploadExtensionsListType', 'UploadExtensionsListTypeComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('upload_extensions_blacklist', NULL, 'textfield', 'Security', '', 'UploadExtensionsBlacklist', 'UploadExtensionsBlacklistComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('upload_extensions_whitelist', NULL, 'textfield', 'Security', 'htm;html;jpg;jpeg;gif;png;swf;avi;mpg;mpeg;mov;flv;doc;docx;xls;xlsx;ppt;pptx;odt;odp;ods;pdf', 'UploadExtensionsWhitelist', 'UploadExtensionsWhitelistComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('upload_extensions_skip', NULL, 'radio', 'Security', 'true', 'UploadExtensionsSkip', 'UploadExtensionsSkipComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('upload_extensions_replace_by', NULL, 'textfield', 'Security', 'txt', 'UploadExtensionsReplaceBy', 'UploadExtensionsReplaceByComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_visio', 'visio_rtmp_host_local', 'textfield',NULL,'', 'VisioHostLocal','', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_visio', 'visio_is_web_rtmp', 'radio',NULL,'false', 'VisioRTMPIsWeb','', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_visio', 'visio_rtmp_port', 'textfield',NULL,'1935', 'VisioRTMPPort','', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('service_visio', 'visio_rtmp_tunnel_port', 'textfield',NULL,'80', 'VisioRTMPTunnelPort','', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_number_of_courses', NULL, 'radio','Platform','false', 'ShowNumberOfCourses','ShowNumberOfCoursesComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_empty_course_categories', NULL, 'radio','Platform','true', 'ShowEmptyCourseCategories','ShowEmptyCourseCategoriesComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_back_link_on_top_of_tree', NULL, 'radio','Platform','false', 'ShowBackLinkOnTopOfCourseTree','ShowBackLinkOnTopOfCourseTreeComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_different_course_language', NULL, 'radio','Platform','true', 'ShowDifferentCourseLanguage','ShowDifferentCourseLanguageComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('split_users_upload_directory', NULL, 'radio','Tuning','false', 'SplitUsersUploadDirectory','SplitUsersUploadDirectoryComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('hide_dltt_markup', NULL, 'radio','Platform','false', 'HideDLTTMarkup','HideDLTTMarkupComment', NULL, NULL); - - -INSERT INTO settings_options(variable,value,display_text) VALUES ('upload_extensions_list_type', 'blacklist', 'Blacklist'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('upload_extensions_list_type', 'whitelist', 'Whitelist'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('upload_extensions_skip', 'true', 'Remove'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('upload_extensions_skip', 'false', 'Rename'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('visio_rtmp_host_local', 'true', 'Web'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('visio_rtmp_host_local', 'false', 'Not web'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_number_of_courses', 'true', 'Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_number_of_courses', 'false', 'No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_empty_course_categories', 'true', 'Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_empty_course_categories', 'false', 'No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_back_link_on_top_of_tree', 'true', 'Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_back_link_on_top_of_tree', 'false', 'No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_different_course_language', 'true', 'Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('show_different_course_language', 'false', 'No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('split_users_upload_directory', 'true', 'Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('split_users_upload_directory', 'false', 'No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('hide_dltt_markup', 'false', 'No'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('hide_dltt_markup', 'true', 'Yes'); - --- Insert anonymous user -INSERT INTO user(lastname, firstname, username, password, auth_source, email, status, official_code, creator_id, registration_date, expiration_date,active) VALUES ('Anonymous', 'Joe', '', '', 'platform', 'anonymous@localhost', 6, 'anonymous', 1, NOW(), '0000-00-00 00:00:00', 1); -ALTER TABLE user ADD INDEX (status); - --- xxSTATSxx -ALTER TABLE track_e_attempt ADD INDEX (exe_id); -ALTER TABLE track_e_attempt ADD INDEX (user_id); -ALTER TABLE track_e_attempt ADD INDEX (question_id); -ALTER TABLE track_e_exercices ADD INDEX (exe_user_id); -ALTER TABLE track_e_course_access ADD INDEX (user_id); -ALTER TABLE track_e_course_access ADD INDEX (login_course_date); -ALTER TABLE track_e_course_access ADD INDEX (course_code); - --- xxUSERxx - --- xxCOURSExx -CREATE TABLE survey_answer (answer_id int unsigned NOT NULL auto_increment, survey_id int unsigned NOT NULL, question_id int NOT NULL, option_id TEXT NOT NULL, value int unsigned not null, user varchar(250) NOT NULL, PRIMARY KEY (answer_id) ); - -ALTER TABLE lp_view ADD INDEX (lp_id); -ALTER TABLE lp_view ADD INDEX (user_id); -ALTER TABLE lp_item ADD INDEX (lp_id); -ALTER TABLE lp_item_view ADD INDEX (lp_item_id); -ALTER TABLE lp_item_view ADD INDEX (lp_view_id); -ALTER TABLE lp_iv_interaction ADD INDEX (lp_iv_id); -ALTER TABLE quiz_question ADD INDEX (position); -ALTER TABLE forum_thread ADD INDEX (forum_id); -ALTER TABLE forum_thread DROP INDEX thread_id; -ALTER TABLE lp_item_view ADD core_exit varchar(32) NOT NULL DEFAULT 'none'; diff --git a/main/install/migrate-db-1.8.2-1.8.3-pre.sql b/main/install/migrate-db-1.8.2-1.8.3-pre.sql deleted file mode 100755 index 430693ab44..0000000000 --- a/main/install/migrate-db-1.8.2-1.8.3-pre.sql +++ /dev/null @@ -1,25 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.2 to version 1.8.3 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database --- xxMAINxx -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('display_categories_on_homepage',NULL,'radio','Platform','true','DisplayCategoriesOnHomepageTitle','DisplayCategoriesOnHomepageComment',NULL,NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('permissions_for_new_directories', NULL, 'textfield', 'Security', '0770', 'PermissionsForNewDirs', 'PermissionsForNewDirsComment', NULL, NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('permissions_for_new_files', NULL, 'textfield', 'Security', '0660', 'PermissionsForNewFiles', 'PermissionsForNewFilesComment', NULL, NULL); - -INSERT INTO settings_options(variable,value,display_text) VALUES ('display_categories_on_homepage', 'true', 'Yes'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('display_categories_on_homepage', 'false', 'No'); --- xxSTATSxx - --- xxUSERxx - --- xxCOURSExx diff --git a/main/install/migrate-db-1.8.3-1.8.4-pre.sql b/main/install/migrate-db-1.8.3-1.8.4-pre.sql deleted file mode 100755 index f03658c5c7..0000000000 --- a/main/install/migrate-db-1.8.3-1.8.4-pre.sql +++ /dev/null @@ -1,37 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.3 to version 1.8.4 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database --- xxMAINxx -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_tabs', 'campus_homepage', 'checkbox', 'Platform', 'true', 'ShowTabsTitle','ShowTabsComment',NULL,'TabsCampusHomepage'); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_tabs', 'my_courses', 'checkbox', 'Platform', 'true', 'ShowTabsTitle','ShowTabsComment',NULL,'TabsMyCourses'); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_tabs', 'reporting', 'checkbox', 'Platform', 'true', 'ShowTabsTitle','ShowTabsComment',NULL,'TabsReporting'); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_tabs', 'platform_administration', 'checkbox', 'Platform', 'true', 'ShowTabsTitle','ShowTabsComment',NULL,'TabsPlatformAdministration'); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_tabs', 'my_agenda', 'checkbox', 'Platform', 'true', 'ShowTabsTitle','ShowTabsComment',NULL,'TabsMyAgenda'); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('show_tabs', 'my_profile', 'checkbox', 'Platform', 'true', 'ShowTabsTitle','ShowTabsComment',NULL,'TabsMyProfile'); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('default_forum_view', NULL, 'radio', 'Course', 'flat', 'DefaultForumViewTitle','DefaultForumViewComment',NULL,NULL); -INSERT INTO settings_current(variable,subkey,type,category,selected_value,title,comment,scope,subkeytext) VALUES ('platform_charset',NULL,'textfield','Platform','iso-8859-15','PlatformCharsetTitle','PlatformCharsetComment','platform',NULL); - -INSERT INTO settings_options(variable,value,display_text) VALUES ('default_forum_view', 'flat', 'Flat'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('default_forum_view', 'threaded', 'Threaded'); -INSERT INTO settings_options(variable,value,display_text) VALUES ('default_forum_view', 'nested', 'Nested'); - --- xxSTATSxx -CREATE TABLE track_e_hotspot (hotspot_id int NOT NULL auto_increment, hotspot_user_id int NOT NULL, hotspot_course_code varchar(50) NOT NULL, hotspot_exe_id int NOT NULL, hotspot_question_id int NOT NULL, hotspot_answer_id int NOT NULL, hotspot_correct tinyint unsigned NOT NULL, hotspot_coordinate varchar(50) NOT NULL, PRIMARY KEY (hotspot_id), KEY hotspot_course_code (hotspot_course_code), KEY hotspot_user_id (hotspot_user_id), KEY hotspot_exe_id (hotspot_exe_id), KEY hotspot_question_id (hotspot_question_id)); - --- xxUSERxx - --- xxCOURSExx -ALTER TABLE survey ADD anonymous ENUM( '0', '1' ) NOT NULL DEFAULT '0'; -ALTER TABLE lp_item ADD max_time_allowed char(13) NULL DEFAULT ''; -ALTER TABLE item_property ADD INDEX (tool(20),ref); -ALTER TABLE lp_item_view ADD max_score varchar(8) default ''; \ No newline at end of file diff --git a/main/install/migrate-db-1.8.4-1.8.5-pre.sql b/main/install/migrate-db-1.8.4-1.8.5-pre.sql deleted file mode 100755 index b1dabd382b..0000000000 --- a/main/install/migrate-db-1.8.4-1.8.5-pre.sql +++ /dev/null @@ -1,159 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.4 to version 1.8.5 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database --- xxMAINxx -ALTER TABLE settings_current ADD UNIQUE unique_setting (variable,subkey,category); -ALTER TABLE settings_options ADD UNIQUE unique_setting_option (variable,value); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('extendedprofile_registration', 'mycomptetences', 'checkbox', 'User', 'false', 'ExtendedProfileRegistrationTitle', 'ExtendedProfileRegistrationComment', NULL, 'MyCompetences'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('extendedprofile_registration', 'mydiplomas', 'checkbox', 'User', 'false', 'ExtendedProfileRegistrationTitle', 'ExtendedProfileRegistrationComment', NULL, 'MyDiplomas'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('extendedprofile_registration', 'myteach', 'checkbox', 'User', 'false', 'ExtendedProfileRegistrationTitle', 'ExtendedProfileRegistrationComment', NULL, 'MyTeach'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('extendedprofile_registration', 'mypersonalopenarea', 'checkbox', 'User', 'false', 'ExtendedProfileRegistrationTitle', 'ExtendedProfileRegistrationComment', NULL, 'MyPersonalOpenArea'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('extendedprofile_registrationrequired', 'mycomptetences', 'checkbox', 'User', 'false', 'ExtendedProfileRegistrationRequiredTitle', 'ExtendedProfileRegistrationRequiredComment', NULL, 'MyCompetences'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('extendedprofile_registrationrequired', 'mydiplomas', 'checkbox', 'User', 'false', 'ExtendedProfileRegistrationRequiredTitle', 'ExtendedProfileRegistrationRequiredComment', NULL, 'MyDiplomas'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('extendedprofile_registrationrequired', 'myteach', 'checkbox', 'User', 'false', 'ExtendedProfileRegistrationRequiredTitle', 'ExtendedProfileRegistrationRequiredComment', NULL, 'MyTeach'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('extendedprofile_registrationrequired', 'mypersonalopenarea', 'checkbox', 'User', 'false', 'ExtendedProfileRegistrationRequiredTitle', 'ExtendedProfileRegistrationRequiredComment', NULL, 'MyPersonalOpenArea'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('noreply_email_address', '', 'textfield', 'Platform', '', 'NoReplyEmailAddress', 'NoReplyEmailAddressComment', NULL, NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('survey_email_sender_noreply', '', 'radio', 'Course', 'coach', 'SurveyEmailSenderNoReply', 'SurveyEmailSenderNoReplyComment', NULL, NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('survey_email_sender_noreply', 'coach', 'CourseCoachEmailSender'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('survey_email_sender_noreply', 'noreply', 'NoReplyEmailSender'); -DELETE FROM settings_current WHERE variable='show_student_view'; -DELETE FROM settings_options WHERE variable='show_student_view'; -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('openid_authentication', NULL, 'radio', 'Security', 'false', 'OpenIdAuthentication', 'OpenIdAuthenticationComment', NULL, NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('openid_authentication', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('openid_authentication', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('profile','openid','checkbox','User','false','ProfileChangesTitle','ProfileChangesComment',NULL,'OpenIDURL'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('display_mini_month_calendar', '', 'radio', 'Tools', 'true', 'DisplayMiniMonthCalendarTitle', 'DisplayMiniMonthCalendarComment', NULL, NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('display_upcoming_events', '', 'radio', 'Tools', 'true', 'DisplayUpcomingEventsTitle', 'DisplayUpcomingEventsComment', NULL, NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('number_of_upcoming_events', '', 'textfield', 'Tools', '1', 'NumberOfUpcomingEventsTitle', 'NumberOfUpcomingEventsComment', NULL, NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('display_mini_month_calendar', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('display_mini_month_calendar', 'false', 'No'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('display_upcoming_events', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('display_upcoming_events', 'false', 'No'); - -CREATE TABLE templates (id int NOT NULL auto_increment, title varchar(100) NOT NULL, description varchar(250) NOT NULL, course_code varchar(40) NOT NULL, user_id int NOT NULL, ref_doc int NOT NULL, PRIMARY KEY (id)); -ALTER TABLE user ADD openid varchar(255) DEFAULT NULL; -ALTER TABLE user ADD INDEX (openid(50)); -CREATE TABLE IF NOT EXISTS openid_association (id int NOT NULL auto_increment,idp_endpoint_uri text NOT NULL,session_type varchar(30) NOT NULL,assoc_handle text NOT NULL,assoc_type text NOT NULL,expires_in bigint NOT NULL,mac_key text NOT NULL,created bigint NOT NULL,PRIMARY KEY (id)); -CREATE TABLE gradebook_category ( id int NOT NULL auto_increment, name text NOT NULL, description text, user_id int NOT NULL, course_code varchar(40) default NULL, parent_id int default NULL, weight smallint NOT NULL, visible tinyint NOT NULL, certif_min_score int DEFAULT NULL, PRIMARY KEY (id)); -CREATE TABLE gradebook_evaluation ( id int unsigned NOT NULL auto_increment, name text NOT NULL, description text, user_id int NOT NULL, course_code varchar(40) default NULL, category_id int default NULL, date int default 0, weight smallint NOT NULL, max float unsigned NOT NULL, visible tinyint NOT NULL, PRIMARY KEY (id)); -CREATE TABLE gradebook_link ( id int NOT NULL auto_increment, type int NOT NULL, ref_id int NOT NULL, user_id int NOT NULL, course_code varchar(40) NOT NULL, category_id int NOT NULL, date int default NULL, weight smallint NOT NULL, visible tinyint NOT NULL, PRIMARY KEY (id)); -CREATE TABLE gradebook_result ( id int NOT NULL auto_increment, user_id int NOT NULL, evaluation_id int NOT NULL, date int NOT NULL, score float unsigned default NULL, PRIMARY KEY (id)); -CREATE TABLE gradebook_score_display ( id int NOT NULL auto_increment, score float unsigned NOT NULL, display varchar(40) NOT NULL, PRIMARY KEY (id)); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('gradebook_enable', NULL, 'radio', 'Gradebook', 'false', 'GradebookActivation', 'GradebookActivationComment', NULL, NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('gradebook_enable', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('gradebook_enable', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('show_tabs','my_gradebook','checkbox','Platform','true','ShowTabsTitle','ShowTabsComment',NULL,'TabsMyGradebook'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('gradebook_score_display_coloring', 'my_display_coloring', 'checkbox', 'Gradebook', 'false', 'GradebookScoreDisplayColoring', 'GradebookScoreDisplayColoringComment', NULL, 'TabsGradebookEnableColoring'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('gradebook_score_display_custom', 'my_display_custom', 'checkbox', 'Gradebook', 'false', 'GradebookScoreDisplayCustom', 'GradebookScoreDisplayCustomComment', NULL, 'TabsGradebookEnableCustom'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('gradebook_score_display_colorsplit', NULL, 'textfield', 'Gradebook', '50', 'GradebookScoreDisplayColorSplit', 'GradebookScoreDisplayColorSplitComment', NULL, NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('gradebook_score_display_upperlimit', 'my_display_upperlimit', 'checkbox', 'Gradebook', 'false', 'GradebookScoreDisplayUpperLimit', 'GradebookScoreDisplayUpperLimitComment', NULL, 'TabsGradebookEnableUpperLimit'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('service_ppt2lp', 'port', 'checkbox', NULL, '2002', 'Port', NULL, NULL, NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('user_selected_theme',NULL,'radio','Platform','false','UserThemeSelection','UserThemeSelectionComment',NULL,NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('profile','theme','checkbox','User','false','ProfileChangesTitle','ProfileChangesComment',NULL,'UserTheme'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('user_selected_theme', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('user_selected_theme', 'false', 'No'); -ALTER TABLE user ADD theme varchar(255) DEFAULT NULL; -ALTER TABLE user ADD hr_dept_id smallint unsigned NOT NULL default 0; -UPDATE settings_current SET variable='service_visio', subkey='active' , title='VisioEnable' WHERE variable='service_visio' AND subkey='active'; -UPDATE settings_current SET variable='service_visio', subkey='visio_host', title='VisioHost' WHERE variable='service_visio' AND subkey='visio_rtmp_host_local'; -UPDATE settings_current SET variable='service_visio', subkey='visio_port', title='VisioPort' WHERE variable='service_visio' AND subkey='visio_rtmp_port'; -UPDATE settings_current SET variable='service_visio', subkey='visio_pass', title='VisioPassword', type='textfield' WHERE variable='service_visio' AND subkey='visio_rtmp_tunnel_port'; -DELETE FROM settings_options WHERE variable = 'visio_rtmp_host_local'; -DELETE FROM settings_current WHERE variable='service_visio' AND subkey='visioconference_url'; -DELETE FROM settings_current WHERE variable='service_visio' AND subkey='visioclassroom_url'; -DELETE FROM settings_current WHERE variable='service_visio' AND subkey='visio_is_web_rtmp'; -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('allow_course_theme',NULL,'radio','Course','true','AllowCourseThemeTitle','AllowCourseThemeComment',NULL,NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_course_theme', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_course_theme', 'false', 'No'); -CREATE TABLE user_field (id INT NOT NULL auto_increment,field_type int NOT NULL DEFAULT 1,field_variable varchar(64) NOT NULL,field_display_text varchar(64),field_default_value text,field_order int,field_visible tinyint default 0,field_changeable tinyint default 0,tms TIMESTAMP,PRIMARY KEY(id)); -CREATE TABLE user_field_options (id int NOT NULL auto_increment,field_id int NOT NULL,option_value text,option_display_text varchar(64),option_order int,tms TIMESTAMP,PRIMARY KEY (id)); -CREATE TABLE user_field_values(id int NOT NULL auto_increment,user_id int NOT NULL,field_id int NOT NULL,field_value text,tms TIMESTAMP,PRIMARY KEY(id)); -ALTER TABLE session ADD session_admin_id INT UNSIGNED NOT NULL ; -ALTER TABLE session ADD INDEX ( session_admin_id ) ; -UPDATE course_module SET position='basic' WHERE name='survey'; -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('show_closed_courses',NULL,'radio','Platform','false','ShowClosedCoursesTitle','ShowClosedCoursesComment',NULL,NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_closed_courses', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_closed_courses', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('ldap_main_server_address', NULL, 'textfield', 'LDAP', 'localhost', 'LDAPMainServerAddressTitle', 'LDAPMainServerAddressComment', NULL, NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('ldap_main_server_port', NULL, 'textfield', 'LDAP', '389', 'LDAPMainServerPortTitle', 'LDAPMainServerPortComment', NULL, NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('ldap_domain', NULL, 'textfield', 'LDAP', 'dc=nodomain', 'LDAPDomainTitle', 'LDAPDomainComment', NULL, NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('ldap_replicate_server_address', NULL, 'textfield', 'LDAP', 'localhost', 'LDAPReplicateServerAddressTitle', 'LDAPReplicateServerAddressComment', NULL, NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('ldap_replicate_server_port', NULL, 'textfield', 'LDAP', '389', 'LDAPReplicateServerPortTitle', 'LDAPReplicateServerPortComment', NULL, NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('ldap_search_term', NULL, 'textfield', 'LDAP', '', 'LDAPSearchTermTitle', 'LDAPSearchTermComment', NULL, NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('ldap_version', NULL, 'radio', 'LDAP', '3', 'LDAPVersionTitle', 'LDAPVersionComment', NULL, ''); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('ldap_filled_tutor_field', NULL, 'textfield', 'LDAP', 'employeenumber', 'LDAPFilledTutorFieldTitle', 'LDAPFilledTutorFieldComment', NULL, ''); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('ldap_authentication_login', NULL, 'textfield', 'LDAP', '', 'LDAPAuthenticationLoginTitle', 'LDAPAuthenticationLoginComment', NULL, ''); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('ldap_authentication_password', NULL, 'textfield', 'LDAP', '', 'LDAPAuthenticationPasswordTitle', 'LDAPAuthenticationPasswordComment', NULL, ''); -INSERT INTO settings_options (variable, value, display_text) VALUES ('ldap_version', '2', 'LDAPVersion2'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('ldap_version', '3', 'LDAPVersion3'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('service_visio', 'visio_use_rtmpt', 'radio', null, 'false', 'VisioUseRtmptTitle', 'VisioUseRtmptComment', NULL, ''); -INSERT INTO settings_options (variable, value, display_text) VALUES ('visio_use_rtmpt', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('visio_use_rtmpt', 'false', 'No'); -ALTER TABLE settings_current ADD COLUMN access_url int unsigned not null default 1; -ALTER TABLE settings_current ADD COLUMN access_url_changeable int unsigned not null default 0; -ALTER TABLE settings_current ADD INDEX (access_url); -CREATE TABLE access_url(id int unsigned NOT NULL auto_increment, url varchar(255) NOT NULL default 'http://localhost/', description text, active int unsigned not null default 0, created_by int not null, tms TIMESTAMP, PRIMARY KEY (id)); -INSERT INTO access_url(url,description,active,created_by) VALUES ('http://localhost/','URL 1',1,1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('ldap_filled_tutor_field_value', NULL, 'textfield', 'LDAP', '', 'LDAPFilledTutorFieldValueTitle', 'LDAPFilledTutorFieldValueComment', NULL, ''); - - --- xxSTATSxx -ALTER TABLE track_e_downloads ADD INDEX (down_user_id); -ALTER TABLE track_e_downloads ADD INDEX (down_cours_id); -ALTER TABLE track_e_exercices ADD INDEX (exe_cours_id); -ALTER TABLE track_e_hotpotatoes ADD INDEX (exe_user_id); -ALTER TABLE track_e_hotpotatoes ADD INDEX (exe_cours_id); -ALTER TABLE track_e_lastaccess ADD INDEX (access_session_id); -ALTER TABLE track_e_links ADD INDEX (links_cours_id); -ALTER TABLE track_e_links ADD INDEX (links_user_id); -ALTER TABLE track_e_uploads ADD INDEX (upload_user_id); -ALTER TABLE track_e_uploads ADD INDEX (upload_cours_id); -ALTER TABLE track_e_attempt ADD tms datetime not null default '0000-00-00 00:00:00'; - --- xxUSERxx -CREATE TABLE personal_agenda_repeat (cal_id INT DEFAULT 0 NOT NULL, cal_type VARCHAR(20), cal_end INT, cal_frequency INT DEFAULT 1, cal_days CHAR(7), PRIMARY KEY (cal_id)); -CREATE TABLE personal_agenda_repeat_not (cal_id INT NOT NULL, cal_date INT NOT NULL, PRIMARY KEY ( cal_id, cal_date )); -ALTER TABLE personal_agenda ADD parent_event_id INT NULL; - --- xxCOURSExx -CREATE TABLE lp_iv_objective(id bigint unsigned primary key auto_increment, lp_iv_id bigint unsigned not null, order_id smallint unsigned not null default 0, objective_id varchar(255) not null default '', score_raw float unsigned not null default 0, score_max float unsigned not null default 0, score_min float unsigned not null default 0, status char(32) not null default 'not attempted'); -ALTER TABLE lp_iv_objective ADD INDEX (lp_iv_id); -ALTER TABLE lp_item CHANGE prerequisite prerequisite TEXT DEFAULT NULL; -INSERT INTO course_setting(variable,value,category) VALUES ('email_alert_manager_on_new_quiz',0,'quiz'); -ALTER TABLE dropbox_post ADD session_id SMALLINT UNSIGNED NOT NULL ; -ALTER TABLE dropbox_post ADD INDEX ( session_id ) ; -ALTER TABLE dropbox_file ADD session_id SMALLINT UNSIGNED NOT NULL ; -ALTER TABLE dropbox_file ADD INDEX ( session_id ) ; -ALTER TABLE item_property ADD INDEX idx_item_property_toolref (tool,ref); -ALTER TABLE forum_forum ADD session_id SMALLINT UNSIGNED DEFAULT 0 ; -INSERT INTO course_setting(variable,value,category) VALUES ('allow_user_image_forum',1,'forum'); -INSERT INTO course_setting(variable,value,category) VALUES ('course_theme','','theme'); -INSERT INTO course_setting(variable,value,category) VALUES ('allow_learning_path_theme','1','theme'); -ALTER TABLE forum_post ADD INDEX idx_forum_post_thread_id (thread_id); -ALTER TABLE forum_post ADD INDEX idx_forum_post_visible (visible); -ALTER TABLE forum_thread ADD INDEX idx_forum_thread_forum_id (forum_id); -ALTER TABLE student_publication ADD COLUMN filetype SET('file','folder') NOT NULL DEFAULT 'file' AFTER sent_date; -ALTER TABLE document ADD readonly TINYINT UNSIGNED NOT NULL ; -ALTER TABLE quiz ADD results_disabled TINYINT UNSIGNED NOT NULL DEFAULT 0; -CREATE TABLE blog_attachment ( id int unsigned NOT NULL auto_increment, path varchar(255) NOT NULL COMMENT 'the real filename', comment text, size int NOT NULL default '0', post_id int NOT NULL, filename varchar(255) NOT NULL COMMENT 'the user s file name', blog_id int NOT NULL, comment_id int NOT NULL default '0', PRIMARY KEY (id)); -CREATE TABLE forum_attachment (id int NOT NULL auto_increment, path varchar(255) NOT NULL, comment text, size int NOT NULL default 0, post_id int NOT NULL, filename varchar(255) NOT NULL, PRIMARY KEY (id)); -ALTER TABLE group_category ADD forum_state TINYINT DEFAULT 0 AFTER announcements_state; -UPDATE tool SET category='interaction', admin='0', visibility='0' WHERE name='survey'; -CREATE TABLE forum_notification (user_id int, forum_id varchar(11), thread_id varchar(11), post_id varchar(11), KEY user_id (user_id), KEY forum_id (forum_id)); -ALTER TABLE quiz ADD access_condition text DEFAULT NULL; -ALTER TABLE survey ADD access_condition text DEFAULT NULL; -UPDATE tool SET category='authoring' WHERE name = 'announcement'; -CREATE TABLE calendar_event_repeat (cal_id INT DEFAULT 0 NOT NULL, cal_type VARCHAR(20), cal_end INT, cal_frequency INT DEFAULT 1, cal_days CHAR(7), PRIMARY KEY (cal_id)); -CREATE TABLE calendar_event_repeat_not (cal_id INT NOT NULL, cal_date INT NOT NULL, PRIMARY KEY ( cal_id, cal_date )); -ALTER TABLE calendar_event ADD parent_event_id INT NULL; -ALTER TABLE lp ADD theme varchar(255) not null default ''; \ No newline at end of file diff --git a/main/install/migrate-db-1.8.5-1.8.6-pre.sql b/main/install/migrate-db-1.8.5-1.8.6-pre.sql deleted file mode 100755 index bb99724273..0000000000 --- a/main/install/migrate-db-1.8.5-1.8.6-pre.sql +++ /dev/null @@ -1,231 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.5 to version 1.8.6 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database --- xxMAINxx -ALTER TABLE settings_current ADD UNIQUE unique_setting (variable, subkey, category, access_url); -ALTER TABLE settings_options ADD UNIQUE unique_setting_option (variable,value); -INSERT INTO settings_current (variable, subkey,type,category,selected_value,title,comment,scope,subkeytext)VALUES ('registration', 'phone', 'checkbox', 'User', 'false', 'RegistrationRequiredFormsTitle','RegistrationRequiredFormsComment', NULL, 'Phone'); -ALTER TABLE php_session CHANGE session_value session_value MEDIUMTEXT NOT NULL; -INSERT INTO settings_current (variable, subkey,type,category,selected_value,title,comment,scope,subkeytext)VALUES ('add_users_by_coach',NULL,'radio','Security','false','AddUsersByCoachTitle','AddUsersByCoachComment',NULL,NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('add_users_by_coach', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('add_users_by_coach', 'false', 'No'); -ALTER TABLE session ADD nb_days_access_before_beginning TINYINT NULL DEFAULT '0' AFTER date_end , ADD nb_days_access_after_end TINYINT NULL DEFAULT '0' AFTER nb_days_access_before_beginning ; -ALTER TABLE course_rel_user ADD INDEX (user_id); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable) VALUES ('course_create_active_tools', 'wiki', 'checkbox', 'Tools', 'true', 'CourseCreateActiveToolsTitle', 'CourseCreateActiveToolsComment', NULL, 'Wiki', 1, 0); -INSERT INTO settings_current (variable, subkey,type,category,selected_value,title,comment,scope,subkeytext)VALUES ('extend_rights_for_coach',NULL,'radio','Security','false','ExtendRightsForCoachTitle','ExtendRightsForCoachComment',NULL,NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('extend_rights_for_coach', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('extend_rights_for_coach', 'false', 'No'); -INSERT INTO settings_current (variable, subkey,type,category,selected_value,title,comment,scope,subkeytext)VALUES ('extend_rights_for_coach_on_surveys',NULL,'radio','Security','false','ExtendRightsForCoachOnSurveyTitle','ExtendRightsForCoachOnSurveyComment',NULL,NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('extend_rights_for_coach_on_surveys', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('extend_rights_for_coach_on_surveys', 'false', 'No'); -INSERT INTO settings_current (variable, subkey,type,category,selected_value,title,comment,scope,subkeytext)VALUES ('show_session_coach',NULL,'radio','Platform','false','ShowSessionCoachTitle','ShowSessionCoachComment',NULL,NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_session_coach', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_session_coach', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable) VALUES ('course_create_active_tools','gradebook','checkbox','Tools','true','CourseCreateActiveToolsTitle','CourseCreateActiveToolsComment',NULL,'Gradebook',1,0); -INSERT INTO course_module (name, link, image, `row`, `column`, position) VALUES ('wiki','wiki/index.php','wiki.gif',2,3,'basic'); -INSERT INTO course_module (name, link, image, `row`, `column`, position) VALUES ('gradebook','gradebook/index.php','gradebook.gif',2,2,'basic'); -ALTER TABLE gradebook_category ADD session_id int DEFAULT NULL; -CREATE TABLE gradebook_result_log (id int NOT NULL auto_increment,id_result int NOT NULL,user_id int NOT NULL,evaluation_id int NOT NULL,date_log datetime default '0000-00-00 00:00:00',score float unsigned default NULL,PRIMARY KEY(id)); -CREATE TABLE gradebook_linkeval_log (id int NOT NULL auto_increment,id_linkeval_log int NOT NULL,name text,description text,date_log int,weight smallint default NULL,visible tinyint default NULL,type varchar(20) NOT NULL,user_id_log int NOT NULL,PRIMARY KEY (id)); -INSERT INTO course_module (name, link, image, `row`, `column`, position) VALUES ('glossary','glossary/index.php','glossary.gif',2,1,'basic'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable) VALUES ('course_create_active_tools','glossary','checkbox','Tools','true','CourseCreateActiveToolsTitle','CourseCreateActiveToolsComment',NULL,'Glossary',1,0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable) VALUES ('course_create_active_tools','notebook','checkbox','Tools','true','CourseCreateActiveToolsTitle','CourseCreateActiveToolsComment',NULL,'Notebook',1,0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable) VALUES ('allow_users_to_create_courses',NULL,'radio','Course','true','AllowUsersToCreateCoursesTitle','AllowUsersToCreateCoursesComment',NULL,NULL,1,0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_users_to_create_courses','true','Yes'),('allow_users_to_create_courses','false','No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable) VALUES ('course_create_active_tools','survey','checkbox','Tools','true','CourseCreateActiveToolsTitle','CourseCreateActiveToolsComment',NULL,'Survey',1,0); -ALTER TABLE user_field_values CHANGE user_id user_id int unsigned not null; -UPDATE settings_options SET display_text = 'YesWillDeletePermanently' WHERE variable = 'permanently_remove_deleted_files' and value = 'true'; -UPDATE settings_options SET display_text = 'NoWillDeletePermanently' WHERE variable = 'permanently_remove_deleted_files' and value = 'false'; -INSERT INTO settings_options (variable, value, display_text) VALUES ('breadcrumbs_course_homepage','session_name_and_course_title','SessionNameAndCourseTitle'); -INSERT INTO course_module (name, link, image, `row`, `column`, position) VALUES ('notebook','notebook/index.php','notebook.gif',2,1,'basic'); -CREATE TABLE sys_calendar ( id int unsigned NOT NULL auto_increment, title varchar(200) NOT NULL, content text, start_date datetime NOT NULL default '0000-00-00 00:00:00', end_date datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (id)); -CREATE TABLE IF NOT EXISTS system_template (id int UNSIGNED NOT NULL auto_increment, title varchar(250) NOT NULL, comment text NOT NULL, image varchar(250) NOT NULL, content text NOT NULL, PRIMARY KEY (id)); -CREATE TABLE reservation_category (id int unsigned NOT NULL auto_increment, parent_id int NOT NULL default 0, name varchar(128) NOT NULL default '', PRIMARY KEY ( id )); -CREATE TABLE reservation_category_rights (category_id int NOT NULL default 0, class_id int NOT NULL default 0, m_items tinyint NOT NULL default 0); -CREATE TABLE reservation_item (id int unsigned NOT NULL auto_increment, category_id int unsigned NOT NULL default 0, course_code varchar(40) NOT NULL default '', name varchar(128) NOT NULL default '', description text NOT NULL, blackout tinyint NOT NULL default 0, creator int unsigned NOT NULL default 0, PRIMARY KEY ( id )); -CREATE TABLE reservation_item_rights (item_id int unsigned NOT NULL default 0, class_id int unsigned NOT NULL default 0, edit_right tinyint unsigned NOT NULL default 0, delete_right tinyint unsigned NOT NULL default 0, m_reservation tinyint unsigned NOT NULL default 0, view_right tinyint NOT NULL default 0, PRIMARY KEY ( item_id , class_id )); -CREATE TABLE reservation_main (id int unsigned NOT NULL auto_increment, subid int unsigned NOT NULL default 0, item_id int unsigned NOT NULL default 0, auto_accept tinyint unsigned NOT NULL default 0, max_users int unsigned NOT NULL default 1, start_at datetime NOT NULL default '0000-00-00 00:00:00', end_at datetime NOT NULL default '0000-00-00 00:00:00', subscribe_from datetime NOT NULL default '0000-00-00 00:00:00', subscribe_until datetime NOT NULL default '0000-00-00 00:00:00', subscribers int unsigned NOT NULL default 0, notes text NOT NULL, timepicker tinyint NOT NULL default 0, timepicker_min int NOT NULL default 0, timepicker_max int NOT NULL default 0, PRIMARY KEY ( id )); -CREATE TABLE reservation_subscription (dummy int unsigned NOT NULL auto_increment, user_id int unsigned NOT NULL default 0, reservation_id int unsigned NOT NULL default 0, accepted tinyint unsigned NOT NULL default 0, start_at datetime NOT NULL default '0000-00-00 00:00:00', end_at datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY ( dummy )); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('allow_reservation', NULL, 'radio', 'Tools', 'false', 'AllowReservationTitle', 'AllowReservationComment', NULL, NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_reservation', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_reservation', 'false', 'No'); -CREATE TABLE access_url_rel_user (access_url_id int unsigned NOT NULL, user_id int unsigned NOT NULL, PRIMARY KEY (access_url_id, user_id)); -ALTER TABLE access_url_rel_user ADD INDEX idx_access_url_rel_user_user (user_id); -ALTER TABLE access_url_rel_user ADD INDEX idx_access_url_rel_user_access_url(access_url_id); -ALTER TABLE access_url_rel_user ADD INDEX idx_access_url_rel_user_access_url_user (user_id,access_url_id); -CREATE TABLE access_url_rel_course (access_url_id int unsigned NOT NULL, course_code char(40) NOT NULL, PRIMARY KEY (access_url_id, course_code)); -CREATE TABLE access_url_rel_session (access_url_id int unsigned NOT NULL, session_id int unsigned NOT NULL, PRIMARY KEY (access_url_id, session_id)); - -CREATE TABLE user_friend(id bigint unsigned not null auto_increment,user_id int unsigned not null,friend_user_id int unsigned not null,relation_type int not null default 0,PRIMARY KEY(id)); -ALTER TABLE user_friend ADD INDEX idx_user_friend_user(user_id); -ALTER TABLE user_friend ADD INDEX idx_user_friend_friend_user(friend_user_id); -ALTER TABLE user_friend ADD INDEX idx_user_friend_user_friend_user(user_id,friend_user_id); -CREATE TABLE user_friend_relation_type(id int unsigned not null auto_increment,title char(20),PRIMARY KEY(id)); -CREATE TABLE user_api_key (id int unsigned NOT NULL auto_increment, user_id int unsigned NOT NULL, api_key char(32) NOT NULL, api_service char(10) NOT NULL default 'dokeos', PRIMARY KEY (id)); -ALTER TABLE user_api_key ADD INDEX idx_user_api_keys_user (user_id); -CREATE TABLE message (id bigint unsigned not null auto_increment, user_sender_id int unsigned not null, user_receiver_id int unsigned not null, msg_status tinyint unsigned not null default 0, send_date datetime not null default '0000-00-00 00:00:00', title varchar(255) not null, content text not null, PRIMARY KEY(id)); -ALTER TABLE message ADD INDEX idx_message_user_sender(user_sender_id); -ALTER TABLE message ADD INDEX idx_message_user_receiver(user_receiver_id); -ALTER TABLE message ADD INDEX idx_message_user_sender_user_receiver(user_sender_id,user_receiver_id); -ALTER TABLE message ADD INDEX idx_message_msg_status(msg_status); -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='Institution'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='InstitutionUrl'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='siteName'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='emailAdministrator'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='administratorSurname'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='administratorName'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='show_administrator_data'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='stylesheets'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='show_tabs' AND subkey='campus_homepage'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='show_tabs' AND subkey='my_courses'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='show_tabs' AND subkey='reporting'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='show_tabs' AND subkey='platform_administration'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='show_tabs' AND subkey='my_agenda'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='show_tabs' AND subkey='my_profile'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='show_tabs' AND subkey='my_gradebook'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='administratorTelephone'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='show_email_addresses'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='show_different_course_language'; -UPDATE settings_current SET access_url_changeable = 1 WHERE variable='display_categories_on_homepage'; -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('advanced_filemanager',NULL,'radio','Platform','false','AdvancedFileManagerTitle','AdvancedFileManagerComment',NULL,NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('advanced_filemanager','true','Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('advanced_filemanager','false','No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_message_tool', NULL, 'radio', 'Tools', 'false', 'AllowMessageToolTitle', 'AllowMessageToolComment', NULL, NULL,0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_message_tool', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_message_tool', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_social_tool', NULL, 'radio', 'Tools', 'false', 'AllowSocialToolTitle', 'AllowSocialToolComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_social_tool', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_social_tool', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_students_to_browse_courses', NULL, 'radio', 'Platform', 'true', 'AllowStudentsToBrowseCoursesTitle', 'AllowStudentsToBrowseCoursesComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_students_to_browse_courses', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_students_to_browse_courses', 'false', 'No'); -ALTER TABLE user_field ADD field_filter tinyint default 0; -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('profile','apikeys','checkbox','User','false','ProfileChangesTitle','ProfileChangesComment',NULL,'ApiKeys', 0); -INSERT INTO user_friend_relation_type(id,title)VALUES(1,'SocialUnknow'); -INSERT INTO user_friend_relation_type(id,title)VALUES(2,'SocialParent'); -INSERT INTO user_friend_relation_type(id,title)VALUES(3,'SocialFriend'); -INSERT INTO user_friend_relation_type(id,title)VALUES(4,'SocialGoodFriend'); -INSERT INTO user_friend_relation_type(id,title)VALUES(5,'SocialEnemy'); -INSERT INTO user_friend_relation_type(id,title)VALUES(6,'SocialDeleted'); -CREATE TABLE course_field (id int NOT NULL auto_increment, field_type int NOT NULL DEFAULT 1, field_variable varchar(64) NOT NULL, field_display_text varchar(64), field_default_value text, field_order int, field_visible tinyint default 0, field_changeable tinyint default 0, field_filter tinyint default 0, tms TIMESTAMP, PRIMARY KEY(id)); -CREATE TABLE course_field_values (id int NOT NULL auto_increment, course_code varchar(40) NOT NULL, field_id int NOT NULL, field_value text, tms TIMESTAMP, PRIMARY KEY(id)); -CREATE TABLE session_field (id int NOT NULL auto_increment, field_type int NOT NULL DEFAULT 1, field_variable varchar(64) NOT NULL, field_display_text varchar(64), field_default_value text, field_order int, field_visible tinyint default 0, field_changeable tinyint default 0, field_filter tinyint default 0, tms TIMESTAMP, PRIMARY KEY(id)); -CREATE TABLE session_field_values(id int NOT NULL auto_increment, session_id int NOT NULL, field_id int NOT NULL, field_value text, tms TIMESTAMP, PRIMARY KEY(id)); -ALTER TABLE templates ADD image VARCHAR( 250 ) NOT NULL ; -INSERT IGNORE INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable) VALUES ('dokeos_database_version',NULL,'textfield',NULL,'1.8.6.20515','DokeosDatabaseVersion','',NULL,NULL,1,0); - --- xxSTATSxx -ALTER TABLE track_e_exercices ADD status varchar(20) NOT NULL default ''; -ALTER TABLE track_e_exercices ADD data_tracking text NOT NULL default ''; -ALTER TABLE track_e_exercices ADD steps_counter SMALLINT UNSIGNED NOT NULL default 0; -ALTER TABLE track_e_exercices ADD start_date datetime NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE track_e_exercices ADD session_id SMALLINT UNSIGNED NOT NULL default 0; -ALTER TABLE track_e_exercices ADD INDEX ( session_id ) ; -CREATE TABLE track_e_attempt_recording (exe_id int unsigned NOT NULL, question_id int unsigned NOT NULL, marks int NOT NULL, insert_date datetime NOT NULL default '0000-00-00 00:00:00', author int unsigned NOT NULL, teacher_comment text NOT NULL); -ALTER TABLE track_e_attempt_recording ADD INDEX (exe_id); -ALTER TABLE track_e_hotspot CHANGE hotspot_coordinate hotspot_coordinate text NOT NULL; -ALTER TABLE track_e_exercices ADD orig_lp_id int NOT NULL default 0; -ALTER TABLE track_e_exercices ADD orig_lp_item_id int NOT NULL default 0; -ALTER TABLE track_e_exercices ADD exe_duration int UNSIGNED NOT NULL default 0; -ALTER TABLE track_e_exercices CHANGE exe_result exe_result FLOAT( 6, 2 ) NOT NULL DEFAULT 0; -ALTER TABLE track_e_exercices CHANGE exe_weighting exe_weighting FLOAT( 6, 2 ) NOT NULL DEFAULT 0; -ALTER TABLE track_e_attempt CHANGE marks marks FLOAT( 6, 2 ) NOT NULL DEFAULT 0; --- xxUSERxx - --- xxCOURSExx -ALTER TABLE course_setting ADD INDEX unique_setting (variable,subkey,category); -ALTER TABLE survey ADD mail_subject VARCHAR( 255 ) NOT NULL AFTER reminder_mail ; -ALTER TABLE quiz_rel_question ADD question_order mediumint unsigned NOT NULL default 1; -ALTER TABLE quiz ADD max_attempt int NOT NULL default 0; -ALTER TABLE survey ADD one_question_per_page bool NOT NULL default 0; -ALTER TABLE survey ADD shuffle bool NOT NULL default 0; -ALTER TABLE survey ADD survey_version varchar(255) NOT NULL default ''; -ALTER TABLE survey ADD parent_id int NOT NULL default 0; -ALTER TABLE survey ADD survey_type int NOT NULL default 0; -ALTER TABLE survey_question ADD survey_group_pri int unsigned NOT NULL default 0; -ALTER TABLE survey_question ADD survey_group_sec1 int unsigned NOT NULL default 0; -ALTER TABLE survey_question ADD survey_group_sec2 int unsigned NOT NULL default 0; -CREATE TABLE survey_group ( id int unsigned NOT NULL auto_increment, name varchar(20) NOT NULL, description varchar(255) NOT NULL, survey_id int unsigned NOT NULL, PRIMARY KEY (id) ); -ALTER TABLE survey_question_option ADD value int NOT NULL default 0; -UPDATE tool SET category = 'interaction' WHERE name = 'forum'; -ALTER TABLE survey ADD show_form_profile int NOT NULL default 0; -ALTER TABLE survey ADD form_fields TEXT NOT NULL; -ALTER TABLE quiz_answer CHANGE hotspot_type hotspot_type ENUM( 'square', 'circle', 'poly', 'delineation' ) NULL DEFAULT NULL; -ALTER TABLE quiz ADD start_time datetime NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE quiz ADD end_time datetime NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE forum_forum ADD forum_image varchar(255) NOT NULL default ''; -ALTER TABLE lp ADD preview_image varchar(255) NOT NULL default ''; -ALTER TABLE lp ADD author varchar(255) NOT NULL default ''; -ALTER TABLE lp_item ADD terms TEXT NULL; -ALTER TABLE lp_item ADD search_did INT NULL; -CREATE TABLE wiki (id int NOT NULL auto_increment, page_id int NOT NULL default 0, reflink varchar(250) NOT NULL default 'index', title text NOT NULL, content mediumtext NOT NULL, user_id int NOT NULL default 0, group_id int default NULL, dtime datetime NOT NULL default '0000-00-00 00:00:00', addlock int NOT NULL default 1, editlock int NOT NULL default 0, visibility int NOT NULL default 1, addlock_disc int NOT NULL default 1, visibility_disc int NOT NULL default 1, ratinglock_disc int NOT NULL default 1, assignment int NOT NULL default 0, comment text NOT NULL, progress text NOT NULL, score int default 0, version int default NULL, is_editing int NOT NULL default 0, hits int default 0, linksto text NOT NULL, tag text NOT NULL, user_ip varchar(39) NOT NULL, PRIMARY KEY (id) ); -INSERT INTO tool(name,link,image,visibility,admin,address,added_tool,target,category) VALUES ('wiki','wiki/index.php','wiki.gif',0,'0','squaregrey.gif',0,'_self','interaction'); -ALTER TABLE group_category ADD COLUMN wiki_state tinyint unsigned NOT NULL default 1; -ALTER TABLE group_info ADD COLUMN wiki_state tinyint unsigned NOT NULL default 1; -ALTER TABLE announcement ADD session_id SMALLINT UNSIGNED NOT NULL default 0; -ALTER TABLE announcement ADD INDEX ( session_id ) ; -ALTER TABLE forum_category ADD session_id SMALLINT UNSIGNED NOT NULL default 0; -ALTER TABLE forum_category ADD INDEX ( session_id ) ; -ALTER TABLE student_publication ADD session_id SMALLINT UNSIGNED NOT NULL default 0 ; -ALTER TABLE student_publication ADD INDEX ( session_id ) ; -ALTER TABLE calendar_event ADD session_id int unsigned NOT NULL default 0 ; -ALTER TABLE calendar_event ADD INDEX ( session_id ) ; -ALTER TABLE group_info ADD session_id SMALLINT UNSIGNED NOT NULL DEFAULT 0; -ALTER TABLE group_info ADD INDEX ( session_id ) ; -ALTER TABLE survey ADD session_id SMALLINT UNSIGNED NOT NULL DEFAULT 0; -ALTER TABLE survey ADD INDEX ( session_id ) ; -CREATE TABLE wiki_discuss (id int NOT NULL auto_increment, publication_id int NOT NULL default 0, userc_id int NOT NULL default 0, comment text NOT NULL, p_score varchar(255) default NULL, dtime datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (id) ); -CREATE TABLE wiki_mailcue (id int NOT NULL, user_id int NOT NULL, type text NOT NULL, group_id int DEFAULT NULL, KEY (id) ); -ALTER TABLE lp_item ADD audio VARCHAR(250); -CREATE TABLE wiki_conf (id int NOT NULL auto_increment, page_id int NOT NULL default 0, feedback1 text NOT NULL, feedback2 text NOT NULL, feedback3 text NOT NULL, max_size int default NULL, max_text int default NULL, max_version int default NULL, startdate_assig datetime NOT NULL default '0000-00-00 00:00:00', enddate_assig datetime NOT NULL default '0000-00-00 00:00:00', delayedsubmit int NOT NULL default 0, PRIMARY KEY (id) ); -CREATE TABLE student_publication_assignment (id int NOT NULL auto_increment, expires_on datetime NOT NULL default '0000-00-00 00:00:00', ends_on datetime NOT NULL default '0000-00-00 00:00:00', add_to_calendar tinyint NOT NULL, enable_qualification tinyint NOT NULL, publication_id int NOT NULL, PRIMARY KEY (id)); -ALTER TABLE student_publication ADD has_properties INT UNSIGNED NOT NULL DEFAULT 0; -ALTER TABLE student_publication ADD qualification float(6,2) UNSIGNED NOT NULL DEFAULT 0; -ALTER TABLE student_publication ADD date_of_qualification datetime NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE student_publication ADD parent_id INT UNSIGNED NOT NULL DEFAULT 0; -ALTER TABLE student_publication ADD qualificator_id INT UNSIGNED NOT NULL DEFAULT 0; -CREATE TABLE forum_thread_qualify (id int unsigned PRIMARY KEY AUTO_INCREMENT, user_id int unsigned NOT NULL,thread_id int NOT NULL,qualify float(6,2) NOT NULL default 0,qualify_user_id int default NULL,qualify_time datetime NOT NULL default '0000-00-00 00:00:00', session_id int default NULL); -ALTER TABLE forum_thread_qualify ADD INDEX (user_id, thread_id); -ALTER TABLE forum_thread ADD session_id int unsigned default NULL; -ALTER TABLE forum_thread ADD thread_title_qualify varchar(255) default ''; -ALTER TABLE forum_thread ADD thread_qualify_max float(6,2) UNSIGNED NOT NULL DEFAULT 0; -CREATE TABLE forum_thread_qualify_log (id int unsigned PRIMARY KEY AUTO_INCREMENT, user_id int unsigned NOT NULL,thread_id int NOT NULL,qualify float(6,2) NOT NULL default 0,qualify_user_id int default NULL,qualify_time datetime NOT NULL default '0000-00-00 00:00:00', session_id int default NULL); -ALTER TABLE forum_thread_qualify_log ADD INDEX (user_id, thread_id); -INSERT INTO tool(name,link,image,visibility,admin,address,added_tool,target,category) VALUES ('gradebook','gradebook/index.php','gradebook.gif',1,'0','squaregrey.gif',0,'_self','authoring'); -ALTER TABLE forum_thread ADD thread_close_date datetime default '0000-00-00 00:00:00'; -ALTER TABLE student_publication ADD view_properties tinyint NULL; -UPDATE forum_notification SET forum_id=NULL WHERE forum_id=''; -ALTER TABLE forum_notification CHANGE forum_id forum_id INT; -UPDATE forum_notification SET thread_id=NULL WHERE thread_id=''; -ALTER TABLE forum_notification CHANGE thread_id thread_id INT; -UPDATE forum_notification SET post_id=NULL WHERE post_id=''; -ALTER TABLE forum_notification CHANGE post_id post_id INT NULL; -ALTER TABLE forum_thread ADD thread_weight float(6,2) UNSIGNED NOT NULL DEFAULT 0; -ALTER TABLE forum_notification CHANGE post_id post_id INT; -ALTER TABLE quiz_answer CHANGE hotspot_coordinates hotspot_coordinates text; -ALTER TABLE group_info ADD forum_state TINYINT unsigned NOT NULL default 0 AFTER announcements_state; -CREATE TABLE calendar_event_attachment ( id int NOT NULL auto_increment, path varchar(255) NOT NULL, comment text, size int NOT NULL default 0, agenda_id int NOT NULL, filename varchar(255) NOT NULL, PRIMARY KEY (id) ); -CREATE TABLE notebook (notebook_id int unsigned NOT NULL auto_increment,user_id int unsigned NOT NULL,course varchar(40) not null,session_id int NOT NULL default 0,title varchar(255) NOT NULL,description text NOT NULL,creation_date datetime NOT NULL default '0000-00-00 00:00:00',update_date datetime NOT NULL default '0000-00-00 00:00:00', status int, PRIMARY KEY (notebook_id)); -INSERT INTO course_setting(variable,value,category) VALUES ('allow_open_chat_window',0,'chat'); -INSERT INTO course_setting(variable,value,category) VALUES ('email_alert_to_teacher_on_new_user_in_course',0,'registration'); -INSERT INTO tool(name,link,image,visibility,admin,address,added_tool,target,category) VALUES ('glossary','glossary/index.php','glossary.gif',0,'0','squaregrey.gif',0,'_self','authoring'); -INSERT INTO tool(name,link,image,visibility,admin,address,added_tool,target,category) VALUES ('notebook','notebook/index.php','notebook.gif',0,'0','squaregrey.gif',0,'_self','interaction'); -ALTER TABLE quiz ADD feedback_type int NOT NULL default 0; -ALTER TABLE quiz_answer ADD destination text NOT NULL; -CREATE TABLE glossary(glossary_id int unsigned NOT NULL auto_increment, name varchar(255) NOT NULL, description text not null, display_order int, PRIMARY KEY (glossary_id)); -ALTER TABLE quiz_question ADD level int UNSIGNED NOT NULL default 0; -ALTER TABLE survey_invitation ADD COLUMN session_id SMALLINT(5) UNSIGNED NOT NULL DEFAULT 0; -ALTER TABLE quiz_answer CHANGE ponderation ponderation float(6,2) NOT NULL DEFAULT 0; -ALTER TABLE quiz_question CHANGE ponderation ponderation float(6,2) NOT NULL DEFAULT 0; -ALTER TABLE lp ADD session_id int unsigned not null default 0; -ALTER TABLE document ADD session_id int unsigned not null default 0; \ No newline at end of file diff --git a/main/install/migrate-db-1.8.6-1.8.6.1-pre.sql b/main/install/migrate-db-1.8.6-1.8.6.1-pre.sql deleted file mode 100755 index 24dfb9b440..0000000000 --- a/main/install/migrate-db-1.8.6-1.8.6.1-pre.sql +++ /dev/null @@ -1,65 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.6 to version 1.8.6.1 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database --- xxMAINxx -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_use_sub_language', NULL, 'radio', 'Platform', 'false', 'AllowUseSubLanguageTitle', 'AllowUseSubLanguageComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_use_sub_language', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_use_sub_language', 'false', 'No'); -ALTER TABLE language ADD COLUMN parent_id tinyint unsigned; -ALTER TABLE language ADD INDEX idx_dokeos_folder(dokeos_folder); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_glossary_in_documents', NULL, 'radio', 'Course', 'none', 'ShowGlossaryInDocumentsTitle', 'ShowGlossaryInDocumentsComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_glossary_in_documents', 'none', 'ShowGlossaryInDocumentsIsNone'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_glossary_in_documents', 'ismanual', 'ShowGlossaryInDocumentsIsManual'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_glossary_in_documents', 'isautomatic', 'ShowGlossaryInDocumentsIsAutomatic'); -CREATE TABLE legal (legal_id int NOT NULL auto_increment, language_id int NOT NULL, date int NOT NULL default 0, content text, type int NOT NULL, changes text NOT NULL, version int, PRIMARY KEY (legal_id)); -INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) values (1, 'legal_accept','Legal',0,0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_terms_conditions', NULL, 'radio', 'Platform', 'false', 'AllowTermsAndConditionsTitle', 'AllowTermsAndConditionsComment', NULL, NULL,0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_terms_conditions', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_terms_conditions', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_tutor_data',NULL,'radio','Platform','true','ShowTutorDataTitle','ShowTutorDataComment',NULL,NULL, 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_teacher_data',NULL,'radio','Platform','true','ShowTeacherDataTitle','ShowTeacherDataComment',NULL,NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_tutor_data','true','Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_tutor_data','false','No'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_teacher_data','true','Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_teacher_data','false','No'); -ALTER TABLE user_friend ADD COLUMN last_edit DATETIME; -ALTER TABLE reservation_item ADD always_available TINYINT NOT NULL default 0; -CREATE TABLE gradebook_certificate( id bigint unsigned not null auto_increment, cat_id int unsigned not null, user_id int unsigned not null, score_certificate float unsigned not null default 0, date_certificate datetime not null default '0000-00-00 00:00:00', path_certificate text null, PRIMARY KEY(id)); -ALTER TABLE gradebook_certificate ADD INDEX idx_gradebook_certificate_category_id(cat_id); -ALTER TABLE gradebook_certificate ADD INDEX idx_gradebook_certificate_user_id(user_id); -ALTER TABLE gradebook_certificate ADD INDEX idx_gradebook_certificate_category_id_user_id(cat_id,user_id); -ALTER TABLE gradebook_category ADD COLUMN document_id int unsigned default NULL; - -CREATE TABLE specific_field (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, code char(1) NOT NULL, name VARCHAR( 200 ) NOT NULL); -CREATE TABLE specific_field_values (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, course_code VARCHAR( 40 ) NOT NULL, tool_id VARCHAR( 100 ) NOT NULL, ref_id INT NOT NULL, field_id INT NOT NULL, value VARCHAR( 200 ) NOT NULL); -ALTER TABLE specific_field ADD CONSTRAINT unique_specific_field__code UNIQUE (code); -CREATE TABLE search_engine_ref (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, course_code VARCHAR( 40 ) NOT NULL, tool_id VARCHAR( 100 ) NOT NULL, ref_id_high_level INT NOT NULL, ref_id_second_level INT NULL, search_did INT NOT NULL); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('search_enabled',NULL,'radio','Tools','false','EnableSearchTitle','EnableSearchComment',NULL,NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('search_prefilter_prefix',NULL, NULL,'Search','','SearchPrefilterPrefix','SearchPrefilterPrefixComment',NULL,NULL); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('search_show_unlinked_results',NULL,'radio','Search','true','SearchShowUnlinkedResultsTitle','SearchShowUnlinkedResultsComment',NULL,NULL); -INSERT INTO settings_options (variable, value, display_text) VALUES ('search_enabled', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('search_enabled', 'false', 'No'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('search_show_unlinked_results', 'true', 'SearchShowUnlinkedResults'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('search_show_unlinked_results', 'false', 'SearchHideUnlinkedResults'); -ALTER TABLE gradebook_evaluation ADD COLUMN type varchar(40) NOT NULL default 'evaluation'; -INSERT IGNORE INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable) VALUES ('dokeos_database_version',NULL,'textfield',NULL,'1.8.6.1.8225','DokeosDatabaseVersion','',NULL,NULL,1,0); - --- xxSTATSxx - --- xxUSERxx - --- xxCOURSExx -ALTER TABLE wiki CHANGE title title varchar(255), CHANGE reflink reflink varchar(255), ADD time_edit datetime NOT NULL default '0000-00-00 00:00:00' AFTER is_editing, ADD INDEX (title), ADD INDEX (reflink), ADD INDEX (group_id), ADD INDEX (page_id); -ALTER TABLE wiki_conf DROP id, ADD task text NOT NULL AFTER page_id, ADD fprogress3 varchar(3) NOT NULL AFTER feedback3, ADD fprogress2 varchar(3) NOT NULL AFTER feedback3, ADD fprogress1 varchar(3) NOT NULL AFTER feedback3, ADD INDEX(page_id); -ALTER TABLE link ADD COLUMN target char(10) DEFAULT '_self'; diff --git a/main/install/migrate-db-1.8.6.1-1.8.6.2-post.sql b/main/install/migrate-db-1.8.6.1-1.8.6.2-post.sql deleted file mode 100755 index 5e0c83ebd7..0000000000 --- a/main/install/migrate-db-1.8.6.1-1.8.6.2-post.sql +++ /dev/null @@ -1,21 +0,0 @@ --- This script updates the databases structure after migrating the data from --- version 1.8.6.1 to version 1.8.6.2 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database --- xxMAINxx -ALTER TABLE session_rel_course DROP COLUMN id_coach; - --- xxSTATSxx - --- xxUSERxx - --- xxCOURSExx diff --git a/main/install/migrate-db-1.8.6.1-1.8.6.2-pre.sql b/main/install/migrate-db-1.8.6.1-1.8.6.2-pre.sql deleted file mode 100755 index 3b1743d009..0000000000 --- a/main/install/migrate-db-1.8.6.1-1.8.6.2-pre.sql +++ /dev/null @@ -1,149 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.6.1 to version 1.8.6.2 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database --- xxMAINxx -ALTER TABLE session ADD COLUMN visibility int NOT NULL default 1; -ALTER TABLE session ADD COLUMN session_category_id INT NOT NULL; - -ALTER TABLE session_rel_course_rel_user ADD COLUMN visibility int NOT NULL default 1; -ALTER TABLE session_rel_course_rel_user ADD COLUMN status int NOT NULL default 0; -CREATE TABLE session_category (id int NOT NULL auto_increment, name varchar(100) default NULL, date_start date default NULL, date_end date default NULL, PRIMARY KEY (id)); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_coach_to_edit_course_session', NULL, 'radio', 'Course', 'false', 'AllowCoachsToEditInsideTrainingSessions', 'AllowCoachsToEditInsideTrainingSessionsComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable) VALUES ('show_courses_descriptions_in_catalog', NULL, 'radio', 'Course', 'true', 'ShowCoursesDescriptionsInCatalogTitle', 'ShowCoursesDescriptionsInCatalogComment', NULL, NULL, 1, 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable) VALUES ('show_glossary_in_extra_tools', NULL, 'radio', 'Course', 'false', 'ShowGlossaryInExtraToolsTitle', 'ShowGlossaryInExtraToolsComment', NULL, NULL,1,0); - -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_courses_descriptions_in_catalog', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_courses_descriptions_in_catalog', 'false', 'No'); - -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_coach_to_edit_course_session', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_coach_to_edit_course_session', 'false', 'No'); - -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_glossary_in_extra_tools', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_glossary_in_extra_tools', 'false', 'No'); - -CREATE TABLE tag (id int NOT NULL auto_increment, tag varchar(255) NOT NULL, field_id int NOT NULL, count int NOT NULL, PRIMARY KEY (id)); -CREATE TABLE user_rel_tag (id int NOT NULL auto_increment,user_id int NOT NULL,tag_id int NOT NULL, PRIMARY KEY (id)); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('send_email_to_admin_when_create_course',NULL,'radio','Platform','false','SendEmailToAdminTitle','SendEmailToAdminComment',NULL,NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('send_email_to_admin_when_create_course','true','Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('send_email_to_admin_when_create_course','false','No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('go_to_course_after_login', NULL, 'radio', 'Course', 'false', 'GoToCourseAfterLoginTitle', 'GoToCourseAfterLoginComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('go_to_course_after_login', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('go_to_course_after_login', 'false', 'No'); - -CREATE TABLE message_attachment (id int NOT NULL AUTO_INCREMENT, path varchar(255) NOT NULL, comment text, size int NOT NULL default 0, message_id int NOT NULL, filename varchar(255) NOT NULL, PRIMARY KEY(id)); - -CREATE TABLE groups (id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, description varchar(255) NOT NULL, picture_uri varchar(255) NOT NULL, url varchar(255) NOT NULL, visibility int NOT NULL, updated_on varchar(255) NOT NULL, created_on varchar(255) NOT NULL, PRIMARY KEY (id)); -CREATE TABLE group_rel_tag (id int NOT NULL AUTO_INCREMENT, tag_id int NOT NULL, group_id int NOT NULL, PRIMARY KEY (id)); -CREATE TABLE group_rel_user (id int NOT NULL AUTO_INCREMENT, group_id int NOT NULL, user_id int NOT NULL, relation_type int NOT NULL, PRIMARY KEY (id)); - -ALTER TABLE message ADD COLUMN group_id INT NOT NULL DEFAULT 0; -ALTER TABLE message ADD COLUMN parent_id INT NOT NULL DEFAULT 0; -ALTER TABLE message ADD INDEX idx_message_group(group_id); -ALTER TABLE message ADD INDEX idx_message_parent(parent_id); - -INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) values (1, 'rssfeeds','RSS',0,0); -INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) values (10,'tags','tags',0,0); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_tabs', 'social', 'checkbox', 'Platform', 'true', 'ShowTabsTitle','ShowTabsComment',NULL,'TabsSocial', 0); - -UPDATE settings_current SET selected_value = '1.8.6.2.9928' WHERE variable = 'dokeos_database_version'; - -INSERT INTO course_field (field_type, field_variable, field_display_text, field_default_value, field_visible, field_changeable) values (10, 'special_course','SpecialCourse', 'Yes', 1 , 1); - -ALTER TABLE group_rel_user ADD INDEX ( group_id ); -ALTER TABLE group_rel_user ADD INDEX ( user_id ); -ALTER TABLE group_rel_user ADD INDEX ( relation_type ); -ALTER TABLE group_rel_tag ADD INDEX ( group_id ); -ALTER TABLE group_rel_tag ADD INDEX ( tag_id ); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_students_to_create_groups_in_social', NULL, 'radio', 'Tools', 'false', 'AllowStudentsToCreateGroupsInSocialTitle', 'AllowStudentsToCreateGroupsInSocialComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_students_to_create_groups_in_social', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_students_to_create_groups_in_social', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_send_message_to_all_platform_users', NULL, 'radio', 'Tools', 'false', 'AllowSendMessageToAllPlatformUsersTitle', 'AllowSendMessageToAllPlatformUsersComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_send_message_to_all_platform_users', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_send_message_to_all_platform_users', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('message_max_upload_filesize', NULL, 'textfield', 'Tools', '20971520', 'MessageMaxUploadFilesizeTitle','MessageMaxUploadFilesizeComment',NULL,NULL, 0); - -ALTER TABLE message ADD COLUMN update_date DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'; - -UPDATE settings_current SET category = 'Languages' WHERE variable = 'hide_dltt_markup'; -UPDATE settings_current SET category = 'Languages' WHERE variable = 'platform_charset'; -UPDATE settings_current SET category = 'Languages' WHERE variable = 'allow_use_sub_language'; - -UPDATE settings_current SET category = 'Editor' WHERE variable = 'wcag_anysurfer_public_pages'; -UPDATE settings_current SET category = 'Editor' WHERE variable = 'advanced_filemanager'; - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('math_mimetex',NULL,'radio','Editor','false','MathMimetexTitle','MathMimetexComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('math_mimetex', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('math_mimetex', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('math_asciimathML',NULL,'radio','Editor','false','MathASCIImathMLTitle','MathASCIImathMLComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('math_asciimathML', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('math_asciimathML', 'false', 'No'); - - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('youtube_for_students',NULL,'radio','Editor','true','YoutubeForStudentsTitle','YoutubeForStudentsComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('youtube_for_students', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('youtube_for_students', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('block_copy_paste_for_students',NULL,'radio','Editor','false','BlockCopyPasteForStudentsTitle','BlockCopyPasteForStudentsComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('block_copy_paste_for_students', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('block_copy_paste_for_students', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('more_buttons_maximized_mode',NULL,'radio','Editor','false','MoreButtonsForMaximizedModeTitle','MoreButtonsForMaximizedModeComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('more_buttons_maximized_mode', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('more_buttons_maximized_mode', 'false', 'No'); - - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('user_order_by', NULL, 'radio', 'User', 'lastname', 'OrderUsersByTitle', 'OrderUsersByComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('user_order_by','firstname','FirstName'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('user_order_by','lastname','LastName'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('read_more_limit', NULL , 'textfield', 'Tools', '100', 'ReadMoreLimitTitle', 'ReadMoreLimitComment', NULL , NULL , '1'); - - --- xxSTATSxx -ALTER TABLE track_e_exercices ADD COLUMN expired_time_control datetime NOT NULL DEFAULT '0000-00-00 00:00:00'; -ALTER TABLE track_e_online ADD INDEX (course); - --- xxUSERxx - --- xxCOURSExx - -CREATE TABLE announcement_attachment ( id int NOT NULL auto_increment, path varchar(255) NOT NULL, comment text, size int NOT NULL default 0, announcement_id int NOT NULL, filename varchar(255) NOT NULL, PRIMARY KEY (id) ); -ALTER TABLE quiz ADD COLUMN session_id smallint DEFAULT 0, ADD INDEX (session_id); -ALTER TABLE blog ADD COLUMN session_id smallint DEFAULT 0, ADD INDEX (session_id); -ALTER TABLE course_description ADD COLUMN session_id smallint DEFAULT 0, ADD INDEX (session_id); -ALTER TABLE glossary ADD COLUMN session_id smallint DEFAULT 0, ADD INDEX (session_id); -ALTER TABLE link ADD COLUMN session_id smallint DEFAULT 0, ADD INDEX (session_id); -ALTER TABLE wiki ADD COLUMN session_id smallint DEFAULT 0, ADD INDEX (session_id); -ALTER TABLE tool ADD COLUMN session_id smallint DEFAULT 0, ADD INDEX (session_id); -ALTER TABLE link_category ADD COLUMN session_id smallint DEFAULT 0, ADD INDEX (session_id); -ALTER TABLE item_property ADD id_session INT NOT NULL DEFAULT 0; -ALTER TABLE item_property DROP INDEX idx_item_property_toolref, ADD INDEX idx_item_property_toolref (tool, ref, id_session); -ALTER TABLE quiz ADD COLUMN expired_time int NOT NULL DEFAULT '0' AFTER feedback_type; -ALTER TABLE group_info ADD COLUMN chat_state TINYINT DEFAULT 1, ADD INDEX (chat_state); -ALTER TABLE group_category ADD COLUMN chat_state TINYINT DEFAULT 1, ADD INDEX (chat_state); -ALTER TABLE student_publication ADD COLUMN weight float(6,2) UNSIGNED NOT NULL DEFAULT 0; -ALTER TABLE course_description ADD COLUMN description_type TINYINT NOT NULL DEFAULT 0; -ALTER TABLE dropbox_category ADD COLUMN session_id smallint NOT NULL DEFAULT 0, ADD INDEX (session_id); -ALTER TABLE quiz ADD COLUMN random_answers TINYINT UNSIGNED NOT NULL DEFAULT 0 AFTER random; -ALTER TABLE quiz_answer ADD COLUMN id_auto INT NOT NULL AUTO_INCREMENT, ADD UNIQUE INDEX (id_auto); - -ALTER TABLE chat_connected ADD COLUMN session_id INT NOT NULL default 0; -ALTER TABLE chat_connected ADD COLUMN to_group_id INT NOT NULL default 0; diff --git a/main/install/migrate-db-1.8.6.2-1.8.7-post.sql b/main/install/migrate-db-1.8.6.2-1.8.7-post.sql deleted file mode 100755 index f647ac6785..0000000000 --- a/main/install/migrate-db-1.8.6.2-1.8.7-post.sql +++ /dev/null @@ -1,38 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.6.2 to version 1.8.7 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database - --- xxMAINxx -ALTER TABLE course_module CHANGE name name varchar(255) NOT NULL; -ALTER TABLE sys_calendar CHANGE title title varchar(255) NOT NULL; -ALTER TABLE tag CHANGE tag tag varchar(255) NOT NULL; - --- xxSTATSxx - --- xxUSERxx - --- xxCOURSExx -ALTER TABLE quiz CHANGE title title VARCHAR(255) NOT NULL; -ALTER TABLE quiz CHANGE sound sound VARCHAR(255) DEFAULT NULL; -ALTER TABLE quiz_question CHANGE question question VARCHAR(511) NOT NULL; -ALTER TABLE tool CHANGE name name VARCHAR(255) NOT NULL; -ALTER TABLE tool CHANGE image image VARCHAR(255) default NULL; -ALTER TABLE tool CHANGE admin admin VARCHAR(255) default NULL; -ALTER TABLE tool CHANGE address address VARCHAR(255) default NULL; -ALTER TABLE calendar_event CHANGE title title VARCHAR(255) NOT NULL; -ALTER TABLE student_publication CHANGE url url VARCHAR(255) default NULL; -ALTER TABLE student_publication CHANGE title title VARCHAR(255) default NULL; -ALTER TABLE student_publication CHANGE author author VARCHAR(255) default NULL; -ALTER TABLE lp CHANGE name name varchar(255) NOT NULL; -ALTER TABLE lp_item CHANGE title title varchar(511) NOT NULL; -ALTER TABLE lp_item CHANGE description description varchar(511) NOT NULL default ''; \ No newline at end of file diff --git a/main/install/migrate-db-1.8.6.2-1.8.7-pre.sql b/main/install/migrate-db-1.8.6.2-1.8.7-pre.sql deleted file mode 100755 index fa741b831a..0000000000 --- a/main/install/migrate-db-1.8.6.2-1.8.7-pre.sql +++ /dev/null @@ -1,154 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.6.2 to version 1.8.7 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database - --- xxMAINxx - -DROP PROCEDURE IF EXISTS drop_index; -CREATE PROCEDURE drop_index(in t_name varchar(128), in i_name varchar(128) ) BEGIN IF ( (SELECT count(*) AS index_exists FROM information_schema.statistics WHERE table_schema = DATABASE( ) AND table_name = t_name AND index_name = i_name ) > 0) THEN SET @s = CONCAT('DROP INDEX ' , i_name , ' ON ' , t_name ); PREPARE stmt FROM @s; EXECUTE stmt; END IF; END; - -CALL drop_index('settings_current', 'unique_setting'); -CALL drop_index('settings_options', 'unique_setting_option'); - -ALTER TABLE user_friend RENAME TO user_rel_user; -ALTER TABLE session_rel_user ADD COLUMN relation_type int NOT NULL default 0; -ALTER TABLE course_rel_user ADD COLUMN relation_type int NOT NULL default 0; - --- see #4705 INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url, access_url_changeable) VALUES ('course_create_active_tools','notebook','checkbox','Tools','true','CourseCreateActiveToolsTitle','CourseCreateActiveToolsComment',NULL,'Notebook',1,0); -ALTER TABLE course DROP PRIMARY KEY , ADD UNIQUE KEY code (code); -ALTER TABLE course ADD id int NOT NULL auto_increment PRIMARY KEY FIRST; -CREATE TABLE block (id INT NOT NULL auto_increment, name VARCHAR(255) NULL, description TEXT NULL, path VARCHAR(255) NOT NULL, controller VARCHAR(100) NOT NULL, active TINYINT NOT NULL default 1, PRIMARY KEY(id)); -ALTER TABLE block ADD UNIQUE(path); -INSERT INTO user_field(field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES(1, 'dashboard', 'Dashboard', 0, 0); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('show_tabs', 'dashboard', 'checkbox', 'Platform', 'true', 'ShowTabsTitle','ShowTabsComment',NULL,'TabsDashboard', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('use_users_timezone', 'timezones', 'radio', 'Timezones', 'true', 'UseUsersTimezoneTitle','UseUsersTimezoneComment',NULL,'Timezones', 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('use_users_timezone', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('use_users_timezone', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('timezone_value', 'timezones', 'select', 'Timezones', '', 'TimezoneValueTitle','TimezoneValueComment',NULL,'Timezones', 1); - -ALTER TABLE user_field CHANGE tms tms DATETIME NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE course_field CHANGE tms tms DATETIME NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE course_field_values CHANGE tms tms DATETIME NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE session_field CHANGE tms tms DATETIME NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE session_field_values CHANGE tms tms DATETIME NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE user_field_options CHANGE tms tms DATETIME NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE user_field_values CHANGE tms tms DATETIME NOT NULL default '0000-00-00 00:00:00'; -ALTER TABLE access_url CHANGE tms tms DATETIME NOT NULL default '0000-00-00 00:00:00'; - -ALTER TABLE gradebook_certificate CHANGE date_certificate created_at DATETIME NOT NULL default '0000-00-00 00:00:00'; - -ALTER TABLE gradebook_evaluation ADD COLUMN created_at DATETIME NOT NULL default '0000-00-00 00:00:00'; -UPDATE gradebook_evaluation SET created_at = FROM_UNIXTIME(date); -ALTER TABLE gradebook_evaluation DROP date; - -ALTER TABLE gradebook_link ADD COLUMN created_at DATETIME NOT NULL default '0000-00-00 00:00:00'; -UPDATE gradebook_link SET created_at = FROM_UNIXTIME(date); -ALTER TABLE gradebook_link DROP date; - -ALTER TABLE gradebook_linkeval_log ADD COLUMN created_at DATETIME NOT NULL default '0000-00-00 00:00:00'; -UPDATE gradebook_linkeval_log SET created_at = FROM_UNIXTIME(date_log); -ALTER TABLE gradebook_linkeval_log DROP date_log; - -ALTER TABLE gradebook_result ADD COLUMN created_at DATETIME NOT NULL default '0000-00-00 00:00:00'; -UPDATE gradebook_result SET created_at = FROM_UNIXTIME(date); -ALTER TABLE gradebook_result DROP date; - -ALTER TABLE gradebook_result_log CHANGE date_log created_at DATETIME NOT NULL default '0000-00-00 00:00:00'; -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('gradebook_number_decimals', NULL, 'select', 'Gradebook', '0', 'GradebookNumberDecimals', 'GradebookNumberDecimalsComment', NULL, NULL, 0); - -INSERT INTO user_field(field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES(11, 'timezone', 'Timezone', 0, 0); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_create_active_tools','attendances','checkbox','Tools','false','CourseCreateActiveToolsTitle','CourseCreateActiveToolsComment',NULL,'Attendances', 0); - -ALTER TABLE user_field_values CHANGE id id BIGINT NOT NULL AUTO_INCREMENT; -ALTER TABLE user_field_values ADD INDEX (user_id, field_id); - -UPDATE settings_current SET selected_value = '1.8.7.11571' WHERE variable = 'dokeos_database_version'; - -ALTER TABLE course_rel_user DROP PRIMARY KEY, ADD PRIMARY KEY (course_code, user_id, relation_type); -ALTER TABLE session_rel_user DROP PRIMARY KEY, ADD PRIMARY KEY (id_session, id_user, relation_type); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_create_active_tools','course_progress','checkbox','Tools','false','CourseCreateActiveToolsTitle','CourseCreateActiveToolsComment',NULL,'CourseProgress', 0); -INSERT INTO settings_options(variable,value,display_text) VALUES ('homepage_view','vertical_activity','HomepageViewVerticalActivity'); - -UPDATE settings_current SET selected_value = 'UTF-8' WHERE variable = 'platform_charset'; - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_user_course_subscription_by_course_admin', NULL, 'radio', 'Security', 'true', 'AllowUserCourseSubscriptionByCourseAdminTitle', 'AllowUserCourseSubscriptionByCourseAdminComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_user_course_subscription_by_course_admin', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_user_course_subscription_by_course_admin', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_link_bug_notification', NULL, 'radio', 'Platform', 'true', 'ShowLinkBugNotificationTitle', 'ShowLinkBugNotificationComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_link_bug_notification', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_link_bug_notification', 'false', 'No'); - -ALTER TABLE gradebook_score_display ADD category_id int NOT NULL DEFAULT 0; -ALTER TABLE gradebook_score_display ADD INDEX (category_id); -ALTER TABLE gradebook_score_display ADD score_color_percent float unsigned NOT NULL DEFAULT 0; - --- xxSTATSxx -CREATE TABLE track_e_item_property(id int NOT NULL auto_increment PRIMARY KEY, course_id int NOT NULL, item_property_id int NOT NULL, title varchar(255), content text, progress int NOT NULL default 0, lastedit_date datetime NOT NULL default '0000-00-00 00:00:00', lastedit_user_id int NOT NULL, session_id int NOT NULL default 0); -ALTER TABLE track_e_item_property ADD INDEX (course_id, item_property_id, session_id); -ALTER TABLE track_e_access ADD access_session_id INT NOT NULL DEFAULT 0; -ALTER TABLE track_e_access ADD INDEX (access_session_id); -ALTER TABLE track_e_course_access ADD session_id INT NOT NULL DEFAULT 0; -ALTER TABLE track_e_course_access ADD INDEX (session_id); -ALTER TABLE track_e_downloads ADD down_session_id INT NOT NULL DEFAULT 0; -ALTER TABLE track_e_downloads ADD INDEX (down_session_id); -ALTER TABLE track_e_links ADD links_session_id INT NOT NULL DEFAULT 0; -ALTER TABLE track_e_links ADD INDEX (links_session_id); -ALTER TABLE track_e_uploads ADD upload_session_id INT NOT NULL DEFAULT 0; -ALTER TABLE track_e_uploads ADD INDEX (upload_session_id); -ALTER TABLE track_e_online ADD session_id INT NOT NULL DEFAULT 0; -ALTER TABLE track_e_online ADD INDEX (session_id); -ALTER TABLE track_e_attempt ADD session_id INT NOT NULL DEFAULT 0; -ALTER TABLE track_e_attempt ADD INDEX (session_id); -ALTER TABLE track_e_attempt_recording ADD session_id INT NOT NULL DEFAULT 0; -ALTER TABLE track_e_attempt_recording ADD INDEX (question_id); -ALTER TABLE track_e_attempt_recording ADD INDEX (session_id); -ALTER TABLE track_e_online ADD COLUMN access_url_id INT NOT NULL DEFAULT 1; - --- xxUSERxx - --- xxCOURSExx -INSERT INTO tool(name,link,image,visibility,admin,address,added_tool,target,category) VALUES ('attendance','attendance/index.php','attendance.gif',0,'0','squaregrey.gif',0,'_self','authoring'); -ALTER TABLE course_description ADD COLUMN progress INT NOT NULL DEFAULT 0 AFTER description_type; -ALTER TABLE item_property ADD id int NOT NULL auto_increment PRIMARY KEY FIRST; -CREATE TABLE attendance_calendar (id int NOT NULL auto_increment, attendance_id int NOT NULL, date_time datetime NOT NULL default '0000-00-00 00:00:00', done_attendance tinyint NOT NULL default 0, PRIMARY KEY(id)); -ALTER TABLE attendance_calendar ADD INDEX(attendance_id); -ALTER TABLE attendance_calendar ADD INDEX(done_attendance); -CREATE TABLE attendance_sheet (user_id int NOT NULL, attendance_calendar_id int NOT NULL, presence tinyint NOT NULL DEFAULT 0, PRIMARY KEY(user_id, attendance_calendar_id)); -ALTER TABLE attendance_sheet ADD INDEX(presence); -CREATE TABLE attendance_result (id int NOT NULL auto_increment PRIMARY KEY, user_id int NOT NULL, attendance_id int NOT NULL, score int NOT NULL DEFAULT 0); -ALTER TABLE attendance_result ADD INDEX(attendance_id); -ALTER TABLE attendance_result ADD INDEX(user_id); -CREATE TABLE attendance (id int NOT NULL auto_increment PRIMARY KEY, name text NOT NULL, description TEXT NULL, active tinyint NOT NULL default 1, attendance_qualify_title varchar(255) NULL, attendance_qualify_max int NOT NULL default 0, attendance_weight float(6,2) NOT NULL default '0.0', session_id int NOT NULL default 0); -ALTER TABLE attendance ADD INDEX(session_id); -ALTER TABLE attendance ADD INDEX(active); -ALTER TABLE lp_view ADD session_id INT NOT NULL DEFAULT 0; -ALTER TABLE lp_view ADD INDEX(session_id); -INSERT INTO course_setting (variable,value,category) VALUES ('allow_user_view_user_list',1,'user'); -ALTER TABLE tool_intro ADD COLUMN session_id INT NOT NULL DEFAULT 0 AFTER intro_text, DROP PRIMARY KEY, ADD PRIMARY KEY USING BTREE(id, session_id); -CREATE TABLE thematic (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, title VARCHAR( 255 ) NOT NULL, content TEXT NULL, display_order int unsigned not null default 0, active TINYINT NOT NULL default 0, session_id INT NOT NULL DEFAULT 0); -ALTER TABLE thematic ADD INDEX (active, session_id); -CREATE TABLE thematic_plan (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, thematic_id INT NOT NULL, title VARCHAR(255) NOT NULL, description TEXT NULL, description_type INT NOT NULL); -ALTER TABLE thematic_plan ADD INDEX (thematic_id, description_type); -CREATE TABLE thematic_advance (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, thematic_id INT NOT NULL, attendance_id INT NOT NULL DEFAULT 0, content TEXT NOT NULL, start_date DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', duration INT NOT NULL DEFAULT 0, done_advance tinyint NOT NULL DEFAULT 0); -ALTER TABLE thematic_advance ADD INDEX (thematic_id); -INSERT INTO course_setting (variable,value,category) VALUES ('display_info_advance_inside_homecourse',1,'thematic_advance'); -INSERT INTO tool(name, link, image, visibility, admin, address, added_tool, target, category) VALUES ('course_progress','course_progress/index.php','course_progress.gif',0,'0','squaregrey.gif',0,'_self','authoring'); -ALTER TABLE lp ADD prerequisite int unsigned NOT NULL DEFAULT 0; -ALTER TABLE student_publication MODIFY COLUMN description TEXT DEFAULT NULL; -ALTER TABLE student_publication ADD COLUMN user_id INTEGER NOT NULL AFTER session_id; -INSERT INTO course_setting(variable,value,category) VALUES ('email_alert_students_on_new_homework',0,'work'); -ALTER TABLE course_setting DROP INDEX unique_setting; diff --git a/main/install/migrate-db-1.8.7-1.8.8-pre.sql b/main/install/migrate-db-1.8.7-1.8.8-pre.sql deleted file mode 100755 index 634fc953ef..0000000000 --- a/main/install/migrate-db-1.8.7-1.8.8-pre.sql +++ /dev/null @@ -1,231 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.7 (or 1.8.7.1) to version 1.8.8 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database - --- xxMAINxx - -DROP PROCEDURE IF EXISTS drop_index; -CREATE PROCEDURE drop_index(in t_name varchar(128), in i_name varchar(128) ) BEGIN IF ( (SELECT count(*) AS index_exists FROM information_schema.statistics WHERE table_schema = DATABASE( ) AND table_name = t_name AND index_name = i_name ) > 0) THEN SET @s = CONCAT('DROP INDEX ' , i_name , ' ON ' , t_name ); PREPARE stmt FROM @s; EXECUTE stmt; END IF; END; - -CREATE TABLE course_request (id int NOT NULL AUTO_INCREMENT, code varchar(40) NOT NULL, user_id int unsigned NOT NULL default '0', directory varchar(40) DEFAULT NULL, db_name varchar(40) DEFAULT NULL, course_language varchar(20) DEFAULT NULL, title varchar(250) DEFAULT NULL, description text, category_code varchar(40) DEFAULT NULL, tutor_name varchar(200) DEFAULT NULL, visual_code varchar(40) DEFAULT NULL, request_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00', objetives text, target_audience text, status int unsigned NOT NULL default '0', info int unsigned NOT NULL default '0', exemplary_content int unsigned NOT NULL default '0', PRIMARY KEY (id), UNIQUE KEY code (code)); - -CALL drop_index('settings_current', 'unique_setting'); -CALL drop_index('settings_options', 'unique_setting_option'); - -ALTER TABLE settings_current ADD UNIQUE unique_setting (variable(110), subkey(110), category(110), access_url); -ALTER TABLE settings_options ADD UNIQUE unique_setting_option (variable(165), value(165)); -ALTER TABLE settings_current CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; -ALTER TABLE settings_options CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; - -ALTER TABLE user MODIFY COLUMN username VARCHAR(40) NOT NULL; - -UPDATE settings_current SET variable='chamilo_database_version' WHERE variable='dokeos_database_version'; - -ALTER TABLE sys_announcement ADD COLUMN access_url_id INT NOT NULL default 1; -ALTER TABLE sys_calendar ADD COLUMN access_url_id INT NOT NULL default 1; - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('users_copy_files', NULL, 'radio', 'Tools', 'true', 'AllowUsersCopyFilesTitle','AllowUsersCopyFilesComment', NULL,NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('users_copy_files', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('users_copy_files', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_validation', NULL, 'radio', 'Platform', 'false', 'EnableCourseValidation', 'EnableCourseValidationComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('course_validation', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('course_validation', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_validation_terms_and_conditions_url', NULL, 'textfield', 'Platform', '', 'CourseValidationTermsAndConditionsLink', 'CourseValidationTermsAndConditionsLinkComment', NULL, NULL, 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('sso_authentication',NULL,'radio','Security','false','EnableSSOTitle','EnableSSOComment',NULL,NULL,1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('sso_authentication_domain',NULL,'textfield','Security','','SSOServerDomainTitle','SSOServerDomainComment',NULL,NULL,1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('sso_authentication_auth_uri',NULL,'textfield','Security','/?q=user','SSOServerAuthURITitle','SSOServerAuthURIComment',NULL,NULL,1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('sso_authentication_unauth_uri',NULL,'textfield','Security','/?q=logout','SSOServerUnAuthURITitle','SSOServerUnAuthURIComment',NULL,NULL,1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('sso_authentication_protocol',NULL,'radio','Security','http://','SSOServerProtocolTitle','SSOServerProtocolComment',NULL,NULL,1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('sso_authentication', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('sso_authentication', 'false', 'No'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('sso_authentication_protocol', 'http://', 'http://'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('sso_authentication_protocol', 'https://', 'https://'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enabled_asciisvg',NULL,'radio','Editor','false','AsciiSvgTitle','AsciiSvgComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_asciisvg', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_asciisvg', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('include_asciimathml_script',NULL,'radio','Editor','false','IncludeAsciiMathMlTitle','IncludeAsciiMathMlComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('include_asciimathml_script', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('include_asciimathml_script', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enabled_wiris',NULL,'radio','Editor','false','EnabledWirisTitle','EnabledWirisComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_wiris', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_wiris', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_spellcheck',NULL,'radio','Editor','false','AllowSpellCheckTitle','AllowSpellCheckComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_spellcheck', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_spellcheck', 'false', 'No'); -ALTER TABLE course ADD INDEX idx_course_category_code (category_code); -ALTER TABLE course ADD INDEX idx_course_directory (directory(10)); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('force_wiki_paste_as_plain_text',NULL,'radio','Editor','false','ForceWikiPasteAsPlainText','ForceWikiPasteAsPlainTextComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('force_wiki_paste_as_plain_text', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('force_wiki_paste_as_plain_text', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enabled_googlemaps',NULL,'radio','Editor','false','EnabledGooglemapsTitle','EnabledGooglemapsComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_googlemaps', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_googlemaps', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enabled_imgmap',NULL,'radio','Editor','true','EnabledImageMapsTitle','EnabledImageMapsComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_imgmap', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_imgmap', 'false', 'No'); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enabled_support_svg',NULL,'radio','Tools','true','EnabledSVGTitle','EnabledSVGComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_support_svg', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_support_svg', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('pdf_export_watermark_enable', NULL,'radio', 'Platform', 'false','PDFExportWatermarkEnableTitle', 'PDFExportWatermarkEnableComment','platform',NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('pdf_export_watermark_enable','true','Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('pdf_export_watermark_enable','false','No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('pdf_export_watermark_by_course', NULL,'radio', 'Platform', 'false','PDFExportWatermarkByCourseTitle', 'PDFExportWatermarkByCourseComment','platform',NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('pdf_export_watermark_by_course','true','Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('pdf_export_watermark_by_course','false','No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('hide_courses_in_sessions', NULL,'radio', 'Platform', 'false','HideCoursesInSessionsTitle', 'HideCoursesInSessionsComment','platform',NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('hide_courses_in_sessions','true','Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('hide_courses_in_sessions','false','No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('pdf_export_watermark_text', NULL,'textfield', 'Platform', '', 'PDFExportWatermarkTextTitle','PDFExportWatermarkTextComment','platform',NULL, 1); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enabled_insertHtml',NULL,'radio','Editor','true','EnabledInsertHtmlTitle','EnabledInsertHtmlComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_insertHtml', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_insertHtml', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('students_export2pdf',NULL,'radio','Tools','true','EnabledStudentExport2PDFTitle','EnabledStudentExport2PDFComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('students_export2pdf', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('students_export2pdf', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('exercise_min_score', NULL,'textfield', 'Course', '', 'ExerciseMinScoreTitle', 'ExerciseMinScoreComment','platform',NULL, 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('exercise_max_score', NULL,'textfield', 'Course', '', 'ExerciseMaxScoreTitle', 'ExerciseMaxScoreComment','platform',NULL, 1); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_users_folders',NULL,'radio','Tools','true','ShowUsersFoldersTitle','ShowUsersFoldersComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_users_folders', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_users_folders', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_default_folders',NULL,'radio','Tools','true','ShowDefaultFoldersTitle','ShowDefaultFoldersComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_default_folders', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_default_folders', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_chat_folder',NULL,'radio','Tools','true','ShowChatFolderTitle','ShowChatFolderComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_chat_folder', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_chat_folder', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enabled_text2audio',NULL,'radio','Tools','false','Text2AudioTitle','Text2AudioComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_text2audio', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_text2audio', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','course_description','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'CourseDescription', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','calendar_event','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Agenda', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','document','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Documents', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','learnpath','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'LearningPath', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','link','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Links', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','announcement','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Announcements', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','forum','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Forums', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','dropbox','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Dropbox', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','quiz','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Quiz', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','user','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Users', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','group','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Groups', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','chat','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Chat', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','student_publication','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'StudentPublications', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','wiki','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Wiki', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','gradebook','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Gradebook', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','survey','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Survey', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','glossary','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Glossary', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','notebook','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Notebook', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','attendance','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Attendances', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','course_progress','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'CourseProgress', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','blog_management','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Blog',1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','tracking','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Stats',1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','course_maintenance','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'Maintenance',1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_hide_tools','course_setting','checkbox','Tools','false','CourseHideToolsTitle','CourseHideToolsComment',NULL,'CourseSettings',1); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enabled_support_pixlr',NULL,'radio','Tools','false','EnabledPixlrTitle','EnabledPixlrComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_support_pixlr', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enabled_support_pixlr', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_groups_to_users',NULL,'radio','Platform','false','ShowGroupsToUsersTitle','ShowGroupsToUsersComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_groups_to_users', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_groups_to_users', 'false', 'No'); - -INSERT INTO language (original_name, english_name, isocode, dokeos_folder, available) VALUES ('हिन्दी', 'hindi', 'hi', 'hindi', 0); - -ALTER TABLE session ADD COLUMN promotion_id INT NOT NULL; - -CREATE TABLE career (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, description TEXT NOT NULL, status INT NOT NULL default '0', created_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00', updated_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (id)); -CREATE TABLE promotion (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, description TEXT NOT NULL, status INT NOT NULL default '0', career_id INT NOT NULL, created_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00', updated_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY(id)); - -CREATE TABLE usergroup ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, description TEXT NOT NULL,PRIMARY KEY (id)); -CREATE TABLE usergroup_rel_user ( usergroup_id INT NOT NULL, user_id INT NOT NULL ); -CREATE TABLE usergroup_rel_course ( usergroup_id INT NOT NULL, course_id INT NOT NULL ); -CREATE TABLE usergroup_rel_session ( usergroup_id INT NOT NULL, session_id INT NOT NULL ); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('accessibility_font_resize',NULL,'radio','Platform','false','EnableAccessibilityFontResizeTitle','EnableAccessibilityFontResizeComment',NULL,NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('accessibility_font_resize', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('accessibility_font_resize', 'false', 'No'); - -CREATE TABLE notification (id BIGINT PRIMARY KEY NOT NULL AUTO_INCREMENT,dest_user_id INT NOT NULL, dest_mail CHAR(255),title CHAR(255), content CHAR(255), send_freq SMALLINT DEFAULT 1, created_at DATETIME NOT NULL, sent_at DATETIME NULL); - -ALTER TABLE notification ADD index mail_notify_sent_index (sent_at); -ALTER TABLE notification ADD index mail_notify_freq_index (sent_at, send_freq, created_at); - -ALTER TABLE session_category ADD COLUMN access_url_id INT NOT NULL default 1; - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enable_quiz_scenario', NULL,'radio','Course','false','EnableQuizScenarioTitle','EnableQuizScenarioComment',NULL,NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_quiz_scenario', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_quiz_scenario', 'false', 'No'); - -UPDATE settings_current SET category='Search' WHERE variable='search_enable'; - -INSERT INTO settings_options (variable, value, display_text) VALUES ('homepage_view', 'activity_big', 'HomepageViewActivityBig'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enable_nanogong',NULL,'radio','Tools','false','EnableNanogongTitle','EnableNanogongComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_nanogong', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_nanogong', 'false', 'No'); - -ALTER TABLE gradebook_evaluation ADD COLUMN locked int NOT NULL DEFAULT 0; - -UPDATE settings_current SET selected_value = '1.8.8.14911' WHERE variable = 'chamilo_database_version'; - --- xxSTATSxx -ALTER TABLE track_e_exercices ADD COLUMN orig_lp_item_view_id INT NOT NULL DEFAULT 0; - --- xxUSERxx -ALTER TABLE personal_agenda ADD PRIMARY KEY (id); -ALTER TABLE personal_agenda ADD INDEX idx_personal_agenda_user (user); -ALTER TABLE personal_agenda ADD INDEX idx_personal_agenda_parent (parent_event_id); -ALTER TABLE user_course_category ADD INDEX idx_user_c_cat_uid (user_id); - --- xxCOURSExx -ALTER TABLE course_setting CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; -ALTER TABLE forum_forum ADD start_time DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'; -ALTER TABLE forum_forum ADD end_time DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'; -ALTER TABLE wiki_mailcue ADD session_id smallint DEFAULT 0; - -ALTER TABLE lp ADD COLUMN use_max_score INT DEFAULT 1; -ALTER TABLE lp_item MODIFY COLUMN max_score FLOAT UNSIGNED DEFAULT 100; -ALTER TABLE tool MODIFY COLUMN category varchar(20) not null default 'authoring'; - -ALTER TABLE lp ADD COLUMN autolunch INT DEFAULT 0; -ALTER TABLE lp ADD COLUMN created_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'; -ALTER TABLE lp ADD COLUMN modified_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'; -ALTER TABLE lp ADD COLUMN expired_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'; -ALTER TABLE lp ADD COLUMN publicated_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'; - -CREATE TABLE quiz_question_option (id int NOT NULL, name varchar(255), position int unsigned NOT NULL, PRIMARY KEY (id)); -ALTER TABLE quiz_question ADD COLUMN extra varchar(255) DEFAULT NULL; -ALTER TABLE quiz_question CHANGE question question TEXT NOT NULL; - -INSERT INTO course_setting(variable,value,category) VALUES ('enable_lp_auto_launch',0,'learning_path'); -INSERT INTO course_setting(variable,value,category) VALUES ('pdf_export_watermark_text','','course'); - -ALTER TABLE quiz ADD COLUMN propagate_neg INT NOT NULL DEFAULT 0; -ALTER TABLE quiz_answer MODIFY COLUMN hotspot_type ENUM('square','circle','poly','delineation','oar'); - -ALTER TABLE attendance ADD COLUMN locked int NOT NULL default 0; -CREATE TABLE attendance_sheet_log (id INT NOT NULL AUTO_INCREMENT, attendance_id INT NOT NULL DEFAULT 0, lastedit_date DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', lastedit_type VARCHAR(200) NOT NULL, lastedit_user_id INT NOT NULL DEFAULT 0, calendar_date_value DATETIME NULL, PRIMARY KEY (id)); - diff --git a/main/install/migrate-db-1.8.8-1.9.0-pre.sql b/main/install/migrate-db-1.8.8-1.9.0-pre.sql deleted file mode 100755 index 456d18f85d..0000000000 --- a/main/install/migrate-db-1.8.8-1.9.0-pre.sql +++ /dev/null @@ -1,344 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.8 (or version 1.8.8.2, 1.8.8.4) to version 1.9.0 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database - --- xxMAINxx - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('filter_terms', NULL, 'textarea', 'Security', '', 'FilterTermsTitle', 'FilterTermsComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('header_extra_content', NULL, 'textarea', 'Tracking', '', 'HeaderExtraContentTitle', 'HeaderExtraContentComment', NULL, NULL, 1),('footer_extra_content', NULL, 'textarea', 'Tracking', '', 'FooterExtraContentTitle', 'FooterExtraContentComment', NULL, NULL,1); - -ALTER TABLE sys_calendar ADD COLUMN all_day INTEGER NOT NULL DEFAULT 0; - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_documents_preview', NULL, 'radio', 'Tools', 'false', 'ShowDocumentPreviewTitle', 'ShowDocumentPreviewComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_documents_preview', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_documents_preview', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('htmlpurifier_wiki',NULL,'radio','Editor','false','HtmlPurifierWikiTitle','HtmlPurifierWikiComment',NULL,NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('htmlpurifier_wiki', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('htmlpurifier_wiki', 'false', 'No'); - --- CAS feature -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('cas_activate', NULL, 'radio', 'CAS', 'false', 'CasMainActivateTitle', 'CasMainActivateComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) values ('cas_activate', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) values ('cas_activate', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('cas_server', NULL, 'textfield', 'CAS', '', 'CasMainServerTitle', 'CasMainServerComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('cas_server_uri', NULL, 'textfield', 'CAS', '', 'CasMainServerURITitle', 'CasMainServerURIComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('cas_port', NULL, 'textfield', 'CAS', '', 'CasMainPortTitle', 'CasMainPortComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('cas_protocol', NULL, 'radio', 'CAS', '', 'CasMainProtocolTitle', 'CasMainProtocolComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) values ('cas_protocol', 'CAS1', 'CAS1Text'); -INSERT INTO settings_options (variable, value, display_text) values ('cas_protocol', 'CAS2', 'CAS2Text'); -INSERT INTO settings_options (variable, value, display_text) values ('cas_protocol', 'SAML', 'SAMLText'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('cas_add_user_activate', NULL, 'radio', 'CAS', 'false', 'CasUserAddActivateTitle', 'CasUserAddActivateComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) values ('cas_add_user_activate', 'platform', 'casAddUserActivatePlatform'); -INSERT INTO settings_options (variable, value, display_text) values ('cas_add_user_activate', 'extldap', 'casAddUserActivateLDAP'); -INSERT INTO settings_options (variable, value, display_text) values ('cas_add_user_activate', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('update_user_info_cas_with_ldap', NULL, 'radio', 'CAS', 'true', 'UpdateUserInfoCasWithLdapTitle', 'UpdateUserInfoCasWithLdapComment', NULL, NULL, 0) - --- Custom Pages -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('use_custom_pages', NULL, 'radio','Platform','false','UseCustomPagesTitle','UseCustomPagesComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) values ('use_custom_pages', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) values ('use_custom_pages', 'false', 'No'); - --- Pages after login by role -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('student_page_after_login', NULL, 'textfield', 'Platform', '', 'StudentPageAfterLoginTitle', 'StudentPageAfterLoginComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('teacher_page_after_login', NULL, 'textfield', 'Platform', '', 'TeacherPageAfterLoginTitle', 'TeacherPageAfterLoginComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('drh_page_after_login', NULL, 'textfield', 'Platform', '', 'DRHPageAfterLoginTitle', 'DRHPageAfterLoginComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('sessionadmin_page_after_login', NULL, 'textfield', 'Session', '', 'SessionAdminPageAfterLoginTitle', 'SessionAdminPageAfterLoginComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('student_autosubscribe', NULL, 'textfield', 'Platform', '', 'StudentAutosubscribeTitle', 'StudentAutosubscribeComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('teacher_autosubscribe', NULL, 'textfield', 'Platform', '', 'TeacherAutosubscribeTitle', 'TeacherAutosubscribeComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('drh_autosubscribe', NULL, 'textfield', 'Platform', '', 'DRHAutosubscribeTitle', 'DRHAutosubscribeComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('sessionadmin_autosubscribe', NULL, 'textfield', 'Session', '', 'SessionadminAutosubscribeTitle', 'SessionadminAutosubscribeComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('show_tabs', 'custom_tab_1', 'checkbox', 'Platform', 'true', 'ShowTabsTitle', 'ShowTabsComment', NULL, 'TabsCustom1', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('show_tabs', 'custom_tab_2', 'checkbox', 'Platform', 'false', 'ShowTabsTitle', 'ShowTabsComment', NULL, 'TabsCustom2', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('show_tabs', 'custom_tab_3', 'checkbox', 'Platform', 'false', 'ShowTabsTitle', 'ShowTabsComment', NULL, 'TabsCustom3', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('languagePriority1', NULL, 'radio', 'Languages', 'course_lang', 'LanguagePriority1Title', 'LanguagePriority1Comment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('languagePriority2', NULL, 'radio', 'Languages', 'user_profil_lang', 'LanguagePriority2Title', 'LanguagePriority2Comment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('languagePriority3', NULL, 'radio', 'Languages', 'user_selected_lang', 'LanguagePriority3Title', 'LanguagePriority3Comment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('languagePriority4', NULL, 'radio', 'Languages', 'platform_lang', 'LanguagePriority4Title', 'LanguagePriority4Comment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('languagePriority1','platform_lang','PlatformLanguage'), ('languagePriority1','user_profil_lang','UserLanguage'), ('languagePriority1','user_selected_lang','UserSelectedLanguage'), ('languagePriority1','course_lang','CourseLanguage'), ('languagePriority2','platform_lang','PlatformLanguage'), ('languagePriority2','user_profil_lang','UserLanguage'), ('languagePriority2','user_selected_lang','UserSelectedLanguage'), ('languagePriority2','course_lang','CourseLanguage'), ('languagePriority3','platform_lang','PlatformLanguage'), ('languagePriority3','user_profil_lang','UserLanguage'), ('languagePriority3','user_selected_lang','UserSelectedLanguage'), ('languagePriority3','course_lang','CourseLanguage'), ('languagePriority4','platform_lang','PlatformLanguage'), ('languagePriority4','user_profil_lang','UserLanguage'), ('languagePriority4','user_selected_lang','UserSelectedLanguage'), ('languagePriority4','course_lang','CourseLanguage'); --- Email is login -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('login_is_email', NULL, 'radio', 'Platform', 'false', 'LoginIsEmailTitle', 'LoginIsEmailComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('login_is_email','true','Yes'),('login_is_email','false','No') ; -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('scorm_cumulative_session_time', NULL, 'radio', 'Course', 'true', 'ScormCumulativeSessionTimeTitle', 'ScormCumulativeSessionTimeComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('scorm_cumulative_session_time','true','Yes'), ('scorm_cumulative_session_time','false','No'); -CREATE TABLE event_type ( id int unsigned NOT NULL AUTO_INCREMENT, name varchar(50) NOT NULL, name_lang_var varchar(50) NOT NULL, desc_lang_var varchar(50) NOT NULL, extendable_variables varchar(255) NOT NULL, PRIMARY KEY (id)); -ALTER TABLE event_type ADD INDEX ( name ); -CREATE TABLE event_type_email_template ( id int unsigned NOT NULL AUTO_INCREMENT, event_type_id int NOT NULL, language_id int NOT NULL, message text NOT NULL, subject varchar(60) NOT NULL, PRIMARY KEY (id)); -ALTER TABLE event_type_email_template ADD INDEX ( language_id ); -INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) values (1, 'already_logged_in','Already logged in',0,0); -INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) values (1, 'update_type','Update script type',0,0); -CREATE TABLE announcement_rel_group (group_id int NOT NULL, announcement_id int NOT NULL, PRIMARY KEY (group_id, announcement_id)); -CREATE TABLE group_rel_group ( id int NOT NULL AUTO_INCREMENT, group_id int NOT NULL, subgroup_id int NOT NULL, relation_type int NOT NULL, PRIMARY KEY (id)); -ALTER TABLE group_rel_group ADD INDEX ( group_id ); -ALTER TABLE group_rel_group ADD INDEX ( subgroup_id ); -ALTER TABLE group_rel_group ADD INDEX ( relation_type ); - - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('gradebook_enable_grade_model', NULL, 'radio', 'Gradebook', 'false', 'GradebookEnableGradeModelTitle', 'GradebookEnableGradeModelComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('gradebook_enable_grade_model', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('gradebook_enable_grade_model', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('teachers_can_change_grade_model_settings', NULL, 'radio', 'Gradebook', 'true', 'TeachersCanChangeGradeModelSettingsTitle', 'TeachersCanChangeGradeModelSettingsComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('teachers_can_change_grade_model_settings', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('teachers_can_change_grade_model_settings', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('gradebook_locking_enabled', NULL, 'radio', 'Gradebook', 'false', 'GradebookEnableLockingTitle', 'GradebookEnableLockingComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('gradebook_locking_enabled', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('gradebook_locking_enabled', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('teachers_can_change_score_settings', NULL, 'radio', 'Gradebook', 'true', 'TeachersCanChangeScoreSettingsTitle', 'TeachersCanChangeScoreSettingsComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('teachers_can_change_score_settings', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('teachers_can_change_score_settings', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_users_to_change_email_with_no_password', NULL, 'radio', 'User', 'false', 'AllowUsersToChangeEmailWithNoPasswordTitle', 'AllowUsersToChangeEmailWithNoPasswordComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_users_to_change_email_with_no_password', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_users_to_change_email_with_no_password', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_session_admins_to_manage_all_sessions', NULL, 'radio', 'Session', 'false', 'AllowSessionAdminsToSeeAllSessionsTitle', 'AllowSessionAdminsToSeeAllSessionsComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_session_admins_to_manage_all_sessions', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_session_admins_to_manage_all_sessions', 'false', 'No'); - --- Shibboleth and Facebook auth and ldap -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('shibboleth_description', NULL, 'radio', 'Shibboleth', 'false', 'ShibbolethMainActivateTitle', 'ShibbolethMainActivateComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('facebook_description', NULL, 'radio', 'Facebook', 'false', 'FacebookMainActivateTitle', 'FacebookMainActivateComment', NULL, NULL, 0); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('ldap_description', NULL, 'radio', 'LDAP', NULL, 'LdapDescriptionTitle', 'LdapDescriptionComment', NULL, NULL, 0); - -ALTER TABLE course_rel_user ADD COLUMN legal_agreement INTEGER DEFAULT 0; -ALTER TABLE session_rel_course_rel_user ADD COLUMN legal_agreement INTEGER DEFAULT 0; -ALTER TABLE course ADD COLUMN legal TEXT NOT NULL; -ALTER TABLE course ADD COLUMN activate_legal INT NOT NULL DEFAULT 0; - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enable_help_link', NULL, 'radio', 'Platform', 'true', 'EnableHelpLinkTitle', 'EnableHelpLinkComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_help_link', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_help_link', 'false', 'No'); - -ALTER TABLE gradebook_category MODIFY COLUMN weight FLOAT NOT NULL; -ALTER TABLE gradebook_link MODIFY COLUMN weight FLOAT NOT NULL; -ALTER TABLE gradebook_link ADD COLUMN locked INT DEFAULT 0; -ALTER TABLE gradebook_category ADD COLUMN locked INT DEFAULT 0; -ALTER TABLE gradebook_category ADD COLUMN default_lowest_eval_exclude TINYINT default null; - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_hr_skills_management', NULL, 'radio', 'Gradebook', 'true', 'AllowHRSkillsManagementTitle', 'AllowHRSkillsManagementComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_hr_skills_management', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_hr_skills_management', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_admin_toolbar', NULL, 'radio', 'Platform', 'show_to_admin', 'ShowAdminToolbarTitle', 'ShowAdminToolbarComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_admin_toolbar', 'do_not_show', 'DoNotShow'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_admin_toolbar', 'show_to_admin', 'ShowToAdminsOnly'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_admin_toolbar', 'show_to_admin_and_teachers', 'ShowToAdminsAndTeachers'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_admin_toolbar', 'show_to_all', 'ShowToAllUsers'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_global_chat', NULL, 'radio', 'Platform', 'true', 'AllowGlobalChatTitle', 'AllowGlobalChatComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_global_chat', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_global_chat', 'false', 'No'); - -CREATE TABLE chat (id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, from_user INTEGER, to_user INTEGER, message TEXT NOT NULL, sent DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', recd INTEGER UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (id)); -ALTER TABLE chat ADD INDEX idx_chat_to_user (to_user); -ALTER TABLE chat ADD INDEX idx_chat_from_user (from_user); - -INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES (1, 'google_calendar_url','Google Calendar URL',0,0); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('courses_default_creation_visibility', NULL, 'radio', 'Course', '2', 'CoursesDefaultCreationVisibilityTitle', 'CoursesDefaultCreationVisibilityComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('courses_default_creation_visibility', '3', 'OpenToTheWorld'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('courses_default_creation_visibility', '2', 'OpenToThePlatform'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('courses_default_creation_visibility', '1', 'Private'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('courses_default_creation_visibility', '0', 'CourseVisibilityClosed'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_browser_sniffer', NULL, 'radio', 'Tuning', 'false', 'AllowBrowserSnifferTitle', 'AllowBrowserSnifferComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_browser_sniffer', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_browser_sniffer', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enable_wami_record', NULL, 'radio', 'Tools', 'false', 'EnableWamiRecordTitle', 'EnableWamiRecordComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_wami_record', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_wami_record', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_public_certificates', NULL, 'radio', 'Course', 'false', 'AllowPublicCertificatesTitle', 'AllowPublicCertificatesComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_public_certificates', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_public_certificates', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enable_iframe_inclusion', NULL, 'radio', 'Editor', 'false', 'EnableIframeInclusionTitle', 'EnableIframeInclusionComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_iframe_inclusion', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_iframe_inclusion', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_hot_courses', NULL, 'radio', 'Platform', 'true', 'ShowHotCoursesTitle', 'ShowHotCoursesComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_hot_courses', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_hot_courses', 'false', 'No'); - - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('gradebook_default_weight', NULL, 'textfield', 'Gradebook', '100', 'GradebookDefaultWeightTitle', 'GradebookDefaultWeightComment', NULL, NULL, 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('gradebook_default_grade_model_id', NULL, 'select', 'Gradebook', '', 'GradebookDefaultGradeModelTitle', 'GradebookDefaultGradeModelComment', NULL, NULL, 1); - -UPDATE settings_current SET category = 'Session' WHERE variable IN ('show_tutor_data', 'use_session_mode', 'add_users_by_coach', 'show_session_coach', 'show_session_data', 'allow_coach_to_edit_course_session','hide_courses_in_sessions', 'show_groups_to_users'); - -INSERT INTO language (original_name, english_name, isocode, dokeos_folder, available) VALUES ('বাংলা','bengali','bn','bengali',0), ('الصومالية','somali','so','somali',0); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enable_webcam_clip', NULL, 'radio', 'Tools', 'false', 'EnableWebCamClipTitle', 'EnableWebCamClipComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_webcam_clip', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_webcam_clip', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('tool_visible_by_default_at_creation','documents','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Documents', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('tool_visible_by_default_at_creation','learning_path','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'LearningPath', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('tool_visible_by_default_at_creation','links','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Links', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('tool_visible_by_default_at_creation','announcements','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Announcements', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('tool_visible_by_default_at_creation','forums','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Forums', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('tool_visible_by_default_at_creation','quiz','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Quiz', 1); -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('tool_visible_by_default_at_creation','gradebook','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Gradebook', 1); - --- Course ranking -CREATE TABLE track_course_ranking (id int unsigned not null PRIMARY KEY AUTO_INCREMENT, c_id int unsigned not null, session_id int unsigned not null default 0, url_id int unsigned not null default 0, accesses int unsigned not null default 0, total_score int unsigned not null default 0, users int unsigned not null default 0, creation_date datetime not null); - -ALTER TABLE track_course_ranking ADD INDEX idx_tcc_cid (c_id); -ALTER TABLE track_course_ranking ADD INDEX idx_tcc_sid (session_id); -ALTER TABLE track_course_ranking ADD INDEX idx_tcc_urlid (url_id); -ALTER TABLE track_course_ranking ADD INDEX idx_tcc_creation_date (creation_date); - -CREATE TABLE user_rel_course_vote ( id int unsigned not null AUTO_INCREMENT PRIMARY KEY, c_id int unsigned not null, user_id int unsigned not null, session_id int unsigned not null default 0, url_id int unsigned not null default 0, vote int unsigned not null default 0); - -ALTER TABLE user_rel_course_vote ADD INDEX idx_ucv_cid (c_id); -ALTER TABLE user_rel_course_vote ADD INDEX idx_ucv_uid (user_id); -ALTER TABLE user_rel_course_vote ADD INDEX idx_ucv_cuid (user_id, c_id); - ---User chat status -INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES (1, 'user_chat_status','User chat status', 0, 0); -UPDATE settings_current SET selected_value = 'true' WHERE variable = 'more_buttons_maximized_mode'; - ---Grade model -CREATE TABLE grade_model (id INTEGER NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, description TEXT, default_lowest_eval_exclude TINYINT default null, default_external_eval_prefix VARCHAR(140) default null, PRIMARY KEY (id)); -CREATE TABLE grade_components (id INTEGER NOT NULL AUTO_INCREMENT, percentage VARCHAR(255) NOT NULL, title VARCHAR(255) NOT NULL, acronym VARCHAR(255) NOT NULL, grade_model_id INTEGER NOT NULL, PRIMARY KEY (id)); -ALTER TABLE gradebook_category ADD COLUMN grade_model_id INT DEFAULT 0; - -UPDATE settings_current SET title = 'DatabaseVersion' WHERE variable = 'chamilo_database_version'; -ALTER TABLE gradebook_evaluation MODIFY COLUMN weight FLOAT NOT NULL; - -INSERT INTO settings_options(variable, value, display_text) VALUES ('page_after_login', 'main/auth/courses.php', 'CourseCatalog'); - -ALTER TABLE settings_current ADD COLUMN access_url_locked INTEGER NOT NULL DEFAULT 0; - --- Event mail -CREATE TABLE event_email_template ( id int NOT NULL AUTO_INCREMENT, message text, subject varchar(255) DEFAULT NULL, event_type_name varchar(255) DEFAULT NULL, activated tinyint NOT NULL DEFAULT '0', language_id int DEFAULT NULL, PRIMARY KEY (id)); -ALTER TABLE event_email_template ADD INDEX event_name_index (event_type_name); - -CREATE TABLE event_sent ( id int NOT NULL AUTO_INCREMENT, user_from int NOT NULL, user_to int DEFAULT NULL, event_type_name varchar(100) DEFAULT NULL, PRIMARY KEY (id)); -ALTER TABLE event_sent ADD INDEX event_name_index (event_type_name); - -CREATE TABLE user_rel_event_type ( id int NOT NULL AUTO_INCREMENT, user_id int NOT NULL, event_type_name varchar(255) NOT NULL, PRIMARY KEY (id)); -ALTER TABLE user_rel_event_type ADD INDEX event_name_index (event_type_name); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('activate_email_template', NULL, 'radio', 'Platform', 'false', 'ActivateEmailTemplateTitle', 'ActivateEmailTemplateComment', NULL, NULL, 0); -INSERT INTO settings_options (variable, value, display_text) VALUES ('activate_email_template', 'true', 'Yes'),('activate_email_template', 'false', 'No'); - --- Skills -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_skills_tool', NULL, 'radio', 'Platform', 'false', 'AllowSkillsToolTitle', 'AllowSkillsToolComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_skills_tool', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_skills_tool', 'false', 'No'); - -CREATE TABLE IF NOT EXISTS skill ( id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, short_code varchar(100) NOT NULL, description TEXT NOT NULL, access_url_id int NOT NULL, icon varchar(255) NOT NULL, PRIMARY KEY (id)); -INSERT INTO skill (name) VALUES ('Root'); - -CREATE TABLE IF NOT EXISTS skill_rel_gradebook ( id int NOT NULL AUTO_INCREMENT, gradebook_id int NOT NULL, skill_id int NOT NULL, type varchar(10) NOT NULL, PRIMARY KEY (id)); -CREATE TABLE IF NOT EXISTS skill_rel_skill (id int NOT NULL AUTO_INCREMENT, skill_id int NOT NULL, parent_id int NOT NULL, relation_type int NOT NULL, level int NOT NULL, PRIMARY KEY (id)); -INSERT INTO skill_rel_skill VALUES(1, 1, 0, 0, 0); - -CREATE TABLE IF NOT EXISTS skill_rel_user ( id int NOT NULL AUTO_INCREMENT, user_id int NOT NULL, skill_id int NOT NULL, acquired_skill_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00',assigned_by int NOT NULL,PRIMARY KEY (id)); -CREATE TABLE IF NOT EXISTS skill_profile ( id INTEGER NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, description TEXT NOT NULL, PRIMARY KEY (id)); -CREATE TABLE IF NOT EXISTS skill_rel_profile ( id INTEGER NOT NULL AUTO_INCREMENT, skill_id INTEGER NOT NULL, profile_id INTEGER NOT NULL, PRIMARY KEY (id)); - --- Removing use_document_title -DELETE FROM settings_current WHERE variable = 'use_document_title'; -DELETE FROM settings_options WHERE variable = 'use_document_title'; - -ALTER TABLE course MODIFY COLUMN disk_quota bigint unsigned DEFAULT NULL; -ALTER TABLE user MODIFY COLUMN username VARCHAR(100) NOT NULL; - -UPDATE language SET english_name = 'basque' , dokeos_folder = 'basque' where english_name = 'euskera'; -UPDATE language SET english_name = 'turkish', dokeos_folder = 'turkish' where english_name = 'turkce'; - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('platform_unsubscribe_allowed', NULL, 'radio', 'Platform', 'false', 'PlatformUnsubscribeTitle', 'PlatformUnsubscribeComment', NULL, NULL, 1); -INSERT INTO settings_options (variable, value, display_text) values ('platform_unsubscribe_allowed', 'true', 'Yes'); -INSERT INTO settings_options (variable, value, display_text) values ('platform_unsubscribe_allowed', 'false', 'No'); - -ALTER TABLE usergroup_rel_session ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE usergroup_rel_course ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE usergroup_rel_user ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE admin ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE reservation_category_rights ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); - - -CREATE TABLE course_type (id int unsigned not null auto_increment primary key, name varchar(50) not null, translation_var char(40) default 'UndefinedCourseTypeLabel', description TEXT default '', props text default ''); - -INSERT INTO course_type (id, name) VALUES (1, 'All tools'); -INSERT INTO course_type (id, name) VALUES (2, 'Entry exam'); - -ALTER TABLE course add course_type_id int unsigned default 1; - -CREATE TABLE usergroup_rel_question (id int unsigned not null auto_increment primary key, c_id int unsigned not null, question_id int unsigned not null, usergroup_id int unsigned not null, coefficient float(6,2)); - --- Remove settings entry that doesnt exist anymore - -DELETE FROM settings_current WHERE variable = 'read_more_limit'; -DELETE FROM settings_current WHERE variable = 'user_order_by'; -DELETE FROM settings_options WHERE variable = 'user_order_by'; - -ALTER TABLE user_api_key ADD COLUMN api_end_point text DEFAULT NULL; -ALTER TABLE user_api_key ADD COLUMN created_date datetime DEFAULT NULL; -ALTER TABLE user_api_key ADD COLUMN validity_start_date datetime DEFAULT NULL; -ALTER TABLE user_api_key ADD COLUMN validity_end_date datetime DEFAULT NULL; -ALTER TABLE user_api_key ADD COLUMN description text DEFAULT NULL; - --- Do not move this query -UPDATE settings_current SET selected_value = '1.9.0.18715' WHERE variable = 'chamilo_database_version'; - --- xxSTATSxx -ALTER TABLE track_e_default MODIFY COLUMN default_value TEXT; -ALTER TABLE track_e_exercices ADD COLUMN questions_to_check TEXT NOT NULL DEFAULT ''; ---CREATE TABLE track_filtered_terms (id int, user_id int, course_id int, session_id int, tool_id char(12), filtered_term varchar(255), created_at datetime); -CREATE TABLE track_stored_values (id int unsigned not null AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, sco_id INT NOT NULL, course_id CHAR(40) NOT NULL, sv_key CHAR(64) NOT NULL, sv_value TEXT NOT NULL); -ALTER TABLE track_stored_values ADD KEY (user_id, sco_id, course_id, sv_key); -ALTER TABLE track_stored_values ADD UNIQUE (user_id, sco_id, course_id, sv_key); - -CREATE TABLE track_stored_values_stack (id int unsigned not null AUTO_INCREMENT PRIMARY KEY,user_id INT NOT NULL, sco_id INT NOT NULL, stack_order INT NOT NULL, course_id CHAR(40) NOT NULL, sv_key CHAR(64) NOT NULL, sv_value TEXT NOT NULL); -ALTER TABLE track_stored_values_stack ADD KEY (user_id, sco_id, course_id, sv_key, stack_order); -ALTER TABLE track_stored_values_stack ADD UNIQUE (user_id, sco_id, course_id, sv_key, stack_order); - -ALTER TABLE track_e_attempt ADD COLUMN filename VARCHAR(255) DEFAULT NULL; -ALTER TABLE track_e_default ADD COLUMN c_id INTEGER DEFAULT NULL; - -ALTER TABLE track_e_attempt_recording ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE track_e_attempt ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE track_e_hotpotatoes ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); - -CREATE TABLE track_e_attempt_coeff ( id int unsigned not null auto_increment primary key, attempt_id INT NOT NULL, marks_coeff float(6,2)); - --- xxUSERxx -ALTER TABLE personal_agenda ADD COLUMN all_day INTEGER NOT NULL DEFAULT 0; - --- xxCOURSExx -CREATE TABLE IF NOT EXISTS metadata (c_id INT NOT NULL, eid VARCHAR(250) NOT NULL, mdxmltext TEXT default '', md5 CHAR(32) default '', htmlcache1 TEXT default '', htmlcache2 TEXT default '', indexabletext TEXT default '', PRIMARY KEY (c_id, eid)) - -ALTER TABLE lp ADD COLUMN hide_toc_frame INT NOT NULL DEFAULT 0; -ALTER TABLE lp ADD COLUMN seriousgame_mode INT NOT NULL DEFAULT 0; -ALTER TABLE lp_item_view modify column suspend_data longtext; -ALTER TABLE quiz ADD COLUMN review_answers INT NOT NULL DEFAULT 0; -ALTER TABLE student_publication ADD COLUMN contains_file INTEGER NOT NULL DEFAULT 1; -ALTER TABLE student_publication ADD COLUMN allow_text_assignment INTEGER NOT NULL DEFAULT 0; -ALTER TABLE quiz ADD COLUMN random_by_category INT NOT NULL DEFAULT 0; -ALTER TABLE quiz ADD COLUMN text_when_finished TEXT DEFAULT NULL; -ALTER TABLE quiz ADD COLUMN display_category_name INT NOT NULL DEFAULT 1; -ALTER TABLE quiz ADD COLUMN pass_percentage INT DEFAULT NULL; -INSERT INTO course_setting(variable,value,category) VALUES ('allow_public_certificates', 0, 'certificates'); - -ALTER TABLE quiz_answer ADD COLUMN answer_code char(10) default ''; -ALTER TABLE quiz_question ADD COLUMN question_code char(10) default ''; \ No newline at end of file diff --git a/main/install/migrate-db-1.8.8-1.9.0-pre.sql.optimized b/main/install/migrate-db-1.8.8-1.9.0-pre.sql.optimized deleted file mode 100755 index faed069bd6..0000000000 --- a/main/install/migrate-db-1.8.8-1.9.0-pre.sql.optimized +++ /dev/null @@ -1,216 +0,0 @@ --- This script updates the databases structure before migrating the data from --- version 1.8.8 (or version 1.8.8.2, 1.8.8.4) to version 1.9.0 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database - --- xxMAINxx - -LOCK TABLES sys_calendar; -ALTER TABLE sys_calendar ADD COLUMN all_day INTEGER NOT NULL DEFAULT 0; -UNLOCK TABLES; - -CREATE TABLE event_type ( id int unsigned NOT NULL AUTO_INCREMENT, name varchar(50) NOT NULL, name_lang_var varchar(50) NOT NULL, desc_lang_var varchar(50) NOT NULL, extendable_variables varchar(255) NOT NULL, PRIMARY KEY (id)); -LOCK TABLES event_type; -ALTER TABLE event_type ADD INDEX ( name ); - -CREATE TABLE event_type_email_template ( id int unsigned NOT NULL AUTO_INCREMENT, event_type_id int NOT NULL, language_id int NOT NULL, message text NOT NULL, subject varchar(60) NOT NULL, PRIMARY KEY (id)); -LOCK TABLES event_type_email_template; -ALTER TABLE event_type_email_template ADD INDEX ( language_id ); - - -CREATE TABLE announcement_rel_group (group_id int NOT NULL, announcement_id int NOT NULL, PRIMARY KEY (group_id, announcement_id)); - -CREATE TABLE group_rel_group ( id int NOT NULL AUTO_INCREMENT, group_id int NOT NULL, subgroup_id int NOT NULL, relation_type int NOT NULL, PRIMARY KEY (id)); - -CREATE TABLE chat (id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, from_user INTEGER, to_user INTEGER, message TEXT NOT NULL, sent DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', recd INTEGER UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (id)); - -CREATE TABLE track_course_ranking (id int unsigned not null PRIMARY KEY AUTO_INCREMENT, c_id int unsigned not null, session_id int unsigned not null default 0, url_id int unsigned not null default 0, accesses int unsigned not null default 0, total_score int unsigned not null default 0, users int unsigned not null default 0, creation_date datetime not null); - -CREATE TABLE user_rel_course_vote ( id int unsigned not null AUTO_INCREMENT PRIMARY KEY, c_id int unsigned not null, user_id int unsigned not null, session_id int unsigned not null default 0, url_id int unsigned not null default 0, vote int unsigned not null default 0); - -CREATE TABLE grade_model (id INTEGER NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, description TEXT, default_lowest_eval_exclude TINYINT default null, default_external_eval_prefix VARCHAR(140) default null, PRIMARY KEY (id)); - -CREATE TABLE grade_components (id INTEGER NOT NULL AUTO_INCREMENT, percentage VARCHAR(255) NOT NULL, title VARCHAR(255) NOT NULL, acronym VARCHAR(255) NOT NULL, grade_model_id INTEGER NOT NULL, PRIMARY KEY (id)); - -CREATE TABLE event_email_template ( id int NOT NULL AUTO_INCREMENT, message text, subject varchar(255) DEFAULT NULL, event_type_name varchar(255) DEFAULT NULL, activated tinyint NOT NULL DEFAULT '0', language_id int DEFAULT NULL, PRIMARY KEY (id)); - -CREATE TABLE event_sent ( id int NOT NULL AUTO_INCREMENT, user_from int NOT NULL, user_to int DEFAULT NULL, event_type_name varchar(100) DEFAULT NULL, PRIMARY KEY (id)); - -CREATE TABLE user_rel_event_type ( id int NOT NULL AUTO_INCREMENT, user_id int NOT NULL, event_type_name varchar(255) NOT NULL, PRIMARY KEY (id)); - -CREATE TABLE IF NOT EXISTS skill ( id int NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, short_code varchar(100) NOT NULL, description TEXT NOT NULL, access_url_id int NOT NULL, icon varchar(255) NOT NULL, PRIMARY KEY (id)); - -CREATE TABLE IF NOT EXISTS skill_rel_gradebook ( id int NOT NULL AUTO_INCREMENT, gradebook_id int NOT NULL, skill_id int NOT NULL, type varchar(10) NOT NULL, PRIMARY KEY (id)); - -CREATE TABLE IF NOT EXISTS skill_rel_skill (id int NOT NULL AUTO_INCREMENT, skill_id int NOT NULL, parent_id int NOT NULL, relation_type int NOT NULL, level int NOT NULL, PRIMARY KEY (id)); - -CREATE TABLE IF NOT EXISTS skill_rel_user ( id int NOT NULL AUTO_INCREMENT, user_id int NOT NULL, skill_id int NOT NULL, acquired_skill_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00',assigned_by int NOT NULL,PRIMARY KEY (id)); - -CREATE TABLE IF NOT EXISTS skill_profile ( id INTEGER NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, description TEXT NOT NULL, PRIMARY KEY (id)); - -CREATE TABLE IF NOT EXISTS skill_rel_profile ( id INTEGER NOT NULL AUTO_INCREMENT, skill_id INTEGER NOT NULL, profile_id INTEGER NOT NULL, PRIMARY KEY (id)); - -CREATE TABLE course_type (id int unsigned not null auto_increment primary key, name varchar(50) not null, translation_var char(40) default 'UndefinedCourseTypeLabel', description TEXT default '', props text default ''); - -CREATE TABLE usergroup_rel_question (id int unsigned not null auto_increment primary key, c_id int unsigned not null, question_id int unsigned not null, usergroup_id int unsigned not null, coefficient float(6,2)); - -CREATE TABLE track_stored_values (id int unsigned not null AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, sco_id INT NOT NULL, course_id CHAR(40) NOT NULL, sv_key CHAR(64) NOT NULL, sv_value TEXT NOT NULL); - -CREATE TABLE track_stored_values_stack (id int unsigned not null AUTO_INCREMENT PRIMARY KEY,user_id INT NOT NULL, sco_id INT NOT NULL, stack_order INT NOT NULL, course_id CHAR(40) NOT NULL, sv_key CHAR(64) NOT NULL, sv_value TEXT NOT NULL); - -CREATE TABLE track_e_attempt_coeff ( id int unsigned not null auto_increment primary key, attempt_id INT NOT NULL, marks_coeff float(6,2)); - - -LOCK TABLES group_rel_group, course_rel_user, session_rel_course_rel_user, course, gradebook_category, gradebook_link, chat, track_course_ranking, user_rel_course_vote, user; -ALTER TABLE group_rel_group ADD INDEX ( group_id ); -ALTER TABLE group_rel_group ADD INDEX ( subgroup_id ); -ALTER TABLE group_rel_group ADD INDEX ( relation_type ); -ALTER TABLE course_rel_user ADD COLUMN legal_agreement INTEGER DEFAULT 0; -ALTER TABLE session_rel_course_rel_user ADD COLUMN legal_agreement INTEGER DEFAULT 0; -ALTER TABLE course ADD COLUMN legal TEXT NOT NULL; -ALTER TABLE course ADD COLUMN activate_legal INT NOT NULL DEFAULT 0; -ALTER TABLE gradebook_category MODIFY COLUMN weight FLOAT NOT NULL; -ALTER TABLE gradebook_category ADD COLUMN locked INT DEFAULT 0; -ALTER TABLE gradebook_category ADD COLUMN default_lowest_eval_exclude TINYINT default null; -ALTER TABLE gradebook_link MODIFY COLUMN weight FLOAT NOT NULL; -ALTER TABLE gradebook_link ADD COLUMN locked INT DEFAULT 0; -ALTER TABLE chat ADD INDEX idx_chat_to_user (to_user); -ALTER TABLE chat ADD INDEX idx_chat_from_user (from_user); -ALTER TABLE track_course_ranking ADD INDEX idx_tcc_cid (c_id); -ALTER TABLE track_course_ranking ADD INDEX idx_tcc_sid (session_id); -ALTER TABLE track_course_ranking ADD INDEX idx_tcc_urlid (url_id); -ALTER TABLE track_course_ranking ADD INDEX idx_tcc_creation_date (creation_date); -ALTER TABLE user_rel_course_vote ADD INDEX idx_ucv_cid (c_id); -ALTER TABLE user_rel_course_vote ADD INDEX idx_ucv_uid (user_id); -ALTER TABLE user_rel_course_vote ADD INDEX idx_ucv_cuid (user_id, c_id); -ALTER TABLE course MODIFY COLUMN disk_quota bigint unsigned DEFAULT NULL; -ALTER TABLE user MODIFY COLUMN username VARCHAR(100) NOT NULL; -UNLOCK TABLES; - -LOCK_TABLES gradebook_category, settings_current, event_email_template, event_sent, user_rel_event_type, usergroup_rel_session, usergroup_rel_course, usergroup_rel_user, admin, reservation_category_rights, course, user_api_key, track_e_default, track_e_exercises; -ALTER TABLE gradebook_category ADD COLUMN grade_model_id INT DEFAULT 0; -ALTER TABLE gradebook_evaluation MODIFY COLUMN weight FLOAT NOT NULL; -ALTER TABLE settings_current ADD COLUMN access_url_locked INTEGER NOT NULL DEFAULT 0; -ALTER TABLE event_email_template ADD INDEX event_name_index (event_type_name); -ALTER TABLE event_sent ADD INDEX event_name_index (event_type_name); -ALTER TABLE user_rel_event_type ADD INDEX event_name_index (event_type_name); -ALTER TABLE usergroup_rel_session ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE usergroup_rel_course ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE usergroup_rel_user ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE admin ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE reservation_category_rights ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE course add course_type_id int unsigned default 1; -ALTER TABLE user_api_key ADD COLUMN api_end_point text DEFAULT NULL; -ALTER TABLE user_api_key ADD COLUMN created_date datetime DEFAULT NULL; -ALTER TABLE user_api_key ADD COLUMN validity_start_date datetime DEFAULT NULL; -ALTER TABLE user_api_key ADD COLUMN validity_end_date datetime DEFAULT NULL; -ALTER TABLE user_api_key ADD COLUMN description text DEFAULT NULL; -ALTER TABLE track_e_default MODIFY COLUMN default_value TEXT; -ALTER TABLE track_e_exercices ADD COLUMN questions_to_check TEXT NOT NULL DEFAULT ''; -UNLOCK TABLES; - -LOCK TABLES track_stored_values, track_stored_values_stack, track_e_attempt, track_e_attempt_recording, track_e_hotpotatoes, personal_agenda; -ALTER TABLE track_stored_values ADD KEY (user_id, sco_id, course_id, sv_key); -ALTER TABLE track_stored_values ADD UNIQUE (user_id, sco_id, course_id, sv_key); -ALTER TABLE track_stored_values_stack ADD KEY (user_id, sco_id, course_id, sv_key, stack_order); -ALTER TABLE track_stored_values_stack ADD UNIQUE (user_id, sco_id, course_id, sv_key, stack_order); -ALTER TABLE track_e_attempt ADD COLUMN filename VARCHAR(255) DEFAULT NULL; -ALTER TABLE track_e_default ADD COLUMN c_id INTEGER DEFAULT NULL; -ALTER TABLE track_e_attempt_recording ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE track_e_attempt ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE track_e_hotpotatoes ADD COLUMN id INTEGER NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (id); -ALTER TABLE personal_agenda ADD COLUMN all_day INTEGER NOT NULL DEFAULT 0; -UNLOCK TABLES; - -INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) values (1, 'already_logged_in','Already logged in',0,0), (1, 'update_type','Update script type',0,0), (1, 'google_calendar_url','Google Calendar URL',0,0), (1, 'user_chat_status','User chat status', 0, 0); - - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('filter_terms', NULL, 'textarea', 'Security', '', 'FilterTermsTitle', 'FilterTermsComment', NULL, NULL, 0), ('header_extra_content', NULL, 'textarea', 'Tracking', '', 'HeaderExtraContentTitle', 'HeaderExtraContentComment', NULL, NULL, 1),('footer_extra_content', NULL, 'textarea', 'Tracking', '', 'FooterExtraContentTitle', 'FooterExtraContentComment', NULL, NULL,1), ('show_documents_preview', NULL, 'radio', 'Tools', 'false', 'ShowDocumentPreviewTitle', 'ShowDocumentPreviewComment', NULL, NULL, 1), ('htmlpurifier_wiki',NULL,'radio','Editor','false','HtmlPurifierWikiTitle','HtmlPurifierWikiComment',NULL,NULL, 0), ('cas_activate', NULL, 'radio', 'CAS', 'false', 'CasMainActivateTitle', 'CasMainActivateComment', NULL, NULL, 0), ('cas_server', NULL, 'textfield', 'CAS', '', 'CasMainServerTitle', 'CasMainServerComment', NULL, NULL, 0), ('cas_server_uri', NULL, 'textfield', 'CAS', '', 'CasMainServerURITitle', 'CasMainServerURIComment', NULL, NULL, 0), ('cas_port', NULL, 'textfield', 'CAS', '', 'CasMainPortTitle', 'CasMainPortComment', NULL, NULL, 0), ('cas_protocol', NULL, 'radio', 'CAS', '', 'CasMainProtocolTitle', 'CasMainProtocolComment', NULL, NULL, 0), ('cas_add_user_activate', NULL, 'radio', 'CAS', 'false', 'CasUserAddActivateTitle', 'CasUserAddActivateComment', NULL, NULL, 0), ('update_user_info_cas_with_ldap', NULL, 'radio', 'CAS', 'true', 'UpdateUserInfoCasWithLdapTitle', 'UpdateUserInfoCasWithLdapComment', NULL, NULL, 0), ('use_custom_pages', NULL, 'radio','Platform','false','UseCustomPagesTitle','UseCustomPagesComment', NULL, NULL, 1); - -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_documents_preview', 'true', 'Yes'), ('show_documents_preview', 'false', 'No'), ('htmlpurifier_wiki', 'true', 'Yes'), ('htmlpurifier_wiki', 'false', 'No'), ('cas_activate', 'true', 'Yes'), ('cas_activate', 'false', 'No'), ('cas_protocol', 'CAS1', 'CAS1Text'), ('cas_protocol', 'CAS2', 'CAS2Text'), ('cas_protocol', 'SAML', 'SAMLText'), ('cas_add_user_activate', 'platform', 'casAddUserActivatePlatform'), ('cas_add_user_activate', 'extldap', 'casAddUserActivateLDAP'), ('cas_add_user_activate', 'false', 'No'), ('use_custom_pages', 'true', 'Yes'), ('use_custom_pages', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('student_page_after_login', NULL, 'textfield', 'Platform', '', 'StudentPageAfterLoginTitle', 'StudentPageAfterLoginComment', NULL, NULL, 0), ('teacher_page_after_login', NULL, 'textfield', 'Platform', '', 'TeacherPageAfterLoginTitle', 'TeacherPageAfterLoginComment', NULL, NULL, 0), ('drh_page_after_login', NULL, 'textfield', 'Platform', '', 'DRHPageAfterLoginTitle', 'DRHPageAfterLoginComment', NULL, NULL, 0), ('sessionadmin_page_after_login', NULL, 'textfield', 'Session', '', 'SessionAdminPageAfterLoginTitle', 'SessionAdminPageAfterLoginComment', NULL, NULL, 0), ('student_autosubscribe', NULL, 'textfield', 'Platform', '', 'StudentAutosubscribeTitle', 'StudentAutosubscribeComment', NULL, NULL, 0), ('teacher_autosubscribe', NULL, 'textfield', 'Platform', '', 'TeacherAutosubscribeTitle', 'TeacherAutosubscribeComment', NULL, NULL, 0), ('drh_autosubscribe', NULL, 'textfield', 'Platform', '', 'DRHAutosubscribeTitle', 'DRHAutosubscribeComment', NULL, NULL, 0), ('sessionadmin_autosubscribe', NULL, 'textfield', 'Session', '', 'SessionadminAutosubscribeTitle', 'SessionadminAutosubscribeComment', NULL, NULL, 0), ('show_tabs', 'custom_tab_1', 'checkbox', 'Platform', 'true', 'ShowTabsTitle', 'ShowTabsComment', NULL, 'TabsCustom1', 1), ('show_tabs', 'custom_tab_2', 'checkbox', 'Platform', 'false', 'ShowTabsTitle', 'ShowTabsComment', NULL, 'TabsCustom2', 1), ('show_tabs', 'custom_tab_3', 'checkbox', 'Platform', 'false', 'ShowTabsTitle', 'ShowTabsComment', NULL, 'TabsCustom3', 1), ('languagePriority1', NULL, 'radio', 'Languages', 'course_lang', 'LanguagePriority1Title', 'LanguagePriority1Comment', NULL, NULL, 0), ('languagePriority2', NULL, 'radio', 'Languages', 'user_profil_lang', 'LanguagePriority2Title', 'LanguagePriority2Comment', NULL, NULL, 0), ('languagePriority3', NULL, 'radio', 'Languages', 'user_selected_lang', 'LanguagePriority3Title', 'LanguagePriority3Comment', NULL, NULL, 0), ('languagePriority4', NULL, 'radio', 'Languages', 'platform_lang', 'LanguagePriority4Title', 'LanguagePriority4Comment', NULL, NULL, 0); - -INSERT INTO settings_options (variable, value, display_text) VALUES ('languagePriority1','platform_lang','PlatformLanguage'), ('languagePriority1','user_profil_lang','UserLanguage'), ('languagePriority1','user_selected_lang','UserSelectedLanguage'), ('languagePriority1','course_lang','CourseLanguage'), ('languagePriority2','platform_lang','PlatformLanguage'), ('languagePriority2','user_profil_lang','UserLanguage'), ('languagePriority2','user_selected_lang','UserSelectedLanguage'), ('languagePriority2','course_lang','CourseLanguage'), ('languagePriority3','platform_lang','PlatformLanguage'), ('languagePriority3','user_profil_lang','UserLanguage'), ('languagePriority3','user_selected_lang','UserSelectedLanguage'), ('languagePriority3','course_lang','CourseLanguage'), ('languagePriority4','platform_lang','PlatformLanguage'), ('languagePriority4','user_profil_lang','UserLanguage'), ('languagePriority4','user_selected_lang','UserSelectedLanguage'), ('languagePriority4','course_lang','CourseLanguage'), ('login_is_email', NULL, 'radio', 'Platform', 'false', 'LoginIsEmailTitle', 'LoginIsEmailComment', NULL, NULL, 0), ('scorm_cumulative_session_time', NULL, 'radio', 'Course', 'true', 'ScormCumulativeSessionTimeTitle', 'ScormCumulativeSessionTimeComment', NULL, NULL, 0), ('login_is_email','true','Yes'),('login_is_email','false','No'), ('scorm_cumulative_session_time','true','Yes'), ('scorm_cumulative_session_time','false','No'); - - - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('gradebook_enable_grade_model', NULL, 'radio', 'Gradebook', 'false', 'GradebookEnableGradeModelTitle', 'GradebookEnableGradeModelComment', NULL, NULL, 1), ('teachers_can_change_grade_model_settings', NULL, 'radio', 'Gradebook', 'true', 'TeachersCanChangeGradeModelSettingsTitle', 'TeachersCanChangeGradeModelSettingsComment', NULL, NULL, 1), ('gradebook_locking_enabled', NULL, 'radio', 'Gradebook', 'false', 'GradebookEnableLockingTitle', 'GradebookEnableLockingComment', NULL, NULL, 0), ('teachers_can_change_score_settings', NULL, 'radio', 'Gradebook', 'true', 'TeachersCanChangeScoreSettingsTitle', 'TeachersCanChangeScoreSettingsComment', NULL, NULL, 1), ('allow_users_to_change_email_with_no_password', NULL, 'radio', 'User', 'false', 'AllowUsersToChangeEmailWithNoPasswordTitle', 'AllowUsersToChangeEmailWithNoPasswordComment', NULL, NULL, 0), ('allow_session_admins_to_manage_all_sessions', NULL, 'radio', 'Session', 'false', 'AllowSessionAdminsToSeeAllSessionsTitle', 'AllowSessionAdminsToSeeAllSessionsComment', NULL, NULL, 1), ('shibboleth_description', NULL, 'radio', 'Shibboleth', 'false', 'ShibbolethMainActivateTitle', 'ShibbolethMainActivateComment', NULL, NULL, 0), ('facebook_description', NULL, 'radio', 'Facebook', 'false', 'FacebookMainActivateTitle', 'FacebookMainActivateComment', NULL, NULL, 0), ('ldap_description', NULL, 'radio', 'LDAP', NULL, 'LdapDescriptionTitle', 'LdapDescriptionComment', NULL, NULL, 0), ('enable_help_link', NULL, 'radio', 'Platform', 'true', 'EnableHelpLinkTitle', 'EnableHelpLinkComment', NULL, NULL, 0), ('allow_hr_skills_management', NULL, 'radio', 'Gradebook', 'true', 'AllowHRSkillsManagementTitle', 'AllowHRSkillsManagementComment', NULL, NULL, 1); - -INSERT INTO settings_options (variable, value, display_text) VALUES ('gradebook_enable_grade_model', 'true', 'Yes'), ('gradebook_enable_grade_model', 'false', 'No'), ('teachers_can_change_grade_model_settings', 'true', 'Yes'), ('teachers_can_change_grade_model_settings', 'false', 'No'), ('gradebook_locking_enabled', 'true', 'Yes'), ('gradebook_locking_enabled', 'false', 'No'), ('teachers_can_change_score_settings', 'true', 'Yes'), ('teachers_can_change_score_settings', 'false', 'No'), ('allow_users_to_change_email_with_no_password', 'true', 'Yes'), ('allow_users_to_change_email_with_no_password', 'false', 'No'), ('allow_session_admins_to_manage_all_sessions', 'true', 'Yes'), ('allow_session_admins_to_manage_all_sessions', 'false', 'No'), ('enable_help_link', 'true', 'Yes'), (variable, value, display_text) VALUES ('enable_help_link', 'false', 'No'), ('allow_hr_skills_management', 'true', 'Yes'), ('allow_hr_skills_management', 'false', 'No'); - - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_admin_toolbar', NULL, 'radio', 'Platform', 'show_to_admin', 'ShowAdminToolbarTitle', 'ShowAdminToolbarComment', NULL, NULL, 1), ('allow_global_chat', NULL, 'radio', 'Platform', 'true', 'AllowGlobalChatTitle', 'AllowGlobalChatComment', NULL, NULL, 1), ('courses_default_creation_visibility', NULL, 'radio', 'Course', '2', 'CoursesDefaultCreationVisibilityTitle', 'CoursesDefaultCreationVisibilityComment', NULL, NULL, 1), ('allow_browser_sniffer', NULL, 'radio', 'Tuning', 'false', 'AllowBrowserSnifferTitle', 'AllowBrowserSnifferComment', NULL, NULL, 0), ('enable_wami_record', NULL, 'radio', 'Tools', 'false', 'EnableWamiRecordTitle', 'EnableWamiRecordComment', NULL, NULL, 0), ('allow_public_certificates', NULL, 'radio', 'Course', 'false', 'AllowPublicCertificatesTitle', 'AllowPublicCertificatesComment', NULL, NULL, 1), ('enable_iframe_inclusion', NULL, 'radio', 'Editor', 'false', 'EnableIframeInclusionTitle', 'EnableIframeInclusionComment', NULL, NULL, 1); - -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_admin_toolbar', 'do_not_show', 'DoNotShow'), ('show_admin_toolbar', 'show_to_admin', 'ShowToAdminsOnly'), ('show_admin_toolbar', 'show_to_admin_and_teachers', 'ShowToAdminsAndTeachers'), ('show_admin_toolbar', 'show_to_all', 'ShowToAllUsers'), ('allow_global_chat', 'true', 'Yes'), ('allow_global_chat', 'false', 'No'), ('courses_default_creation_visibility', '3', 'OpenToTheWorld'), ('courses_default_creation_visibility', '2', 'OpenToThePlatform'), ('courses_default_creation_visibility', '1', 'Private'), ('courses_default_creation_visibility', '0', 'CourseVisibilityClosed'), ('allow_browser_sniffer', 'true', 'Yes'), ('allow_browser_sniffer', 'false', 'No'), ('enable_wami_record', 'true', 'Yes'), ('enable_wami_record', 'false', 'No'), ('allow_public_certificates', 'true', 'Yes'), ('allow_public_certificates', 'false', 'No'), ('enable_iframe_inclusion', 'true', 'Yes'), ('enable_iframe_inclusion', 'false', 'No'); - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_hot_courses', NULL, 'radio', 'Platform', 'true', 'ShowHotCoursesTitle', 'ShowHotCoursesComment', NULL, NULL, 1), ('gradebook_default_weight', NULL, 'textfield', 'Gradebook', '100', 'GradebookDefaultWeightTitle', 'GradebookDefaultWeightComment', NULL, NULL, 1), ('gradebook_default_grade_model_id', NULL, 'select', 'Gradebook', '', 'GradebookDefaultGradeModelTitle', 'GradebookDefaultGradeModelComment', NULL, NULL, 1); - -UPDATE settings_current SET category = 'Session' WHERE variable IN ('show_tutor_data', 'use_session_mode', 'add_users_by_coach', 'show_session_coach', 'show_session_data', 'allow_coach_to_edit_course_session','hide_courses_in_sessions', 'show_groups_to_users'); - - -INSERT INTO language (original_name, english_name, isocode, dokeos_folder, available) VALUES ('বাংলা','bengali','bn','bengali',0), ('الصومالية','somali','so','somali',0); - - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('enable_webcam_clip', NULL, 'radio', 'Tools', 'false', 'EnableWebCamClipTitle', 'EnableWebCamClipComment', NULL, NULL, 0), ('tool_visible_by_default_at_creation','documents','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Documents', 1), ('tool_visible_by_default_at_creation','learning_path','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'LearningPath', 1), ('tool_visible_by_default_at_creation','links','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Links', 1), ('tool_visible_by_default_at_creation','announcements','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Announcements', 1), ('tool_visible_by_default_at_creation','forums','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Forums', 1), ('tool_visible_by_default_at_creation','quiz','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Quiz', 1), ('tool_visible_by_default_at_creation','gradebook','checkbox','Tools','true','ToolVisibleByDefaultAtCreationTitle','ToolVisibleByDefaultAtCreationComment',NULL,'Gradebook', 1), ('activate_email_template', NULL, 'radio', 'Platform', 'false', 'ActivateEmailTemplateTitle', 'ActivateEmailTemplateComment', NULL, NULL, 0); - -UPDATE settings_current SET title = 'DatabaseVersion' WHERE variable = 'chamilo_database_version'; -UPDATE settings_current SET selected_value = 'true' WHERE variable = 'more_buttons_maximized_mode'; - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_skills_tool', NULL, 'radio', 'Platform', 'false', 'AllowSkillsToolTitle', 'AllowSkillsToolComment', NULL, NULL, 1); - -INSERT INTO settings_options (variable, value, display_text) VALUES ('show_hot_courses', 'true', 'Yes'), ('show_hot_courses', 'false', 'No'), ('enable_webcam_clip', 'true', 'Yes'), ('enable_webcam_clip', 'false', 'No'), ('page_after_login', 'main/auth/courses.php', 'CourseCatalog'), ('activate_email_template', 'true', 'Yes'),('activate_email_template', 'false', 'No'), ('allow_skills_tool', 'true', 'Yes'), ('allow_skills_tool', 'false', 'No'); - -INSERT INTO skill (name) VALUES ('Root'); -INSERT INTO skill_rel_skill VALUES(1, 1, 0, 0, 0); - -DELETE FROM settings_current WHERE variable = 'use_document_title'; -DELETE FROM settings_options WHERE variable = 'use_document_title'; - -UPDATE language SET english_name = 'basque' , dokeos_folder = 'basque' where english_name = 'euskera'; -UPDATE language SET english_name = 'turkish', dokeos_folder = 'turkish' where english_name = 'turkce'; - -INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES('platform_unsubscribe_allowed', NULL, 'radio', 'Platform', 'false', 'PlatformUnsubscribeTitle', 'PlatformUnsubscribeComment', NULL, NULL, 1); - -INSERT INTO settings_options (variable, value, display_text) values ('platform_unsubscribe_allowed', 'true', 'Yes'), ('platform_unsubscribe_allowed', 'false', 'No'); - -INSERT INTO course_type (id, name) VALUES (1, 'All tools'); -INSERT INTO course_type (id, name) VALUES (2, 'Entry exam'); - -DELETE FROM settings_current WHERE variable = 'read_more_limit'; -DELETE FROM settings_current WHERE variable = 'user_order_by'; -DELETE FROM settings_options WHERE variable = 'user_order_by'; - - --- Do not move this query -UPDATE settings_current SET selected_value = '1.9.0.18715b' WHERE variable = 'chamilo_database_version'; - --- xxSTATSxx - --- xxUSERxx - --- xxCOURSExx - -CREATE TABLE IF NOT EXISTS metadata (c_id INT NOT NULL, eid VARCHAR(250) NOT NULL, mdxmltext TEXT default '', md5 CHAR(32) default '', htmlcache1 TEXT default '', htmlcache2 TEXT default '', indexabletext TEXT default '', PRIMARY KEY (c_id, eid)) -ALTER TABLE lp ADD COLUMN hide_toc_frame INT NOT NULL DEFAULT 0; -ALTER TABLE lp ADD COLUMN seriousgame_mode INT NOT NULL DEFAULT 0; -ALTER TABLE lp_item_view modify column suspend_data longtext; -ALTER TABLE quiz ADD COLUMN review_answers INT NOT NULL DEFAULT 0; -ALTER TABLE student_publication ADD COLUMN contains_file INTEGER NOT NULL DEFAULT 1; -ALTER TABLE student_publication ADD COLUMN allow_text_assignment INTEGER NOT NULL DEFAULT 0; -ALTER TABLE quiz ADD COLUMN random_by_category INT NOT NULL DEFAULT 0; -ALTER TABLE quiz ADD COLUMN text_when_finished TEXT DEFAULT NULL; -ALTER TABLE quiz ADD COLUMN display_category_name INT NOT NULL DEFAULT 1; -ALTER TABLE quiz ADD COLUMN pass_percentage INT DEFAULT NULL; -ALTER TABLE quiz_answer ADD COLUMN answer_code char(10) default ''; -ALTER TABLE quiz_question ADD COLUMN question_code char(10) default ''; -INSERT INTO course_setting(variable,value,category) VALUES ('allow_public_certificates', 0, 'certificates'); diff --git a/main/install/update-db-1.6.x-1.8.0.inc.php b/main/install/update-db-1.6.x-1.8.0.inc.php deleted file mode 100755 index ae03098edf..0000000000 --- a/main/install/update-db-1.6.x-1.8.0.inc.php +++ /dev/null @@ -1,538 +0,0 @@ -' . get_lang('Error') . ' ! Dokeos ' . implode('|', $updateFromVersion) . ' ' . get_lang('HasNotBeenFound') . '.

- ' . get_lang('PleasGoBackToStep1') . '. -

- '; - exit(); - } - - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - - $dbScormForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbScormForm); - - if (!empty($dbPrefixForm) && strpos($dbScormForm, $dbPrefixForm) !== 0) { - $dbScormForm = $dbPrefixForm . $dbScormForm; - } - - if (empty($dbScormForm) || $dbScormForm == 'mysql' || $dbScormForm == $dbPrefixForm) { - $dbScormForm = $dbPrefixForm . 'scorm'; - } - - /* Normal upgrade procedure: start by updating main, statistic, user databases */ - - // If this script has been included by index.php, not update_courses.php, so - // that we want to change the main databases as well... - $only_test = false; - $log = 0; - - if (defined('SYSTEM_INSTALLATION')) { - - if ($singleDbForm) { - if (empty($dbStatsForm)) - $dbStatsForm = $dbNameForm; - if (empty($dbScormForm)) - $dbScormForm = $dbNameForm; - if (empty($dbUserForm)) - $dbUserForm = $dbNameForm; - } - /** - * Update the databases "pre" migration - */ - include_once '../lang/english/trad4all.inc.php'; - - if ($languageForm != 'english') { - // languageForm has been escaped in index.php - include_once '../lang/' . $languageForm . '/trad4all.inc.php'; - } - - //get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-1.6.x-1.8.0-pre.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - error_log('Database name ' . $dbNameForm . ' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database ' . $dbNameForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbNameForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbNameForm, executed: $query", 0); - } - } - } - } - } - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-1.6.x-1.8.0-pre.sql', 'stats'); - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - error_log('Database name ' . $dbStatsForm . ' is too long, skipping', 0); - } elseif (!in_array($dbStatsForm, $dblist)) { - error_log('Database ' . $dbStatsForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbStatsForm); - foreach ($s_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbStatsForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbStatsForm, executed: $query", 0); - } - } - } - } - } - - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-1.6.x-1.8.0-pre.sql', 'user'); - if (count($u_q_list) > 0) { - // Now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - error_log('Database name ' . $dbUserForm . ' is too long, skipping', 0); - } elseif (!in_array($dbUserForm, $dblist)) { - error_log('Database ' . $dbUserForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbUserForm); - foreach ($u_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbUserForm,$query)", 0); - error_log("In $dbUserForm, executed: $query", 0); - } else { - $res = Database::query($query); - } - } - } - } - // The SCORM database doesn't need a change in the pre-migrate part - ignore. - } - - $prefix = ''; - if ($singleDbForm) { - $prefix = $_configuration['table_prefix']; - } - - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-1.6.x-1.8.0-pre.sql', 'course'); - if (count($c_q_list) > 0) { - - // Get the courses list - if (strlen($dbNameForm) > 40) { - error_log('Database name ' . $dbNameForm . ' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database ' . $dbNameForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - $res = Database::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL"); - if ($res === false) { - die('Error while querying the courses list in update_db-1.6.x-1.8.0.inc.php'); - } - if (Database::num_rows($res) > 0) { - $i = 0; - $list = array(); - while ($row = Database::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row_course) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (!$singleDbForm) { // otherwise just use the main one - Database::select_db($row_course['db_name']); - } - - foreach ($c_q_list as $query) { - if ($singleDbForm) { - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query); - } - - if ($only_test) { - error_log("Database::query(" . $row_course['db_name'] . ",$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In " . $row_course['db_name'] . ", executed: $query", 0); - } - } - } - - // Prepare reusable users list to avoid repetition of the SQL query, but only select - // users from the current course to avoid blowing the memory limit - $users_list = array(); - $sql_uc = "SELECT u.user_id as ui, u.firstname as fn, u.lastname as ln " . - " FROM $dbNameForm.user u, $dbNameForm.course_rel_user cu " . - " WHERE cu.course_code = '" . $row_course['code'] . "' " . - " AND u.user_id = cu.user_id"; - $res_uc = Database::query($sql_uc); - while ($user_row = Database::fetch_array($res_uc)) { - $users_list[$user_row['fn'] . ' ' . $user_row['ln']] = $user_row['ui']; - } - - // Update course manually - // Update group_category.forum_state ? - // Update group_info.tutor_id (put it in group_tutor table?) ? - // Update group_info.forum_state, forum_id ? - // Update forum tables (migrate from bb_ tables to forum_ tables) - // Migrate categories - $prefix_course = $prefix; - if ($singleDbForm) { - $prefix_course = $prefix . $row_course['db_name'] . "_"; - } - - $sql_orig = "SELECT * FROM " . $prefix_course . "bb_categories"; - $res_orig = Database::query($sql_orig); - $order = 1; - while ($row = Database::fetch_array($res_orig)) { - $myorder = (empty($row['cat_order']) ? $order : $row['cat_order']); - $sql = "INSERT INTO " . $prefix_course . "forum_category " . - "(cat_id,cat_title,cat_comment,cat_order,locked) VALUES " . - "('" . $row['cat_id'] . "','" . Database::escape_string($row['cat_title']) . "','','" . $myorder . "',0)"; - $res = Database::query($sql); - $lastcatid = Database::insert_id(); - //error_log($sql,0); - $order++; - // Add item_property - forum categories were not put into item_properties before - $sql = "INSERT INTO " . $prefix_course . "item_property (tool,insert_user_id,ref,lastedit_type,lastedit_user_id,visibility) " . - "VALUES ('forum_category','1','$lastcatid','ForumCategoryAdded','1','1')"; - $res = Database::query($sql); - //error_log($sql,0); - } - - $sql_orig = "SELECT * FROM " . $prefix_course . "bb_forums ORDER BY forum_last_post_id desc"; - $res_orig = Database::query($sql_orig); - $order = 1; - while ($row = Database::fetch_array($res_orig)) { - $sql = "INSERT INTO " . $prefix_course . "forum_forum " . - "(forum_id,forum_category,allow_edit,forum_comment," . - "forum_title," . - "forum_last_post, forum_threads," . - "locked, forum_posts, " . - "allow_new_threads, forum_order) VALUES " . - "('" . $row['forum_id'] . "','" . $row['cat_id'] . "',1,'" . Database::escape_string($row['forum_desc']) . "'," . - "'" . Database::escape_string($row['forum_name']) . "'," . - "'" . $row['forum_last_post_id'] . "','" . $row['forum_topics'] . "'," . - "0,'" . $row['forum_posts'] . "'," . - "1,$order)"; - //error_log($sql,0); - $res = Database::query($sql); - $lastforumid = Database::insert_id(); - $order++; - - // Add item_property - forums were not put into item_properties before - $sql = "INSERT INTO " . $prefix_course . "item_property (tool,insert_user_id,ref,lastedit_type,lastedit_user_id,visibility) " . - "VALUES ('forum','1','$lastforumid','ForumAdded','1','1')"; - $res = Database::query($sql); - //error_log($sql,0); - } - - $sql_orig = "SELECT * FROM " . $prefix_course . "bb_topics"; - $res_orig = Database::query($sql_orig); - while ($row = Database::fetch_array($res_orig)) { - $name = $row['prenom'] . ' ' . $row['nom']; - // Check whether user id is reusable - if ($row['topic_poster'] <= 1) { - if (isset($users_list[$name])) { - $poster_id = $users_list[$name]; - } else { - $poster_id = $row['topic_poster']; - } - } - // Convert time from varchar to datetime - $time = $row['topic_time']; - $name = Database::escape_string($name); - $sql = "INSERT INTO " . $prefix_course . "forum_thread " . - "(thread_id,forum_id,thread_poster_id," . - "locked,thread_replies,thread_sticky,thread_title," . - "thread_poster_name, thread_date, thread_last_post," . - "thread_views) VALUES " . - "('" . $row['topic_id'] . "','" . $row['forum_id'] . "','" . $poster_id . "'," . - "0,'" . $row['topic_replies'] . "',0,'" . Database::escape_string($row['topic_title']) . "'," . - "'$name','$time','" . $row['topic_last_post_id'] . "'," . - "'" . $row['topic_views'] . "')"; - //error_log($sql,0); - $res = Database::query($sql); - $lastthreadid = Database::insert_id(); - - // Add item_property - forum threads were not put into item_properties before - $sql = "INSERT INTO " . $prefix_course . "item_property (tool,insert_user_id,ref,lastedit_type,lastedit_user_id,visibility) " . - "VALUES ('forum_thread','1','$lastthreadid','ForumThreadAdded','1','1')"; - $res = Database::query($sql); - //error_log($sql,0); - } - - $sql_orig = "SELECT * FROM " . $prefix_course . "bb_posts bp, " . $prefix_course . "bb_posts_text bpt WHERE bp.post_id = bpt.post_id"; - $res_orig = Database::query($sql_orig); - while ($row = Database::fetch_array($res_orig)) { - $name = $row['prenom'] . ' ' . $row['nom']; - // Check whether user id is reusable - if ($row['poster_id'] <= 0) { - if (isset($users_list[$name])) { - $poster_id = $users_list[$name]; - } else { - $poster_id = $row['poster_id']; - } - } - // Convert time from varchar to datetime - $time = $row['post_time']; - $name = Database::escape_string($name); - $sql = "INSERT INTO " . $prefix_course . "forum_post " . - "(post_id,forum_id,thread_id," . - "poster_id,post_parent_id,visible, " . - "post_title,poster_name, post_text, " . - "post_date, post_notification) VALUES " . - "('" . $row['post_id'] . "','" . $row['forum_id'] . "','" . $row['topic_id'] . "'," . - "'" . $poster_id . "','" . $row['parent_id'] . "',1," . - "'" . Database::escape_string($row['post_title']) . "','$name', '" . Database::escape_string($row['post_text']) . "'," . - "'$time',0)"; - //error_log($sql,0); - $res = Database::query($sql); - $lastpostid = Database::insert_id(); - - // Add item_property - forum threads were not put into item_properties before - $sql = "INSERT INTO " . $prefix_course . "item_property(tool,insert_user_id,ref,lastedit_type,lastedit_user_id,visibility) " . - "VALUES ('forum_post','1','$lastpostid','ForumPostAdded','1','1')"; - $res = Database::query($sql); - //error_log($sql,0); - } - unset($users_list); - - $sql_orig = "SELECT id, tutor_id FROM " . $prefix_course . "group_info"; - $res_orig = Database::query($sql_orig); - $order = 1; - while ($row = Database::fetch_array($res_orig)) { - $sql = "INSERT INTO " . $prefix_course . "group_rel_tutor " . - "(user_id,group_id) VALUES " . - "('" . $row['tutor_id'] . "','" . $row['id'] . "')"; - $res = Database::query($sql); - } - } - } - } - } - - // Load the old-scorm to new-scorm migration script - if (!$only_test) { - include('update-db-scorm-1.6.x-1.8.0.inc.php'); - } - if (defined('SYSTEM_INSTALLATION')) { - if ($singleDbForm) { - if (empty($dbStatsForm)) - $dbStatsForm = $dbNameForm; - if (empty($dbScormForm)) - $dbScormForm = $dbNameForm; - if (empty($dbUserForm)) - $dbUserForm = $dbNameForm; - } - // Deal with migrate-db-1.6.x-1.8.0-post.sql - // Get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-1.6.x-1.8.0-post.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - error_log('Database name ' . $dbNameForm . ' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database ' . $dbNameForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbNameForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbNameForm, executed: $query", 0); - } - } - } - } - } - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-1.6.x-1.8.0-post.sql', 'stats'); - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - error_log('Database name ' . $dbStatsForm . ' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database ' . $dbNameForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbStatsForm); - foreach ($s_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbStatsForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbStatsForm, executed: $query", 0); - } - } - } - } - } - - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-1.6.x-1.8.0-post.sql', 'user'); - if (count($u_q_list) > 0) { - //now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - error_log('Database name ' . $dbUserForm . ' is too long, skipping', 0); - } elseif (!in_array($dbUserForm, $dblist)) { - error_log('Database ' . $dbUserForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbUserForm); - foreach ($u_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbUserForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbUserForm, executed: $query", 0); - } - } - } - } - } - // The SCORM database should need a drop in the post-migrate part. However, we will keep these tables a bit more, just in case... - } - - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-1.6.x-1.8.0-post.sql', 'course'); - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - error_log('Database name ' . $dbNameForm . ' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database ' . $dbNameForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - $res = Database::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL"); - if ($res === false) { - die('Error while querying the courses list in update_db-1.6.x-1.8.0.inc.php'); - } - if (Database::num_rows($res) > 0) { - $i = 0; - while ($row = Database::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - $prefix_course = $prefix; - if ($singleDbForm) { - $prefix_course = $prefix . $row['db_name'] . "_"; - } else { - Database::select_db($row['db_name']); - } - - foreach ($c_q_list as $query) { - if ($singleDbForm) { //otherwise just use the main one - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix$2$3", $query); - } - if ($only_test) { - error_log("Database::query(" . $row['db_name'] . ",$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In " . $row['db_name'] . ", executed: $query", 0); - } - } - } - } - } - } - } - - // Upgrade user categories sort - $table_user_categories = $dbUserForm . '.user_course_category'; - - $sql = 'SELECT * FROM ' . $table_user_categories . ' ORDER BY user_id, title'; - $rs = Database::query($sql); - - $sort = 0; - $old_user = 0; - while ($cat = Database::fetch_array($rs)) { - if ($old_user != $cat['user_id']) { - $old_user = $cat['user_id']; - $sort = 0; - } - $sort++; - $sql = 'UPDATE ' . $table_user_categories . ' SET - sort = ' . intval($sort) . ' - WHERE id=' . intval($cat['id']); - Database::query($sql); - } -} else { - - echo 'You are not allowed here !' . __FILE__; -} diff --git a/main/install/update-db-1.8.0-1.8.2.inc.php b/main/install/update-db-1.8.0-1.8.2.inc.php deleted file mode 100755 index 99c9ec6faf..0000000000 --- a/main/install/update-db-1.8.0-1.8.2.inc.php +++ /dev/null @@ -1,212 +0,0 @@ -' . get_lang('Error') . ' ! Dokeos ' . implode('|', $updateFromVersion) . ' ' . get_lang('HasNotBeenFound') . '.

- ' . get_lang('PleasGoBackToStep1') . '. -

- '; - exit(); - } - - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - - $dbScormForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbScormForm); - - if (!empty($dbPrefixForm) && strpos($dbScormForm, $dbPrefixForm) !== 0) { - $dbScormForm = $dbPrefixForm . $dbScormForm; - } - - if (empty($dbScormForm) || $dbScormForm == 'mysql' || $dbScormForm == $dbPrefixForm) { - $dbScormForm = $dbPrefixForm . 'scorm'; - } - - /* Normal upgrade procedure: start by updating main, statistic, user databases */ - - // If this script has been included by index.php, not update_courses.php, so - // that we want to change the main databases as well... - $only_test = false; - $log = 0; - if (defined('SYSTEM_INSTALLATION')) { - if ($singleDbForm) { - $dbStatsForm = $dbNameForm; - $dbScormForm = $dbNameForm; - $dbUserForm = $dbNameForm; - } - /** - * Update the databases "pre" migration - */ - include_once '../lang/english/trad4all.inc.php'; - - if ($languageForm != 'english') { - //languageForm has been escaped in index.php - include_once '../lang/' . $languageForm . '/trad4all.inc.php'; - } - - // Get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-1.8.0-1.8.2-pre.sql', 'main'); - if (count($m_q_list) > 0) { - //now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - error_log('Database name ' . $dbNameForm . ' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database ' . $dbNameForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbNameForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbNameForm, executed: $query", 0); - } - } - } - } - } - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-1.8.0-1.8.2-pre.sql', 'stats'); - - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - error_log('Database name ' . $dbStatsForm . ' is too long, skipping', 0); - } elseif (!in_array($dbStatsForm, $dblist)) { - error_log('Database ' . $dbStatsForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbStatsForm); - foreach ($s_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbStatsForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbStatsForm, executed: $query", 0); - } - } - } - } - } - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-1.8.0-1.8.2-pre.sql', 'user'); - if (count($u_q_list) > 0) { - //now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - error_log('Database name ' . $dbUserForm . ' is too long, skipping', 0); - } elseif (!in_array($dbUserForm, $dblist)) { - error_log('Database ' . $dbUserForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbUserForm); - foreach ($u_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbUserForm,$query)", 0); - error_log("In $dbUserForm, executed: $query", 0); - } else { - $res = Database::query($query); - } - } - } - } - // The SCORM database doesn't need a change in the pre-migrate part - ignore - } - - $prefix = ''; - if ($singleDbForm) { - $prefix = $_configuration['table_prefix']; - } - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-1.8.0-1.8.2-pre.sql', 'course'); - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - error_log('Database name ' . $dbNameForm . ' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database ' . $dbNameForm . ' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - $res = Database::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL"); - if ($res === false) { - die('Error while querying the courses list in update_db-1.8.0-1.8.2.inc.php'); - } - if (Database::num_rows($res) > 0) { - $i = 0; - $list = array(); - while ($row = Database::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row_course) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (!$singleDbForm) { // otherwise just use the main one - Database::select_db($row_course['db_name']); - } - Log::notice('Course db ' . $row_course['db_name']); - - foreach ($c_q_list as $query) { - if ($singleDbForm) { - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query); - } - - if ($only_test) { - error_log("Database::query(" . $row_course['db_name'] . ",$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In " . $row_course['db_name'] . ", executed: $query", 0); - } - } - } - } - } - } - } -} else { - - echo 'You are not allowed here !' . __FILE__; -} diff --git a/main/install/update-db-1.8.2-1.8.3.inc.php b/main/install/update-db-1.8.2-1.8.3.inc.php deleted file mode 100755 index 126698e781..0000000000 --- a/main/install/update-db-1.8.2-1.8.3.inc.php +++ /dev/null @@ -1,212 +0,0 @@ -'.get_lang('Error').' ! Dokeos '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.

- '.get_lang('PleasGoBackToStep1').'. -

- '; - exit (); - } - - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - - $dbScormForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbScormForm); - - if (!empty($dbPrefixForm) && strpos($dbScormForm, $dbPrefixForm) !== 0) { - $dbScormForm = $dbPrefixForm.$dbScormForm; - } - - if (empty($dbScormForm) || $dbScormForm == 'mysql' || $dbScormForm == $dbPrefixForm) { - $dbScormForm = $dbPrefixForm.'scorm'; - } - - /* Normal upgrade procedure: start by updating main, statistic, user databases */ - - // If this script has been included by index.php, not update_courses.php, so - // that we want to change the main databases as well... - $only_test = false; - $log = 0; - if (defined('SYSTEM_INSTALLATION')) { - - if ($singleDbForm) { - $dbStatsForm = $dbNameForm; - $dbScormForm = $dbNameForm; - $dbUserForm = $dbNameForm; - } - /** - * Update the databases "pre" migration - */ - include_once '../lang/english/trad4all.inc.php'; - - if ($languageForm != 'english') { - // languageForm has been escaped in index.php - include_once '../lang/'.$languageForm.'/trad4all.inc.php'; - } - - // get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-1.8.2-1.8.3-pre.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - error_log('Database name '.$dbNameForm.' is too long, skipping', 0); - } elseif (!in_array($dbNameForm,$dblist)) { - error_log('Database '.$dbNameForm.' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbNameForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbNameForm, executed: $query", 0); - } - } - } - } - } - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-1.8.2-1.8.3-pre.sql', 'stats'); - - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - error_log('Database name '.$dbStatsForm.' is too long, skipping', 0); - } elseif (!in_array($dbStatsForm, $dblist)) { - error_log('Database '.$dbStatsForm.' was not found, skipping', 0); - } else { - Database::select_db($dbStatsForm); - foreach ($s_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbStatsForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbStatsForm, executed: $query", 0); - } - } - } - } - } - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-1.8.2-1.8.3-pre.sql', 'user'); - if (count($u_q_list) > 0) { - // Now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - error_log('Database name '.$dbUserForm.' is too long, skipping', 0); - } elseif (!in_array($dbUserForm, $dblist)) { - error_log('Database '.$dbUserForm.' was not found, skipping', 0); - } else { - Database::select_db($dbUserForm); - foreach ($u_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbUserForm, $query)", 0); - error_log("In $dbUserForm, executed: $query", 0); - } else { - $res = Database::query($query); - } - } - } - } - // The SCORM database doesn't need a change in the pre-migrate part - ignore - } - - $prefix = ''; - if ($singleDbForm) { - $prefix = $_configuration['table_prefix']; - } - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-1.8.2-1.8.3-pre.sql', 'course'); - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - error_log('Database name '.$dbNameForm.' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database '.$dbNameForm.' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - $res = Database::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL"); - if ($res === false) { die('Error while querying the courses list in update_db-1.8.2-1.8.3.inc.php'); } - if (Database::num_rows($res) > 0) { - $i = 0; - $list = array(); - while ($row = Database::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row_course) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (!$singleDbForm) { //otherwise just use the main one - Database::select_db($row_course['db_name']); - } - Log::notice('Course db ' . $row_course['db_name']); - - foreach ($c_q_list as $query) { - if ($singleDbForm) { //otherwise just use the main one - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query); - } - - if ($only_test) { - error_log("Database::query(".$row_course['db_name'].",$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In ".$row_course['db_name'].", executed: $query", 0); - } - } - } - } - } - } - } - -} else { - - echo 'You are not allowed here !' . __FILE__; - -} diff --git a/main/install/update-db-1.8.3-1.8.4.inc.php b/main/install/update-db-1.8.3-1.8.4.inc.php deleted file mode 100755 index b180aac379..0000000000 --- a/main/install/update-db-1.8.3-1.8.4.inc.php +++ /dev/null @@ -1,265 +0,0 @@ -'.get_lang('Error').' ! Dokeos '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.

- '.get_lang('PleasGoBackToStep1').'. -

- '; - exit (); - } - - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - - $dbScormForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbScormForm); - - if (!empty($dbPrefixForm) && strpos($dbScormForm, $dbPrefixForm) !== 0) { - $dbScormForm = $dbPrefixForm.$dbScormForm; - } - - if (empty($dbScormForm) || $dbScormForm == 'mysql' || $dbScormForm == $dbPrefixForm) { - $dbScormForm = $dbPrefixForm.'scorm'; - } - - /* Normal upgrade procedure: start by updating main, statistic, user databases */ - - // If this script has been included by index.php, not update_courses.php, so - // that we want to change the main databases as well... - $only_test = false; - $log = 0; - if (defined('SYSTEM_INSTALLATION')) { - - if ($singleDbForm) { - $dbStatsForm = $dbNameForm; - $dbScormForm = $dbNameForm; - $dbUserForm = $dbNameForm; - } - /** - * Update the databases "pre" migration - */ - include_once '../lang/english/trad4all.inc.php'; - - if ($languageForm != 'english') { - // languageForm has been escaped in index.php - include_once '../lang/'.$languageForm.'/trad4all.inc.php'; - } - - //get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-1.8.3-1.8.4-pre.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - error_log('Database name '.$dbNameForm.' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database '.$dbNameForm.' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbNameForm, $query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbNameForm, executed: $query", 0); - } - } - } - } - } - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-1.8.3-1.8.4-pre.sql', 'stats'); - - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - error_log('Database name '.$dbStatsForm.' is too long, skipping', 0); - } elseif (!in_array($dbStatsForm, $dblist)) { - error_log('Database '.$dbStatsForm.' was not found, skipping', 0); - } else { - Database::select_db($dbStatsForm); - foreach ($s_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbStatsForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbStatsForm, executed: $query", 0); - } - } - } - } - } - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-1.8.3-1.8.4-pre.sql', 'user'); - if (count($u_q_list) > 0) { - // Now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - error_log('Database name '.$dbUserForm.' is too long, skipping', 0); - } elseif (!in_array($dbUserForm, $dblist)){ - error_log('Database '.$dbUserForm.' was not found, skipping', 0); - } else { - Database::select_db($dbUserForm); - foreach ($u_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbUserForm,$query)", 0); - error_log("In $dbUserForm, executed: $query", 0); - } else { - $res = Database::query($query); - } - } - } - } - // The SCORM database doesn't need a change in the pre-migrate part - ignore - } - - $prefix = ''; - if ($singleDbForm) { - $prefix = $_configuration['table_prefix']; - } - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-1.8.3-1.8.4-pre.sql', 'course'); - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - error_log('Database name '.$dbNameForm.' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database '.$dbNameForm.' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - $res = Database::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL"); - if ($res === false) { die('Error while querying the courses list in update_db-1.8.3-1.8.4.inc.php'); } - if (Database::num_rows($res) > 0) { - $i = 0; - $list = array(); - while ($row = Database::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row_course) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (!$singleDbForm) { //otherwise just use the main one - Database::select_db($row_course['db_name']); - } - Log::notice('Course db ' . $row_course['db_name']); - - foreach ($c_q_list as $query) { - if ($singleDbForm) { - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query); - } - - if ($only_test) { - error_log("Database::query(".$row_course['db_name'].",$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In ".$row_course['db_name'].", executed: $query", 0); - } - } - } - // Ensure each learnpath is present in the item_property table - $prefix_course = ''; - if ($singleDbForm) { - $prefix_course = $prefix.$row_course['db_name']."_"; - } - - $sql_ip = "SELECT * FROM ".$prefix_course."item_property WHERE tool='learnpath'"; - $res_ip = Database::query($sql_ip); - $paths = array(); - while ($row_ip = Database::fetch_array($res_ip)) { - $paths[] = $row_ip['ref']; - } - $sql_lp = "SELECT * FROM ".$prefix_course."lp"; - $res_lp = Database::query($sql_lp); - $tbl_tool = $prefix_course."tool"; - while ($row_lp = Database::fetch_array($res_lp)) { - $time = date("Y-m-d H:i:s", time()); - $vis = 'v'; - $input = stripslashes($row_lp['name']); - $input = str_replace("'", "''", $input); - $input = str_replace('"', "''", $input); - $mylink = 'newscorm/lp_controller.php?action=view&lp_id='.$row_lp['id']; - $sql2 = "SELECT * FROM $tbl_tool where (name='$input' and image='scormbuilder.gif' and link LIKE '$mylink%')"; - - if (in_array($row_lp['id'], $paths)) { - // The path is already in item_property, check the visibility is the - // same as the homepage tool's - $res2 = Database::query($sql2); - if (Database::num_rows($res2) > 0) { - $row2 = Database::fetch_array($res2); - $vis = $row2['visibility']; - } - $visi = array('v' => 1, 'i' => 0); - if ($visi[$vis] != $row_ip['visibility']) { - $sql_upd = "UPDATE ".$prefix_course."item_propery SET visibility=".$visi[$vis]." WHERE tool='learnpath' AND ref='".$row_lp['id']."'"; - $res_upd = Database::query($sql_upd); - } - } else { - // The path is not in item_property, insert it - $res2 = Database::query($sql2); - if (Database::num_rows($res2) > 0) { - $row2 = Database::fetch_array($res2); - $vis = $row2['visibility']; - } - $visi = array('v' => 1, 'i' => 0); - - $sql_ins = "INSERT INTO ".$prefix_course."item_property " . - "(tool,ref,insert_date,last_edit_date,insert_user_id,lastedit_type,lastedit_user_id,visibility)" . - "VALUES" . - "('learnpath',".$row_lp['id'].",'$time','$time',1,'learnpathAdded',1,".$visi[$vis].")"; - $res_ins = Database::query($sql_ins); - } - } - } - } - } - } - -} else { - - echo 'You are not allowed here !' . __FILE__; - -} diff --git a/main/install/update-db-1.8.4-1.8.5.inc.php b/main/install/update-db-1.8.4-1.8.5.inc.php deleted file mode 100755 index e95b7778af..0000000000 --- a/main/install/update-db-1.8.4-1.8.5.inc.php +++ /dev/null @@ -1,283 +0,0 @@ -'.get_lang('Error').' ! Dokeos '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.

- '.get_lang('PleasGoBackToStep1').'. -

- '; - exit (); - } - - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - - $dbScormForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbScormForm); - - if (!empty($dbPrefixForm) && strpos($dbScormForm, $dbPrefixForm) !== 0) { - $dbScormForm = $dbPrefixForm.$dbScormForm; - } - - if (empty($dbScormForm) || $dbScormForm == 'mysql' || $dbScormForm == $dbPrefixForm) { - $dbScormForm = $dbPrefixForm.'scorm'; - } - - /* Normal upgrade procedure: start by updating main, statistic, user databases */ - - // If this script has been included by index.php, not update_courses.php, so - // that we want to change the main databases as well... - $only_test = false; - $log = 0; - if (defined('SYSTEM_INSTALLATION')) { - - if ($singleDbForm) { - $dbStatsForm = $dbNameForm; - $dbScormForm = $dbNameForm; - $dbUserForm = $dbNameForm; - } - /** - * Update the databases "pre" migration - */ - include_once '../lang/english/trad4all.inc.php'; - - if ($languageForm != 'english') { - // languageForm has been escaped in index.php - include_once '../lang/'.$languageForm.'/trad4all.inc.php'; - } - - //get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - error_log('Database name '.$dbNameForm.' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database '.$dbNameForm.' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbNameForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbNameForm, executed: $query", 0); - } - } - } - } - } - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'stats'); - - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - error_log('Database name '.$dbStatsForm.' is too long, skipping', 0); - } elseif (!in_array($dbStatsForm, $dblist)) { - error_log('Database '.$dbStatsForm.' was not found, skipping', 0); - } else { - Database::select_db($dbStatsForm); - foreach ($s_q_list as $query) { - if ($only_test) { - error_log("Database::query($dbStatsForm,$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In $dbStatsForm, executed: $query", 0); - } - } - } - } - } - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'user'); - if (count($u_q_list) > 0) { - // Now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - error_log('Database name '.$dbUserForm.' is too long, skipping', 0); - } elseif (!in_array($dbUserForm, $dblist)) { - error_log('Database '.$dbUserForm.' was not found, skipping', 0); - } else { - Database::select_db($dbUserForm); - foreach ($u_q_list as $query){ - if ($only_test) { - error_log("Database::query($dbUserForm,$query)", 0); - error_log("In $dbUserForm, executed: $query", 0); - } else { - $res = Database::query($query); - } - } - } - } - // The SCORM database doesn't need a change in the pre-migrate part - ignore - } - - $prefix = ''; - if ($singleDbForm) { - $prefix = get_config_param ('table_prefix'); - } - - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'course'); - - if (count($c_q_list) > 0) { - //get the courses list - if (strlen($dbNameForm) > 40) { - error_log('Database name '.$dbNameForm.' is too long, skipping', 0); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database '.$dbNameForm.' was not found, skipping', 0); - } else { - Database::select_db($dbNameForm); - $res = Database::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL ORDER BY code"); - - if ($res === false) { die('Error while querying the courses list in update_db-1.8.4-1.8.5.inc.php'); } - - if (Database::num_rows($res) > 0) { - $i = 0; - $list = array(); - while($row = Database::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row_course) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (!$singleDbForm) { //otherwise just use the main one - Database::select_db($row_course['db_name']); - } - Log::notice('Course db ' . $row_course['db_name']); - - foreach ($c_q_list as $query) { - if ($singleDbForm) { - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query); - } - - if ($only_test) { - error_log("Database::query(".$row_course['db_name'].",$query)", 0); - } else { - $res = Database::query($query); - if ($log) { - error_log("In ".$row_course['db_name'].", executed: $query", 0); - } - } - } - - $mytable = $row_course['db_name'].".lp_item"; - - if ($singleDbForm) { - $mytable = "$prefix{$row_course['db_name']}_lp_item"; - } - - $mysql = "SELECT * FROM $mytable WHERE min_score != 0 AND prerequisite != ''"; - $myres = Database::query($query); - - if ($myres !== false && Database::num_rows($myres) > 0) { - while ($myrow = Database::fetch_array($myres)) { - if (is_numeric($myrow['prerequisite'])) { - $mysql2 = "UPDATE $mytable SET mastery_score = '".$myrow['min_score']."' WHERE id = '".$myrow['prerequisite']."'"; - $myres2 = Database::query($mysql2); - //echo $mysql2."
"; - if ($myres2 !== false) { - $mysql3 = "UPDATE $mytable SET min_score = 0 WHERE id = '".$myrow['id']."'"; - $myres3 = Database::query($mysql3); - //echo $mysql3."
"; - } - } - } - } - - // Work Tool Folder Update - // We search into DB all the folders in the work tool - if ($singleDbForm) { - $my_course_table = "$prefix{$row_course['db_name']}_student_publication"; - } else { - $my_course_table = $row_course['db_name'].".student_publication"; - } - - $sys_course_path = $_configuration['root_sys'].$_configuration['course_folder']; - - $course_dir = $sys_course_path.$row_course['directory'].'/work'; - - $dir_to_array = my_directory_to_array($course_dir, true); - $only_dir = array(); - - $sql_select = "SELECT filetype FROM " . $my_course_table . " WHERE filetype = 'folder'"; - $result = Database::query($sql_select); - $num_row = Database::num_rows($result); - - // Check if there are already folder registered - if ($num_row == 0) { - for ($i = 0; $i < count($dir_to_array); $i++) { - $only_dir[] = substr($dir_to_array[$i], strlen($course_dir), strlen($dir_to_array[$i])); - } - - for ($i = 0; $i < count($only_dir); $i++) { - $sql_insert_all= "INSERT INTO " . $my_course_table . " SET url = '" . $only_dir[$i] . "', " . - "title = '', - description = '', - author = '', - active = '0', - accepted = '1', - filetype = 'folder', - post_group_id = '0', - sent_date = '0000-00-00 00:00:00' "; - Database::query($sql_insert_all); - } - } - - } - } - } - } - -} else { - - echo 'You are not allowed here !' . __FILE__; - -} diff --git a/main/install/update-db-1.8.5-1.8.6.inc.php b/main/install/update-db-1.8.5-1.8.6.inc.php deleted file mode 100755 index 8c989a298d..0000000000 --- a/main/install/update-db-1.8.5-1.8.6.inc.php +++ /dev/null @@ -1,1147 +0,0 @@ -' . get_lang('Error') . ' ! Dokeos ' . implode('|', $updateFromVersion) . ' ' . get_lang('HasNotBeenFound') . '.

- ' . get_lang('PleasGoBackToStep1') . '. -

- '; - exit(); - } - - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - - $dbScormForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbScormForm); - - if (!empty($dbPrefixForm) && strpos($dbScormForm, $dbPrefixForm) !== 0) { - $dbScormForm = $dbPrefixForm . $dbScormForm; - } - - if (empty($dbScormForm) || $dbScormForm == 'mysql' || $dbScormForm == $dbPrefixForm) { - $dbScormForm = $dbPrefixForm . 'scorm'; - } - - /* Normal upgrade procedure: start by updating main, statistic, user databases */ - - // If this script has been included by index.php, not update_courses.php, so - // that we want to change the main databases as well... - $only_test = false; - $log = 0; - if (defined('SYSTEM_INSTALLATION')) { - - if ($singleDbForm) { - $dbStatsForm = $dbNameForm; - $dbScormForm = $dbNameForm; - $dbUserForm = $dbNameForm; - } - /** - * Update the databases "pre" migration - */ - include_once '../lang/english/trad4all.inc.php'; - - if ($languageForm != 'english') { - // languageForm has been escaped in index.php - include_once '../lang/' . $languageForm . '/trad4all.inc.php'; - } - - // Get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-' . $old_file_version . '-' . $new_file_version . '-pre.sql', 'main'); - if (count($m_q_list) > 0) { - //now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - Log::error('Database name ' . $dbNameForm . ' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database ' . $dbNameForm . ' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - Log::notice("iDatabase::query($dbNameForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbNameForm, executed: $query"); - } - } - } - } - } - - require_once '../inc/lib/image.lib.php'; //this library has been created - // in 1.8.8, which makes this inclusion retroactively necessary in - // updates from 1.8.5 - // Filling the access_url_rel_user table with access_url_id by default = 1 - $query = "SELECT user_id FROM $dbNameForm.user"; - - $result_users = iDatabase::query($query); - while ($row = iDatabase::fetch_array($result_users, 'NUM')) { - $user_id = $row[0]; - $sql = "INSERT INTO $dbNameForm.access_url_rel_user SET user_id=$user_id, access_url_id=1"; - $res = iDatabase::query($sql); - //Updating user image - $query = "SELECT picture_uri FROM $dbNameForm.user WHERE user_id=$user_id"; - $res = iDatabase::query($query); - $picture_uri = iDatabase::fetch_array($res, 'NUM'); - $file = $picture_uri[0]; - $dir = api_get_path(SYS_CODE_PATH) . 'upload/users/'; - $image_repository = file_exists($dir . $file) ? $dir . $file : $dir . $user_id . '/' . $file; - - if (!is_dir($dir . $user_id)) { - @mkdir($dir . $user_id, $perm); - } - - if (file_exists($image_repository) && is_file($image_repository)) { - chmod($dir . $user_id, 0777); - if (is_dir($dir . $user_id)) { - $picture_location = $dir . $user_id . '/' . $file; - $big_picture_location = $dir . $user_id . '/big_' . $file; - - $temp = new Image($image_repository); - - $picture_infos = getimagesize($image_repository); - - $thumbwidth = 150; - if (empty($thumbwidth) or $thumbwidth == 0) { - $thumbwidth = 150; - } - - $new_height = ($picture_infos[0] > 0) ? round(($thumbwidth / $picture_infos[0]) * $picture_infos[1]) : 0; - - $temp->resize($thumbwidth, $new_height, 0); - - $type = $picture_infos[2]; - - // Original picture - $big_temp = new Image($image_repository); - - switch (!empty($type)) { - case 2 : $temp->send_image('JPG', $picture_location); - $big_temp->send_image('JPG', $big_picture_location); - break; - case 3 : $temp->send_image('PNG', $picture_location); - $big_temp->send_image('JPG', $big_picture_location); - break; - case 1 : $temp->send_image('GIF', $picture_location); - $big_temp->send_image('JPG', $big_picture_location); - break; - } - if ($image_repository == $dir . $file) { - @unlink($image_repository); - } - } - } - } - // Filling the access_url_rel_session table with access_url_id by default = 1 - $query = "SELECT id FROM $dbNameForm.session"; - $result = iDatabase::query($query); - while ($row = iDatabase::fetch_array($result, 'NUM')) { - $sql = "INSERT INTO $dbNameForm.access_url_rel_session SET session_id=" . $row[0] . ", access_url_id=1"; - $res = iDatabase::query($sql); - } - - // Since the parser of the migration DB does not work for this kind of inserts (HTML) we move it here - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleCourseTitle\', \'TemplateTitleCourseTitleDescription\', \'coursetitle.gif\', \' - - {CSS} - - - - - - - - - - - -
-

TITULUS 1
- TITULUS 2
-

-
- Chamilo logo
-


-
-

- - \');'; - $res = iDatabase::query($sql); - - /* - $sql = 'INSERT INTO '.$dbNameForm.'.system_template (title, comment, image, content) VALUES - (\'TemplateTitleCheckList\', \'TemplateTitleCheckListDescription\', \'checklist.gif\', \' - - {CSS} - - - - - - - - - -
-

Lorem ipsum dolor sit amet

-
    -
  • consectetur adipisicing elit
  • -
  • sed do eiusmod tempor incididunt
  • -
  • ut labore et dolore magna aliqua
  • -
- -

Ut enim ad minim veniam

-
    -
  • quis nostrud exercitation ullamco
  • -
  • laboris nisi ut aliquip ex ea commodo consequat
  • -
  • Excepteur sint occaecat cupidatat non proident
  • -
- -

Sed ut perspiciatis unde omnis

-
    -
  • iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam
  • -
  • eaque ipsa quae ab illo inventore veritatis
  • -
  • et quasi architecto beatae vitae dicta sunt explicabo. 
  • -
- -
-

Ut enim ad minima

- Veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur.
-

- trainer

-
-


-
-

- - \');'; - - $res = iDatabase::query($sql); - */ - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleTeacher\', \'TemplateTitleTeacherDescription\', \'yourinstructor.gif\', \' - - {CSS} - - - - - - - - - - - - - - - - -
- -
- Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis pellentesque.
-
- trainer
-


-
-

- - \'); - '; - $res = iDatabase::query($sql); - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleLeftList\', \'TemplateTitleListLeftListDescription\', \'leftlist.gif\', \' - - {CSS} - - - - - - - - - - - - - - - - - - -
 trainer
-
Lorem - ipsum dolor sit amet. -
- Vivamus - a quam. 
-
- Proin - a est stibulum ante ipsum.
-


-
-

- - \');'; - $res = iDatabase::query($sql); - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleLeftRightList\', \'TemplateTitleLeftRightListDescription\', \'leftrightlist.gif\', \' - - - {CSS} - - - - - - - - - - - - - - - - - - - - - - -
 Trainer
-
Lorem - ipsum dolor sit amet. - - Convallis - ut. Cras dui magna.
- Vivamus - a quam. 
-
- Etiam - lacinia stibulum ante.
-
- Proin - a est stibulum ante ipsum. - Consectetuer - adipiscing elit.
-
-


-
-

- - - \');'; - $res = iDatabase::query($sql); - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleRightList\', \'TemplateTitleRightListDescription\', \'rightlist.gif\', \' - - {CSS} - - - - - - - - - - - - - - - - - - -
trainer
-
- Convallis - ut. Cras dui magna.
- Etiam - lacinia.
-
- Consectetuer - adipiscing elit.
-
-


-
-

- - \');'; - $res = iDatabase::query($sql); - - /* - $sql = 'INSERT INTO '.$dbNameForm.'.system_template (title, comment, image, content) VALUES - (\'TemplateTitleComparison\', \'TemplateTitleComparisonDescription\', \'compare.gif\', \' - - {CSS} - - - - - - - - - - - - - - - \');'; - $res = iDatabase::query($sql); - */ - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleDiagram\', \'TemplateTitleDiagramDescription\', \'diagram.gif\', \' - - {CSS} - - - -
 trainer
-
- Lorem ipsum dolor sit amet. - - Convallis - ut. Cras dui magna.
- - - - - - - - - - - -
-
- Etiam - lacinia stibulum ante. - Convallis - ut. Cras dui magna.
- Alaska chart
- trainer
-


-
-

- - \'); - '; - $res = iDatabase::query($sql); - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleDesc\', \'TemplateTitleCheckListDescription\', \'description.gif\', \' - - {CSS} - - - - - - - - - - -
- 01
Lorem ipsum dolor sit amet


- 02 -
Ut enim ad minim veniam


- 03Duis aute irure dolor in reprehenderit


- 04Neque porro quisquam est
- Gearbox
-


-
-

- - \'); - '; - $res = iDatabase::query($sql); - - /* - $sql = 'INSERT INTO '.$dbNameForm.'.system_template (title, comment, image, content) VALUES - (\'TemplateTitleObjectives\', \'TemplateTitleObjectivesDescription\', \'courseobjectives.gif\', \' - - {CSS} - - - - - - - - - - - - - -
- trainer
-
-

Lorem ipsum dolor sit amet

-
    -
  • consectetur adipisicing elit
  • -
  • sed do eiusmod tempor incididunt
  • -
  • ut labore et dolore magna aliqua
  • -
-

Ut enim ad minim veniam

-
    -
  • quis nostrud exercitation ullamco
  • -
  • laboris nisi ut aliquip ex ea commodo consequat
  • -
  • Excepteur sint occaecat cupidatat non proident
  • -
-
-


-
-

- - \');'; - $res = iDatabase::query($sql); - */ - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleCycle\', \'TemplateTitleCycleDescription\', \'cyclechart.gif\', \' - - {CSS} - - - - - - - - - - - - - - - - - - - - - - - - - -
- arrow -
- Lorem ipsum - - Sed ut perspiciatis -
-
    -
  • dolor sit amet
  • -
  • consectetur adipisicing elit
  • -
  • sed do eiusmod tempor 
  • -
  • adipisci velit, sed quia non numquam
  • -
  • eius modi tempora incidunt ut labore et dolore magnam
  • -
-
-
    -
  • ut enim ad minim veniam
  • -
  • quis nostrud exercitation
  • ullamco laboris nisi ut
  • -
  • Quis autem vel eum iure reprehenderit qui in ea
  • -
  • voluptate velit esse quam nihil molestiae consequatur,
  • -
-
- arrow         -
-


-
-

- - \');'; - $res = iDatabase::query($sql); - - /* - $sql = 'INSERT INTO '.$dbNameForm.'.system_template (title, comment, image, content) VALUES - (\'TemplateTitleLearnerWonder\', \'TemplateTitleLearnerWonderDescription\', \'learnerwonder.gif\', \' - - {CSS} - - - - - - - - - - - - - - - - - - - -
- learner wonders
-
- Convallis - ut. Cras dui magna.
- Etiam - lacinia stibulum ante.
-
- Consectetuer - adipiscing elit.
-
-


-
-

- - \'); - '; - $res = iDatabase::query($sql); - */ - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleTimeline\', \'TemplateTitleTimelineDescription\', \'phasetimeline.gif\', \' - - {CSS} - - - - - - - - - - - - - - - - - - - - - - - - -
Lorem ipsumPerspiciatisNemo enim
-
    -
  • dolor sit amet
  • -
  • consectetur
  • -
  • adipisicing elit
  • -
-
-
- arrow - -
    -
  • ut labore
  • -
  • et dolore
  • -
  • magni dolores
  • -
-
- arrow - -
    -
  • neque porro
  • -
  • quisquam est
  • -
  • qui dolorem  
  • -
-

-
-


-
-

- - \'); - '; - $res = iDatabase::query($sql); - - /* - $sql = 'INSERT INTO '.$dbNameForm.'.system_template (title, comment, image, content) VALUES - (\'TemplateTitleStopAndThink\', \'TemplateTitleStopAndThinkDescription\', \'stopthink.gif\', \' - - {CSS} - - - - - - - - - - - - -
- trainer -
-
-

Attentio sectetur adipisicing elit

-
    -
  • sed do eiusmod tempor incididunt
  • -
  • ut labore et dolore magna aliqua
  • -
  • quis nostrud exercitation ullamco
  • -

-


-
-

- - \');'; - $res = iDatabase::query($sql); - */ - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleTable\', \'TemplateTitleCheckListDescription\', \'table.gif\', \' - - {CSS} - - - - -
-

A table

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
City2005200620072008
Lima10,408,959,199,76
New York18,3917,5216,5716,60
Barcelona0,100,100,050,05
Paris3,383,633,633,54
-
- - \');'; - $res = iDatabase::query($sql); - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleAudio\', \'TemplateTitleAudioDescription\', \'audiocomment.gif\', \' - - {CSS} - - - - - - - - - - - - - - -
-
- - -
- -
-

- image
- trainer
-


-
-

- - \');'; - $res = iDatabase::query($sql); - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleVideo\', \'TemplateTitleVideoDescription\', \'video.gif\', \' - - {CSS} - - - - - - - - - - -
- -
-
- -
- -
- - - -
-
- -
-


-

-

Lorem ipsum dolor sit amet

-
    -
  • consectetur adipisicing elit
  • -
  • sed do eiusmod tempor incididunt
  • -
  • ut labore et dolore magna aliqua
  • -
-

Ut enim ad minim veniam

-
    -
  • quis nostrud exercitation ullamco
  • -
  • laboris nisi ut aliquip ex ea commodo consequat
  • -
  • Excepteur sint occaecat cupidatat non proident
  • -
-
-


-
-

- - - \'); '; - $res = iDatabase::query($sql); - - $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES - (\'TemplateTitleFlash\', \'TemplateTitleFlashDescription\', \'flash.gif\', \' - - {CSS} - - -
- - - - - - -
-
-
-


-
-

-
- - \'); '; - $res = iDatabase::query($sql); - - // Check if course_module exists, as it was not installed in Dokeos 1.8.5 because of a broken query, and $sql = 'INSERT it if necessary - $query = "SELECT * FROM $dbNameForm.course_module"; - $result = iDatabase::query($query); - if ($result === false) { - //the course_module table doesn't exist, create it - $sql = "CREATE TABLE $dbNameForm.course_module ( - id int unsigned NOT NULL auto_increment, - name varchar(100) NOT NULL, - link varchar(255) NOT NULL, - image varchar(100) default NULL, - `row` int unsigned NOT NULL default '0', - `column` int unsigned NOT NULL default '0', - position varchar(20) NOT NULL default 'basic', - PRIMARY KEY (id) - ) - "; - $result = iDatabase::query($sql); - if ($result !== false) { - $sql = "INSERT INTO $dbNameForm.course_module (name, link, image, `row`,`column`, position) VALUES - ('calendar_event','calendar/agenda.php','agenda.gif',1,1,'basic'), - ('link','link/link.php','links.gif',4,1,'basic'), - ('document','document/document.php','documents.gif',3,1,'basic'), - ('student_publication','work/work.php','works.gif',3,2,'basic'), - ('announcement','announcements/announcements.php','valves.gif',2,1,'basic'), - ('user','user/user.php','members.gif',2,3,'basic'), - ('forum','forum/index.php','forum.gif',1,2,'basic'), - ('quiz','exercice/exercice.php','quiz.gif',2,2,'basic'), - ('group','group/group.php','group.gif',3,3,'basic'), - ('course_description','course_description/','info.gif',1,3,'basic'), - ('chat','chat/chat.php','chat.gif',0,0,'external'), - ('dropbox','dropbox/index.php','dropbox.gif',4,2,'basic'), - ('tracking','tracking/courseLog.php','statistics.gif',1,3,'courseadmin'), - ('homepage_link','link/link.php?action=addlink','npage.gif',1,1,'courseadmin'), - ('course_setting','course_info/infocours.php','reference.gif',1,1,'courseadmin'), - ('External','','external.gif',0,0,'external'), - ('AddedLearnpath','','scormbuilder.gif',0,0,'external'), - ('conference','conference/index.php?type=conference','conf.gif',0,0,'external'), - ('conference','conference/index.php?type=classroom','conf.gif',0,0,'external'), - ('learnpath','newscorm/lp_controller.php','scorm.gif',5,1,'basic'), - ('blog','blog/blog.php','blog.gif',1,2,'basic'), - ('blog_management','blog/blog_admin.php','blog_admin.gif',1,2,'courseadmin'), - ('course_maintenance','course_info/maintenance.php','backup.gif',2,3,'courseadmin'), - ('survey','survey/survey_list.php','survey.gif',2,1,'basic'), - ('wiki','wiki/index.php','wiki.gif',2,3,'basic'), - ('gradebook','gradebook/index.php','gradebook.gif',2,2,'basic'), - ('glossary','glossary/index.php','glossary.gif',2,1,'basic'), - ('notebook','notebook/index.php','notebook.gif',2,1,'basic')"; - $res = iDatabase::query($sql); - } - } - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-' . $old_file_version . '-' . $new_file_version . '-pre.sql', 'stats'); - - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - Log::error('Database name ' . $dbStatsForm . ' is too long, skipping'); - } elseif (!in_array($dbStatsForm, $dblist)) { - Log::error('Database ' . $dbStatsForm . ' was not found, skipping'); - } else { - iDatabase::select_db($dbStatsForm); - foreach ($s_q_list as $query) { - if ($only_test) { - Log::notice("iDatabase::query($dbStatsForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbStatsForm, executed: $query"); - } - } - } - } - } - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-' . $old_file_version . '-' . $new_file_version . '-pre.sql', 'user'); - if (count($u_q_list) > 0) { - // Now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - Log::error('Database name ' . $dbUserForm . ' is too long, skipping'); - } elseif (!in_array($dbUserForm, $dblist)) { - Log::error('Database ' . $dbUserForm . ' was not found, skipping'); - } else { - iDatabase::select_db($dbUserForm); - foreach ($u_q_list as $query) { - if ($only_test) { - error_log("iDatabase::query($dbUserForm,$query)"); - error_log("In $dbUserForm, executed: $query"); - } else { - $res = iDatabase::query($query); - } - } - } - } - // The SCORM database doesn't need a change in the pre-migrate part - ignore - } - - $prefix = ''; - if ($singleDbForm) { - $prefix = get_config_param('table_prefix'); - } - - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-' . $old_file_version . '-' . $new_file_version . '-pre.sql', 'course'); - - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - error_log('Database name ' . $dbNameForm . ' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - error_log('Database ' . $dbNameForm . ' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - $res = iDatabase::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL ORDER BY code"); - - if ($res === false) { - die('Error while querying the courses list in update_db-1.8.5-1.8.6.inc.php'); - } - - if (iDatabase::num_rows($res) > 0) { - $i = 0; - $list = array(); - while ($row = iDatabase::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row_course) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (!$singleDbForm) { //otherwise just use the main one - iDatabase::select_db($row_course['db_name']); - } - Log::notice('Course db ' . $row_course['db_name']); - - foreach ($c_q_list as $query) { - if ($singleDbForm) { //otherwise just use the main one - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query); - } - - if ($only_test) { - Log::notice("iDatabase::query(" . $row_course['db_name'] . ",$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In " . $row_course['db_name'] . ", executed: $query"); - } - } - } - - $t_d = $row_course['db_name'] . ".document"; - $t_ip = $row_course['db_name'] . ".item_property"; - - if ($singleDbForm) { - $t_d = "$prefix{$row_course['db_name']}_document"; - $t_ip = "$prefix{$row_course['db_name']}_item_property"; - } - // Shared documents folder - $query = "INSERT INTO $t_d (path,title,filetype,size) VALUES ('/shared_folder','" . get_lang('SharedDocumentsDirectory') . "','folder','0')"; - $myres = iDatabase::query($query); - if ($myres !== false) { - $doc_id = iDatabase::insert_id(); - $query = "INSERT INTO $t_ip (tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ('document',1,NOW(),NOW(),$doc_id,'FolderAdded',1,0,NULL,1)"; - $myres = iDatabase::query($query); - } - } - } - } - } -} else { - - echo 'You are not allowed here !' . __FILE__; -} diff --git a/main/install/update-db-1.8.6-1.8.6.1.inc.php b/main/install/update-db-1.8.6-1.8.6.1.inc.php deleted file mode 100755 index 426e04e5fc..0000000000 --- a/main/install/update-db-1.8.6-1.8.6.1.inc.php +++ /dev/null @@ -1,264 +0,0 @@ -'.get_lang('Error').' ! Dokeos '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.

- '.get_lang('PleasGoBackToStep1').'. -

- '; - exit (); - } - - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - - $dbScormForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbScormForm); - - if (!empty($dbPrefixForm) && strpos($dbScormForm, $dbPrefixForm) !== 0) { - $dbScormForm = $dbPrefixForm.$dbScormForm; - } - - if (empty($dbScormForm) || $dbScormForm == 'mysql' || $dbScormForm == $dbPrefixForm) { - $dbScormForm = $dbPrefixForm.'scorm'; - } - - /* Normal upgrade procedure: start by updating main, statistic, user databases */ - - // If this script has been included by index.php, not update_courses.php, so - // that we want to change the main databases as well... - $only_test = false; - $log = 0; - if (defined('SYSTEM_INSTALLATION')) { - - if ($singleDbForm) { - $dbStatsForm = $dbNameForm; - $dbScormForm = $dbNameForm; - $dbUserForm = $dbNameForm; - } - /** - * Update the databases "pre" migration - */ - include_once '../lang/english/trad4all.inc.php'; - - if ($languageForm != 'english') { - //languageForm has been escaped in index.php - include_once '../lang/'.$languageForm.'/trad4all.inc.php'; - } - - //get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - Log::error('Database name '.$dbNameForm.' is too long, skipping'); - } elseif (!in_array($dbNameForm,$dblist)) { - Log::error('Database '.$dbNameForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - foreach($m_q_list as $query) { - if ($only_test){ - Log::notice("iDatabase::query($dbNameForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbNameForm, executed: $query"); - } - } - } - } - } - - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'stats'); - - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - Log::error('Database name '.$dbStatsForm.' is too long, skipping'); - } elseif (!in_array($dbStatsForm,$dblist)) { - Log::error('Database '.$dbStatsForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbStatsForm); - foreach ($s_q_list as $query) { - if ($only_test) { - Log::notice("iDatabase::query($dbStatsForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbStatsForm, executed: $query"); - } - } - } - } - } - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'user'); - if (count($u_q_list) > 0) { - // Now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - Log::error('Database name '.$dbUserForm.' is too long, skipping'); - } elseif (!in_array($dbUserForm, $dblist)) { - Log::error('Database '.$dbUserForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbUserForm); - foreach ($u_q_list as $query) { - if ($only_test) { - Log::notice("iDatabase::query($dbUserForm,$query)"); - Log::notice("In $dbUserForm, executed: $query"); - } else { - $res = iDatabase::query($query); - } - } - } - } - // The SCORM database doesn't need a change in the pre-migrate part - ignore - } - - $prefix = ''; - if ($singleDbForm) { - $prefix = get_config_param ('table_prefix'); - } - - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'course'); - - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - Log::error('Database name '.$dbNameForm.' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database '.$dbNameForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - $res = iDatabase::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL ORDER BY code"); - - if ($res === false) { die('Error while querying the courses list in update_db-1.8.6-1.8.6.1.inc.php'); } - - if (iDatabase::num_rows($res) > 0) { - $i = 0; - $list = array(); - while ($row = iDatabase::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row_course) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (!$singleDbForm) { //otherwise just use the main one - iDatabase::select_db($row_course['db_name']); - } - Log::notice('Course db ' . $row_course['db_name']); - - foreach ($c_q_list as $query) { - if ($singleDbForm) { - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query); - } - - if ($only_test) { - Log::notice("iDatabase::query(".$row_course['db_name'].",$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In ".$row_course['db_name'].", executed: $query"); - } - } - } - - $t_wiki = $row_course['db_name'].".wiki"; - $t_wiki_conf = $row_course['db_name'].".wiki_conf"; - - if ($singleDbForm) { - $t_wiki = "$prefix{$row_course['db_name']}_wiki"; - $t_wiki_conf = "$prefix{$row_course['db_name']}_wiki_conf"; - } - - // Update correct page_id to wiki table, actually only store 0 - $query = "SELECT id, reflink FROM $t_wiki"; - $res_page = iDatabase::query($query); - $wiki_id = $reflink = array(); - - if (iDatabase::num_rows($res_page) > 0) { - while ($row_page = iDatabase::fetch_row($res_page)) { - $wiki_id[] = $row_page[0]; - $reflink[] = $row_page[1]; - } - } - - $reflink_unique = array_unique($reflink); - $reflink_flip = array_flip($reflink_unique); - - if (is_array($wiki_id)) { - foreach ($wiki_id as $key => $wiki_page) { - $pag_id = $reflink_flip[$reflink[$key]]; - $sql= "UPDATE $t_wiki SET page_id='".($pag_id + 1)."' WHERE id = '$wiki_page'"; - $res_update = iDatabase::query($sql); - } - } - - // Insert page_id into wiki_conf table, actually this table is empty - $query = "SELECT DISTINCT page_id FROM $t_wiki ORDER BY page_id"; - $myres_wiki = iDatabase::query($query); - - if (iDatabase::num_rows($myres_wiki) > 0) { - while ($row_wiki = iDatabase::fetch_row($myres_wiki)) { - $page_id = $row_wiki[0]; - $query = "INSERT INTO ".$t_wiki_conf." (page_id, task, feedback1, feedback2, feedback3, fprogress1, fprogress2, fprogress3) VALUES ('".$page_id."','','','','','','','')"; - $myres_wiki_conf = iDatabase::query($query); - } - } - - } - } - } - } - -} else { - - echo 'You are not allowed here !' . __FILE__; - -} diff --git a/main/install/update-db-1.8.6.1-1.8.6.2.inc.php b/main/install/update-db-1.8.6.1-1.8.6.2.inc.php deleted file mode 100755 index 6df0fb542c..0000000000 --- a/main/install/update-db-1.8.6.1-1.8.6.2.inc.php +++ /dev/null @@ -1,349 +0,0 @@ -'.get_lang('Error').' ! Dokeos '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.

- '.get_lang('PleasGoBackToStep1').'. -

- '; - exit (); - } - - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - - $dbScormForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbScormForm); - - if (!empty($dbPrefixForm) && strpos($dbScormForm, $dbPrefixForm) !== 0) { - $dbScormForm = $dbPrefixForm.$dbScormForm; - } - - if (empty($dbScormForm) || $dbScormForm == 'mysql' || $dbScormForm == $dbPrefixForm) { - $dbScormForm = $dbPrefixForm.'scorm'; - } - - /* Normal upgrade procedure: start by updating main, statistic, user databases */ - - // If this script has been included by index.php, not update_courses.php, so - // that we want to change the main databases as well... - $only_test = false; - $log = 0; - if (defined('SYSTEM_INSTALLATION')) { - - if ($singleDbForm) { - $dbStatsForm = $dbNameForm; - $dbScormForm = $dbNameForm; - $dbUserForm = $dbNameForm; - } - /** - * Update the databases "pre" migration - */ - include_once '../lang/english/trad4all.inc.php'; - - if ($languageForm != 'english') { - // languageForm has been escaped in index.php - include_once '../lang/'.$languageForm.'/trad4all.inc.php'; - } - - // Get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - Log::error('Database name '.$dbNameForm.' is too long, skipping'); - } elseif (!in_array($dbNameForm,$dblist)) { - Log::error('Database '.$dbNameForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - Log::notice("iDatabase::query($dbNameForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbNameForm, executed: $query"); - } - } - } - - - // There might now be multiple course coaches. This implies - // moving the previous course coach elements from the - // session_rel_course table to the session_rel_course_rel_user - // table with status 2 - // Select all the current course coaches in sessions - - $sql = "SELECT id_session, course_code, id_coach - FROM session_rel_course - ORDER BY id_session, course_code"; - - $res = iDatabase::query($sql); - - if ($res === false) { - Log::error('Could not query session course coaches table: '.iDatabase::error()); - } else { - // For each coach found, add him as a course coach in the - // session_rel_course_rel_user table - while ($row = iDatabase::fetch_array($res)) { - - // Check whether coach is a student - $sql = "SELECT 1 FROM session_rel_course_rel_user - WHERE id_session='{$row[id_session]}' AND course_code='{$row[course_code]}' AND id_user='{$row[id_coach]}'"; - $rs = iDatabase::query($sql); - - if (iDatabase::num_rows($rs) > 0) { - $sql_upd = "UPDATE session_rel_course_rel_user SET status=2 - WHERE id_session='{$row[id_session]}' AND course_code='{$row[course_code]}' AND id_user='{$row[id_coach]}'"; - } else { - $sql_ins = "INSERT INTO session_rel_course_rel_user(id_session, course_code, id_user, status) - VALUES ('{$row[id_session]}','{$row[course_code]}','{$row[id_coach]}',2)"; - } - - $rs_coachs = iDatabase::query($sql_ins); - - if ($rs_coachs === false) { - Log::error('Could not move course coach to new table: '.iDatabase::error()); - } - - } - } - - // Remove duplicated rows for 'show_tutor_data' AND 'show_teacher_data' into settings_current table - - $sql = "SELECT id FROM settings_current WHERE variable='show_tutor_data' ORDER BY id"; - $rs_chk_id1 = iDatabase::query($sql); - - if ($rs_chk_id1 === false) { - Log::error('Could not query settings_current ids table: '.iDatabase::error()); - } else { - $i = 1; - while ($row_id1 = iDatabase::fetch_array($rs_chk_id1)) { - $id = $row_id1['id']; - if ($i > 1) { - $sql_del = "DELETE FROM settings_current WHERE id = '$id'"; - iDatabase::query($sql_del); - } - $i++; - } - } - - $sql = "SELECT id FROM settings_current WHERE variable='show_teacher_data' ORDER BY id"; - $rs_chk_id2 = iDatabase::query($sql); - - if ($rs_chk_id2 === false) { - Log::error('Could not query settings_current ids table: '.iDatabase::error()); - } else { - $i = 1; - while ($row_id2 = iDatabase::fetch_array($rs_chk_id2)) { - $id = $row_id2['id']; - if ($i > 1) { - $sql_del = "DELETE FROM settings_current WHERE id = '$id'"; - iDatabase::query($sql_del); - } - $i++; - } - } - - } - } - // Now clean the deprecated id_coach field from the session_rel_course table - $m_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-post.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - Log::error('Database name '.$dbNameForm.' is too long, skipping'); - } elseif (!in_array($dbNameForm,$dblist)) { - Log::error('Database '.$dbNameForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - Log::notice("iDatabase::query($dbNameForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbNameForm, executed: $query"); - } - } - } - } - } - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'stats'); - - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - Log::error('Database name '.$dbStatsForm.' is too long, skipping'); - } elseif (!in_array($dbStatsForm, $dblist)) { - Log::error('Database '.$dbStatsForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbStatsForm); - foreach ($s_q_list as $query) { - if ($only_test) { - Log::notice("iDatabase::query($dbStatsForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbStatsForm, executed: $query"); - } - } - } - } - } - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'user'); - if (count($u_q_list) > 0) { - // Now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - Log::error('Database name '.$dbUserForm.' is too long, skipping'); - } elseif (!in_array($dbUserForm,$dblist)) { - Log::error('Database '.$dbUserForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbUserForm); - foreach ($u_q_list as $query) { - if ($only_test){ - Log::notice("iDatabase::query($dbUserForm,$query)"); - Log::notice("In $dbUserForm, executed: $query"); - } else { - $res = iDatabase::query($query); - } - } - } - } - // The SCORM database doesn't need a change in the pre-migrate part - ignore - } - - $prefix = ''; - if ($singleDbForm) { - $prefix = get_config_param ('table_prefix'); - } - - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'course'); - - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - Log::error('Database name '.$dbNameForm.' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database '.$dbNameForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - $res = iDatabase::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL ORDER BY code"); - - if ($res === false) { die('Error while querying the courses list in update_db-1.8.6.1-1.8.6.2.inc.php'); } - - if (iDatabase::num_rows($res) > 0) { - $i = 0; - $list = array(); - while ($row = iDatabase::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row_course) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (!$singleDbForm) { //otherwise just use the main one - iDatabase::select_db($row_course['db_name']); - } - Log::notice('Course db ' . $row_course['db_name']); - - foreach ($c_q_list as $query) { - if ($singleDbForm) { - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query); - } - - if ($only_test) { - Log::error("iDatabase::query(".$row_course['db_name'].",$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::error("In ".$row_course['db_name'].", executed: $query"); - } - } - } - - // Fill description type into course_description table - - $t_course_description = $row_course['db_name'].".course_description"; - - if ($singleDbForm) { - $t_course_description = "$prefix{$row_course['db_name']}_course_description"; - } - - // Get all ids and update description_type field with them from course_description table - $sql_sel = "SELECT id FROM $t_course_description"; - $rs_sel = iDatabase::query($sql_sel); - - if ($rs_sel === false) { - Log::error('Could not query course_description ids table: '.iDatabase::error()); - } else { - if (iDatabase::num_rows($rs_sel) > 0) { - while ($row_ids = iDatabase::fetch_array($rs_sel)) { - $description_id = $row_ids['id']; - $sql_upd = "UPDATE $t_course_description SET description_type='$description_id' WHERE id='$description_id'"; - iDatabase::query($sql_upd); - } - } - } - - } - } - } - } - -} else { - - echo 'You are not allowed here !' . __FILE__; - -} diff --git a/main/install/update-db-1.8.6.2-1.8.7.inc.php b/main/install/update-db-1.8.6.2-1.8.7.inc.php deleted file mode 100755 index b407645a09..0000000000 --- a/main/install/update-db-1.8.6.2-1.8.7.inc.php +++ /dev/null @@ -1,568 +0,0 @@ -' . get_lang('Error') . ' ! Chamilo ' . implode('|', $updateFromVersion) . ' ' . get_lang('HasNotBeenFound') . '.

- ' . get_lang('PleasGoBackToStep1') . '. -

- '; - exit(); - } - - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - - $dbScormForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbScormForm); - - if (!empty($dbPrefixForm) && strpos($dbScormForm, $dbPrefixForm) !== 0) { - $dbScormForm = $dbPrefixForm . $dbScormForm; - } - - if (empty($dbScormForm) || $dbScormForm == 'mysql' || $dbScormForm == $dbPrefixForm) { - $dbScormForm = $dbPrefixForm . 'scorm'; - } - - /* Normal upgrade procedure: start by updating main, statistic, user databases */ - - // If this script has been included by index.php, not update_courses.php, so - // that we want to change the main databases as well... - $only_test = false; - $log = 0; - if (defined('SYSTEM_INSTALLATION')) { - - if ($singleDbForm) { - $dbStatsForm = $dbNameForm; - $dbScormForm = $dbNameForm; - $dbUserForm = $dbNameForm; - } - /** - * Update the databases "pre" migration - */ - include_once '../lang/english/trad4all.inc.php'; - - if ($languageForm != 'english') { - // languageForm has been escaped in index.php - include_once '../lang/' . $languageForm . '/trad4all.inc.php'; - } - - // Get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-' . $old_file_version . '-' . $new_file_version . '-pre.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - Log::error('Database name ' . $dbNameForm . ' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database ' . $dbNameForm . ' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - Log::notice("Database::query($dbNameForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbNameForm, executed: $query"); - } - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - } - $tables = iDatabase::get_tables($dbNameForm); - foreach ($tables as $table) { - $query = "ALTER TABLE `" . $table . "` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;"; - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - $query = "ALTER DATABASE `" . $dbNameForm . "` DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;"; - $res = Database::query($query); - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - } - - if (DATE_TIME_INSTALLED) { - // Converting dates and times to UTC using the default timezone of PHP - // Converting gradebook dates and times - $timezone = date_default_timezone_get(); - // Calculating the offset - $dateTimeZoneCurrent = new DateTimeZone($timezone); - $dateTimeUTC = new DateTime("now", new DateTimeZone('UTC')); - $timeOffsetSeconds = $dateTimeZoneCurrent->getOffset($dateTimeUTC); - $timeOffsetHours = $timeOffsetSeconds / 3600; - $timeOffsetString = ""; - - if ($timeOffsetHours < 0) { - $timeOffsetString .= "-"; - $timeOffsetHours = abs($timeOffsetHours); - } else { - $timeOffsetString .= "+"; - } - - if ($timeOffsetHours < 10) { - $timeOffsetString .= "0"; - } - - $timeOffsetString .= "$timeOffsetHours"; - $timeOffsetString .= ":00"; - - // Executing the queries to convert everything - $queries[] = "UPDATE gradebook_certificate SET created_at = CONVERT_TZ(created_at, '" . $timeOffsetString . "', '+00:00');"; - $queries[] = "UPDATE gradebook_evaluation SET created_at = CONVERT_TZ(created_at, '" . $timeOffsetString . "', '+00:00');"; - $queries[] = "UPDATE gradebook_link SET created_at = CONVERT_TZ(created_at, '" . $timeOffsetString . "', '+00:00');"; - $queries[] = "UPDATE gradebook_linkeval_log SET created_at = CONVERT_TZ(created_at, '" . $timeOffsetString . "', '+00:00');"; - $queries[] = "UPDATE gradebook_result SET created_at = CONVERT_TZ(created_at, '" . $timeOffsetString . "', '+00:00');"; - $queries[] = "UPDATE gradebook_result_log SET created_at = CONVERT_TZ(created_at, '" . $timeOffsetString . "', '+00:00');"; - - foreach ($queries as $query) { - iDatabase::query($query); - } - } - // Moving user followed by a human resource manager from hr_dept_id field to user_rel_user table - $query = "SELECT user_id, hr_dept_id FROM $dbNameForm.user"; - $result = iDatabase::query($query); - if (iDatabase::num_rows($result) > 0) { - require_once api_get_path(LIBRARY_PATH) . 'usermanager.lib.php'; - while ($row = iDatabase::fetch_array($result, 'ASSOC')) { - $user_id = $row['user_id']; - $hr_dept_id = $row['hr_dept_id']; - // moving data to user_rel_user table - if (!empty($hr_dept_id)) { - $sql = " SELECT id FROM $dbNameForm.user_rel_user WHERE user_id = $user_id AND friend_user_id = $hr_dept_id AND relation_type = " . USER_RELATION_TYPE_RRHH . " "; - $rs = iDatabase::query($sql); - if (iDatabase::num_rows($rs) == 0) { - $ins = "INSERT INTO $dbNameForm.user_rel_user SET user_id = $user_id, friend_user_id = $hr_dept_id, relation_type = " . USER_RELATION_TYPE_RRHH . " "; - iDatabase::query($ins); - } - } - } - // cleaning hr_dept_id field inside user table - $upd = "UPDATE $dbNameForm.user SET hr_dept_id = 0"; - iDatabase::query($upd); - } - - // Updating score display for each gradebook category - // first we check if there already is migrated data to categoy_id field - $query = "SELECT id FROM $dbNameForm.gradebook_score_display WHERE category_id = 0"; - $rs_check = iDatabase::query($query); - - if (iDatabase::num_rows($rs_check) > 0) { - // get all gradebook categories id - $a_categories = array(); - $query = "SELECT id FROM $dbNameForm.gradebook_category"; - $rs_gradebook = iDatabase::query($query); - if (iDatabase::num_rows($rs_gradebook) > 0) { - while ($row_gradebook = iDatabase::fetch_row($rs_gradebook)) { - $a_categories[] = $row_gradebook[0]; - } - } - - // get all gradebook score display - $query = "SELECT * FROM $dbNameForm.gradebook_score_display"; - $rs_score_display = iDatabase::query($query); - if (iDatabase::num_rows($rs_score_display) > 0) { - $score_color_percent = api_get_setting('gradebook_score_display_colorsplit'); - while ($row_score_display = iDatabase::fetch_array($rs_score_display)) { - $score = $row_score_display['score']; - $display = $row_score_display['display']; - foreach ($a_categories as $category_id) { - $ins = "INSERT INTO $dbNameForm.gradebook_score_display(score, display, category_id, score_color_percent) VALUES('$score', '$display', $category_id, '$score_color_percent')"; - iDatabase::query($ins); - } - } - // remove score display with category id = 0 - $del = "DELETE FROM $dbNameForm.gradebook_score_display WHERE category_id = 0"; - iDatabase::query($del); - } - } - - // Now clean the deprecated id_coach field from the session_rel_course table - $m_q_list = get_sql_file_contents('migrate-db-' . $old_file_version . '-' . $new_file_version . '-post.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - Log::error('Database name ' . $dbNameForm . ' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database ' . $dbNameForm . ' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - Log::notice("Database::query($dbNameForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbNameForm, executed: $query"); - } - } - } - } - } - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-' . $old_file_version . '-' . $new_file_version . '-pre.sql', 'stats'); - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - Log::error('Database name ' . $dbStatsForm . ' is too long, skipping'); - } elseif (!in_array($dbStatsForm, $dblist)) { - Log::error('Database ' . $dbStatsForm . ' was not found, skipping'); - } else { - iDatabase::select_db($dbStatsForm); - - foreach ($s_q_list as $query) { - if ($only_test) { - Log::notice("Database::query($dbStatsForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbStatsForm, executed: $query"); - } - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - } - $tables = iDatabase::get_tables($dbStatsForm); - foreach ($tables as $table) { - $query = "ALTER TABLE `" . $table . "` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;"; - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - $query = "ALTER DATABASE `" . $dbStatsForm . "` DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;"; - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - - - // chamilo_stat.track_e_attempt table update changing id by id_auto - - $sql = "SELECT exe_id, question_id, course_code, answer FROM $dbStatsForm.track_e_attempt"; - $result = iDatabase::query($sql); - if (iDatabase::num_rows($result) > 0) { - while ($row = iDatabase::fetch_array($result)) { - $course_code = $row['course_code']; - $course_info = api_get_course_info($course_code); - if (empty($course_info)) { - continue; - } - $my_course_db = $course_info['dbName']; - $question_id = $row['question_id']; - $answer = $row['answer']; - $exe_id = $row['exe_id']; - - if(empty($answer)){ - continue; - } - - //getting the type question id - $sql_question = "SELECT type FROM $my_course_db.quiz_question where id = $question_id"; - $res_question = iDatabase::query($sql_question); - $row = iDatabase::fetch_array($res_question); - $type = $row['type']; - - require_once api_get_path(SYS_CODE_PATH) . 'exercice/question.class.php'; - //this type of questions produce problems in the track_e_attempt table - if (in_array($type, array(UNIQUE_ANSWER, MULTIPLE_ANSWER, MATCHING, MULTIPLE_ANSWER_COMBINATION))) { - $sql_question = "SELECT id_auto FROM $my_course_db.quiz_answer where question_id = $question_id and id = $answer"; - $res_question = iDatabase::query($sql_question); - $row = iDatabase::fetch_array($res_question); - if($row){ - $id_auto = $row['id_auto']; - if (!empty($id_auto)) { - $sql = "UPDATE $dbStatsForm.track_e_attempt SET answer = '$id_auto' WHERE exe_id = $exe_id AND question_id = $question_id AND course_code = '$course_code' and answer = $answer "; - iDatabase::query($sql); - } - } - } - } - } - } - } - - - - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-' . $old_file_version . '-' . $new_file_version . '-pre.sql', 'user'); - if (count($u_q_list) > 0) { - // Now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - Log::error('Database name ' . $dbUserForm . ' is too long, skipping'); - } elseif (!in_array($dbUserForm, $dblist)) { - Log::error('Database ' . $dbUserForm . ' was not found, skipping'); - } else { - iDatabase::select_db($dbUserForm); - foreach ($u_q_list as $query) { - if ($only_test) { - Log::notice("Database::query($dbUserForm,$query)"); - Log::notice("In $dbUserForm, executed: $query"); - } else { - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - } - $tables = iDatabase::get_tables($dbUserForm); - foreach ($tables as $table) { - $query = "ALTER TABLE `" . $table . "` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;"; - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - $query = "ALTER DATABASE `" . $dbUserForm . "` DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;"; - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - } - // The SCORM database doesn't need a change in the pre-migrate part - ignore - } - - $prefix = ''; - if ($singleDbForm) { - $prefix = get_config_param('table_prefix'); - } - - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-' . $old_file_version . '-' . $new_file_version . '-pre.sql', 'course'); - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - Log::error('Database name ' . $dbNameForm . ' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database ' . $dbNameForm . ' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - $res = iDatabase::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL ORDER BY code"); - - if ($res === false) { - die('Error while querying the courses list in update_db-1.8.6.2-1.8.7.inc.php'); - } - - if (iDatabase::num_rows($res) > 0) { - $i = 0; - $list = array(); - while ($row = iDatabase::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row_course) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (!$singleDbForm) { // otherwise just use the main one - iDatabase::select_db($row_course['db_name']); - } - - foreach ($c_q_list as $query) { - if ($singleDbForm) { - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query); - } - - if ($only_test) { - Log::notice("Database::query(" . $row_course['db_name'] . ",$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In " . $row_course['db_name'] . ", executed: $query"); - } - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - } - - if (!$singleDbForm) { - $tables = iDatabase::get_tables($row_course['db_name']); - foreach ($tables as $table) { - $query = "ALTER TABLE `" . $table . "` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;"; - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - $query = "ALTER DATABASE `" . $row_course['db_name'] . "` DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;"; - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - $t_student_publication = $row_course['db_name'] . ".student_publication"; - $t_item_property = $row_course['db_name'] . ".item_property"; - - if ($singleDbForm) { - $t_student_publication = "$prefix{$row_course['db_name']}_student_publication"; - $t_item_property = "$prefix{$row_course['db_name']}_item_property"; - } - - $sql_insert_user = "SELECT ref, insert_user_id FROM $t_item_property WHERE tool='work'"; - - $rs_insert_user = iDatabase::query($sql_insert_user); - - if ($rs_insert_user === false) { - Log::error('Could not query insert_user_id table: ' . iDatabase::error()); - } else { - if (iDatabase::num_rows($rs_insert_user) > 0) { - while ($row_ids = iDatabase::fetch_array($rs_insert_user)) { - $user_id = $row_ids['insert_user_id']; - $ref = $row_ids['ref']; - $sql_upd = "UPDATE $t_student_publication SET user_id='$user_id' WHERE id='$ref'"; - iDatabase::query($sql_upd); - } - } - } - - //updating parent_id of the student_publication table - $sql = 'SELECT id, url, parent_id FROM ' . $t_student_publication; - $result = iDatabase::query($sql); - if (iDatabase::num_rows($result) > 0) { - $items = iDatabase::store_result($result); - $directory_list = $file_list = array(); - - foreach ($items as $item) { - $student_slash = substr($item['url'], 0, 1); - //means this is a directory - if ($student_slash == '/') { - $directory_list[$item['id']] = $item['url']; - } else { - // this is a file with no parents - if ($item['parent_id'] == 0) - $file_list [] = $item; - } - } - - if (is_array($file_list) && count($file_list) > 0) { - foreach ($file_list as $file) { - $parent_id = 0; - if (is_array($directory_list) && count($directory_list) > 0) { - foreach ($directory_list as $id => $dir) { - $pos = strpos($file['url'], $dir . '/'); - if ($pos !== false) { - $parent_id = $id; - break; - } - } - } - - if ($parent_id != 0) { - $sql = 'UPDATE ' . $t_student_publication . ' SET parent_id = ' . $parent_id . ' WHERE id = ' . $file['id'] . ''; - iDatabase::query($sql); - } - } - } - } - } - } - } - } - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-' . $old_file_version . '-' . $new_file_version . '-post.sql', 'course'); - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - Log::error('Database name ' . $dbNameForm . ' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database ' . $dbNameForm . ' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - $res = iDatabase::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL"); - if ($res === false) { - die('Error while querying the courses list in update_db-1.8.6.2-1.8.7.inc.php'); - } - if (iDatabase::num_rows($res) > 0) { - $i = 0; - while ($row = iDatabase::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - $prefix_course = $prefix; - if ($singleDbForm) { - $prefix_course = $prefix . $row['db_name'] . "_"; - } else { - iDatabase::select_db($row['db_name']); - } - - foreach ($c_q_list as $query) { - if ($singleDbForm) { //otherwise just use the main one - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix$2$3", $query); - } - if ($only_test) { - Log::notice("Database::query(" . $row['db_name'] . ",$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In " . $row['db_name'] . ", executed: $query"); - } - } - } - } - } - } - } -} else { - - echo 'You are not allowed here !' . __FILE__; -} diff --git a/main/install/update-db-1.8.7-1.8.8.inc.php b/main/install/update-db-1.8.7-1.8.8.inc.php deleted file mode 100755 index b085a44aa0..0000000000 --- a/main/install/update-db-1.8.7-1.8.8.inc.php +++ /dev/null @@ -1,409 +0,0 @@ -'.get_lang('Error').' ! Chamilo '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.

- '.get_lang('PleasGoBackToStep1').'. -

- '; - exit (); - } - - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - - $dbScormForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbScormForm); - - if (!empty($dbPrefixForm) && strpos($dbScormForm, $dbPrefixForm) !== 0) { - $dbScormForm = $dbPrefixForm.$dbScormForm; - } - - if (empty($dbScormForm) || $dbScormForm == 'mysql' || $dbScormForm == $dbPrefixForm) { - $dbScormForm = $dbPrefixForm.'scorm'; - } - - /* Normal upgrade procedure: start by updating main, statistic, user databases */ - - // If this script has been included by index.php, not update_courses.php, so - // that we want to change the main databases as well... - $only_test = false; - $log = 0; - if (defined('SYSTEM_INSTALLATION')) { - - if ($singleDbForm) { - $dbStatsForm = $dbNameForm; - $dbScormForm = $dbNameForm; - $dbUserForm = $dbNameForm; - } - /** - * Update the databases "pre" migration - */ - include_once '../lang/english/trad4all.inc.php'; - - if ($languageForm != 'english') { - // languageForm has been escaped in index.php - include_once '../lang/'.$languageForm.'/trad4all.inc.php'; - } - - // Get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - Log::error('Database name '.$dbNameForm.' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database '.$dbNameForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - foreach ($m_q_list as $query){ - if ($only_test) { - Log::notice("iDatabase::query($dbNameForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbNameForm, executed: $query"); - } - if ($res === false) { - Log::error('Error in '.$query.': '.iDatabase::error()); - } - } - } - } - } - - /* // This fragment of code is not necessary so far. - // Get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-post.sql', 'main'); - if (count($m_q_list) > 0) { - // Now use the $m_q_list - // We connect to the right DB first to make sure we can use the queries - // without a database name. - if (strlen($dbNameForm) > 40) { - error_log('Database name '.$dbNameForm.' is too long, skipping'); - } elseif (!in_array($dbNameForm,$dblist)) { - error_log('Database '.$dbNameForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - foreach ($m_q_list as $query) { - if ($only_test) { - error_log("iDatabase::query($dbNameForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - error_log("In $dbNameForm, executed: $query"); - } - } - } - } - } - */ - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'stats'); - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - Log::error('Database name '.$dbStatsForm.' is too long, skipping'); - } elseif (!in_array($dbStatsForm, $dblist)){ - Log::error('Database '.$dbStatsForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbStatsForm); - - foreach ($s_q_list as $query) { - if ($only_test) { - Log::notice("iDatabase::query($dbStatsForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In $dbStatsForm, executed: $query"); - } - if ($res === false) { - Log::error('Error in '.$query.': '.iDatabase::error()); - } - } - } - - } - } - - - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'user'); - if (count($u_q_list) > 0) { - // Now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - Log::error('Database name '.$dbUserForm.' is too long, skipping'); - } elseif (!in_array($dbUserForm,$dblist)) { - Log::error('Database '.$dbUserForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbUserForm); - foreach ($u_q_list as $query) { - if ($only_test) { - Log::notice("iDatabase::query($dbUserForm,$query)"); - Log::notice("In $dbUserForm, executed: $query"); - } else { - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in '.$query.': '.iDatabase::error()); - } - } - } - } - } - // The SCORM database doesn't need a change in the pre-migrate part - ignore - } - - $prefix = ''; - if ($singleDbForm) { - $prefix = get_config_param ('table_prefix'); - } - - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'course'); - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - Log::error('Database name '.$dbNameForm.' is too long, skipping'); - } elseif(!in_array($dbNameForm, $dblist)) { - Log::error('Database '.$dbNameForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - $res = iDatabase::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL ORDER BY code"); - - if ($res === false) { die('Error while querying the courses list in update_db-1.8.7.1-1.8.8.inc.php'); } - - if (iDatabase::num_rows($res) > 0) { - $i = 0; - $list = array(); - while ($row = iDatabase::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row_course) { - // Now use the $c_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (!$singleDbForm) { // otherwise just use the main one - iDatabase::select_db($row_course['db_name']); - } - Log::notice('Course db ' . $row_course['db_name']); - - foreach ($c_q_list as $query) { - if ($singleDbForm) { - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query); - } - - if ($only_test) { - Log::notice("iDatabase::query(".$row_course['db_name'].",$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In ".$row_course['db_name'].", executed: $query"); - } - if ($res === false) { - Log::error('Error in '.$query.': '.iDatabase::error()); - } - } - } - - $table_lp_item_view = $row_course['db_name'].".lp_item_view"; - $table_lp_view = $row_course['db_name'].".lp_view"; - $table_lp_item = $row_course['db_name'].".lp_item"; - - if ($singleDbForm) { - $table_lp_item_view = "$prefix{$row_course['db_name']}_lp_item_view"; - $table_lp_view = "$prefix{$row_course['db_name']}_lp_view"; - $table_lp_item = "$prefix{$row_course['db_name']}_lp_item"; - } - - // Filling the track_e_exercices.orig_lp_item_view_id field in order to have better traceability in exercises included in a LP see #3188 - - $query = "SELECT DISTINCT path as exercise_id, lp_item_id, lp_view_id, user_id, v.lp_id - FROM $table_lp_item_view iv INNER JOIN $table_lp_view v ON v.id = iv.lp_view_id INNER JOIN $table_lp_item i ON i.id = lp_item_id - WHERE item_type = 'quiz'"; - $result = iDatabase::query($query); - - if (iDatabase::num_rows($result) > 0) { - while ($row = iDatabase::fetch_array($result,'ASSOC')) { - $sql = "SELECT exe_id FROM $dbStatsForm.track_e_exercices - WHERE exe_user_id = {$row['user_id']} AND - exe_cours_id = '{$row_course['code']}' AND - exe_exo_id = {$row['exercise_id']} AND - orig_lp_id = {$row['lp_id']} AND - orig_lp_item_id = {$row['lp_item_id']} "; - $sub_result = iDatabase::query($sql); - $exe_list = array(); - while ($sub_row = iDatabase::fetch_array($sub_result,'ASSOC')) { - $exe_list[] = $sub_row['exe_id']; - } - - $sql = "SELECT iv.id, iv.view_count - FROM $table_lp_item_view iv INNER JOIN $table_lp_view v ON v.id = iv.lp_view_id INNER JOIN $table_lp_item i ON i.id = lp_item_id - WHERE item_type = 'quiz' AND user_id = {$row['user_id']} AND path = {$row['exercise_id']} "; - $sub_result = iDatabase::query($sql); - $lp_item_view_id_list = array(); - while ($sub_row = iDatabase::fetch_array($sub_result,'ASSOC')) { - $lp_item_view_id_list[] = $sub_row['id']; - } - $i = 0; - foreach($exe_list as $exe_id) { - $lp_item_view_id = $lp_item_view_id_list[$i]; - $update = "UPDATE $dbStatsForm.track_e_exercices SET orig_lp_item_view_id = '$lp_item_view_id' WHERE exe_id = $exe_id "; - iDatabase::query($update); - $i++; - } - } - } - } - } - - //Adding notifications options - - $sql = "INSERT INTO $dbNameForm.user_field (field_type, field_variable, field_display_text, field_visible, field_changeable, field_default_value) values (4, 'mail_notify_invitation', 'MailNotifyInvitation',1,1,'1') "; - $result = iDatabase::query($sql); - $id = iDatabase::insert_id(); - - $sql = "INSERT INTO $dbNameForm.user_field_options (field_id, option_value, option_display_text, option_order) values ($id, '1', 'AtOnce',1) "; - $result = iDatabase::query($sql); - $sql = "INSERT INTO $dbNameForm.user_field_options (field_id, option_value, option_display_text, option_order) values ($id, '8', 'Daily',2) "; - $result = iDatabase::query($sql); - $sql = "INSERT INTO $dbNameForm.user_field_options (field_id, option_value, option_display_text, option_order) values ($id, '0', 'No',3) "; - $result = iDatabase::query($sql); - - - $sql = "INSERT INTO $dbNameForm.user_field (field_type, field_variable, field_display_text, field_visible, field_changeable, field_default_value) values (4, 'mail_notify_message', 'MailNotifyMessage',1,1,'1')"; - $result = iDatabase::query($sql); - $id = iDatabase::insert_id(); - - $sql = "INSERT INTO $dbNameForm.user_field_options (field_id, option_value, option_display_text, option_order) values ($id, '1', 'AtOnce',1) "; - $result = iDatabase::query($sql); - $sql = "INSERT INTO $dbNameForm.user_field_options (field_id, option_value, option_display_text, option_order) values ($id, '8', 'Daily',2) "; - $result = iDatabase::query($sql); - $sql = "INSERT INTO $dbNameForm.user_field_options (field_id, option_value, option_display_text, option_order) values ($id, '0', 'No',3) "; - $result = iDatabase::query($sql); - - - $sql = "INSERT INTO $dbNameForm.user_field (field_type, field_variable, field_display_text, field_visible, field_changeable, field_default_value) values (4, 'mail_notify_group_message','MailNotifyGroupMessage',1,1,'1') "; - $result = iDatabase::query($sql); - $id = iDatabase::insert_id(); - - $sql = "INSERT INTO $dbNameForm.user_field_options (field_id, option_value, option_display_text, option_order) values ($id, '1', 'AtOnce',1) "; - $result = iDatabase::query($sql); - $sql = "INSERT INTO $dbNameForm.user_field_options (field_id, option_value, option_display_text, option_order) values ($id, '8', 'Daily',2) "; - $result = iDatabase::query($sql); - $sql = "INSERT INTO $dbNameForm.user_field_options (field_id, option_value, option_display_text, option_order) values ($id, '0', 'No',3) "; - $result = iDatabase::query($sql); - - //Fixing table access_url_rel_course if the platform have courses that were created in Dok€os 1.8.5 - - if (!isset($_configuration['multiple_access_urls']) || $_configuration['multiple_access_urls'] == false) { - $sql = "SELECT code FROM $dbNameForm.course"; - $result = iDatabase::query($sql); - while ($row = iDatabase::fetch_array($result)) { - //Adding course to default URL just in case - $sql = "INSERT INTO $dbNameForm.access_url_rel_course SET course_code = '".iDatabase::escape_string($row['code'])."', access_url_id = '1' "; - iDatabase::query($sql); - } - } - } - } - - - - - - - /* // This fragment of code is not necessary so far. - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-post.sql', 'course'); - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - Log::error('Database name '.$dbNameForm.' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database '.$dbNameForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - $res = iDatabase::query("SELECT code,db_name,directory,course_language FROM course WHERE target_course_code IS NULL"); - if ($res === false) { die('Error while querying the courses list in update_db-1.8.7-1.8.8.inc.php'); } - if (iDatabase::num_rows($res) > 0) { - $i = 0; - while ($row = iDatabase::fetch_array($res)) { - $list[] = $row; - $i++; - } - foreach ($list as $row) { - // Now use the $c_q_list - // We connect to the right DB first to make sure we can use the queries - // without a database name - $prefix_course = $prefix; - if ($singleDbForm) { - $prefix_course = $prefix.$row['db_name']."_"; - } else { - iDatabase::select_db($row['db_name']); - } - - foreach($c_q_list as $query) { - if ($singleDbForm) { //otherwise just use the main one - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix$2$3", $query); - } - if ($only_test) { - Log::notice("iDatabase::query(".$row['db_name'].",$query)"); - } else { - $res = iDatabase::query($query); - if ($log) { - Log::notice("In ".$row['db_name'].", executed: $query"); - } - } - } - } - } - } - } - */ -} else { - echo 'You are not allowed here !' . __FILE__; -} diff --git a/main/install/update-db-1.8.8-1.9.0.inc.php b/main/install/update-db-1.8.8-1.9.0.inc.php deleted file mode 100755 index bd0e37b5b3..0000000000 --- a/main/install/update-db-1.8.8-1.9.0.inc.php +++ /dev/null @@ -1,678 +0,0 @@ -'.get_lang('Error').' ! Chamilo '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.

- '.get_lang('PleasGoBackToStep1').'. -

- '; - exit (); - } - - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - - $dbScormForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbScormForm); - - if (!empty($dbPrefixForm) && strpos($dbScormForm, $dbPrefixForm) !== 0) { - $dbScormForm = $dbPrefixForm.$dbScormForm; - } - - if (empty($dbScormForm) || $dbScormForm == 'mysql' || $dbScormForm == $dbPrefixForm) { - $dbScormForm = $dbPrefixForm.'scorm'; - } - - /* Normal upgrade procedure: start by updating main, statistic, user databases */ - - // If this script has been included by index.php, not update_courses.php, so - // that we want to change the main databases as well... - $only_test = false; - if (defined('SYSTEM_INSTALLATION')) { - - if ($singleDbForm) { - $dbStatsForm = $dbNameForm; - $dbScormForm = $dbNameForm; - $dbUserForm = $dbNameForm; - } - /** - * Update the databases "pre" migration - */ - include_once '../lang/english/trad4all.inc.php'; - - if ($languageForm != 'english') { - // languageForm has been escaped in index.php - include_once '../lang/'.$languageForm.'/trad4all.inc.php'; - } - - // Get the main queries list (m_q_list) - $m_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'main'); - - if (count($m_q_list) > 0) { - // Now use the $m_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - Log::error('Database name '.$dbNameForm.' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database '.$dbNameForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbNameForm); - foreach ($m_q_list as $query){ - if ($only_test) { - Log::notice("iDatabase::query($dbNameForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in '.$query.': '.iDatabase::error()); - } - } - } - } - } - - if (INSTALL_TYPE_UPDATE == 'update') { - - //Migrate classes to the new classes (usergroups) - - $sql = "SELECT selected_value FROM $dbNameForm.settings_current WHERE variable='use_session_mode' "; - $result = iDatabase::query($sql); - $result = Database::fetch_array($result); - $session_mode = $result['selected_value']; - - if ($session_mode == 'true') { - - $sql = "UPDATE $dbNameForm.settings_current SET selected_value = 'true' WHERE variable='use_session_mode' "; - $result = iDatabase::query($sql); - - $sql = "SELECT * FROM $dbNameForm.class"; - $result = iDatabase::query($sql); - $count = 0; - $new_table = "$dbNameForm.usergroup"; - $classes_added = 0; - $mapping_classes = array(); - if (Database::num_rows($result)) { - while($row = iDatabase::fetch_array($result, 'ASSOC')) { - $old_id = $row['id']; - unset($row['id']); - unset($row['code']); - $new_user_group_id = Database::insert($new_table, $row); - $mapping_classes[$old_id] = $new_user_group_id; - if (is_numeric($id)) { - $classes_added ++; - } - } - } - - $sql = "SELECT * FROM $dbNameForm.class_user"; - $result = iDatabase::query($sql); - $new_table = "$dbNameForm.usergroup_rel_user"; - if (Database::num_rows($result)) { - while ($row = iDatabase::fetch_array($result, 'ASSOC')) { - $values = array('usergroup_id' => $mapping_classes[$row['class_id']], - 'user_id' => $row['user_id']); - iDatabase::insert($new_table, $values); - } - } - - $sql = "SELECT * FROM $dbNameForm.course_rel_class"; - $result = iDatabase::query($sql); - $new_table = "$dbNameForm.usergroup_rel_course"; - - if (Database::num_rows($result)) { - while ($row = iDatabase::fetch_array($result, 'ASSOC')) { - $course_code = $row['course_code']; - $course_code = addslashes($course_code); - $sql_course = "SELECT id from $dbNameForm.course WHERE code = '$course_code'"; - $result_course = iDatabase::query($sql_course); - $result_course = Database::fetch_array($result_course); - $course_id = $result_course['id']; - $values = array('usergroup_id' => $mapping_classes[$row['class_id']], - 'course_id' => $course_id); - iDatabase::insert($new_table, $values); - } - } - - Log::notice("#classes added $classes_added"); - } - } - - - // Get the stats queries list (s_q_list) - $s_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'stats'); - if (count($s_q_list) > 0) { - // Now use the $s_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbStatsForm) > 40) { - Log::error('Database name '.$dbStatsForm.' is too long, skipping'); - } elseif (!in_array($dbStatsForm, $dblist)){ - Log::error('Database '.$dbStatsForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbStatsForm); - - foreach ($s_q_list as $query) { - if ($only_test) { - Log::notice("iDatabase::query($dbStatsForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in '.$query.': '.iDatabase::error()); - } - } - } - } - } - - //Moving Stats DB to the main DB - - $stats_table = array( - "track_c_browsers", - "track_c_countries", - "track_c_os", - "track_c_providers", - "track_c_referers", - "track_e_access", - "track_e_attempt", - "track_e_attempt_recording", - "track_e_course_access", - "track_e_default", - "track_e_downloads", - "track_e_exercices", - "track_e_hotpotatoes", - "track_e_hotspot", - "track_e_item_property", - "track_e_lastaccess", - "track_e_links", - "track_e_login", - "track_e_online", - "track_e_open", - "track_e_uploads", - "track_stored_values", - "track_stored_values_stack", - ); - - if ($dbNameForm != $dbStatsForm) { - iDatabase::select_db($dbStatsForm); - foreach ($stats_table as $stat_table) { - $sql = "ALTER TABLE $dbStatsForm.$stat_table RENAME $dbNameForm.$stat_table"; - iDatabase::query($sql); - } - iDatabase::select_db($dbNameForm); - } - - // Get the user queries list (u_q_list) - $u_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'user'); - - if (count($u_q_list) > 0) { - // Now use the $u_q_list - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbUserForm) > 40) { - Log::error('Database name '.$dbUserForm.' is too long, skipping'); - } elseif (!in_array($dbUserForm,$dblist)) { - Log::error('Database '.$dbUserForm.' was not found, skipping'); - } else { - iDatabase::select_db($dbUserForm); - foreach ($u_q_list as $query) { - if ($only_test) { - Log::notice("iDatabase::query($dbUserForm,$query)"); - Log::notice("In $dbUserForm, executed: $query"); - } else { - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in '.$query.': '.iDatabase::error()); - } - } - } - } - } - - //Moving user database to the main database - $users_tables = array( - "personal_agenda", - "personal_agenda_repeat", - "personal_agenda_repeat_not", - "user_course_category" - ); - - if ($dbNameForm != $dbUserForm) { - iDatabase::select_db($dbUserForm); - foreach ($users_tables as $table) { - $sql = "ALTER TABLE $dbUserForm.$table RENAME $dbNameForm.$table"; - iDatabase::query($sql); - } - iDatabase::select_db($dbNameForm); - } - } - - //Adding admin user in the access_url_rel_user table - $sql = "SELECT user_id FROM admin WHERE user_id = 1"; - $result = iDatabase::query($sql); - $has_user_id = Database::num_rows($result) > 0; - - $sql = "SELECT * FROM access_url_rel_user WHERE user_id = 1 AND access_url_id = 1"; - $result = iDatabase::query($sql); - $has_entry = Database::num_rows($result) > 0; - - if ($has_user_id && !$has_entry) { - $sql = "INSERT INTO access_url_rel_user VALUES(1, 1)"; - iDatabase::query($sql); - } - - global $_configuration; - - $prefix = ''; - if ($singleDbForm) { - $prefix = get_config_param('table_prefix'); - } - - Log::notice("Database prefix: '$prefix'"); - - // Get the courses databases queries list (c_q_list) - $c_q_list = get_sql_file_contents('migrate-db-'.$old_file_version.'-'.$new_file_version.'-pre.sql', 'course'); - Log::notice('Starting migration: '.$old_file_version.' - '.$new_file_version); - - if (count($c_q_list) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - Log::error('Database name '.$dbNameForm.' is too long, skipping'); - } elseif(!in_array($dbNameForm, $dblist)) { - Log::error('Database '.$dbNameForm.' was not found, skipping'); - } else { - 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"); - - if ($res === false) { die('Error while querying the courses list in update_db-1.8.8-1.9.0.inc.php'); } - - $errors = array(); - - if (iDatabase::num_rows($res) > 0) { - $i = 0; - $list = array(); - while ($row = iDatabase::fetch_array($res)) { - $list[] = $row; - $i++; - } - - foreach ($list as $row_course) { - if (!$singleDbForm) { // otherwise just use the main one - iDatabase::select_db($row_course['db_name']); - } - Log::notice('Course db ' . $row_course['db_name']); - - // Now use the $c_q_list - foreach ($c_q_list as $query) { - if ($singleDbForm) { - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query); - } - if ($only_test) { - Log::notice("iDatabase::query(".$row_course['db_name'].",$query)"); - } else { - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in '.$query.': '.iDatabase::error()); - } - } - } - - $work_table = $row_course['db_name'].".student_publication"; - $item_table = $row_course['db_name'].".item_property"; - - if ($singleDbForm) { - $work_table = "$prefix{$row_course['db_name']}_student_publication"; - $item_table = $row_course['db_name'].".item_property"; - } - - if (!$singleDbForm) { - // otherwise just use the main one - iDatabase::select_db($row_course['db_name']); - } else { - iDatabase::select_db($dbNameForm); - } - - - /* Start work fix */ - - /* Fixes the work subfolder and work with no parent issues */ - - //1. Searching for works with no parents - $sql = "SELECT * FROM $work_table WHERE parent_id = 0 AND filetype ='file'"; - $result = Database::query($sql); - - $work_list = array(); - - if (Database::num_rows($result)) { - while ($row = Database::fetch_array($result, 'ASSOC')) { - $work_list[] = $row; - } - } - - $today = api_get_utc_datetime(); - $user_id = 1; - require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php'; - - $sys_course_path = api_get_path(SYS_COURSE_PATH); - $course_dir = $sys_course_path . $row_course['directory']; - $base_work_dir = $course_dir . '/work'; - - //2. Looping if there are works with no parents - if (!empty($work_list)) { - $work_dir_created = array(); - - foreach ($work_list as $work) { - $session_id = intval($work['session_id']); - $group_id = intval($work['post_group_id']); - $work_key = $session_id.$group_id; - - //Only create the folder once - if (!isset($work_dir_created[$work_key])) { - - $dir_name = "default_tasks_".$group_id."_".$session_id; - - //2.1 Creating a new work folder - $sql = "INSERT INTO $work_table SET - url = 'work/".$dir_name."', - title = 'Tasks', - description = '', - author = '', - active = '1', - accepted = '1', - filetype = 'folder', - post_group_id = '$group_id', - sent_date = '".$today."', - parent_id = '0', - qualificator_id = '', - user_id = '".$user_id."'"; - iDatabase::query($sql); - - $id = Database::insert_id(); - //2.2 Adding the folder in item property - if ($id) { - //api_item_property_update($row_course, 'work', $id, 'DirectoryCreated', $user_id, $group_id, null, 0, 0 , $session_id); - $sql = "INSERT INTO $item_table (tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id, to_group_id, visibility, id_session) - VALUES ('work','$id','$today', '$user_id', '$today', 'DirectoryCreated','$user_id', '$group_id', '1', '$session_id')"; - - iDatabase::query($sql); - $work_dir_created[$work_key] = $id; - create_unexisting_work_directory($base_work_dir, $dir_name); - $final_dir = $base_work_dir.'/'.$dir_name; - } - } else { - $final_dir = $base_work_dir.'/'.$dir_name; - } - - //2.3 Updating the url - if (!empty($work_dir_created[$work_key])) { - $parent_id = $work_dir_created[$work_key]; - $new_url = "work/".$dir_name.'/'.basename($work['url']); - $new_url = Database::escape_string($new_url);$sql = "UPDATE $work_table SET url = '$new_url', parent_id = $parent_id, contains_file = '1' WHERE id = {$work['id']}"; - iDatabase::query($sql); - if (is_dir($final_dir)) { - rename($course_dir.'/'.$work['url'], $course_dir.'/'.$new_url); - } - } - } - } - - //3.0 Moving subfolders to the root - $sql = "SELECT * FROM $work_table WHERE parent_id <> 0 AND filetype ='folder'"; - $result = Database::query($sql); - $work_list = array(); - - if (Database::num_rows($result)) { - while ($row = Database::fetch_array($result, 'ASSOC')) { - $work_list[] = $row; - } - if (!empty($work_list)) { - foreach ($work_list as $work_folder) { - $folder_id = $work_folder['id']; - check_work($folder_id, $work_folder['url'], $work_table, $base_work_dir); - } - } - } - - /* End of work fix */ - - //Course tables to be migrated - $table_list = array( - 'announcement', - 'announcement_attachment', - 'attendance', - 'attendance_calendar', - 'attendance_result', - 'attendance_sheet', - 'attendance_sheet_log', - 'blog', - 'blog_attachment', - 'blog_comment', - 'blog_post', - 'blog_rating', - 'blog_rel_user', - 'blog_task', - 'blog_task_rel_user', - 'calendar_event', - 'calendar_event_attachment', - 'calendar_event_repeat', - 'calendar_event_repeat_not', - 'chat_connected', - 'course_description', - 'course_setting', - 'document', - 'dropbox_category', - 'dropbox_feedback', - 'dropbox_file', - 'dropbox_person', - 'dropbox_post', - 'forum_attachment', - 'forum_category', - 'forum_forum', - 'forum_mailcue', - 'forum_notification', - 'forum_post', - 'forum_thread', - 'forum_thread_qualify', - 'forum_thread_qualify_log', - 'glossary', - 'group_category', - 'group_info', - 'group_rel_tutor', - 'group_rel_user', - 'item_property', - 'link', - 'link_category', - 'lp', - 'lp_item', - 'lp_item_view', - 'lp_iv_interaction', - 'lp_iv_objective', - 'lp_view', - 'notebook', - 'metadata', - 'online_connected', - 'online_link', - 'permission_group', - 'permission_task', - 'permission_user', - 'quiz', - 'quiz_answer', - 'quiz_question', - 'quiz_question_option', - 'quiz_rel_question', - 'resource', - 'role', - 'role_group', - 'role_permissions', - 'role_user', - 'student_publication', - 'student_publication_assignment', - 'survey', - 'survey_answer', - 'survey_group', - 'survey_invitation', - 'survey_question', - 'survey_question_option', - 'thematic', - 'thematic_advance', - 'thematic_plan', - 'tool', - 'tool_intro', - 'userinfo_content', - 'userinfo_def', - 'wiki', - 'wiki_conf', - 'wiki_discuss', - 'wiki_mailcue' - ); - - Log::notice('<<<------- Loading DB course '.$row_course['db_name'].' -------->>'); - //Install::message('<<<------- Loading DB course '.$row_course['db_name'].' -------->>'); - - $count = $old_count = 0; - foreach ($table_list as $table) { - $just_table_name = $table; - $old_table = $row_course['db_name'].".".$table; - - if ($singleDbForm) { - $old_table = "$prefix{$row_course['db_name']}_".$table; - $just_table_name = "$prefix{$row_course['db_name']}_".$table; - } - - $course_id = $row_course['id']; - $new_table = DB_COURSE_PREFIX.$table; - - //Use the old database (if this is the case) - - if (!$singleDbForm) { - // otherwise just use the main one - iDatabase::select_db($row_course['db_name']); - } else { - iDatabase::select_db($dbNameForm); - } - - //Count of rows - $sql = "SHOW TABLES LIKE '$just_table_name'"; - $result = iDatabase::query($sql); - - if (Database::num_rows($result)) { - - $sql = "SELECT count(*) FROM $old_table"; - $result = iDatabase::query($sql); - - $old_count = 0; - if ($result) { - $row = iDatabase::fetch_row($result); - $old_count = $row[0]; - } else { - Log::error("Count(*) in table $old_table failed"); - } - - Log::notice("# rows in $old_table: $old_count"); - - $sql = "SELECT * FROM $old_table"; - $result = iDatabase::query($sql); - - $count = 0; - - /* Loads the main database */ - iDatabase::select_db($dbNameForm); - - while($row = iDatabase::fetch_array($result, 'ASSOC')) { - $row['c_id'] = $course_id; - $id = iDatabase::insert($new_table, $row); - if (is_numeric($id)) { - $count++; - } else { - $errors[$old_table][] = $row; - } - } - Log::notice("#rows inserted in $new_table: $count"); - - if ($old_count != $count) { - Log::error("ERROR count of new and old table doesn't match: $old_count - $new_table"); - Log::error("Check the results: "); - Log::error(print_r($errors, 1)); - error_log(print_r($errors, 1)); - } - } else { - Log::error("Seems that the table $old_table doesn't exists "); - } - } - Log::notice('<<<------- end -------->>'); - } - } - } - } -} else { - echo 'You are not allowed here !' . __FILE__; -} - -function check_work($folder_id, $work_url, $work_table, $base_work_dir) { - $uniq_id = uniqid(); - //Looking for subfolders - $sql = "SELECT * FROM $work_table WHERE parent_id = $folder_id AND filetype ='folder'"; - $result = Database::query($sql); - - if (Database::num_rows($result)) { - while ($row = Database::fetch_array($result, 'ASSOC')) { - check_work($row['id'], $row['url'], $work_table, $base_work_dir); - } - } - - //Moving the subfolder in the root - $new_url = '/'.basename($work_url).'_mv_'.$uniq_id; - $new_url = Database::escape_string($new_url); - $sql = "UPDATE $work_table SET url = '$new_url', parent_id = 0 WHERE id = $folder_id"; - iDatabase::query($sql); - - if (is_dir($base_work_dir.$work_url)) { - rename($base_work_dir.$work_url, $base_work_dir.$new_url); - - //Rename all files inside the folder - $sql = "SELECT * FROM $work_table WHERE parent_id = $folder_id AND filetype ='file'"; - $result = Database::query($sql); - - if (Database::num_rows($result)) { - while ($row = Database::fetch_array($result, 'ASSOC')) { - $new_url = "work".$new_url.'/'.basename($row['url']); - $new_url = Database::escape_string($new_url); - $sql = "UPDATE $work_table SET url = '$new_url', parent_id = $folder_id, contains_file = '1' WHERE id = {$row['id']}"; - iDatabase::query($sql); - } - } - } -} diff --git a/main/install/update-db-1.9.0-1.10.0.inc.php b/main/install/update-db-1.9.0-1.10.0.inc.php index 54fa41576e..0c4fe985cd 100644 --- a/main/install/update-db-1.9.0-1.10.0.inc.php +++ b/main/install/update-db-1.9.0-1.10.0.inc.php @@ -39,14 +39,6 @@ if (defined('SYSTEM_INSTALLATION')) { exit (); } - $_configuration['db_glue'] = get_config_param('dbGlu'); - - if ($singleDbForm) { - $_configuration['table_prefix'] = get_config_param('courseTablePrefix'); - $_configuration['main_database'] = get_config_param('mainDbName'); - $_configuration['db_prefix'] = get_config_param('dbNamePrefix'); - } - /* Normal upgrade procedure: start by updating the main database */ // If this script has been included by index.php, not update_courses.php, so @@ -99,13 +91,6 @@ if (defined('SYSTEM_INSTALLATION')) { } } - $prefix = ''; - if ($singleDbForm) { - $prefix = get_config_param('table_prefix'); - } - - Log::notice("Database prefix: '$prefix'"); - // Get the courses databases queries list (c_q_list) $sqlFile = 'migrate-db-'.$oldFileVersion.'-'.$newFileVersion.'-pre.sql'; diff --git a/main/install/update-files-1.6.x-1.8.0.inc.php b/main/install/update-files-1.6.x-1.8.0.inc.php deleted file mode 100755 index faa18b022a..0000000000 --- a/main/install/update-files-1.6.x-1.8.0.inc.php +++ /dev/null @@ -1,152 +0,0 @@ - audio - if (!is_dir($currentCourseRepositorySys . "document/audio")) { - mkdir($currentCourseRepositorySys . "document/audio", $perm); - insert_db($db_name, "audio", get_lang('Audio')); - } - - // document > flash - if (!is_dir($currentCourseRepositorySys . "document/flash")) { - mkdir($currentCourseRepositorySys . "document/flash", $perm); - insert_db($db_name, "flash", get_lang('Flash')); - } - - // document > images - if (!is_dir($currentCourseRepositorySys . "document/images")) { - mkdir($currentCourseRepositorySys . "document/images", $perm); - insert_db($db_name, "images", get_lang('Images')); - } - - // document > video - if (!is_dir($currentCourseRepositorySys . "document/video")) { - mkdir($currentCourseRepositorySys . "document/video", $perm); - insert_db($db_name, "video", get_lang('Video')); - } - - // document > video > flv - if (!is_dir($currentCourseRepositorySys . "document/video/flv")) { - mkdir($currentCourseRepositorySys . "document/video/flv", $perm); - insert_db($db_name, "video", get_lang('Video') . " (flv)"); - } - - // FOLDER UPLOAD - // upload - if (!is_dir($currentCourseRepositorySys . "upload")) { - mkdir($currentCourseRepositorySys . "upload", $perm); - } - - // upload > blog - if (!is_dir($currentCourseRepositorySys . "upload/blog")) { - mkdir($currentCourseRepositorySys . "upload/blog", $perm); - } - - // upload > forum - if (!is_dir($currentCourseRepositorySys . "upload/forum")) { - mkdir($currentCourseRepositorySys . "upload/forum", $perm); - } - - // upload > test - if (!is_dir($currentCourseRepositorySys . "upload/test")) { - mkdir($currentCourseRepositorySys . "upload/test", $perm); - } - - // Updating index file in courses directories to change claroline/ into main/ - $content = ''; - unlink($currentCourseRepositorySys . 'index.php'); - $fp = @ fopen($currentCourseRepositorySys . 'index.php', 'w'); - if ($fp) { - Log::error('Writing redirection file in ' . $currentCourseRepositorySys . 'index.php'); - fwrite($fp, $content); - fclose($fp); - } else { - Log::error('Could not open file ' . $currentCourseRepositorySys . 'index.php'); - } - } - - // Write the config file - write_system_config_file(api_get_path(CONFIGURATION_PATH) . 'configuration.php'); - // Write a distribution file with the config as a backup for the admin - write_system_config_file(api_get_path(CONFIGURATION_PATH) . 'configuration.dist.php'); - // Write a .htaccess file in the course repository - write_courses_htaccess_file($urlAppendPath); - copy($updatePath . 'claroline/inc/conf/add_course.conf.php', $pathForm . 'main/inc/conf/add_course.conf.php'); - copy($updatePath . 'claroline/inc/conf/course_info.conf.php', $pathForm . 'main/inc/conf/course_info.conf.php'); - copy($updatePath . 'claroline/inc/conf/mail.conf.php', $pathForm . 'main/inc/conf/mail.conf.php'); - copy($updatePath . 'claroline/inc/conf/profile.conf.inc.php', $pathForm . 'main/inc/conf/profile.conf.php'); - - Log::notice('Renaming ' . $updatePath . 'claroline/upload/users to ' . $pathForm . 'main/upload/users'); - rename($updatePath . 'claroline/upload/users', $pathForm . 'main/upload/users'); - Log::notice('Renaming ' . $updatePath . 'claroline/upload/audio to ' . $pathForm . 'main/upload/audio'); - rename($updatePath . 'claroline/upload/audio', $pathForm . 'main/upload/audio'); - Log::notice('Renaming ' . $updatePath . 'claroline/upload/images to ' . $pathForm . 'main/upload/images'); - rename($updatePath . 'claroline/upload/images', $pathForm . 'main/upload/images'); - Log::notice('Renaming ' . $updatePath . 'claroline/upload/linked_files to ' . $pathForm . 'main/upload/linked_files'); - rename($updatePath . 'claroline/upload/linked_files', $pathForm . 'main/upload/linked_files'); - Log::notice('Renaming ' . $updatePath . 'claroline/upload/video to ' . $pathForm . 'main/upload/video'); - rename($updatePath . 'claroline/upload/video', $pathForm . 'main/upload/video'); -} else { - - echo 'You are not allowed here !' . __FILE__; -} diff --git a/main/install/update-files-1.8.3-1.8.4.inc.php b/main/install/update-files-1.8.3-1.8.4.inc.php deleted file mode 100755 index 048a22b32b..0000000000 --- a/main/install/update-files-1.8.3-1.8.4.inc.php +++ /dev/null @@ -1,58 +0,0 @@ -') !== false) { - // Ignore the line - $ignore = true; - } - if (!$ignore) { - fwrite($fh, $line); - } - } - if (!$found_version) { - fwrite($fh, '$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n"); - } - if (!$found_stable) { - fwrite($fh, '$_configuration[\'dokeos_stable\'] = '.($new_version_stable ? 'true' : 'false').';'."\r\n"); - } - fwrite($fh, '?>'); - fclose($fh); - -} else { - - echo 'You are not allowed here !' . __FILE__; - -} diff --git a/main/install/update-files-1.8.4-1.8.5.inc.php b/main/install/update-files-1.8.4-1.8.5.inc.php deleted file mode 100755 index 179c401d31..0000000000 --- a/main/install/update-files-1.8.4-1.8.5.inc.php +++ /dev/null @@ -1,58 +0,0 @@ -') !== false) { - // Ignore the line - $ignore = true; - } - if (!$ignore) { - fwrite($fh, $line); - } - } - if (!$found_version) { - fwrite($fh, '$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n"); - } - if (!$found_stable) { - fwrite($fh, '$_configuration[\'dokeos_stable\'] = '.($new_version_stable ? 'true' : 'false').';'."\r\n"); - } - fwrite($fh, '?>'); - fclose($fh); - -} else { - - echo 'You are not allowed here !' . __FILE__; - -} diff --git a/main/install/update-files-1.8.5-1.8.6.inc.php b/main/install/update-files-1.8.5-1.8.6.inc.php deleted file mode 100755 index b267a05d58..0000000000 --- a/main/install/update-files-1.8.5-1.8.6.inc.php +++ /dev/null @@ -1,121 +0,0 @@ -') !== false) { - // Ignore the line - $ignore = true; - } - if (!$ignore) { - fwrite($fh, $line); - } - } - if (!$found_version) { - fwrite($fh, '$_configuration[\'dokeos_version\'] = \'' . $new_version . '\';' . "\r\n"); - } - if (!$found_stable) { - fwrite($fh, '$_configuration[\'dokeos_stable\'] = ' . ($new_version_stable ? 'true' : 'false') . ';' . "\r\n"); - } - fwrite($fh, '?>'); - fclose($fh); - - $sys_course_path = $pathForm . 'courses/'; - - //$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE); - //// Linking (The following line is disabled, connection has been already done) - //$res = @iDatabase::connect(array('server' => $dbHostForm, 'username' => $dbUsernameForm, 'password' => $dbPassForm)); - //iDatabase::select_db($dbNameForm, $link); - iDatabase::select_db($dbNameForm); - - $db_name = $dbNameForm; - $sql = "SELECT * FROM $db_name.course"; - Log::notice('Getting courses for files updates: ' . $sql); - $result = iDatabase::query($sql); - - while ($courses_directories = iDatabase::fetch_array($result)) { - - $currentCourseRepositorySys = $sys_course_path . $courses_directories['directory'] . '/'; - - $db_name = $courses_directories['db_name']; - $origCRS = $updatePath . 'courses/' . $courses_directories['directory']; - - if (!is_dir($origCRS)) { - Log::error('Directory ' . $origCRS . ' does not exist. Skipping.'); - continue; - } - // Move everything to the new hierarchy (from old path to new path) - Log::notice('Renaming ' . $origCRS . ' to ' . $sys_course_path . $courses_directories['directory']); - rename($origCRS, $sys_course_path . $courses_directories['directory']); - Log::notice('Creating dirs in ' . $currentCourseRepositorySys); - - // DOCUMENT FOLDER - // document > shared_folder - if (!is_dir($currentCourseRepositorySys . "document/shared_folder")) { - mkdir($currentCourseRepositorySys . "document/shared_folder", $perm); - } - - // UPLOAD FOLDER - // upload > forum > images - if (!is_dir($currentCourseRepositorySys . "upload/forum/images")) { - mkdir($currentCourseRepositorySys . "upload/forum/images", $perm); - } - - // upload > learning_path - if (!is_dir($currentCourseRepositorySys . "upload/learning_path")) { - mkdir($currentCourseRepositorySys . "upload/learning_path", $perm); - } - - // upload > learning_path > images - if (!is_dir($currentCourseRepositorySys . "upload/learning_path/images")) { - mkdir($currentCourseRepositorySys . "upload/learning_path/images", $perm); - } - - // upload > calendar - if (!is_dir($currentCourseRepositorySys . "upload/calendar")) { - mkdir($currentCourseRepositorySys . "upload/calendar", $perm); - } - - // upload > calendar > images - if (!is_dir($currentCourseRepositorySys . "upload/calendar/images")) { - mkdir($currentCourseRepositorySys . "upload/calendar/images", $perm); - } - } -} else { - - echo 'You are not allowed here !' . __FILE__; -} diff --git a/main/install/update-files-1.8.6-1.8.6.1.inc.php b/main/install/update-files-1.8.6-1.8.6.1.inc.php deleted file mode 100755 index 79100af115..0000000000 --- a/main/install/update-files-1.8.6-1.8.6.1.inc.php +++ /dev/null @@ -1,66 +0,0 @@ -') !== false) { - //ignore the line - $ignore = true; - } - if (!$ignore) { - fwrite($fh, $line); - } - } - if (!$found_version) { - fwrite($fh, '$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n"); - } - if (!$found_stable) { - fwrite($fh, '$_configuration[\'dokeos_stable\'] = '.($new_version_stable ? 'true' : 'false').';'."\r\n"); - } - fwrite($fh, '?>'); - fclose($fh); - - //// Ccreate a specific directory for global thumbails - // home > default_platform_document > template_thumb - if (!is_dir($pathForm.'home/default_platform_document/template_thumb')) { - mkdir($pathForm.'home/default_platform_document/template_thumb', $perm); - } - -} else { - - echo 'You are not allowed here !' . __FILE__; - -} diff --git a/main/install/update-files-1.8.6.1-1.8.6.2.inc.php b/main/install/update-files-1.8.6.1-1.8.6.2.inc.php deleted file mode 100755 index 98e071ba76..0000000000 --- a/main/install/update-files-1.8.6.1-1.8.6.2.inc.php +++ /dev/null @@ -1,98 +0,0 @@ -') !== false) { - //ignore the line - $ignore = true; - } - if (!$ignore) { - fwrite($fh, $line); - } - } - if (!$found_version) { - fwrite($fh, '$_configuration[\'dokeos_version\'] = \'' . $new_version . '\';' . "\r\n"); - } - if (!$found_stable) { - fwrite($fh, '$_configuration[\'dokeos_stable\'] = ' . ($new_version_stable ? 'true' : 'false') . ';' . "\r\n"); - } - fwrite($fh, '?>'); - fclose($fh); - - $sys_course_path = $pathForm . 'courses/'; - - $perm = api_get_permissions_for_new_directories(); - - // The following line is disabled, connection has been already done - //$link = iDatabase::connect(array('server' => $dbHostForm, 'username' => $dbUsernameForm, 'password' => $dbPassForm)); - //iDatabase::select_db($dbNameForm, $link); - iDatabase::select_db($dbNameForm); - - $db_name = $dbNameForm; - $sql = "SELECT * FROM $db_name.course"; - Log::notice('Getting courses for files updates: ' . $sql); - $result = iDatabase::query($sql); - - if (iDatabase::num_rows($result) > 0) { - while ($courses_directories = iDatabase::fetch_array($result)) { - $currentCourseRepositorySys = $sys_course_path . $courses_directories['directory'] . '/'; - // upload > announcements - $path = $currentCourseRepositorySys . "upload/announcements"; - if (!is_dir($path)) { - $success = mkdir($path, $perm, true); - if(!$success){ - $course_directory = $courses_directories['directory']; - Log::error("Failed to create dir path: $path, course directory: $course_directory, sys course path: $sys_course_path, perm: , perm: $perm"); - } - } - - // upload > announcements > images - $path = $currentCourseRepositorySys . "upload/announcements/images"; - if (!is_dir($path)) { - $success = mkdir($path, $perm, true); - if(!$success){ - $course_directory = $courses_directories['directory']; - Log::error("Failed to create dir path: $path, course directory: $course_directory, sys course path: $sys_course_path, perm: $perm"); - } - } - } - } - - //// Create a specific directory for global thumbails - // home > default_platform_document > template_thumb - if (!is_dir($pathForm . 'home/default_platform_document/template_thumb')) { - mkdir($pathForm . 'home/default_platform_document/template_thumb', $perm); - } -} else { - - echo 'You are not allowed here !' . __FILE__; -} diff --git a/main/install/update-files-1.8.6.2-1.8.7.inc.php b/main/install/update-files-1.8.6.2-1.8.7.inc.php deleted file mode 100755 index fa8537fa96..0000000000 --- a/main/install/update-files-1.8.6.2-1.8.7.inc.php +++ /dev/null @@ -1,77 +0,0 @@ -') !== false) { - $ignore = true; - } - if (!$ignore) { - fwrite($fh, $line); - } - } - if (!$found_version) { - fwrite($fh, '$_configuration[\'system_version\'] = \''.$new_version.'\';'."\r\n"); - } - if (!$found_stable) { - fwrite($fh, '$_configuration[\'system_stable\'] = '.($new_version_stable?'true':'false').';'."\r\n"); - } - if (!$found_software_name) { - fwrite($fh, '$_configuration[\'software_name\'] = \''.$software_name.'\';'."\r\n"); - } - if (!$found_software_url) { - fwrite($fh, '$_configuration[\'software_url\'] = \''.$software_url.'\';'."\r\n"); - } - fwrite($fh, '?>'); - fclose($fh); - -} else { - - echo 'You are not allowed here !' . __FILE__; - -} diff --git a/main/install/update-files-1.8.7-1.8.8.inc.php b/main/install/update-files-1.8.7-1.8.8.inc.php deleted file mode 100755 index 82b35a1c5d..0000000000 --- a/main/install/update-files-1.8.7-1.8.8.inc.php +++ /dev/null @@ -1,77 +0,0 @@ -') !== false) { - $ignore = true; - } - if (!$ignore) { - fwrite($fh, $line); - } - } - if (!$found_version) { - fwrite($fh, '$_configuration[\'system_version\'] = \''.$new_version.'\';'."\r\n"); - } - if (!$found_stable) { - fwrite($fh, '$_configuration[\'system_stable\'] = '.($new_version_stable?'true':'false').';'."\r\n"); - } - if (!$found_software_name) { - fwrite($fh, '$_configuration[\'software_name\'] = \''.$software_name.'\';'."\r\n"); - } - if (!$found_software_url) { - fwrite($fh, '$_configuration[\'software_url\'] = \''.$software_url.'\';'."\r\n"); - } - fwrite($fh, '?>'); - fclose($fh); - -} else { - - echo 'You are not allowed here !' . __FILE__; - -} diff --git a/main/install/update-files-1.8.8-1.9.0.inc.php b/main/install/update-files-1.8.8-1.9.0.inc.php deleted file mode 100755 index eedff8cc2d..0000000000 --- a/main/install/update-files-1.8.8-1.9.0.inc.php +++ /dev/null @@ -1,87 +0,0 @@ -') !== false) { - $ignore = true; - } - if (!$ignore) { - fwrite($fh, $line); - } - } - if (!$found_version) { - fwrite($fh, '$_configuration[\'system_version\'] = \'' . $new_version . '\';' . "\r\n"); - } - if (!$found_stable) { - fwrite($fh, '$_configuration[\'system_stable\'] = ' . ($new_version_stable ? 'true' : 'false') . ';' . "\r\n"); - } - if (!$found_software_name) { - fwrite($fh, '$_configuration[\'software_name\'] = \'' . $software_name . '\';' . "\r\n"); - } - if (!$found_software_url) { - fwrite($fh, '$_configuration[\'software_url\'] = \'' . $software_url . '\';' . "\r\n"); - } - $string = " -//===========================================================================\n -// Hosting settings - Allows you to set limits to the Chamilo portal when\n -// hosting it for a third party. These settings can be overwritten by an\n -// optionally-loaded extension file with only the settings (no comments).\n -//===========================================================================\n -// Set a maximum number of users. Default (0) = no limit\n -".'$'."_configuration['hosting_limit_users'] = 0;\n -// Set a maximum number of teachers. Default (0) = no limit\n -".'$'."_configuration['hosting_limit_teachers'] = 0;\n -// Set a maximum number of courses. Default (0) = no limit\n -".'$'."_configuration['hosting_limit_courses'] = 0;\n -// Set a maximum number of sessions. Default (0) = no limit\n -".'$'."_configuration['hosting_limit_sessions'] = 0;\n -// Set a maximum disk space used, in MB (set to 1024 for 1GB, 5120 for 5GB).\n -// Default (0) = no limit\n -".'$'."_configuration['hosting_limit_disk_space'] = 0;\n -"; - fwrite($fh, $string); - fwrite($fh, '?>'); - fclose($fh); - //Adds events.conf file - if (! file_exists(api_get_path(CONFIGURATION_PATH).'events.conf.php')) { - copy(api_get_path(CONFIGURATION_PATH).'events.conf.dist.php', api_get_path(CONFIGURATION_PATH).'events.conf.php'); - } - -} else { - - echo 'You are not allowed here !'. __FILE__; -} From c670521de34f25fd7a9c9cf3b13148bbd305ca51 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 27 Mar 2015 17:39:59 +0100 Subject: [PATCH 007/159] Remove unused code. --- main/inc/global.inc.php | 44 - main/inc/lib/database.lib.php | 621 +------- main/inc/lib/diagnoser.lib.php | 6 +- main/inc/lib/session_handler.class.php | 4 + .../lib/session_handler_memcache.class.php | 3 + main/install/i_database.class.php | 13 +- main/install/index.php | 2 - main/install/install.lib.php | 8 +- main/install/install_db.inc.php | 2 - main/install/update-db-1.9.0-1.10.0.inc.php | 6 - .../update-db-scorm-1.6.x-1.8.0.inc.php | 1289 ----------------- 11 files changed, 57 insertions(+), 1941 deletions(-) delete mode 100755 main/install/update-db-scorm-1.6.x-1.8.0.inc.php diff --git a/main/inc/global.inc.php b/main/inc/global.inc.php index 986e0741fc..e9ef85d8a2 100755 --- a/main/inc/global.inc.php +++ b/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); diff --git a/main/inc/lib/database.lib.php b/main/inc/lib/database.lib.php index 16570af075..276154b11b 100755 --- a/main/inc/lib/database.lib.php +++ b/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 "

Dev Message: get_course_table() doesn't have a 2nd parameter

"; - //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 - * @author Patrick Cool , 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 + * + * @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 - **/ + * @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 '
';
-                $message = '

Dev message: please add the c_id field in this query or report this error in support.chamilo.org

'; - $message .= $query; - echo $message; - echo '
'; - //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 = '
' .
-                    'DATABASE ERROR #'.self::errno($connection).':
' . - self::remove_XSS(self::error($connection)) . '
' . - 'QUERY :
' . - self::remove_XSS($query) . '
' . - 'FILE :
' . - (empty($file) ? ' unknown ' : $file) . '
' . - 'LINE :
' . - (empty($line) ? ' unknown ' : $line) . '
'; - if (empty($type)) { - if (!empty($function)) { - $info .= 'FUNCTION :
' . $function; - } - } else { - if (!empty($class) && !empty($function)) { - $info .= 'CLASS :
' . $class . '
'; - $info .= 'METHOD :
' . $function; - } - } - $info .= '
'; - 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; } diff --git a/main/inc/lib/diagnoser.lib.php b/main/inc/lib/diagnoser.lib.php index 03e2de5472..b6cbbf16d1 100755 --- a/main/inc/lib/diagnoser.lib.php +++ b/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; } diff --git a/main/inc/lib/session_handler.class.php b/main/inc/lib/session_handler.class.php index 5bfedfdced..6035caf6a3 100755 --- a/main/inc/lib/session_handler.class.php +++ b/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) { diff --git a/main/inc/lib/session_handler_memcache.class.php b/main/inc/lib/session_handler_memcache.class.php index 7f7bc5d2eb..74134664cd 100644 --- a/main/inc/lib/session_handler_memcache.class.php +++ b/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) { diff --git a/main/install/i_database.class.php b/main/install/i_database.class.php index 67eebf3bff..07d1c8213f 100755 --- a/main/install/i_database.class.php +++ b/main/install/i_database.class.php @@ -1,8 +1,8 @@ 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 diff --git a/main/install/index.php b/main/install/index.php index 2acf0267bc..d1c8074b37 100755 --- a/main/install/index.php +++ b/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(); diff --git a/main/install/install.lib.php b/main/install/install.lib.php index 19af20d397..1510cb7054 100755 --- a/main/install/install.lib.php +++ b/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(
Database host: getConnection()->getHost(); ?>
- Database server version:
- Database client version:
- Database protocol version: + Database port: getConnection()->getPort(); ?>
+ Database platform: getConnection()->getDatabasePlatform()->getName(); ?>
@@ -1944,8 +1942,6 @@ function display_database_settings_form(

- Database error:
- '; ?>
diff --git a/main/install/install_db.inc.php b/main/install/install_db.inc.php index 8f3f4f5724..f35c2c78db 100755 --- a/main/install/install_db.inc.php +++ b/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; diff --git a/main/install/update-db-1.9.0-1.10.0.inc.php b/main/install/update-db-1.9.0-1.10.0.inc.php index 0c4fe985cd..8d62224ef5 100644 --- a/main/install/update-db-1.9.0-1.10.0.inc.php +++ b/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)"); diff --git a/main/install/update-db-scorm-1.6.x-1.8.0.inc.php b/main/install/update-db-scorm-1.6.x-1.8.0.inc.php deleted file mode 100755 index 758c374d65..0000000000 --- a/main/install/update-db-scorm-1.6.x-1.8.0.inc.php +++ /dev/null @@ -1,1289 +0,0 @@ - - */ - -/** - * 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 ""; - -/** - * 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']."
\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 "
lp_ids:".print_r($lp_ids,true)."
\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
\n"; - $res_lp_chap = Database::query($sql_lp_chap); - while ($row = Database::fetch_array($res_lp_chap)) { - //echo "Treating chapter id : ".$row['id']."
\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."
\n"; - $ins_res = Database::query($ins_lp_sql); - $in_id = Database::insert_id(); - //echo "  Inserted item $in_id
\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 "
parent_lps:".print_r($parent_lps,true)."
\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
\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']."
\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 "  Inserted item $in_id (".$row['title'].")
\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 "
lp_items:".print_r($lp_items,true)."
\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
\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 "
";
-    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
\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
\n"; - Database::query($upd); - $last = $item_id; - } - - //echo "
\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
\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
\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...
"; - $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')
\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"\'&]*)(&|&)file=([^\s"\'&]*)@'; - if (preg_match($pattern, $link, $matches)) { - //echo "Found match for scorm link in $tbl_tool: $link
"; - if (!empty($matches[3]) && (strtolower(substr($matches[3], -15)) == 'imsmanifest.xml') && !is_file(realpath(urldecode($matches[3])))) { - //echo "Removing link $link from tools
"; - $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')
\n"; - $res_tool_upd = Database::query($sql_tool_upd); - } - } else { - //echo "No scorm link found in tool link $link
"; - } - //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 "
Replacing ".$row_i['intro_text']."\n by \n ".$intro."

\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."
\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
"; - $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
\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.
"); } - $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."
\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
"; - foreach ($matches as $match) { - //echo "Found match ".print_r($match,true)."
"; - $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
"; - // 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
"; - 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
"; - if (is_file($courses_dir.$entry."/imsmanifest.xml")) { - //echo "found $courses_dir/$entry/imsmanifest.xml!
"; - 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.
"); } - //echo "Recording $entry
"; - $scormdocuments_lps[] = $entry; - } - } else { - //echo "Manifest does not exist in ".$courses_dir.$entry."/imsmanifest.xml
"; - } - } - } - } - } - } - } - - // 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 "
courses_id_list: ".print_r($courses_id_list,true)."
\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 "
scorm row: ".print_r($scorm,true)."
\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)
\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__.")
"; - $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
\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 "  FOUND item belonging to old learnpath num $my_content_id so belongs to course ".$lp_course[$my_content_id]."
\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
"; - $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
"; - $ins_res = Database::query($ins_sql); - } else { - //echo " Didn't find corresponding item for $my_identifier in new tables
\n"; - } - } - } - - } else { - //echo "Could not find $ims... Proceeding from database...(line ".__LINE__.")
"; - 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 "  Inserted item $in_id
\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)
\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']."
\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
\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 "  FOUND item belonging to old learnpath num $my_content_id so belongs to course ".$lp_course[$my_content_id]."
\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."
\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()."
\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 "
Lookin for ".$subarray['identifier']." ".print_r($lp_item_refs,true)."
\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
\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."
\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
"; - } - $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
"; - } - if ($intro != $row_i['intro_text']) { - //echo "
Replacing ".$row_i['intro_text']."\n by \n ".$intro."

\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."
\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 ""; From 588d847e009155453648f523731b2cde0a4397d0 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 30 Mar 2015 09:58:04 +0200 Subject: [PATCH 008/159] Remove 1.6/1.8 code use Doctrine to query the DB. --- main/install/index.php | 83 +++-------- main/install/install.lib.php | 242 ++++---------------------------- main/install/install_db.inc.php | 18 +-- 3 files changed, 48 insertions(+), 295 deletions(-) diff --git a/main/install/index.php b/main/install/index.php index d1c8074b37..ecf1e40b3d 100755 --- a/main/install/index.php +++ b/main/install/index.php @@ -103,7 +103,6 @@ error_reporting(E_ALL); // Overriding the timelimit (for large campusses that have to be migrated). @set_time_limit(0); -$update_from_version_6 = array(); // Upgrading from any subversion of 1.9 $update_from_version_8 = array('1.9.0', '1.9.2','1.9.4','1.9.6', '1.9.6.1', '1.9.8', '1.9.8.1', '1.9.8.2', '1.9.10'); @@ -168,25 +167,6 @@ if (@$_POST['step2_install'] || @$_POST['step2_update_8'] || @$_POST['step2_upda } else { $badUpdatePath = true; } - } else { //step2_update_6, presumably - if (empty($_POST['updatePath'])) { - $_POST['step1'] = 1; - } else { - $emptyUpdatePath = false; - $_POST['updatePath'] = api_add_trailing_slash($_POST['updatePath']); - if (file_exists($_POST['updatePath'])) { - //1.6.x - $my_old_version = get_config_param('clarolineVersion', $_POST['updatePath']); - if (in_array($my_old_version, $update_from_version_6)) { - $_POST['step2'] = 1; - $proposedUpdatePath = $_POST['updatePath']; - } else { - $badUpdatePath = true; - } - } else { - $badUpdatePath = true; - } - } } } } elseif (@$_POST['step1']) { @@ -606,40 +586,23 @@ if (@$_POST['step2']) { $tmp = get_config_param_from_db($dbHostForm, $dbUsernameForm, $dbPassForm, $db_name, 'InstitutionUrl'); if (!empty($tmp)) $institutionUrlForm = $tmp; - if (in_array($my_old_version, $update_from_version_6)) { //for version 1.6 - $urlForm = get_config_param('rootWeb'); - $encryptPassForm = get_config_param('userPasswordCrypted'); - if (empty($encryptPassForm)) { - $encryptPassForm = get_config_param('password_encryption'); - } - // Managing the $encryptPassForm - if ($encryptPassForm == '1') { - $encryptPassForm = 'sha1'; - } elseif ($encryptPassForm == '0') { - $encryptPassForm = 'none'; - } - - $allowSelfReg = get_config_param('allowSelfReg'); - $allowSelfRegProf = get_config_param('allowSelfRegProf'); - - } else { //for version 1.8 - $urlForm = $_configuration['root_web']; - $encryptPassForm = get_config_param('userPasswordCrypted'); - // Managing the $encryptPassForm - if ($encryptPassForm == '1') { - $encryptPassForm = 'sha1'; - } elseif ($encryptPassForm == '0') { - $encryptPassForm = 'none'; - } + // For version 1.9 + $urlForm = $_configuration['root_web']; + $encryptPassForm = get_config_param('userPasswordCrypted'); + // Managing the $encryptPassForm + if ($encryptPassForm == '1') { + $encryptPassForm = 'sha1'; + } elseif ($encryptPassForm == '0') { + $encryptPassForm = 'none'; + } - $allowSelfReg = false; - $tmp = get_config_param_from_db($dbHostForm, $dbUsernameForm, $dbPassForm, $db_name, 'allow_registration'); - if (!empty($tmp)) $allowSelfReg = $tmp; + $allowSelfReg = false; + $tmp = get_config_param_from_db($dbHostForm, $dbUsernameForm, $dbPassForm, $db_name, 'allow_registration'); + if (!empty($tmp)) $allowSelfReg = $tmp; - $allowSelfRegProf = false; - $tmp = get_config_param_from_db($dbHostForm, $dbUsernameForm, $dbPassForm, $db_name, 'allow_registration_as_teacher'); - if (!empty($tmp)) $allowSelfRegProf = $tmp; - } + $allowSelfRegProf = false; + $tmp = get_config_param_from_db($dbHostForm, $dbUsernameForm, $dbPassForm, $db_name, 'allow_registration_as_teacher'); + if (!empty($tmp)) $allowSelfRegProf = $tmp; } display_configuration_settings_form( @@ -774,7 +737,6 @@ if (@$_POST['step2']) { if (empty($my_old_version)) { $my_old_version = '1.8.6.2'; } //we guess $_configuration['main_database'] = $dbNameForm; - //$urlAppendPath = get_config_param('urlAppend'); Log::notice('Starting migration process from '.$my_old_version.' ('.time().')'); if ($userPasswordCrypted == '1') { @@ -813,7 +775,6 @@ if (@$_POST['step2']) { } else { set_file_folder_permissions(); - //database_server_connect(); $manager = testDbConnect( $dbHostForm, $dbUsernameForm, @@ -822,11 +783,11 @@ if (@$_POST['step2']) { ); // Initialization of the database encoding to be used. - Database::query("SET storage_engine = MYISAM;"); - Database::query("SET SESSION character_set_server='utf8';"); - Database::query("SET SESSION collation_server='utf8_general_ci';"); + Database::query("SET storage_engine = INNODB;"); + //Database::query("SET SESSION character_set_server='utf8';"); + //Database::query("SET SESSION collation_server='utf8_general_ci';"); //Database::query("SET CHARACTER SET 'utf8';"); // See task #1802. - Database::query("SET NAMES 'utf8';"); + //Database::query("SET NAMES 'utf8';"); include 'install_db.inc.php'; include 'install_files.inc.php'; @@ -839,8 +800,10 @@ if (@$_POST['step2']) { } elseif (@$_POST['step1'] || $badUpdatePath) { //STEP 1 : REQUIREMENTS //make sure that proposed path is set, shouldn't be necessary but... - if (empty($proposedUpdatePath)) { $proposedUpdatePath = $_POST['updatePath']; } - display_requirements($installType, $badUpdatePath, $proposedUpdatePath, $update_from_version_8, $update_from_version_6); + if (empty($proposedUpdatePath)) { + $proposedUpdatePath = $_POST['updatePath']; + } + display_requirements($installType, $badUpdatePath, $proposedUpdatePath, $update_from_version_8); } else { // This is the start screen. display_language_selection(); diff --git a/main/install/install.lib.php b/main/install/install.lib.php index 1510cb7054..0fec1481e0 100755 --- a/main/install/install.lib.php +++ b/main/install/install.lib.php @@ -690,6 +690,7 @@ function fill_track_countries_table($trackCountriesTable) */ function load_main_database($installation_settings, $dbScript = '') { + $sql_text = null; if (!empty($dbScript)) { if (file_exists($dbScript)) { $sql_text = file_get_contents($dbScript); @@ -708,168 +709,10 @@ function load_main_database($installation_settings, $dbScript = '') } global $manager; - $manager->getConnection()->prepare($sql_text); - //parse_sql_queries($sql_text); + $result = $manager->getConnection()->prepare($sql_text); + $result->execute(); } -/** - * Creates the structure of the stats database - * @param string $dbScript Name of the file containing the SQL script inside the install directory - */ -function load_database_script($dbScript) -{ - $dbScript = api_get_path(SYS_CODE_PATH).'install/'.$dbScript; - if (file_exists($dbScript)) { - $sql_text = file_get_contents($dbScript); - } - parse_sql_queries($sql_text); -} - -/** - * Parse SQL queries - * @param string $sql_text SQL code - */ -function parse_sql_queries($sql_text) -{ - //split in array of sql strings - $sql_instructions = array(); - split_sql_file($sql_instructions, $sql_text); - - //execute the sql instructions - $count = count($sql_instructions); - for ($i = 0; $i < $count; $i++) { - $this_sql_query = $sql_instructions[$i]['query']; - - Database::query($this_sql_query); - //UTF8 fix see #5678 - /* - if (strpos(strtolower($this_sql_query), 'create table') === false) { - Database::query($this_sql_query); - } else { - //$this_sql_query .= substr($this_sql_query, strlen($this_sql_query), strlen($this_sql_query)-1); - $this_sql_query .= ' DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci '; - Database::query($this_sql_query); - }*/ - } -} - - -/** - * Function copied and adapted from phpMyAdmin 2.6.0 PMA_splitSqlFile (also GNU GPL) - * Removes comment lines and splits up large sql files into individual queries - * Last revision: September 23, 2001 - gandon - * @param array $ret the split sql commands - * @param string $sql the sql commands - * @return boolean always true - */ -function split_sql_file(&$ret, $sql) -{ - // do not trim, see bug #1030644 - //$sql = trim($sql); - $sql = rtrim($sql, "\n\r"); - $sql_len = strlen($sql); - $char = ''; - $string_start = ''; - $in_string = false; - $nothing = true; - $time0 = time(); - - for ($i = 0; $i < $sql_len; ++$i) { - $char = $sql[$i]; - - // We are in a string, check for not escaped end of strings except for - // back-quotes that can't be escaped - if ($in_string) { - for (;;) { - $i = strpos($sql, $string_start, $i); - // No end of string found -> add the current substring to the - // returned array - if (!$i) { - $ret[] = $sql; - return true; - } elseif ($string_start == '`' || $sql[$i - 1] != '\\') { - // Back-quotes or no backslashes before quotes: it's indeed the - // end of the string -> exit the loop - $string_start = ''; - $in_string = false; - break; - } else { // one or more Backslashes before the presumed end of string... - // ... first checks for escaped backslashes - $j = 2; - $escaped_backslash = false; - while ($i - $j > 0 && $sql[$i - $j] == '\\') { - $escaped_backslash = !$escaped_backslash; - $j++; - } - // ... if escaped backslashes: it's really the end of the - // string -> exit the loop - if ($escaped_backslash) { - $string_start = ''; - $in_string = false; - break; - } else { // ... else loop - $i++; - } - } // end if...elseif...else - } // end for - // end if (in string) - - // lets skip comments (/*, -- and #) - } elseif (($char == '-' && $sql_len > $i + 2 && $sql[$i + 1] == '-' && $sql[$i + 2] <= ' ') || - $char == '#' || - ($char == '/' && $sql_len > $i + 1 && $sql[$i + 1] == '*') - ) { - $i = strpos($sql, $char == '/' ? '*/' : "\n", $i); - // didn't we hit end of string? - if ($i === false) { - break; - } - if ($char == '/') { - $i++; - } - - // We are not in a string, first check for delimiter... - } elseif ($char == ';') { - // if delimiter found, add the parsed part to the returned array - $ret[] = array('query' => substr($sql, 0, $i), 'empty' => $nothing); - $nothing = true; - $sql = ltrim(substr($sql, min($i + 1, $sql_len))); - $sql_len = strlen($sql); - if ($sql_len) { - $i = -1; - } else { - // The submitted statement(s) end(s) here - return true; - } - // end elseif (is delimiter) - - // ... then check for start of a string,... - } elseif (($char == '"') || ($char == '\'') || ($char == '`')) { - $in_string = true; - $nothing = false; - $string_start = $char; - // end elseif (is start of string) - - } elseif ($nothing) { - $nothing = false; - } - - // Send a fake header each 30 sec. to bypass browser timeout - $time1 = time(); - if ($time1 >= $time0 + 30) { - $time0 = $time1; - header('X-pmaPing: Pong'); - } // end if - } // end for - - // add any rest to the returned array - if (!empty($sql) && preg_match('@[^[:space:]]+@', $sql)) { - $ret[] = array('query' => $sql, 'empty' => $nothing); - } - - return true; -} // end of the 'split_sql_file()' function - /** * Get an SQL file's contents * @@ -1085,8 +928,7 @@ function display_language_selection() * @param string $installType * @param boolean $badUpdatePath * @param string The updatePath given (if given) - * @param array $update_from_version_8 The different subversions from version 1.8 - * @param array $update_from_version_6 The different subversions from version 1.6 + * @param array $update_from_version_8 The different subversions from version 1.9 * * @author unknow * @author Patrick Cool , Ghent University @@ -1095,8 +937,7 @@ function display_requirements( $installType, $badUpdatePath, $updatePath = '', - $update_from_version_8 = array(), - $update_from_version_6 = array() + $update_from_version_8 = array() ) { global $_setting; echo '

'.display_step_sequence().get_lang('Requirements')."

"; @@ -1418,7 +1259,7 @@ function display_requirements( if ($badUpdatePath) { ?>
!
- Chamilo . + Chamilo .
'.get_lang('UpgradeFromLMS18x').''; - echo ' '; + echo ' > '.get_lang('UpgradeFromLMS19x').''; + echo '

'; } } @@ -1814,9 +1649,6 @@ function display_database_settings_form( echo get_lang('DBSettingUpgradeIntro'); echo '
'; } else { - if (empty($dbPrefixForm)) { //make sure there is a default value for db prefix - $dbPrefixForm = ''; - } echo '

' . display_step_sequence() .get_lang('DBSetting') . '

'; echo '
'; echo get_lang('DBSettingIntro'); @@ -1848,13 +1680,6 @@ function display_database_settings_form( $example_password = get_lang('EG').' '.api_generate_password(); displayDatabaseParameter($installType, get_lang('DBPassword'), 'dbPassForm', $dbPassForm, $example_password); - echo ''; - - $style = ''; - if ($installType == INSTALL_TYPE_UPDATE) { - $style = ''; - } - //Database Name fix replace weird chars if ($installType != INSTALL_TYPE_UPDATE) { $dbNameForm = str_replace(array('-','*', '$', ' ', '.'), '', $dbNameForm); @@ -1868,7 +1693,7 @@ function display_database_settings_form( $dbNameForm, ' ', null, - 'id="optional_param1" '.$style + 'id="optional_param1"' ); ?> @@ -1886,53 +1711,34 @@ function display_database_settings_form( getMessage(); - } - - $databases = $manager->getConnection()->getSchemaManager()->listDatabases(); + $databases = $manager->getConnection()->getSchemaManager()->listDatabases(); - if (in_array($dbNameForm, $databases)) { - $database_exists_text = '
'.get_lang('ADatabaseWithTheSameNameAlreadyExists').'
'; - } else { - - if ($dbConnect == -1) { - $database_exists_text = '
'.sprintf(get_lang('UserXCantHaveAccessInTheDatabaseX'), $dbUsernameForm, $dbNameForm).'
'; + if (in_array($dbNameForm, $databases)) { + $database_exists_text = '
'.get_lang('ADatabaseWithTheSameNameAlreadyExists').'
'; } else { - $manager->getConnection()->getSchemaManager()->createDatabase($dbNameForm); - /* - //Try to create the database - $user_can_create_databases = false; - $multipleDbCheck = @Database::query("CREATE DATABASE ".mysql_real_escape_string($dbNameForm)); - if ($multipleDbCheck !== false) { - $multipleDbCheck = @Database::query("DROP DATABASE IF EXISTS ".mysql_real_escape_string($dbNameForm)); - $user_can_create_databases = true; - } - - if ($user_can_create_databases) { - $database_exists_text = '
'.sprintf(get_lang('DatabaseXWillBeCreated'), $dbNameForm, $dbUsernameForm).'
'; - } else { - $dbConnect = 0; - $database_exists_text = '
'.sprintf(get_lang('DatabaseXCantBeCreatedUserXDoestHaveEnoughPermissions'), $dbNameForm, $dbUsernameForm).'
'; - }*/ + $manager->getConnection()->getSchemaManager()->createDatabase( + $dbNameForm + ); } + } catch (Exception $e) { + $database_exists_text = $e->getMessage(); } - if ($manager): ?> + if ($manager->getConnection()->isConnected()): ?>
Database host: getConnection()->getHost(); ?>
- Database port: getConnection()->getPort(); ?>
- Database platform: getConnection()->getDatabasePlatform()->getName(); ?>
+ Database driver: getConnection()->getDriver()->getName(); ?>
@@ -2235,7 +2041,7 @@ function get_countries_list_from_array($combo = false) } /** - * Lockis settings that can't be changed in other portals + * Lock settings that can't be changed in other portals */ function locking_settings() { diff --git a/main/install/install_db.inc.php b/main/install/install_db.inc.php index f35c2c78db..d0cc768b69 100755 --- a/main/install/install_db.inc.php +++ b/main/install/install_db.inc.php @@ -9,6 +9,7 @@ /* This page is called only during a NEW chamilo installation */ /* This page can only be access through including from the install script. */ + /** * Init checks */ @@ -53,16 +54,6 @@ if (empty($mysqlMainDb) || $mysqlMainDb == 'mysql' || $mysqlMainDb == $dbPrefixF $mysqlMainDb = $dbPrefixForm . 'main'; } -$mysqlStatsDb = $dbStatsForm; -if (empty($mysqlStatsDb) || $mysqlStatsDb == 'mysql' || $mysqlStatsDb == $dbPrefixForm) { - $mysqlStatsDb = $dbPrefixForm . 'stats'; -} - -$mysqlUserDb = $dbUserForm; -if (empty($mysqlUserDb) || $mysqlUserDb == 'mysql' || $mysqlUserDb == $dbPrefixForm) { - $mysqlUserDb = $dbPrefixForm . 'user'; -} - //This parameter is needed to run a command line to install Chamilo using BNPanel + ISPConfig see #1799 if (!defined('CLI_INSTALLATION')) { @@ -80,7 +71,6 @@ if (!defined('CLI_INSTALLATION')) { $create_database = false; } - // Create database if ($create_database) { $manager->getConnection()->getSchemaManager()->createDatabase($mysqlMainDb); @@ -89,9 +79,6 @@ if (!defined('CLI_INSTALLATION')) { } } -$mysqlStatsDb = $mysqlMainDb; -$mysqlUserDb = $mysqlMainDb; - // This parameter is needed to run a command line install of Chamilo (needed for Phing) if (!defined('CLI_INSTALLATION')) { include_once api_get_path(SYS_LANG_PATH) . 'english/trad4all.inc.php'; @@ -122,9 +109,6 @@ AddCourse::drop_course_tables(); load_main_database($installation_settings); -$track_countries_table = "track_c_countries"; -fill_track_countries_table($track_countries_table); - locking_settings(); update_dir_and_files_permissions(); From d654bb558abc32f3a26358851eaf8e159f12b12a Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 30 Mar 2015 12:46:38 +0200 Subject: [PATCH 009/159] Remove unused code. --- main/inc/lib/database.lib.php | 15 +-------------- main/mySpace/user_add.php | 1 - 2 files changed, 1 insertion(+), 15 deletions(-) diff --git a/main/inc/lib/database.lib.php b/main/inc/lib/database.lib.php index 276154b11b..fcb2f7233f 100755 --- a/main/inc/lib/database.lib.php +++ b/main/inc/lib/database.lib.php @@ -42,8 +42,6 @@ class Database public static function get_main_database() { return self::getManager()->getConnection()->getDatabase(); - /*global $_configuration; - return $_configuration['main_database'];*/ } /** @@ -87,9 +85,6 @@ class Database return $obj->n; } - /* - An intermediate API-layer between the system and the database server. - */ /** * Returns the number of affected rows in the last database operation. @@ -103,6 +98,7 @@ class Database } /** + * Connect to the database sets the entity manager. * @param array $params * * @throws \Doctrine\ORM\ORMException @@ -171,15 +167,6 @@ class Database : mysql_connect($server, $username, $password, $new_link, $client_flags);*/ } - /** - * 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(). - * @return string Returns the error text from the last database operation, or '' (empty string) if no error occurred. - */ - public static function error($connection = null) { - return self::use_default_connection($connection) ? mysql_error() : mysql_error($connection); - } - /** * Escape MySQL wildchars _ and % in LIKE search * @param string The string to escape diff --git a/main/mySpace/user_add.php b/main/mySpace/user_add.php index 940cef66af..bbcc9fdf51 100755 --- a/main/mySpace/user_add.php +++ b/main/mySpace/user_add.php @@ -48,7 +48,6 @@ api_block_anonymous_users(); // Database table definitions $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN); $table_user = Database :: get_main_table(TABLE_MAIN_USER); -$database = Database::get_main_database(); $htmlHeadXtra[] = ' '; - } - - public static function tag_code($code) - { - $new_line = "\n"; - return ''; - } - -} \ No newline at end of file diff --git a/main/inc/lib/page.class.php b/main/inc/lib/page.class.php deleted file mode 100755 index 1b06ef4453..0000000000 --- a/main/inc/lib/page.class.php +++ /dev/null @@ -1,168 +0,0 @@ -title('my_title')->display($content); - * - * $page = Page::create()->title('my_title')->help('help')->content($content); - * $page->display(); - * - * @license see /license.txt - * @author Laurent Opprecht for the Univesity of Geneva - */ -class Page -{ - - protected $title = null; - protected $help = null; - protected $header = null; - protected $content; - protected $breadcrumbs = ''; - protected $message = null; - protected $warning = null; - protected $error = null; - - /** - * - * @return Page - */ - static function create($title = '') - { - return new self($title); - } - - function __construct($title = '') - { - $this->title = $title; - } - - /** - * - * @param $header - * @return Page - */ - function header($header) - { - $this->header = $header; - return $this; - } - - /** - * - * @param string $title - * @return Page - */ - function title($title) - { - $this->title = $title; - return $this; - } - - /** - * - * @param array $crumbs_ - * @return Page - */ - function breadcrumbs($crumbs) - { - $this->breadcrumbs = $crumbs; - return $this; - } - - /** - * - * @param string $help help file name - * @return Page - */ - function help($help) - { - $this->help = $help; - return $this; - } - - /** - * - * @param string $message - * @return Page - */ - function message($message) - { - $this->message = $message; - return $this; - } - - /** - * - * @param string $warning - * @return Page - */ - function warning($warning) - { - $this->warning = $warning; - return $this; - } - - /** - * - * @param string $error - * @return Page - */ - function error($error) - { - $this->error = $error; - return $this; - } - - /** - * - * @param object|string $content - * @return Page - */ - function content($content) - { - $this->content = $content; - return $this; - } - - function __toString() - { - $this->display($this->content); - } - - function display($content = null) - { - $this->display_header(); - $this->display_content($content); - $this->display_footer(); - } - - function display_header() - { - global $interbreadcrumb; - $interbreadcrumb = $this->breadcrumbs; - - Display::display_header($this->title, $this->help, $this->header); - if ($message = $this->message) { - Display::display_confirmation_message($message); - } - if ($warning = $this->warning) { - Display::display_warning_message($warning); - } - if ($error = $this->error) { - Display::display_error_message($error); - } - } - - protected function display_content($content) - { - $content = $content ? $content : $this->content; - echo $content; - } - - function display_footer() - { - Display::display_footer(); - } - -} \ No newline at end of file diff --git a/main/inc/lib/response.class.php b/main/inc/lib/response.class.php deleted file mode 100755 index 5d46185765..0000000000 --- a/main/inc/lib/response.class.php +++ /dev/null @@ -1,23 +0,0 @@ - for the Univesity of Geneva - */ -class Response -{ - - public static function not_found() - { - Header::response_code(404); - exit; - } - -} \ No newline at end of file diff --git a/main/inc/lib/result_set.class.php b/main/inc/lib/result_set.class.php deleted file mode 100755 index daa79bdb88..0000000000 --- a/main/inc/lib/result_set.class.php +++ /dev/null @@ -1,194 +0,0 @@ - for the Univesity of Geneva - * @deprecated - */ -class ResultSet implements Countable, Iterator -{ - - /** - * - * @param string $sql - * @return ResultSet - */ - static function create($sql) - { - return new self($sql); - } - - protected $sql = ''; - protected $handle = null; - protected $current = false; - protected $index = -1; - protected $count = false; - protected $limit_count = null; - protected $limit_offset = null; - protected $orderby_column = null; - protected $orderby_direction = null; - protected $return_type = null; - - function __construct($sql, $limit_count = null, $limit_offset = null, $orderby_column = null, $orderby_direction = null, $return_type = null) - { - $this->sql = $sql; - $this->limit_count = $limit_count; - $this->limit_offset = $limit_offset; - $this->orderby_column = $orderby_column; - $this->orderby_direction = $orderby_direction; - $this->return_type = $return_type; - } - - public function sql() - { - $sql = $this->sql; - - $column = $this->orderby_column; - $direction = $this->orderby_direction; - - $offset = $this->limit_offset; - $count = $this->limit_count; - if (is_null($column) && is_null($count) && is_null($offset)) { - return $sql; - } - - if (strpos($sql, ' ORDER ') || strpos($sql, ' LIMIT ') || strpos($sql, ' OFFSET ')) { - $sql = "SELECT * FROM ($sql) AS dat "; - } else { - $sql .= ' '; - } - - if ($column) { - $sql .= "ORDER BY $column $direction "; - } - - if ($count) { - $sql .= "LIMIT $count "; - } - if ($offset) { - $sql .= "OFFSET $offset"; - } - - return $sql; - } - - protected function handle() - { - if (is_null($this->handle)) { - $this->handle = Database::query($this->sql()); - } - - return $this->handle; - } - - public function count() - { - if ($this->count === false) { - $sql = $this->sql(); - $sql = "SELECT COUNT(*) AS alpha FROM ($sql) AS dat "; - $rs = Database :: query($sql); - $data = Database::fetch_array($rs); - $count = $data ? $data['alpha'] : 0; - $this->count = (int) $count; - } - return $this->count; - } - - public function first() - { - foreach ($this as $item) { - return $item; - } - return null; - } - - /** - * - * @param int $count - * @param int $from - * @return ResultSet - */ - public function limit($count, $from = 0) - { - $result = clone($this); - $result->limit_offset = $from; - $result->limit_count = $count; - return $result; - } - - /** - * - * @param int $column - * @param int $dir - * @return ResultSet - */ - public function orderby($column, $dir = 'ASC') - { - $result = clone($this); - $result->orderby_column = $column; - $result->orderby_direction = $dir; - return $result; - } - - public function return_type($value) - { - $result = clone($this); - $result->return_type = $value; - return $result; - } - - public function current() - { - return $this->current; - } - - public function key() - { - return $this->index; - } - - public function next() - { - $data = Database::fetch_assoc($this->handle()); - if (!$data) { - $this->current = $this->return_type ? null : array(); - } else if (empty($this->return_type)) { - $this->current = $data; - } else if ($this->return_type == 'object') { - $this->current = (object) $data; - } else { - $this->current = new $this->return_type($data); - } - $this->index++; - return $this->current; - } - - public function rewind() - { - $this->handle = null; - $this->current = false; - $this->index = -1; - $this->next(); - } - - public function valid() - { - return !empty($this->current); - } - - function __clone() - { - $this->reset(); - } - - function reset() - { - $this->handle = null; - $this->current = false; - $this->index = -1; - $this->count = false; - } - -} diff --git a/main/inc/lib/session_handler_memcache.class.php b/main/inc/lib/session_handler_memcache.class.php deleted file mode 100644 index 74134664cd..0000000000 --- a/main/inc/lib/session_handler_memcache.class.php +++ /dev/null @@ -1,206 +0,0 @@ -memcache = new Memcache; - if (!empty($_configuration['memcache_server'])) { - foreach ($_configuration['memcache_server'] as $serverData) { - $isServerAvailable = @fsockopen($serverData['host'], $serverData['port']); - if (!$isServerAvailable){ - continue; - } - $this->memcache->addServer($serverData['host'], $serverData['port']); - } - } - $this->lifetime = 3600; // 60 minutes - - $this->connection = array ( - 'server' => $_configuration['db_host'], - 'login' => $_configuration['db_user'], - 'password' => $_configuration['db_password'], - 'base' => $_configuration['main_database'] - ); - - $this->connection_handler = false; - } - - /** - *@deprecated - * */ - public function sqlConnect() - { - if (!$this->connection_handler) { - $this->connection_handler = @mysql_connect($this->connection['server'], $this->connection['login'], $this->connection['password'], true); - - // The system has not been designed to use special SQL modes that were introduced since MySQL 5 - @mysql_query("set session sql_mode='';", $this->connection_handler); - - @mysql_select_db($this->connection['base'], $this->connection_handler); - - // Initialization of the database connection encoding to be used. - // The internationalization library should be already initialized. - @mysql_query("SET SESSION character_set_server='utf8';", $this->connection_handler); - @mysql_query("SET SESSION collation_server='utf8_general_ci';", $this->connection_handler); - $system_encoding = api_get_system_encoding(); - if (api_is_utf8($system_encoding)) { - // 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. - @mysql_query("SET NAMES 'utf8';", $this->connection_handler); - } else { - @mysql_query("SET CHARACTER SET '" . Database::to_db_encoding($system_encoding) . "';", $this->connection_handler); - } - } - - return ($this->connection_handler) ? true : false; - } - - public function sqlClose() - { - - if ($this->connection_handler) { - mysql_close($this->connection_handler); - $this->connection_handler = false; - return true; - } - - return false; - } - - public function sqlQuery($query, $dieOnError = true) - { - $result = mysql_query($query, $this->connection_handler); - if ($dieOnError && !$result) { - $this->sqlClose(); - return; - } - - return $result; - } - - public function open($savePath, $sessionName) - { - $sessionID = session_id(); - if ($sessionID !== "") { - $this->initSessionData = $this->read($sessionID); - $this->session_name = $sessionName; - } - return true; - } - - public function close() - { - $this->lifeTime = null; - $this->memcache = null; - $this->initSessionData = null; - - return $this->gc(0) ? true : false; - } - - public function read($sessionID) - { - $data = $this->memcache->get($sessionID); - if (($data === false || empty($data)) && $this->sqlConnect()) { - $result = $this->sqlQuery("SELECT session_value FROM ".$this->connection['base'].".php_session WHERE session_id='$sessionID'"); - if (!empty($result) && $result !== false && $row = Database::fetch_row($result)) { - $data = stripslashes($row[0]); - $this->memcache->set($sessionID, $data); - } else { - $data = false; - } - } else { - $data = stripslashes($data); - } - - return $data; - } - - public function write($sessionID, $data) - { - global $_configuration; - - $this->memcache->set($sessionID, $data); - if ($this->memcache->get('interactions-' . $sessionID) !== false) { - $interactions = $this->memcache->get('interactions-' . $sessionID); - ++$interactions; - if ($_configuration['session_stored_after_n_times'] < $interactions) { - $interactions = 1; - } - $this->memcache->set('interactions-' . $sessionID, $interactions); - } else { - $this->memcache->set('interactions-' . $sessionID, 1); - } - - $interactions = $this->memcache->get('interactions-' . $sessionID); - //$this->initSessionData !== $data #avoid this validation for performance improvements - - if ($_configuration['session_stored_after_n_times'] === $interactions) { - $sessionID = mysql_real_escape_string($sessionID); - $sessionExpirationTS = ($this->lifetime + time()); - $sessionData = mysql_real_escape_string($data); - - if ($this->sqlConnect()) { - $result = $this->sqlQuery("INSERT INTO ".$this->connection['base'].".php_session( - session_id,session_name,session_time,session_start,session_value) - VALUES('$sessionID','".$this->session_name."','$sessionExpirationTS','$sessionExpirationTS','".addslashes($sessionData)."')", false); - - if (!$result) { - $this->sqlQuery("UPDATE ".$this->connection['base'].".php_session - SET session_name='".$this->session_name."',session_time='$sessionExpirationTS',session_value='".addslashes($sessionData)."' - WHERE session_id='$sessionID'"); - } - return true; - } - } - - return false; - } - - public function destroy($sessionID) - { - $this->memcache->delete($sessionID); - if ($this->sqlConnect()) { - $this->sqlQuery("DELETE FROM ".$this->connection['base'].".php_session WHERE session_id='$sessionID'"); - return true; - } - - return false; - } - - public function gc($maxlifetime) - { - if ($this->sqlConnect()) { - $result = $this->sqlQuery("SELECT COUNT(session_id) FROM ".$this->connection['base'].".php_session"); - list($nbr_results) = Database::fetch_row($result); - - if ($nbr_results > 5000) { - $this->sqlQuery("DELETE FROM ".$this->connection['base'].".php_session WHERE session_time<'".strtotime('-'.$this->lifetime.' minutes')."'"); - } - - $this->sqlClose(); - - return true; - } - - return false; - } -} diff --git a/main/inc/lib/student_publication.class.php b/main/inc/lib/student_publication.class.php deleted file mode 100755 index 35b19eb031..0000000000 --- a/main/inc/lib/student_publication.class.php +++ /dev/null @@ -1,487 +0,0 @@ - for the Univesity of Geneva - */ -class StudentPublication -{ - - public static function void() - { - static $result = null; - if ($result) { - return $result; - } - - $result = new self(); - return $result; - } - - /** - * @return Model\StudentPublicationRepository - */ - public static function repository() - { - return StudentPublicationRepository::instance(); - } - - /** - * - * @param string $where - * @return \ResultSet - */ - public static function query($where) - { - return self::repository()->query($where); - } - - /** - * - * @param int|Course $c_id - * @param int $id - * @return \Model\StudentPublication - */ - public static function get_by_id($c_id, $id) - { - return self::repository()->get_by_id($c_id, $id); - } - - protected $c_id = 0; - protected $id = 0; - protected $url = ''; - protected $title = ''; - protected $description = ''; - protected $author = ''; - protected $active = null; - protected $accepted = false; - protected $post_group_id = 0; - protected $sent_date = 0; - protected $filetype = ''; - protected $has_properties = 0; - protected $view_properties = null; - protected $qualification = 0; - protected $date_of_qualification = 0; - protected $parent_id = 0; - protected $qualificator_id = 0; - protected $weight = 0; - protected $session_id = 0; - protected $user_id = null; - protected $allow_text_assignment = 0; - protected $contains_file = 0; - protected $course = null; - protected $item_property = null; - - public function __construct($data) - { - $data = (object) $data; - $this->c_id = (int) $data->c_id; - $this->id = (int) $data->id; - $this->url = $data->url; - $this->title = $data->title; - $this->description = $data->description; - $this->author = $data->author; - $this->active = $data->active; - $this->accepted = $data->accepted; - $this->post_group_id = $data->post_group_id; - $this->sent_date = $data->sent_date; - $this->filetype = $data->filetype; - $this->has_properties = $data->has_properties; - $this->view_properties = $data->view_properties; - $this->qualification = $data->qualification; - $this->date_of_qualification = $data->date_of_qualification; - $this->parent_id = $data->parent_id; - $this->qualificator_id = $data->qualificator_id; - $this->weight = $data->weight; - $this->session_id = $data->session_id; - $this->user_id = $data->user_id; - $this->allow_text_assignment = $data->allow_text_assignment; - $this->contains_file = $data->contains_file; - $this->course = $data->course; - $this->item_property = $data->item_property; - - $this->course = null; - - if (isset($data->property_id)) { - $property = (array) $data; - $property = (object) $property; - $property->id = $property->property_id; - $this->item_property = ItemProperty::create($property); - } else { - $this->item_property = null; - } - } - - public function get_c_id() - { - return $this->c_id; - } - - public function set_c_id($value) - { - $this->c_id = $value; - } - - public function get_id() - { - return $this->id; - } - - public function set_id($value) - { - $this->id = $value; - } - - public function get_url() - { - return $this->url; - } - - public function set_url($value) - { - $this->url = $value; - } - - public function get_title() - { - return $this->title; - } - - public function set_title($value) - { - $this->title = $value; - } - - public function get_description() - { - return $this->description; - } - - public function set_description($value) - { - $this->description = $value; - } - - public function get_author() - { - return $this->author; - } - - public function set_author($value) - { - $this->author = $value; - } - - public function get_active() - { - return $this->active; - } - - public function set_active($value) - { - $this->active = $value; - } - - public function get_accepted() - { - return $this->accepted; - } - - public function set_accepted($value) - { - $this->accepted = $value; - } - - public function get_post_group_id() - { - return $this->post_group_id; - } - - public function set_post_group_id($value) - { - $this->post_group_id = $value; - } - - public function get_sent_date() - { - return $this->sent_date; - } - - public function set_sent_date($value) - { - $this->sent_date = $value; - } - - public function get_filetype() - { - return $this->filetype; - } - - public function set_filetype($value) - { - $this->filetype = $value; - } - - public function get_has_properties() - { - return $this->has_properties; - } - - public function set_has_properties($value) - { - $this->has_properties = $value; - } - - public function get_view_properties() - { - return $this->view_properties; - } - - public function set_view_properties($value) - { - $this->view_properties = $value; - } - - public function get_qualification() - { - return $this->qualification; - } - - public function set_qualification($value) - { - $this->qualification = $value; - } - - public function get_date_of_qualification() - { - return $this->date_of_qualification; - } - - public function set_date_of_qualification($value) - { - $this->date_of_qualification = $value; - } - - public function get_parent_id() - { - return $this->parent_id; - } - - public function set_parent_id($value) - { - $this->parent_id = $value; - } - - public function get_qualificator_id() - { - return $this->qualificator_id; - } - - public function set_qualificator_id($value) - { - $this->qualificator_id = $value; - } - - public function get_weight() - { - return $this->weight; - } - - public function set_weight($value) - { - $this->weight = $value; - } - - public function get_session_id() - { - return $this->session_id; - } - - public function set_session_id($value) - { - $this->session_id = $value; - } - - public function get_user_id() - { - return $this->user_id; - } - - public function set_user_id($value) - { - $this->user_id = $value; - } - - public function get_allow_text_assignment() - { - return $this->allow_text_assignment; - } - - public function set_allow_text_assignment($value) - { - $this->allow_text_assignment = $value; - } - - public function get_contains_file() - { - return $this->contains_file; - } - - public function set_contains_file($value) - { - $this->contains_file = $value; - } - - public function is_folder() - { - return $this->filetype == 'folder'; - } - - public function is_file() - { - return $this->filetype == 'file'; - } - - public function is_visible() - { - $this->get_item_property()->get_visibility() == 1; - } - - public function is_accessible($user = null) - { - $user_id = $user ? $user : api_get_user_id(); - $result = $this->is_visible() || $this->get_user_id() == $user_id || api_is_allowed_to_edit(); - return $result; - } - - public function get_absolute_path() - { - return api_get_path(SYS_COURSE_PATH) . api_get_course_path() . '/' . $this->get_url(); - } - - /** - * - * @return \Model\ItemProperty - */ - public function get_item_property() - { - if ($this->item_property && $this->item_property->get_c_id() == $this->c_id && $this->item_property->get_ref() == $this->id) { - return $this->item_property; - } - - $this->item_property = ItemProperty::get_by_ref($this->id, TOOL_DOCUMENT); - return $this->item_property; - } - - /** - * - * @param bool $all - * @return ResultSet|array - */ - public function get_children() - { - if (!$this->is_folder()) { - return array(); - } - $id = $this->id; - $c_id = $this->c_id; - $where = "pub.c_id = $c_id AND pub.parent_id = $id"; - return self::query($where); - } - -} - -class StudentPublicationRepository -{ - - /** - * - * @staticvar null $result - * @return StudentPublicationRepository - */ - public static function instance() - { - static $result = null; - if (empty($result)) { - $result = new self(); - } - return $result; - } - - /** - * - * @param string $where - * @return \ResultSet - */ - public function query($where) - { - $table_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY); - $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION); - $tool = 'work'; - - $sql = "SELECT pub.*, - prop.id AS property_id, - prop.tool, - prop.insert_user_id, - prop.insert_date, - prop.lastedit_date, - prop.ref, - prop.lastedit_type, - prop.lastedit_user_id, - prop.to_group_id, - prop.to_user_id, - prop.visibility, - prop.start_visible, - prop.end_visible, - prop.id_session - FROM - $table AS pub, - $table_item_property AS prop - WHERE - (pub.id = prop.ref AND - pub.c_id = prop.c_id AND - prop.tool = '$tool')"; - - $sql .= $where ? "AND ($where)" : ''; - $result = new ResultSet($sql); - return $result->return_type(__CLASS__); - } - - /** - * - * @param int|Course $c_id - * @param int $id - * @return \Model\StudentPublication - */ - public function get_by_id($c_id, $id) - { - $c_id = is_object($c_id) ? $c_id->get_id() : (int) $c_id; - return $this->query("pub.c_id = $c_id AND pub.id = $id")->first(); - } - - public function update($pub) - { - - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/closure_compiler.class.php b/main/inc/lib/system/closure_compiler.class.php deleted file mode 100755 index f69d00b27c..0000000000 --- a/main/inc/lib/system/closure_compiler.class.php +++ /dev/null @@ -1,92 +0,0 @@ - for the Univesity of Geneva - * @see http://closure-compiler.appspot.com/home - * @see https://developers.google.com/closure/compiler/ - * - */ -class ClosureCompiler -{ - - const PARAM_OUTPUT_FORMAT = 'output_format'; - const PARAM_OUTPUT_INFO = 'output_info'; - const PARAM_COMPILATION_LEVEL = 'compilation_level'; - const PARAM_JS_CODE = 'js_code'; - const LEVEL_SIMPLE = 'SIMPLE_OPTIMIZATIONS'; - const LEVEL_WHITESPACE = 'WHITESPACE_ONLY'; - const LEVEL_ADVANCED = 'ADVANCED_OPTIMIZATIONS'; - const OUTPUT_FORMAT_TEXT = 'text'; - const OUTPUT_INFO_CODE = 'compiled_code'; - - /** - * Url of the service - * - * @return string - */ - public static function url() - { - return 'closure-compiler.appspot.com/compile'; - } - - /** - * Post data the closure compiler service. By default it returns minimized code - * with the simple option. - * - * @param string $code Javascript code to minimify - * @param array $params parameters to pass to the service - * @return string minimified code - */ - public static function post($code, $params = array()) - { - if (!isset($params[self::PARAM_OUTPUT_FORMAT])) - { - $params[self::PARAM_OUTPUT_FORMAT] = self::OUTPUT_FORMAT_TEXT; - } - if (!isset($params[self::PARAM_OUTPUT_INFO])) - { - $params[self::PARAM_OUTPUT_INFO] = self::OUTPUT_INFO_CODE; - } - if (!isset($params[self::PARAM_COMPILATION_LEVEL])) - { - $params[self::PARAM_JS_CODE] = $code; - } - - $params[self::PARAM_COMPILATION_LEVEL] = self::LEVEL_SIMPLE; - - $fields = array(); - foreach ($params as $key => $value) - { - $fields[] = $key . '=' . urlencode($value); - } - $fields = implode('&', $fields); - - $headers = array("Content-type: application/x-www-form-urlencoded"); - - $url = self::url(); - - $ch = curl_init(); - - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); - //curl_setopt($ch, CURLOPT_HEADER, false); - //curl_setopt($ch, CURLOPT_VERBOSE, true); - - $content = curl_exec($ch); - $error = curl_error($ch); - $info = curl_getinfo($ch); - - curl_close($ch); - - return $content; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/code_utilities.class.php b/main/inc/lib/system/code_utilities.class.php deleted file mode 100755 index 377674adf1..0000000000 --- a/main/inc/lib/system/code_utilities.class.php +++ /dev/null @@ -1,92 +0,0 @@ - for the Univesity of Geneva - */ -class CodeUtilities -{ - - const CLASS_PATTERN = '/(?:\s+class\s+[a-zA-Z_0-9\x7f-\xff]+\s*{)|(?:\s+class\s+[a-zA-Z_0-9\x7f-\xff]+\s*extends)|(?:\s+class\s+[a-zA-Z_0-9\x7f-\xff]+\s*implements)|(?:\s+interface\s+[a-zA-Z_0-9\x7f-\xff]+\s*{)|(?:\s+interface\s+[a-zA-Z_0-9\x7f-\xff]+\s*extends)/mi'; - const INLINE_COMMENT_PATTERN = '#//.*$#m'; - const MULTILINE_COMMENT_PATTERN = '#/\*.*?\*/#ms'; - const NAMESPACE_PATTERN = '/namespace\s*(.*);/'; - const IDENTIFIER_PATTERN = '/^[a-zA-Z_][a-zA-Z0-9_]*$/'; - - static function remove_comments($content) - { - $content = preg_replace(self::INLINE_COMMENT_PATTERN, '', $content); - $content = preg_replace(self::MULTILINE_COMMENT_PATTERN, '', $content); - return $content; - } - - /** - * Returns the name of classes and interfaces contained in content. - * - * @param text $content - * @return array - */ - static function get_classes($content) - { - $result = array(); - $cls_pattern = self::CLASS_PATTERN; - - $content = self::remove_comments($content); //comments may contains class declaration we don't want to capture. - - $matches = array(); - if (preg_match_all($cls_pattern, $content, $matches)) { - $matches = reset($matches); - foreach ($matches as $match) { - $match = str_replace("\n", ' ', $match); - $match = str_replace('{', ' ', $match); - $words = explode(' ', $match); - foreach ($words as $word) { - $word = trim($word); - //we capture the interface/class name with the current pattern - if (strtolower($word) != 'class' && strtolower($word) != 'interface' && strtolower($word) != 'implements' && strtolower($word) != 'extends' && !empty($word)) { - $result[] = $word; - break; //we only take the first name as we don't want to capture the name of the interface or of the parent class name - } - } - } - } - return $result; - } - - static function get_namespace($content) - { - $namespace_pattern = self::NAMESPACE_PATTERN; - if (preg_match($namespace_pattern, $content, $matches)) { - $result = end($matches); - return trim($result); - } else { - return false; - } - } - - static function is_valid_identifier($name) - { - $pattern = self::IDENTIFIER_PATTERN; - $r = preg_match($pattern, $name); - return $r; - } - - /** - * Make path relative to root. - * - * @param string $root - * @param string $path - * @return string - */ - static function relative_path($root, $path) - { - $path = realpath($path); - $root = realpath($root); - $path = str_ireplace($root, '', $path); - $path = str_ireplace('\\', '/', $path); - return $path; - } - -} diff --git a/main/inc/lib/system/media/renderer/__README.txt b/main/inc/lib/system/media/renderer/__README.txt deleted file mode 100755 index da33a4f0af..0000000000 --- a/main/inc/lib/system/media/renderer/__README.txt +++ /dev/null @@ -1 +0,0 @@ -Used to extract metadata from external resources : youtube, dailymotion, etc \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/asset_aggregated_renderer.class.php b/main/inc/lib/system/media/renderer/asset_aggregated_renderer.class.php deleted file mode 100755 index a36c91d812..0000000000 --- a/main/inc/lib/system/media/renderer/asset_aggregated_renderer.class.php +++ /dev/null @@ -1,56 +0,0 @@ -renderers = $renderers; - } - - /** - * - * @return array - */ - public function renderers() - { - return $this->renderers; - } - - /** - * - * @param HttpResource $asset - * @return array - */ - public function render($asset) - { - $result = array(); - $plugins = self::plugins(); - foreach ($this->renderers as $renderer) - { - $data = $renderer->render($asset); - $data = $data ? $data : array(); - foreach ($data as $key => $value) - { - if (!isset($result[$key]) && !empty($value)) - { - $result[$key] = $value; - } - } - } - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/asset_renderer.class.php b/main/inc/lib/system/media/renderer/asset_renderer.class.php deleted file mode 100755 index 3173e0518d..0000000000 --- a/main/inc/lib/system/media/renderer/asset_renderer.class.php +++ /dev/null @@ -1,107 +0,0 @@ -render($asset); - $result['url'] = $url; - return $result; - } - - static function plugins() - { - static $result = array(); - if (!empty($result)) - { - return $result; - } - - /* - * We make sure we load them from most specialized to less specialized. - * The first that provides a value for a field wins. - */ - $protocols = array( - 'oembed', - 'og', - 'image', - 'media', - 'rss', - 'google_map', - 'google_document', - 'google_document_viewer', - 'google_widget', - 'mediaserver', - 'scratch', - 'page'); - - foreach ($protocols as $protocol) - { - $file = "asset_{$protocol}_renderer.class.php"; - require_once dirname(__FILE__) . '/protocol/' . $file; - - $class = "asset_{$protocol}_renderer"; - $class = explode('_', $class); - $class = array_map('ucfirst', $class); - $class = implode($class); - - $result[] = new $class(); - } - return $result; - } - - /** - * Renderer function. Take a http asset as input and return an array containing - * various properties: metadata, html snippet, etc. - * - * @param HttpResource $asset - * @return array - */ - public function render($asset) - { - $result = array(); - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/http_resource.class.php b/main/inc/lib/system/media/renderer/http_resource.class.php deleted file mode 100755 index 591da048eb..0000000000 --- a/main/inc/lib/system/media/renderer/http_resource.class.php +++ /dev/null @@ -1,662 +0,0 @@ -url = $url; - $this->config = $config; - } - - public function config($key = '', $default = null) - { - return isset($this->config[$key]) ? $this->config[$key] : $default; - } - - /** - * Url of the resource - * - * @return string - */ - public function url() - { - return $this->url; - } - - public function url_domain() - { - $url = $this->url(); - $url = trim($url, '/'); - if (strpos($url, '//') !== false) - { - $parts = explode('//', $url); - $url = end($parts); - } - $parts = explode('/', $url); - $result = reset($parts); - return $result; - } - - /** - * - * @param array|string $part - * @return boolean - */ - public function url_match($part) - { - $params = func_get_args(); - $params = is_array($params) ? $params : array($params); - - $url = strtolower($this->url()); - foreach ($params as $param) - { - if (strpos($url, strtolower($param)) !== false) - { - return true; - } - } - return false; - } - - public function url_params() - { - if (!is_null($this->url_params)) - { - return $this->url_params; - } - - $url = $this->url(); - if (strpos($url, '?') === false) - { - return $this->url_params = array(); - } - - $result = array(); - $params = explode('?', $url); - $params = end($params); - $params = explode('&', $params); - foreach ($params as $param) - { - list($key, $val) = explode('=', $param); - $result[$key] = $val; - } - - return $this->url_params = $result; - } - - public function url_param($name, $default = false) - { - $params = $this->url_params(); - return isset($params[$name]) ? $params[$name] : $default; - } - - /** - * The name of the resource. I.e. the last part of the url without the ext - * - * @return string - */ - public function name() - { - $url = $this->url(); - $url = explode('/', $url); - $title = end($url); - $title = explode('.', $title); - $title = reset($title); - return $title; - } - - /** - * Extention of the url - * - * @return string - */ - public function ext() - { - $url = $this->url(); - $url = explode('.', $url); - $ext = end($url); - $ext = strtolower($ext); - return $ext; - } - - /** - * Return true if the object has one of the extentions. Overloaded: - * - * $res->has_ext('pdf'); - * $res->has_ext('pdf', 'doc'); - * $res->has_ext(array('pdf', 'doc')); - * - * @param array|string $_ - * @return boolean true if the resource has one of the extentions passed - */ - public function has_ext($_) - { - if (is_array($_)) - { - $params = $_; - } - else - { - $params = func_get_args(); - $params = is_array($params) ? $params : array($params); - } - $ext = $this->ext(); - foreach ($params as $param) - { - if (strtolower($param) == $ext) - { - return true; - } - } - return false; - } - - public function charset() - { - $info = $this->info(); - - $content_type = isset($info['content_type']) ? $info['content_type'] : ''; - if (empty($content_type)) - { - return null; - } - $items = explode(';', $content_type); - foreach ($items as $item) - { - $parts = explode('=', $item); - if (count($parts) == 2 && reset($parts) == 'charset') - { - return strtolower(end($parts)); - } - } - return null; - } - - /** - * The mime type of the resource or the empty string if none has been specified - * - * @return string - */ - public function mime() - { - if (!is_null($this->mime)) - { - return $this->mime; - } - $info = $this->info(); - - $content_type = isset($info['content_type']) ? $info['content_type'] : ''; - if ($content_type) - { - $result = reset(explode(';', $content_type)); - $result = strtolower($result); - return $this->mime = $result; - } - - return $this->mime = ''; - } - - public function is_xml() - { - $mime = $this->mime(); - if (!empty($mime)) - { - return strpos($mime, 'xml') !== false; - } - return $this->ext() == 'xml'; - } - - public function is_image() - { - $mime = $this->mime(); - if ($mime) - { - return strpos($mime, 'image') !== false; - } - - $ext = $this->ext(); - $formats = array('gif', 'jpeg', 'jpg', 'jpe', 'pjpeg', 'png', 'svg', 'tiff', 'ico'); - foreach ($formats as $format) - { - if ($format == $ext) - { - return true; - } - } - return false; - } - - public function is_video() - { - $mime = $this->mime(); - if ($mime) - { - return strpos($mime, 'video') !== false; - } - - $ext = $this->ext(); - $formats = array('mpeg', 'mp4', 'ogg', 'wmv', 'mkv'); - foreach ($formats as $format) - { - if ($format == $ext) - { - return true; - } - } - return false; - } - - public function is_audio() - { - $mime = $this->mime(); - if ($mime) - { - return strpos($mime, 'audio') !== false; - } - - $ext = $this->ext(); - $formats = array('mp3'); - foreach ($formats as $format) - { - if ($format == $ext) - { - return true; - } - } - return false; - } - - public function is_rss() - { - if (!$this->is_xml()) - { - return false; - } - - $doc = $this->doc(); - $nodes = $doc->getElementsByTagName('rss'); - return $nodes->length != 0; - } - - public function is_gadget() - { - if (!$this->is_xml()) - { - return false; - } - - $doc = $this->doc(); - $nodes = $doc->getElementsByTagName('ModulePrefs'); - return $nodes->length != 0; - } - - public function canonic_url($src) - { - if (strpos($src, '//') === 0) - { - $src = "http:$src"; - } - else if (strpos($src, '/') === 0) //relative url to the root - { - $url = $this->url(); - $protocol = reset(explode('://', $url)); - $domain = end(explode('://', $url)); - $domain = reset(explode('/', $domain)); - $src = "$protocol://$domain/$src"; - } - else if (strpos($src, 'http') !== 0) //relative url to the document - { - $url = $this->url(); - $tail = end(explode('/', $url)); - $base = str_replace($tail, '', $url); - - $src = $base . $src; - } - return $src; - } - - /** - * Content of the resource. - * - * @return string - */ - public function source() - { - if (!is_null($this->source)) - { - return $this->source; - } - $info = $this->info(); - - return $this->source = $info['content']; - } - - /** - * Array of arrays containing the page's metadata. - * - * @return array - */ - public function metadata() - { - if (!is_null($this->metadata)) - { - return $this->metadata; - } - return $this->metadata = $this->get_metadata(); - } - - public function title() - { - if (!is_null($this->title)) - { - return $this->title; - } - return $this->title = $this->get_title(); - } - - /** - * - * @return DOMDocument|boolean - */ - public function doc() - { - if (!is_null($this->doc)) - { - return $this->doc; - } - return $this->doc = $this->get_doc($this->source()); - } - - function get_meta($name) - { - $metadata = $this->metadata(); - $name = strtolower($name); - foreach ($metadata as $attributes) - { - $key = isset($attributes['name']) ? $attributes['name'] : false; - $key = $key ? strtolower($key) : $key; - if ($name == $key) - { - return $attributes['content']; - } - $key = isset($attributes['property']) ? $attributes['property'] : false; - $key = $key ? strtolower($key) : $key; - if ($name == $key) - { - return isset($attributes['content']) ? $attributes['content'] : false; - } - } - return false; - } - - function get_link($key, $value) - { - $links = $this->links(); - $key = strtolower($key); - $value = strtolower($value); - foreach ($links as $attributes) - { - $a = isset($attributes[$key]) ? $attributes[$key] : false; - $a = $a ? strtolower($a) : $a; - if ($a == $value) - { - return $attributes; - } - } - return false; - } - - public function links() - { - if (!is_null($this->links)) - { - return $this->links; - } - return $this->links = $this->get_links(); - } - - /** - * - * @param string $xpath dom xpath - * @return string - */ - public function findx($query) - { - $doc = $this->doc(); - if (empty($doc)) - { - return array(); - } - $xpath = new DOMXpath($doc); - $nodes = $xpath->query($query); - if ($nodes->length > 0) - { - return $doc->saveXML($nodes->item(0)); - } - else - { - return ''; - } - } - - protected function info() - { - if (!is_null($this->info)) - { - return $this->info; - } - return $this->info = self::fetch($this->url()); - } - - /** - * - * @param string $source - * @return boolean|DOMDocument - */ - protected function get_doc($source) - { - if ($source == false) - { - return false; - } - $source = $this->source(); - $result = new DOMDocument(); - libxml_clear_errors(); - libxml_use_internal_errors(true); - if ($this->is_xml()) - { - $success = $result->loadXML($source); - } - else - { - $success = $result->loadHTML($source); - } - //$e = libxml_get_errors(); - return $result ? $result : false; - } - - protected function get_metadata() - { - $result = array(); - - $doc = $this->doc(); - if ($doc == false) - { - return array(); - } - $metas = $doc->getElementsByTagName('meta'); - if ($metas->length == 0) - { - return $result; - } - foreach ($metas as $meta) - { - $values = array(); - $attributes = $meta->attributes; - $length = $attributes->length; - for ($i = 0; $i < $length; ++$i) - { - $name = $attributes->item($i)->name; - $value = $attributes->item($i)->value; - $value = $attributes->item($i)->value; - $values[$name] = $value; - } - $result[] = $values; - } - return $result; - } - - protected function get_title() - { - $doc = $this->doc(); - if ($doc == false) - { - return ''; - } - $titles = $doc->getElementsByTagName('title'); - if ($titles->length == 0) - { - return false; - } - $result = $titles->item(0)->nodeValue; - return $result; - } - - protected function get_links() - { - $doc = $this->doc(); - if ($doc == false) - { - return array(); - } - $result = array(); - - $metas = $doc->getElementsByTagName('link'); - if ($metas->length == 0) - { - return $result; - } - foreach ($metas as $meta) - { - $values = array(); - $attributes = $meta->attributes; - $length = $attributes->length; - for ($i = 0; $i < $length; ++$i) - { - $name = $attributes->item($i)->name; - $value = $attributes->item($i)->value; - $values[$name] = $value; - } - $result[] = $values; - } - return $result; - } - -} diff --git a/main/inc/lib/system/media/renderer/lab/asset_google_calendar_renderer.class.php b/main/inc/lib/system/media/renderer/lab/asset_google_calendar_renderer.class.php deleted file mode 100755 index 8787b16ba6..0000000000 --- a/main/inc/lib/system/media/renderer/lab/asset_google_calendar_renderer.class.php +++ /dev/null @@ -1,113 +0,0 @@ -url(); - $url = str_replace('http://', '', $url); - $url = str_replace('https://', '', $url); - - $domain = reset(split('/', $url)); - return strpos($domain, 'google.com/calendar') !== false; - } - - /** - * - * @param string $url - */ - public function explode_url_parameters($url = null) - { - if (strpos($url, '?') === false) - { - return array(); - } - - $result = array(); - $params = explode('?', $url); - $params = end($params); - $params = explode('&', $params); - foreach ($params as $param) - { - list($key, $val) = explode('=', $param); - $result[$key] = $val; - } - - return $result; - } - - public function implode_url_parameters($params) - { - $result = array(); - foreach ($params as $key => $value) - { - if ($value) - { - $result[] = "$key=$value"; - } - } - return join('&', $result); - } - - protected function url($base = 'http:://map.google.com/', $params = array()) - { - $head = reset(explode('?', $base)); - $items = $this->explode_url_parameters($base); - foreach ($params as $key => $value) - { - $items[$key] = $value; - } - $tail = $this->implode_url_parameters($items); - $tail = empty($tail) ? '' : "?$tail"; - return $head . $tail; - } - - /** - * - * @param HttpResource $asset - */ - public function render($asset) - { - if (!$this->accept($asset)) - { - return; - } - $params = array('output' => 'embed'); - - $base = $asset->url(); - $url = $this->url($base, $params); - - $title = $asset->title(); - $description = $asset->get_meta('description'); - - $keywords = $asset->get_meta('keywords'); - - $embed = << -EOT; - - - $result = array(); - $result[self::EMBED_SNIPPET] = $embed; - $result[self::TITLE] = $title; - $result[self::THUMBNAIL] = $image_src; - $result[self::DESCRIPTION] = $description; - $result[self::TAGS] = $keywords; - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/lab/asset_mahara_group_renderer.class.php b/main/inc/lib/system/media/renderer/lab/asset_mahara_group_renderer.class.php deleted file mode 100755 index 85e0a6c1bc..0000000000 --- a/main/inc/lib/system/media/renderer/lab/asset_mahara_group_renderer.class.php +++ /dev/null @@ -1,57 +0,0 @@ -url(); - $group_id = self::get_group_id($url); - if (empty($group_id)) - { - return false; - } - - $data = get_record('group', 'id', $group_id); - - $result = array(); - safe_require('blocktype', 'ple/group'); - $result[self::EMBED_SNIPPET] = PluginBlocktypeGroup::render_preview($group_id); - $result[self::THUMBNAIL] = PluginBlocktypeGroup::get_thumbnail($group_id); - $result[self::TITLE] = $data->name; - $result[self::DESCRIPTION] = $data->description; - - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/lab/asset_mahara_person_renderer.class.php b/main/inc/lib/system/media/renderer/lab/asset_mahara_person_renderer.class.php deleted file mode 100755 index a264885ad0..0000000000 --- a/main/inc/lib/system/media/renderer/lab/asset_mahara_person_renderer.class.php +++ /dev/null @@ -1,63 +0,0 @@ -id; - } - //user id - if ($val = intval($ref)) - { - return $val; - } - - return false; - } - - /** - * - * @param HttpResource $asset - */ - public function render($asset) - { - $url = $asset->url(); - $id = self::get_user_id($url); - if (empty($id)) - { - return false; - } - - $data = get_record('usr', 'id', $id); - - $result = array(); - safe_require('blocktype', 'ple/person'); - $result[self::EMBED_SNIPPET] = PluginBlocktypePerson::render_preview($id); - $result[self::THUMBNAIL] = PluginBlocktypePerson::get_thumbnail($id); - $result[self::TITLE] = $data->prefferedname ? $data->prefferedname : $data->firstname . ' ' . $data->lastname; - $result[self::DESCRIPTION] = isset($data->description) ? $data->description : ''; - - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/lab/asset_wiki_renderer.class.php b/main/inc/lib/system/media/renderer/lab/asset_wiki_renderer.class.php deleted file mode 100755 index b110cdab07..0000000000 --- a/main/inc/lib/system/media/renderer/lab/asset_wiki_renderer.class.php +++ /dev/null @@ -1,46 +0,0 @@ -url_match('wikipedia.org/wiki', 'mediawiki.org/wiki'); - } - - /** - * - * @param HttpResource $asset - * - */ - public function render($asset) - { - if (!$this->accept($asset)) - { - return; - } - - $domain = $asset->url_domain(); - $description = $asset->findx('//div[@id="bodyContent"]/p'); - $result = array(); - $result[self::EMBED_SNIPPET] = $description; - $result[self::TITLE] = $title; - $result[self::DESCRIPTION] = $description; - $result[self::TAGS] = $keywords; - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_google_document_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_google_document_renderer.class.php deleted file mode 100755 index f8e26995c2..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_google_document_renderer.class.php +++ /dev/null @@ -1,75 +0,0 @@ -url(); - - return strpos($url, 'docs.google.com/document/pub') !== false; - } - - /** - * - * @param HttpResource $asset - */ - public function render($asset) - { - if (!$this->accept($asset)) - { - return; - } - - $url = $asset->url(); - - $title = $asset->title(); - $description = $asset->get_meta('description'); - $keywords = $asset->get_meta('keywords'); - - $size = (int) $asset->config('size'); - $size = (24 <= $size && $size <= 800) ? $size : 300; - - $embed = << - -
- -EOT; - - - $result = array(); - $result[self::EMBED_SNIPPET] = $embed; - $result[self::TITLE] = $title; - $result[self::DESCRIPTION] = $description; - $result[self::TAGS] = $keywords; - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_google_document_viewer_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_google_document_viewer_renderer.class.php deleted file mode 100755 index fc9197a92a..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_google_document_viewer_renderer.class.php +++ /dev/null @@ -1,95 +0,0 @@ -has_ext($supported_extentions); - } - - protected function url($document_url) - { - return 'https://docs.google.com/viewer?embedded=true&url=' . urlencode($document_url); - } - - /** - * - * @param HttpResource $asset - */ - public function render($asset) - { - if (!$this->accept($asset)) - { - return; - } - - $url = $this->url($asset->url()); - - $title = $asset->title(); - $description = $asset->get_meta('description'); - - $keywords = $asset->get_meta('keywords'); - - $size = (int) $asset->config('size'); - $size = (24 <= $size && $size <= 800) ? $size : 300; - - $embed = << - -
- -EOT; - - - $result = array(); - $result[self::EMBED_SNIPPET] = $embed; - $result[self::TITLE] = $title; - //$result[self::THUMBNAIL] = $image_src; - $result[self::DESCRIPTION] = $description; - $result[self::TAGS] = $keywords; - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_google_map_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_google_map_renderer.class.php deleted file mode 100755 index c49eee8dd4..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_google_map_renderer.class.php +++ /dev/null @@ -1,129 +0,0 @@ -url(); - $url = str_replace('http://', '', $url); - $url = str_replace('https://', '', $url); - - $domain = reset(explode('/', $url)); - return strpos($domain, 'maps.google') !== false; - } - - /** - * - * @param string $url - */ - public function explode_url_parameters($url = null) - { - if (strpos($url, '?') === false) - { - return array(); - } - - $result = array(); - $params = explode('?', $url); - $params = end($params); - $params = explode('&', $params); - foreach ($params as $param) - { - list($key, $val) = explode('=', $param); - $result[$key] = $val; - } - - return $result; - } - - public function implode_url_parameters($params) - { - $result = array(); - foreach ($params as $key => $value) - { - if ($value) - { - $result[] = "$key=$value"; - } - } - return join('&', $result); - } - - protected function url($base = 'http:://map.google.com/', $params = array()) - { - $head = reset(explode('?', $base)); - $items = $this->explode_url_parameters($base); - foreach ($params as $key => $value) - { - $items[$key] = $value; - } - $tail = $this->implode_url_parameters($items); - $tail = empty($tail) ? '' : "?$tail"; - return $head . $tail; - } - - /** - * - * @param HttpResource $asset - */ - public function render($asset) - { - if (!$this->accept($asset)) - { - return; - } - - $params = array('output' => 'embed'); - - $base = $asset->url(); - $url = $this->url($base, $params); - - $title = $asset->title(); - $description = $asset->get_meta('description'); - - $keywords = $asset->get_meta('keywords'); - - $size = (int) $asset->config('size'); - $size = (24 <= $size && $size <= 800) ? $size : 300; - - $embed = << - -
- -EOT; - - - $result = array(); - $result[self::EMBED_SNIPPET] = $embed; - $result[self::TITLE] = $title; - $result[self::DESCRIPTION] = $description; - $result[self::TAGS] = $keywords; - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_google_widget_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_google_widget_renderer.class.php deleted file mode 100755 index b98a46149c..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_google_widget_renderer.class.php +++ /dev/null @@ -1,90 +0,0 @@ -url_match('gmodules.com/ig/') && $asset->url_param('url') != false) - { - $url = $asset->url(); - $title = $asset->url_param('title'); - $title = ($title == '__MSG_title__') ? '' : $title; - - $embed = << -EOT; - - $result = array(); - $result[self::EMBED_SNIPPET] = $embed; - $result[self::TITLE] = $title; - return $result; - } - - if (!$asset->is_gadget()) - { - $url = $asset->url(); - - if (!$asset->url_match('google.com/ig/directory')) - { - return false; - } - if (!$asset->url_match('type=gadgets')) - { - return false; - } - - $url = $asset->url_param('url'); - if (empty($url)) - { - return false; - } - $asset = new HttpResource($url); - if (!$asset->is_gadget()) - { - return false; - } - } - - $url = $asset->url(); - if (strpos($url, 'http') !== 0) - { - $url = "http://$url"; - } - $url = urlencode($url); - $title = $asset->title(); - $title = $title ? $title : $asset->name(); - - $size = (int) $asset->config('size'); - $size = (24 <= $size && $size <= 800) ? $size : 300; - - $embed = << -EOT; - - $result = array(); - $result[self::EMBED_SNIPPET] = $embed; - $result[self::TITLE] = $title; - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_image_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_image_renderer.class.php deleted file mode 100755 index 9b8df5b364..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_image_renderer.class.php +++ /dev/null @@ -1,44 +0,0 @@ -is_image()) - { - return false; - } - - global $THEME; - $url = $asset->url(); - $title = $asset->title(); - $title = $title ? $title : $asset->name(); - - $size = (int) $asset->config('size'); - $size = (24 <= $size && $size <= 800) ? $size : 300; - - $embed = <<{$title}
-EOT; - - $result = array(); - $result[self::URL] = $url; - $result[self::EMBED_SNIPPET] = $embed; - $result[self::TITLE] = $title; - $result[self::THUMBNAIL] = $url; - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_media_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_media_renderer.class.php deleted file mode 100755 index 5572296b32..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_media_renderer.class.php +++ /dev/null @@ -1,65 +0,0 @@ -is_video()) - { - return true; - } - - //swf mime type is application/x-shockwave-flash - return $asset->has_ext('swf'); - } - - /** - * - * @param HttpResource $asset - */ - public function render($asset) - { - if (!$this->accept($asset)) - { - return; - } - - $url = $asset->url(); - - $title = $asset->title(); - $description = $asset->get_meta('description'); - $keywords = $asset->get_meta('keywords'); - - - $size = (int) $asset->config('size'); - $size = (24 <= $size && $size <= 800) ? $size : 300; - - $width = $size; - $height = $size *9/16; - - $embed = <<
-EOT; - - - $result = array(); - $result[self::EMBED_SNIPPET] = $embed; - $result[self::TITLE] = $title; - $result[self::DESCRIPTION] = $description; - $result[self::TAGS] = $keywords; - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_mediaserver_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_mediaserver_renderer.class.php deleted file mode 100755 index f83d9a5831..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_mediaserver_renderer.class.php +++ /dev/null @@ -1,65 +0,0 @@ -url_match('https://mediaserver.unige.ch/play/') ||$asset->url_match('http://mediaserver.unige.ch/play/'); - } - - /** - * - * @param HttpResource $asset - */ - public function render($asset) - { - if (!$this->accept($asset)) - { - return; - } - - $width = (int) $asset->config('size'); - $width = (24 <= $width && $width <= 800) ? $width : 300; - - $url = $asset->url(); - - $oembed = self::API_ENDPOINT . '?url=' . urlencode($url) . '&maxwidth=' . $width; - - $data = HttpResource::fetch_json($oembed); - if (empty($data)) - { - return false; - } - - $result[self::THUMBNAIL] = isset($data['thumbnail_url']) ? $data['thumbnail_url'] : ''; - $result[self::TITLE] = isset($data['title']) ? $data['title'] : ''; - $result[self::EMBED_SNIPPET] = isset($data['html']) ? $data['html'] : ''; - - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_oembed_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_oembed_renderer.class.php deleted file mode 100755 index 1eef014baa..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_oembed_renderer.class.php +++ /dev/null @@ -1,124 +0,0 @@ -get_link('type', 'application/json+oembed'); - if (empty($link)) - { - return false; - } - - $width = (int) $asset->config('size'); - $width = (24 <= $width && $width <= 800) ? $width : 300; - - $href = $link['href']; - $data = HttpResource::fetch_json("$href&maxwidth=$width"); //&maxheight=$height - if (empty($data)) - { - return false; - } - - $data['title'] = isset($data['title']) ? $data['title'] : ''; - $data['width'] = isset($data['width']) ? intval($data['width']) : ''; - $data['height'] = isset($data['height']) ? intval($data['height']) : ''; - - $type = $data['type']; - $f = array($this, "render_$type"); - if (is_callable($f)) - { - $result = call_user_func($f, $asset, $data); - } - else - { - $result = array(); - } - $result[self::THUMBNAIL] = isset($data['thumbnail_url']) ? $data['thumbnail_url'] : ''; - $result[self::TITLE] = isset($data['title']) ? $data['title'] : ''; - - return $result; - } - - protected function render_photo($asset, $data) - { - if ($data['type'] != 'photo') - { - return array(); - } - - $result = array(); - $html = isset($data['html']) ? $data['html'] : ''; - if ($html) - { - $result[self::EMBED_SNIPPET] = '
' . $html . '
'; - return $result; - } - - $title = $data['title']; - $width = (int)$data['width']; - $height = (int)$data['height']; -// $ratio = $height / $width; -// $height = $ratio * $width; - - $url = $data['url']; - - $embed = << -EOT; - - $result[self::EMBED_SNIPPET] = $embed; - return $result; - } - - protected function render_video($asset, $data) - { - if ($data['type'] != 'video') - { - return array(); - } - $result = array(); - $result[self::EMBED_SNIPPET] = '
' . $data['html'] . '
'; - return $result; - } - - protected function render_rich($asset, $data) - { - if ($data['type'] != 'rich') - { - return array(); - } - - $result = array(); - $result[self::EMBED_SNIPPET] = '
' . $data['html'] . '
'; - return $result; - } - - protected function render_link($asset, $data) - { - if ($data['type'] != 'link') - { - return array(); - } - return array(); - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_og_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_og_renderer.class.php deleted file mode 100755 index 9eb56ce1bf..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_og_renderer.class.php +++ /dev/null @@ -1,201 +0,0 @@ -get_meta('og:type'); - if (empty($type)) - { - if ($video = $asset->get_meta('og:video')) - { - $type = 'video'; - } - else if ($video = $asset->get_meta('og:image')) - { - $type = 'default'; - } - } - if (empty($type)) - { - return array(); - } - - $type = explode('.', $type); - $type = reset($type); - $f = array($this, "render_$type"); - if (is_callable($f)) - { - $result = call_user_func($f, $asset); - } - else - { - $result = $this->render_default($asset); - } - - $result[self::TITLE] = $asset->get_meta('og:title'); - $result[self::THUMBNAIL] = $asset->get_meta('og:image'); - $result[self::LANGUAGE] = $asset->get_meta('og:language'); - - return $result; - } - - /** - * @param HttpResource $asset - * @return array - */ - protected function render_video($asset) - { - $url = $asset->get_meta('og:video'); - $url = str_replace('?autoPlay=1', '?', $url); - $url = str_replace('&autoPlay=1', '', $url); - - if (empty($url)) - { - return array(); - } - - $type = $asset->get_meta('og:video:type'); - if ($type) - { - $type = ' type="' . $type . '" '; - } - - $size = (int) $asset->config('size'); - $size = (24 <= $size && $size <= 800) ? $size : 300; - - $width = $asset->get_meta('og:video:width'); - $width = $width ? $width : $asset->get_meta('video_width'); - $height = $asset->get_meta('og:video:height'); - $height = $height ? $height : $asset->get_meta('video_height'); - - if ($width) - { - $ratio = $height / $width; - $base = min($size, $width); - $width = $base; - $height = $ratio * $base; - $size = 'width="' . $width . '" height="' . $height . '"'; - } - else - { - $size = 'width="' . $size . '"'; - } - - $embed = << -EOT; - - $result[self::EMBED_TYPE] = $type; - $result[self::EMBED_URL] = $url; - $result[self::EMBED_SNIPPET] = $embed; - $result[self::TAGS] = $asset->get_meta('og:video:tag'); - $result[self::CREATED_TIME] = $asset->get_meta('og:video:release_date'); - $result[self::DURATION] = $asset->get_meta('og:duration'); - return $result; - } - - protected function render_article($asset) - { - $result = $this->render_default($asset); - return $result; - } - - protected function render_audio($asset) - { - $result = $this->render_default($asset); - return $result; - } - - protected function render_book($asset) - { - $result = $this->render_default($asset); - return $result; - } - - /** - * - * @param HttpResource $asset - * @return array - */ - protected function render_default($asset) - { - $url = $asset->get_meta('og:url'); - $url = htmlentities($url); - $title = $asset->get_meta('og:title'); - $image = $asset->get_meta('og:image'); - $image = htmlentities($image); - $width = $asset->get_meta('og:image:width'); - $height = $asset->get_meta('og:image:height'); - $description = $asset->get_meta('og:description'); - $description = $description ? $description : $asset->get_meta('description'); - - $size = (int) $asset->config('size'); - $size = (24 <= $size && $size <= 800) ? $size : 300; - - if ($width) - { - $ratio = $height / $width; - $base = min($size, $width); - $width = $base; - $height = $ratio * $base; - $size = 'width="' . $width . '" height="' . $height . '"'; - } - else - { - $size = 'width="' . $size . '"'; - } - $embed = << - {$title} -
- -EOT; - - $result[self::EMBED_SNIPPET] = $embed; - $result[self::DESCRIPTION] = $asset->get_meta('description'); - return $result; - } - - /** - * @param HttpResource $asset - * @return array - */ - protected function render_image($asset) - { - $size = (int) $asset->config('size'); - $size = (24 <= $size && $size <= 800) ? $size : 300; - - $title = $data['title']; - $width = $data['width']; - $height = $data['height']; - $ratio = $height / $width; - $base = min($size, $width); - $width = $base; - $height = $ratio * $base; - - $url = $data['url']; - - $embed = <<{$title} -EOT; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_page_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_page_renderer.class.php deleted file mode 100755 index d37608d1e9..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_page_renderer.class.php +++ /dev/null @@ -1,83 +0,0 @@ -url(); - $title = $asset->title(); - $title = $title ? $title : $asset->name(); - $description = $asset->get_meta('description'); - $description = $description; - - $keywords = $asset->get_meta('keywords'); - - $image_src = $asset->get_link('rel', 'image_src'); - $image_src = $image_src ? $image_src['href'] : false; - - if (empty($image_src)) - { - $image_src = $this->get_icon($asset); - } - - $icon = $this->get_icon($asset); - - $image_src = $asset->canonic_url($image_src); - $icon = $asset->canonic_url($icon); - - $embed = << - {$title} - - $description - -EOT; - - - $result = array(); - $result[self::EMBED_SNIPPET] = $embed; - $result[self::TITLE] = $title; - $result[self::THUMBNAIL] = $image_src; - $result[self::DESCRIPTION] = $description; - $result[self::ICON] = $icon; - $result[self::TAGS] = $keywords; - return $result; - } - - function get_icon($asset) - { - - $icon = $asset->get_link('rel', 'apple-touch-icon'); - $icon = $icon ? $icon['href'] : false; - if (empty($icon)) - { - $icon = $asset->get_link('rel', 'fluid-icon'); - $icon = $icon ? $icon['href'] : false; - } - if (empty($icon)) - { - $icon = $asset->get_link('rel', 'shortcut icon'); - $icon = $icon ? $icon['href'] : false; - } - if (empty($icon)) - { - $icon = $asset->get_link('rel', 'icon'); - $icon = $icon ? $icon['href'] : false; - } - return $icon; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_rss_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_rss_renderer.class.php deleted file mode 100755 index 589466965f..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_rss_renderer.class.php +++ /dev/null @@ -1,95 +0,0 @@ -is_rss()) - { - return; - } - - $url = $asset->url(); - $title = $asset->title(); - $id = 'a' . md5($url); - - $embed = << - .gfg-root { - border: none; - font-family: inherit; - } - - - - -
Loading...
-EOT; - - - $result = array(); - $result[self::EMBED_SNIPPET] = $embed; - $result[self::TITLE] = $title; - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/media/renderer/protocol/asset_scratch_renderer.class.php b/main/inc/lib/system/media/renderer/protocol/asset_scratch_renderer.class.php deleted file mode 100755 index 189c088b5b..0000000000 --- a/main/inc/lib/system/media/renderer/protocol/asset_scratch_renderer.class.php +++ /dev/null @@ -1,76 +0,0 @@ -url_match('http://scratch.mit.edu/projects/'); - } - - /** - * - * @param HttpResource $asset - */ - public function render($asset) - { - if (!$this->accept($asset)) - { - return; - } - - $matches = array(); - $pattern = "#http:\/\/scratch.mit.edu\/projects\/(\w+)/(\d*)\/?#ims"; - preg_match($pattern, $asset->url(), $matches); - - $url = $matches[0]; - $author = $matches[1]; - $project_id = $matches[2]; - - $project_url = "../../static/projects/$author/$project_id.sb"; - $image_url = "http://scratch.mit.edu/static/projects/$author/{$project_id}_med.png"; - $thumb_url = "http://scratch.mit.edu/static/projects/$author/{$project_id}_sm.png"; - - $height = 387; - $width = 482; - - if (function_exists('get_string')) - { - $no_java = get_string('no_java', 'artefact.extresource'); - } - else - { - $no_java = 'Java is not installed on your computer. You must install java first.'; - } - - $embed = << - - - - - -
$no_java
- - -EOT; - $result = array(); - $result[self::EMBED_SNIPPET] = $embed; - $result[self::THUMBNAIL] = $thumb_url; - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/net/curl.class.php b/main/inc/lib/system/net/curl.class.php deleted file mode 100755 index aceafc0646..0000000000 --- a/main/inc/lib/system/net/curl.class.php +++ /dev/null @@ -1,131 +0,0 @@ - - */ -class Curl -{ - - protected static $default_options = array(); - - static function get_default_options($options = array()) - { - if (empty(self::$default_options)) { - self::$default_options[CURLOPT_HEADER] = false; - self::$default_options[CURLOPT_RETURNTRANSFER] = true; - self::$default_options[CURLOPT_SSL_VERIFYPEER] = false; - } - - $result = self::$default_options; - foreach ($options as $key => $value) { - $result[$key] = $value; - } - return $result; - } - - static function set_default_option($key, $value) - { - $options = $this->get_options(array($key => $value)); - self::$default_options = $options; - } - - /** - * - * @param string $url - * @param array $options - * @return Curl - */ - static function get($url, $options = array()) - { - $options[CURLOPT_HTTPGET] = true; - $result = new self($url, $options); - return $result; - } - - /** - * - * @param string $url - * @param array $fields - * @param array $options - * @return Curl - */ - static function post($url, $fields, $options = array()) - { - $options[CURLOPT_POST] = true; - $options[CURLOPT_POSTFIELDS] = $fields; - $result = new self($url, $options); - return $result; - } - - protected $url = ''; - protected $options = array(); - protected $content = ''; - protected $info = array(); - protected $error = ''; - protected $error_no = 0; - - function __construct($url, $options = array()) - { - $this->url = $url; - $this->options = self::get_default_options($options); - } - - function url() - { - return $this->url; - } - - function options() - { - return $this->options; - } - - function execute() - { - $ch = curl_init(); - - $options = $this->options; - $options[CURLOPT_URL] = $this->url; - curl_setopt_array($ch, $options); - - $this->content = curl_exec($ch); - $this->error = curl_error($ch); - $this->info = curl_getinfo($ch); - $this->error_no = curl_errno($ch); - - curl_close($ch); - - return $this->content; - } - - function content() - { - return $this->content; - } - - /** - * @return array|string - */ - function info($key = false) - { - if ($key) { - return isset($this->info[$key]) ? $this->info[$key] : false; - } else { - return $this->info; - } - } - - function error() - { - return $this->error; - } - - function error_no() - { - return $this->error_no; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/net/http_channel.class.php b/main/inc/lib/system/net/http_channel.class.php deleted file mode 100755 index becb08008e..0000000000 --- a/main/inc/lib/system/net/http_channel.class.php +++ /dev/null @@ -1,72 +0,0 @@ - - */ -class HttpChannel -{ - - /** - * - * @param string $url - * @param type $modules - * @return HttpChannel - */ - static function create($url, $modules = array()) - { - return new self($url, $modules); - } - - protected $base_url = ''; - protected $modules = array(); - - public function __construct($base_url = '', $modules = array()) - { - $this->base_url = $base_url; - $this->modules = $modules; - } - - function modules() - { - return $this->modules; - } - - function get($url, $parameters) - { - $options = $this->get_options(); - $url = $this->base_url . $url; - return Curl::get($url, $options)->execute(); - } - - function post($url, $fields) - { - $options = $this->get_options(); - $url = $this->base_url . $url; - return Curl::post($url, $fields, $options)->execute(); - } - - protected function get_options() - { - $result = array(); - $modules = $this->modules(); - foreach ($modules as $module) { - if (is_array($module)) { - $options = $module; - } else { - - $options = $module->get_options(); - } - $result = array_merge($result, $options); - } - return $result; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/portfolio/artefact.class.php b/main/inc/lib/system/portfolio/artefact.class.php deleted file mode 100755 index 1a69f33a04..0000000000 --- a/main/inc/lib/system/portfolio/artefact.class.php +++ /dev/null @@ -1,149 +0,0 @@ -set_path('...'); - * - * or - * - * - * $artefact = new artefact(); - * $artefact->set_url('...'); - * - * @copyright (c) 2012 University of Geneva - * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html - * @author Laurent Opprecht - */ -class Artefact -{ - - protected $id = ''; - protected $mime_type = ''; - protected $name = ''; - protected $description = ''; - protected $path = ''; - protected $url = ''; - protected $creation_date = ''; - protected $modification_date = ''; - protected $metadata = null; - - /** - * - * @param string $file Either url or file path - */ - public function __construct($file = '') - { - if ($file) { - if (strpos($file, 'http') !== false) { - $this->url = $file; - } else { - $this->path = $file; - } - } - $this->id = uniqid('', true); - $this->mime_type = ''; - $time = time(); - $this->creation_date = $time; - $this->modification_date = $time; - } - - public function get_id() - { - return $this->id; - } - - public function set_id($value) - { - $this->id = $value; - } - - public function get_name() - { - return $this->name; - } - - public function set_name($value) - { - $this->name = $value; - } - - public function get_mime_type() - { - return $this->mime_type; - } - - public function set_mime_type($value) - { - $this->mime_type = $value; - } - - public function get_description() - { - return $this->description; - } - - public function set_description($value) - { - $this->description = $value; - } - - public function get_path() - { - return $this->path; - } - - public function set_path($value) - { - $this->path = $value; - } - - public function get_url() - { - return $this->url; - } - - public function set_url($value) - { - $this->url = $value; - } - - public function get_creation_date() - { - return $this->creation_date; - } - - public function set_creation_date($value) - { - $this->creation_date = $value; - } - - public function get_modification_date() - { - return $this->modification_date; - } - - public function set_modification_date($value) - { - $this->modification_date = $value; - } - - public function get_metadata() - { - return $this->metadata; - } - - public function set_metadata($value) - { - $this->metadata = $value; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/portfolio/download.class.php b/main/inc/lib/system/portfolio/download.class.php deleted file mode 100755 index 7bfe5436ac..0000000000 --- a/main/inc/lib/system/portfolio/download.class.php +++ /dev/null @@ -1,35 +0,0 @@ - - */ -class Download extends Portfolio -{ - - function __construct() - { - parent::__construct('download', null); - } - - /** - * - * @param User $user - * @param Artefact $artefact - * @return bool - */ - function send($user, $artefact) - { - if ($artefact->get_url()) { - Header::location($artefact->get_url()); - } - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/portfolio/mahara.class.php b/main/inc/lib/system/portfolio/mahara.class.php deleted file mode 100755 index f8b526d7f0..0000000000 --- a/main/inc/lib/system/portfolio/mahara.class.php +++ /dev/null @@ -1,59 +0,0 @@ - - */ -class Mahara extends Portfolio -{ - - protected $url = ''; - - /** - * - * @param string $url The root url - */ - function __construct($url) - { - $name = md5($url); - parent::__construct($name, null); - $this->url = $url; - } - - function get_url() - { - return $this->url; - } - - function get_title(){ - $result = parent::get_title(); - $result = $result ? $result : 'Mahara'; - return $result; - } - - /** - * - * @param User $user - * @param Artefact $artefact - * @return bool - */ - function send($user, $artefact) - { - $root = $this->get_url(); - rtrim($root, '/'); - $url = $artefact->get_url(); - $url = $root . '/artefact/connect/upload.php?url=' . urlencode($url) . '&extract=true'; - Header::location($url); - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/portfolio/portfolio.class.php b/main/inc/lib/system/portfolio/portfolio.class.php deleted file mode 100755 index b1fc225527..0000000000 --- a/main/inc/lib/system/portfolio/portfolio.class.php +++ /dev/null @@ -1,106 +0,0 @@ - - */ -class Portfolio -{ - - public static function none() - { - static $result = null; - if (empty($result)) { - $result = new self('empty', null); - } - return $result; - } - - public static function all() - { - - } - - protected $name; - protected $title = ''; - protected $description = ''; - protected $channel; - - function __construct($name, $channel = null) - { - $this->name = $name; - $this->title = $name; - $this->channel = $channel; - } - - /** - * The name of the portfolio - i.e. the unique id. - * @return type - */ - function get_name() - { - return $this->name; - } - - /** - * Title for the end user. - * - * @return type - */ - function get_title() - { - return $this->title; - } - - function set_title($value) - { - $this->title = $value; - } - - /** - * Description for the end user. - * - * @return type - */ - function get_description() - { - return $this->description; - } - - function set_description($value) - { - $this->description = $value; - } - - /** - * - * @return HttpChannel - */ - function channel() - { - return $this->channel; - } - - function __toString() - { - return $this->name; - } - - /** - * - * @param User $user - * @param Artefact $artefact - * @return bool - */ - function send($user, $artefact) - { - return false; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/portfolio/user.class.php b/main/inc/lib/system/portfolio/user.class.php deleted file mode 100755 index 52ddbacf9b..0000000000 --- a/main/inc/lib/system/portfolio/user.class.php +++ /dev/null @@ -1,19 +0,0 @@ - - */ -class User -{ - public $id; - public $email; - public $token; - -} \ No newline at end of file diff --git a/main/inc/lib/system/text/converter.class.php b/main/inc/lib/system/text/converter.class.php deleted file mode 100755 index 3579d3f700..0000000000 --- a/main/inc/lib/system/text/converter.class.php +++ /dev/null @@ -1,33 +0,0 @@ - - */ -class Converter -{ - - /** - * Identity converter. Returns the string with no transformations. - * - * @return Converter - */ - public static function identity() - { - static $result = null; - if(empty($result)) - { - $result = new self(); - } - return $result; - } - - - function convert($string) - { - return $string; - } -} \ No newline at end of file diff --git a/main/inc/lib/system/text/encoding.class.php b/main/inc/lib/system/text/encoding.class.php deleted file mode 100755 index f72c0eb6b5..0000000000 --- a/main/inc/lib/system/text/encoding.class.php +++ /dev/null @@ -1,158 +0,0 @@ -decoder(); - * $decoder->convert('text'); - * - * The system encoding is the platform/system/default encoding. This defaults to - * UTF8 but can be changed: - * - * Encoding::system('name'); - * - * Note that Encoding returns to its name when converted to a string. As such it - * can be used in places where a string is expected: - * - * $utf8 = Encoding::Utf8(); - * echo $utf8; - * - * @copyright (c) 2012 University of Geneva - * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html - * @author Laurent Opprecht - */ -class Encoding -{ - - private static $system = null; - - /** - * Returns encoding for $name. - * - * @param string $name - * @return Encoding - */ - public static function get($name) - { - if (is_object($name)) { - return $name; - } else if (Encoding::utf8()->is($name)) { - return self::utf8(); - } else { - return new self($name); - } - } - - /** - * Returns the Utf8 encoding. - * - * @return Utf8 - */ - public static function utf8() - { - return Utf8::instance(); - } - - /** - * Returns/set the system/default encoding. - * - * @return Encoding - */ - public static function system($value = null) - { - if (is_object($value)) { - self::$system = $value; - } else if (is_string($value)) { - self::$system = self::get($value); - } - - return self::$system ? self::$system : self::utf8(); - } - - /** - * Detect encoding from an abstract. - * - * @param string $abstract - * @return Encoding - */ - public static function detect_encoding($abstract) - { - $encoding_name = api_detect_encoding($abstract); - return self::get($encoding_name); - } - - protected $name = ''; - - protected function __construct($name = '') - { - $this->name = $name; - } - - /** - * The name of the encoding - * - * @return string - */ - function name() - { - return $this->name; - } - - /** - * The Byte Order Mark. - * - * @see http://en.wikipedia.org/wiki/Byte_order_mark - * @return string - */ - function bom() - { - return ''; - } - - /** - * Returns a decoder that convert encoding to another encoding. - * - * @param string|Encoder $to Encoding to convert to, defaults to system encoding - * @return Converter - */ - public function decoder($to = null) - { - $from = $this; - $to = $to ? $to : Encoding::system(); - return EncodingConverter::create($from, $to); - } - - /** - * Returns an encoder that convert from another encoding to this encoding. - * - * @param string|Encoder $from Encoding to convert from, defaults to system encoding. - * @return Converter - */ - public function encoder($from = null) - { - $from = $from ? $from : Encoding::system(); - $to = $this; - return EncodingConverter::create($from, $to); - } - - function __toString() - { - return $this->name(); - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/text/encoding_converter.class.php b/main/inc/lib/system/text/encoding_converter.class.php deleted file mode 100755 index 460a056e8e..0000000000 --- a/main/inc/lib/system/text/encoding_converter.class.php +++ /dev/null @@ -1,71 +0,0 @@ -convert($text); - * - * Note that the create function will returns an identify converter if from and to - * encodings are the same. Reason why the constructor is private. - * - * @copyright (c) 2012 University of Geneva - * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html - * @author Laurent Opprecht - */ -class EncodingConverter extends Converter -{ - - /** - * - * @param string $from_encoding - * @param string $to_encoding - * - * @return EncodingConverter - */ - public static function create($from_encoding, $to_encoding) - { - $from_encoding = (string) $from_encoding; - $to_encoding = (string) $to_encoding; - if (strtolower($from_encoding) == strtolower($to_encoding)) { - return Converter::identity(); - } else { - return new self($from_encoding, $to_encoding); - } - } - - protected $from_encoding; - protected $to_encoding; - - protected function __construct($from_encoding, $to_encoding) - { - $this->from_encoding = $from_encoding; - $this->to_encoding = $to_encoding; - } - - function from_encoding() - { - return $this->from_encoding; - } - - function to_encoding() - { - return $this->to_encoding; - } - - function convert($string) - { - $from = $this->from_encoding; - $to = $this->to_encoding; - if ($from == $to) { - return $string; - } - return api_convert_encoding($string, $to, $from); - } - - function reset() - { - ; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/text/utf8.class.php b/main/inc/lib/system/text/utf8.class.php deleted file mode 100755 index 8a7c1ee950..0000000000 --- a/main/inc/lib/system/text/utf8.class.php +++ /dev/null @@ -1,287 +0,0 @@ - for the Univesity of Geneva - * @author More authors, mentioned in the correpsonding fragments of this source. - */ -class Utf8 extends Encoding -{ - - const PATTERN_NOT_VISIBLE_CHARS = '/[^[:print:]-]/'; //Visible characters and the space character - - /** - * @see http://en.wikipedia.org/wiki/Byte_order_mark - */ - const BOM = "\xEF\xBB\xBF"; - const NAME = 'UTF-8'; - - /** - * - * @return Utf8 - */ - public static function instance() - { - static $result = null; - if (empty($result)) { - $result = new self(); - } - return $result; - } - - /** - * Returns true if encoding is UTF8. - * - * @param string|Encoding $encoding - * @return bool - */ - function is($encoding) - { - $encoding = (string) $encoding; - return strtolower($encoding) == strtolower(self::NAME); - } - - protected function __construct() - { - parent::__construct(self::NAME); - } - - function name() - { - return self::NAME; - } - - function bom() - { - return self::BOM; - } - - /** - * Returns the hexa decimal representation of an utf8 string. Usefull to understand - * what is going on - not printable chars, rare patterns such as e' for é, etc. - * - * @param type $text - * @return string - */ - function to_hex($text) - { - $result = ''; - mb_internal_encoding('utf-8'); - - for ($i = 0, $n = mb_strlen($text); $i < $n; $i++) { - $char = mb_substr($text, $i, 1); - $num = strlen($char); - for ($j = 0; $j < $num; $j++) { - $result .= sprintf('%02x', ord($char[$j])); - } - $result .= ' '; - } - return $result; - } - - /** - * Trim the BOM from an utf-8 string - * - * @param string $text - * @return string - */ - function trim($text) - { - $bom = self::BOM; - if (strlen($text) < strlen($bom)) { - return $text; - } - - if (substr($text, 0, 3) == $bom) { - return substr($text, 3); - } - return $text; - } - - /** - * Checks a string for UTF-8 validity. - * - * @param string $string The string to be tested. - * @return bool Returns TRUE when the tested string is valid UTF-8, FALSE othewise. - * @link http://en.wikipedia.org/wiki/UTF-8 - * @author see internationalization.lib.php - */ - static function is_valid(&$string) - { - - //return @mb_detect_encoding($string, 'UTF-8', true) == 'UTF-8' ? true : false; - // Ivan Tcholakov, 05-OCT-2008: I do not trust mb_detect_encoding(). I have - // found a string with a single cyrillic letter (single byte), that is - // wrongly detected as UTF-8. Possibly, there would be problems with other - // languages too. An alternative implementation will be used. - - $str = (string) $string; - $len = api_byte_count($str); - $i = 0; - while ($i < $len) { - $byte1 = ord($str[$i++]); // Here the current character begins. Its size is - // determined by the senior bits in the first byte. - - if (($byte1 & 0x80) == 0x00) { // 0xxxxxxx - // & - // 10000000 - // -------- - // 00000000 - // This is s valid character and it contains a single byte. - } elseif (($byte1 & 0xE0) == 0xC0) { // 110xxxxx 10xxxxxx - // & & - // 11100000 11000000 - // -------- -------- - // 11000000 10000000 - // The character contains two bytes. - if ($i == $len) { - return false; // Here the string ends unexpectedly. - } - - if (!((ord($str[$i++]) & 0xC0) == 0x80)) - return false; // Invalid second byte, invalid string. - } - - elseif (($byte1 & 0xF0) == 0xE0) { // 1110xxxx 10xxxxxx 10xxxxxx - // & & & - // 11110000 11000000 11000000 - // -------- -------- -------- - // 11100000 10000000 10000000 - // This is a character of three bytes. - if ($i == $len) { - return false; // Unexpected end of the string. - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; // Invalid second byte. - } - if ($i == $len) { - return false; // Unexpected end of the string. - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; // Invalid third byte, invalid string. - } - } elseif (($byte1 & 0xF8) == 0xF0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - // & & & & - // 11111000 11000000 11000000 11000000 - // -------- -------- -------- -------- - // 11110000 10000000 10000000 10000000 - // This is a character of four bytes. - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - } elseif (($byte1 & 0xFC) == 0xF8) { // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - // & & & & & - // 11111100 11000000 11000000 11000000 11000000 - // -------- -------- -------- -------- -------- - // 11111000 10000000 10000000 10000000 10000000 - // This is a character of five bytes. - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - } elseif (($byte1 & 0xFE) == 0xFC) { // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - // & & & & & & - // 11111110 11000000 11000000 11000000 11000000 11000000 - // -------- -------- -------- -------- -------- -------- - // 11111100 10000000 10000000 10000000 10000000 10000000 - // This is a character of six bytes. - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - if ($i == $len) { - return false; - } - if (!((ord($str[$i++]) & 0xC0) == 0x80)) { - return false; - } - } else { - return false; // In any other case the character is invalid. - } - // Here the current character is valid, it - // matches to some of the cases above. - // The next character is to be examinated. - } - return true; // Empty strings are valid too. - } - - /** - * - * @param type $to - * @return Utf8Decoder - */ - public function decoder($to = null) - { - $to = $to ? $to : Encoding::system(); - return new Utf8Decoder($to); - } - - /** - * - * @param type $from - * @return Utf8Encoder - */ - public function encoder($from = null) - { - $from = $from ? $from : Encoding::system(); - return new Utf8Encoder($from); - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/text/utf8_decoder.class.php b/main/inc/lib/system/text/utf8_decoder.class.php deleted file mode 100755 index 04d5cd7857..0000000000 --- a/main/inc/lib/system/text/utf8_decoder.class.php +++ /dev/null @@ -1,54 +0,0 @@ - - */ -class Utf8Decoder extends Converter -{ - - protected $started = false; - protected $to_encoding; - protected $encoding_converter; - - function __construct($to_encoding = null) - { - $this->to_encoding = $to_encoding ? $to_encoding : Encoding::system(); - $this->encoding_converter = EncodingConverter::create(Utf8::NAME, $this->to_encoding); - $this->reset(); - } - - function from_encoding() - { - return Utf8::NAME; - } - - function to_encoding() - { - return $this->to_encoding; - } - - function reset() - { - $this->started = false; - } - - function convert($string) - { - if (!$this->started) { - $this->started = true; - $string = Utf8::instance()->trim($string); - return $this->encoding_converter->convert($string); - } else { - return $this->encoding_converter->convert($string); - } - return $string; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/text/utf8_encoder.class.php b/main/inc/lib/system/text/utf8_encoder.class.php deleted file mode 100755 index aabe921cf6..0000000000 --- a/main/inc/lib/system/text/utf8_encoder.class.php +++ /dev/null @@ -1,72 +0,0 @@ - - */ -class Utf8Encoder extends Converter -{ - - protected $started = false; - protected $from_encoding; - protected $encoding_converter; - protected $convert_html_entities = false; - - function __construct($from_encoding = null , $convert_html_entities = false) - { - $this->from_encoding = $from_encoding ? $from_encoding : Encoding::system(); - $this->encoding_converter = EncodingConverter::create($this->from_encoding, Utf8::NAME); - $this->convert_html_entities = $convert_html_entities; - $this->reset(); - } - - function from_encoding() - { - return $this->from_encoding; - } - - function to_encoding() - { - return Utf8::NAME; - } - - function get_convert_html_entities() - { - return $this->convert_html_entities; - } - - function reset() - { - $this->started = false; - } - - function convert($string) - { - if ($this->convert_html_entities) { - $string = html_entity_decode($string, ENT_COMPAT, Utf8::NAME); - } - $string = $this->encoding_converter->convert($string); - if (!$this->started) { - $this->started = true; - $string = Utf8::BOM . $string; - } - return $string; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/web/request_server.class.php b/main/inc/lib/system/web/request_server.class.php deleted file mode 100755 index cd6741ed61..0000000000 --- a/main/inc/lib/system/web/request_server.class.php +++ /dev/null @@ -1,302 +0,0 @@ - request_uri() - * - * - * @license see /license.txt - * @author Laurent Opprecht for the Univesity of Geneva - */ -class RequestServer -{ - - public static function instance() - { - static $result = null; - if (empty($result)) { - $result = new self(); - } - return $result; - } - - function get($key, $default = null) - { - return isset($_SERVER[$key]) ? $_SERVER[$key] : null; - } - - /** - * The timestamp of the start of the request. Available since PHP 5.1.0. - * - * @return string - */ - function request_time() - { - return isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : null; - } - - /** - * Contents of the Host: header from the current request, if there is one. - * - * @return string - */ - function http_host() - { - return isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null; - } - - /** - * Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent. - * - * @return string - */ - function http_user_agent() - { - return isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null; - } - - /** - * Contents of the Accept: header from the current request, if there is one. - * - * @return string - */ - function http_accept() - { - return isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null; - } - - /** - * Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'. - * - * @return string - */ - function http_accept_language() - { - return isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null; - } - - /** - * Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'. - * - * @return string - */ - function http_accept_encoding() - { - return isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : null; - } - - /** - * Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'. - * - * @return string - */ - function http_connection() - { - return isset($_SERVER['HTTP_CONNECTION']) ? $_SERVER['HTTP_CONNECTION'] : null; - } - - function http_cookie() - { - return isset($_SERVER['HTTP_COOKIE']) ? $_SERVER['HTTP_COOKIE'] : null; - } - - function http_cache_control() - { - return isset($_SERVER['HTTP_CACHE_CONTROL']) ? $_SERVER['HTTP_CACHE_CONTROL'] : null; - } - - function path() - { - return isset($_SERVER['PATH']) ? $_SERVER['PATH'] : null; - } - - function systemroot() - { - return isset($_SERVER['SystemRoot']) ? $_SERVER['SystemRoot'] : null; - } - - function comspec() - { - return isset($_SERVER['COMSPEC']) ? $_SERVER['COMSPEC'] : null; - } - - function pathext() - { - return isset($_SERVER['PATHEXT']) ? $_SERVER['PATHEXT'] : null; - } - - function windir() - { - return isset($_SERVER['WINDIR']) ? $_SERVER['WINDIR'] : null; - } - - function server_signature() - { - return isset($_SERVER['SERVER_SIGNATURE']) ? $_SERVER['SERVER_SIGNATURE'] : null; - } - - /** - * Server identification string, given in the headers when responding to requests. - * - * @return string - */ - function server_software() - { - return isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : null; - } - - /** - * The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host. - * - * @return string - */ - function server_name() - { - return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null; - } - - /** - * The IP address of the server under which the current script is executing. - * - * @return string - */ - function server_addr() - { - return isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : null; - } - - function server_port() - { - return isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : null; - } - - /** - * The IP address from which the user is viewing the current page. - * - * @return string - */ - function remote_addr() - { - return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null; - } - - /** - * The document root directory under which the current script is executing, as defined in the server's configuration file. - * @return string - */ - function document_root() - { - return isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : null; - } - - /** - * The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host. - * - * @return string - */ - function server_admin() - { - return isset($_SERVER['SERVER_ADMIN']) ? $_SERVER['SERVER_ADMIN'] : null; - } - - /** - * The absolute pathname of the currently executing script. - * - * Note: - * - * If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user. - * - * @return string - */ - function script_filename() - { - return isset($_SERVER['SCRIPT_FILENAME']) ? $_SERVER['SCRIPT_FILENAME'] : null; - } - - /** - * The port being used on the user's machine to communicate with the web server. - * - * @return string - */ - function remote_port() - { - return isset($_SERVER['REMOTE_PORT']) ? $_SERVER['REMOTE_PORT'] : null; - } - - /** - * What revision of the CGI specification the server is using; i.e. 'CGI/1.1'. - * - * @return string - */ - function gateway_interface() - { - return isset($_SERVER['GATEWAY_INTERFACE']) ? $_SERVER['GATEWAY_INTERFACE'] : null; - } - - /** - * Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0'; - * - * @return string - */ - function server_protocol() - { - return isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : null; - } - - /** - * Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'. - * - * Note: - * PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD. - * - * @return string - */ - function request_method() - { - return isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null; - } - - /** - * The query string, if any, via which the page was accessed. - * - * @return string - */ - function query_string() - { - return isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : null; - } - - /** - * The URI which was given in order to access this page; for instance, '/index.html'. - * @return string - */ - function request_uri() - { - return isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null; - } - - /** - * Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. - * - * @return string - */ - function script_name() - { - return isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : null; - } - - /** - * The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available. - * - * @return string - */ - function php_self() - { - return isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : null; - } - -} \ No newline at end of file diff --git a/main/inc/lib/tools/entity_generator.class.php b/main/inc/lib/tools/entity_generator.class.php deleted file mode 100755 index ffe04b00b9..0000000000 --- a/main/inc/lib/tools/entity_generator.class.php +++ /dev/null @@ -1,1170 +0,0 @@ -getClassMetadataFactory()->getAllMetadata(); - * - * $generator = new \Doctrine\ORM\Tools\EntityGenerator(); - * $generator->setGenerateAnnotations(true); - * $generator->setGenerateStubMethods(true); - * $generator->setRegenerateEntityIfExists(false); - * $generator->setUpdateEntityIfExists(true); - * $generator->generate($classes, '/path/to/generate/entities'); - * - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org - * @since 2.0 - * @version $Revision$ - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - */ -class EntityGenerator -{ - - /** - * @var bool - */ - private $_backupExisting = true; - - /** The extension to use for written php files */ - private $_extension = '.php'; - - /** Whether or not the current ClassMetadataInfo instance is new or old */ - private $_isNew = true; - private $_staticReflection = array(); - - /** Number of spaces to use for indention in generated code */ - private $_numSpaces = 4; - - /** The actual spaces to use for indention */ - private $_spaces = ' '; - - /** The class all generated entities should extend */ - private $_classToExtend; - - /** Whether or not to generation annotations */ - private $_generateAnnotations = false; - - /** - * @var string - */ - private $_annotationsPrefix = ''; - - /** Whether or not to generated sub methods */ - private $_generateEntityStubMethods = false; - - /** Whether or not to update the entity class if it exists already */ - private $_updateEntityIfExists = false; - - /** Whether or not to re-generate entity class if it exists already */ - private $_regenerateEntityIfExists = false; - private static $_classTemplate = - ' -{ -/** - * @return \Entity\Repository\Repository - */ - public static function repository(){ -return \Entity\Repository\Repository::instance(); -} - -/** - * @return \Entity\ - */ - public static function create(){ -return new self(); -} - - -}'; - private static $_getMethodTemplate = - '/** - * - * - * @return - */ -public function () -{ -return $this->; -}'; - private static $_setMethodTemplate = - '/** - * - * - * @param $ - * @return - */ -public function ($) -{ -$this-> = $; -return $this; -}'; - private static $_addMethodTemplate = - '/** - * - * - * @param $ - * @return - */ -public function ($) -{ -$this->[] = $; -return $this; -}'; - private static $_lifecycleCallbackMethodTemplate = - '/** - * @ - */ -public function () -{ -// Add your code here -}'; - private static $_constructorMethodTemplate = - 'public function __construct() -{ - -} -'; - - public function __construct() - { - if (version_compare(\Doctrine\Common\Version::VERSION, '2.2.0-DEV', '>=')) { - $this->_annotationsPrefix = 'ORM\\'; - } - } - - /** - * Generate and write entity classes for the given array of ClassMetadataInfo instances - * - * @param array $metadatas - * @param string $outputDirectory - * @return void - */ - public function generate(array $metadatas, $outputDirectory) - { - foreach ($metadatas as $metadata) { - $this->writeEntityClass($metadata, $outputDirectory); - } - } - - /** - * Generated and write entity class to disk for the given ClassMetadataInfo instance - * - * @param ClassMetadataInfo $metadata - * @param string $outputDirectory - * @return void - */ - public function writeEntityClass(ClassMetadataInfo $metadata, $outputDirectory) - { - //change - $name = $metadata->name; - $name = explode('\\', $name); - $name = end($name); - $name = Inflector::tableize($name); - $is_course_table = (strpos($name, 'c_') === 0); - if ($is_course_table) { - $name = substr($name, 2, strlen($name) - 2); - } - $name = Inflector::tableize($name); - // - - $path = $outputDirectory . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $name) . $this->_extension; - $dir = dirname($path); - - if (!is_dir($dir)) { - mkdir($dir, 0777, true); - } - - $this->_isNew = !file_exists($path) || (file_exists($path) && $this->_regenerateEntityIfExists); - - if (!$this->_isNew) { - $this->_parseTokensInEntityFile(file_get_contents($path)); - } else { - $this->_staticReflection[$metadata->name] = array('properties' => array(), 'methods' => array()); - } - - if ($this->_backupExisting && file_exists($path)) { - $backupPath = dirname($path) . DIRECTORY_SEPARATOR . basename($path) . "~"; - if (!copy($path, $backupPath)) { - throw new \RuntimeException("Attempt to backup overwritten entity file but copy operation failed."); - } - } - - // If entity doesn't exist or we're re-generating the entities entirely - if ($this->_isNew) { - file_put_contents($path, $this->generateEntityClass($metadata)); - // If entity exists and we're allowed to update the entity class - } else if (!$this->_isNew && $this->_updateEntityIfExists) { - file_put_contents($path, $this->generateUpdatedEntityClass($metadata, $path)); - } - } - - /** - * Generate a PHP5 Doctrine 2 entity class from the given ClassMetadataInfo instance - * - * @param ClassMetadataInfo $metadata - * @return string $code - */ - public function generateEntityClass(ClassMetadataInfo $metadata) - { - $placeHolders = array( - '', - '', - '', - '' - ); - - $replacements = array( - $this->_generateEntityNamespace($metadata), - $this->_generateEntityDocBlock($metadata), - $this->_generateEntityClassName($metadata), - $this->_generateEntityBody($metadata) - ); - - - $code = str_replace($placeHolders, $replacements, self::$_classTemplate); - $result = str_replace('', $this->_spaces, $code); - $result = str_replace('', $this->_getClassName($metadata), $result); - return $result; - } - - /** - * Generate the updated code for the given ClassMetadataInfo and entity at path - * - * @param ClassMetadataInfo $metadata - * @param string $path - * @return string $code; - */ - public function generateUpdatedEntityClass(ClassMetadataInfo $metadata, $path) - { - $currentCode = file_get_contents($path); - - $body = $this->_generateEntityBody($metadata); - $body = str_replace('', $this->_spaces, $body); - $last = strrpos($currentCode, '}'); - - return substr($currentCode, 0, $last) . $body . (strlen($body) > 0 ? "\n" : '') . "}"; - } - - /** - * Set the number of spaces the exported class should have - * - * @param integer $numSpaces - * @return void - */ - public function setNumSpaces($numSpaces) - { - $this->_spaces = str_repeat(' ', $numSpaces); - $this->_numSpaces = $numSpaces; - } - - /** - * Set the extension to use when writing php files to disk - * - * @param string $extension - * @return void - */ - public function setExtension($extension) - { - $this->_extension = $extension; - } - - /** - * Set the name of the class the generated classes should extend from - * - * @return void - */ - public function setClassToExtend($classToExtend) - { - $this->_classToExtend = $classToExtend; - } - - /** - * Set whether or not to generate annotations for the entity - * - * @param bool $bool - * @return void - */ - public function setGenerateAnnotations($bool) - { - $this->_generateAnnotations = $bool; - } - - /** - * Set an annotation prefix. - * - * @param string $prefix - */ - public function setAnnotationPrefix($prefix) - { - $this->_annotationsPrefix = $prefix; - } - - /** - * Set whether or not to try and update the entity if it already exists - * - * @param bool $bool - * @return void - */ - public function setUpdateEntityIfExists($bool) - { - $this->_updateEntityIfExists = $bool; - } - - /** - * Set whether or not to regenerate the entity if it exists - * - * @param bool $bool - * @return void - */ - public function setRegenerateEntityIfExists($bool) - { - $this->_regenerateEntityIfExists = $bool; - } - - /** - * Set whether or not to generate stub methods for the entity - * - * @param bool $bool - * @return void - */ - public function setGenerateStubMethods($bool) - { - $this->_generateEntityStubMethods = $bool; - } - - /** - * Should an existing entity be backed up if it already exists? - */ - public function setBackupExisting($bool) - { - $this->_backupExisting = $bool; - } - - private function _generateEntityNamespace(ClassMetadataInfo $metadata) - { - if ($this->_hasNamespace($metadata)) { - return 'namespace ' . $this->_getNamespace($metadata) . ';'; - } - } - - private function _generateEntityClassName(ClassMetadataInfo $metadata) - { - return 'class ' . $this->_getClassName($metadata) . - ($this->_extendsClass() ? ' extends ' . $this->_getClassToExtendName($metadata) : null); - } - - private function _generateEntityBody(ClassMetadataInfo $metadata) - { - $fieldMappingProperties = $this->_generateEntityFieldMappingProperties($metadata); - $associationMappingProperties = $this->_generateEntityAssociationMappingProperties($metadata); - $stubMethods = $this->_generateEntityStubMethods ? $this->_generateEntityStubMethods($metadata) : null; - $lifecycleCallbackMethods = $this->_generateEntityLifecycleCallbackMethods($metadata); - - $code = array(); - - if ($fieldMappingProperties) { - $code[] = $fieldMappingProperties; - } - - if ($associationMappingProperties) { - $code[] = $associationMappingProperties; - } - - $code[] = $this->_generateEntityConstructor($metadata); - - if ($stubMethods) { - $code[] = $stubMethods; - } - - if ($lifecycleCallbackMethods) { - $code[] = $lifecycleCallbackMethods; - } - - return implode("\n", $code); - } - - private function _generateEntityConstructor(ClassMetadataInfo $metadata) - { - if ($this->_hasMethod('__construct', $metadata)) { - return ''; - } - - $collections = array(); - - foreach ($metadata->associationMappings AS $mapping) { - if ($mapping['type'] & ClassMetadataInfo::TO_MANY) { - $collections[] = '$this->' . $mapping['fieldName'] . ' = new \Doctrine\Common\Collections\ArrayCollection();'; - } - } - - if ($collections) { - return $this->_prefixCodeWithSpaces(str_replace("", implode("\n" . $this->_spaces, $collections), self::$_constructorMethodTemplate)); - } - - return ''; - } - - /** - * @todo this won't work if there is a namespace in brackets and a class outside of it. - * @param string $src - */ - private function _parseTokensInEntityFile($src) - { - $tokens = token_get_all($src); - $lastSeenNamespace = ""; - $lastSeenClass = false; - - $inNamespace = false; - $inClass = false; - for ($i = 0; $i < count($tokens); $i++) { - $token = $tokens[$i]; - if (in_array($token[0], array(T_WHITESPACE, T_COMMENT, T_DOC_COMMENT))) { - continue; - } - - if ($inNamespace) { - if ($token[0] == T_NS_SEPARATOR || $token[0] == T_STRING) { - $lastSeenNamespace .= $token[1]; - } else if (is_string($token) && in_array($token, array(';', '{'))) { - $inNamespace = false; - } - } - - if ($inClass) { - $inClass = false; - $lastSeenClass = $lastSeenNamespace . ($lastSeenNamespace ? '\\' : '') . $token[1]; - $this->_staticReflection[$lastSeenClass]['properties'] = array(); - $this->_staticReflection[$lastSeenClass]['methods'] = array(); - } - - if ($token[0] == T_NAMESPACE) { - $lastSeenNamespace = ""; - $inNamespace = true; - } else if ($token[0] == T_CLASS) { - $inClass = true; - } else if ($token[0] == T_FUNCTION) { - if ($tokens[$i + 2][0] == T_STRING) { - $this->_staticReflection[$lastSeenClass]['methods'][] = $tokens[$i + 2][1]; - } else if ($tokens[$i + 2] == "&" && $tokens[$i + 3][0] == T_STRING) { - $this->_staticReflection[$lastSeenClass]['methods'][] = $tokens[$i + 3][1]; - } - } else if (in_array($token[0], array(T_VAR, T_PUBLIC, T_PRIVATE, T_PROTECTED)) && $tokens[$i + 2][0] != T_FUNCTION) { - $this->_staticReflection[$lastSeenClass]['properties'][] = substr($tokens[$i + 2][1], 1); - } - } - } - - private function _hasProperty($property, ClassMetadataInfo $metadata) - { - if ($this->_extendsClass()) { - // don't generate property if its already on the base class. - $reflClass = new \ReflectionClass($this->_getClassToExtend($metadata)); - if ($reflClass->hasProperty($property)) { - return true; - } - } - - return ( - isset($this->_staticReflection[$metadata->name]) && - in_array($property, $this->_staticReflection[$metadata->name]['properties']) - ); - } - - private function _hasMethod($method, ClassMetadataInfo $metadata) - { - if ($this->_extendsClass()) { - // don't generate method if its already on the base class. - $reflClass = new \ReflectionClass($this->_getClassToExtend($metadata)); - if ($reflClass->hasMethod($method)) { - return true; - } - } - - return ( - isset($this->_staticReflection[$metadata->name]) && - in_array($method, $this->_staticReflection[$metadata->name]['methods']) - ); - } - - private function _hasNamespace(ClassMetadataInfo $metadata) - { - return strpos($metadata->name, '\\') ? true : false; - } - - private function _extendsClass() - { - return $this->_classToExtend ? true : false; - } - - private function _getClassToExtend($metadata) - { - return isset($metadata->class_to_extend) ? $metadata->class_to_extend : $this->_classToExtend; - } - - private function _getClassToExtendName($metadata) - { - $refl = new \ReflectionClass($this->_getClassToExtend($metadata)); - - return '\\' . $refl->getName(); - } - - private function _getClassName(ClassMetadataInfo $metadata) - { - //changed - $name = $metadata->name; - $name = explode('\\', $name); - $name = end($name); - $name = Inflector::tableize($name); - $is_course_table = (strpos($name, 'c_') === 0); - if ($is_course_table) { - $name = substr($name, 2, strlen($name) - 2); - } - $name = Inflector::classify($name); - - $result = ($pos = strrpos($name, '\\')) ? substr($name, $pos + 1, strlen($name)) : $name; - return $result; - } - - private function _getNamespace(ClassMetadataInfo $metadata) - { - return substr($metadata->name, 0, strrpos($metadata->name, '\\')); - } - - private function _generateEntityDocBlock(ClassMetadataInfo $metadata) - { - $lines = array(); - $lines[] = '/**'; - $lines[] = ' * ' . $metadata->name; - - if ($this->_generateAnnotations) { - $lines[] = ' *'; - - $methods = array( - '_generateTableAnnotation', - '_generateInheritanceAnnotation', - '_generateDiscriminatorColumnAnnotation', - '_generateDiscriminatorMapAnnotation' - ); - - foreach ($methods as $method) { - if ($code = $this->$method($metadata)) { - $lines[] = ' * ' . $code; - } - } - - if ($metadata->isMappedSuperclass) { - $lines[] = ' * @' . $this->_annotationsPrefix . 'MappedSuperClass'; - } else { - $lines[] = ' * @' . $this->_annotationsPrefix . 'Entity'; - } - - if ($metadata->customRepositoryClassName) { - $lines[count($lines) - 1] .= '(repositoryClass="' . $metadata->customRepositoryClassName . '")'; - } - - if (isset($metadata->lifecycleCallbacks) && $metadata->lifecycleCallbacks) { - $lines[] = ' * @' . $this->_annotationsPrefix . 'HasLifecycleCallbacks'; - } - } - - $lines[] = ' */'; - - return implode("\n", $lines); - } - - private function _generateTableAnnotation($metadata) - { - $table = array(); - - if (isset($metadata->table['schema'])) { - $table[] = 'schema="' . $metadata->table['schema'] . '"'; - } - - if (isset($metadata->table['name'])) { - $table[] = 'name="' . $metadata->table['name'] . '"'; - } - - if (isset($metadata->table['uniqueConstraints']) && $metadata->table['uniqueConstraints']) { - $constraints = $this->_generateTableConstraints('UniqueConstraint', $metadata->table['uniqueConstraints']); - $table[] = 'uniqueConstraints={' . $constraints . '}'; - } - - if (isset($metadata->table['indexes']) && $metadata->table['indexes']) { - $constraints = $this->_generateTableConstraints('Index', $metadata->table['indexes']); - $table[] = 'indexes={' . $constraints . '}'; - } - - return '@' . $this->_annotationsPrefix . 'Table(' . implode(', ', $table) . ')'; - } - - private function _generateTableConstraints($constraintName, $constraints) - { - $annotations = array(); - foreach ($constraints as $name => $constraint) { - $columns = array(); - foreach ($constraint['columns'] as $column) { - $columns[] = '"' . $column . '"'; - } - $annotations[] = '@' . $this->_annotationsPrefix . $constraintName . '(name="' . $name . '", columns={' . implode(', ', $columns) . '})'; - } - return implode(', ', $annotations); - } - - private function _generateInheritanceAnnotation($metadata) - { - if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) { - return '@' . $this->_annotationsPrefix . 'InheritanceType("' . $this->_getInheritanceTypeString($metadata->inheritanceType) . '")'; - } - } - - private function _generateDiscriminatorColumnAnnotation($metadata) - { - if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) { - $discrColumn = $metadata->discriminatorValue; - $columnDefinition = 'name="' . $discrColumn['name'] - . '", type="' . $discrColumn['type'] - . '", length=' . $discrColumn['length']; - - return '@' . $this->_annotationsPrefix . 'DiscriminatorColumn(' . $columnDefinition . ')'; - } - } - - private function _generateDiscriminatorMapAnnotation($metadata) - { - if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) { - $inheritanceClassMap = array(); - - foreach ($metadata->discriminatorMap as $type => $class) { - $inheritanceClassMap[] .= '"' . $type . '" = "' . $class . '"'; - } - - return '@' . $this->_annotationsPrefix . 'DiscriminatorMap({' . implode(', ', $inheritanceClassMap) . '})'; - } - } - - private function _generateEntityStubMethods(ClassMetadataInfo $metadata) - { - $methods = array(); - - foreach ($metadata->fieldMappings as $fieldMapping) { - if (!isset($fieldMapping['id']) || !$fieldMapping['id'] || $metadata->generatorType == ClassMetadataInfo::GENERATOR_TYPE_NONE) { - if ($code = $this->_generateEntityStubMethod($metadata, 'set', $fieldMapping['fieldName'], $fieldMapping['type'])) { - $methods[] = $code; - } - } - - if ($code = $this->_generateEntityStubMethod($metadata, 'get', $fieldMapping['fieldName'], $fieldMapping['type'])) { - $methods[] = $code; - } - } - - foreach ($metadata->associationMappings as $associationMapping) { - if ($associationMapping['type'] & ClassMetadataInfo::TO_ONE) { - $nullable = $this->_isAssociationIsNullable($associationMapping) ? 'null' : null; - if ($code = $this->_generateEntityStubMethod($metadata, 'set', $associationMapping['fieldName'], $associationMapping['targetEntity'], $nullable)) { - $methods[] = $code; - } - if ($code = $this->_generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], $associationMapping['targetEntity'])) { - $methods[] = $code; - } - } else if ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) { - if ($code = $this->_generateEntityStubMethod($metadata, 'add', $associationMapping['fieldName'], $associationMapping['targetEntity'])) { - $methods[] = $code; - } - if ($code = $this->_generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], 'Doctrine\Common\Collections\Collection')) { - $methods[] = $code; - } - } - } - - return implode("\n\n", $methods); - } - - private function _isAssociationIsNullable($associationMapping) - { - if (isset($associationMapping['id']) && $associationMapping['id']) { - return false; - } - if (isset($associationMapping['joinColumns'])) { - $joinColumns = $associationMapping['joinColumns']; - } else { - //@todo thereis no way to retreive targetEntity metadata - $joinColumns = array(); - } - foreach ($joinColumns as $joinColumn) { - if (isset($joinColumn['nullable']) && !$joinColumn['nullable']) { - return false; - } - } - return true; - } - - private function _generateEntityLifecycleCallbackMethods(ClassMetadataInfo $metadata) - { - if (isset($metadata->lifecycleCallbacks) && $metadata->lifecycleCallbacks) { - $methods = array(); - - foreach ($metadata->lifecycleCallbacks as $name => $callbacks) { - foreach ($callbacks as $callback) { - if ($code = $this->_generateLifecycleCallbackMethod($name, $callback, $metadata)) { - $methods[] = $code; - } - } - } - - return implode("\n\n", $methods); - } - - return ""; - } - - private function _generateEntityAssociationMappingProperties(ClassMetadataInfo $metadata) - { - $lines = array(); - - foreach ($metadata->associationMappings as $associationMapping) { - if ($this->_hasProperty($associationMapping['fieldName'], $metadata)) { - continue; - } - - $lines[] = $this->_generateAssociationMappingPropertyDocBlock($associationMapping, $metadata); - $lines[] = $this->_spaces . 'protected $' . $associationMapping['fieldName'] - . ($associationMapping['type'] == 'manyToMany' ? ' = array()' : null) . ";\n"; - } - - return implode("\n", $lines); - } - - private function _generateEntityFieldMappingProperties(ClassMetadataInfo $metadata) - { - $lines = array(); - - foreach ($metadata->fieldMappings as $fieldMapping) { - if ($this->_hasProperty($fieldMapping['fieldName'], $metadata) || - $metadata->isInheritedField($fieldMapping['fieldName'])) { - continue; - } - - $fieldMapping['fieldName'] = Inflector::tableize($fieldMapping['fieldName']); - - $lines[] = $this->_generateFieldMappingPropertyDocBlock($fieldMapping, $metadata); - $lines[] = $this->_spaces . 'protected $' . $fieldMapping['fieldName'] - . (isset($fieldMapping['default']) ? ' = ' . var_export($fieldMapping['default'], true) : null) . ";\n"; - } - - return implode("\n", $lines); - } - - private function _generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null) - { - - $fieldName = Inflector::tableize($fieldName); - if ($type == "add") { - $addMethod = explode("\\", $typeHint); - $addMethod = end($addMethod); - $methodName = $type . $addMethod; - } else { - //change - $methodName = $type . '_' . Inflector::tableize($fieldName); - // - } - - if ($this->_hasMethod($methodName, $metadata)) { - return; - } - $this->_staticReflection[$metadata->name]['methods'][] = $methodName; - - $var = sprintf('_%sMethodTemplate', $type); - $template = self::$$var; - - $variableType = $typeHint ? $typeHint . ' ' : null; - - $types = \Doctrine\DBAL\Types\Type::getTypesMap(); - $methodTypeHint = $typeHint && !isset($types[$typeHint]) ? '\\' . $typeHint . ' ' : null; - - $replacements = array( - '' => ucfirst($type) . ' ' . $fieldName, - '' => $methodTypeHint, - '' => $variableType, - '' => 'value', - '' => $methodName, - '' => $fieldName, - '' => ($defaultValue !== null ) ? (' = ' . $defaultValue) : '', - '' => $this->_getClassName($metadata) - ); - - $method = str_replace( - array_keys($replacements), array_values($replacements), $template - ); - - return $this->_prefixCodeWithSpaces($method); - } - - private function _generateLifecycleCallbackMethod($name, $methodName, $metadata) - { - if ($this->_hasMethod($methodName, $metadata)) { - return; - } - $this->_staticReflection[$metadata->name]['methods'][] = $methodName; - - $replacements = array( - '' => $this->_annotationsPrefix . $name, - '' => $methodName, - ); - - $method = str_replace( - array_keys($replacements), array_values($replacements), self::$_lifecycleCallbackMethodTemplate - ); - - return $this->_prefixCodeWithSpaces($method); - } - - private function _generateJoinColumnAnnotation(array $joinColumn) - { - $joinColumnAnnot = array(); - - if (isset($joinColumn['name'])) { - $joinColumnAnnot[] = 'name="' . $joinColumn['name'] . '"'; - } - - if (isset($joinColumn['referencedColumnName'])) { - $joinColumnAnnot[] = 'referencedColumnName="' . $joinColumn['referencedColumnName'] . '"'; - } - - if (isset($joinColumn['unique']) && $joinColumn['unique']) { - $joinColumnAnnot[] = 'unique=' . ($joinColumn['unique'] ? 'true' : 'false'); - } - - if (isset($joinColumn['nullable'])) { - $joinColumnAnnot[] = 'nullable=' . ($joinColumn['nullable'] ? 'true' : 'false'); - } - - if (isset($joinColumn['onDelete'])) { - $joinColumnAnnot[] = 'onDelete="' . ($joinColumn['onDelete'] . '"'); - } - - if (isset($joinColumn['columnDefinition'])) { - $joinColumnAnnot[] = 'columnDefinition="' . $joinColumn['columnDefinition'] . '"'; - } - - return '@' . $this->_annotationsPrefix . 'JoinColumn(' . implode(', ', $joinColumnAnnot) . ')'; - } - - private function _generateAssociationMappingPropertyDocBlock(array $associationMapping, ClassMetadataInfo $metadata) - { - $lines = array(); - $lines[] = $this->_spaces . '/**'; - - if ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) { - $lines[] = $this->_spaces . ' * @var \Doctrine\Common\Collections\ArrayCollection'; - } else { - $lines[] = $this->_spaces . ' * @var ' . $associationMapping['targetEntity']; - } - - if ($this->_generateAnnotations) { - $lines[] = $this->_spaces . ' *'; - - if (isset($associationMapping['id']) && $associationMapping['id']) { - $lines[] = $this->_spaces . ' * @' . $this->_annotationsPrefix . 'Id'; - - if ($generatorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { - $lines[] = $this->_spaces . ' * @' . $this->_annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")'; - } - } - - $type = null; - switch ($associationMapping['type']) { - case ClassMetadataInfo::ONE_TO_ONE: - $type = 'OneToOne'; - break; - case ClassMetadataInfo::MANY_TO_ONE: - $type = 'ManyToOne'; - break; - case ClassMetadataInfo::ONE_TO_MANY: - $type = 'OneToMany'; - break; - case ClassMetadataInfo::MANY_TO_MANY: - $type = 'ManyToMany'; - break; - } - $typeOptions = array(); - - if (isset($associationMapping['targetEntity'])) { - $typeOptions[] = 'targetEntity="' . $associationMapping['targetEntity'] . '"'; - } - - if (isset($associationMapping['inversedBy'])) { - $typeOptions[] = 'inversedBy="' . $associationMapping['inversedBy'] . '"'; - } - - if (isset($associationMapping['mappedBy'])) { - $typeOptions[] = 'mappedBy="' . $associationMapping['mappedBy'] . '"'; - } - - if ($associationMapping['cascade']) { - $cascades = array(); - - if ($associationMapping['isCascadePersist']) - $cascades[] = '"persist"'; - if ($associationMapping['isCascadeRemove']) - $cascades[] = '"remove"'; - if ($associationMapping['isCascadeDetach']) - $cascades[] = '"detach"'; - if ($associationMapping['isCascadeMerge']) - $cascades[] = '"merge"'; - if ($associationMapping['isCascadeRefresh']) - $cascades[] = '"refresh"'; - - $typeOptions[] = 'cascade={' . implode(',', $cascades) . '}'; - } - - if (isset($associationMapping['orphanRemoval']) && $associationMapping['orphanRemoval']) { - $typeOptions[] = 'orphanRemoval=' . ($associationMapping['orphanRemoval'] ? 'true' : 'false'); - } - - $lines[] = $this->_spaces . ' * @' . $this->_annotationsPrefix . '' . $type . '(' . implode(', ', $typeOptions) . ')'; - - if (isset($associationMapping['joinColumns']) && $associationMapping['joinColumns']) { - $lines[] = $this->_spaces . ' * @' . $this->_annotationsPrefix . 'JoinColumns({'; - - $joinColumnsLines = array(); - - foreach ($associationMapping['joinColumns'] as $joinColumn) { - if ($joinColumnAnnot = $this->_generateJoinColumnAnnotation($joinColumn)) { - $joinColumnsLines[] = $this->_spaces . ' * ' . $joinColumnAnnot; - } - } - - $lines[] = implode(",\n", $joinColumnsLines); - $lines[] = $this->_spaces . ' * })'; - } - - if (isset($associationMapping['joinTable']) && $associationMapping['joinTable']) { - $joinTable = array(); - $joinTable[] = 'name="' . $associationMapping['joinTable']['name'] . '"'; - - if (isset($associationMapping['joinTable']['schema'])) { - $joinTable[] = 'schema="' . $associationMapping['joinTable']['schema'] . '"'; - } - - $lines[] = $this->_spaces . ' * @' . $this->_annotationsPrefix . 'JoinTable(' . implode(', ', $joinTable) . ','; - $lines[] = $this->_spaces . ' * joinColumns={'; - - foreach ($associationMapping['joinTable']['joinColumns'] as $joinColumn) { - $lines[] = $this->_spaces . ' * ' . $this->_generateJoinColumnAnnotation($joinColumn); - } - - $lines[] = $this->_spaces . ' * },'; - $lines[] = $this->_spaces . ' * inverseJoinColumns={'; - - foreach ($associationMapping['joinTable']['inverseJoinColumns'] as $joinColumn) { - $lines[] = $this->_spaces . ' * ' . $this->_generateJoinColumnAnnotation($joinColumn); - } - - $lines[] = $this->_spaces . ' * }'; - $lines[] = $this->_spaces . ' * )'; - } - - if (isset($associationMapping['orderBy'])) { - $lines[] = $this->_spaces . ' * @' . $this->_annotationsPrefix . 'OrderBy({'; - - foreach ($associationMapping['orderBy'] as $name => $direction) { - $lines[] = $this->_spaces . ' * "' . $name . '"="' . $direction . '",'; - } - - $lines[count($lines) - 1] = substr($lines[count($lines) - 1], 0, strlen($lines[count($lines) - 1]) - 1); - $lines[] = $this->_spaces . ' * })'; - } - } - - $lines[] = $this->_spaces . ' */'; - - return implode("\n", $lines); - } - - private function _generateFieldMappingPropertyDocBlock(array $fieldMapping, ClassMetadataInfo $metadata) - { - - $lines = array(); - $lines[] = $this->_spaces . '/**'; - $lines[] = $this->_spaces . ' * @var ' . $fieldMapping['type'] . ' $' . $fieldMapping['fieldName']; - - if ($this->_generateAnnotations) { - $lines[] = $this->_spaces . ' *'; - - $column = array(); - if (isset($fieldMapping['columnName'])) { - $column[] = 'name="' . $fieldMapping['columnName'] . '"'; - } - - if (isset($fieldMapping['type'])) { - $column[] = 'type="' . $fieldMapping['type'] . '"'; - } - - if (isset($fieldMapping['length'])) { - $column[] = 'length=' . $fieldMapping['length']; - } - - if (isset($fieldMapping['precision'])) { - $column[] = 'precision=' . $fieldMapping['precision']; - } - - if (isset($fieldMapping['scale'])) { - $column[] = 'scale=' . $fieldMapping['scale']; - } - - if (isset($fieldMapping['nullable'])) { - $column[] = 'nullable=' . var_export($fieldMapping['nullable'], true); - } - - if (isset($fieldMapping['columnDefinition'])) { - $column[] = 'columnDefinition="' . $fieldMapping['columnDefinition'] . '"'; - } - - if (isset($fieldMapping['unique'])) { - $column[] = 'unique=' . var_export($fieldMapping['unique'], true); - } - - $lines[] = $this->_spaces . ' * @' . $this->_annotationsPrefix . 'Column(' . implode(', ', $column) . ')'; - - if (isset($fieldMapping['id']) && $fieldMapping['id']) { - $lines[] = $this->_spaces . ' * @' . $this->_annotationsPrefix . 'Id'; - - if ($generatorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { - $lines[] = $this->_spaces . ' * @' . $this->_annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")'; - } - - if ($metadata->sequenceGeneratorDefinition) { - $sequenceGenerator = array(); - - if (isset($metadata->sequenceGeneratorDefinition['sequenceName'])) { - $sequenceGenerator[] = 'sequenceName="' . $metadata->sequenceGeneratorDefinition['sequenceName'] . '"'; - } - - if (isset($metadata->sequenceGeneratorDefinition['allocationSize'])) { - $sequenceGenerator[] = 'allocationSize="' . $metadata->sequenceGeneratorDefinition['allocationSize'] . '"'; - } - - if (isset($metadata->sequenceGeneratorDefinition['initialValue'])) { - $sequenceGenerator[] = 'initialValue="' . $metadata->sequenceGeneratorDefinition['initialValue'] . '"'; - } - - $lines[] = $this->_spaces . ' * @' . $this->_annotationsPrefix . 'SequenceGenerator(' . implode(', ', $sequenceGenerator) . ')'; - } - } - - if (isset($fieldMapping['version']) && $fieldMapping['version']) { - $lines[] = $this->_spaces . ' * @' . $this->_annotationsPrefix . 'Version'; - } - } - - $lines[] = $this->_spaces . ' */'; - - return implode("\n", $lines); - } - - private function _prefixCodeWithSpaces($code, $num = 1) - { - $lines = explode("\n", $code); - - foreach ($lines as $key => $value) { - $lines[$key] = str_repeat($this->_spaces, $num) . $lines[$key]; - } - - return implode("\n", $lines); - } - - private function _getInheritanceTypeString($type) - { - switch ($type) { - case ClassMetadataInfo::INHERITANCE_TYPE_NONE: - return 'NONE'; - - case ClassMetadataInfo::INHERITANCE_TYPE_JOINED: - return 'JOINED'; - - case ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_TABLE: - return 'SINGLE_TABLE'; - - case ClassMetadataInfo::INHERITANCE_TYPE_TABLE_PER_CLASS: - return 'PER_CLASS'; - - default: - throw new \InvalidArgumentException('Invalid provided InheritanceType: ' . $type); - } - } - - private function _getChangeTrackingPolicyString($policy) - { - switch ($policy) { - case ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT: - return 'DEFERRED_IMPLICIT'; - - case ClassMetadataInfo::CHANGETRACKING_DEFERRED_EXPLICIT: - return 'DEFERRED_EXPLICIT'; - - case ClassMetadataInfo::CHANGETRACKING_NOTIFY: - return 'NOTIFY'; - - default: - throw new \InvalidArgumentException('Invalid provided ChangeTrackingPolicy: ' . $policy); - } - } - - private function _getIdGeneratorTypeString($type) - { - switch ($type) { - case ClassMetadataInfo::GENERATOR_TYPE_AUTO: - return 'AUTO'; - - case ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE: - return 'SEQUENCE'; - - case ClassMetadataInfo::GENERATOR_TYPE_TABLE: - return 'TABLE'; - - case ClassMetadataInfo::GENERATOR_TYPE_IDENTITY: - return 'IDENTITY'; - - case ClassMetadataInfo::GENERATOR_TYPE_NONE: - return 'NONE'; - - default: - throw new \InvalidArgumentException('Invalid provided IdGeneratorType: ' . $type); - } - } - -} diff --git a/main/inc/lib/tools/entity_repository_generator.class.php b/main/inc/lib/tools/entity_repository_generator.class.php deleted file mode 100755 index f5a4a70468..0000000000 --- a/main/inc/lib/tools/entity_repository_generator.class.php +++ /dev/null @@ -1,138 +0,0 @@ -. - */ - -namespace Tools; - -use Doctrine\ORM\Mapping\ClassMetadataInfo, - Doctrine\ORM\Mapping\AssociationMapping, - Doctrine\Common\Util\Inflector; - -/** - * Class to generate entity repository classes - * - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org - * @since 2.0 - * @version $Revision$ - * @author Benjamin Eberlei - * @author Guilherme Blanco - * @author Jonathan Wage - * @author Roman Borschel - */ -class EntityRepositoryGenerator -{ - - protected static $_template = - ' extends -{ - - /** - * @return \Entity\Repository\ - */ - public static function instance(){ - static $result = false; - if($result === false){ - $result = db::instance()->get_repository(\'\\Entity\\\'); - } - return $result; - } - - /** - * - * @param EntityManager $em The EntityManager to use. - * @param ClassMetadata $class The class descriptor. - */ - public function __construct($em, $class){ - parent::__construct($em, $class); - } - -}'; - - public function generateEntityRepositoryClass($name) - { - $name = Inflector::tableize($name); - $is_course_table = (strpos($name, 'c_') === 0); - if ($is_course_table) { - $name = substr($name, 2, strlen($name) - 2); - } - $name = Inflector::classify($name); - $className = $name; - //$namespace = substr($fullClassName, 0, strrpos($fullClassName, '\\')); - //$className = substr($fullClassName, strrpos($fullClassName, '\\') + 1, strlen($fullClassName)); - - $is_course_table = $metadata->is_course_table; - - - $variables = array( - '' => $namespace, - '' => $className, - '' => str_replace('Repository', '', $className), - '' => $is_course_table ? '\CourseEntityRepository' : '\EntityRepository' - ); - return str_replace(array_keys($variables), array_values($variables), self::$_template); - } - - /** - * - * @param type $name - * @param type $outputDirectory - */ - public function writeEntityRepositoryClass($name, $outputDirectory) - { - $name = explode('\\', $name); - $name = end($name); - $name = Inflector::tableize($name); - $is_course_table = (strpos($name, 'c_') === 0); - if ($is_course_table) { - $name = substr($name, 2, strlen($name) - 2); - } - $name = Inflector::classify($name) . 'Repository'; - $fullClassName = $name; - - $file_name = Inflector::tableize($name); - - $code = $this->generateEntityRepositoryClass($fullClassName); - - $path = $outputDirectory . DIRECTORY_SEPARATOR - . str_replace('\\', \DIRECTORY_SEPARATOR, $file_name) . '.class.php'; - $dir = dirname($path); - - if (!is_dir($dir)) { - mkdir($dir, 0777, true); - } - - if (!file_exists($path)) { - file_put_contents($path, $code); - } - } - -} \ No newline at end of file diff --git a/main/inc/lib/tools/yaml_exporter.class.php b/main/inc/lib/tools/yaml_exporter.class.php deleted file mode 100755 index e56a856b5e..0000000000 --- a/main/inc/lib/tools/yaml_exporter.class.php +++ /dev/null @@ -1,214 +0,0 @@ -. - */ - -namespace Tools; - -use Doctrine\ORM\Mapping\ClassMetadataInfo; -use Doctrine\ORM\Tools\Export\Driver\AbstractExporter; - -/** - * ClassMetadata exporter for Doctrine YAML mapping files - * - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org - * @since 2.0 - * @version $Revision$ - * @author Jonathan Wage - */ -class YamlExporter extends AbstractExporter -{ - protected $_extension = '.dcm.yml'; - - /** - * Converts a single ClassMetadata instance to the exported format - * and returns it - * - * TODO: Should this code be pulled out in to a toArray() method in ClassMetadata - * - * @param ClassMetadataInfo $metadata - * @return mixed $exported - */ - public function exportClassMetadata(ClassMetadataInfo $metadata) - { - $array = array(); - - if ($metadata->isMappedSuperclass) { - $array['type'] = 'mappedSuperclass'; - } else { - $array['type'] = 'entity'; - } - - $array['table'] = $metadata->table['name']; - - if (isset($metadata->table['schema'])) { - $array['schema'] = $metadata->table['schema']; - } - - $inheritanceType = $metadata->inheritanceType; - if ($inheritanceType !== ClassMetadataInfo::INHERITANCE_TYPE_NONE) { - $array['inheritanceType'] = $this->_getInheritanceTypeString($inheritanceType); - } - - if ($column = $metadata->discriminatorColumn) { - $array['discriminatorColumn'] = $column; - } - - if ($map = $metadata->discriminatorMap) { - $array['discriminatorMap'] = $map; - } - - if ($metadata->changeTrackingPolicy !== ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT) { - $array['changeTrackingPolicy'] = $this->_getChangeTrackingPolicyString($metadata->changeTrackingPolicy); - } - - if (isset($metadata->table['indexes'])) { - $array['indexes'] = $metadata->table['indexes']; - } - - if ($metadata->customRepositoryClassName) { - $array['repositoryClass'] = $metadata->customRepositoryClassName; - } - - if (isset($metadata->table['uniqueConstraints'])) { - $array['uniqueConstraints'] = $metadata->table['uniqueConstraints']; - } - - $fieldMappings = $metadata->fieldMappings; - - $ids = array(); - foreach ($fieldMappings as $name => $fieldMapping) { - $fieldMapping['column'] = $fieldMapping['columnName']; - unset( - $fieldMapping['columnName'], - $fieldMapping['fieldName'] - ); - - if ($fieldMapping['column'] == $name) { - unset($fieldMapping['column']); - } - - if (isset($fieldMapping['id']) && $fieldMapping['id']) { - $ids[$name] = $fieldMapping; - unset($fieldMappings[$name]); - continue; - } - - $fieldMappings[$name] = $fieldMapping; - } - - if ($idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) { - $ids[$metadata->getSingleIdentifierFieldName()]['generator']['strategy'] = $this->_getIdGeneratorTypeString($metadata->generatorType); - }else{ - if(count($metadata->identifier) == 2){ - foreach($metadata->identifier as $identifier){ - if($identifier != 'c_id'){ - $ids[$identifier]['generator']['strategy'] = 'IDENTITY'; - } - } - } - - } - - if ($ids) { - $array['fields'] = $ids; - } - - if ($fieldMappings) { - if ( ! isset($array['fields'])) { - $array['fields'] = array(); - } - $array['fields'] = array_merge($array['fields'], $fieldMappings); - } - - $associations = array(); - foreach ($metadata->associationMappings as $name => $associationMapping) { - $cascade = array(); - if ($associationMapping['isCascadeRemove']) { - $cascade[] = 'remove'; - } - if ($associationMapping['isCascadePersist']) { - $cascade[] = 'persist'; - } - if ($associationMapping['isCascadeRefresh']) { - $cascade[] = 'refresh'; - } - if ($associationMapping['isCascadeMerge']) { - $cascade[] = 'merge'; - } - if ($associationMapping['isCascadeDetach']) { - $cascade[] = 'detach'; - } - if (count($cascade) === 5) { - $cascade = array('all'); - } - $associationMappingArray = array( - 'targetEntity' => $associationMapping['targetEntity'], - 'cascade' => $cascade, - ); - - if ($associationMapping['type'] & ClassMetadataInfo::TO_ONE) { - $joinColumns = $associationMapping['joinColumns']; - $newJoinColumns = array(); - foreach ($joinColumns as $joinColumn) { - $newJoinColumns[$joinColumn['name']]['referencedColumnName'] = $joinColumn['referencedColumnName']; - if (isset($joinColumn['onDelete'])) { - $newJoinColumns[$joinColumn['name']]['onDelete'] = $joinColumn['onDelete']; - } - } - $oneToOneMappingArray = array( - 'mappedBy' => $associationMapping['mappedBy'], - 'inversedBy' => $associationMapping['inversedBy'], - 'joinColumns' => $newJoinColumns, - 'orphanRemoval' => $associationMapping['orphanRemoval'], - ); - - $associationMappingArray = array_merge($associationMappingArray, $oneToOneMappingArray); - $array['oneToOne'][$name] = $associationMappingArray; - } else if ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_MANY) { - $oneToManyMappingArray = array( - 'mappedBy' => $associationMapping['mappedBy'], - 'inversedBy' => $associationMapping['inversedBy'], - 'orphanRemoval' => $associationMapping['orphanRemoval'], - 'orderBy' => isset($associationMapping['orderBy']) ? $associationMapping['orderBy'] : null - ); - - $associationMappingArray = array_merge($associationMappingArray, $oneToManyMappingArray); - $array['oneToMany'][$name] = $associationMappingArray; - } else if ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_MANY) { - $manyToManyMappingArray = array( - 'mappedBy' => $associationMapping['mappedBy'], - 'inversedBy' => $associationMapping['inversedBy'], - 'joinTable' => isset($associationMapping['joinTable']) ? $associationMapping['joinTable'] : null, - 'orderBy' => isset($associationMapping['orderBy']) ? $associationMapping['orderBy'] : null - ); - - $associationMappingArray = array_merge($associationMappingArray, $manyToManyMappingArray); - $array['manyToMany'][$name] = $associationMappingArray; - } - } - if (isset($metadata->lifecycleCallbacks)) { - $array['lifecycleCallbacks'] = $metadata->lifecycleCallbacks; - } - - return \Symfony\Component\Yaml\Yaml::dump(array($metadata->name => $array), 10); - } -} diff --git a/main/inc/lib/uri.class.php b/main/inc/lib/uri.class.php deleted file mode 100755 index e75b5e6636..0000000000 --- a/main/inc/lib/uri.class.php +++ /dev/null @@ -1,104 +0,0 @@ - for the Univesity of Geneva - */ -class Uri -{ - - public static function chamilo() - { - return 'http://chamilo.org/'; - } - - /** - * Application web root - */ - public static function www() - { - static $result = false; - if (empty($result)) { - $result = api_get_path(WEB_PATH); - } - return $result; - } - - public static function here($params = array(), $html = true) - { - $protocol = Request::server()->server_protocol(); - $protocol = stripos($protocol, 'https') !== false ? 'https' : 'http'; - - $host = Request::server()->server_name(); - $host = $host ? $host : Request::server()->server_addr(); - - $here = Request::server()->request_uri(); - $here = explode('?', $here); - $here = reset($here); - $here = $protocol . '://' . $host . $here; - return self::url($here, $params, $html); - } - - /** - * Returns a full url from local/absolute path and parameters. - * Append the root as required for relative urls. - * - * @param string $path - * @param array $params - * @return string - */ - public static function url($path = '', $params = array(), $html = true) - { - $result = $path; - if (strpos($result, 'http') !== 0) - { - $result = ltrim($result, '/'); - $result = self::www() . $result; - } - if ($params) - { - - $result = rtrim($result, '?'); - $result = $result . '?' . self::params($params, $html); - } - return $result; - } - - /** - * Format url parameters - * - * @param array $params - * @return string - */ - public static function params($params = array(), $html = true) - { - $result = array(); - foreach ($params as $key => $value) - { - $result[] = $key . '=' . urlencode($value); - } - $result = implode($html ? '&' : '&', $result); - return $result; - } - - /** - * Returns the course parameters. If null default to the current user parameters. - * - * @param string $course_code - * @param string|int $session_id - * @param string|int $group_id - * @return type - */ - public static function course_params($course_code = null, $session_id = null, $group_id = null) - { - $course_code = is_null($course_code) ? api_get_course_id() : $course_code; - $session_id = is_null($session_id) ? api_get_session_id() : $session_id; - $session_id = $session_id ? $session_id : '0'; - $group_id = is_null($group_id) ? '' : $group_id; - $group_id = $group_id ? $group_id : '0'; - return array('cidReq' => $course_code, 'id_session' => $session_id, 'gidReq' => $group_id); - } - -} diff --git a/main/inc/lib/zip.class.php b/main/inc/lib/zip.class.php deleted file mode 100755 index 57c456c595..0000000000 --- a/main/inc/lib/zip.class.php +++ /dev/null @@ -1,131 +0,0 @@ -add($file_path, $local_path); - * - * Note - * - * Pclzip do not accept method callbacks. It only accepts pure function callbacks. - * As a result the implementation is a bit more complicated than it should be. - * - * @license see /license.txt - * @author Laurent Opprecht for the Univesity of Geneva - */ -/** - * Zip wrapper class - */ -class Zip -{ - - protected static $pool = array(); - - public static function pool($hash = '') - { - if (empty($hash)) { - return self::$pool; - } else { - return self::$pool[$hash]; - } - } - - - /** - * - * @param string $path - * @return Zip - */ - public static function create($path) - { - return new self($path); - } - - protected $path = ''; - protected $archive = null; - protected $entries = array(); - - public function __construct($path = '') - { - $this->path = $path; - self::$pool[$this->get_hash()] = $this; - } - - public function get_path() - { - return $this->path; - } - - public function get_hash() - { - return md5($this->path); - } - - public function add($file_path, $archive_path = '', $comment = '') - { - /** - * Remove c: when working on windows. - */ - if (substr($file_path, 1, 1) == ':') { - $file_path = substr($file_path, 2); - } - - $entry = array( - 'file_path' => $file_path, - 'archive_path' => $archive_path, - 'comment' => $comment - ); - $this->entries[$file_path] = $entry; - - $callback_name = 'zipcallback_' . $this->get_hash(); - if (!function_exists($callback_name)) { - $callback = ''; - $callback .= 'function ' . $callback_name . '($event, &$header){'; - $callback .= '$parts = explode(\'_\', __FUNCTION__);'; - $callback .= '$hash = end($parts);'; - $callback .= 'return Zip::pool($hash)->callback($event, $header);'; - $callback .= '};'; - eval($callback); - } - - $archive = $this->archive(); - $archive->add($file_path, PCLZIP_CB_PRE_ADD, $callback_name); - } - - /** - * - * @return PclZip - */ - protected function archive() - { - if ($this->archive) { - return $this->archive; - } - if (empty($this->path)) { - return null; - } - return $this->archive = new PclZip($this->path); - } - - public function callback($event, &$header) - { - if ($event != PCLZIP_CB_PRE_ADD) { - return 0; - } - - $path = $header['filename']; - if (!isset($this->entries[$path])) { - return 1; - } - - $entry = $this->entries[$path]; - $archive_path = $entry['archive_path']; - if (!empty($archive_path)) { - $header['stored_filename'] = $archive_path; - } - return 1; - } - -} diff --git a/main/tracking/userlogCSV.php b/main/tracking/userlogCSV.php index 0b6175b6dc..4cc5086970 100755 --- a/main/tracking/userlogCSV.php +++ b/main/tracking/userlogCSV.php @@ -22,14 +22,6 @@ $user_id = api_get_user_id(); $course_id = api_get_course_id(); $courseId = api_get_course_int_id(); -/* -$role_id = RolesRights::get_local_user_role_id($user_id, $course_id); -$location_id = RolesRights::get_course_tool_location_id($course_id, TOOL_TRACKING); -$is_allowed = RolesRights::is_allowed_which_rights($role_id, $location_id); - -//block users without view right -RolesRights::protect_location($role_id, $location_id); -*/ //YW Hack security to quick fix RolesRights bug $is_allowed = true; diff --git a/tests/phpunit/classes/UriTest.class.php b/tests/phpunit/classes/UriTest.class.php deleted file mode 100755 index 5162df9dec..0000000000 --- a/tests/phpunit/classes/UriTest.class.php +++ /dev/null @@ -1,100 +0,0 @@ -object = new Uri; - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } - - /** - * @covers Uri::chamilo - * @todo Implement testChamilo(). - */ - public function testChamilo() - { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - } - - /** - * @covers Uri::www - * @todo Implement testWww(). - */ - public function testWww() - { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - } - - /** - * @covers Uri::here - * @todo Implement testHere(). - */ - public function testHere() - { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - } - - /** - * @covers Uri::url - * @todo Implement testUrl(). - */ - public function testUrl() - { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - } - - /** - * @covers Uri::params - * @todo Implement testParams(). - */ - public function testParams() - { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - } - - /** - * @covers Uri::course_params - * @todo Implement testCourse_params(). - */ - public function testCourse_params() - { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - } -} From 941828be0b9969445edc77f82bd64e31927add13 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 30 Mar 2015 15:56:53 +0200 Subject: [PATCH 011/159] Remove unused libs and code. --- main/inc/lib/AnnouncementManager.php | 24 ---- main/inc/lib/api.lib.php | 1 - main/inc/lib/chamilo.class.php | 118 +--------------- main/inc/lib/chamilo_session.class.php | 103 ++------------ main/inc/lib/course.lib.php | 28 ---- main/inc/lib/internationalization.lib.php | 9 +- main/inc/lib/portfolio.class.php | 136 +++++++++--------- main/inc/lib/redirect.class.php | 3 +- main/inc/lib/rights.lib.php | 12 +- main/inc/lib/system/io/temp.class.php | 164 ---------------------- main/inc/lib/system/web/header.class.php | 71 +--------- main/inc/lib/system/web/request.class.php | 25 ++-- 12 files changed, 106 insertions(+), 588 deletions(-) delete mode 100755 main/inc/lib/system/io/temp.class.php diff --git a/main/inc/lib/AnnouncementManager.php b/main/inc/lib/AnnouncementManager.php index e964c5b2bf..e7fbc50c78 100755 --- a/main/inc/lib/AnnouncementManager.php +++ b/main/inc/lib/AnnouncementManager.php @@ -1013,30 +1013,6 @@ class AnnouncementManager "; } - /** - * returns all the javascript that is required for easily - * setting the target people/groups - * this goes into the $htmlHeadXtra[] array - */ - public static function to_javascript() - { - $www = api_get_path(WEB_PATH); - /* - * Do not allow this kind of behaviour. js minifieds should be manage by the template class or assetic or whatever see #4757 for more info - if (api_get_setting('server_type') == 'test') { - $src = $www . 'main/announcements/resources/js/main.js'; - } else { - $src = $www . 'main/announcements/resources/js/main.min.js'; - }*/ - $src = $www . 'main/announcements/resources/js/main.js'; - $result = Javascript::tag($src); - $root = Chamilo::url(); - $code = "var www = '$root';\n"; - $code .= Javascript::get_lang('FieldRequired', 'Send2All', 'AddAnAttachment', 'Everybody'); - $result .= Javascript::tag_code($code); - return $result; - } - /** * constructs the form to display all the groups and users the message has been sent to * input: $sent_to_array is a 2 dimensional array containing the groups and the users diff --git a/main/inc/lib/api.lib.php b/main/inc/lib/api.lib.php index c1f8ff8107..7d39789989 100644 --- a/main/inc/lib/api.lib.php +++ b/main/inc/lib/api.lib.php @@ -3273,7 +3273,6 @@ function api_not_allowed($print_headers = false, $message = null) $osso->logout(); } } - Header::response_code(403); $home_url = api_get_path(WEB_PATH); $user_id = api_get_user_id(); $course = api_get_course_id(); diff --git a/main/inc/lib/chamilo.class.php b/main/inc/lib/chamilo.class.php index a6bdef5d0a..10ab8bfcc5 100755 --- a/main/inc/lib/chamilo.class.php +++ b/main/inc/lib/chamilo.class.php @@ -17,23 +17,6 @@ function session() */ class Chamilo { - - public static function name() - { - //@todo: add version - return 'chamilo'; - } - - static function is_test_server() - { - return api_get_setting('server_type') == 'test'; - } - - static function is_production_server() - { - return api_get_setting('server_type') == 'production'; - } - /** * * @return ChamiloSession @@ -42,103 +25,4 @@ class Chamilo { return ChamiloSession::instance(); } - - /** - * - * @return CurrentUser - */ - static function user() - { - return ChamiloSession::instance()->user(); - } - - /** - * Returns a full url from local/absolute path and parameters. - * Append the root as required for relative urls. - * - * @param string $path - * @param array $params - * @return string - */ - public static function url($path = '', $params = array(), $html = true) - { - return Uri::url($path, $params, $html); - } - - public static function here($params = array(), $html = true) - { - return Uri::here($params, $html); - } - - /** - * Application web root - */ - public static function www() - { - return Uri::www(); - } - - /** - * File system root for Chamilo - * - * @return string - */ - public static function root() - { - return api_get_path(SYS_PATH); - } - - public static function root_courses() - { - return api_get_path(SYS_COURSE_PATH); - } - - /** - * Returns a temporary file - one that is automatically deleted at the end - * of the script. - * - * @param string $ext - * @return Temp - */ - public static function temp_file($ext = '') - { - $ext = $ext ? '.' . $ext : ''; - Temp::set_temp_root(api_get_path(SYS_ARCHIVE_PATH) . 'temp'); - $path = Temp::get_temporary_name() . $ext; - return Temp::create($path); - } - - /** - * Returns a temporary directory - one that is automatically deleted at the end - * of the script. - * - * @param string $ext - * @return Temp - */ - public static function temp_dir() - { - $ext = $ext ? '.' . $ext : ''; - Temp::set_temp_root(api_get_path(SYS_ARCHIVE_PATH) . 'temp'); - $path = Temp::get_temporary_name() . $ext; - return Temp::dir($path); - } - - /** - * - * @return Zip - */ - public static function temp_zip() - { - return Zip::create(self::temp_file('zip')); - } - - public static function path($path = '') - { - $root = self::root(); - if (empty($path)) { - return $root; - } - return $root . $path; - } - -} \ No newline at end of file +} diff --git a/main/inc/lib/chamilo_session.class.php b/main/inc/lib/chamilo_session.class.php index 3ea4738c2d..5f26fffc12 100755 --- a/main/inc/lib/chamilo_session.class.php +++ b/main/inc/lib/chamilo_session.class.php @@ -1,16 +1,16 @@ ... * session()->... * @@ -27,7 +27,7 @@ class ChamiloSession extends System\Session /** * Generate new session instance - * @return ChamiloSession + * @return ChamiloSession */ static function instance() { @@ -74,54 +74,8 @@ class ChamiloSession extends System\Session { global $_configuration; - /* Causes too many problems and is not configurable dynamically. - if ($already_installed) { - $session_lifetime = 360000; - if (isset($_configuration['session_lifetime'])) { - $session_lifetime = $_configuration['session_lifetime']; - } - //session_set_cookie_params($session_lifetime,api_get_path(REL_PATH)); - } - */ - - if (isset($_configuration['session_stored_in_db']) && - $_configuration['session_stored_in_db'] && - function_exists('session_set_save_handler') - ) { - $handler = new SessionHandlerDatabase(); - @session_set_save_handler( - array($handler, 'open'), - array($handler, 'close'), - array($handler, 'read'), - array($handler, 'write'), - array($handler, 'destroy'), - array($handler, 'garbage') - ); - } - - // An alternative session handler, storing the session in memcache, - // and in the DB as backup for memcache server failure, can be used - // by defining specific configuration settings. - // This requires memcache or memcached and the php5-memcache module - // to be installed. - // See configuration.dist.php for greater details - if (isset($_configuration['session_stored_in_db_as_backup']) && - $_configuration['session_stored_in_db_as_backup'] && - function_exists('session_set_save_handler') - ) { - $handler = new SessionHandlerMemcache(); - session_set_save_handler( - array(&$handler, 'open'), - array(&$handler, 'close'), - array(&$handler, 'read'), - array(&$handler, 'write'), - array(&$handler, 'destroy'), - array(&$handler, 'gc') - ); - } - /* - * Prevent Session fixation bug fixes + * Prevent Session fixation bug fixes * See http://support.chamilo.org/issues/3600 * http://php.net/manual/en/session.configuration.php * @todo use session_set_cookie_params with some custom admin parameters @@ -131,12 +85,12 @@ class ChamiloSession extends System\Session //the session ID is only accepted from a cookie ini_set('session.use_only_cookies', 1); - //HTTPS only if possible + //HTTPS only if possible //ini_set('session.cookie_secure', 1); - //session ID in the cookie is only readable by the server + //session ID in the cookie is only readable by the server ini_set('session.cookie_httponly', 1); - //Use entropy file + //Use entropy file //session.entropy_file //ini_set('session.entropy_length', 128); //Do not include the identifier in the URL, and not to read the URL for @@ -198,39 +152,4 @@ class ChamiloSession extends System\Session { return $this->end_time() < time(); } - - /** - * The current (logged in) user. - * @return CurrentUser The current user instance - */ - public function user() - { - static $result = null; - if (empty($result)) { - $result = CurrentUser::instance(); - } - return $result; - } - - /** - * Returns the current (active) course - * @return CurrentCourse The current course instance - */ - public function course() - { - static $result = null; - if (empty($result)) { - $result = CurrentCourse::instance(); - } - return $result; - } - - /** - * The current group for the current (logged in) user. - * @return int the current group id - */ - public function group_id() - { - return Session::read('_gid'); - } } diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php index afc7b5cab4..9e15ea349a 100755 --- a/main/inc/lib/course.lib.php +++ b/main/inc/lib/course.lib.php @@ -4751,34 +4751,6 @@ class CourseManager return $result; } - /** - * @deprecated seems not to be used - */ - static function list_inactive_courses($ceiling, $visibility_level = COURSE_VISIBILITY_REGISTERED) - { - $ceiling = is_numeric($ceiling) ? (int)$ceiling : strtotime($ceiling); - $ceiling = date('Y-m-d H:i:s', $ceiling); - $visibility_level = $visibility_level ? $visibility_level : '0'; - - $table_course = Database::get_main_table(TABLE_MAIN_COURSE); - $table_category = Database::get_main_table(TABLE_MAIN_CATEGORY); - $sql = "SELECT - c.*, - cat.name AS category - FROM - $table_course AS c - LEFT JOIN - $table_category AS cat - ON - c.category_code = cat.code - WHERE - c.visibility >= $visibility_level AND - c.last_visit<='$ceiling' - "; - - return ResultSet::create($sql); - } - /** * Get courses count * @param int Access URL ID (optional) diff --git a/main/inc/lib/internationalization.lib.php b/main/inc/lib/internationalization.lib.php index 1a49b55b8d..a367f75f9f 100755 --- a/main/inc/lib/internationalization.lib.php +++ b/main/inc/lib/internationalization.lib.php @@ -11,6 +11,8 @@ * @package chamilo.library */ +use Patchwork\Utf8; + /** * Constants */ @@ -3295,10 +3297,11 @@ function api_detect_encoding($string, $language = null) { /** * Checks a string for UTF-8 validity. * - * @deprecated Use Encoding::utf8()->is_valid() instead */ -function api_is_valid_utf8(&$string) { - return Encoding::utf8()->is_valid($string); +function api_is_valid_utf8(&$string) +{ + return Utf8::isUtf8($string); + } /** diff --git a/main/inc/lib/portfolio.class.php b/main/inc/lib/portfolio.class.php index 2ce09caefc..a136d4ca35 100755 --- a/main/inc/lib/portfolio.class.php +++ b/main/inc/lib/portfolio.class.php @@ -2,8 +2,8 @@ /* For licensing terms, see /license.txt */ /* * This file contains several classes related to portfolios management to avoid - * having too much files under the lib/. - * + * having too much files under the lib/. + * * Once external libraries are moved to their own directory it would be worth * moving them to their own files under a common portfolio directory. * @package chamilo.portfolio @@ -16,19 +16,19 @@ use Model\Course; /** * A portfolio is used to present content to other people. In most cases it is - * an external application. - * + * an external application. + * * From the application point of view it is an end point to which the user can send * content. - * + * * Available portfolios are configured in /main/inc/config/portfolio.conf.php - * + * * The Portfolio class serves as an entry point to other portfolio components: - * + * * - portfolio controller * - portfolio share button * - portfolio action - * + * * Note: * @author Laurent Opprecht for the Univesity of Geneva */ @@ -38,7 +38,7 @@ class Portfolio /** * Returns all portfolios available - * + * * @return array */ public static function all() @@ -53,7 +53,7 @@ class Portfolio /** * Returns a portfolio from its name. - * + * * @param string $name * @return Portfolio\Portfolio */ @@ -70,8 +70,8 @@ class Portfolio /** * True if portfolios are enabled. False otherwise. - * - * @return boolean + * + * @return boolean */ public static function is_enabled() { @@ -91,8 +91,8 @@ class Portfolio /** * The controller for portfolio. - * - * @return \PortfolioController + * + * @return \PortfolioController */ public static function controller() { @@ -101,11 +101,11 @@ class Portfolio /** * Returns a share component/button. - * + * * @param string $tool * @param int $id * @param array $attributes - * @return \PortfolioShare + * @return \PortfolioShare */ public static function share($tool, $id, $attributes = array()) { @@ -114,8 +114,8 @@ class Portfolio /** * Returns the list of actions. - * - * @return array + * + * @return array */ public static function actions() { @@ -124,9 +124,9 @@ class Portfolio /** * Returns a temporary url to download files and/or folders. - * + * * @param string|array $ids - * @return string + * @return string */ public static function download_url($ids, $tool) { @@ -143,14 +143,14 @@ class Portfolio /** * The portfolio controller. Responsible to dispatch/process portfolio actions. - * + * * Usage: - * + * * if(Porfolio::contoller()->accept()){ * Portfolio::controller()->run(); * } - * - * + * + * */ class PortfolioController { @@ -166,7 +166,7 @@ class PortfolioController /** * - * @return \PortfolioController + * @return \PortfolioController */ static function instance() { @@ -181,7 +181,7 @@ class PortfolioController protected function __construct() { - + } public static function portfolios() @@ -190,9 +190,9 @@ class PortfolioController } /** - * List of actions for the SortableTable. - * - * @return array + * List of actions for the SortableTable. + * + * @return array */ public static function actions() { @@ -216,10 +216,10 @@ class PortfolioController } /** - * Returns true if the controller accept to process the current request. + * Returns true if the controller accept to process the current request. * Returns false otherwise. - * - * @return boolean + * + * @return boolean */ function accept() { @@ -249,8 +249,8 @@ class PortfolioController /** * Returns the value of the current controller request parameters. That is - * the name of the controller which shall handle the current request. - * + * the name of the controller which shall handle the current request. + * * @return string */ function get_controller() @@ -261,8 +261,8 @@ class PortfolioController /** * Returns the value of the action parameter. That is which action shall be * performed. That is share to send an object to a portfolio. - * - * @return string + * + * @return string */ function get_action() { @@ -272,7 +272,7 @@ class PortfolioController /** * Returns the value of the id parameter: id of object to send. - * + * * @return int */ function get_id() @@ -282,7 +282,7 @@ class PortfolioController /** * The course code (id) to which the object belongs. - * + * * @return string */ function course_code() @@ -292,8 +292,8 @@ class PortfolioController /** * The name of the porfolio where to send. - * - * @return type + * + * @return type */ function get_portfolio() { @@ -302,9 +302,9 @@ class PortfolioController /** * Name of the tool: document, work, etc. Defaults to current_course_tool. - * + * * @global string $current_course_tool - * @return string + * @return string */ function get_tool() { @@ -322,12 +322,12 @@ class PortfolioController } /** - * Execute the controller action as required. If a registered action accept + * Execute the controller action as required. If a registered action accept * the current request the controller calls it. - * + * * If not action is accept the current request and current action is "share" * the controller execute the "send to portfolio" action - * + * * @return PortfolioController */ function run() @@ -373,28 +373,28 @@ class PortfolioController /** * This component is used to display a "send to portfolio" button for a specific - * object. - * - * Note that the component implement the __toString() magic method and can be + * object. + * + * Note that the component implement the __toString() magic method and can be * therefore used in situation where a string is expected: for ex echo $button. - * + * * Usage - * + * * $button = Portfolio::share(...); * echo $button; - * + * */ class PortfolioShare { /** * Create a "send to portfolio" button - * + * * @param string $tool The name of the tool: document, work. * @param int $c_id The id of the course - * @param int $id The id of the object + * @param int $id The id of the object * @param array $attributes Html attributes - * @return \PortfolioShare + * @return \PortfolioShare */ static function factory($tool, $id, $attributes = array()) { @@ -404,8 +404,8 @@ class PortfolioShare /** * Returns the current secuirty token. Used to avoid see surfing attacks. - * - * @return type + * + * @return type */ static function security_token() { @@ -446,8 +446,8 @@ class PortfolioShare } /** - * Html attributes. - * + * Html attributes. + * * @return array */ function get_attributes() @@ -457,7 +457,7 @@ class PortfolioShare /** * Name of the tool. I.e. the type of the id parameter. Can be document, work. - * + * * @return string */ function get_tool() @@ -467,8 +467,8 @@ class PortfolioShare /** * Display the component. - * - * @return string + * + * @return string */ function display() { @@ -503,7 +503,7 @@ class PortfolioShare $parameters[PortfolioController::PARAM_TOOL] = $this->get_tool(); $parameters[PortfolioController::PARAM_ID] = $id; $parameters[PortfolioController::PARAM_TOOL] = $tool; - $url = Chamilo::url('/main/portfolio/share.php', $parameters); + $url = api_get_path(WEB_CODE_PATH).'portfolio/share.php', $parameters); $result[] = '
  • '; $result[] = '' . $portfolio->get_title() . ''; $result[] = '
  • '; @@ -522,15 +522,15 @@ class PortfolioShare } /** - * A "send to this portfolio" action. Actions are used by the SortableTable to + * A "send to this portfolio" action. Actions are used by the SortableTable to * perform actions on a set of objects. An action is composed of - * + * * - a name * - a title (displayed to the user) * - code to execute - * + * * Usage: - * + * * $form_actions = array(); * $form_action['...'] = get_lang('...'); * $portfolio_actions = Portfolio::actions(); @@ -538,7 +538,7 @@ class PortfolioShare * $form_action[$action->get_name()] = $action->get_title(); * } * $table->set_form_actions($form_action, 'path'); - * + * * @see SortableTable */ class PortfolioBulkAction @@ -560,7 +560,7 @@ class PortfolioBulkAction /** * - * @param \Portfolio\Portfolio $portfolio + * @param \Portfolio\Portfolio $portfolio */ public function __construct($portfolio) { diff --git a/main/inc/lib/redirect.class.php b/main/inc/lib/redirect.class.php index 7ceb99ca97..d0bfd1c280 100755 --- a/main/inc/lib/redirect.class.php +++ b/main/inc/lib/redirect.class.php @@ -12,7 +12,7 @@ class Redirect */ public static function www() { - return Uri::www(); + return api_get_path(WEB_PATH); } /** @@ -141,7 +141,6 @@ class Redirect */ protected static function navigate($url) { - //$url = Security::remove_XSS($url); session_write_close(); //should not be neeeded header("Location: $url"); exit; diff --git a/main/inc/lib/rights.lib.php b/main/inc/lib/rights.lib.php index e1c614d8a4..5fbca40af0 100755 --- a/main/inc/lib/rights.lib.php +++ b/main/inc/lib/rights.lib.php @@ -1,9 +1,13 @@ + 'show_tabs:reports' => array ( 'type' => 'const', 'const' => 'true' ) @@ -12,7 +16,7 @@ class Rights { // warning the goal of this function is to enforce rights managment in Chamilo // thus default return value is always true public static function hasRight($handler) { - if (array_key_exists($handler, self::$rights_cache)) + if (array_key_exists($handler, self::$rights_cache)) return self::$rights_cache[$handler]; if (!array_key_exists($handler, self::$rights)) @@ -20,7 +24,7 @@ class Rights { if (self::$rights[$handler]['type'] == 'sql') { $result = Database::query(self::$rights[$handler]['sql']); - if (Database::num_rows($result) > 0) + if (Database::num_rows($result) > 0) $result = true; else $result = false; @@ -33,7 +37,7 @@ class Rights { self::$rights_cache[$handler] = $result; return $result; } - + public static function hasRightClosePageWithError($handler) { if (hasRight($handler) == false) die("You are not allowed here"); //FIXME diff --git a/main/inc/lib/system/io/temp.class.php b/main/inc/lib/system/io/temp.class.php deleted file mode 100755 index 5d5308fee5..0000000000 --- a/main/inc/lib/system/io/temp.class.php +++ /dev/null @@ -1,164 +0,0 @@ - - */ -class Temp -{ - - protected static $files = array(); - - /** - * Returns the list of temporary files opened by the script. - * This is mostly due to pin temporary files and prevent garbage collection. - * This ensure files are not unlinked while still using it to send data in - * an upload. - * - * @return array - */ - public static function files() - { - return self::$files; - } - - /** - * Recursively delete files and/or folders. - * - * @param string $path - * @return boolean - */ - public static function delete($path) - { - if (!file_exists($path)) { - return false; - } - - if (is_readable($path)) { - unlink($path); - return true; - } - - if (is_dir($path)) { - $files = scandir($path); - $files = array_diff($files, array('.', '..')); - foreach ($files as $file) { - self::delete($file); - } - rmdir($path); - } - } - - private static $temp_root = ''; - - /** - * Set the temp root directory. Temporary files are by default created in this directory. - * Defaults to sys_get_temp_dir(). - * - * @param string $value - */ - public static function set_temp_root($value) - { - self::$temp_root = $value; - } - - public static function get_temp_root() - { - if (empty(self::$temp_root)) { - self::$temp_root = sys_get_temp_dir(); - } - - return self::$temp_root; - } - - /** - * Returns a path to a non-existing temporary file located under temp_dir. - * - * @return string - */ - public static function get_temporary_name() - { - $result = self::get_temp_root() . '/' . md5(uniqid('tmp', true)); - while (file_exists($result)) { - $result = self::get_temp_root() . '/' . md5(uniqid('tmp', true)); - } - return $result; - } - - /** - * - * @param string $path - * @return Temp - */ - public static function file($path = '') - { - $path = $path ? $path : self::get_temporary_name(); - return new self($path); - } - - /** - * - * @param string $path - * @return Temp - */ - public static function dir($path = '') - { - $path = $path ? $path : self::get_temporary_name(); - if (!file_exists($path)) { - mkdir($path, 0777, $true); - } - return new self($path); - } - - /** - * - * @param string $path - * @return Temp - */ - public static function create($path = '') - { - $path = $path ? $path : self::get_temporary_name(); - return new self($path); - } - - protected $path = ''; - - function __construct($path = '') - { - self::$files[] = $this; - $this->path = $path; - } - - function get_path() - { - return $this->path; - } - - function __toString() - { - return $this->path; - } - - function __destruct() - { - $path = $this->path; - self::delete($path); - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/web/header.class.php b/main/inc/lib/system/web/header.class.php index b1c23d08ab..1495c0babc 100755 --- a/main/inc/lib/system/web/header.class.php +++ b/main/inc/lib/system/web/header.class.php @@ -8,79 +8,14 @@ */ class Header { - - public static function response_code($response_code) - { - if (function_exists('http_response_code')) { - http_response_code($response_code); - return; - } - - switch ($response_code) { - case 400: - header("HTTP/1.0 $response_code Bad Request"); - case 401: - header("HTTP/1.0 $response_code Unauthorized"); - case 402: - header("HTTP/1.0 $response_code Payment Required"); - case 403: - header("HTTP/1.0 $response_code Forbidden"); - case 404: - header("HTTP/1.0 $response_code Not Found"); - default: - header("HTTP/1.0 $response_code"); - } - } - - public static function content_type($mime_type, $charset = '') - { - if (empty($mime_type)) { - return; - } - $type = $charset ? "$mime_type;charset=$charset" : $mime_type; - header('Content-type: ' . $type); - } - - public static function content_type_xml() - { - header('Content-type: text/xml'); - } - - public static function content_type_json() - { - header('Content-type: application/json'); - } - - public static function content_type_javascript() - { - header('Content-type: application/javascript'); - } - /** * Redirect the navigator to the specified url. - * - * @param string $url + * + * @param string $url */ public static function location($url) { header("Location: $url"); exit; } - - public static function expires($timestamp) - { - $value = gmdate('D, d M Y H:i:s \G\M\T', $timestamp); - header('Expires: ' . $value); - } - - public static function cache_control($value) - { - header('Cache-Control: ' . $value); - } - - public static function pragma($value) - { - header('Pragma: ' . $value); - } - -} \ No newline at end of file +} diff --git a/main/inc/lib/system/web/request.class.php b/main/inc/lib/system/web/request.class.php index 5e827f8f96..3979b70c9c 100755 --- a/main/inc/lib/system/web/request.class.php +++ b/main/inc/lib/system/web/request.class.php @@ -2,7 +2,7 @@ /** * Provides access to various HTTP request elements: GET, POST, FILE, etc paramaters. - + * @license see /license.txt * @author Laurent Opprecht for the Univesity of Geneva */ @@ -13,14 +13,14 @@ class Request { return isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default; } - + public static function has($key){ return isset($_REQUEST[$key]); } - + /** * Returns true if the request is a GET request. False otherwise. - * + * * @return bool */ public static function is_get() @@ -29,15 +29,15 @@ class Request $method = strtoupper($method); return $method == 'GET'; } - + public static function post($key, $default = null) { return isset($_POST[$key]) ? $_POST[$key] : $default; } - + /** * Returns true if the request is a POST request. False otherwise. - * + * * @return bool */ public static function is_post() @@ -46,15 +46,6 @@ class Request $method = strtoupper($method); return $method == 'POST'; } - - /** - * - * @return RequestServer - */ - static function server() - { - return RequestServer::instance(); - } static function file($key, $default = null) { @@ -66,4 +57,4 @@ class Request return isset($_ENV[$key]) ? $_ENV[$key] : $default; } -} \ No newline at end of file +} From 757192be2f24294c43168d49e34e568a5357e32b Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 31 Mar 2015 15:31:40 +0200 Subject: [PATCH 012/159] Remove unused classes. --- main/install/i_database.class.php | 66 ------------------------------- main/install/install.class.php | 16 -------- 2 files changed, 82 deletions(-) delete mode 100755 main/install/i_database.class.php delete mode 100755 main/install/install.class.php diff --git a/main/install/i_database.class.php b/main/install/i_database.class.php deleted file mode 100755 index 07d1c8213f..0000000000 --- a/main/install/i_database.class.php +++ /dev/null @@ -1,66 +0,0 @@ - for the Univesity of Geneva - */ -class iDatabase extends Database -{ - - private static $is_logging = true; - - static function is_logging() - { - return self::$is_logging; - } - - static function set_is_logging($value) - { - self::$is_logging = $value; - } - - - static function query($query, $connection = null, $file = null, $line = null) - { - if (self::is_logging()) { - $query = str_replace("\n", '', $query); - Log::notice(__FUNCTION__ . ' ' . $query, Log::frame(1)); - } - - $result = parent::query($query, $connection, $file, $line); - - if (empty($result)) { - $backtrace = debug_backtrace(); // Retrieving information about the caller statement. - $caller = isset($backtrace[0]) ? $backtrace[0] : array(); - $file = $caller['file']; - $line = $caller['line']; - $message = " sql: $query \n file: $file \n line:$line"; - Log::error($message); - } - return $result; - } - - /** - * Returns true if the table exists in the database, false otherwise. - * @param string $database - * @param string table - * @return boolean - */ - static - - function table_exists($database, $table) - { - $tables = mysql_list_tables($db); - while (list ($temp) = mysql_fetch_array($tables)) { - if (strtolower($temp) == strtolower($table)) { - return true; - } - } - return false; - } - -} - diff --git a/main/install/install.class.php b/main/install/install.class.php deleted file mode 100755 index 06340cf715..0000000000 --- a/main/install/install.class.php +++ /dev/null @@ -1,16 +0,0 @@ - for the Univesity of Geneva - */ -class Install -{ - static function message($message) - { - echo '
    ' . $message . '
    '; - } - -} \ No newline at end of file From ebeeb85c030d97a5ca18d05b913890430a134983 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 31 Mar 2015 15:32:32 +0200 Subject: [PATCH 013/159] Remove enum type. --- main/install/migrate-db-1.9.0-1.10.0-post.sql | 16 +++--------- main/install/migrate-db-1.9.0-1.10.0-pre.sql | 26 ++++++++++++------- 2 files changed, 19 insertions(+), 23 deletions(-) diff --git a/main/install/migrate-db-1.9.0-1.10.0-post.sql b/main/install/migrate-db-1.9.0-1.10.0-post.sql index 9e61eb72c9..03eed6a0e2 100644 --- a/main/install/migrate-db-1.9.0-1.10.0-post.sql +++ b/main/install/migrate-db-1.9.0-1.10.0-post.sql @@ -1,18 +1,7 @@ -- This script updates the databases structure after migrating the data from -- version 1.9.0 (or version 1.9.*) to version 1.10.0 --- it is intended as a standalone script, however, because of the multiple --- databases related difficulties, it should be parsed by a PHP script in --- order to connect to and update the right databases. --- There is one line per query, allowing the PHP function file() to read --- all lines separately into an array. The xxMAINxx-type markers are there --- to tell the PHP script which database we're talking about. --- By always using the keyword "TABLE" in the queries, we should be able --- to retrieve and modify the table name from the PHP script if needed, which --- will allow us to deal with the unique-database-type installations --- --- This first part is for the main database --- xxMAINxx +-- Main table changes ALTER TABLE track_e_access DROP COLUMN access_cours_code; ALTER TABLE track_e_default DROP COLUMN default_cours_code; @@ -28,7 +17,8 @@ ALTER TABLE track_e_attempt DROP COLUMN course_code; -- not yet ready, uncomment when all user_id have been replaced by id -- ALTER TABLE user DROP COLUMN user_id; --- xxCOURSExx +-- Course table changes (c_*) +hjus diff --git a/main/install/migrate-db-1.9.0-1.10.0-pre.sql b/main/install/migrate-db-1.9.0-1.10.0-pre.sql index 770cb458ea..ce22972e67 100644 --- a/main/install/migrate-db-1.9.0-1.10.0-pre.sql +++ b/main/install/migrate-db-1.9.0-1.10.0-pre.sql @@ -1,16 +1,12 @@ -- This script updates the databases structure before migrating the data from -- version 1.9.0 (or version 1.9.*) to version 1.10.0 --- Main DB changes +-- Main table changes ALTER TABLE skill_rel_user ADD COLUMN course_id INT NOT NULL DEFAULT 0 AFTER id; ALTER TABLE skill_rel_user ADD COLUMN session_id INT NOT NULL DEFAULT 0 AFTER course_id; ALTER TABLE skill_rel_user ADD INDEX idx_select_cs (course_id, session_id); -CREATE TABLE IF NOT EXISTS hook_observer( id int UNSIGNED NOT NULL AUTO_INCREMENT, class_name varchar(255) UNIQUE, path varchar(255) NOT NULL, plugin_name varchar(255) NULL, PRIMARY KEY PK_hook_management_hook_observer(id)); -CREATE TABLE IF NOT EXISTS hook_event( id int UNSIGNED NOT NULL AUTO_INCREMENT, class_name varchar(255) UNIQUE, description varchar(255), PRIMARY KEY PK_hook_management_hook_event(id)); -CREATE TABLE IF NOT EXISTS hook_call( id int UNSIGNED NOT NULL AUTO_INCREMENT, hook_event_id int UNSIGNED NOT NULL, hook_observer_id int UNSIGNED NOT NULL, type tinyint NOT NULL, hook_order int UNSIGNED NOT NULL, enabled tinyint NOT NULL, PRIMARY KEY PK_hook_management_hook_call(id)); - ALTER TABLE session ADD COLUMN description TEXT DEFAULT NULL; ALTER TABLE session ADD COLUMN show_description TINYINT UNSIGNED DEFAULT 0 AFTER description; @@ -21,6 +17,9 @@ ALTER TABLE session_rel_user ADD COLUMN duration int; CREATE TABLE course_field_options (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, field_id INT NOT NULL, option_value TEXT, option_display_text VARCHAR(64), option_order INT, tms DATETIME); CREATE TABLE session_field_options (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, field_id INT NOT NULL, option_value TEXT, option_display_text VARCHAR(64), option_order INT, tms DATETIME); +CREATE TABLE IF NOT EXISTS hook_observer( id int UNSIGNED NOT NULL AUTO_INCREMENT, class_name varchar(255) UNIQUE, path varchar(255) NOT NULL, plugin_name varchar(255) NULL, PRIMARY KEY PK_hook_management_hook_observer(id)); +CREATE TABLE IF NOT EXISTS hook_event( id int UNSIGNED NOT NULL AUTO_INCREMENT, class_name varchar(255) UNIQUE, description varchar(255), PRIMARY KEY PK_hook_management_hook_event(id)); +CREATE TABLE IF NOT EXISTS hook_call( id int UNSIGNED NOT NULL AUTO_INCREMENT, hook_event_id int UNSIGNED NOT NULL, hook_observer_id int UNSIGNED NOT NULL, type tinyint NOT NULL, hook_order int UNSIGNED NOT NULL, enabled tinyint NOT NULL, PRIMARY KEY PK_hook_management_hook_call(id)); ALTER TABLE skill ADD COLUMN criteria text DEFAULT ''; @@ -104,15 +103,23 @@ ALTER TABLE session MODIFY COLUMN name char(100) NOT NULL DEFAULT ''; ALTER TABLE track_e_default MODIFY COLUMN c_id int default NULL; UPDATE course_field SET field_type = 1 WHERE field_variable = 'special_course'; --- Course DB changes (c_*) +-- Course table changes (c_*) ALTER TABLE c_survey ADD COLUMN visible_results INT UNSIGNED DEFAULT 0; ALTER TABLE c_survey_invitation ADD COLUMN group_id INT NOT NULL; ALTER TABLE c_lp_item ADD COLUMN prerequisite_min_score float; ALTER TABLE c_lp_item ADD COLUMN prerequisite_max_score float; -ALTER TABLE c_lp_item MODIFY COLUMN description VARCHAR(511) DEFAULT ''; -ALTER TABLE c_student_publication ADD COLUMN document_id int DEFAULT 0; ALTER TABLE c_group_info ADD COLUMN status tinyint DEFAULT 1; +ALTER TABLE c_student_publication ADD COLUMN document_id int DEFAULT 0; +ALTER TABLE c_lp_item MODIFY COLUMN description VARCHAR(511) DEFAULT ''; + +ALTER TABLE course_category MODIFY COLUMN auth_course_child VARCHAR(40) DEFAULT 'TRUE'; +ALTER TABLE course_category MODIFY COLUMN auth_cat_child VARCHAR(40) DEFAULT 'TRUE'; +ALTER TABLE c_quiz_answer MODIFY COLUMN hotspot_type varchar(40) default NULL; +ALTER TABLE c_tool MODIFY COLUMN target varchar(20) NOT NULL default '_self'; +ALTER TABLE c_link MODIFY COLUMN on_homepage char(10) NOT NULL default '0'; +ALTER TABLE c_blog_rating MODIFY COLUMN rating_type char(40) NOT NULL default 'post'; +ALTER TABLE c_survey MODIFY COLUMN anonymous char(10) NOT NULL default '0'; ALTER TABLE c_course_setting MODIFY COLUMN value varchar(255) default ''; @@ -121,6 +128,5 @@ CREATE TABLE IF NOT EXISTS c_student_publication_rel_user (id INT PRIMARY KEY N CREATE TABLE IF NOT EXISTS c_student_publication_comment (id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, work_id INT NOT NULL, c_id INT NOT NULL, comment text, file VARCHAR(255), user_id int NOT NULL, sent_at datetime NOT NULL); CREATE TABLE IF NOT EXISTS c_attendance_calendar_rel_group (id int NOT NULL auto_increment PRIMARY KEY, c_id INT NOT NULL, group_id INT NOT NULL, calendar_id INT NOT NULL); - -- Do not move this query -UPDATE settings_current SET selected_value = '1.10.0.33' WHERE variable = 'chamilo_database_version'; +UPDATE settings_current SET selected_value = '1.10.0.34' WHERE variable = 'chamilo_database_version'; From d646ba41addc58a06e6aef0ca3e141148e26d4c7 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 31 Mar 2015 15:33:29 +0200 Subject: [PATCH 014/159] Minor - UI fixes --- main/admin/user_edit.php | 29 ++++++++--------------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/main/admin/user_edit.php b/main/admin/user_edit.php index 1862abdb93..627468c619 100755 --- a/main/admin/user_edit.php +++ b/main/admin/user_edit.php @@ -97,7 +97,12 @@ $extra_data = UserManager :: get_extra_user_data($user_id, true); $user_data = array_merge($user_data, $extra_data); // Create the form -$form = new FormValidator('user_edit', 'post', '', '', array('style' => 'width: 60%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;'))); +$form = new FormValidator( + 'user_edit', + 'post', + '', + '' +); $form->addElement('header', '', $tool_name); $form->addElement('hidden', 'user_id', $user_id); @@ -131,7 +136,7 @@ $form->applyFilter('official_code', 'html_filter'); $form->applyFilter('official_code', 'trim'); // Email -$form->addElement('text', 'email', get_lang('Email'), array('size' => '40')); +$form->addElement('text', 'email', get_lang('Email')); $form->addRule('email', get_lang('EmailWrong'), 'email'); if (api_get_setting('registration', 'email') == 'true') { $form->addRule('email', get_lang('EmailWrong'), 'required'); @@ -144,7 +149,7 @@ if (api_get_setting('login_is_email') == 'true') { // OpenID if (api_get_setting('openid_authentication') == 'true') { - $form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => '40')); + $form->addElement('text', 'openid', get_lang('OpenIDURL')); } // Phone @@ -159,7 +164,6 @@ if (strlen($user_data['picture_uri']) > 0) { } // Username - if (api_get_setting('login_is_email') != 'true') { $form->addElement('text', 'username', get_lang('LoginName'), array('maxlength' => USERNAME_MAX_LENGTH)); $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required'); @@ -220,23 +224,6 @@ $form->addElement( $display = isset($user_data['status']) && ($user_data['status'] == STUDENT || (isset($_POST['status']) && $_POST['status'] == STUDENT)) ? 'block' : 'none'; -/* -$form->addElement('html', '
    '); -$drh_select = $form->addElement('select', 'hr_dept_id', get_lang('Drh'), array(), 'id="drh_select"'); -$drh_list = UserManager :: get_user_list(array('status' => DRH), api_sort_by_first_name() ? array('firstname', 'lastname') : array('lastname', 'firstname')); - -if (count($drh_list) == 0) { - $drh_select->addOption('- '.get_lang('ThereIsNotStillAResponsible', '').' -', 0); -} else { - $drh_select->addOption('- '.get_lang('SelectAResponsible').' -', 0); -} - -foreach($drh_list as $drh) { - $drh_select->addOption(api_get_person_name($drh['firstname'], $drh['lastname']), $drh['user_id']); -} -$form->addElement('html', '
    '); -*/ - // Platform admin if (api_is_platform_admin()) { $group = array(); From 798fae72ee340e8e9dca05fb2787f05b5098a877 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 31 Mar 2015 15:33:48 +0200 Subject: [PATCH 015/159] Remove enum type --- main/install/database.sql | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/main/install/database.sql b/main/install/database.sql index 76ca1ac1f5..69cb8cc1e9 100644 --- a/main/install/database.sql +++ b/main/install/database.sql @@ -80,7 +80,6 @@ CREATE TABLE IF NOT EXISTS admin ( -- Dumping data for table admin -- - /*!40000 ALTER TABLE admin DISABLE KEYS */; LOCK TABLES admin WRITE; INSERT INTO admin VALUES (1, 1); @@ -189,8 +188,8 @@ CREATE TABLE IF NOT EXISTS course_category ( parent_id varchar(40) default NULL, tree_pos int unsigned default NULL, children_count smallint default NULL, - auth_course_child enum('TRUE','FALSE') default 'TRUE', - auth_cat_child enum('TRUE','FALSE') default 'TRUE', + auth_course_child varchar(40) default 'TRUE', + auth_cat_child varchar(40) default 'TRUE', PRIMARY KEY (id), UNIQUE KEY code (code), KEY parent_id (parent_id), @@ -3615,7 +3614,7 @@ CREATE TABLE c_quiz_answer( ponderation float(6,2) NOT NULL default 0, position mediumint unsigned NOT NULL default 1, hotspot_coordinates text, - hotspot_type enum('square','circle','poly','delineation','oar') default NULL, + hotspot_type varchar(40) default NULL, destination text NOT NULL, answer_code char(10) default '', PRIMARY KEY (id_auto, c_id) @@ -3676,7 +3675,7 @@ CREATE TABLE c_tool( admin varchar(255) default NULL, address varchar(255) default NULL, added_tool tinyint unsigned default 1, - target enum('_self','_blank') NOT NULL default '_self', + target varchar(20) NOT NULL default '_self', category varchar(20) not null default 'authoring', session_id int default 0, PRIMARY KEY (id, c_id) @@ -3787,7 +3786,7 @@ CREATE TABLE c_link( description text, category_id int unsigned default NULL, display_order int unsigned NOT NULL default 0, - on_homepage enum('0','1') NOT NULL default '0', + on_homepage char(10) NOT NULL default '0', target char(10) default '_self', session_id int default 0, PRIMARY KEY (id, c_id) @@ -4243,7 +4242,7 @@ CREATE TABLE c_blog_rating( rating_id int NOT NULL AUTO_INCREMENT , c_id INT NOT NULL, blog_id int NOT NULL default 0, - rating_type enum( 'post', 'comment' ) NOT NULL default 'post', + rating_type char(40) NOT NULL default 'post', item_id int NOT NULL default 0, user_id int NOT NULL default 0, rating int NOT NULL default 0, @@ -4367,7 +4366,7 @@ CREATE TABLE c_course_setting ( PRIMARY KEY (id, c_id) ); -CREATE TABLE c_survey ( +CREATE TABLE c_survey ( survey_id int unsigned NOT NULL auto_increment, c_id INT NOT NULL, code varchar(20) default NULL, @@ -4387,7 +4386,7 @@ CREATE TABLE c_survey ( invite_mail text NOT NULL, reminder_mail text NOT NULL, mail_subject VARCHAR( 255 ) NOT NULL, - anonymous enum('0','1') NOT NULL default '0', + anonymous char(10) NOT NULL default '0', access_condition TEXT DEFAULT NULL, shuffle bool NOT NULL default '0', one_question_per_page bool NOT NULL default '0', @@ -4619,5 +4618,5 @@ CREATE TABLE c_attendance_calendar_rel_group ( -- Version LOCK TABLES settings_current WRITE; -UPDATE settings_current SET selected_value = '1.10.0.33' WHERE variable = 'chamilo_database_version'; +UPDATE settings_current SET selected_value = '1.10.0.34' WHERE variable = 'chamilo_database_version'; UNLOCK TABLES; From 82a63e9dacbdb2a32bffdd1748ba2cda6aacd283 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 31 Mar 2015 15:38:26 +0200 Subject: [PATCH 016/159] Format code, remove unused code. --- main/install/update-configuration.inc.php | 42 +++++++----------- main/install/version.php | 19 ++++---- .../main/install/install_upgrade.lib.test.php | 44 ------------------- 3 files changed, 27 insertions(+), 78 deletions(-) diff --git a/main/install/update-configuration.inc.php b/main/install/update-configuration.inc.php index 2eef2d1bf6..8dd31c1649 100755 --- a/main/install/update-configuration.inc.php +++ b/main/install/update-configuration.inc.php @@ -1,11 +1,11 @@ ') !== false) { $ignore = true; } @@ -55,7 +47,7 @@ if (defined('SYSTEM_INSTALLATION')) { fwrite($fh, $line); } } - + if (!$found_version) { fwrite($fh, '$_configuration[\'system_version\'] = \'' . $new_version . '\';' . "\r\n"); } @@ -67,9 +59,9 @@ if (defined('SYSTEM_INSTALLATION')) { } if (!$found_software_url) { fwrite($fh, '$_configuration[\'software_url\'] = \'' . $software_url . '\';' . "\r\n"); - } + } fwrite($fh, '?>'); fclose($fh); } else { echo 'You are not allowed here !'. __FILE__; -} \ No newline at end of file +} diff --git a/main/install/version.php b/main/install/version.php index 9ccd6283fd..ca7b7d00f6 100755 --- a/main/install/version.php +++ b/main/install/version.php @@ -2,20 +2,21 @@ /* For licensing terms, see /license.txt */ /** * This script lists the necessary variables that allow the installation - * system to know in which version is the current Chamilo install. This + * system to know in which version is the current Chamilo install. This * script should be overwritten with each upgrade of Chamilo. It is not * required from any other process of Chamilo than the installation or upgrade. * It also helps for automatic packaging of unstable versions. - * + * * @package chamilo.install */ + /** * Variables used from the main/install/index.php */ -$new_version = '1.10.0'; -$new_version_status = 'alpha'; -$new_version_last_id = 0; -$new_version_stable = false; -$new_version_major = true; -$software_name = 'Chamilo'; -$software_url = 'http://www.chamilo.org/'; +$new_version = '1.10.0'; +$new_version_status = 'alpha'; +$new_version_last_id = 0; +$new_version_stable = false; +$new_version_major = true; +$software_name = 'Chamilo'; +$software_url = 'http://www.chamilo.org/'; diff --git a/tests/main/install/install_upgrade.lib.test.php b/tests/main/install/install_upgrade.lib.test.php index b349d9ffd9..be20146852 100755 --- a/tests/main/install/install_upgrade.lib.test.php +++ b/tests/main/install/install_upgrade.lib.test.php @@ -15,13 +15,6 @@ class TestInstallUpgrade extends UnitTestCase{ //var_dump($res); } - public function testFillTrackCountriesTable() { - $track_countries_table=''; - $res = fill_track_countries_table($track_countries_table); - $this->assertEqual(null,$res); - //var_dump($res); - } - public function testWriteCoursesHtaccessFile() { $chamilo_path_folder = api_get_path(SYS_PATH); $url_append=$chamilo_path_folder.'main/install/'; @@ -33,30 +26,6 @@ class TestInstallUpgrade extends UnitTestCase{ $this->assertEqual($chamilo_path_folder.'main/install/',$res); //var_dump($res); } - //This function is ok but the problem is than create course with other code - /* - public function testLoadMainDatabase() { - $chamilo_path_folder= api_get_path(SYS_CODE_PATH); - $installation_settings['{ORGANISATIONNAME}'] = 'My Organisation'; - $installation_settings['{ORGANISATIONURL}'] = 'http://www.chamilo.org'; - $installation_settings['{CAMPUSNAME}'] = 'My campus'; - $installation_settings['{PLATFORMLANGUAGE}'] = 'spanish'; - $installation_settings['{ALLOWSELFREGISTRATION}'] = 1; - $installation_settings['{ALLOWTEACHERSELFREGISTRATION}'] = 1; - $installation_settings['{ADMINLASTNAME}'] = 'Doe'; - $installation_settings['{ADMINFIRSTNAME}'] = 'John'; - $installation_settings['{ADMINLOGIN}'] = 'admin'; - $installation_settings['{ADMINPASSWORD}'] = md5('admin'); - $installation_settings['{ADMINEMAIL}'] = '.localdomain'; - $installation_settings['{ADMINPHONE}'] = '(000) 001 02 03'; - $installation_settings['{PLATFORM_AUTH_SOURCE}'] = PLATFORM_AUTH_SOURCE; - $installation_settings['{ADMINLANGUAGE}'] = 'spanish'; - $installation_settings['{HASHFUNCTIONMODE}'] = 'md5'; - $db_script = $chamilo_path_folder.'install/db_main.sql'; - $res = load_main_database($installation_settings,$db_script); - $this->assertFalse($res); - } -*/ public function testSplitSqlFile() { $ret=''; @@ -67,19 +36,6 @@ class TestInstallUpgrade extends UnitTestCase{ $this->assertTrue($res===true); } - public function testGetSqlFileContents() { - ob_start(); - $file='txt'; - $section='course'; - $print_errors=true; - $res = get_sql_file_contents($file,$section,$print_errors); - ob_end_clean(); - if(is_bool($res)); - $this->assertTrue(is_bool($res)); - $this->assertTrue($res===true || $res === false); - //var_dump($res); - } - public function testMyDirectoryToArray() { $chamilo_path_folder= api_get_path(SYS_PATH); $directory= $chamilo_path_folder.'home'; From 822d785142b6831411e5116e4fced2b7ff53a01a Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 31 Mar 2015 15:54:01 +0200 Subject: [PATCH 017/159] Replacing database calls with Doctrine --- main/install/index.php | 43 +---- main/install/install.lib.php | 167 +------------------- main/install/install_db.inc.php | 65 ++++---- main/install/update-db-1.9.0-1.10.0.inc.php | 132 ++-------------- 4 files changed, 51 insertions(+), 356 deletions(-) diff --git a/main/install/index.php b/main/install/index.php index ecf1e40b3d..dada882862 100755 --- a/main/install/index.php +++ b/main/install/index.php @@ -107,7 +107,6 @@ error_reporting(E_ALL); $update_from_version_8 = array('1.9.0', '1.9.2','1.9.4','1.9.6', '1.9.6.1', '1.9.8', '1.9.8.1', '1.9.8.2', '1.9.10'); $my_old_version = ''; -$tmp_version = get_config_param('dokeos_version'); if (empty($tmp_version)) { $tmp_version = get_config_param('system_version'); } @@ -115,8 +114,6 @@ if (!empty($_POST['old_version'])) { $my_old_version = $_POST['old_version']; } elseif (!empty($tmp_version)) { $my_old_version = $tmp_version; -} elseif (!empty($dokeos_version)) { //variable coming from installedVersion, normally - $my_old_version = $dokeos_version; } require_once __DIR__.'/version.php'; @@ -720,7 +717,6 @@ if (@$_POST['step2']) { if ($installType == 'update') { remove_memory_and_time_limits(); - //database_server_connect(); $manager = testDbConnect( $dbHostForm, $dbUsernameForm, @@ -728,32 +724,11 @@ if (@$_POST['step2']) { $dbNameForm ); - // Initialization of the database connection encoding intentionaly is not done. - // This is the old style for connecting to the database server, that is implemented here. - $perm = api_get_permissions_for_new_directories(); $perm_file = api_get_permissions_for_new_files(); - if (empty($my_old_version)) { $my_old_version = '1.8.6.2'; } //we guess - - $_configuration['main_database'] = $dbNameForm; Log::notice('Starting migration process from '.$my_old_version.' ('.time().')'); - if ($userPasswordCrypted == '1') { - $userPasswordCrypted = 'md5'; - } elseif ($userPasswordCrypted == '0') { - $userPasswordCrypted = 'none'; - } - - Database::query("SET storage_engine = MYISAM;"); - - if (version_compare($my_old_version, '1.8.7', '>=')) { - Database::query("SET SESSION character_set_server='utf8';"); - Database::query("SET SESSION collation_server='utf8_general_ci';"); - //Database::query("SET CHARACTER SET 'utf8';"); // See task #1802. - Database::query("SET NAMES 'utf8';"); - } - switch ($my_old_version) { case '1.9.0': case '1.9.2': @@ -764,6 +739,7 @@ if (@$_POST['step2']) { case '1.9.8.1': case '1.9.8.2': case '1.9.10': + case '1.9.10.2': include 'update-db-1.9.0-1.10.0.inc.php'; include 'update-files-1.9.0-1.10.0.inc.php'; //Only updates the configuration.inc.php with the new version @@ -775,23 +751,8 @@ if (@$_POST['step2']) { } else { set_file_folder_permissions(); - $manager = testDbConnect( - $dbHostForm, - $dbUsernameForm, - $dbPassForm, - $dbNameForm - ); - - // Initialization of the database encoding to be used. - Database::query("SET storage_engine = INNODB;"); - //Database::query("SET SESSION character_set_server='utf8';"); - //Database::query("SET SESSION collation_server='utf8_general_ci';"); - //Database::query("SET CHARACTER SET 'utf8';"); // See task #1802. - //Database::query("SET NAMES 'utf8';"); - - include 'install_db.inc.php'; + $manager = require 'install_db.inc.php'; include 'install_files.inc.php'; - } display_after_install_message($installType); //Hide the "please wait" message sent previously diff --git a/main/install/install.lib.php b/main/install/install.lib.php index 0fec1481e0..e43f510e72 100755 --- a/main/install/install.lib.php +++ b/main/install/install.lib.php @@ -614,29 +614,6 @@ function get_config_param_from_db($host, $login, $pass, $dbName, $param = '') return null; } -/** - * Connects to the database server. - */ -function database_server_connect() -{ - global $dbHostForm, $dbUsernameForm, $dbPassForm; - if (($res = @Database::connect(array('server' => $dbHostForm, 'username' => $dbUsernameForm, 'password' => $dbPassForm))) === false) { - $no = Database::errno(); - $msg = Database::error(); - echo '
    #'.$no.': '.$msg.'
    '; - echo get_lang('DBServerDoesntWorkOrLoginPassIsWrong').'.

    '. - get_lang('PleaseCheckTheseValues').' :

    '. - ''.get_lang('DBHost').' : '.$dbHostForm.'
    '. - ''.get_lang('DBLogin').' : '.$dbUsernameForm.'
    '. - ''.get_lang('DBPassword').' : '.$dbPassForm.'

    '. - get_lang('PleaseGoBackToStep').' '. (defined('SYSTEM_INSTALLATION') ? '3' : '1').'.'. - '

    '. - ''; - exit (); - } - @Database::query("set session sql_mode='';"); // Disabling special SQL modes (MySQL 5) -} - /** * In step 3. Tests establishing connection to the database server. * If it's a single database environment the function checks if the database exist. @@ -662,23 +639,6 @@ function testDbConnect($dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm) return $database->getManager(); } -/** - * Fills the countries table with a list of countries. - * @param string $trackCountriesTable Table name - */ -function fill_track_countries_table($trackCountriesTable) -{ - $file_path = dirname(__FILE__).'/'.COUNTRY_DATA_FILENAME; - $countries = file($file_path); - $addCountrySql = "INSERT INTO $trackCountriesTable (id, code, country, counter) VALUES "; - foreach ($countries as $line) { - $elems = explode(',', $line); - $addCountrySql .= '('.intval($elems[0]).',\''.Database::escape_string($elems[1]).'\',\''.Database::escape_string($elems[2]).'\','.intval($elems[3]).'),'; - } - $addCountrySql = substr($addCountrySql, 0, -1); - @Database::query($addCountrySql); -} - /** * Creates the structure of the main database and fills it * with data. Placeholder symbols in the main database file @@ -688,7 +648,7 @@ function fill_track_countries_table($trackCountriesTable) * @param string $dbScript optional path about the script for database * @return void */ -function load_main_database($installation_settings, $dbScript = '') +function createSchema($manager, $installation_settings, $dbScript = '') { $sql_text = null; if (!empty($dbScript)) { @@ -702,122 +662,15 @@ function load_main_database($installation_settings, $dbScript = '') } } - //replace symbolic parameters with user-specified values foreach ($installation_settings as $key => $value) { $sql_text = str_replace($key, Database::escape_string($value), $sql_text); } - global $manager; $result = $manager->getConnection()->prepare($sql_text); $result->execute(); } -/** - * Get an SQL file's contents - * - * This function bases its parsing on the pre-set format of the specific SQL files in - * the install/upgrade procedure: - * Lines starting with "--" are comments (but need to be taken into account as they also hold sections names) - * Other lines are considered to be one-line-per-query lines (this is checked quickly by this function) - * @param string File to parse (in the current directory) - * @param string Section to return - * @param boolean Print (true) or hide (false) error texts when they occur - * @return array Array of SQL statements - */ -function get_sql_file_contents($file, $section, $print_errors = true) -{ - //check given parameters - if (empty($file)) { - $error = "Missing name of file to parse in get_sql_file_contents()"; - if ($print_errors) { - echo $error; - } - return false; - } - if (!in_array($section, array('main', 'user', 'stats', 'scorm', 'course'))) { - $error = "Section '$section' is not authorized in get_sql_file_contents()"; - if ($print_errors) { - echo $error; - } - return false; - } - $filePath = getcwd().'/'.$file; - if (!is_file($filePath) or !is_readable($filePath)) { - $error = "File $filePath not found or not readable in get_sql_file_contents()"; - if ($print_errors) { - echo $error; - } - return false; - } - //read the file in an array - // Empty lines should not be executed as SQL statements, because errors occur, see Task #2167. - $fileContents = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - if (!is_array($fileContents) or count($fileContents) < 1) { - $error = "File $filePath looks empty in get_sql_file_contents()"; - if ($print_errors) { - echo $error; - } - return false; - } - - //prepare the resulting array - $section_contents = array(); - $record = false; - foreach ($fileContents as $index => $line) { - if (substr($line, 0, 2) == '--') { - //This is a comment. Check if section name, otherwise ignore - $result = array(); - if (preg_match('/^-- xx([A-Z]*)xx/', $line, $result)) { //we got a section name here - if ($result[1] == strtoupper($section)) { - //we have the section we are looking for, start recording - $record = true; - } else { - //we have another section's header. If we were recording, stop now and exit loop - if ($record) { - break; - } - $record = false; - } - } - } else { - if ($record) { - if (!empty($line)) { - $section_contents[] = $line; - } - } - } - } - //now we have our section's SQL statements group ready, return - return $section_contents; -} - -/** - * Adds a new document to the database - specific to version 1.8.0 - * - * @param array $_course - * @param string $path - * @param string $fileType - * @param int $fileSize - * @param string $title - * @return id if inserted document - */ -function add_document_180($_course, $path, $fileType, $fileSize, $title, $comment = null) -{ - $table_document = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']); - $sql = "INSERT INTO $table_document - (`path`,`filetype`,`size`,`title`, `comment`) - VALUES ('$path','$fileType','$fileSize','". - Database::escape_string($title)."', '$comment')"; - if (Database::query($sql)) { - //display_message("Added to database (id ".Database::insert_id().")!"); - return Database::insert_id(); - } else { - //display_error("The uploaded file could not be added to the database (".Database::error().")!"); - return false; - } -} - /* DISPLAY FUNCTIONS */ /** @@ -1368,10 +1221,8 @@ function display_requirements( echo '
  • '.$value.'
  • '; } echo ''; - } - - // Check wether a Chamilo configuration file already exists. - elseif (file_exists(api_get_path(CONFIGURATION_PATH).'configuration.php')) { + } elseif (file_exists(api_get_path(CONFIGURATION_PATH).'configuration.php')) { + // Check wether a Chamilo configuration file already exists. echo '

    '; echo get_lang('WarningExistingLMSInstallationDetected'); echo '

    '; @@ -1713,7 +1564,6 @@ function display_database_settings_form( $database_exists_text = ''; $manager = null; try { - $manager = testDbConnect( $dbHostForm, $dbUsernameForm, @@ -1721,13 +1571,8 @@ function display_database_settings_form( null ); $databases = $manager->getConnection()->getSchemaManager()->listDatabases(); - if (in_array($dbNameForm, $databases)) { $database_exists_text = '
    '.get_lang('ADatabaseWithTheSameNameAlreadyExists').'
    '; - } else { - $manager->getConnection()->getSchemaManager()->createDatabase( - $dbNameForm - ); } } catch (Exception $e) { $database_exists_text = $e->getMessage(); @@ -1988,7 +1833,9 @@ function display_after_install_message($installType) echo ''; ?>
    - + + + getConnection()->getSchemaManager()->listDatabases(); - if (in_array($mysqlMainDb, $databases)) { - $create_database = false; + if (in_array($dbNameForm, $databases)) { + $createDatabase = false; } // Create database - if ($create_database) { - $manager->getConnection()->getSchemaManager()->createDatabase($mysqlMainDb); - /*$sql = "CREATE DATABASE IF NOT EXISTS `$mysqlMainDb`"; - Database::query($sql) or die(Database::error());*/ + if ($createDatabase) { + $manager->getConnection()->getSchemaManager()->createDatabase($dbNameForm); } + + $manager = testDbConnect( + $dbHostForm, + $dbUsernameForm, + $dbPassForm, + $dbNameForm + ); } // This parameter is needed to run a command line install of Chamilo (needed for Phing) @@ -107,8 +91,17 @@ $installation_settings['{HASHFUNCTIONMODE}'] = $encryptPassForm; AddCourse::drop_course_tables(); -load_main_database($installation_settings); +// Initialization of the database encoding to be used. +Database::query("SET storage_engine = INNODB;"); +Database::query("SET SESSION character_set_server='utf8';"); +Database::query("SET SESSION collation_server='utf8_general_ci';"); +Database::query("SET CHARACTER SET 'utf8';"); // See task #1802. +//Database::query("SET NAMES 'utf8';"); + +createSchema($manager, $installation_settings); -locking_settings(); +lockSettings(); update_dir_and_files_permissions(); + +return $manager; diff --git a/main/install/update-db-1.9.0-1.10.0.inc.php b/main/install/update-db-1.9.0-1.10.0.inc.php index 8d62224ef5..b60428480d 100644 --- a/main/install/update-db-1.9.0-1.10.0.inc.php +++ b/main/install/update-db-1.9.0-1.10.0.inc.php @@ -45,10 +45,6 @@ if (defined('SYSTEM_INSTALLATION')) { // that we want to change the main databases as well... $onlyTest = false; if (defined('SYSTEM_INSTALLATION')) { - - /** - * Update the databases "pre" migration - */ include_once '../lang/english/trad4all.inc.php'; if ($languageForm != 'english') { @@ -56,123 +52,21 @@ if (defined('SYSTEM_INSTALLATION')) { include_once '../lang/' . $languageForm . '/trad4all.inc.php'; } - // Get the main queries list (m_q_list) + // PRE $sqlFile = 'migrate-db-' . $oldFileVersion . '-' . $newFileVersion . '-pre.sql'; - $mainQueriesList = get_sql_file_contents($sqlFile, 'main'); - - if (count($mainQueriesList) > 0) { - // Now use the $mainQueriesList - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - Log::error('Database name ' . $dbNameForm . ' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database ' . $dbNameForm . ' was not found, skipping'); - } else { - foreach ($mainQueriesList as $query) { - if ($onlyTest) { - Log::notice("iDatabase::query($dbNameForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - } - } - } - - if (INSTALL_TYPE_UPDATE == 'update') { - // Updating track tables with c_id -> moved to migrate-db - - } + Log::notice('Starting migration: '.$oldFileVersion.' - '.$newFileVersion); + $sql = file_get_contents($sqlFile); + $result = $manager->getConnection()->prepare($sql); + $result->execute(); + + // Do something in between + + // POST + $sqlFile = 'migrate-db-' . $oldFileVersion . '-' . $newFileVersion . '-post.sql'; + $sql = file_get_contents($sqlFile); + $result = $manager->getConnection()->prepare($sql); + $result->execute(); } - - // Get the courses databases queries list (c_q_list) - - $sqlFile = 'migrate-db-'.$oldFileVersion.'-'.$newFileVersion.'-pre.sql'; - $courseQueriesList = get_sql_file_contents($sqlFile, 'course'); - Log::notice('Starting migration: '.$oldFileVersion.' - '.$newFileVersion); - - if (count($courseQueriesList) > 0) { - // Get the courses list - if (strlen($dbNameForm) > 40) { - Log::error('Database name '.$dbNameForm.' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database '.$dbNameForm.' was not found, skipping'); - } else { - $res = iDatabase::query( - "SELECT id, code, db_name, directory, course_language, id as real_id " - ." FROM course WHERE target_course_code IS NULL ORDER BY code" - ); - - if ($res === false) { - die('Error while querying the courses list in update_db-1.9.0-1.10.0.inc.php'); - } - $errors = array(); - - if (iDatabase::num_rows($res) > 0) { - $i = 0; - $list = array(); - while ($row = iDatabase::fetch_array($res)) { - $list[] = $row; - $i++; - } - - foreach ($list as $rowCourse) { - Log::notice('Course db ' . $rowCourse['db_name']); - - // Now use the $c_q_list - foreach ($courseQueriesList as $query) { - if ($singleDbForm) { - $query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$rowCourse['db_name']}_$2$3", $query); - } - if ($onlyTest) { - Log::notice("iDatabase::query(".$rowCourse['db_name'].",$query)"); - } else { - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in '.$query.': '.iDatabase::error()); - } - } - } - - Log::notice('<<<------- end -------->>'); - } - } - } - } - - // Get the main queries *POST* list (m_q_list) - $sqlFile = 'migrate-db-' . $oldFileVersion . '-' . $newFileVersion . '-post.sql'; - $mainQueriesList = get_sql_file_contents($sqlFile, 'main'); - - if (count($mainQueriesList) > 0) { - // Now use the $mainQueriesList - /** - * We connect to the right DB first to make sure we can use the queries - * without a database name - */ - if (strlen($dbNameForm) > 40) { - Log::error('Database name ' . $dbNameForm . ' is too long, skipping'); - } elseif (!in_array($dbNameForm, $dblist)) { - Log::error('Database ' . $dbNameForm . ' was not found, skipping'); - } else { - foreach ($mainQueriesList as $query) { - if ($onlyTest) { - Log::notice("iDatabase::query($dbNameForm,$query)"); - } else { - $res = iDatabase::query($query); - if ($res === false) { - Log::error('Error in ' . $query . ': ' . iDatabase::error()); - } - } - } - } - } - } else { echo 'You are not allowed here !' . __FILE__; } From 41c5916849b074a136b99af605b86b0339d23f9a Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 09:11:22 +0200 Subject: [PATCH 018/159] Fix typo --- plugin/buycourses/src/function.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/buycourses/src/function.php b/plugin/buycourses/src/function.php index db7244e8d3..35167cbdda 100644 --- a/plugin/buycourses/src/function.php +++ b/plugin/buycourses/src/function.php @@ -364,7 +364,7 @@ if ($_REQUEST['tab'] == 'save_currency') { $res = Database::query($sql); $sql = "UPDATE $tableBuyCourseCountry SET status='1' WHERE country_id='" . $id . "';"; $res = Database::query($sql); - if (!res) { + if (!$res) { $content = $plugin->get_lang('ProblemToSaveTheCurrencyType') . Database::error(); echo json_encode(array("status" => "false", "content" => $content)); } else { From a2144b6d5ab874d0d8f075eab6fd54c9a1c24bdb Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 09:12:10 +0200 Subject: [PATCH 019/159] Fix typos. --- plugin/buycourses/src/function.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/plugin/buycourses/src/function.php b/plugin/buycourses/src/function.php index 35167cbdda..4292a1d746 100644 --- a/plugin/buycourses/src/function.php +++ b/plugin/buycourses/src/function.php @@ -365,7 +365,7 @@ if ($_REQUEST['tab'] == 'save_currency') { $sql = "UPDATE $tableBuyCourseCountry SET status='1' WHERE country_id='" . $id . "';"; $res = Database::query($sql); if (!$res) { - $content = $plugin->get_lang('ProblemToSaveTheCurrencyType') . Database::error(); + $content = $plugin->get_lang('ProblemToSaveTheCurrencyType'); echo json_encode(array("status" => "false", "content" => $content)); } else { $content = get_lang('Saved'); @@ -386,7 +386,7 @@ if ($_REQUEST['tab'] == 'save_paypal') { WHERE id = '1';"; $res = Database::query($sql); - if (!res) { + if (!$res) { $content = $plugin->get_lang('ProblemToSaveThePaypalParameters') . Database::error(); echo json_encode(array("status" => "false", "content" => $content)); } else { @@ -403,7 +403,7 @@ if ($_REQUEST['tab'] == 'add_account') { VALUES ('" . $name . "','" . $account . "', '" . $swift . "');"; $res = Database::query($sql); - if (!res) { + if (!$res) { $content = $plugin->get_lang('ProblemToInsertANewAccount') . Database::error(); echo json_encode(array("status" => "false", "content" => $content)); } else { @@ -417,7 +417,7 @@ if ($_REQUEST['tab'] == 'delete_account') { $sql = "DELETE FROM $tableBuyCourseTransfer WHERE id='" . $id . "';"; $res = Database::query($sql); - if (!res) { + if (!$res) { $content = $plugin->get_lang('ProblemToDeleteTheAccount') . Database::error(); echo json_encode(array("status" => "false", "content" => $content)); } else { @@ -479,7 +479,7 @@ if ($_REQUEST['tab'] == 'clear_order') { $sql = "DELETE FROM $tableBuyCourseTemporal WHERE cod='" . $id . "';"; $res = Database::query($sql); - if (!res) { + if (!$res) { $content = $plugin->get_lang('ProblemToDeleteTheAccount') . Database::error(); echo json_encode(array("status" => "false", "content" => $content)); } else { From 80982cc02dbcebd8d8a4e68ba990c366a2234309 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 09:12:55 +0200 Subject: [PATCH 020/159] Remove use of Database::error() --- main/inc/lib/blog.lib.php | 18 ++++++++---------- main/newscorm/aicc.class.php | 6 +++--- main/newscorm/scorm.class.php | 2 +- main/reports/reports.cli.php | 19 ++++++++----------- main/reports/reports.cron.php | 6 ++---- main/webservices/registration.soap.php | 3 +-- main/wiki/wiki.inc.php | 8 ++++---- plugin/buycourses/src/function.php | 10 +++++----- 8 files changed, 32 insertions(+), 40 deletions(-) diff --git a/main/inc/lib/blog.lib.php b/main/inc/lib/blog.lib.php index 8a705f6c6c..5fd5d537c4 100755 --- a/main/inc/lib/blog.lib.php +++ b/main/inc/lib/blog.lib.php @@ -2129,16 +2129,14 @@ class Blog $row[] = Display::icon_mailto_link($myrow["email"]); $sql = "SELECT bt.title task - FROM " . Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER) . " btu - INNER JOIN " . Database::get_course_table(TABLE_BLOGS_TASKS) . " bt ON btu.task_id = bt.task_id - WHERE btu.c_id = $course_id AND - bt.c_id = $course_id AND - btu.blog_id = $blog_id AND - btu.user_id = " . $myrow['user_id']; - - if (!($sql_res = Database::query($sql))) { - die(Database::error()); - } + FROM " . Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER) . " btu + INNER JOIN " . Database::get_course_table(TABLE_BLOGS_TASKS) . " bt + ON btu.task_id = bt.task_id + WHERE btu.c_id = $course_id AND + bt.c_id = $course_id AND + btu.blog_id = $blog_id AND + btu.user_id = " . $myrow['user_id']; + $sql_res = Database::query($sql); $task = ''; diff --git a/main/newscorm/aicc.class.php b/main/newscorm/aicc.class.php index e9c99a59d6..deb322b6cb 100755 --- a/main/newscorm/aicc.class.php +++ b/main/newscorm/aicc.class.php @@ -283,13 +283,13 @@ class aicc extends learnpath "$parent, $previous, 0, " . "'$prereq', 0" . ")"; - $res_item = Database::query($sql_item); - if ($this->debug > 1) { error_log('New LP - In aicc::import_aicc() - inserting item : '.$sql_item.' : '.Database::error(), 0); } + Database::query($sql_item); + if ($this->debug > 1) { error_log('New LP - In aicc::import_aicc() - inserting item : '.$sql_item.' : ', 0); } $item_id = Database::insert_id(); // Now update previous item to change next_item_id. if ($previous != 0) { $upd = "UPDATE $new_lp_item SET next_item_id = $item_id WHERE c_id = $course_id AND id = $previous"; - $upd_res = Database::query($upd); + Database::query($upd); // Update the previous item id. } $previous = $item_id; diff --git a/main/newscorm/scorm.class.php b/main/newscorm/scorm.class.php index 8ca90fdc44..fa7d62bd5c 100755 --- a/main/newscorm/scorm.class.php +++ b/main/newscorm/scorm.class.php @@ -398,7 +398,7 @@ class scorm extends learnpath VALUES ($course_id, $lp_id, '$type', '$identifier', '$title', '$path' , 0, $max_score, $value_add $parent, $previous, 0, '$prereq', ".$item['rel_order'] .", '".$item['datafromlms']."', '".$item['parameters']."' )"; Database::query($sql); - if ($this->debug > 1) { error_log('New LP - In import_manifest(), inserting item : '.$sql.' : '.Database::error(), 0); } + if ($this->debug > 1) { error_log('New LP - In import_manifest(), inserting item : '.$sql, 0); } $item_id = Database::insert_id(); // Now update previous item to change next_item_id. $upd = "UPDATE $new_lp_item SET next_item_id = $item_id WHERE c_id = $course_id AND id = $previous"; diff --git a/main/reports/reports.cli.php b/main/reports/reports.cli.php index 8cbff96fd6..5ee9644d28 100755 --- a/main/reports/reports.cli.php +++ b/main/reports/reports.cli.php @@ -1,4 +1,6 @@ diff --git a/main/reports/reports.cron.php b/main/reports/reports.cron.php index 6c9a121cb2..8feb34e600 100755 --- a/main/reports/reports.cron.php +++ b/main/reports/reports.cron.php @@ -1,10 +1,8 @@ diff --git a/main/webservices/registration.soap.php b/main/webservices/registration.soap.php index 587de59993..325be32402 100755 --- a/main/webservices/registration.soap.php +++ b/main/webservices/registration.soap.php @@ -1085,10 +1085,9 @@ function WSCreateUserPasswordCrypted($params) { } } } else { - $error = Database::error(); - if ($debug) error_log($error); return 0; } + return $return; } diff --git a/main/wiki/wiki.inc.php b/main/wiki/wiki.inc.php index 402d094e62..9014db31fa 100755 --- a/main/wiki/wiki.inc.php +++ b/main/wiki/wiki.inc.php @@ -3173,7 +3173,7 @@ class Wiki $message_author = api_get_user_id(); $sql="INSERT INTO $tbl_wiki_discuss (c_id, publication_id, userc_id, comment, p_score, dtime) VALUES ($course_id, '".$id."','".$message_author."','".Database::escape_string($_POST['comment'])."','".Database::escape_string($_POST['rating'])."','".$dtime."')"; - $result=Database::query($sql) or die(Database::error()); + $result = Database::query($sql); self::check_emailcue($id, 'D', $dtime, $message_author); } }//end discuss lock @@ -3184,7 +3184,7 @@ class Wiki $sql="SELECT * FROM $tbl_wiki_discuss reviews, $user_table user WHERE reviews.c_id = $course_id AND reviews.publication_id='".$id."' AND user.user_id='".$firstuserid."' ORDER BY id DESC"; - $result=Database::query($sql) or die(Database::error()); + $result=Database::query($sql); $countWPost = Database::num_rows($result); echo get_lang('NumComments').": ".$countWPost; //comment's numbers @@ -3193,12 +3193,12 @@ class Wiki FROM $tbl_wiki_discuss WHERE c_id = $course_id AND publication_id = '".$id."' AND NOT p_score='-' ORDER BY id DESC"; - $result2=Database::query($sql) or die(Database::error()); + $result2=Database::query($sql); $row2=Database::fetch_array($result2); $sql = "SELECT * FROM $tbl_wiki_discuss WHERE c_id = $course_id AND publication_id='".$id."' AND NOT p_score='-'"; - $result3=Database::query($sql) or die(Database::error()); + $result3=Database::query($sql); $countWPost_score= Database::num_rows($result3); echo ' - '.get_lang('NumCommentsScore').': '.$countWPost_score;// diff --git a/plugin/buycourses/src/function.php b/plugin/buycourses/src/function.php index 4292a1d746..30a3488d18 100644 --- a/plugin/buycourses/src/function.php +++ b/plugin/buycourses/src/function.php @@ -387,7 +387,7 @@ if ($_REQUEST['tab'] == 'save_paypal') { $res = Database::query($sql); if (!$res) { - $content = $plugin->get_lang('ProblemToSaveThePaypalParameters') . Database::error(); + $content = $plugin->get_lang('ProblemToSaveThePaypalParameters'); echo json_encode(array("status" => "false", "content" => $content)); } else { $content = get_lang('Saved'); @@ -404,7 +404,7 @@ if ($_REQUEST['tab'] == 'add_account') { $res = Database::query($sql); if (!$res) { - $content = $plugin->get_lang('ProblemToInsertANewAccount') . Database::error(); + $content = $plugin->get_lang('ProblemToInsertANewAccount'); echo json_encode(array("status" => "false", "content" => $content)); } else { $content = get_lang('Saved'); @@ -418,7 +418,7 @@ if ($_REQUEST['tab'] == 'delete_account') { $sql = "DELETE FROM $tableBuyCourseTransfer WHERE id='" . $id . "';"; $res = Database::query($sql); if (!$res) { - $content = $plugin->get_lang('ProblemToDeleteTheAccount') . Database::error(); + $content = $plugin->get_lang('ProblemToDeleteTheAccount'); echo json_encode(array("status" => "false", "content" => $content)); } else { $content = get_lang('Saved'); @@ -452,7 +452,7 @@ if ($_REQUEST['tab'] == 'save_mod') { $res = Database::query($sql); if (!$res) { - $content = $plugin->get_lang('ProblemToSaveTheMessage') . Database::error(); + $content = $plugin->get_lang('ProblemToSaveTheMessage'); echo json_encode(array("status" => "false", "content" => $content)); } else { echo json_encode(array("status" => "true", "course_id" => $id)); @@ -480,7 +480,7 @@ if ($_REQUEST['tab'] == 'clear_order') { $res = Database::query($sql); if (!$res) { - $content = $plugin->get_lang('ProblemToDeleteTheAccount') . Database::error(); + $content = $plugin->get_lang('ProblemToDeleteTheAccount'); echo json_encode(array("status" => "false", "content" => $content)); } else { $content = get_lang('Saved'); From 0c0a2bf1443bc4f16aebdbb9b79f7410c3ce2c2d Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 09:30:57 +0200 Subject: [PATCH 021/159] Remove metadata code see #1370 --- main/document/edit_document.php | 5 +- main/inc/lib/add_course.lib.inc.php | 1 - main/inc/lib/database.constants.inc.php | 3 - main/inc/lib/document.lib.php | 16 - main/inc/lib/fileManage.lib.php | 14 - main/inc/lib/xht.lib.php | 552 ----------- main/inc/lib/xmd.lib.php | 883 ------------------ main/install/database.sql | 13 +- main/install/migrate-db-1.9.0-1.10.0-pre.sql | 4 +- main/metadata/doc/CourseKwds.xml | 116 --- main/metadata/doc/Metadata_for_Chamilo.html | 655 ------------- main/metadata/doc/SelKwds.xsl | 533 ----------- main/metadata/doc/dcex.php | 23 - main/metadata/doc/imsmanifest_reload.xml | 189 ---- main/metadata/doc/mdApiTest.php | 140 --- main/metadata/doc/mdp_scorm.htt | 61 -- main/metadata/doc/testMiniDom.php | 241 ----- main/metadata/doc/testXht.php | 215 ----- main/metadata/importdocs.php | 106 --- main/metadata/importlinks.php | 355 ------- main/metadata/importmanifest.php | 662 ------------- main/metadata/index.php | 186 ---- main/metadata/md_document.htt | 262 ------ main/metadata/md_document.php | 189 ---- main/metadata/md_editxml.htt | 21 - main/metadata/md_funcs.php | 406 -------- main/metadata/md_link.htt | 202 ---- main/metadata/md_link.php | 256 ----- main/metadata/md_mix.php | 85 -- main/metadata/md_phpdig.php | 215 ----- main/metadata/md_scorm.htt | 17 - main/metadata/md_scorm.php | 106 --- main/metadata/md_script.js | 577 ------------ main/metadata/md_styles.css | 25 - main/metadata/mds_mix.htt | 115 --- main/metadata/openobject.php | 32 - main/metadata/phpdig/CourseKwds_example.js | 79 -- main/metadata/phpdig/CourseKwds_example.jsc | 11 - main/metadata/phpdig/config.php | 450 --------- main/metadata/phpdig/en-language.php | 199 ---- main/metadata/phpdig/phpdig_functions.php | 279 ------ main/metadata/phpdig/search.php | 295 ------ main/metadata/phpdig/search_function.php | 785 ---------------- .../phpdig/update_db_to_1_8_6_from_1_8_3.sql | 35 - main/metadata/playscormmdset.inc.php | 215 ----- main/metadata/search.php | 149 --- main/metadata/statistics.php | 133 --- main/metadata/update_indexabletext.php | 67 -- main/newscorm/learnpath_functions.inc.php | 171 ---- main/newscorm/lp_edit.php | 16 - 50 files changed, 5 insertions(+), 10360 deletions(-) delete mode 100755 main/inc/lib/xht.lib.php delete mode 100755 main/inc/lib/xmd.lib.php delete mode 100755 main/metadata/doc/CourseKwds.xml delete mode 100644 main/metadata/doc/Metadata_for_Chamilo.html delete mode 100755 main/metadata/doc/SelKwds.xsl delete mode 100755 main/metadata/doc/dcex.php delete mode 100755 main/metadata/doc/imsmanifest_reload.xml delete mode 100755 main/metadata/doc/mdApiTest.php delete mode 100755 main/metadata/doc/mdp_scorm.htt delete mode 100755 main/metadata/doc/testMiniDom.php delete mode 100755 main/metadata/doc/testXht.php delete mode 100755 main/metadata/importdocs.php delete mode 100755 main/metadata/importlinks.php delete mode 100755 main/metadata/importmanifest.php delete mode 100755 main/metadata/index.php delete mode 100755 main/metadata/md_document.htt delete mode 100755 main/metadata/md_document.php delete mode 100755 main/metadata/md_editxml.htt delete mode 100755 main/metadata/md_funcs.php delete mode 100755 main/metadata/md_link.htt delete mode 100755 main/metadata/md_link.php delete mode 100755 main/metadata/md_mix.php delete mode 100755 main/metadata/md_phpdig.php delete mode 100755 main/metadata/md_scorm.htt delete mode 100755 main/metadata/md_scorm.php delete mode 100755 main/metadata/md_script.js delete mode 100755 main/metadata/md_styles.css delete mode 100755 main/metadata/mds_mix.htt delete mode 100755 main/metadata/openobject.php delete mode 100755 main/metadata/phpdig/CourseKwds_example.js delete mode 100755 main/metadata/phpdig/CourseKwds_example.jsc delete mode 100755 main/metadata/phpdig/config.php delete mode 100755 main/metadata/phpdig/en-language.php delete mode 100755 main/metadata/phpdig/phpdig_functions.php delete mode 100755 main/metadata/phpdig/search.php delete mode 100755 main/metadata/phpdig/search_function.php delete mode 100755 main/metadata/phpdig/update_db_to_1_8_6_from_1_8_3.sql delete mode 100755 main/metadata/playscormmdset.inc.php delete mode 100755 main/metadata/search.php delete mode 100755 main/metadata/statistics.php delete mode 100755 main/metadata/update_indexabletext.php diff --git a/main/document/edit_document.php b/main/document/edit_document.php index b6600007ec..6b9008e371 100755 --- a/main/document/edit_document.php +++ b/main/document/edit_document.php @@ -458,12 +458,9 @@ if ($owner_id == api_get_user_id() || } if (!$group_document && !DocumentManager::is_my_shared_folder(api_get_user_id(), $currentDirPath, $sessionId)) { - $metadata_link = ''.get_lang('AddMetadata').''; - - //Updated on field + // Updated on field $last_edit_date = api_get_local_time($last_edit_date); $display_date = date_to_str_ago($last_edit_date).' '.api_format_date($last_edit_date).''; - $form->addElement('static', null, get_lang('Metadata'), $metadata_link); $form->addElement('static', null, get_lang('UpdatedOn'), $display_date); } diff --git a/main/inc/lib/add_course.lib.inc.php b/main/inc/lib/add_course.lib.inc.php index e87db94b56..fff35f85a4 100755 --- a/main/inc/lib/add_course.lib.inc.php +++ b/main/inc/lib/add_course.lib.inc.php @@ -284,7 +284,6 @@ class AddCourse $tables[] = 'thematic'; $tables[] = 'thematic_plan'; $tables[] = 'thematic_advance'; - $tables[] = 'metadata'; return $tables; } diff --git a/main/inc/lib/database.constants.inc.php b/main/inc/lib/database.constants.inc.php index ec59e713ea..29a94174b1 100755 --- a/main/inc/lib/database.constants.inc.php +++ b/main/inc/lib/database.constants.inc.php @@ -294,9 +294,6 @@ define('TABLE_NOTEBOOK', 'notebook'); define('TABLE_MESSAGE', 'message'); define('TABLE_MESSAGE_ATTACHMENT', 'message_attachment'); -// Metadata -define('TABLE_METADATA', 'metadata'); - // Attendance Sheet define('TABLE_ATTENDANCE', 'attendance'); define('TABLE_ATTENDANCE_CALENDAR', 'attendance_calendar'); diff --git a/main/inc/lib/document.lib.php b/main/inc/lib/document.lib.php index af480b576d..93ce07c9ba 100755 --- a/main/inc/lib/document.lib.php +++ b/main/inc/lib/document.lib.php @@ -1045,25 +1045,9 @@ class DocumentManager $sql = "DELETE FROM $TABLE_DOCUMENT WHERE c_id = {$course_info['real_id']} AND id = ".$document_id; Database::query($sql); - self::delete_document_metadata($document_id); } } - /** - * @param int $document_id - */ - public static function delete_document_metadata($document_id) - { - // needed to deleted medadata - require_once api_get_path(SYS_CODE_PATH) . 'metadata/md_funcs.php'; - $mdStore = new mdstore(true); - - //delete metadata - $eid = 'Document' . '.' . $document_id; - $mdStore->mds_delete($eid); - $mdStore->mds_delete_offspring($eid); - } - /** * This deletes a document by changing visibility to 2, renaming it to filename_DELETED_#id * Files/folders that are inside a deleted folder get visibility 2 diff --git a/main/inc/lib/fileManage.lib.php b/main/inc/lib/fileManage.lib.php index 610d184b23..f79bb02740 100755 --- a/main/inc/lib/fileManage.lib.php +++ b/main/inc/lib/fileManage.lib.php @@ -25,20 +25,6 @@ function update_db_info($action, $old_path, $new_path = '') $old_path = Database::escape_string($old_path); $to_delete = "WHERE c_id = $course_id AND (path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%')"; $query = "DELETE FROM $dbTable " . $to_delete; - $result = Database::query("SELECT id FROM $dbTable " . $to_delete); - - if (Database::num_rows($result)) { - require_once api_get_path(INCLUDE_PATH).'../metadata/md_funcs.php'; - $mdStore = new mdstore(TRUE); // create if needed - - $md_type = (substr($dbTable, -13) == 'scormdocument') ? 'Scorm' : 'Document'; - - while ($row = Database::fetch_array($result)) { - $eid = $md_type . '.' . $row['id']; - $mdStore->mds_delete($eid); - $mdStore->mds_delete_offspring($eid); - } - } Database::query($query); break; case 'update': diff --git a/main/inc/lib/xht.lib.php b/main/inc/lib/xht.lib.php deleted file mode 100755 index 6652c11d84..0000000000 --- a/main/inc/lib/xht.lib.php +++ /dev/null @@ -1,552 +0,0 @@ - - - - - - -*/ - -/** -* This is an XML HTML template library. -* Include/require it in your code to use its functionality. -* -* This library defines function xht_htmlwchars & class xhtdoc with methods: -* - xht_fill_template($template_name) -* - xht_substitute($subtext) -* -* Check htt_error after defining a new xhtdoc(htt_file_contents). -* -* Assign xht_xmldoc (, xht_get_lang, xht_resource, xht_dbgn) -* before calling the class methods. -* -* @package chamilo.library -*/ - - - -function xht_htmlwchars($s) // use only where ISO-8859-1 is not required! -{ - //return ereg_replace('\[((/?(b|big|i|small|sub|sup|u))|br/)\]', '<\\1>', - // str_replace('@�@', '&', - // htmlspecialchars(ereg_replace('&#([0-9]+);', '@�@#\\1;', $s)))); - global $charset; - return api_ereg_replace('\[((/?(b|big|i|small|sub|sup|u))|br/)\]', '<\\1>', - str_replace('@�@', '&', - htmlspecialchars(api_ereg_replace('&#([0-9]+);', '@�@#\\1;', $s), ENT_QUOTES, $charset))); - // replaces htmlspecialchars for double-escaped xml chars like '&#nnn;' - // and when html tags <...> are represented as [...] -} - -function xht_is_assoclist($s) // ":key1:value1,, key2:value2,, ..." -{ - return is_string($s) && strpos($s, ',,'); -} - -function xht_explode_assoclist($s) -{ - $result = array(); if (!xht_is_assoclist($s)) return $result; - - foreach (explode(',,', api_substr($s, 1)) as $keyplusvalue) - if ($cp = api_strpos($keyplusvalue, api_substr($s, 0, 1))) - $result[trim(api_substr($keyplusvalue, 0, $cp))] = - api_substr($keyplusvalue, $cp+1); - - return $result; -} - - -class xhtdoc -{ - -var $htt_array; // array with HTML templates -var $htt_error; // error while parsing htt_file_contents to templates - -var $xht_xmldoc; // XML Mini-DOM document for which templates are processed -var $xht_param; // parameter array for template processing -var $xht_get_lang; // user-supplied function for {-L xx-}, e.g. Dokeos get_lang -var $xht_resource; // user-supplied function for '=/' in path - -var $xht_dbgn; // set to a positive value for debugging output -var $xht_dbgo; // debugging output accumulates here - -var $_prev_param; // old parameter values - - -function xht_fill_template($template_name, $cur_elem = 0) -{ - $template_name = trim($template_name); - if (!$template_name || (api_strpos($template_name, ' ') !== FALSE)) return ''; - if (!is_string($httext = $this->htt_array[$template_name])) return ''; - - if ($this->xht_dbgn) $this->xht_dbgo .= '\n"; - - $prev_lpp = 0; $prev_sub = ''; $scanpos = 0; - - while (($rpp = api_strpos($httext, XHT_RP, $scanpos)) !== FALSE) // first -} - { - if (($lpp = api_strpos($httext, XHT_LP)) === FALSE) break; // no {- for -} - if ($lpp > $rpp) break; // no {- preceding -} - - while (($next_lpp = api_strpos($httext, XHT_LP, $lpp + XHT_PL)) !== FALSE) - if ($next_lpp > $rpp) break; - else $lpp = $next_lpp; // find {- closest to -} - - $subtext = api_substr($httext, $lpp + XHT_PL, $rpp - $lpp - XHT_PL); - - $httext = api_substr($httext, 0, $lpp) . - $this->xht_substitute($subtext, $cur_elem, XHT_LP, XHT_RP) . - api_substr($httext, $rpp + XHT_PL); // substitute or leave intact - - if ($lpp == $prev_lpp && $subtext == $prev_sub) // prevent looping - { - $scanpos = $rpp + 1; $prev_lpp = 0; $prev_sub = ''; - } - else - { - $prev_lpp = $lpp; $prev_sub = $subtext; - } - } - - return $httext; -} - - -function xht_substitute($subtext, $cur_elem = 0, $pre = '', $post = '') -{ - global $charset; - - $regs = array(); // for use with ereg() - if (!api_ereg(XHT_SUBS2, $subtext, $regs) && !api_ereg(XHT_SUBS1, $subtext, $regs)) - return $pre . $subtext . $post; - - $type = $regs[1]; $text = $regs[2]; $result = ''; $subnum = FALSE; - $subtext = isset($regs[3]) ? $regs[3] : ''; - - if ($this->xht_dbgn) // generate debugging output, with new number $subnum - { - $subnum = ++ $this->xht_dbgn; - $this->xht_dbgo .= '\n"; - } - - if ($type == 'D') // Define, e.g. {-D key value-} - { - // Assign the value to parameter [key] - $this->xht_param[$text] = $subtext; - // used to be: = $this->xht_substitute($subtext, $cur_elem); - } - elseif ($type == 'E') // Escape, e.g. {-E userFunction subtext-} - { - $result = call_user_func($text, FALSE); // get cached result, if any - - if ($result === FALSE) // no cached result available - { - $result = $this->xht_substitute($subtext, $cur_elem); - $result = call_user_func($text, $result); // allow to cache - } - } - elseif ($type == 'R') // Repeat, e.g. {-R general/title/string subtext-} - { - $rdepthn = 'rdepth' . (++ $this->xht_param['rdepth']); - $n = 0; $this->xht_param['number'] = '0'; - - if (is_array($a = $this->_lang($text, $cur_elem))) // repeat on array - { - foreach ($a as $key => $value) - { - $this->xht_param['number'] = (string) (++ $n); - $this->xht_param[$rdepthn] = (string) ($n); - $this->xht_param['key'] = $key; - $this->xht_param['value'] = $value; - $result .= $this->xht_substitute($subtext, $cur_elem); - } - } - elseif (xht_is_assoclist($a)) // repeat on associative list - { - foreach (xht_explode_assoclist($a) as $key => $value) - { - $this->xht_param['number'] = (string) (++ $n); - $this->xht_param[$rdepthn] = (string) ($n); - $this->xht_param['key'] = $key; - $this->xht_param['value'] = $value; - $result .= $this->xht_substitute($subtext, $cur_elem); - } - } - elseif (!is_object($this->xht_xmldoc)) - { - $result = '? R Error: no XML doc has been assigned to xht_xmldoc'; - } - else // repeat on XML elements - { - $sub_elems = - $this->xht_xmldoc->xmd_select_elements($text, $cur_elem); - - foreach ($sub_elems as $subElem) - { - $this->xht_param['number'] = (string) (++ $n); - $this->xht_param[$rdepthn] = (string) ($n); - $result .= $this->xht_substitute($subtext, $subElem); - } - } - // removed 2004/10/05: template_array (security) - // added 2005/03/08: associative list (lang arrays deprecated) - - $this->xht_param['rdepth'] --; - - // As there is only one ['number'] or one set ['key'] + ['value'], - // using them in nested repeats may not have the desired result. - } - elseif ($type == 'T') // Test, e.g. {-T key1 == key2 text-} - { - if (api_ereg('^(=|==|<=|<|!=|<>|>|>=) +([^ ]+) +(.*)$', $subtext, $regs)) - { - // Comparand= parameter value if set, else languagevar value - - $cmp1 = isset($this->xht_param[$text]) ? - $this->xht_param[$text] : $this->_lang($text, $cur_elem); - $cmp3 = isset($this->xht_param[$cmp3 = $regs[2]]) ? - $this->xht_param[$cmp3] : $this->_lang($cmp3, $cur_elem); - $cmp = strcmp($cmp1, $cmp3); $op = ' ' . $regs[1] . ' '; - - if ($subnum) $this->xht_dbgo .= '\n"; // debugging output - - if ( ($cmp < 0 && api_strpos(' <= < != <> ', $op)) || - ($cmp == 0 && api_strpos(' = == <= >= ', $op)) || - ($cmp > 0 && api_strpos(' != <> > >= ', $op)) ) - $result = $this->xht_substitute($regs[3], $cur_elem); - // else $result is empty - } - else - { - $result = $pre . $subtext . $post; - } - } - else - { - if (api_strpos('CLPVX', $type) !== FALSE) // used to be always - $text = $this->xht_substitute($text, $cur_elem); // nested escape - - if ($type == 'C') // Call, e.g. {-C SUBTEMPLATE-} - $result = $this->xht_fill_template($text, $cur_elem); - elseif ($type == 'H') $result = htmlspecialchars($text, ENT_QUOTES, $charset); - elseif ($type == 'L') $result = $this->_lang($text, $cur_elem); - elseif ($type == 'P') $result = $this->xht_param[$text]; - elseif ($type == 'U') $result = urlencode($text); - elseif ($type == 'W') $result = xht_htmlwchars($text); - elseif (!is_object($this->xht_xmldoc)) - { - $result = '? V/X Error: no XML doc has been assigned to xht_xmldoc'; - } - else // $type == 'V' or 'X' - { - - if (api_ereg('^(.*)=/(.+)$', $text, $regs)) // special resource-marker - { - $path = $regs[1]; $text = $regs[2]; - if (api_substr($path, -1) == '/') $path = api_substr($path, 0, -1); - - if ($path) $cur_elem = $this->xht_xmldoc-> - xmd_select_single_element($path, $cur_elem); - - $cur_elem = call_user_func($this->xht_resource, $cur_elem); - } - - $result = ($type == 'V') ? - $this->xht_xmldoc->xmd_value($text, $cur_elem) : - $this->xht_xmldoc-> - xmd_html_value($text, $cur_elem, 'xht_htmlwchars'); - } - } - - if ($subnum) $this->xht_dbgo .= '\n"; - - return $result; -} - - -function xht_add_template($template_name, $httext) -{ - $this->htt_array[$template_name] = $httext; - // removed 2004/10/05: (substr($httext, 0, 6) == 'array(') ? - // removed 2004/10/05: @eval('return ' . $httext . ';') : $httext; - - if (!$this->htt_array[$template_name]) - { - $this->htt_error = 'template ' . $template_name . - ' is empty or invalid'; return; - } -} - - -function xhtdoc($htt_file_contents) -{ - $htt_file_contents = // normalize \r (Mac) and \r\n (Windows) to \n - str_replace("\r", "\n", str_replace("\r\n", "\n", $htt_file_contents)); - - while (api_substr($htt_file_contents, -1) == "\n") - $htt_file_contents = api_substr($htt_file_contents, 0, -1); - - $last_line = api_strrchr($htt_file_contents, "\n"); $this->htt_error = ''; - - if (api_strlen($last_line) < 12 || api_substr($last_line, 0, 6) != "\n") - { - $this->htt_error = 'last line must be of the form '; - return; - } - - define('XHT_PL', (int) (api_strlen($last_line) - 10) / 2); // Parentheses Lth - define('XHT_LP', api_substr($last_line, 6, XHT_PL)); // Left Par - define('XHT_RP', api_substr($last_line, 6 + XHT_PL, XHT_PL)); // Right Par - - if (XHT_LP == XHT_RP) - { - $this->htt_error = - 'parentheses in last line must not be identical'; - return; - } - - $this->htt_array = array(); // named elements are arrays and strings - - foreach (explode("\n\n"))) - { - $template_name = trim(api_substr($name_and_text, 0, $name_length)); - - if (api_strpos($template_name, ' ') !== FALSE) give_up('Template ' . - $template_name . ' has a space in its name'); - $httext = api_substr($name_and_text, $name_length + XHT_PL + 5); - - while (api_substr($httext, 0, 1) == "\n") $httext = api_substr($httext, 1); - while (api_substr($httext, -1) == "\n") $httext = api_substr($httext,0,-1); - - $this->xht_add_template($template_name, $httext); - } - } - - define('XHT_SUBS1', '^(C|H|L|P|U|V|W|X) +(.*)$'); // substitution types 1: - // Call, Htmlchars, Lang, Param, Urlencode, Value, Wchars, Xvalue - define('XHT_SUBS2', '^(D|E|R|T) +([^ ]+) +(.*)$'); // substitution types 2: - // Define, Escape, Repeat, Test - - $this->xht_dbgo = ''; - - $this->xht_param = array(0 => '0', 1 => '1', - '' => '', 'empty' => '', 'rdepth' => 0); - $this->_prev_param = $this->xht_param; - // empty: {-R * P empty-} puts the number of subelements in {-P number-} - // rdepth: current number of nested R's - // rdepth1, rdepth2, ...: key or number, see R -} - - -function _show_param() // for debugging info -{ - global $charset; - $result = ''; - foreach ($this->xht_param as $k => $v) - if ($v !== $this->_prev_param[$k]) { - $this->_prev_param[$k] = $v; $result .= ', ' . $k . ': ' . - ((api_strlen($v) <= 20) ? $v : api_substr($v, 0, 17).'...'); - } - return $result ? htmlspecialchars(api_substr($result, 1), ENT_QUOTES, $charset) : ''; -} - -function _lang($var, $cur_elem = 0) -{ - $result = @call_user_func($this->xht_get_lang, $var, $cur_elem); - - // This is a hack for proper working of the language selectors - // in the forms that are generated through templates. - if ($var == 'Langs') - { - global $langLangs; - if (isset($langLangs)) - { - $result = $langLangs; - } - } - - return isset($result) ? $result : $var; -} - - -} - -/* - -A word of explanation... - -The last line of a template file (example below) defines the special markers -that are used around template names such as INPUT and OPTION and around HTML -escapes such as 'P value' and 'L Store', { and } in the example. You can also -use markers of more than one character as long as both have the same length, -e.g. <% and %>. The markers must not be equal. In templates with JavaScript -or - - -

    {H {L Tool}: {P entry}}

    - - - - - - -{R general/keyword C KEYWORD} -
    {D label {L Language}}{D tip {L LanguageTip}}{C LABEL}
    - - - - -{H {P label}} : - - - - - - - {D label {L Keyword}}{D tip {L KeywordTip}}{C LABEL} - - {D value {X string}}{D title general/keyword[{P number}]/string}{C INPUT} - - - --------------------------------------------------------------------------------- - - -*/ - -?> diff --git a/main/inc/lib/xmd.lib.php b/main/inc/lib/xmd.lib.php deleted file mode 100755 index 624b868694..0000000000 --- a/main/inc/lib/xmd.lib.php +++ /dev/null @@ -1,883 +0,0 @@ - - - - - - -*/ - -/** -* This is the XML Dom library for Dokeos. -* Include/require it in your code to use its functionality. -* -* @author René Haentjens -* @package chamilo.library -*/ - -class xmddoc -{ - /* This MiniDom for XML essentially implements an array of elements, each - with a parent, a name, a namespace-URI, attributes & namespace definitions, - and children. Child nodes are a mix of texts and subelements. Parent - and subelements are stored as elementnumbers, the root is element 0. - - Parsing is built on James Clark's expat, by default enabled in PHP. - - The MiniDom is an alternative to the experimental DOM XML functions. - It is open source PHP and requires no extra libraries. - - Restrictions of the MiniDom: - - no two attributes with same name (different namespaces) on one element; - - only 'ISO-8859-1' right now; author will investigate 'UTF-8' later; - - processing instructions & external entities are ignored; - - no distinction between text and cdata child nodes; - - xmd_xml(nonrootelement) may not generate all needed namespace definitions; - - xmd_value, xmd_html_value, xmd_select_xxx, xmd_update, xmd_update_many: - path parameter uses names without namespaces - and supports only a small subset of XPath, with some extensions; - - maximum 11 auto-generated namespace prefixes (can be changed in xmddoc) - - Namespace definitions are stored as attributes, with name = 'xmlns...' - e.g. xmlns:xml='http://www.w3.org/XML/1998/namespace' - e.g. xmlns='http://www.imsglobal.org/xsd/imscp_v1p1' (default namespace) - - Exposed methods: - - new xmddoc(array_of_strings, charset = 'ISO-8859-1'): parse strings - new xmddoc(names, numbers, textstring): restore from cached arrays & string - - xmd_add_element(complete_name, parent, attributes_with_complete_names) - complete name = [ URI + ':' + ] name - xmd_set_attribute(element, complete_attribute_name, value) (id. as above) - xmd_add_text(text, element) - xmd_add_text_element(complete_name, text, parent, attributes) = - xmd_add_text(text, xmd_add_element(complete_name, parent, attributes)) - - xmd_get_element(element) => children, attributes, '?name', '?parent' - xmd_get_ns_uri(element [, attribute_name_without_uri] ) - - xmd_text(element): combines element and subelements' text nodes - xmd_xml(): generate XML-formatted string (reverse parsing) - xmd_xml(indent_increase, initial_indent, lbr): e.g. ' ', '', "\n" - - xmd_value(path): follow path from root, return attribute value or text - e.g. 'manifest/organizations/@default' 'body/p[1]' (1=first, -1=last) - xmd_value(path, parent, fix, function): find value(s) with path from parent, - apply function and decorate with fix = ('pre'=>..., 'in'=>..., 'post') - e.g. 'general/title/*' array('in' => ', ') - extensions to XPath: - - and + for previous and next sibling, e.g. general/title/+/string - -name and +name for sibling with specific name, e.g. item[2]/+item - .. for parent, e.g. general/title/../../technical/format (stops at root) - @* for location (element number within siblings, starts at 1) - @*name for location in siblings with specific name - @. for element name, e.g. organization/*[1]/@. - namespaces are not supported in paths: they use names without URI - - xmd_html_value(pathFix, parent, fun): 'path' 'path infix' 'prefix -% path' - 'path infix %- postfix': fun = 'htmlspecialchars' by default - - xmd_select_elements(path, parent): find element nodes with path (see above) - xmd_select_single_element (id.) returns -1 or elementnumber - xmd_select_elements_where(path, subpath, value, parent): e.g. '@id', '12' - is like XPath with path[@id='12']; subpath = '.' means text - xmd_select_elements_where_notempty(path, subpath, parent): e.g. '@id' - xmd_select_xxx methods only select elements, not attributes - - xmd_remove_element(childelement_number) - xmd_remove_nodes(childelement_numbers_and_strings, parent) - - xmd_update(path, text, parent): select single element, then: - text element: replace text by new text - attribute: give attribute new value = text - somepath/!newtag: create new child element containing text - somepath/~: delete single (first or only) element - xmd_update_many(paths, subpath, ...): paths can be path1,path2,...: - for all elements selected by all paths, update with subpath - - xmd_copy_foreign_child(fdoc, child, parent): - copies fdoc's child as a new child of parent; - note this method hasn't been tested for all cases (namespaces...) - - xmd_cache(): dump xmddoc into names+numbers+textstring for serialization - - Order of parameters (if present) for xmd_xxx methods: - name, text, children, path, subPath, value, - parent, fix, fun, attributes (name value) - - - Properties: (G)lobal to xmddoc or array (one for each xmddoc (E)lement) - - e.g. $this->name[0] is the name of the document root element - e.g. $this->names[$this->ns[0]] is its namespace URI - e.g. $this->attributes[0]['title'] is the value of its attribute 'title' - e.g. $this->attributes[0]['xmlns:a'] is the URI for prefix 'a:' - */ - - var $names; //G array: n => namespace URI (0 => '') - var $numbers; //G array: numeric dump of xmddoc for caching - var $textstring; //G string: string dump of xmddoc for caching - var $error; //G string: empty or parsing error message - var $_nesting; //G array: nested elements while parsing (internal) - var $_ns; //G array: namespace defs for upcoming element (id.) - var $_concat; //G bool: concatenate cData with previous (id.) - var $_nsp; //G array: namespace prefixes in use somewhere (id.) - var $_last; //G int: last used elementnumber (id.) - var $_strings; //G int: number of string child nodes cached (id.) - - var $parent; //E int: elementnumber: 0 is root, -1 is parent of root - var $name; //E string: element name, without namespace - var $ns; //E int: index into $names to find namespace URI - var $attributes; //E array: attribute name(without namespace) => value - var $atns; //E array: attribute name(id.) => index into $names - var $children; //E array: elementnumbers and strings (text children) - - - function xmd_get_element($parent = 0) // for convenience, readonly copy - { - // returns mixed array: children + texts have numeric key, - // other elements are attributes, '?name' and '?parent' - - if ($parent < 0 || $parent > $this->_last) return array(); - - return array_merge($this->children[$parent], $this->attributes[$parent], - array('?name' => $this->name[$parent], - '?parent' => $this->parent[$parent])); - } - - - function xmd_get_ns_uri($parent = 0, $attName = '') - { - if ($parent < 0 || $parent > $this->_last) return ''; - - return $attName ? $this->names[$this->atns[$parent][$attName]] : - $this->names[$this->ns[$parent]]; - } - - - function xmd_remove_element($child) // success = TRUE - { - if ($child <= 0 || $child > $this->_last) return FALSE; - - $parent = $this->parent[$child]; - - foreach ($this->children[$parent] as $key => $value) - if ($value === $child) - { - unset($this->children[$parent][$key]); return TRUE; - } - - return FALSE; - } - - - function xmd_remove_nodes($children, $parent = 0) // success = TRUE - { - if ($parent < 0 || $parent > $this->_last) return FALSE; - - if (!is_array($children)) $children = array($children); - - foreach ($children as $child) - { - $childFound = FALSE; - foreach ($this->children[$parent] as $key => $value) - if ($value === $child) - { - unset($this->children[$parent][$key]); - $childFound = TRUE; break; - } - if (!$childFound) return FALSE; - } - - return TRUE; - } - - - function xmd_update($xmPath, $text = '', $parent = 0) // success = TRUE - { - if ($parent < 0 || $parent > $this->_last || - !is_string($text) || !is_string($xmPath)) return FALSE; - - $m = array(); - if (api_ereg('^(.*)([~!@])(.*)$', $xmPath, $m)) // split on ~ or ! or @ - { - $xmPath = $m[1]; $op = $m[2]; $name = $m[3]; - } - - if (($elem = $this->xmd_select_single_element($xmPath, $parent)) == -1) - return FALSE; - - if (isset($op)) - { - if ($op == '!' && $name) - { - $this->xmd_add_text_element($name, $text, $elem); return TRUE; - } - elseif ($op == '@' && $name) - { - $this->attributes[$elem][$name] = $text; return TRUE; - } - elseif ($op == '~' && !$name) - return $this->xmd_remove_element($elem); - - return FALSE; - } - - if (($nch = count($this->children[$elem])) > 1) return FALSE; - - $this->children[$elem][0] = $text; return TRUE; - } - - - function xmd_update_many($xmPaths, $subPath = '', $text = '', $parent = 0) - { - $result = TRUE; - - foreach (explode(',', $xmPaths) as $xmPath) - foreach ($this->xmd_select_elements($xmPath, $parent) as $elem) - $result &= $this->xmd_update($subPath, $text, $elem); - // '&=' always evaluates rhs, '&&=' skips it if $result is FALSE - - return $result; - } - - - function xmd_copy_foreign_child($fdoc, $fchild = 0, $parent = 0) - { - $my_queue = array($fchild, $parent); // optimization, see below - - while (!is_null($fchild = array_shift($my_queue))) - { - $parent = array_shift($my_queue); - - if (is_string($fchild)) - $this->xmd_add_text($fchild, $parent); - - elseif (isset($fdoc->name[$fchild])) - { - $fullname = $fdoc->name[$fchild]; - $attribs = array(); $nsdefs = array(); - - if (($nsn = $fdoc->ns[$fchild])) - $fullname = $fdoc->names[$nsn] . ':' . $fullname; - - foreach ($fdoc->attributes[$fchild] as $name => $value) - { - if (($p = strrpos($name, ':')) !== FALSE) // 'xmlns:...' - $nsdefs[$name] = $value; - - else - { - if (($nsn = $fdoc->atns[$fchild][$name])) - $name = $fdoc->names[$nsn] . ':' . $name; - $attribs[$name] = $value; - } - } - - $child = $this->xmd_add_element($fullname, $parent, - array_merge($attribs, $nsdefs)); - - foreach ($fdoc->children[$fchild] as $ch) - array_push($my_queue, $ch, $child); - // recursive call was 10 times slower... - } - } - } - - - function xmd_add_element($name, $parent = 0, $attribs = array()) - { - if (!is_string($name) || $name == '') return -1; - - if (($p = strrpos($name, ':')) !== FALSE) // URI + ':' + name - if ($p == 0 || $p == api_strlen($name) - 1) return -1; - - $child = ($this->_last += 1); $uris = array(); $uri = ''; - - if ($p) - { - $uri = api_substr($name, 0, $p); $name = api_substr($name, $p + 1); - $uris[] = $uri; // check uris after defining all attributes - } - - $this->parent[$child] = $parent; $this->name[$child] = $name; - $this->ns[$child] = $uri ? $this->_lookup($uri) : 0; - $this->children[$child] = array(); - - $this->attributes[$child] = array(); $this->atns[$child] = array(); - - foreach ($attribs as $name => $value) - if (($uri = $this->xmd_set_attribute($child, $name, $value, FALSE))) - $uris[] = $uri; // check at end, not immediately - - if ($parent >= 0 && $parent <= $this->_last) - $this->children[$parent][] = $child; // link to parent - - foreach ($uris as $uri) $this->_nsPfx($child, $uri); - // find prefix (child and upwards) or create new prefix at root - - return $child; - } - - - function xmd_set_attribute($parent, $name, $value, $checkurihaspfx = TRUE) - { - if (!is_string($name) || $name == '') return ''; - - if (($p = strrpos($name, ':')) !== FALSE) // URI + ':' + name - if ($p == 0 || $p == api_strlen($name) - 1) return ''; - - $uri = ''; // beware of 'xmlns...', which is a namespace def! - - if ($p) if (api_substr($name, 0, 6) != 'xmlns:') - { - $uri = api_substr($name, 0, $p); $name = api_substr($name, $p + 1); - } - $this->attributes[$parent][$name] = $value; - $this->atns[$parent][$name] = $uri ? $this->_lookup($uri) : 0; - if ($checkurihaspfx) if ($uri) $this->_nsPfx($parent, $uri); - - if (api_substr($name, 0, 6) == 'xmlns:') // namespace def with prefix - $this->_nsp[api_substr($name, 6)] = $value; // prefix is in use - - return $uri; - } - - - function xmd_add_text($text, $parent = 0) // success = TRUE - { - if ($parent < 0 || $parent > $this->_last || !is_string($text)) - return FALSE; - - if ($text) $this->children[$parent][] = $text; return TRUE; - } - - - function xmd_add_text_element($name, $text, $parent = 0, $attribs = array()) - { - $this->xmd_add_text($text, - $child = $this->xmd_add_element($name, $parent, $attribs)); - - return $child; - } - - - function xmd_text($parent = 0) - { - if ($parent < 0 || $parent > $this->_last) return ''; - - $text = ''; // assemble text subnodes and text in child elements - - foreach ($this->children[$parent] as $child) - $text .= is_string($child) ? $child : $this->xmd_text($child); - - return $text; - } - - - function xmd_xml($increase = ' ', $indent = '', $lbr = "\n", $parent = 0) - { - global $charset; - - if ($parent < 0 || $parent > $this->_last) return ''; - - $uri = $this->names[$this->ns[$parent]]; - $pfxc = ($uri == '') ? '' : $this->_nsPfx($parent, $uri); - - $dbg = ''; // ($uri == '') ? '' : (' '); - - $result = $indent . '<' . ($element = $pfxc . $this->name[$parent]); - - $atnsp = $this->atns[$parent]; - - foreach ($this->attributes[$parent] as $name => $value) - { - if (isset($atnsp[$name])) - $atnsn = $atnsp[$name]; - elseif (isset($atnsn)) - unset($atnsn); - $uri = isset($atnsn) && isset($this->names[$atnsn]) ? - $this->names[$atnsn] : ''; - $pfxc = ($uri == '') ? '' : $this->_nsPfx($parent, $uri); - $result .= ' ' . $pfxc . $name - . '="' . htmlspecialchars($value, ENT_QUOTES, $charset) . '"'; - } - - if (count($this->children[$parent]) == 0) - return $result . ' />' . $dbg; - - $result .= '>'; - - foreach ($this->children[$parent] as $child) - $result .= is_string($child) ? htmlspecialchars($child, ENT_QUOTES, $charset) : ($lbr . - $this->xmd_xml($increase, $indent.$increase, $lbr, $child)); - - if (!is_string($child)) $result .= $lbr . $indent; // last $child - - return $result . '' . $dbg; - } - - - function xmd_value($xmPath, $parent = 0, $fix = array(), $fun = '') - { - // extensions: @*[name] for element position (starts at 1) - // @. for element (tag)name - - if ($parent < 0 || $parent > $this->_last || !is_string($xmPath)) - return ''; - - if (($p = strrpos($xmPath, '@')) !== FALSE) - { - $attName = api_substr($xmPath, $p+1); $xmPath = api_substr($xmPath, 0, $p); - } - - if (!($elems = $this->xmd_select_elements($xmPath, $parent))) return ''; - - $result = ''; $fixin = isset($fix['in']) ? $fix['in'] : ''; - - foreach ($elems as $elem) - { - $value = isset($attName) && api_strlen($attName) >= 1 ? - ($attName == '.' ? $this->name[$elem] : - ($attName{0} == '*' ? - $this->_sibnum($elem, api_substr($attName, 1)) : - $this->attributes[$elem][$attName])) : - $this->xmd_text($elem); - $result .= $fixin . ($fun ? $fun($value) : $value); - } - - return (isset($fix['pre']) ? $fix['pre'] : '') . - api_substr($result, api_strlen($fixin)) . - (isset($fix['post']) ? $fix['post'] : ''); - } - - - function xmd_html_value($xmPath, $parent = 0, $fun = 'htmlspecialchars') - { - if (!is_string($xmPath)) return ''; - - $fix = array(); - - if (($p = api_strpos($xmPath, ' -% ')) !== FALSE) - { - $fix['pre'] = api_substr($xmPath, 0, $p); - $xmPath = api_substr($xmPath, $p+4); - } - if (($p = api_strpos($xmPath, ' %- ')) !== FALSE) - { - $fix['post'] = api_substr($xmPath, $p+4); - $xmPath = api_substr($xmPath, 0, $p); - } - if (($p = api_strpos($xmPath, ' ')) !== FALSE) - { - $fix['in'] = api_substr($xmPath, $p+1); - $xmPath = api_substr($xmPath, 0, $p); - } - - return $this->xmd_value($xmPath, $parent, $fix, $fun); - } - - - function xmd_select_single_element($xmPath, $parent = 0) // for convenience - { - $elements = $this->xmd_select_elements($xmPath, $parent); - if (count($elements) == 0) return -1; - return $elements[0]; - } - - - function xmd_select_elements_where($xmPath, - $subPath = '.', $value = '', $parent = 0) - { - if (!is_string($subPath)) return array(); - - $elems = array(); if ($subPath == '.') $subPath = ''; - - foreach ($this->xmd_select_elements($xmPath, $parent) as $elem) - if ($this->xmd_value($subPath, $elem) == $value) $elems[] = $elem; - - return $elems; - } - - - function xmd_select_elements_where_notempty($xmPath, - $subPath = '.', $parent = 0) - { - if (!is_string($subPath)) return array(); - - $elems = array(); if ($subPath == '.') $subPath = ''; - - foreach ($this->xmd_select_elements($xmPath, $parent) as $elem) - if ($this->xmd_value($subPath, $elem)) $elems[] = $elem; - - return $elems; - } - - - function xmd_select_elements($xmPath, $parent = 0) - { - // XPath subset: e1/e2/.../en, also * and e[n] and *[n] (at 1 or -1) - // /*/... starts from root, regardless of $parent - // extensions: e= - or + (previous & next sibling) - // e= -name or +name (sibling of specific name) - // e= .. (stops at root, so too many doesn't matter) - - if (api_substr($xmPath, 0, 3) == '/*/') - { - $xmPath = api_substr($xmPath, 3); $parent = 0; - } - - if ($parent < 0 || $parent > $this->_last) return array(); - - while (api_substr($xmPath, 0, 1) == '/') $xmPath = api_substr($xmPath, 1); - while (api_substr($xmPath, -1) == '/') $xmPath = api_substr($xmPath, 0, -1); - - if ($xmPath == '' || $xmPath == '.') return array($parent); - - if ($xmPath == '..') - { - if ($parent > 0) return array($this->parent[$parent]); - return array($parent); - } - - if ($xmPath{0} == '-' || $xmPath{0} == '+') - { - $sib = $this->_sibnum($parent, api_substr($xmPath, 1), $xmPath{0}); - if ($sib == -1) return array(); return array($sib); - } - - $m = array(); - if (api_ereg('^(.+)/([^/]+)$', $xmPath, $m)) // split on last / - { - if (!($set = $this->xmd_select_elements($m[1], $parent))) - return $set; // which is empty array - if (count($set) == 1) - return $this->xmd_select_elements($m[2], $set[0]); - - $bigset = array(); $m2 = $m[2]; - foreach ($set as $e) - $bigset = array_merge($bigset, - $this->xmd_select_elements($m2, $e)); - return $bigset; - } - - $xmName = $xmPath; $xmNum = 0; $elems = array(); - - if (api_ereg('^(.+)\[(-?[0-9]+)\]$', $xmPath, $m)) - { - $xmName = $m[1]; $xmNum = (int) $m[2]; - } - - foreach ($this->children[$parent] as $child) if (!is_string($child)) - if ($xmName == '*' || ($this->name[$child]) == $xmName) - $elems[] = $child; - - if ($xmNum == 0) return $elems; - - $xmNum = ($xmNum > 0) ? $xmNum - 1 : count($elems) + $xmNum; - - return ($xmNum < count($elems)) ? array($elems[$xmNum]) : array(); - } - - // Notes on parsing and caching: - // - parsing 388 KB -> 0.94 sec - // - caching 298 KB <- 1.63 sec: 11387 elements, 5137 string nodes - // - uncache 298 KB -> 0.42 sec - // - $this->children[$n][] in a loop is quicker than a temporary array - // $children[] and copying $this->children[$n] = $children after the loop - // - incremental operator ++$numptr is not quicker than ($numptr += 1) - // - numbers & textstring: more compact with base64_encode(gzcompress()) - - function xmd_cache() // store all data in numbers+names+textstring - { - $this->numbers = array(); $this->textstring = ''; $this->_strings = 0; - // add all element- and attributenames to names - see below - - for ($n = 0; $n <= $this->_last; $n++) - { - $this->numbers[] = count($this->children[$n]); - - foreach ($this->children[$n] as $ch) - { - if (is_string($ch)) - { - $this->numbers[] = 0; $this->_strings += 1; - $this->numbers[] = strlen($ch); $this->textstring .= $ch; //!!! Here strlen() has not been changed to api_strlen(). To be investigated. Ivan Tcholakov, 29-AUG-2008. - } - else - { - $this->numbers[] = ($ch-$n); // more compact than $ch - } - } - - $this->numbers[] = count($this->attributes[$n]); - - foreach ($this->attributes[$n] as $name => $value) - { - $this->numbers[] = $this->_lookup($name); - $this->numbers[] = $this->atns[$n][$name]; - $this->numbers[] = strlen($value); $this->textstring .= $value; //!!! Here strlen() has not been changed to api_strlen(). To be investigated. Ivan Tcholakov, 29-AUG-2008. - } - - $this->numbers[] = $this->_lookup($this->name[$n]); - $this->numbers[] = $this->ns[$n]; - $this->numbers[] = $n - $this->parent[$n]; // more compact - } - } - - - function xmddoc($strings, $charset = null, $textstring = '') - { - if (empty($charset)) - { - $charset = api_get_system_encoding(); - } - - $this->parent = array(); $this->name = array(); - $this->ns = array(); $this->attributes = array(); - $this->atns = array(); $this->children = array(); - $this->error = ''; $this->_nesting = array(); - $this->_ns = array(); $this->_last = -1; - - $this->_nsp = array(); - foreach (explode(',', 'eb,tn,eg,ut,as,ne,jt,ne,ah,en,er') as $pfx) - $this->_nsp[$pfx] = ''; - - if (is_array($charset)) // new xmddoc($names, $numbers, $textstring) - { - $this->names = $strings; $this->numbers = $charset; - $this->textstring = $textstring; $this->_uncache(); return; - } - - $this->names = array(); $this->_lookup(''); // empty ns is number 0 - - // This is a quick workaround. - // The xml-parser supports only ISO-8859-1, UTF-8 and US-ASCII. - // See http://php.net/manual/en/function.xml-parser-create-ns.php - //$xml_parser = xml_parser_create_ns($charset, ':'); - $xml_parser = xml_parser_create_ns(api_is_utf8($charset) ? 'UTF-8' : 'ISO-8859-1', ':'); - - xml_set_object($xml_parser,$this); // instead of ...,&$this - // See PHP manual: Passing by Reference vs. xml_set_object - xml_set_element_handler($xml_parser, '_startElement', '_endElement'); - xml_set_character_data_handler($xml_parser, '_cData'); - xml_set_start_namespace_decl_handler($xml_parser, '_startNs'); - // xml_set_end_namespace_decl_handler($xml_parser, '_endNs'); - // xml_set_default_handler ($xml_parser, ''); - xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, FALSE); - - if (!is_array($strings)) $strings = array($strings); - - if (count($strings) && (api_substr($strings[0], 0, 5) != '', FALSE)) - { - $this->error = 'Encoding ' . $charset . ': ' . - xml_error_string(xml_get_error_code($xml_parser)); - $strings = array(); - } - - foreach ($strings as $s) - { - if (api_substr($s, -1) != "\n") $s .= "\n"; - - if (!xml_parse($xml_parser, $s, FALSE)) - { - $errCode = xml_get_error_code($xml_parser); - $this->error = 'Line '. xml_get_current_line_number($xml_parser) . - ' (c' . xml_get_current_column_number($xml_parser) . - // ', b' . xml_get_current_byte_index($xml_parser) . - '): error ' . $errCode . '= ' . xml_error_string($errCode); - break; // the error string is English... - } - } - - xml_parse($xml_parser, '', TRUE); xml_parser_free($xml_parser); - } - - - // internal methods - - function _sibnum($parent, $name = '', $pmn = 'N') // sibling or number - { - if ($parent <= 0) return -1; - - $found = FALSE; $prev = -1; $next = -1; $num = 0; - - foreach ($this->children[$this->parent[$parent]] as $child) - { - if (is_string($child)) continue; - - $name_ok = $name ? ($this->name[$child] == $name) : TRUE; - - if ($found && $name_ok) - { - $next = $child; break; - } - elseif ($parent === $child) - { - $num ++; $found = TRUE; - } - elseif ($name_ok) - { - $num ++; $prev = $child; - } - } - - return ($pmn == '-') ? $prev : (($pmn == '+') ? $next : $num); - } - - function _uncache() // restore all data from numbers+names+textstring - { - $n = -1; $numptr = -1; $txtptr = 0; $count = count($this->numbers); - $A0 = array(); // believe it or not, this makes the loops quicker! - - while (++$numptr < $count) - { - $n++; - - if (($countdown = $this->numbers[$numptr]) == 0) - { - $this->children[$n] = $A0; - } - else while (--$countdown >= 0) - { - if (($chc = $this->numbers[++$numptr]) == 0) - { - $this->children[$n][] = api_substr($this->textstring, - $txtptr, ($len = $this->numbers[++$numptr])); - $txtptr += $len; - } - else - { - $this->children[$n][] = $n + $chc; - } - } - - if (($countdown = $this->numbers[++$numptr]) == 0) - { - $this->attributes[$n] = $this->atns[$n] = $A0; - } - else while (--$countdown >= 0) - { - $name = $this->names[$this->numbers[++$numptr]]; - $this->atns[$n][$name] = $this->numbers[++$numptr]; - $this->attributes[$n][$name] = api_substr($this->textstring, - $txtptr, ($len = $this->numbers[++$numptr])); - $txtptr += $len; - } - - $this->name[$n] = $this->names[$this->numbers[++$numptr]]; - $this->ns[$n] = $this->numbers[++$numptr]; - - $this->parent[$n] = $n - $this->numbers[++$numptr]; - } - - $this->_last = $n; - } - - function _startElement($parser, $name, $attribs) - { - $level = count($this->_nesting); - $parent = ($level == 0) ? -1 : $this->_nesting[$level-1]; - - $child = $this->xmd_add_element($name, $parent, - array_merge($attribs, $this->_ns)); - - $this->_nesting[] = $child; $this->_ns = array(); - - $this->_concat = FALSE; // see _cData - } - - function _endElement($parser, $name) - { - array_pop($this->_nesting); $this->_concat = FALSE; - } - - function _cData($parser, $data) - { - if (!ltrim($data)) return; // empty line, or whitespace preceding - - $level = count($this->_nesting); - $parent = ($level == 0) ? -1 : $this->_nesting[$level-1]; - - if ($parent >= 0) - { - $nc = count($this->children[$parent]); - $pcs = ($nc > 0 && is_string($this->children[$parent][$nc - 1])); - - if ($pcs && api_strlen($data) == 1) $this->_concat = TRUE; - // expat parser puts &xx; in a separate cData, try to re-assemble - - if ($pcs && $data{0} > '~') $this->_concat = TRUE; - // PHP5 expat breaks before 8-bit characters - - if ($this->_concat) - { - $this->children[$parent][$nc - 1] .= $data; - $this->_concat = (api_strlen($data) == 1); - } - else - $this->children[$parent][] = $pcs ? "\n" . $data : $data; - } - } - - function _startNs($parser, $pfx, $uri) // called before _startElement - { - $this->_ns['xmlns' . ($pfx ? ':'.$pfx : '')] = $uri; - $this->_nsp[$pfx] = $uri; - } - - function _nsPfx($ppar, $uri) // find namespace prefix - { - while ($ppar >= 0) - { - foreach ($this->attributes[$ppar] as $name => $value) - if (api_substr($name, 0, 5) == 'xmlns' && $value == $uri) - { - $pfxc = api_substr($name, 6) . api_substr($name, 5, 1); break 2; - } - - $ppar = $this->parent[$ppar]; - } - - if ($ppar >= 0) return $pfxc; if ($uri == '') return ''; - - if ($uri == 'http://www.w3.org/XML/1998/namespace') return 'xml:'; - - foreach($this->_nsp as $pfx => $used) if (!$used) break; - - $this->_nsp[$pfx] = $uri; $xmlnspfx = 'xmlns:' . $pfx; - $this->attributes[0][$xmlnspfx] = $uri; $this->atns[0][$xmlnspfx] = 0; - - return $pfx . ':'; - - } - - function _lookup($name) // for namespaces + see cache - { - $where = array_search($name, $this->names); - - if ($where === FALSE || $where === NULL) - { - $where = count($this->names); $this->names[] = $name; - } - return $where; - } -} - -/* - -*/ -?> diff --git a/main/install/database.sql b/main/install/database.sql index 69cb8cc1e9..a8dd017138 100644 --- a/main/install/database.sql +++ b/main/install/database.sql @@ -4590,17 +4590,6 @@ CREATE TABLE c_thematic_advance( ALTER TABLE c_thematic_advance ADD INDEX (thematic_id); -CREATE TABLE IF NOT EXISTS c_metadata ( - c_id INT NOT NULL, - eid VARCHAR(250) NOT NULL, - mdxmltext TEXT default '', - md5 CHAR(32) default '', - htmlcache1 TEXT default '', - htmlcache2 TEXT default '', - indexabletext TEXT default '', - PRIMARY KEY (c_id, eid) -); - DROP TABLE IF EXISTS c_student_publication_rel_document; CREATE TABLE IF NOT EXISTS c_student_publication_rel_document (id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, work_id INT NOT NULL, document_id INT NOT NULL, c_id INT NOT NULL); DROP TABLE IF EXISTS c_student_publication_rel_user; @@ -4618,5 +4607,5 @@ CREATE TABLE c_attendance_calendar_rel_group ( -- Version LOCK TABLES settings_current WRITE; -UPDATE settings_current SET selected_value = '1.10.0.34' WHERE variable = 'chamilo_database_version'; +UPDATE settings_current SET selected_value = '1.10.0.35' WHERE variable = 'chamilo_database_version'; UNLOCK TABLES; diff --git a/main/install/migrate-db-1.9.0-1.10.0-pre.sql b/main/install/migrate-db-1.9.0-1.10.0-pre.sql index ce22972e67..c78164e5ed 100644 --- a/main/install/migrate-db-1.9.0-1.10.0-pre.sql +++ b/main/install/migrate-db-1.9.0-1.10.0-pre.sql @@ -128,5 +128,7 @@ CREATE TABLE IF NOT EXISTS c_student_publication_rel_user (id INT PRIMARY KEY N CREATE TABLE IF NOT EXISTS c_student_publication_comment (id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, work_id INT NOT NULL, c_id INT NOT NULL, comment text, file VARCHAR(255), user_id int NOT NULL, sent_at datetime NOT NULL); CREATE TABLE IF NOT EXISTS c_attendance_calendar_rel_group (id int NOT NULL auto_increment PRIMARY KEY, c_id INT NOT NULL, group_id INT NOT NULL, calendar_id INT NOT NULL); +DROP TABLE c_metadata; + -- Do not move this query -UPDATE settings_current SET selected_value = '1.10.0.34' WHERE variable = 'chamilo_database_version'; +UPDATE settings_current SET selected_value = '1.10.0.35' WHERE variable = 'chamilo_database_version'; diff --git a/main/metadata/doc/CourseKwds.xml b/main/metadata/doc/CourseKwds.xml deleted file mode 100755 index 8e05723104..0000000000 --- a/main/metadata/doc/CourseKwds.xml +++ /dev/null @@ -1,116 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/main/metadata/doc/Metadata_for_Chamilo.html b/main/metadata/doc/Metadata_for_Chamilo.html deleted file mode 100644 index c70f613480..0000000000 --- a/main/metadata/doc/Metadata_for_Chamilo.html +++ /dev/null @@ -1,655 +0,0 @@ - - - - Metadata for Dokeos - - - - - -

    Metadata for Dokeos 1.6

    -
    document version:2005/09/20.
    -
    -
    -This is a short technical documentation about the metadata (MD) -implementation in Dokeos 1.6. The 1.6 implementation (DMD1.6) mainly -consists of:
    -
      -
    • screens and scripts for document-MD viewing and editing;
    • -
    • two XML-related libraries;
    • -
    • a general MD toolkit with some API functions;
    • -
    • experimental scripts for search via MD and for getting statistics -on keyword usage;
    • -
    • not fully supported scripts for indexing and searching MD with -PhpDig;
      -
    • -
    • not fully supported scripts for storing/editing MD related to -Links;
      -
    • -
    • not fully supported scripts for SCORM package metadata import -and custom browsing (see end of document).
    • -
    -Background information can be found on Zephyr: -VeloMetadataClaroline.doc (via Documenten, Metadata). (That document -is, however, outdated where it -describes the implementation.)
    -
    -

    Metadata, XML, MD table

    -MD is XML-formatted information about a Dokeos object. It is stored in -a course database table (not globally), and Dokeos objects are -identified in that table by their type + '.' + id. For example, -'Document.12' -refers to an object -of type 'Document' (a file or a folder in the Dokeos Documents tool).
    -
    -The design of DMD1.6 allows to define, per type of object, which info -is to be stored as MD, and how the MD is represented in XML. Both can -be -adapted relatively easily, in a PHP-script that defines the object -class -'mdobject' for the object type at hand.
    -
    -DMD1.6 fully implements MD definition, storage and editing for -'Document'-type -objects. The class 'mdobject' for these type of objects is defined in -the script 'md_document.php'. The class definition includes a method -to generate the default MD for new entries. (The scripts 'md_link.php' -and 'md_scorm.php' define the class 'mdobject' for 'Link'- and -'Scorm'-type objects. Script 'md_mix.php' defines a subset of the -'mdobject' class functionality for the experimental Search script.)
    -
    -DMD1.6 works with standard IEEE LOM (Learning Objects MD). The -XML-representation -conforms to SCORM 1.3 (also known as SCORM 2004). The IEEE LOM elements -General.Identifier.Catalog -and .Entry are made to contain a globally unique object identifier of -the -form urn:institution:platform.coursecode.type.id and for element -Technical.Location an URL is generated that points to script -'openobject.php', also part of DMD1.6.
    -
    -To make changes to type and representation of MD more easy, the -'mdobject' class also defines a map for the (generally accepted) Dublin -Core elements. A specific Dokeos installation can thereby adapt -DMD1.6 relatively easily e.g. to use SCORM 1.2 and/or IMS-XML instead -of SCORM 2004.
    -
    -MD is stored in the (new) course database table 'metadata'. Count on -2-4 KB per metadata record.
    -
    -The MD records currently have 5 fields: eid (entry-id or object -identifier), -mdxmltext (metadata text, XML-formatted), md5, htmlcache1, htmlcache2, -indexabletext. The latter three fields are used for cached HTML and for -storing text to be indexed for search; the hash-value md5 is used to -validate -the cache.
    -
    -The script -'md_funcs', part of the MD toolkit, and used a.o. in the index and -search -scripts, contains a class definition 'mdstore', which handles all -database operations. Code -that is shared by several other scripts is also to be found in -'md_funcs.php': common functions, code related to IEEE, and code -related -to the keyword tree (see below).
    -
    -

    XMD and XHT

    -Two new libraries in inc/lib are essential for DMD1.6: the XML Mini-DOM -'xmd' and XML HTML Templates 'xht'. The corresponding scripts contain -some comments describing their functionality. Test scripts are included -in DMD1.6 -to demonstrate the use of these libraries.
    -
    -DOM XML functions are also available in PHP 4 itself, but they are -experimental. They require an extra -nonstandard XML library and, on Windows, fiddling with DLLs. To avoid -these problems, DMD1.6 comes with its own XML Mini-DOM library.
    -
    -Several open source template libraries exist for PHP, and yet DMD1.6 -again comes with its own one. The main design goal for the XML HTML -Templates library is -to combine HTML separation and a tight connection with an XML -(mini-dom-)document. These -are essential, given the goal of flexibility concerning kind and -representation of MD and presentation to the user. The 'xht' library -is mainly used to generate HTML, but DMD1.6 also uses it to generate -XML -(e.g. the default XML for new MD records in 'md_document.php') and -JavaScript (in 'md_funcs.php').
    -
    -If it is decided for a future version of Dokeos to use a more -'standard' -approach for XML and/or for templates (e.g. Smarty), then DMD will -most -probably be adapted.
    -
    -The use of 'xht' in DMD1.6 allows to define, per type of object, -what part of the MD is to be shown to a Dokeos user or presented for -editing, and how -that info is rendered as HTML (between the page header and footer). -For 'Document'-type objects, the HTML templates for MD viewing and -editing are to be found in 'md_document.htt'. (Compare them with the -templates in 'md_link.htt', 'md_scorm.htt' (both not fully supported), -and 'mds_mix.htt'., the -templates used when rendering the (experimental) -search screen.)
    -
    -Some little notes here will come in handy for easier understanding of -the templates. For more info, look into the -source code of the libraries.
    -
      -
    • A template starts with a special comment line -giving the -template name. A template ends where the next one starts.
      -
    • -
    • Templates can call other templates, example "{-C -LANGSELECT-}" (a "call" construct).
    • -
    • Calls do not have parameters. Instead, there is a global -parameter array. String values are stored in it with the "define -construct", e.g. "{-D label Language-}" -(define "label" to have the value "Language"). Parameter values are -fetched with the "parameter" construct, e.g. "{-P -title-}". 
    • -
    • Some parameters are predefined, e.g. "{-P 0-}" -('0'), "{-P 1-}", "{-P -empty-}" (empty string). When another literal values needs to be -used in a construct, put it in a parameter, e.g. "{-D -XML application/xml;iso-8859-1-}"
    • -
    • The "language" construct "{-L KwHelp-}" -includes the value of a language variable from a Dokeos language file -(here: $langKwHelp). (To be correct, it calls the function that has -been assigned to xht_get_lang, usually get_lang.)
      -
    • -
    • The "XML construct", e.g. "{-X -technical/format-}" fetches a value from the associated XML -document (in DMD1.6 most often the metadata of a Dokeos object).
    • -
    • The "test construct", e.g. "{-T key == -selvalue selected-}" provides conditional inclusion. Our -example: include -the word "selected" only when parameter "key" is equal to parameter -"selvalue".
    • -
    • Constructs can span several lines, but special care is required -for correct spacing. See examples with the test construct in -'md_document.htt': the space at the end of an unclosed "{-T ..." line is essential!
    • -
    • The "repeat construct", e.g. "{-R Langs C -OPTION-}" repeatedly calls a subtemplate. In this example, the -subtemplate "OPTION" is repeated for all values in the associative list -$langLangs. (Sample associative lists can be found in lang/english/trad4all.inc.php -Another example: "{-R general/keyword C -KEYWORD-}" - repeat "KEYWORD" for all XML elements found by the -given path "general/keyword".
    • -
    • Constructs can be nested such as in e.g. "{-H -{-L {-P label-}Tip-}-}".
    • -
    • The "X" construct implicitly includes the htmlspecialchars -transformation. Where this is not desired, the "V" ("value") construct -can be used instead. ("X" = "V" + "H") To refer to the associated XML -document, both constructs use an XPath parameter such as -'general/title/string/@language'. There is a provision in 'xht' -allowing to include the callback marker '=/' in XPaths (see source -code).
      -
    • -
    • As a convenience, the C, L, P, V, and X constructs allow -cascading instead of nesting, e.g. "{-V P xpath-}" -is equivalent to "{-V {-P xpath-}-}".
    • -
    • For the "E" construct, see "Caching".
      -
    • -
    • It should be kept in mind that template scanning and substitution -is simple character-processing. To help with template definition and -adaptation, 'xht' can generate tracing information that can be -made visible in the HTML page source (see xht_dbgn and xht_dbgo).
    • -
      -
    -
    -

    Mime types and Technical.Format

    -In the IEEE LOM standard, the metadata element Technical.Format must -contain the learning object mime type. DMD1.6 uses -DocumentManager::file_get_mime_type as authorative source for mime -types and for determining the default mime type based on file extension.
    -
    -There is a provision for adding mime types that are not listed in -DocumentManager::file_get_mime_type, -for example alternative mime types for a specific file extension. This -is done via the language variable $langFormats (see DLTT and Dokeos -lang-file md_document). This language variable must contain an -associative list such as e.g. ":text/plain;iso-8859-1:Text;Latin-1,, -application/xml;iso-8859-1:Xml;Latin-1". (The second part of a -list -item, e.g. "Text;Latin-1", appears in the -selection box in the metadata -screen and can be made language-specific.) (In associative lists, -elements are separated by double comma; value and language text are -separated by the first character in the language string, here a colon.)
    -
    -One specific mime type can be designated as the mime type for course -keywords documents (see next section). This is done by defining -parameter XML in the template file metadata/md_document.htt. In DMD1.6 -it contains:
    -{-D XML application/xml;iso-8859-1-}
    -
    -

    Keywords in a tree, JavaScript
    -

    -MD usually includes -keywords, and there is a special provision in -DMD1.6 allowing to (optionally) define a structured set of keywords for -each course. The course manager defines the keywords in an xml file (an -example is provided) and uploads it to the course documents area. When -browsing to that document's metadata, there will be a button 'This -document contains the course keywords'. The -XML-structured keywordtree is then converted to the cache file -'CourseKwds.js' -in the course's top-level directory. The button must be used after each -change to the xml file. To remove all course keywords (and the cache -file), use the button on an xml file containing only spaces or only a -top element with no content.
    -
    -The cache file constructs a clickable tree -in HTML (restricted to W3C browsers). The toolkit script 'md_funcs' -contains the server-side functions related to the keyword tree, the -file 'md_script.js' contains -the client-side script.

    -Whether the keyword tree is -presented in a screen (index, search, ...), and if so, where and how, -can again be defined relatively easily via the templates. The MD -view-and-edit screen also converts comma-separated keywords (whether -selected with the clickable tree or typed in) -to separate XML elements (as required by SCORM 1.3).
    -
    -The file 'md_script.js' also contains the client-side script used by -the HTML templates in 'md_document.htt' for input validation and MD -update preparation in screens for 'Document'-type object MD. Whereas -keyword-tree clicking requires a W3C browser, input validation and MD -update should also work with IE4 and NS4 browsers (not tested).
    -
    -DMD1.6 contains input validation of two kinds (put the following on the -HTML INPUT element):
    -
      -
    • onKeyPress="return -isValidChar(event, pattern, flags)", e.g. '[a-z]', 'i': allow -only the -26*2 letters: all other input is disabled in the INPUT field; examples -in the fields for the learning object identifier and for keywords;
    • -
    • onKeyUp="checkValid(this, -pattern, flags)", e.g. '^[a-z]{2,8}$', 'i': field must contain -between 2 -and 8 letters: nonconforming input will pass, but text is rendered in -red to alert the user; an example in the date field (lng. obj. -creation).
    • -
    -To provide a minimum level of MD editing support when there is no -scripting in the browser, the templates in 'md_editxml' allow direct -editing of the XML formatted data. (This same template is used should -an XML syntax error be detected, thereby allowing to repair XML -metadata.)
    -
    -To view the XML formatted data, click the 'Store' button while holding -CTRL- and ALT-keys down.
    -
    -The server-side functions for the construction of the keyword tree -cache file (in 'md_funcs') -mimic an XSLT process which is -documented in 'SelKwds.xsl'. (This file, and XSLT in general, is not -used in DMD1.6.)
    -
    -The experimental script 'statistics.php' gives statistics about the -usage of course keywords. It is not linked to any Dokeos -1.6 screen, therefore not reachable in a standard installation.
    -
    -

    MD toolkit and API
    -

    -The script 'md_funcs' contains the main part of the toolkit and API. -They allow other Dokeos scripts to define, modify and delete MD for -specific objects (see class 'mdstore'). The script 'md_funcs' must be -combined with a script -that defines the object class 'mdobject' for the specific type of -object -(such as  'md_document.php' for 'Document'-type objects). The test -scripts 'dcex' and 'mdApiTest' demonstrate the toolkit and the API -functions.
    -
    -The simplest way of working with the API is by using the functions -'mds_get_dc_elements' and 'mds_put_dc_elements'. They allow to fetch -and store the MD elements that are part of the so called Dublin Core. -The DC elements form a generally accepted core set of metadata.
    -
    -The function 'mds_update_xml_and_mdt' is particularly useful for -translating user interactions with a MD edit screen to MD-store -operations. When using the API, it might be more handy to work with xmd -and mdstore operations directly.
    -
    -A word of warning: MD scanning is a relatively compute-intensive task. -If used in a loop, e.g. to display some specific info about several -hundreds of documents, server response might slow down.
    -
    -

    Other files in DMD1.6

    -Language files -'trad4all.inc.php' are available for English, French and Dutch. -Language files 'md_link.inc.php' and 'md_scorm.inc.php' only exist in -English.
    -
    -Files 'md_link.php' and 'md_link.htt', also 'md_scorm.php' and -'md_scorm.htt', all already mentioned, are used in -conjunction with the not fully supported functionality related to Link -metadata -and SCORM -package metadata import.
    -
    -File 'md_link.php', in conjunction with 'index.php', demonstrates the -use of the mdo_override and mdo_storeback methods allowing to implement -a more tight synchronization between MD and standard Dokeos object -properties than is actually implemented for document MD (see also -below: Link metadata editing).
    -
    -

    Caching

    -The 'xht' library provides caching functions, which allow to speed up -screen building. DMD1.6 caches information to database fields -'htmlcache1' and 'indexabletext' ('htmlcache2' is not used in DMD1.6).
    -
    -In 'md_document.htt' it can be seen that the MD view-and-edit screen -(produced by index.php) is divided in four main parts: part 1, the -keywords tree, -part 2 and the POST form.
    -
    -Instead of a normal "call" from a template to a subtemplate, which -would be "{-C METADATA_PART1-}", the main -template does an "escape-call" "{-E -md_part1 C METADATA_PART1-}". The escape construct works as -follows: the -'xht' library does a callback to the user code, in this example to the -PHP -function 'md_part1'. The code for that function can be found in -'index.php'. -That function checks whether it has a valid cached HTML and if so, -returns -it, thereby avoiding the template expansion of the subtemplate -METADATA_PART1. -If not, 'xht' effectively does the (supposedly slow) expansion and -allows -the callback function 'md_part1' to store it for re-use.
    -
    -In DMD1.6, "part 1" of the screen contains most template expansion -work, hence the database field 'htmlcache1' is a real HTML cache. -Another part of the screen is made to contain the "words" from the -metadata that must -be indexable and searchable. It corresponds with the database -field 'indexabletext'.
    -
    -Under certain circumstances, caching may cause a delay after a change. -For example, when making languages visible or unvisible, they may not -immediately appear in or disappear from the SELECT inputfields in -existing metadata. To make the change visible, edit that metadata.
    -
    -Toolkit/API functions such as -'mds_append', useful e.g. for adding searchable words to -'indexabletext', must be used with care, because of possible -interactions with the index -script, when it allows users to modify metadata (and therefore also -indexable words) interactively.
    -
    -

    Index and Search scripts
    -

    -Both scripts lean heavily on the libraries and on the API; -they are therefore relatively short.
    -
    -Note that all output is produced in a section at the end of the scripts.
    -
    -DMD1.6 has an experimental screen for searching documents based on -their MD. It is not linked to any Dokeos -1.6 screen, therefore not reachable in a standard installation.
    -
    -This MD search screen described in this section does not require the -installation of PhpDig 1.8.6. as opposed to the (not fully supported) -PhpDig indexing/searching scripts described further down.
    -
    -A general search in all metadata is not so easy, -because the metadata can in theory be quite different for different -types of -Dokeos objects. In practice, Dokeos platforms will probably stick to -identical or rather similar metadata for all objects and might -therefore find the search script useful.
    -
    -The DMD1.6 MD search script does an unsophisticated database query in -field 'indexabletext', supposedly containing all searchable words.
    -
    -DMD1.6 puts these searchable words in the field: -
      -
    • via function md_indexabletext in index.php if that function is -called from the templates in a "E" construct (see Caching); this is the -case for Document;
    • -
    • for Scorm and Link: via function mdo_define_htt in md_scorm.php -and md_link.php, called by -importmanifest.php and importlinks.php.
    • -
    -Note that keywords are transformed, e.g. MD keyword 'fish' will become -searchable word 'fish-kw'. This allows search to focus on the keyword, -without finding references where the word 'fish' is part of some -description. This can of course (because of the templates) be changed -relatively easily, but it should be noted that the current search -screen & script, and also the PhpDig connection, assume this -transformation.
    -
    -The script -'update_indexabletext.php' can be used to update MD records when the -definition of the searchable words is changed. It is not linked to any Dokeos -1.6 screen, therefore not reachable in a standard installation. It uses -function mdo_define_htt already mentioned above. For documents, -md_document.php should then contain the same definition as the one in -md_document.htt. Use the script with e.g. '?eid_type=Document'.
    -The SCORM package metadata import script importmanifest.php (see -below), if used with SCORM -2004 packages, generates metadata records (type 'Scorm') that are very -similar to the 'Document' type metadata records.
    -
    -Before generating output, search combines (in memory) the XML metadata -of all -Dokeos objects that it has found for a particular query into a big, -imsmanifest-like XML document. It is expected that this will cause -problems if many hundreds or thousands of objects have metadata and can -therefore be "found" in one query.
    -
    -All of this shows that the search script will need to evolve in future -Dokeos versions.
    -
    -To make metadata search available on your Dokeos server, include a link -to
    -.../metadata/search.php?type=Mix -
    -
    -

    DMD1.6 files with comments

    -

    Updates for standard Dokeos scripts

    -

    document/edit_document.php

    -The (one and only) link between Dokeos and metadata (via Documents).
    -

    lang/*/document.inc.php

    -Two additional language-dependent words for edit_document.
    -

    inc/lib/fileManage.lib.php

    -Updated to delete the metadata entry when deleting a document or a -SCORM folder. (Link-MD is not automatically deleted.)
    -
    -

    Functionality not fully -supported in DMD1.6

    -

    Link metadata editing

    -To allow course managers to interactively store and edit metadata about -a Link, provide an URL such as:
    -.../metadata/?eid=Link.nnn
    -
    -This metadata may e.g. add keywords.
    -
    -Unlike with Document-type objects, Link-type metadata object editing -has an override- and storeback-functionality. When metadata is -displayed for editing, DB data is overridden by new data from the Links -table (but not automatically stored): category, url, title, -description, keywords. When metadata is changed in the MD edit screen -and stored, then new data is stored back into the Links table: url, -title, description, keywords (but not category).
    -
    -In the Links table, MD description and keywords are combined in the -description field, as follows:
    -<i kw="kw1, kw2, ...">Description</i>
    -Thereby keywords are not visible to the user, yet editable by the -course admin.
    -

    importlinks.php

    -This script, not reachable -until you e.g. link it to a course homepage, -performs the following operations -related to Links:
    -
      -
    • Create MTEs (Metadata -Table Entries) for all Links of a specific category
    • -
    • Delete all MTEs for -Links of a specific category
    • -
    • Index all MTEs of a -Link category for search (see also below, PhpDig connection)
    • -
    -As importlinks is meant to be used only by course admins, hide -it after you have linked it to the course homepage.
    -
    -

    SCORM metadata import and custom browsing

    -

    importmanifest.php

    -This script, not reachable until you e.g. link it to a course homepage, -performs the following operations -related to Metadata Table Entries (MTEs) and SCORM package directories -(SPDs) in Learning Path (which have a SCORM Directory Id SDI): -
      -
    • Import or re-import the 'imsmanifest.xml' file from a SPD into -MTEs
    • -
    • Find the SDI of some SPD
    • -
    • Delete all MTEs corresponding to a specific SDI
    • -
    • Show the main MTE corresponding to some SDI (after import)
    • -
    • Start 'index.php' in some SPD (after import)
      -
    • -
    • Index some SPD for search (see also below, PhpDig connection)
      -
    • -
    -Note that the above mentioned 'index.php' in the SPD is created by -import.
    -
    -As importmanifest is meant to be used only by course admins, hide -it after you have linked it to the course homepage.
    -

    playscormmdset.inc.php

    -This include-script contains the main functionality of the custom -browser.
    -
    -Import creates an 'index.php' in the corresponding scorm folder of a -course. It includes 'playscormmdset'.
    -
    -(Thereby to a search engine, the custom browser will appear as if it is -located in that scorm folder. This is important for search engines that -allow to index/re-index by virtual directory.)
    -
    -The custom browser uses a templates file to generate HTML, but unlike -the standard MD screens, it looks for that templates file in the scorm -folder or in its parent folders. Thereby the generated HTML can be -different for different scorm folders. -
    -An example templates file can be found in metadata/doc/mdp_scorm.htt.
    -
    -
    -

    PhpDig connection

    -DMD1.6 includes functionality -allowing a specific course to work with a customized version of PhpDig -1.8.6 that has been built into the course. This provides quicker and -more -sophisticated search functionality.
    -
    -The connection consists of the script 'md_phpdig.php', this document -section, and the customized files in ...main/metadata/phpdig.
    -
    -It is assumed that a system admin installs a copy of PhpDig in a -subfolder 'phpdig-1.8.6' of the course webfolder, customizes it as -described below and by the sample files, and initializes it by running -PhpDig's install script.
    -
    -The admin screen of PhpDig can best be defined as a hidden -link (because course-admin only) in the course homepage. A link in a -separate window is best, as the admin screen has no Dokeos header.
    -
    -Script 'md_phpdig.php' contains a few lines copied from the PhpDig -config script and a set of functions that can be used as API functions -providing a PhpDig DB-feeder mechanism. They allow combinations of URLs -and searchable words to be fed into the DB directly, bypassing the -PhpDig spider script. The API code is PhpDig spider code, covered by -the GNU GPL just like PhpDig is.
    -
    -Scripts 'importdocs.php', 'importlinks.php' and -'importmanifest.php' make use of that API to index MD for PhpDig. None -of them are reachable from standard Dokeos 1.6 screens.
    -
    -The PhpDig Search screen, which can be used instead of the experimental -MD search screen, is the custom 'search.php' available in the -metadata/phpdig folder. It must be copied to the 'phpdig-1.8.6' -subfolder of the -course webfolder and then made reachable from the course homepage.
    -
    -PhpDig by default combines search terms with AND and searches for words -starting with the search term strings. Negation is done by putting a -hyphen before the search term (implemented as ALT-click in the search -screen keyword tree).
    -
    -Some background information can be found on Zephyr: -VeloMetadataClaroline.doc (via Documenten, Leerobjectbouwstenen, -Exploreerbare leerstof: document SearchableImageWebsite).
    -

    PhpDig 1.8.6 customizations overview

    -
    includes/config
    -
      -
    • define('PHPDIG_ADM_PASS','admin'); -// insert a password
    • -
    • $template = -"array";
    • -
    • define('MAX_WORDS_SIZE',50);
    • -
    • define('SUMMARY_DISPLAY_LENGTH',700);
    • -
    • define('CONTENT_TEXT',0);
    • -
    • define('USE_IS_EXECUTABLE_COMMAND','0');
    • -
      -
    -
    libs/phpdig_functions
    -
    -' \'._~@#$:&%/;,=-]+' -replaced (twice) by
    -' \'._~@#$&%/=-]+' no :;, in words
    -
    search.php
    -This is the script that must be made accessible in the course, to -provide PhpDig search. It is a newly developed script replacing -PhpDig's standard one.
    -
    -Course managers can adapt the search form and provide extra search -criteria as explained in the SearchableImageWebsite document mentioned -above.
    -
    libs/search_function
    -" \'.\_~@#$:&\%/;,=-]+" -replaced by
    -" \'._~@#$&%/=-]+" no \:;, in words
    -
    -two special "words" are used for controlling the displaying of the -search results: "txt-sep" (newline) and "txt-end" (end of display)
    -
    -the "-kw" tail of keywords is stripped off in the search results

    -
    thumbnail support
    -This is quite well explained in the above mentioned background material.
    -
    -This works only with special-design SCORM packages: item resource -file[1]/@href is assumed to point to the thumbnail image, which must -have a filename 'pptsl' + nnn + '_t.jpg' (see a.o. -'importmanifest.php').
    -
    -In md_phpdig.php, the '&thumb=...' part of URLs is cut off for -display.
    -
    -Metadata search also displays the thumbs (see -'.../main/metadata/search.php' and 'mds_mix.htt'). -
    -
    -
    - - diff --git a/main/metadata/doc/SelKwds.xsl b/main/metadata/doc/SelKwds.xsl deleted file mode 100755 index 70abe91200..0000000000 --- a/main/metadata/doc/SelKwds.xsl +++ /dev/null @@ -1,533 +0,0 @@ - - - - - - - - - - - - - - - - <xsl:value-of select="@title"/> - - - - - - - - - - - - -

    - -
    - -  Click a keyword in the tree to select or deselect it. -
    - -
    -
    - Click '+' button to open, '-' button to close, '++' button to open all, '--' button to close all.
    -
    - Clear all selected keywords by closing the tree and opening it again with the '+' button.
    - Alt-click '+' searches the current keywords in the tree.
    - Control-Alt-click '+' searches the keywords of the current slide.
    -
    - Alt-click keyword selects a keyword without broader terms or - deselects a keyword with broader terms.

    - Selected keywords are available in the Clipboard.
    -
    - 'nei' stands for 'not elswhere included'.

    -
    - -
    - - -   -
    - -
    - - - - - - - -
    - - - - - - -
    - - - - - - - -   - - - - - - - - - -
    - - - -
    -
    - -
    - - \ No newline at end of file diff --git a/main/metadata/doc/dcex.php b/main/metadata/doc/dcex.php deleted file mode 100755 index 64aaf11b5b..0000000000 --- a/main/metadata/doc/dcex.php +++ /dev/null @@ -1,23 +0,0 @@ -mds_get_dc_elements($mdObj))) { - echo '
    ', htmlspecialchars($dcelems['Identifier']), ': ', - htmlspecialchars($dcelems['Description']), '
    '; -} -// Store example: -$langMdCopyright = 'Provided the source is acknowledged'; -$mdStore->mds_put_dc_elements($mdObj, array('Description'=>time())); diff --git a/main/metadata/doc/imsmanifest_reload.xml b/main/metadata/doc/imsmanifest_reload.xml deleted file mode 100755 index 3aee83d1a5..0000000000 --- a/main/metadata/doc/imsmanifest_reload.xml +++ /dev/null @@ -1,189 +0,0 @@ - - - - - - IMS Content - 1.2.2 - - - - Summer Pictures - - - - - - - - en - - Simple exemplar content package - - - Exemplar - - - - LOMv1.0 - - - Linear - - - - - - 0.1 - - - - LOMv1.0 - - - Draft - - - - - - - - LOMv1.0 - - - Creator - - - - BEGIN:VCARD FN:Dr.Colin D. Milligan END:VCARD - - - 2003-07-08 - - - UKCMF - en - - - text/html - http://www.reload.ac.uk/ex/testpkg.zip - - - - - - - - LOMv1.0 - - - no - - - - - LOMv1.0 - - - no - - - - This content is copyright free. - - - - - BEGIN:VCARD FN:Dr.Colin D. Milligan END:VCARD - - - 2003-07-08 - - - These materials are very simplistic. - - - - - - - Summer Pictures - - Loch Katrine - - - Ben Ledi - - - Jencks Earthwork - - - MSP Cells - - - Holyrood Building Site - - - Salisbury Crags - - - Castle Sunset - - - Bridges Sunset - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/main/metadata/doc/mdApiTest.php b/main/metadata/doc/mdApiTest.php deleted file mode 100755 index 087752962b..0000000000 --- a/main/metadata/doc/mdApiTest.php +++ /dev/null @@ -1,140 +0,0 @@ -mdo_eid; - - $titlePath = $mdObj->mdo_dcmap_v['Title']; // no IEEE dependencies here... - - if (($mdt_rec = $mdStore->mds_get($eid)) === FALSE) - { - $mdt = $mdObj->mdo_generate_default_xml_metadata(); - - $xmlDoc = new xmddoc(explode("\n", $mdt)); - if (!$xmlDoc->error) - { - echo htmlspecialchars($titlePath), ': '; - $mdTitle = $xmlDoc->xmd_value($titlePath); - if ($mdTitle == $langMdTitle) - { - $mdTitle = EID_TYPE . ' ' . $eid_id; - $xmlDoc->xmd_update($titlePath, $mdTitle); - $mdt = $xmlDoc->xmd_xml(); - } - echo htmlspecialchars($mdTitle), ':'; - } - - $mdStore->mds_put($eid, $mdt, 'mdxmltext', FALSE); - echo '', - htmlspecialchars($eid), '
    '; - } -} -echo '
    '; - - -$xmlDoc = new xmddoc(explode("\n", $mdStore->mds_get($eid = EID_TYPE . '.1002'))); -if ($xmlDoc->error) give_up($xmlDoc->error); - -$mdObj = new mdobject($_course, '1002'); -$mda = "~~"; // delete metadata of 'Document.1002' -$mdt = $mdStore->mds_update_xml_and_mdt($mdObj, $xmlDoc, $mda, $eid, $trace); -// note: $xmlDoc and $trace are passed by reference... - - -$mdObj = new mdobject($_course, '1003'); -$xmlDoc = new xmddoc(explode("\n", $mdStore->mds_get($eid = EID_TYPE . '.1003'))); -if ($xmlDoc->error) give_up($xmlDoc->error); - -$map_lang = 'string/@language'; -$dcmap_e_kwplace = 'metadata/lom/general'; $dcmap_e_kwelem = 'keyword'; -$dcmap_e_keyword = $dcmap_e_kwplace . '/' . $dcmap_e_kwelem; - -$mda = $mdObj->mdo_dcmap_v['Description'] . '=Nouvelle description' . - "\n" . $mdObj->mdo_dcmap_e['Coverage'] . "~" . - "\n" . $dcmap_e_kwplace . '!' . $dcmap_e_kwelem . - "\n" . $dcmap_e_keyword . "[-1]!string=afrique" . - "\n" . $dcmap_e_keyword . "[-1]/" . $map_lang . "=en" . - "\n" . $mdObj->mdo_dcmap_e['Title'] . ',' . - $mdObj->mdo_dcmap_e['Description'] . ',' . - $dcmap_e_keyword . ";" . $map_lang . "=fr" . - ""; // update metadata of 'Document.1003' - see md_funcs - // note we don't go far with IEEE independence... -$mdt = $mdStore->mds_update_xml_and_mdt($mdObj, $xmlDoc, $mda, $eid, $trace); - -echo htmlspecialchars($trace), '

    '; - - -// The simplest API calls: store and fetch DC metadata element values: - -$mdObj = new mdobject($_course, '1003'); -$mdStore->mds_put_dc_elements($mdObj, array('Coverage' => 'broad...', 'Type' => 'aggressive text')); -// Coverage won't work, because that element has been removed above... -$dcelem = $mdStore->mds_get_dc_elements($mdObj); -foreach (array('Identifier', 'Title', 'Language', 'Description', 'Coverage', - 'Type', 'Date', 'Creator', 'Format', 'Rights') as $dce) -{ - echo $dce, '= ', htmlspecialchars($dcelem[$dce]), '
    '; -} - -echo '
    '; - -$mdObj = new mdobject($_course, '1002'); -$mdStore->mds_put_dc_elements($mdObj, array('Coverage' => 'broad...')); -$dcelem = $mdStore->mds_get_dc_elements($mdObj); -foreach (array('Identifier', 'Title', 'Language', 'Description', 'Coverage', - 'Type', 'Date', 'Creator', 'Format', 'Rights') as $dce) -{ - echo $dce, '= ', htmlspecialchars($dcelem[$dce]), '
    '; -} - -echo '
    '; - -$mdStore->mds_append(EID_TYPE . '.1001', ' search words'); -$mdStore->mds_append(EID_TYPE . '.1001', ' more findable terms'); - - -Display::display_footer(); -?> diff --git a/main/metadata/doc/mdp_scorm.htt b/main/metadata/doc/mdp_scorm.htt deleted file mode 100755 index d6d3543a55..0000000000 --- a/main/metadata/doc/mdp_scorm.htt +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - -{-D level {-V @level-}-}{-T level == 0 C SCORM0-}{-T level != 0 C SCORM123-} - - - - -

    {-X title-}

    - - - {-R child C SUBITEM-} -
    - - - - - - {-X @identifier-} - {-X title-} - - - - - -
    -{-D prv {-V previous/@identifier-}-}{-D nxt {-V next/@identifier-}-}{-D kwds {-X metadata/lom/general/keyword/string , -}-} - - - - - - - - - -
    - {-T prv != empty {-H {-P prv-}-}-}{-T prv == empty X @identifier-} - - {-X parent/@identifier-} - - {-T nxt != empty {-H {-P nxt-}-}-}{-T nxt == empty X @identifier-} -
    {-X @identifier-}: {-X title-}
    - - - - -{-X title-} - - - - -Expires: Mon, 26 Jul 1997 05:00:00 GMT - - - \ No newline at end of file diff --git a/main/metadata/doc/testMiniDom.php b/main/metadata/doc/testMiniDom.php deleted file mode 100755 index 0a03fb186c..0000000000 --- a/main/metadata/doc/testMiniDom.php +++ /dev/null @@ -1,241 +0,0 @@ -= PHP 4.3.0 - - return str_replace("\r", "\n", str_replace("\r\n", "\n", $buffer)); -} - - -require("../../inc/lib/xmd.lib.php"); - - -$testdoc = new xmddoc(''); // docroot is element 0 - - -function showDoc($title, $morestuff = '') -{ - global $testdoc; echo '

    ', $title, '

    ', '
    ',
    -        htmlspecialchars($morestuff ? $morestuff : $testdoc->xmd_xml()), '
    '; -} - - -$sometag1 = $testdoc->xmd_add_element('sometag'); -$testdoc->xmd_set_attribute(0, 'owner', 'rene'); -$testdoc->xmd_add_text('text in my first child element', $sometag1); - -showDoc('Small XML document'); - -$sometag2 = $testdoc->xmd_add_element('sometag', 0, array('x' => 'somevalue')); -$testdoc->xmd_add_text('bizarre in "my& 2nd child', $sometag2); -$testdoc->xmd_add_text(' + more text in first one', $sometag1); -$testdoc->xmd_set_attribute($sometag2, 'owner', ''); -$testdoc->xmd_add_element('innertag', $sometag2); - -showDoc('Slightly changed'); - -showDoc('All text', $testdoc->xmd_text()); - -$stuff = ''; -foreach ($testdoc->xmd_get_element($sometag2) as $key => $value) - $stuff .= $key . ': ' . $value . "\n"; - -showDoc('Children, attributes, name and parent of 2nd sometag', $stuff); - -$testdoc->xmd_remove_nodes('text in my first child element', $sometag1); -// note: remove text may remove more than one node... -$testdoc->xmd_set_attribute(0, 'owner', 'haentjens'); // new value - -showDoc('Text removed from 1st sometag, docroot owner changed'); - -$testdoc->xmd_remove_element($sometag2); -$sometag2 = $testdoc->xmd_add_text_element('��', 'alors!'); - -showDoc('2nd sometag replaced by new subelement with French name'); - -$testdoc->name[$sometag2] = 'sometag'; // properties are read/write -$testdoc->xmd_set_attribute($sometag2, 'xmlns:tn', 'urn:ugent-be'); // namesp def -$subtag = $testdoc->xmd_add_element('urn:ugent-be:subtag', $sometag2); -$testdoc->xmd_set_attribute($sometag2, 'urn:ugent-be:owner', 'FTW'); - -showDoc('French name replaced, namespace definition added and used'); - -$testdoc->xmd_set_attribute($sometag1, 'urn:ugent-be:owner', 'FTW'); -$testdoc->xmd_set_attribute($sometag1, 'urn:rug-ac-be:owner2', 'FLA'); -// restriction: cannot add attribute 'urn:rug-ac-be:owner' (same name) - -showDoc('Attributes with namespaces added, ns def is auto-generated'); - -$stuff = 'subtag => ' . $testdoc->xmd_get_ns_uri($subtag) . "\n"; -foreach ($testdoc->attributes[$sometag1] as $name => $value) - $stuff .= $name . ' => ' . $testdoc->xmd_get_ns_uri($sometag1, $name) . "\n"; - -showDoc('Namespace-URI of subtag, of 1st sometag attributes', $stuff); - -$subsub = $testdoc->xmd_add_element('urn:sample-default:subsub', $subtag, - array('xmlns' => 'urn:sample-default', 'someatt' => 'somevalue')); -$subsubsub = $testdoc->xmd_add_element('urn:sample-default:subsubsub', $subsub); - -showDoc('Subsub element has default namespace'); - -$stuff = 'subsub => ' . $testdoc->xmd_get_ns_uri($subsub) . "\n"; -$stuff .= 'subsubsub => ' . $testdoc->xmd_get_ns_uri($subsubsub) . "\n"; -foreach ($testdoc->attributes[$subsub] as $name => $value) - $stuff .= $name . ' => ' . $testdoc->xmd_get_ns_uri($subsub, $name) . "\n"; - -showDoc('Namespace-URI of subsub and subsubsub; attributes have none', $stuff); - -$testdoc->xmd_update('!newtag', 'text for newtag'); -showDoc("After update '!newtag', 'text for newtag'"); - -$testdoc->xmd_update('newtag', 'new text for newtag'); -showDoc("After update 'newtag', 'new text for newtag'"); - -$testdoc->xmd_update('newtag/@someatt', 'attval'); -showDoc("After update 'newtag/@someatt', 'attval'"); - -$testdoc->xmd_update('newtag/~', ''); -showDoc("After update 'newtag/~', ''"); - -$keepdoc = $testdoc; - -$wrongdoc = "\n \n

    Text

    \n

    More text" . - "\n \n"; -$testdoc = new xmddoc(explode("\n", $wrongdoc)); - -showDoc('Xml doc with syntax error + error message', - $wrongdoc . "\n\n" . $testdoc->error); - -$xmlFile = 'imsmanifest_reload.xml'; - -($presXmlFileContents = @file_get_contents_n($xmlFile)) - or die('XML file ' . htmlspecialchars($xmlFile) . ' is missing...'); - -showDoc('XML file to be parsed', $presXmlFileContents); - -$testdoc = new xmddoc(explode("\n", $presXmlFileContents)); -unset($presXmlFileContents); - -if ($testdoc->error) die($xmlFile . ':

    ' . $testdoc->error); - -$testdoc->xmd_update_many('metadata/lom/general/title,metadata/lom/general/description', 'langstring/@lang', 'fr'); -$testdoc->xmd_copy_foreign_child($keepdoc, $keepdoc->xmd_select_single_element('sometag[2]')); - -showDoc('After parsing, and after changing 2* langstring/@lang to fr, ' . - 'and after adding a foreign doc, reconstruction from memory'); - -showDoc('Element tagname of first metadata/lom/* element', - $testdoc->name[$testdoc->xmd_select_single_element('metadata/lom/*')]); - -showDoc('Element namespace URI of metadata/lom/*[2]', - $testdoc->xmd_get_ns_uri($testdoc->xmd_select_single_element('metadata/lom/*[2]'))); - -showDoc('Number of metadata/lom/* elements', - count($testdoc->xmd_select_elements('metadata/lom/*'))); - -showDoc('Number of resources/resource/file elements with @href', - count($testdoc->xmd_select_elements_where_notempty( - 'resources/resource/file', '@href'))); - -$elems = $testdoc->xmd_select_elements_where('resources/resource', - 'file[1]/@href', 'three.html'); -showDoc('Resource identifier where file[1]/@href is three.html', - $testdoc->xmd_value('@identifier', $elems[0])); - -$elems = $testdoc->xmd_select_elements_where('resources/resource', '@identifier', - $testdoc->xmd_value('organizations/organization/item[2]/@identifierref')); -showDoc('Resource href for item[2]', - $testdoc->xmd_value('@href', $elems[0])); - -$stuff = ''; -foreach (array('@identifier', 'metadata/schema', '*/*/*/*[1]/langstring', - 'resources/resource[3]/@href', 'resources/resource[3]/file/@href', - 'resources/resource[3]/@*', 'resources/resource[3]/-/@href', - 'resources/resource[3]/+/@href', 'resources/resource[1]/-/@href', - 'resources/../../../../../../../@identifier', '@*', 'resources/@*', - 'organizations/organization/item[4]/title', - 'organizations/organization/item[-2]/title', - 'organizations/organization/item[4]/@*', - 'organizations/organization/item[4]/@*item', - 'organizations/organization/item[2]/+item/title', - 'organizations/organization/item[2]/+/+/+/title', - 'organizations/organization/item[2]/-item', - 'organizations/organization/item[1]/-item', - 'organizations/organization/item[1]/-', - 'organizations/organization/item[1]/-/@.' - ) as $path) - $stuff .= $path . ' => ' . $testdoc->xmd_value($path) . "\n"; - -showDoc('Values of: @identifier, metadata/schema, ... (see below)', $stuff); - - -function showHtml($path) -{ - global $testdoc; echo '

    Html-value of ', htmlspecialchars($path), - '

    ', $testdoc->xmd_html_value($path), '
    '; -} - - -showHtml('/*/organizations/organization/item[1]/title'); - -showHtml('organizations/organization/item/title'); - -showHtml('organizations/organization/item/title *'); - -showHtml('Titles: -% organizations/organization/item/titl , %- .'); -// if no elements are found, prefix and postfix are not generated - -showHtml('Titles: -% organizations/organization/item/title , %- .'); - -showHtml('
    • -% resources/resource/file/../@identifier
    • %-
    '); - -showHtml('metadata/lom/general/description/langstring'); -echo '
    The same, but in a HTML construct:
    ', - $testdoc->xmd_html_value('metadata/lom/general/description/langstring'); - - -function getmicrotime() -{ - list($usec, $sec) = explode(" ",microtime()); - return ((float)$usec + (float)$sec); -} - -$xmlFile = 'imsmanifest_reload.xml'; - -($presXmlFileContents = @file_get_contents_n($xmlFile)) - or die('XML file ' . htmlspecialchars($xmlFile) . ' is missing...'); -$presXmlFileContents = explode("\n", $presXmlFileContents); - -$seconds = getmicrotime(); -$testdoc2 = new xmddoc($presXmlFileContents); -$seconds = getmicrotime() - $seconds; - -showDoc('Time to parse', $seconds); - -$seconds = getmicrotime(); -$testdoc2->xmd_cache(); -$seconds = getmicrotime() - $seconds; - -showDoc('Time to cache', $seconds); - -$seconds = getmicrotime(); -$testdoc = new xmddoc($testdoc2->names, $testdoc2->numbers, - $testdoc2->textstring); -$seconds = getmicrotime() - $seconds; - -showDoc('Time to restore from cache', $seconds); - -showDoc('OK after restore'); -?> diff --git a/main/metadata/doc/testXht.php b/main/metadata/doc/testXht.php deleted file mode 100755 index 2876f33b23..0000000000 --- a/main/metadata/doc/testXht.php +++ /dev/null @@ -1,215 +0,0 @@ - - * @package chamilo.metadata - */ -/** - * Chamilo Metadata: XHT test and demo - */ - -require('../../inc/lib/xmd.lib.php'); -require('../../inc/lib/xht.lib.php'); - - -// XML DOCUMENT ---------------------------------------------------------------> - -$testdoc = new xmddoc( -<< - Test for XML HTML Templates - This is a [b]test[/b] for &#911; XML with <some> "funny" stuff... - a new line and 1 inside tag. - - kw1 - kw2 - kw3 - - - IMS Content - 1.2.2 - - - - - - - - - en - - Simple exemplar content package - - -, this description was - modified -by - René - - - - - -
    -EOD -); - -if ($testdoc->error) die($testdoc->error); - - -// TEMPLATES ------------------------------------------------------------------> - -$xhtDoc = new xhtdoc( -<< - -Expires: Mon, 26 Jul 1997 05:00:00 GMT - - - - - - - - - -

    testXht

    - -

    {-X title-}

    - -Hello {-P p1-}! {-X description-}
    -{-X metadata/lom/general/description/langstring-}

    - -{-D label This is a funny -}{-C LABEL-}

    - - {-R keywords/keyword C KEYWORD-} -
    -There are {-R keywords/keyword P empty-}{-P number-} keywords...

    - - -

    - -{-R Langnames C LEVEL1-}

    - -{-D author {-V author-}-} -{-T author != empty -
    There is an author
    - - - -This text is re-calculated when the cache is no longer valid. - - - - -{-H {-P label-}-} :  - - - - - - {-D label {-L Kw-}-}{-C LABEL-}{-X .-} - - - - - - - - - - - -{-P rdepth-}.{-P key-}: {-R keywords/keyword C LEVEL2-}
    - - - - -{-P rdepth-}.{-P number-} - - - -EOD -); - -if ($xhtDoc->htt_error) die($xhtDoc->htt_error); - -$xhtDoc->xht_xmldoc = $testdoc; - - -// PREPARE FOR PROCESSING -----------------------------------------------------> - -function get_lang($word) -{ - if ($word == 'Kw') return 'Keyword'; - elseif ($word == 'Am') return '"Automatic"'; - elseif ($word == 'Langnames') - return array("de"=>"German", "fr"=>"French", "nl"=>"Dutch"); - else return 'To be translated'; -} - -$xhtDoc->xht_get_lang = 'get_lang'; - -$xhtDoc->xht_param['p1'] = 'world'; - -function md_cache($newtext) // callback from template (for cached HTML) -{ - if ($newtext === FALSE) // this is always the first callback - { - $cachedHtmlIsValid = FALSE; // in real examples, not always - - if ($cachedHtmlIsValid) - return 'Cached HTML'; - else - // do some preparations - return FALSE; // signals XHT to generate new text from template - } - else // after template expansion, XHT does a second callback - { - // store the new text in the cache... - // possibly modify the text to be output... - return $newtext; // often the output is identical to the new text - } -} - - -// GENERATE OUTPUT ------------------------------------------------------------> - -foreach (explode("\n", $xhtDoc->htt_array['HTTP']) as $httpXtra) - if ($httpXtra) header($httpXtra); - -echo "\n", $xhtDoc->xht_fill_template('HEAD'), - "\n\n\n\n"; - -$xhtDoc->xht_dbgn = 0; // for template debug info, set to e.g. 10000 - -echo $xhtDoc->xht_fill_template('MAIN'), - '

    Child nodes of "description":'; - -foreach($testdoc->children[$testdoc->xmd_select_single_element('description')] as $child) - echo '
    ', strlen($child), ': ', htmlspecialchars($child); -echo "\n\n\n\n"; - -if ($xhtDoc->xht_dbgn) echo $xhtDoc->xht_dbgo; - -// Note: XML document and templates would normally be fetched from (different) -// external sources, such as a file or a DB record... -?> diff --git a/main/metadata/importdocs.php b/main/metadata/importdocs.php deleted file mode 100755 index 43139ee4c0..0000000000 --- a/main/metadata/importdocs.php +++ /dev/null @@ -1,106 +0,0 @@ - -$getpostvars = array('dmo'); require('md_funcs.php'); - -define('EID_TYPE', 'Document'); define('AFTER_DOT', strlen(EID_TYPE) + 1); -define('OF_EID_TYPE', "eid LIKE '" . EID_TYPE . ".%'"); - -require('md_' . strtolower(EID_TYPE) . '.php'); - -// name of the language file that needs to be included -$language_file = 'md_' . strtolower(EID_TYPE); -include('../inc/global.inc.php'); -$nameTools = get_lang('Tool'); - -($nameTools && get_lang('Sorry')) or give_up( - 'Language file ' . $language_file . " doesn't define 'Tool' and 'Sorry'"); - -$_course = api_get_course_info(); isset($_course) or give_up(get_lang('Sorry')); - -$is_allowed_to_edit = isset($_user['user_id']) && $is_courseMember && api_is_allowed_to_edit(); -if (!$is_allowed_to_edit) give_up(get_lang('Denied')); - -$mdObj = new mdobject($_course, 0); -$mdStore = new mdstore($is_allowed_to_edit); // create table if needed - -require(api_get_path(LIBRARY_PATH) . 'xmd.lib.php'); -require(api_get_path(LIBRARY_PATH) . 'xht.lib.php'); - -require('md_phpdig.php'); - -$mdObj->mdo_add_breadcrump_nav(); // see 'md_' . EID_TYPE . '.php' - -$htmlHeadXtra[] = ' - - -'; -Display::display_header($nameTools); - - -if (isset($dmo)) // for future use -{ - echo '

    ', $dmo, '

    ', "\n"; // document metadata op - - // if ($dmo == get_lang('Index')) $dmo = $dmo; -} - -$result = $mdStore->mds_get_many('eid,indexabletext', OF_EID_TYPE); -echo get_lang('Tool'), ': ', Database::num_rows($result), "

    \n"; - -$idt = array(); $cidpar = '?cidReq=' . $_course['sysCode']; - -while ($row = Database::fetch_array($result)) // load indexabletexts in memory -{ - $mdObj = new mdobject($_course, substr($row['eid'], AFTER_DOT)); - $idt[$mdObj->mdo_url . $cidpar] = $row['indexabletext']; -} - -if (count($idt) && file_exists($phpDigIncCn)) -{ - require($phpDigIncCn); // switch to PhpDig DB - - foreach ($idt as $url => $text) - if (ereg('^http://([^/]+)/(.+)/([^/]+)\?cidReq=(.+)$', $url, $regs)) - { - $path = $regs[2] .'/'; $file = $regs[3] . '?cidReq=' . $regs[4]; - if ($site_id = remove_engine_entries('http://' . $regs[1] .'/', - $path, $file)) - { - echo '', "\n"; - index_words($site_id, $path, $file, - get_first_words($text, $path, $file), - get_keywords($text)); - echo '
    ', "\n"; - } - } - - if(isset($db)) - { - //mysql_select_db($_configuration['main_database'], $db); - Database::select_db($_configuration['main_database'], $db); - } -} -else -{ - echo 'No documents with metadata or no PhpDig in this course...
    '; -} - -if (false && file_exists($phpDigIncCn)) // future: buttons for operations -{ - echo '
    ', "\n", - '', "\n", - '', "\n", - '
    ', "\n"; -} - -Display::display_footer(); -?> diff --git a/main/metadata/importlinks.php b/main/metadata/importlinks.php deleted file mode 100755 index 7d2485a9aa..0000000000 --- a/main/metadata/importlinks.php +++ /dev/null @@ -1,355 +0,0 @@ - - -$getpostvars = array('lcn', 'slo'); require('md_funcs.php'); - -define('EID_TYPE', 'Link'); -define('OF_EID_TYPE', "eid LIKE '" . EID_TYPE . ".%'"); - -require('md_' . strtolower(EID_TYPE) . '.php'); - -// name of the language file that needs to be included -$language_file = 'md_' . strtolower(EID_TYPE); -include('../inc/global.inc.php'); -$nameTools = get_lang('Tool'); - -($nameTools && get_lang('Sorry')) or give_up( - 'Language file ' . $language_file . " doesn't define 'Tool' and 'Sorry'"); - -$_course = api_get_course_info(); isset($_course) or give_up(get_lang('Sorry')); - -$is_allowed_to_edit = isset($_user['user_id']) && $is_courseMember && api_is_allowed_to_edit(); -if (!$is_allowed_to_edit) give_up(get_lang('Denied')); - -$mdStore = new mdstore($is_allowed_to_edit); // create table if needed - -require(api_get_path(LIBRARY_PATH) . 'xmd.lib.php'); -require(api_get_path(LIBRARY_PATH) . 'xht.lib.php'); - -require('md_phpdig.php'); - -$mdObj = new mdobject($_course, 0); -$mdCat = $mdObj->mdo_dcmap_v['Coverage']; -$mdUrl = 'metadata/lom/technical/location[1]'; - -$mdObj->mdo_add_breadcrump_nav(); // see 'md_' . EID_TYPE . '.php' - -$htmldecode = array_flip(get_html_translation_table(HTML_SPECIALCHARS)); - - -function check_andor_get($row, $get = '', $check = '', $tobe = '') -{ - global $mdCat, $htmldecode; - - if (!$check && !$get) return FALSE; - - $regs = array(); // for use with ereg() - - if ($get == $mdCat && !$check) // cheat to be quicker - if (ereg('[^<]*([^<]+)<\/string>', - $row['mdxmltext'], $regs)) return strtr($regs[1], $htmldecode); - - if ($check == $mdCat && !$get) // cheat to be quicker - if (ereg('[^<]*([^<]+)<\/string>', - $row['mdxmltext'], $regs)) - return (strtr($regs[1], $htmldecode) == $tobe); - - $xmlDoc = new xmddoc(explode("\n", $row['mdxmltext'])); - if ($xmlDoc->error) return FALSE; - - if (!$check) return $xmlDoc->xmd_value($get); - - if ($xmlDoc->xmd_value($check) == $tobe) - return $get ? $xmlDoc->xmd_value($get) : TRUE; - - return FALSE; -} - - -function get_cat($catname) -{ - global $_course; $cateq = "category_title='". addslashes($catname) . "'"; - - $linkcat_table = Database::get_course_table(TABLE_LINK_CATEGORY); - $result = Database::query("SELECT id FROM $linkcat_table WHERE " . $cateq); - - if (Database::num_rows($result) >= 1 && ($row = Database::fetch_array($result))) - return $row['id']; // several categories with same name: take first - - return FALSE; -} - - -// SET CURRENT LINKS CATEGORY - HEADER ----------------------------------------> - -unset($lci); // category-id - -if (isset($lcn)) // category_title -{ - $lcn = substr(ereg_replace("[^\x20-\x7E\xA1-\xFF]", "", $lcn), 0, 255); - - $uceids = array(); $mceids = array(); - - $result = $mdStore->mds_get_many('eid,mdxmltext', OF_EID_TYPE); - - while ($row = Database::fetch_array($result)) - if (check_andor_get($row, '', $mdCat, $lcn)) $uceids[] = $row['eid']; - - if (($lci = get_cat($lcn)) !== FALSE) - { - $link_table = Database::get_course_table(TABLE_LINK); - $result = Database::query("SELECT id FROM $link_table WHERE category_id=" . $lci); - - while ($row = Database::fetch_array($result)) - { - $lceids[$id = (int) $row['id']] = ($eid = EID_TYPE . '.' . $id); - - if (in_array($eid, $uceids)) $mceids[] = $eid; - } - - $hdrInfo = ' ' . get_lang('WorkOn') . ' ' . htmlspecialchars($lcn, ENT_QUOTES, $charset) . - ', LC-id= ' . htmlspecialchars($lci, ENT_QUOTES, $charset); - } - elseif ($lcn) - { - $hdrInfo = ' (' . htmlspecialchars($lcn, ENT_QUOTES, $charset) . - ': ' . get_lang('NotInDB') . ')'; - } - else - unset($lcn); - - $uceids = array_diff($uceids, $mceids); // old entries with no link - - if (count($lceids) && count($uceids)) - { - $mdStore->mds_delete_many($uceids); $ufos = Database::affected_rows(); - } - - $interbreadcrumb[]= array( - 'url' => api_get_self() . '?lcn=' . urlencode($lcn), - 'name'=> get_lang('Continue') . ' ' . htmlspecialchars($lcn, ENT_QUOTES, $charset)); -} - -$htmlHeadXtra[] = ' - - -'; -Display::display_header($nameTools); - -// OPERATIONS -----------------------------------------------------------------> - -if ($ufos) echo '

    ', $ufos, ' ', get_lang('RemainingFor'), ' ', - htmlspecialchars($lcn, ENT_QUOTES, $charset), '

    ', "\n"; - -if (isset($slo)) echo '

    ', $slo, '

    ', "\n"; // selected links op - -if (isset($slo)) -if ($slo == get_lang('Create') && count($lceids)) -{ - foreach ($lceids as $id => $eid) - { - $mdObj = new mdobject($_course, $id); $xht = $mdObj->mdo_define_htt(); - $mdStore->mds_put($eid, $mdt = $mdObj->mdo_generate_default_xml_metadata(), - 'mdxmltext', '?'); - $xht->xht_xmldoc = new xmddoc(explode("\n", $mdt)); - $mdStore->mds_put($eid, $xht->xht_fill_template('INDEXABLETEXT'), - 'indexabletext'); - echo '", htmlspecialchars($eid, ENT_QUOTES, $charset), ' '; - } - echo '
    '; -} -elseif ($slo == get_lang('Remove') && count($lceids)) -{ - $mdStore->mds_delete_many($mceids); $aff = Database::affected_rows(); - - echo $aff, ' MDEs/ ', count($lceids), ' ', get_lang('MdCallingTool'), - '

    ', get_lang('AllRemovedFor'), - ' ', htmlspecialchars($lcn, ENT_QUOTES, $charset), '
    '; -} -elseif ($slo == get_lang('Remove') && count($mceids)) // obsolete category -{ - $mdStore->mds_delete_many($mceids); - - echo get_lang('AllRemovedFor'), ' ', htmlspecialchars($lcn, ENT_QUOTES, $charset), '
    '; -} -elseif ($slo == get_lang('Index') && file_exists($phpDigIncCn) && count($mceids)) -{ - $result = $mdStore->mds_get_many('eid,mdxmltext,indexabletext', - OF_EID_TYPE . " AND eid IN ('" . - implode("','", array_map('addslashes', $mceids)) . "')"); - - while ($row = Database::fetch_array($result)) // load indexabletexts in memory - $idt[check_andor_get($row, $mdUrl)] = $row['indexabletext']; - - require($phpDigIncCn); // switch to PhpDig DB - - foreach ($idt as $url => $text) - { - $pu = parse_url($url); - if (!isset($pu['scheme'])) $pu['scheme'] = "http"; - - if (isset($pu['host'])) - { - $url = $pu['scheme'] . "://" . $pu['host'] . "/"; $file = ''; - - if (($path = $pu['path'])) - if (substr($path, -1) == '/') $path = substr($path, 1); - else - { - $pi = pathinfo($path); $path = $pi['dirname']; - if ($path{0} == '\\') $path = substr($path, 1); - if ($path{0} == '/') $path = substr($path, 1) . '/'; - - $file = $pi['basename']; - } - - $file .= ($pu['query'] ? '?'.$pu['query'] : '') . - ($pu['fragment'] ? '#'.$pu['fragment'] : ''); - - - if ($site_id = remove_engine_entries($url, $path, $file)) - { - echo '', "\n"; - index_words($site_id, $path, $file, - get_first_words($text, $url . $path, $file), - get_keywords($text)); - echo '
    ', "\n"; - } - else - { - echo '', "\n"; - echo ''; - echo '
    ', htmlspecialchars($url, ENT_QUOTES, $charset), - '', htmlspecialchars($path, ENT_QUOTES, $charset), - '', htmlspecialchars($file, ENT_QUOTES, $charset), '
    ', "\n"; - } - } - elseif (isset($pu['scheme']) && $pu['scheme'] == 'mailto' && isset($pu['path'])) - { - if ($site_id = remove_engine_entries($url = 'mailto:' . $pu['path'], '')) - { - echo '', "\n"; - index_words($site_id, '', '', - get_first_words($text, $url, ''), - get_keywords($text)); - echo '
    ', "\n"; - } - else - { - echo '', "\n"; - echo ''; - echo '
    ', htmlspecialchars($url, ENT_QUOTES, $charset), - '', htmlspecialchars($path, ENT_QUOTES, $charset), - '', htmlspecialchars($file, ENT_QUOTES, $charset), '
    ', "\n"; - } - } - } - - if(isset($db)) - { - //mysql_select_db($_configuration['main_database'], $db); - Database::select_db($_configuration['main_database'], $db); - } -} -elseif ($slo == get_lang('Index')) -{ - echo 'Problem! PhpDig connect.php has gone ...'; -} - - -// STATISTICS -----------------------------------------------------------------> - -echo '

    ', get_lang('Statistics'), '

    ', "\n"; - -$result = $mdStore->mds_get_many('eid,mdxmltext', OF_EID_TYPE); -echo get_lang('TotalMDEs'), Database::num_rows($result), "\n"; - -while ($row = Database::fetch_array($result)) -{ - $cat = check_andor_get($row, $mdCat); - $perCat[$cat] = ($pc = $perCat[$cat]) ? $pc + 1 : 1; -} - -if (count($perCat)) -{ - echo '', "\n"; - foreach ($perCat as $cat => $number) - { - echo '', "\n"; - } - echo '
    ', $cat == $lcn ? '' : '(', htmlspecialchars($cat, ENT_QUOTES, $charset), - $cat == $lcn ? '' : ')', ':', - $number, '
    ', "\n"; -} - -if (isset($lci)) -{ - echo '

    ', htmlspecialchars($lcn, ENT_QUOTES, $charset), ' ', get_lang('MdCallingTool'), - ': ', count($lceids), '
    ', "\n"; -} - - - -// SELECT & FOOTER ------------------------------------------------------------> - -echo '

    ', $nameTools, $hdrInfo, '

    ', "\n"; - -echo '
    ', "\n"; - -if (count($lceids)) echo - '', "\n"; -if ($perCat[$lcn]) echo - '', "\n"; -if ($perCat[$lcn] && file_exists($phpDigIncCn)) echo - '', "\n"; - -echo '
    ', "\n"; - -if (count($perCat)) foreach ($perCat as $cat => $number) - $perCat[$cat] = '(' . htmlspecialchars($cat, ENT_QUOTES, $charset) . ')'; - -$linkcat_table = Database::get_course_table(TABLE_LINK_CATEGORY); -$result = Database::query("SELECT category_title FROM $linkcat_table"); - -while ($row = Database::fetch_array($result)) -{ - $cat = $row['category_title']; $hcat = htmlspecialchars($cat, ENT_QUOTES, $charset); - if ($perCat[$cat] == $hcat) $dups[] = $cat; - else $perCat[$cat] = $hcat; -} - -if (count($dups)) -{ - $warning = get_lang('WarningDups');; - - foreach ($dups as $cat) unset($perCat[$cat]); -} - -echo '

    ', get_lang('OrElse'), $warning, '

    ', "\n", // select new target - '
    ', "\n", - '
    ', "\n", - get_lang('SLC'), ' :', "\n", '', "\n", - '
    ', "\n", '
    ', "\n"; - -Display::display_footer(); -?> diff --git a/main/metadata/importmanifest.php b/main/metadata/importmanifest.php deleted file mode 100755 index 15ab0d7f41..0000000000 --- a/main/metadata/importmanifest.php +++ /dev/null @@ -1,662 +0,0 @@ - - -$getpostvars = array('sdisub','workWith','sdi','smo'); require('md_funcs.php'); - -define('EID_TYPE', 'Scorm'); define('TPLEN', strlen(EID_TYPE) + 1); - -require('md_' . strtolower(EID_TYPE) . '.php'); - -// name of the language file that needs to be included -$language_file = 'md_' . strtolower(EID_TYPE); -include('../inc/global.inc.php'); -$nameTools = get_lang('Tool'); - -if (!isset($sdisub)) $sdisub = ''; -$sdisub = substr(ereg_replace("[^0-9A-Za-z]", "", $sdisub), 0, 4); -// $sdisub is for split manifests - Scorm.NNN.$sdisub_xxx e.g. Scorm.3.1979_12 - -define('MFFNAME', 'imsmanifest'); define('MFFDEXT', '.xml'); -define('HTF', 'mdp_scorm.htt'); - -$regs = array(); - -($nameTools && get_lang('Sorry')) or give_up( - 'Language file ' . $language_file . " doesn't define 'Tool' and 'Sorry'"); - -$_course = api_get_course_info(); isset($_course) or give_up(get_lang('Sorry')); - -$is_allowed_to_edit = isset($_user['user_id']) && $is_courseMember && api_is_allowed_to_edit(); -if (!$is_allowed_to_edit) give_up(get_lang('Denied')); - -$baseWorkDir = get_course_path() . ($courseDir = $_course['path'] . '/scorm'); - -$mdStore = new mdstore($is_allowed_to_edit); // create table if needed - -require(api_get_path(LIBRARY_PATH) . 'xmd.lib.php'); -require(api_get_path(LIBRARY_PATH) . 'xht.lib.php'); - -require('md_phpdig.php'); - - -// SET CURRENT SCORM DIRECTORY - HEADER ---------------------------------------> - -if (isset($workWith)) // explicit in URL, or selected at bottom of screen -{ - $scormdocument = Database::get_course_table(TABLE_LP_MAIN); - $sql = "SELECT id FROM $scormdocument WHERE path='". Database::escape_string(api_substr($workWith,1)) . "' OR path='". Database::escape_string(substr($workWith,1)) . "/.'"; - $result = Database::query($sql); - - if (Database::num_rows($result) == 1) - { - if (($row = Database::fetch_array($result))) - { - $sdi = $row['id']; - } - } -} - -if (isset($sdi) && is_numeric($sdi) && $sdi > 0 && $sdi == (int) $sdi) -{ - $mdObj = new mdobject($_course, $sdi); $workWith = $mdObj->mdo_path; - $hdrInfo = ' ' . get_lang('WorkOn') . ' ' . - ($workWith ? htmlspecialchars($workWith, ENT_QUOTES, $charset) . ', ' : '') . - 'SD-id= ' . htmlspecialchars($sdi, ENT_QUOTES, $charset) . - ($sdisub ? ' (' . htmlspecialchars($sdisub, ENT_QUOTES, $charset) . ')' : ''); -} -else -{ - unset($sdi); $mdObj = new mdobject($_course, 0); - if ($workWith) $hdrInfo = ' (' . htmlspecialchars($workWith, ENT_QUOTES, $charset) . - ': ' . get_lang('NotInDB') . ')'; unset($workWith); -} - -define('UZYX', 'UZYX'); // magic word to repeat for all $sdisub - -if (($sdiall = ($sdisub == UZYX))) -{ - $sdisub = ''; $sdiall = array(); - if (($dh = opendir($baseWorkDir . $workWith))) - { - while (FALSE !== ($file = readdir($dh))) - if (ereg('^'.MFFNAME.'(.+)\\'.MFFDEXT .'$', $file, $regs)) - $sdiall[] = $regs[1]; - closedir($dh); - } - sort($sdiall); -} - -$originalHdrInfo = $hdrInfo; - -function slurpmanifest() -{ - global $baseWorkDir, $workWith, $sdisub, $mfContents, $xht_doc, $charset; - $fmff = $baseWorkDir .'/'. $workWith . '/' . MFFNAME . $sdisub . MFFDEXT; - if (file_exists($fmff)) - { - if (($mfContents = @fgc($fmff))) - { - set_time_limit(120); // for analyzing the manifest file - $xht_doc = new xmddoc(explode("\n", $mfContents)); - if (!$xht_doc->error) return ''; // keeping $mfContents and $xht_doc - - unset($mfContents); - return get_lang('ManifestSyntax') . ' ' . htmlspecialchars($xht_doc->error, ENT_QUOTES, $charset); - } - else - { - return get_lang('EmptyManifest'); - } - } - else - { - return get_lang('NoManifest'); - } -} - -if (isset($workWith)) // now checked to be a valid path in scormdocument -{ - if ($mdObj->mdo_filetype == 'folder') // a folder with a manifest? - { - if (($errmsg = slurpmanifest())) $hdrInfo .= ' ' . $errmsg; - } - else - { - $hdrInfo .= ' ' . get_lang('NotFolder'); unset($sdi); - } -} - -$mdObj->mdo_add_breadcrump_nav(); // see 'md_' . EID_TYPE . '.php' -if (isset($sdi)) $interbreadcrumb[]= array( - 'url' => api_get_self() . '?sdi=' . urlencode($sdi) . - ($sdisub ? '&sdisub=' . urlencode($sdisub) : - ($sdiall ? '&sdisub='.UZYX : '')), - 'name'=> get_lang('Continue') . ' ' . $sdi . - ($sdisub ? ' (' . $sdisub . ')' : ($sdiall ? ' ('.UZYX.')' : ''))); - -$htmlHeadXtra[] = ' - - -'; -Display::display_header($nameTools); - -// OPERATIONS -----------------------------------------------------------------> - -if (isset($smo)) echo '

    ', $smo, '

    ', "\n"; // selected manifest op - -if (isset($smo)) -if ($smo == get_lang('UploadMff')) -{ - if (is_uploaded_file($filespec = $_FILES['import_file']['tmp_name']) && - filesize($filespec) && ($myFile = @fopen($filespec, 'r'))) - { - fclose($myFile); - - if (move_uploaded_file($filespec, - $baseWorkDir . $workWith . '/' . MFFNAME . $sdisub . MFFDEXT)) - { - echo get_lang('MffOk'); $hdrInfo = $originalHdrInfo; - - if (($errmsg = slurpmanifest())) $hdrInfo .= ' ' . $errmsg; - } - else echo get_lang('MffNotOk'); - } - else echo get_lang('MffFileNotFound'); -} -elseif ($smo == get_lang('UploadHtt')) -{ - $filespec = $_FILES['import_file']['tmp_name']; - if (is_uploaded_file($filespec) && filesize($filespec) && ($myFile = @fopen($filespec, 'r'))) - { - fclose($myFile); - $htt_file = $baseWorkDir .'/'. $workWith . '/' . HTF; - if (move_uploaded_file($filespec,$htt_file)) - { - echo get_lang('HttOk'); - } - else - { - echo get_lang('HttNotOk'); - } - } - else - { - echo get_lang('HttFileNotFound'); - } -} -elseif ($smo == get_lang('RemoveHtt')) -{ - @unlink($fhtf = $baseWorkDir . $workWith . '/' . HTF); - if (file_exists($fhtf)) - echo get_lang('HttRmvNotOk'); - else echo get_lang('HttRmvOk'); -} -elseif ($smo == get_lang('Import')) -{ - define('TREETOP', 'organizations/organization'); - define('TITLE', 'title'); - define('SUBITEM', 'item'); - define('IDENTIF', 'identifier'); - define('ITEMID', '@'.IDENTIF); - define('SUBIT', SUBITEM.'/'.ITEMID); - define('RESOURCE', 'resources/resource'); - define('WHERE', ITEMID); - define('ISITEM', '@identifierref'); - define('HREF', 'href'); - define('WEBF', '@'.HREF); - define('FILE', 'file'); - define('THUMB', FILE.'[1]/'.WEBF); - - function resource_for($elem) - { - global $xht_doc; - - $resForItem = $xht_doc->xmd_select_elements_where(RESOURCE, - WHERE, $xht_doc->xmd_value(ISITEM, $elem)); - - return (count($resForItem) == 0) ? -1 : $resForItem[0]; - } - - function store_md_and_traverse_subitems($mfdocId, $level, $counter, - $contextElem, $treeElem, $parentElem) - { - global $_user, $xht_doc, $mdStore, $mdObj, $sdisub, $charset; - - // $contextElem -> @identifier, metadata/lom - // $treeElem -> title, items - - $itemId = $xht_doc->xmd_value(ITEMID, $contextElem); - if ($sdisub && $level == 1 && $sdisub != $itemId) return; - - // : - // ... - // - // ... - // - // ... - // - // ... - // - - set_time_limit(30); // again 30 seconds from here on... - - $mddoc = new xmddoc(''); // version, name ? - $mddoc->xmd_set_attribute(0, 'level', $level, FALSE); - $mddoc->xmd_set_attribute(0, 'number', $counter, FALSE); - $mddoc->xmd_set_attribute(0, IDENTIF, $itemId, FALSE); - - if ($level == 0) - { - $mddoc->xmd_set_attribute(0, 'created', date('Y/m/d H:i:s'), FALSE); - $mddoc->xmd_set_attribute(0, 'by', $_user['user_id'], FALSE); - } - - - $mddoc->xmd_add_text_element(TITLE, - $xht_doc->xmd_value(TITLE, $treeElem)); - - if (($ppnId = $xht_doc->xmd_value(ITEMID, $parentElem))) $mddoc-> - xmd_add_element('parent', 0, array(IDENTIF => $ppnId)); - if (($ppnId = $xht_doc->xmd_value('-'.SUBIT, $treeElem))) $mddoc-> - xmd_add_element('previous', 0, array(IDENTIF => $ppnId)); - if (($ppnId = $xht_doc->xmd_value('+'.SUBIT, $treeElem))) $mddoc-> - xmd_add_element('next', 0, array(IDENTIF => $ppnId)); - - if (($srcElem = resource_for($treeElem)) > 0) - { - // change stuff below to xmd_copy_foreign_child ? - $resElem = $mddoc->xmd_add_element('resource', 0, - array(HREF => $xht_doc->xmd_value(WEBF, $srcElem))); - foreach ($xht_doc->xmd_select_elements(FILE, $srcElem) as $fileElem) - $mddoc->xmd_add_element(FILE, $resElem, - array(HREF => $xht_doc->xmd_value(WEBF, $fileElem))); - } - - $mddoc->xmd_copy_foreign_child($xht_doc, - $xht_doc->xmd_select_single_element('metadata', $contextElem)); - - foreach ($xht_doc->xmd_select_elements(SUBITEM, $treeElem) as $subElem) - $mddoc->xmd_add_element('child', 0, - array(IDENTIF => $xht_doc->xmd_value(ITEMID, $subElem))); - - $mdt = $mddoc->xmd_xml(); - - $xhtDoc = $mdObj->mdo_define_htt(); - $xhtDoc->xht_xmldoc = $mddoc; // $xhtDoc->xht_param['xxx'] = 'yyy'; - - $mdStore->mds_put($eid = EID_TYPE . '.' . $mfdocId . '.' . $itemId, - $mdt, 'mdxmltext', '?'); - $mdStore->mds_put($eid, $ixt = - $xhtDoc->xht_fill_template('INDEXABLETEXT'), 'indexabletext'); - - if ($level == 0) // store a copy as 'Scorm.nnn' - { - $mdStore->mds_put(EID_TYPE . '.' . $mfdocId, $mdt, 'mdxmltext', '?'); - $mdStore->mds_put(EID_TYPE . '.' . $mfdocId, $ixt, 'indexabletext'); - } - - echo $level <= 1 ? '
    '.$level.'/ ' : ' ', htmlspecialchars($itemId, ENT_QUOTES, $charset); - flush(); $loopctr = 0; - - foreach ($xht_doc->xmd_select_elements(SUBITEM, $treeElem) as $subElem) - { - store_md_and_traverse_subitems($mfdocId, $level + 1, ++$loopctr, - $subElem, $subElem, $contextElem); - // note: replacing this recursion by queue+loop makes it slower! - } - } - - function content_for_index_php($scid) - { - // 'if {}' and 'else {}' are string literals spanning several lines - - return '', api_get_path(SYS_PATH), - str_replace('', $scid, // 2 * replace in $drs-line below -' - else - { - $drs = ""; $scormid = ""; - require($drs. "main/metadata/playscormmdset.inc.php"); - } -' )) . '?' . '>'; - } - - if ($mfContents) - { - if ($sdiall) - { - foreach ($sdiall as $sdisub) - { - if (($errmsg = slurpmanifest())) - echo '? ', $sdisub, ': ', $errmsg, '
    '; - else - store_md_and_traverse_subitems($sdi, 0, 1, 0, - $xht_doc->xmd_select_single_element(TREETOP), -1); - } - $sdisub = ''; - } - else // just once, slurpmanifest() has already been done - store_md_and_traverse_subitems($sdi, 0, 1, 0, - $xht_doc->xmd_select_single_element(TREETOP), -1); - - $playIt = $baseWorkDir .'/'. $workWith . '/index.php'; - $fileHandler = @fopen($playIt, 'w'); - @fwrite($fileHandler, content_for_index_php($sdi)); - @fclose($fileHandler); - - echo '
    ', htmlspecialchars($workWith, ENT_QUOTES, $charset); - if (file_exists($playIt)) echo '/index.php ', - htmlspecialchars(date('Y/m/d H:i:s', filemtime($playIt)), ENT_QUOTES, $charset); - } -} -elseif ($smo == get_lang('Remove') && $sdisub) -{ - $screm = EID_TYPE . '.' . $sdi . '.' . $sdisub; - $mdStore->mds_delete_offspring($screm, '\_'); // SQL LIKE underscore - echo htmlspecialchars($screm . '_*: ' . Database::affected_rows(), ENT_QUOTES, $charset), '
    '; -} -elseif ($smo == get_lang('Remove')) // remove all, regardless of $sdiall -{ - $mdStore->mds_delete($screm = EID_TYPE . '.' . $sdi); - echo htmlspecialchars($screm . ': ' . Database::affected_rows(), ENT_QUOTES, $charset), '
    '; - $mdStore->mds_delete_offspring($screm); - echo htmlspecialchars($screm . '.*: ' . Database::affected_rows(), ENT_QUOTES, $charset), '

    ', - '' . get_lang('AllRemovedFor') . ' ' . $screm . '
    '; -} -elseif ($smo == get_lang('Index') && file_exists($phpDigIncCn) && - ereg('^http://([^/]+)/(.+)/index\.php$', $mdObj->mdo_url, $regs)) -{ - $result = $mdStore->mds_get_many('eid,mdxmltext,indexabletext', - "eid LIKE '" . EID_TYPE . "." . $sdi . - ($sdisub ? "." . $sdisub . "\_%'" : ".%'") . - ($sdiall ? "" : " AND NOT INSTR(eid,'_')")); // SQL LIKE underscore - - while ($row = Database::fetch_array($result)) // load indexabletexts in memory - { - // URL: index.php[?sid=xxx[&thumb=yyy]] (file[1]/@href: pptslnnn_t.jpg) - - $th = ''; $indtxt = $row['indexabletext']; - - if (($fh = strpos($rx = $row['mdxmltext'], 'file href="')) !== FALSE) - if (($cq = strpos($rx, '"', $fh += 11)) !== FALSE) - if (ereg('^pptsl[0-9]+_t\.jpg$', $thwf = substr($rx, $fh, $cq - $fh))) - $th = '&thumb=' . urlencode($thwf); - - if ($th == '' && ($sclvl = strpos($indtxt, 'scorm-level-')) !== FALSE) - $th = '&thumb=scorm-level-' . $indtxt{$sclvl + 12} . '.jpg'; - - $idt[($dotpos = strpos($ri = $row['eid'], '.', TPLEN)) !== FALSE ? - ('index.php?sid=' . urlencode(substr($ri, $dotpos+1)) . $th) : - 'index.php'] = $indtxt; - } - - require($phpDigIncCn); // switch to PhpDig DB - - if (($site_id = remove_engine_entries('http://' . $regs[1] .'/', $path = - $regs[2] . '/', $sdisub ? 'index.php?sid=' . $sdisub . '_' : ''))) - { - echo '', "\n"; - foreach ($idt as $url => $text) - { - set_time_limit(30); // again 30 seconds from here on... - index_words($site_id, $path, $url, - get_first_words($text, $path, $url), get_keywords($text)); - } - echo '
    ', "\n"; - } - // possible enhancement: UPDATE spider record for still existing pages - - if(isset($db)) { - //mysql_select_db($_configuration['main_database'], $db); - Database::select_db($_configuration['main_database'], $db); - } -} -elseif ($smo == get_lang('Index')) -{ - echo 'Problem! PhpDig connect.php has gone or else URL "' . - htmlspecialchars($mdObj->mdo_url, ENT_QUOTES, $charset) . - '" is not like "http://xxxx/yyy.../zzz/index.php"'; -} - - -// STATISTICS -----------------------------------------------------------------> - -echo '

    ', get_lang('Statistics'), '

    ', "\n"; - -$result = $mdStore->mds_get_many('eid', "eid LIKE '" . EID_TYPE . ".%'"); -echo get_lang('TotalMDEs'), Database::num_rows($result), "\n"; - -while ($row = Database::fetch_array($result)) -{ - $eid_id = substr($eid = $row['eid'], TPLEN); - - if (($dotpos = strpos($eid_id, '.'))) - $eid_id = substr($eid_id, 0, $dotpos); - else - $mdtmain[$eid_id] = $mdStore->mds_get($eid); - - $perId[$eid_id] = ($pi = $perId[$eid_id]) ? $pi + 1 : 1; -} - - -if (isset($sdi)) -{ - $mdo = new mdobject($_course, $sdi); - echo '
    ', htmlspecialchars($mdo->mdo_path, ENT_QUOTES, $charset), ', SD-id ', $sdi, ': ', - ($perId[$sdi] ? $perId[$sdi] : '0'), ' ', - ($mdtmain[$sdi] ? '- " . - get_lang('MainMD') . '' : ''), "\n"; -} - -if (count($perId)) -{ - foreach ($perId as $id => $number) - { - $mdo = new mdobject($_course, $id); - if (!($pth = $mdo->mdo_path)) - { - $pth = $mdtmain[$id]; // fetch something simple without parsing - if ($ttopen = strpos($pth, '')) - if ($ttclose = strpos($pth, '', $ttopen)) - $pth = ' ' . api_html_entity_decode - (substr($pth, $ttopen+7, $ttclose-$ttopen-7), ENT_QUOTES, $charset); - else $pth = ' ' . substr($pth, $ttopen+7, 30); - else $pth = ' ' . substr($pth, 0, 30); - } - - $pathId[$pth] = $id; - } - - echo '

    ', "\n"; ksort($pathId); $wwl = strlen($workWith); - - foreach ($pathId as $pth => $id) if ($wwl == 0 || - ($wwl < strlen($pth) && substr($pth, 0, $wwl) == $workWith)) - { - $tmfdt = file_exists($tfmff = $baseWorkDir . $pth . '/' . MFFNAME . $sdisub . MFFDEXT) ? - date('Y/m/d H:i:s', filemtime($tfmff)) : '-'; - echo '', - '', "\n"; - } - echo '
    ', htmlspecialchars($tmfdt, ENT_QUOTES, $charset), '', htmlspecialchars($pth, ENT_QUOTES, $charset), - '(SD-id ', $id, - '):', $perId[$id], '
    ', "\n"; -} - -if ($mfContents) -{ - echo $workWith, '/', MFFNAME . $sdisub . MFFDEXT, ': ', - htmlspecialchars(date('Y/m/d H:i:s', filemtime($fmff)), ENT_QUOTES, $charset) , ", \n", - substr_count($mfContents, "\n") + 1, - ' ' . get_lang('Lines') . '.', "\n"; - - if (!$sdisub && ($dh = opendir($baseWorkDir . $workWith))) - { - $nsplit = array(); - while (FALSE !== ($file = readdir($dh))) - if (ereg('^'.MFFNAME.'(.+)\\'.MFFDEXT .'$', $file, $regs)) - { - $nsplit []= $regs[1]; - } - closedir($dh); - - if (count($nsplit)) - { - echo '
    ', get_lang('SplitData'); sort($nsplit); - foreach ($nsplit as $ns) - { - $result = $mdStore->mds_get_many('eid', "eid LIKE '" . - EID_TYPE . "." . $sdi . "." . $ns . "\_%'"); - $nns = Database::num_rows($result); - echo $ns, $nns ? '_ ' . $nns : '', '; '; - } - echo '
    '; - } - } -} - -if (file_exists($baseWorkDir . $workWith . '/index.php')) - echo "mdo_url . "', '', '')\">" . get_lang('Play'), '', "\n"; - -if (file_exists($fhtf = $baseWorkDir . $workWith . '/' . HTF)) - echo '
    ', $workWith, '/', HTF, ': ', - htmlspecialchars(date('Y/m/d H:i:s', filemtime($fhtf)), ENT_QUOTES, $charset) , "\n"; - - - -// SELECT & FOOTER ------------------------------------------------------------> - -if ($mfContents || $xht_doc->error) -{ - echo '

    ', get_lang('UploadMff'), "

    \n\n", - '
    ', "\n", - '', "\n", - '', "\n", - '' . "\n
    \n"; -} - -echo '

    ', get_lang('UploadHtt'), file_exists($fhtf) ? - (' + ' . get_lang('RemoveHtt')) : '', "

    \n\n", - - '
    ', "\n", - '', "\n", - '', "\n", - ''; -if (file_exists($fhtf)) echo - ''; -echo "\n
    \n"; - -echo '

    ', $nameTools, $hdrInfo, '

    ', "\n"; - -if ($mfContents || $perId[$sdi]) // buttons for manifest operations -{ - echo '
    ', "\n"; - if ($mfContents) echo - '', "\n"; - if ($perId[$sdi]) echo - '', "\n"; - if ($mfContents && $perId[$sdi] && file_exists($phpDigIncCn)) echo - '', "\n"; - echo - '
    ', "\n"; -} -else -{ - echo '(', get_lang('NonePossible'), '...)'; -} - - -function showSelectForm($label, $specifics) -{ - echo '', "\n", - '
    ', "\n", - get_lang($label), ' :', "\n", $specifics, "\n", - '', "\n", - '
    ', "\n"; -} - -echo '

    ', get_lang('OrElse'), '

    ', "\n\n"; - -$specifics = ''); - -showSelectForm('SDI', - '' . - '()' . "\n"); - -echo '
    ', "\n"; - - -Display::display_footer(); -?> diff --git a/main/metadata/index.php b/main/metadata/index.php deleted file mode 100755 index 29178c7516..0000000000 --- a/main/metadata/index.php +++ /dev/null @@ -1,186 +0,0 @@ - - -$result = Database::query("SELECT isocode FROM " .Database :: get_main_table(TABLE_MAIN_LANGUAGE) ." WHERE available='1' ORDER BY isocode ASC"); - -$sep = ":"; $langLangs = $sep . "xx" . $sep . "xx"; - -while ($row = Database::fetch_array($result)) - if (($isocode = $row['isocode'])) - $langLangs .= ",, " . $isocode . $sep . $isocode; - - -// XML and DB STUFF -----------------------------------------------------------> - -$is_allowed_to_edit = isset($_user['user_id']) && $is_courseMember && api_is_allowed_to_edit(); - -$mdStore = new mdstore($is_allowed_to_edit); - -if (($mdt_rec = $mdStore->mds_get(EID)) === FALSE) // no record, default XML - $mdt = $mdObj->mdo_generate_default_xml_metadata(); -else $mdt = $mdt_rec; - -$xhtxmldoc = new xmddoc(explode("\n", $mdt)); - -$httfile = ($xhtxmldoc->error) ? 'md_editxml.htt' : HTT . '.htt'; - -if (!$xhtxmldoc->error && $mdt_rec !== FALSE && - method_exists($mdObj, 'mdo_override')) - $mdt = $mdObj->mdo_override($xhtxmldoc); - -$xhtDoc = define_htt($httfile, $urlp, $_course['path']); - -define('HSH', md5($mdt . LFN . $nameTools . get_lang('Sorry') . $httfile . - implode('{}', $xhtDoc->htt_array))); // cached HTML depends on LFN+HTT - -$xhtDoc->xht_param['traceinfo'] = $xhtxmldoc->error; -$xhtDoc->xht_param['dbrecord'] = $mdt_rec !== FALSE ? 'TRUE' : ''; - -$xhtDoc->xht_xmldoc = $xhtxmldoc; - -if ($is_allowed_to_edit) $xhtDoc->xht_param['isallowedtoedit'] = 'TRUE'; - -// MD updates to Doc and DB -if ($is_allowed_to_edit && isset($_POST['mda'])) { - $mdt = $mdStore->mds_update_xml_and_mdt($mdObj, $xhtDoc->xht_xmldoc, - get_magic_quotes_gpc() ? stripslashes($_POST['mda']) : $_POST['mda'], - EID, $xhtDoc->xht_param['traceinfo'], $mdt_rec !== FALSE); - - if ($mdt_rec !== FALSE) { - if (strpos($xhtDoc->xht_param['traceinfo'], 'DELETE') !== FALSE) - $xhtDoc->xht_param['dbrecord'] = ''; - } else if (strpos($xhtDoc->xht_param['traceinfo'], 'INSERT') !== FALSE) - $xhtDoc->xht_param['dbrecord'] = 'TRUE'; - - if (method_exists($mdObj, 'mdo_storeback')) - $mdObj->mdo_storeback($xhtDoc->xht_xmldoc); - - $mdt_rec = FALSE; // cached HTML obsolete, must re-apply templates -} elseif ($is_allowed_to_edit && $_POST['mdt']) { - // md_editxml.htt - $mdStore->mds_put(EID, - get_magic_quotes_gpc() ? stripslashes($_POST['mdt']) : $_POST['mdt'], - 'mdxmltext', '?'); - $mdStore->mds_put(EID, HSH, 'md5'); - - $xhtDoc->xht_param['dbrecord'] = 'TRUE'; - - $mdt = ''; $xhtDoc->xht_param['traceinfo'] = get_lang('PressAgain'); - - $mdt_rec = FALSE; // cached HTML obsolete, must re-apply templates -} - -$xhtDoc->xht_param['mdt'] = $mdt; - -define('CACHE_IS_VALID', isset($mdt_rec) && $mdt_rec !== FALSE && - HSH && HSH == $mdStore->mds_get(EID, 'md5')); - - -function md_part($part, $newtext) // callback from template (HTML cache in DB) -{ - global $mdStore; - - if ($newtext === FALSE) - { - if (!CACHE_IS_VALID) return FALSE; - return '' . $mdStore->mds_get(EID, $part); - } - else - { - $mdStore->mds_put(EID, HSH, 'md5'); - $mdStore->mds_put(EID, $newtext, $part); - - return $newtext; - } -} - -function md_part1($newtext) { return md_part('htmlcache1', $newtext); } -function md_part2($newtext) { return md_part('htmlcache2', $newtext); } -function md_indexabletext($newtext) { return md_part('indexabletext', $newtext); } - - -// GENERATE OUTPUT ------------------------------------------------------------> - -foreach (explode("\n", $xhtDoc->htt_array['HTTP']) as $httpXtra) - if ($httpXtra) $httpHeadXtra[] = $httpXtra; - -$xhtDoc->xht_get_lang = 'get_lang'; - -function resource_for($e) {return $e;} // dummy, '=/' not used here -$xhtDoc->xht_resource = 'resource_for'; - -$htmlHeadXtra[] = $xhtDoc->xht_fill_template('HEAD'); - -$mdObj->mdo_add_breadcrump_nav(); // see 'md_' . EID_TYPE . '.php' -$noPHP_SELF = TRUE; // in breadcrumps - -Display::display_header($nameTools); echo "\n"; - -$xhtDoc->xht_dbgn = DBG; // for template debug info, set to e.g. 10000 -if (($ti = $xhtDoc->xht_param['traceinfo'])) $xhtDoc->xht_param['traceinfo'] = - '
    Trace information
    ' . htmlspecialchars($ti, ENT_QUOTES, $charset); - -echo $xhtDoc->xht_fill_template('METADATA'), "\n"; - -if ($xhtDoc->xht_dbgn) echo $xhtDoc->xht_dbgo; - -Display::display_footer(); -?> diff --git a/main/metadata/md_document.htt b/main/metadata/md_document.htt deleted file mode 100755 index 0f3f76f976..0000000000 --- a/main/metadata/md_document.htt +++ /dev/null @@ -1,262 +0,0 @@ - - - - - - - - -{-D TRUE TRUE-}{-D XML application/xml;utf-8-} - -
    -{-H {-E md_indexabletext C METADATA_INDEXABLETEXT-}-} -
    - - - -
    -{-T dbrecord == empty
    -} -{-E md_part1 C METADATA_PART1-} -{-T dbrecord == empty
    -} - -{-T isallowedtoedit == TRUE - -
    {-P traceinfo-}
    - -
    - - - - - - {-T dbrecord != empty - - - -} -   -{-D techfmt {-V metadata/lom/technical/format-}-}{-T techfmt == XML - - -} -
    - - - - -} - -{-T keywordscache != empty - -
    - - - -  {-L ClickKw-} - {-P keywordscache-} -
    - -
    - {-L KwHelp-} -
    - - -} - -{-T keywordscache == empty - - -} - - -
    - - - - - - -

    {-L Tool-}: {-X metadata/lom/general/identifier/entry-}

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
         
    {-D label Language-}{-C LABEL-}{-D xpath metadata/lom/general/language-}{-C LANGSELECT-}{-D xpath metadata/lom/general/identifier/catalog-}{-D iclass disabled class="wd2" -}{-C INPUT-}{-D label Identifier-}{-C LABEL-}{-D xpath metadata/lom/general/identifier/entry-}{-D iclass class="wd2" onKeyPress="javascript: return isValidChar(event, '[a-z0-9\x08\x25\x27\*\.\'\(\)_!-]', 'i');" -}{-C INPUT-}
    {-D label Title-}{-C LABEL-}{-D xpath metadata/lom/general/title/string/@language-}{-C LANGSELECT-}{-D xpath metadata/lom/general/title/string-}{-C INPUTW-}
    {-D label Description-}{-C LABEL-}{-C MDLANGSELECT-}{-D xpath metadata/lom/general/description/string-}{-C INPUTW-}
    {-D label Coverage-}{-C LABEL-}{-D xpath metadata/lom/general/coverage/string-}{-C INPUTW-}
    {-D label Keyword-}{-C LABEL-}{-C INPUT_ALLKWDS-}
    {-D label Rights-}{-C LABEL-}{-D xpath metadata/lom/rights/description/string-}{-C INPUTW-}
    {-D label Version-}{-C LABEL-}{-D xpath metadata/lom/lifeCycle/version/string-}{-D iclass class="wd2" -}{-C INPUT-}{-D label Status-}{-C LABEL-} - {-D xpath metadata/lom/lifeCycle/status/value-}{-D optionarray Statuses-}{-C SELECT-} - {-D xpath metadata/lom/rights/cost/value-}{-D optionarray Costs-}{-C SELECT-} - {-D xpath metadata/lom/rights/copyrightAndOtherRestrictions/value-}{-D optionarray Copyrights-}{-C SELECT-} -
    {-D label CreatedSize-}{-C LABEL-} - {-D xpath metadata/lom/lifeCycle/contribute[1]/date/dateTime-}{-D iclass class="wd1" onKeyUp="javascript: checkValid(this,'^[0-9]{4}-[0-9]{2}-[0-9]{2}$','i');" -}{-C INPUT-} - {-D xpath metadata/lom/technical/size-}{-D iclass class="wd1" onKeyPress="javascript: return isValidChar(event, '[0-9\x08\x25\x27]', 'i');" -}{-C INPUT-} - {-D label Author-}{-C LABEL-}{-D xpath metadata/lom/lifeCycle/contribute[1]/entity-}{-C INPUTW-}
    {-D label Format-}{-C LABEL-}{-D xpath metadata/lom/technical/format-}{-D optionarray Formats-}{-C SELECT-}{-D label Location-}{-C LABEL-}{-D xpath metadata/lom/technical/location-}{-C INPUTW-}
         
    - - - - - {-V metadata/lom/general/title/string-} txt-sep - {-R metadata/lom/general/keyword C KWTEXT-} txt-sep - {-V metadata/lom/general/description[1]/string-} txt-end - document-type - {-V metadata/lom/lifeCycle/contribute[1]/entity-} - {-V metadata/lom/lifeCycle/contribute[1]/date/dateTime-} - {-V metadata/lom/technical/format-} - - - - - {-V string-}-kw - - - - -{-L {-P label-}-} : - - - - - - - - - -{-D optionarray Langs-}{-C SELECT-} - - - - - - - - - - - - - - -{-D iclass class="wide" -}{-C INPUT-} - - - - - - - - - - - - - - - - - - - - - - -Expires: Mon, 26 Jul 1997 05:00:00 GMT - - - - - - {-D label Keyword-}{-D tip {-L KeywordTip-}-}{-C LABEL-} - - - {-D value {-X string-}-}{-D title metadata/lom/general/keyword[{-P number-}]/string-}{-C INPUTKWD-} - - - - - - - {-D label Keyword-}{-D tip {-L KeywordTip-}-}{-C LABEL-} - - {-D value {-X string-}-}{-D title metadata/lom/general/keyword[{-P number-}]/string-}{-C INPUTKWD-} - - - - - - - - - - -Small problems with NS 7 and Mozilla 1.7... - -1. See 'End Of script Output' below: a double diff --git a/main/metadata/md_document.php b/main/metadata/md_document.php deleted file mode 100755 index 8769748a13..0000000000 --- a/main/metadata/md_document.php +++ /dev/null @@ -1,189 +0,0 @@ - - * @package chamilo.metadata - */ -/** - * Chamilo Metadata: class mdobject for Document-type items - * @package chamilo.metadata - */ -class mdobject { - -var $mdo_course; -var $mdo_type; -var $mdo_id; -var $mdo_eid; - -var $mdo_dcmap_e; -var $mdo_dcmap_v; - -var $mdo_path; -var $mdo_title; -var $mdo_comment; -var $mdo_filetype; -var $mdo_group; -var $mdo_url; - - -function mdo_define_htt() { return new xhtdoc(<< - - {-V metadata/lom/general/title/string-} txt-sep - {-R metadata/lom/general/keyword C KWTEXT-} txt-sep - {-V metadata/lom/general/description[1]/string-} txt-end - document-type - {-V metadata/lom/lifeCycle/contribute[1]/entity-} - {-V metadata/lom/lifeCycle/contribute[1]/date/dateTime-} - {-V metadata/lom/technical/format-} - - - - - {-V string-}-kw - - - -EOD -); -} - -function mdo_generate_default_xml_metadata() -{ - global $iso639_2_code, $ieee_xml; - - $xhtDoc = new xhtdoc($ieee_xml); $_user = api_get_user_info(); - - if ($xhtDoc->htt_error) - give_up('IEEE XML (metadata/md_funcs): ' . $xhtDoc->htt_error); - - $xhtDoc->xht_get_lang = 'get_lang'; $xhtDoc->xht_xmldoc = new xmddoc(''); - if ($xhtDoc->xht_xmldoc->error) give_up($xhtDoc->xht_xmldoc->error); - - $xhtDoc->xht_param['siteUri'] = make_uri(); - - $xhtDoc->xht_param['entry'] = $this->mdo_course['sysCode'] . - '.Document.' . $this->mdo_id; // 2005-05-30: path->sysCode - - $xhtDoc->xht_param['location'] = api_get_path(WEB_PATH) . - 'main/metadata/openobject.php?cidReq=' . - urlencode($this->mdo_course['sysCode']) . '&eid=' . - urlencode($this->mdo_eid); - - $xhtDoc->xht_param['mdlang'] = strtolower($iso639_2_code); - $xhtDoc->xht_param['lang'] = strtolower($iso639_2_code); - - $xhtDoc->xht_param['title'] = - $this->mdo_title ? $this->mdo_title : - ($this->mdo_path ? $this->mdo_path : get_lang('MdTitle', '')); - $xhtDoc->xht_param['description'] = - $this->mdo_comment ? $this->mdo_comment : get_lang('MdDescription', ''); - $xhtDoc->xht_param['coverage'] = get_lang('MdCoverage', ''); - - if (isset($_user)) - { - $xhtDoc->xht_param['author'] = "BEGIN:VCARD\\nFN:" . - api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS) . - "\\nEMAIL:".$_user['mail'] . "\\nEND:VCARD\\n"; - } - - $xhtDoc->xht_param['dateTime'] = date('Y-m-d'); - - if ($this->mdo_filetype == 'folder') $format = "inode/directory"; - else - { - require_once(api_get_path(LIBRARY_PATH) . 'document.lib.php'); - $format = DocumentManager::file_get_mime_type($this->mdo_path); - } - - $xhtDoc->xht_param['format'] = $format; - - $xhtDoc->xht_param['size'] = (($s = filesize(get_course_path() . - $this->mdo_course['path'] . '/document' . $this->mdo_path))) ? $s : '0'; - - return $xhtDoc->xht_fill_template('XML'); -} - - -function mdo_add_breadcrump_nav() -{ - global $interbreadcrumb, $langFormats; - $regs = array(); // for use with ereg() - - $docurl = api_get_self(); // should be .../main/xxx/yyy.php - if (ereg('^(.+[^/\.]+)/[^/\.]+/[^/\.]+.[^/\.]+$', $docurl, $regs)) - $docurl = $regs[1] . '/document/document.php'; - - $interbreadcrumb[]= array ('url' => $docurl, - "name"=> get_lang('MdCallingTool')); - - if (($docpath = $this->mdo_path)) - { - $docpath = substr($docpath, 0, strrpos($docpath, '/')); - - if (strlen($docpath) > 1) $interbreadcrumb[]= array ('url' => - $docurl . '?curdirpath=' . urlencode($docpath) . - ($this->mdo_group ? '&gidReq=' . $this->mdo_group : ''), "name" => - htmlspecialchars(substr($docpath, strrpos($docpath, '/') + 1))); - } - - // Complete assoclist $langFormats from mime types - - require_once(api_get_path(LIBRARY_PATH) . 'xht.lib.php'); - require_once(api_get_path(LIBRARY_PATH) . 'document.lib.php'); - - $sep = $langFormats{0} ? $langFormats{0} : ":"; - $arrFormats = xht_explode_assoclist($langFormats); - - foreach (DocumentManager::file_get_mime_type(TRUE) as $format) - if (!isset($arrFormats[$format])) - $langFormats .= ",, " . $format . $sep . $format; - - if (!isset($arrFormats["inode/directory"])) - $langFormats .= ",, inode/directory" . $sep . "inode/directory"; - - if (substr($langFormats, 0, 3) == ",, ") - $langFormats = $sep . substr($langFormats, 3); -} - - -function mdobject($_course, $id) { - global $ieee_dcmap_e, $ieee_dcmap_v; // md_funcs - $course_id = api_get_course_int_id(); - - $this->mdo_course = $_course; $this->mdo_type = 'Document'; - $this->mdo_id = $id; $this->mdo_eid = $this->mdo_type . '.' . $id; - - $this->mdo_dcmap_e = $ieee_dcmap_e; $this->mdo_dcmap_v = $ieee_dcmap_v; - - $document_table = Database::get_course_table(TABLE_DOCUMENT); - $sql = "SELECT path,title,comment,filetype FROM $document_table WHERE c_id = $course_id AND id='" .intval($id) . "'"; - - if (($docinfo = Database::fetch_array(Database::query($sql)))) { - $this->mdo_path = $docinfo['path']; - $this->mdo_title = $docinfo['title']; - $this->mdo_comment = $docinfo['comment']; - $this->mdo_filetype = $docinfo['filetype']; - $this->mdo_group = ''; // 2005-05-30: find group_id, if any - - $group_info = Database::get_course_table(TABLE_GROUP); - $sql = "SELECT id,secret_directory FROM $group_info WHERE c_id = $course_id"; - if (($result = Database::query($sql))) - while (($row = Database::fetch_array($result))) - if (($secdir = $row['secret_directory'] . '/') == - substr($this->mdo_path, 0, strlen($secdir))) - { - $this->mdo_group = $row['id']; break; - } - - // 2005-05-30: use direct URL - $this->mdo_url = api_get_path(WEB_COURSE_PATH) . $_course['path'] . - '/document' . str_replace('%2F', '/', urlencode($this->mdo_path)) . - ($this->mdo_group ? '?gidReq=' . $this->mdo_group : ''); - } -} - -} -?> diff --git a/main/metadata/md_editxml.htt b/main/metadata/md_editxml.htt deleted file mode 100755 index a45e42adc1..0000000000 --- a/main/metadata/md_editxml.htt +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - -{-P traceinfo-} -
    -
    - - -
    - - - -Expires: Mon, 26 Jul 1997 05:00:00 GMT - - - \ No newline at end of file diff --git a/main/metadata/md_funcs.php b/main/metadata/md_funcs.php deleted file mode 100755 index 4a9f9e20e7..0000000000 --- a/main/metadata/md_funcs.php +++ /dev/null @@ -1,406 +0,0 @@ - - * 2006/12/15 - * Copyright (C) 2006 rene.haentjens@UGent.be - see note at end of text --> - * @package chamilo.metadata -*/ - -/** -* Chamilo Metadata: common functions and mdstore class -* -* This script requires xmd.lib.php and xht.lib.php (Chamilo inc/lib). -* -* Note on the funny characters used in mds_update_xml_and_mdt: -* -* ! and ~ and , are handled by xmd_update, see xmd.lib.php -* ~~ !! ; and = are handled here; note that = excludes newlines in value -* -* path!elem create new element (not for attributes!) -* path=value assign new value to existing element or value to attribute -* path~ delete element (you cannot delete an attribute) -* ~~ delete the whole xmldoc and the DB entry -* !! this (xml) document contains the course keywords -* -* path1,path2,...;subpath=value for all elements in path1, path2, ... -* assign value to subpath (see also xmd_update_many) -* -*/ - -// FETCH GET/POST-DATA; GENERAL FUNCTIONS - -define('MDS_TABLE', Database::get_course_table(TABLE_METADATA)); - - -if (isset($getpostvars) && is_array($getpostvars)) - foreach ($getpostvars as $gpvar) - if (is_string($gpvar) && (isset($_POST[$gpvar]) || isset($_GET[$gpvar]))) { - $val = isset($_POST[$gpvar]) ? $_POST[$gpvar] : $_GET[$gpvar]; - $GLOBALS[$gpvar] = get_magic_quotes_gpc() ? stripslashes($val) : $val; - } - -function fgc($filename) { - $fp = fopen($filename, 'rb'); $buffer = fread($fp, filesize($filename)); - fclose($fp); return $buffer; // file_get_contents: PHP >= 4.3.0 -} - - -function give_up($msg) { - global $charset; - echo '

    MetaData:
    ? ', - htmlspecialchars($msg, ENT_QUOTES, $charset), '

    '; exit; -} - - -function getpar($name, $description, $default = '') -{ - $value = isset($_GET[$value = api_strtolower($name)]) ? $_GET[$value] : ''; - $value = get_magic_quotes_gpc() ? stripslashes($value) : $value; - if (!$value) $value = $default; - if ($value == '') give_up('URL parameter ' . api_strtoupper($name) . ' - ' . - $description . ' - is required'); - - define(api_strtoupper($name), $value); -} - - -function get_course_path() { - return api_get_path(SYS_COURSE_PATH); -} - -function get_course_web() { - return api_get_path(WEB_COURSE_PATH); -} - - -function define_htt($htt_file, $urlp, $course_path) { - global $charset; - - ($htt_file_contents = @fgc($htt_file)) - or give_up('Templates file "' . $htt_file . '" is missing...'); - - $xhtDoc = new xhtdoc($htt_file_contents); - if ($xhtDoc->htt_error) - give_up('Templates file "' . $htt_file . '": ' . $xhtDoc->htt_error); - - $xhtDoc->xht_param['self'] = api_get_self() . $urlp; - - $xhtDoc->xht_param['dateTime'] = date('Y-m-d'); - - $ckw = $course_path . '/CourseKwds.js'; - define('KEYWORDS_CACHE', get_course_path() . $ckw); - - if (file_exists(KEYWORDS_CACHE)) $kcdt = - htmlspecialchars(date('Y/m/d H:i:s', filemtime(KEYWORDS_CACHE)), ENT_QUOTES, $charset); - - $xhtDoc->xht_param['keywordscache'] = $kcdt ? - '' . - '
    (CourseKwds cache: ' . $kcdt . ')' : ''; - - return $xhtDoc; -} - - -function make_uri() { - $regs = array(); // for use with ereg() - - $uri = strtr(ereg_replace( - "[^0-9A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\xFF\*\(\('!_.-]", "_", - api_get_setting('siteName')), "\\", "_"); // allow letdigs, and _-.()'!* - - if (($p = strpos($uri, '.')) !== FALSE) - $uri = substr($uri, 0, $p); - if (ereg('^([^/]+//)?([^/\?]+)[/\?]',api_get_path(WEB_PATH).'/',$regs)) - if (ereg('([^\.]+)(\.ca)?(\.[^\.]+)?', strrev($regs[2]), $regs)) - $uri = str_replace('.', '-', - strrev($regs[1].$regs[2].$regs[3])) . ':' . $uri; - $uri = 'urn:' . strtolower($uri); - while (substr($uri, -1)=='.') $uri = substr($uri,0,-1); - - return $uri; -} - - -// IEEE LOM: DEFAULT XML AND DUBLIN CORE MAPPING ------------------------------> - -$ieee_xml = << - - - - - - {-H {-P siteUri-}-}.{-H {-P entry-}-} - <string language="{-H {-P mdlang-}-}">{-H {-P title-}-}</string> - {-H {-P lang-}-} - {-H {-P description-}-} - {-H {-P coverage-}-} - - - 0.5 - LOMv1.0draft - - LOMv1.0author - {-H {-P author-}-} - {-H {-P dateTime-}-} - - - - ADLv1.3 - - - {-H {-P format-}-} - {-H {-P size-}-} - {-H {-P location-}-} - - - LOMv1.0narrative text - - - LOMv1.0yes - LOMv1.0yes - {-L MdCopyright-} - - - LOMv1.0educational objective - - - - - -EOD; - -$ieee_dcmap_e = array( -'Identifier'=> 'metadata/lom/general/identifier[1]', -'Title'=> 'metadata/lom/general/title[1]', -'Language'=> 'metadata/lom/general/language[1]', -'Description'=> 'metadata/lom/general/description[1]', -'Coverage'=> 'metadata/lom/general/coverage[1]', -'Type'=> 'metadata/lom/educational/learningResourceType[1]', -'Date'=> 'metadata/lom/lifeCycle/contribute[1]/date', -'Creator'=> 'metadata/lom/lifeCycle/contribute[1]/entity', -'Format'=> 'metadata/lom/technical/format[1]', -'Rights'=> 'metadata/lom/rights/description[1]'); -// maps Dublin Core elements to xmd paths for elements (not yet complete) - -$ieee_dcmap_v = array( -'Identifier'=> 'metadata/lom/general/identifier[1]/entry', -'Title'=> 'metadata/lom/general/title[1]/string', -'Language'=> 'metadata/lom/general/language[1]', -'Description'=> 'metadata/lom/general/description[1]/string', -'Coverage'=> 'metadata/lom/general/coverage[1]/string', -'Type'=> 'metadata/lom/educational/learningResourceType[1]/value', -'Date'=> 'metadata/lom/lifeCycle/contribute[1]/date/dateTime', -'Creator'=> 'metadata/lom/lifeCycle/contribute[1]/entity', -'Format'=> 'metadata/lom/technical/format[1]', -'Rights'=> 'metadata/lom/rights/description[1]/string'); -// maps Dublin Core elements to xmd paths for values (not yet complete) - - -// KEYWORD TREE -function define_kwds($mdo) { - if (!($newtext = trim(@fgc(get_course_path() . $mdo->mdo_course['path'] . - '/document' . $mdo->mdo_path )))) - { - unlink(KEYWORDS_CACHE); return; - } - // templates to define the tree as JScript object - $xhtDocKw = new xhtdoc(<< - -KWTREE_OBJECT = {n:"", ti:"{-X @title-}" -, c:[{-R * C DOWN_THE_KWTREE-}]}; - -document.write(traverseKwObj(KWTREE_OBJECT, '', 0)); KWDS_ARRAY.sort(); - - -{-T number > 1 , -}{n:"{-V @.-}"{-D cm {-X @comment-}-}{-T cm != empty , cm:"{-P cm-}"-}{-D pt {-X @postit-}-}{-T pt != empty , pt:"{-P pt-}"-}{-R * P empty-}{-T number >= 1 -, c:[-}{-T number >= 1 R * C DOWN_THE_KWTREE-}{-R * P empty-}{-T number >= 1 ]-}} - - -EOD - ); // traverseKwObj (md_script) generates clickable tree and populates KWDS_ARRAY - - - if ($xhtDocKw->htt_error) - give_up('KwdTree template (metadata/md_funcs): ' . $xhtDocKw->htt_error); - - $xhtDocKw->xht_xmldoc = new xmddoc(explode("\n", $newtext)); - if ($xhtDocKw->xht_xmldoc->error) - give_up('CourseKwds (metadata/md_funcs): XML error: ' . - $xhtDocKw->xht_xmldoc->error); - - if (count($xhtDocKw->xht_xmldoc->children[0]) < 2) - { - unlink(KEYWORDS_CACHE); return; - } - - $fileHandler = @fopen(KEYWORDS_CACHE, 'w'); - @fwrite($fileHandler, $xhtDocKw->xht_fill_template('KWTREE_OBJECT')); - @fclose($fileHandler); -} - - -// METADATA STORE -/** - * mdstore class - * @package chamilo.metadata - */ -class mdstore { - - var $mds_something; - - function __construct($allow_create) { - global $_course; - $this->course_id = api_get_course_int_id(); - if (!isset($_course)) return; - } - - function mds_get($eid, $column = 'mdxmltext', $must_exist = '') { - // none: FALSE - if (($mdt = Database::fetch_array(Database::query("SELECT " . $column ." FROM ".MDS_TABLE." WHERE eid = '$eid' AND c_id = {$this->course_id} ")))) - return $mdt[$column]; - if ($must_exist) give_up($must_exist . $this->_coldat('eid', $eid)); - - return FALSE; - } - - function mds_get_dc_elements($mdo) // no record: FALSE - { - if (!($mdt = $this->mds_get($mdo->mdo_eid))) return FALSE; - $xmlDoc = new xmddoc(explode("\n", $mdt)); if ($xmlDoc->error) return FALSE; - $result = array(); - foreach ($mdo->mdo_dcmap_v as $dce => $xp) { - $result[$dce] = $xmlDoc->xmd_value($xp); - } - return $result; - } - - function mds_get_many($columns, $where_clause) { - $cols = ''; - foreach (explode(',', $columns) as $col) $cols .= "," . trim($col); - if (!$cols) return; - return $this->_query("SELECT " . api_substr($cols, 1) ." FROM " . MDS_TABLE . " WHERE c_id = {$this->course_id} AND ". $where_clause); - } - - function mds_put($eid, $data, $column = 'mdxmltext', $exists = TRUE) { - if ($exists === TRUE) - return $this->_query("UPDATE " . MDS_TABLE . " SET " .$this->_coldat($column, $data) . " WHERE c_id = {$this->course_id} AND ", $eid); - elseif ($exists === FALSE) - return $this->_query("INSERT INTO " . MDS_TABLE . " SET c_id = {$this->course_id} , ".$this->_coldat($column, $data).", ", $eid); - else // user doesn't know, check first whether the record exists - return $this->mds_put($eid, $data, $column, !($this->mds_get($eid) === FALSE)); - } - - function mds_put_dc_elements($mdo, $dcelem) { - if (($mdt = $this->mds_get($mdo->mdo_eid)) === FALSE) { - $mdt = $mdo->mdo_generate_default_xml_metadata(); $exists = FALSE; - } else - $exists = TRUE; - - $xmlDoc = new xmddoc(explode("\n", $mdt)); if ($xmlDoc->error) return FALSE; - foreach ($dcelem as $dce => $value) { - $xmlDoc->xmd_update($mdo->mdo_dcmap_v[$dce], (string) $value); - } - $this->mds_put($mdo->mdo_eid, '', 'md5', $exists); - return $this->mds_put($mdo->mdo_eid, $xmlDoc->xmd_xml()); - } - - function mds_append($eid, $moredata, $column = 'indexabletext') { - if (($olddata = $this->mds_get($eid, $column)) === FALSE) return FALSE; - $this->mds_put($eid, $olddata . $moredata, $column); return $olddata; - } - - function mds_delete($eid) { - return $this->_query("DELETE FROM " . MDS_TABLE . " WHERE c_id = {$this->course_id} AND ", $eid); - } - - function mds_delete_offspring($eid, $sep = '.') { - return $this->_query("DELETE FROM " . MDS_TABLE . " WHERE c_id = {$this->course_id} AND ", $eid, $sep); - } - - function mds_delete_many($idarray) { - if (!is_array($idarray) || count($idarray) == 0) return FALSE; - - return $this->_query("DELETE FROM " . MDS_TABLE . " WHERE c_id = {$this->course_id} AND eid IN ('" . - implode("','", array_map('addslashes', $idarray)) . "')"); - } - - function mds_update_xml_and_mdt($mdo, &$xmlDoc, $mda, $eid, &$traceinfo, - $exists = TRUE) // note: $xmlDoc and $traceinfo passed by reference - { - foreach (explode("\n", - str_replace("\r", "\n", str_replace("\r\n", "\n", $mda))) as $update) - { - if (!$update) continue; - - if (($nameLth = strpos($update, '='))) // e.g. 'gen/tit/str=new' - { - if (($text = api_substr($update, $nameLth + 1)) === FALSE) $text = ''; - - if (!($path = trim(api_substr($update, 0, $nameLth)))) continue; - - if (($sc = api_strpos($path, ';'))) // e.g. 'gen/tit,gen/des;str@lang' - $xmlDoc->xmd_update_many(api_substr($path, 0, $sc), - api_substr($path, $sc + 1), $text); - else - $xmlDoc->xmd_update($path, $text); - } - elseif ($nameLth === FALSE) // e.g. 'gen/tit/str[-1]~' - { - if ($update == '~~') - { - $update = 'DELETE ' . $eid; - if ($exists === FALSE) $update = ''; - else $this->mds_delete($eid); - $mda = ''; $exists = TRUE; - foreach ($xmlDoc->children[0] as $key => $child) - unset($xmlDoc->children[0][$key]); - } - elseif ($update == '!!') - { - define_kwds($mdo); - $update = ''; $mda = ''; $exists = TRUE; - } - else - { - $x = $xmlDoc->xmd_update(trim($update), ''); - } - } - if ($update) $traceinfo .= $update . '- '; - } - - $mdt = $xmlDoc->xmd_xml(); - - if ($exists === FALSE) - { - $this->mds_put($eid, $mdt, 'mdxmltext', FALSE); - $traceinfo .= 'INSERT ' . $eid . '- '; - } - elseif($mda) - { - $this->mds_put($eid, $mdt, 'mdxmltext'); - $traceinfo .= 'UPDATE ' . $eid . '- '; - } - - return $mdt; - } - - - function _coldatstart($column, $data) { - return $column . " LIKE '" . Database::escape_string($data) . "%'"; - } - - function _coldat($column, $data) { - return $column . "='" . Database::escape_string($data) . "'"; - } - - function _query($sql, $eid = '', $sep = '') { - if ($eid) $sql .= $sep ? $this->_coldatstart('eid', $eid . $sep) : - $this->_coldat('eid', $eid); - return Database::query($sql); - } - -} \ No newline at end of file diff --git a/main/metadata/md_link.htt b/main/metadata/md_link.htt deleted file mode 100755 index 293107b9a2..0000000000 --- a/main/metadata/md_link.htt +++ /dev/null @@ -1,202 +0,0 @@ - - - - - - - - -{-D TRUE TRUE-} - -
    -{-H {-E md_indexabletext C METADATA_INDEXABLETEXT-}-} -
    - - - -
    -{-T dbrecord == empty
    -} -{-E md_part1 C METADATA_PART1-} -{-T dbrecord == empty
    -} - -{-T isallowedtoedit == TRUE - -
    {-P traceinfo-}
    - -
    - - - - -
    - - - - -} - -{-T keywordscache != empty - -
    - - - -  {-L ClickKw-} - {-P keywordscache-} -
    - -
    - {-L KwHelp-} -
    - - -} - -{-T keywordscache == empty - -
    -{-L KwNote-} -
    - - -} - - -
    - - - - - - -

    {-L Tool-}: {-X metadata/lom/general/identifier/entry-}

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
         
    {-D label Language-}{-C LABEL-}{-D xpath metadata/lom/general/language-}{-C LANGSELECT-}{-D xpath metadata/lom/general/identifier/catalog-}{-D iclass disabled class="wd2" -}{-C INPUT-}{-D label Identifier-}{-C LABEL-}{-D xpath metadata/lom/general/identifier/entry-}{-D iclass class="wd2" onKeyPress="return isValidChar(event, '[a-z0-9\x08\x25\x27\*\.\'\(\)_!-]', 'i');" -}{-C INPUT-}
    {-D label Title-}{-C LABEL-}{-D xpath metadata/lom/general/title/string/@language-}{-C LANGSELECT-}{-D xpath metadata/lom/general/title/string-}{-C INPUTW-}
    {-D label Description-}{-C LABEL-}{-C MDLANGSELECT-}{-D xpath metadata/lom/general/description/string-}{-C INPUTW-}
    {-D label Coverage-}{-C LABEL-}{-D xpath metadata/lom/general/coverage/string-}{-C INPUTW-}
    {-D label Keyword-}{-C LABEL-}{-C INPUT_ALLKWDS-}
    {-D label Location-}{-C LABEL-}{-D xpath metadata/lom/technical/location-}{-C INPUTW-}
         
    - - - - -Title: {-V metadata/lom/general/title/string-} txt-sep -Keyword(s): {-R metadata/lom/general/keyword C KWTEXT-} txt-sep -Category: {-V metadata/lom/general/coverage/string-} - {-V metadata/lom/general/description[1]/string-} txt-end - link-type - {-V metadata/lom/lifeCycle/contribute[1]/entity-} - {-V metadata/lom/lifeCycle/contribute[1]/date/dateTime-} - - - - {-V metadata/lom/general/identifier/entry-} - {-V metadata/lom/general/title/string-} - {-V metadata/lom/general/description/string-} - {-V metadata/lom/general/coverage/string-} - {-R metadata/lom/general/keyword C KWTEXT-} - - - - - {-V string-}-kw - - - - -{-L {-P label-}-} : - - - - - - - - - -{-D optionarray Langs-}{-C SELECT-} - - - - - - - - - - - - - - -{-D iclass class="wide" -}{-C INPUT-} - - - - - - - - - - - - - - - - - - - - - - -Expires: Mon, 26 Jul 1997 05:00:00 GMT - - - \ No newline at end of file diff --git a/main/metadata/md_link.php b/main/metadata/md_link.php deleted file mode 100755 index b84b22773e..0000000000 --- a/main/metadata/md_link.php +++ /dev/null @@ -1,256 +0,0 @@ - - -Title: {-V metadata/lom/general/title/string-} txt-sep -Keyword(s): {-R metadata/lom/general/keyword C KWTEXT-} txt-sep -Category: {-V metadata/lom/general/coverage/string-} txt-sep - {-V metadata/lom/general/description[1]/string-} txt-end - link-type - - - - - {-V string-}-kw - - - -EOD -); -} - -function mdo_generate_default_xml_metadata() -{ - global $iso639_2_code, $ieee_xml; - - $xhtDoc = new xhtdoc($ieee_xml); $_user = api_get_user_info(); - - if ($xhtDoc->htt_error) - give_up('IEEE XML (metadata/md_funcs): ' . $xhtDoc->htt_error); - - $xhtDoc->xht_get_lang = 'get_lang'; $xhtDoc->xht_xmldoc = new xmddoc(''); - if ($xhtDoc->xht_xmldoc->error) give_up($xhtDoc->xht_xmldoc->error); - - $xhtDoc->xht_param['siteUri'] = make_uri(); - - $xhtDoc->xht_param['entry'] = $this->mdo_course['sysCode'] . - '.Link.' . $this->mdo_id; // 2005-05-30: path->sysCode - - $xhtDoc->xht_param['location'] = $this->mdo_url . ''; - - $xhtDoc->xht_param['mdlang'] = strtolower($iso639_2_code); - $xhtDoc->xht_param['lang'] = strtolower($iso639_2_code); - - $xhtDoc->xht_param['title'] = - $this->mdo_title ? $this->mdo_title : get_lang('MdTitle'); - - if (($d = $this->mdo_description)) - { - if ($keywords = $this->_find_keywords($d)) $d = array_pop($keywords); - $xhtDoc->xht_param['description'] = $d; - } - else - $xhtDoc->xht_param['description'] = get_lang('MdDescription'); - - $xhtDoc->xht_param['coverage'] = $this->mdo_category_title ? - $this->mdo_category_title : get_lang('MdCoverage'); - - if (isset($_user)) - { - $xhtDoc->xht_param['author'] = "BEGIN:VCARD\\nFN:" . - api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS) . - "\\nEMAIL:".$_user['mail'] . "\\nEND:VCARD\\n"; - } - - $xhtDoc->xht_param['dateTime'] = date('Y-m-d'); - - $xhtDoc->xht_param['format'] = ''; $xhtDoc->xht_param['size'] = '0'; - - if (count($keywords)) - { - $xd = new xmddoc(explode("\n", - $mdt = $xhtDoc->xht_fill_template('XML'))); - if ($xd->error) return $mdt; // and worry later - - $this->_add_keywords($xd, $keywords); - - return $xd->xmd_xml(); - } - - return $xhtDoc->xht_fill_template('XML'); -} - - -function mdo_override(&$xmlDoc) // by ref! -{ - if ($this->mdo_url) - { - $xmlDoc->xmd_update('metadata/lom/technical/location', $this->mdo_url); - - $ge = $xmlDoc->xmd_select_single_element("metadata/lom/general"); - - $xmlDoc->xmd_update('title[1]/string', $this->mdo_title, $ge); - $xmlDoc->xmd_update('coverage[1]/string', $this->mdo_category_title, $ge); - - if (($d = $this->mdo_description)) - if ($keywords = $this->_find_keywords($d)) $d = array_pop($keywords); - - $xmlDoc->xmd_update('description[1]/string', $d, $ge); - - $xmlDoc->xmd_remove_nodes($xmlDoc->xmd_select_elements('keyword', $ge), $ge); - - if (count($keywords)) $this->_add_keywords($xmlDoc, $keywords); - } - - return $xmlDoc->xmd_xml(); -} - - -function mdo_storeback(&$xmlDoc) // by ref! -{ - $course_id = api_get_course_int_id(); - - if (!$this->mdo_url) return; // no record in link table, most probably - - if (!($v = $xmlDoc->xmd_value('metadata/lom/technical/location'))) return; - - if ($v != $this->mdo_url) - { $this->mdo_url = $v; $u .= ", url = '" . addslashes($v) . "'"; } - - $ge = $xmlDoc->xmd_select_single_element("metadata/lom/general"); - - $v = $xmlDoc->xmd_value('title[1]/string', $ge); - if ($v != $this->mdo_title) - { $this->mdo_title = $v; $u .= ", title = '" . addslashes($v) . "'"; } - - $vd = $xmlDoc->xmd_value('description[1]/string', $ge); - $vk = $xmlDoc->xmd_value('keyword/string', $ge, array('in' => ', ')); - $v = $vk ? '' . - ereg_replace('\[((/?(b|big|i|small|sub|sup|u))|br/)\]', '<\\1>', - htmlspecialchars($vd)) . '' : $vd; - - if ($v != $this->mdo_description) - { - $this->mdo_description = $v; - $u .= ", description = '" . addslashes($v) . "'"; - } - - // do not store back a modified coverage as category... - - $link_table = Database::get_course_table(TABLE_LINK); - if ($u) Database::query("UPDATE $link_table SET " . substr($u, 2) . - " WHERE c_id = $course_id AND id='" . addslashes($this->mdo_id) . "'"); -} - - -function mdo_add_breadcrump_nav() -{ - global $interbreadcrumb; - - $regs = array(); // for use with ereg() - - $docurl = api_get_self(); // should be .../main/xxx/yyy.php - if (ereg('^(.+[^/\.]+)/[^/\.]+/[^/\.]+.[^/\.]+$', $docurl, $regs)) - $docurl = $regs[1] . '/link/link.php'; - - $interbreadcrumb[]= array ('url' => $docurl, - "name"=> get_lang('MdCallingTool')); -} - - -function mdobject($_course, $id) -{ - global $ieee_dcmap_e, $ieee_dcmap_v; // md_funcs - $course_id = api_get_course_int_id(); - - $this->mdo_course = $_course; $this->mdo_type = 'Link'; - $this->mdo_id = $id; $this->mdo_eid = $this->mdo_type . '.' . $id; - - $this->mdo_dcmap_e = $ieee_dcmap_e; $this->mdo_dcmap_v = $ieee_dcmap_v; - - $link_table = Database::get_course_table(TABLE_LINK); - if (($linkinfo = @Database::fetch_array(Database::query( - "SELECT url,title,description,category_id FROM $link_table WHERE c_id = $course_id AND id='" .intval($id) . "'")))) - { - $this->mdo_url = $linkinfo['url']; - $this->mdo_title = $linkinfo['title']; - $this->mdo_description = $linkinfo['description']; - $this->mdo_category = ($lci = $linkinfo['category_id']); - - $linkcat_table = Database::get_course_table(TABLE_LINK_CATEGORY); - if (($catinfo = @Database::fetch_array(Database::query( - "SELECT category_title FROM $linkcat_table WHERE c_id = $course_id AND id='" . - addslashes($lci) . "'")))) - $this->mdo_category_title = $catinfo['category_title']; - } -} - - -function _find_keywords($d) -{ - $dd = new xmddoc($d); if ($dd->error) return NULL; - - $regs = array(); // for use with ereg() - - foreach ($dd->attributes[0] as $name => $value) - if ($name == 'kw' && ereg('^]+)>?$', $value, $regs)) - { - $kwa = array_map('trim', explode(',', $regs[1])); - - if (ereg('^<' . ($tag = $dd->name[0]) . '[^>]*>(.*)$', - $d, $regs)) // e.g. A & B! - { - $htdc = array_flip(get_html_translation_table(HTML_ENTITIES)); - $d = strtr(ereg_replace( // first -> [b] etc. - '<((/?(b|big|i|small|sub|sup|u))|br/)>', '[\\1]', - ($regs[1])), $htdc); // then & -> & etc. - $d = strtr(str_replace("\r\n", " ", $d), "\r\n", " "); - } - else $d = $dd->xmd_text(); - - array_push($kwa, $d); return $kwa; - } - - return NULL; -} - -function _add_keywords(&$xmlDoc, $keywords) // by ref! -{ - $ge = $xmlDoc->xmd_select_single_element("metadata/lom/general"); - $dl = array("language" => - $xmlDoc->xmd_value("description/string/@language", $ge)); - - foreach ($keywords as $kw) - $xmlDoc->xmd_add_text_element("string", $kw, - $xmlDoc->xmd_add_element("keyword", $ge), $dl); -} - -} -?> diff --git a/main/metadata/md_mix.php b/main/metadata/md_mix.php deleted file mode 100755 index ebb7e665a3..0000000000 --- a/main/metadata/md_mix.php +++ /dev/null @@ -1,85 +0,0 @@ -mdo_course = $_course; $this->mdo_eid = $eid; - $this->mdo_type = ($type = substr($eid, 0, $dotpos)); - $this->mdo_id = ($id = substr($eid, $dotpos + 1)); - - if ($type == 'Document' || $type == 'Scorm') - { - $table = $type == 'Scorm' ? - Database::get_course_table(TABLE_SCORMDOC) : - Database::get_course_table(TABLE_DOCUMENT); - - if (($dotpos = strpos($id, '.'))) - { - $urlp = '?sid=' . urlencode(substr($id, $dotpos+1)); - $id = substr($id, 0, $dotpos); - } - - if (($docinfo = @mysql_fetch_array(Database::query( - "SELECT path,comment,filetype FROM - $table WHERE id='" . - addslashes($id) . "'")))) - { - $this->mdo_path = $docinfo['path']; - $this->mdo_comment = $docinfo['comment']; - $this->mdo_filetype = $docinfo['filetype']; - - if ($type == 'Scorm') - { - $this->mdo_base_url = get_course_web() . - $this->mdo_course['path'] . '/scorm' . $this->mdo_path; - $this->mdo_url = $this->mdo_base_url . '/index.php' . $urlp; - } - else - { - $this->mdo_url = api_get_path(WEB_PATH) . 'main/document/' . - (($this->mdo_filetype == 'file') ? 'download' : 'document').'.php?'. - (($this->mdo_filetype == 'file') ? 'doc_url=' : 'curdirpath=') . - urlencode($this->mdo_path); - } - } - } - elseif ($type == 'Link') - { - $link_table = Database::get_course_table(TABLE_LINK); - if (($linkinfo = @mysql_fetch_array(Database::query( - "SELECT url,title,description,category_id FROM - $link_table WHERE id='" . addslashes($id) . - "'")))) - { - $this->mdo_url = $linkinfo['url']; - } - } -} - -} -?> diff --git a/main/metadata/md_phpdig.php b/main/metadata/md_phpdig.php deleted file mode 100755 index fd12e42b33..0000000000 --- a/main/metadata/md_phpdig.php +++ /dev/null @@ -1,215 +0,0 @@ - - -$phpDigInc = get_course_path() . $_course['path'] . '/phpdig-1.8.6/includes/'; -$phpDigIncCn = $phpDigInc. 'connect.php'; // to connect to PhpDig's database -$phpDigIncCw = $phpDigInc. 'common_words.txt'; // stopwords - -// if (!file_exists($phpDigIncCn)) return(); doesn't seem to work properly... - - -if (file_exists($phpDigIncCw)) - if (is_array($lines = @file($phpDigIncCw))) - while (list($id,$word) = each($lines)) - $common_words[trim($word)] = 1; - -define('SUMMARY_DISPLAY_LENGTH', 700); -//define('PHPDIG_ENCODING', 'iso-8859-1'); -define('PHPDIG_ENCODING', strtolower($charset)); -define('SMALL_WORDS_SIZE', 2); -define('MAX_WORDS_SIZE',50); -define('WORDS_CHARS_LATIN1', '[:alnum:]��ߵ'); - -foreach (array( 'A'=>'������', 'a'=>'������', 'O'=>'������', 'o'=>'������', - 'E'=>'����', 'e'=>'����', 'C'=>'�', 'c'=>'�', 'I'=>'����', - 'i'=>'����', 'U'=>'����', 'u'=>'����', 'Y'=>'�', 'y'=>'��', - 'N'=>'�', 'n'=>'�') as $without => $allwith) - foreach (explode('!', chunk_split($allwith, 1, '!')) as $with) - if ($with) // because last one will be empty! - { - $letterswithout .= $without; $letterswith .= $with; - } -define('LETTERS_WITH_ACCENTS', $letterswith); -define('SAME_WITHOUT_ACCENTS', $letterswithout); - -(strlen(LETTERS_WITH_ACCENTS) == strlen(SAME_WITHOUT_ACCENTS)) - or give_up('LETTERS_WITH_ACCENTS problem in md_phpdig.php'); - - -function find_site($url) -{ - $site_url = "site_url = '" . addslashes($url) . "'"; - - $result = Database::query("SELECT site_id FROM " . PHPDIG_DB_PREFIX . - "sites WHERE " . $site_url); // find site - - if (Database::num_rows($result) == 1) - { - $row = Database::fetch_array($result); return (int) $row['site_id']; - } - else - { - $result = Database::query("INSERT INTO " . PHPDIG_DB_PREFIX . - "sites SET " . $site_url); // new site - $site_id = Database::insert_id(); - - $result = Database::query("INSERT INTO " . PHPDIG_DB_PREFIX . - "site_page (site_id,num_page) VALUES ('$site_id', '0')"); - - return $site_id; - } -} - -function remove_engine_entries($url, $path, $file = '') -{ - global $charset; - - $and_path = " AND path = '" . addslashes($path) . "'"; - if ($file) $and_path .= " AND file LIKE '" . addslashes( - str_replace(array('_', '%'), array('\_', '\%'), $file)) . "%'"; - - $result = Database::query("SELECT spider_id FROM " . PHPDIG_DB_PREFIX . - "spider WHERE site_id=" . ($site_id = find_site($url)) . $and_path); // find page(s) - - while ($row = Database::fetch_array($result)) - { - Database::query("DELETE FROM " . PHPDIG_DB_PREFIX . - "engine WHERE spider_id=" . (int)$row['spider_id']); // delete all references to keywords - $aff .= ' +' . Database::affected_rows(); - } - - Database::query("DELETE FROM " . PHPDIG_DB_PREFIX . - "spider WHERE site_id=" . $site_id . $and_path); // delete page - - echo htmlspecialchars($url . $path . $file, ENT_QUOTES, $charset), ' (site_id ', - $site_id, '): ', Database::affected_rows(), $aff, - ' pages + word references removed from index.
    '; - - return $site_id; -} - -function index_words($site_id, $path, $file, $first_words, $keywords) -{ - global $common_words; - - $spider_set_path_etc = "spider SET path='" . addslashes($path) . - "',file='" . addslashes($file) . "',first_words='" . - addslashes($first_words) . "',site_id='$site_id'"; - // do not set upddate,md5,num_words,last_modified,filesize - - Database::query("INSERT INTO " . PHPDIG_DB_PREFIX . $spider_set_path_etc); - - $spider_id = Database::insert_id(); $new = 0; - - foreach ($keywords as $key => $w) - if (strlen($key) > SMALL_WORDS_SIZE and strlen($key) <= MAX_WORDS_SIZE and - !isset($common_words[$key]) and - ereg('^['.WORDS_CHARS_LATIN1.'#$]', $key)) - { - $result = Database::query("SELECT key_id FROM " . PHPDIG_DB_PREFIX . - "keywords WHERE keyword = '" . addslashes($key) . "'"); - - if (Database::num_rows($result) == 0) - { - Database::query("INSERT INTO " . PHPDIG_DB_PREFIX . - "keywords (keyword,twoletters) VALUES ('" . addslashes($key) . - "','" .addslashes(substr(str_replace('\\','',$key),0,2)) ."')"); - $key_id = Database::insert_id(); $new++; - } - else - { - $keyid = Database::fetch_row($result); $key_id = $keyid[0]; - } - - Database::query("INSERT INTO " . PHPDIG_DB_PREFIX . - "engine (spider_id,key_id,weight) VALUES ($spider_id,$key_id,$w)"); - } - global $charset; - echo '', htmlspecialchars($file, ENT_QUOTES, $charset), '(spider_id ', - $spider_id, '):', count($keywords), ' kwds, ', - $new , ' new', "\n"; -} - -function get_first_words($text, $path, $file) -{ - $db_some_text = preg_replace("/([ ]{2}|\n|\r|\r\n)/" ," ", $text); - if (strlen($db_some_text) > SUMMARY_DISPLAY_LENGTH) { - $db_some_text = substr($db_some_text, 0, SUMMARY_DISPLAY_LENGTH) . "..."; - } - - $titre_resume = $path . $file; - if (($psc = strpos($titre_resume, 'scorm/')) !== FALSE) - $titre_resume = substr($titre_resume, $psc + 6); - if (($pth = strpos($titre_resume, '&thumb')) !== FALSE) - $titre_resume = substr($titre_resume, 0, $pth); - - return $titre_resume."\n".$db_some_text; -} - -function get_keywords($text) -{ - if (($token = strtok(phpdigEpureText($text), ' '))) $nbre_mots[$token] = 1; - - while (($token = strtok(' '))) - $nbre_mots[$token] = ($nm = $nbre_mots[$token]) ? $nm + 1 : 1; - - return $nbre_mots; -} - -function phpdigEpureText($text) -{ - $text = strtr(phpdigStripAccents(strtolower($text)), '��', '��'); - - $text = ereg_replace('[^'.WORDS_CHARS_LATIN1.' \'._~@#$&%/=-]+',' ',$text); // RH: was ' \'._~@#$:&%/;,=-]+', also below - - $text = ereg_replace('(['.WORDS_CHARS_LATIN1.'])[\'._~@#$&%/=-]+($|[[:space:]]$|[[:space:]]['.WORDS_CHARS_LATIN1.'])','\1\2',$text); - - // the next two repeated lines needed - if (SMALL_WORDS_SIZE >= 1) { - $text = ereg_replace('[[:space:]][^ ]{1,'.SMALL_WORDS_SIZE.'}[[:space:]]',' ',' '.$text.' '); - $text = ereg_replace('[[:space:]][^ ]{1,'.SMALL_WORDS_SIZE.'}[[:space:]]',' ',' '.$text.' '); - } - //$text = ereg_replace('\.+[[:space:]]|\.+$|\.{2,}',' ',$text); - $text = ereg_replace('\.{2,}',' ',$text); - $text = ereg_replace('^[[:space:]]*\.+',' ',$text); - - return trim(ereg_replace("[[:space:]]+"," ",$text)); -} - -function phpdigStripAccents($chaine) -{ - $chaine = str_replace('�','ae',str_replace('�','ae',$chaine)); - return strtr($chaine, LETTERS_WITH_ACCENTS, SAME_WITHOUT_ACCENTS); -} -?> diff --git a/main/metadata/md_scorm.htt b/main/metadata/md_scorm.htt deleted file mode 100755 index 1cfeb60caa..0000000000 --- a/main/metadata/md_scorm.htt +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - -Expires: Mon, 26 Jul 1997 05:00:00 GMT - - - \ No newline at end of file diff --git a/main/metadata/md_scorm.php b/main/metadata/md_scorm.php deleted file mode 100755 index 2f7c7b22eb..0000000000 --- a/main/metadata/md_scorm.php +++ /dev/null @@ -1,106 +0,0 @@ - - -{-D scormlevel {-V @level-}-}{-D two 2-} -Title: {-V metadata/lom/general/title/string-} txt-sep -{-T scormlevel == two Author(s): {-V metadata/lom/lifeCycle/contribute[1]/entity-} txt-sep-} -Keyword(s): {-R metadata/lom/general/keyword C KWTEXT-} txt-sep - {-V metadata/lom/general/description[1]/string-} - {-V metadata/lom/technical/location-} txt-end - {-V metadata/lom/general/description[2]/string-} scorm-level-{-P scormlevel-} - {-V metadata/lom/lifeCycle/contribute[1]/entity-} - {-V metadata/lom/lifeCycle/contribute[1]/date/dateTime-} - - - - - {-V string-}-kw - - - -EOD -); -} - - -function mdo_generate_default_xml_metadata() -{ - return ''; -} - - -function mdo_add_breadcrump_nav() -{ - global $interbreadcrumb; - $regs = array(); // for use with ereg() - - $docurl = api_get_self(); // should be .../main/xxx/yyy.php - if (ereg('^(.+[^/\.]+)/[^/\.]+/[^/\.]+.[^/\.]+$', $docurl, $regs)) - $docurl = $regs[1] . '/newscorm/index.php'; - - $interbreadcrumb[] = array ('url' => $docurl, - 'name' => get_lang('MdCallingTool')); -} - - -function mdobject($_course, $id) -{ - global $ieee_dcmap_e, $ieee_dcmap_v; // md_funcs - - $scormdocument = Database::get_course_table(TABLE_LP_MAIN); - - $this->mdo_course = $_course; $this->mdo_type = 'Scorm'; - $this->mdo_id = $id; $this->mdo_eid = $this->mdo_type . '.' . $id; - - $this->mdo_dcmap_e = $ieee_dcmap_e; $this->mdo_dcmap_v = $ieee_dcmap_v; - $sql = "SELECT path,description,lp_type FROM $scormdocument WHERE id='" . addslashes($id) . "'"; - if (($docinfo = @Database::fetch_array(Database::query($sql)))) - { - $this->mdo_path = $docinfo['path']; - //Sometimes the new scorm-tool adds '/.' at the end of a directory name, so remove this before continue - //the process -- bmol - if(substr($this->mdo_path,-2) == '/.') - { - $this->mdo_path = substr($this->mdo_path,0, strlen($this->mdo_path)-2); - } - $this->mdo_comment = $docinfo['description']; - //Don't think the next line is correct. There used to be a 'type' field in the scormdocument table. - //This metadata tool only works on folder types -- bmol - $this->mdo_filetype = ($docinfo['lp_type'] == 2 ? 'folder' : 'xxx'); - - $this->mdo_url = get_course_web() . $this->mdo_course['path'] . - '/scorm/' . $this->mdo_path . '/index.php'; - } -} - -} -?> diff --git a/main/metadata/md_script.js b/main/metadata/md_script.js deleted file mode 100755 index 51ccf8fa29..0000000000 --- a/main/metadata/md_script.js +++ /dev/null @@ -1,577 +0,0 @@ -// md_script.js -// - -// Copyright (C) 2006 rene.haentjens@UGent.be - see metadata/md_funcs.php --> - - -// Part 1: General funcs & Keyword Tree: copied (with modifs) from SelKwds.xsl - - String.prototype.trim = function() - { - return this.replace(/^\s*/,"").replace(/\s*$/,""); // \f\n\r\t\v - } // Dave Anderson, dbforums.com/arch/195/2003/3/724117 - - String.prototype.removeExtraSpaces = function() - { - return this.replace(/\s+/g, ' ').trim(); - } - - function makeWindow(url, htmlText) - { - var newWindow = window.open(url, '', - 'toolbar=no, location=no, directories=no, status=yes, '+ - 'menubar=yes, scrollbars=yes, resizable=yes, ' + - 'width=800, height=600, left=10, top=10'); - if (url == '') newWindow.document.write('' + - htmlText + ''); - return newWindow; - } - - function isNotW3C() - { - if (!document.getElementById) - alert('Sorry, the buttons only work with W3C browsers. ' + - 'Use FireFox or IE6 or Moz1.7 or type in keywords manually...'); - return !document.getElementById; - } - - - function openOrCloseHelp(btn) - { - if (isNotW3C()) return false; - - document.getElementById('moreHelp').className = - (btn.value == "?") ? "dvo" : "dvc"; - btn.value = (btn.value == "?") ? "¿" : "?"; - } - - function hasTagAndClass(obj, tag, cl) - { - return obj.tagName && (obj.tagName.toUpperCase() == tag) && - (obj.className == cl); - } - - - function openOrClose(btn) // show or hide part of keyword-tree - { - var oldcl = (btn.value == "-") ? "dvo" : "dvc"; - var newcl = (oldcl == "dvo") ? "dvc" : "dvo"; - btn.value = (oldcl == "dvo") ? "+" : "-" ; - - var ch = btn.parentNode.childNodes; // opera crashes on with() - for (var i = 0; i < ch.length; i++) // netscape requires .item - if (hasTagAndClass(ch.item(i), 'DIV', oldcl)) - ch.item(i).className = newcl; - } - - function openOrCloseHere(div, wrong) // show or hide recursively - { - var ch = div.childNodes; - for (var i = 0; i < ch.length; i++) - { - var thisCh = ch.item(i); - if (thisCh.className == 'btn' && thisCh.value == wrong) - openOrClose(thisCh) - else if (thisCh.className == 'dvo' || thisCh.className == 'dvc') - openOrCloseHere(thisCh, wrong); - } - } - - function openOrCloseAll(btn) // show or hide whole keyword-tree - { - if (isNotW3C()) return false; - - var wrong = (btn.value == "--") ? "-" : "+" ; - btn.value = (wrong == "-") ? "++" : "--"; - - openOrCloseHere(btn.parentNode, wrong); - } - - - var selspans = new Array; // selected SPANs with keywords - - function deselect(span) - { - for (var s in selspans) if (selspans[s] == span) delete selspans[s]; - } - - function copyToClipboard(allKwds) // md_script: not used - { - if (window.clipboardData) - { - window.clipboardData.setData("Text", '<' + allKwds + '>\r\n'); - return; - } - - netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); - var gClipboardHelper = Components.classes['@mozilla.org/widget/clipboardhelper;1'] - .getService(Components.interfaces.nsIClipboardHelper); - gClipboardHelper.copyString('<' + allKwds + '>\n'); - } - - function getSelectedKeywords() - { - var sortedKwds = new Array, allKwds = ''; - - for (var s in selspans) - sortedKwds.push(selspans[s].parentNode.getAttribute('level') - + '.' + selspans[s].innerHTML) - - sortedKwds.sort(); // according to level, which follows the tree - - for (var k in sortedKwds) - { - var someWords = sortedKwds[k]; - allKwds += ', ' + someWords.substr(someWords.indexOf('.')+1); - } - - return allKwds.replace(/[,_\s]+/g, ', ').substr(2); // strip ', ' - } - - - var orkwds; // array of ', kw, ' strings - - function selectOriginal(div) - { - var ch = div.childNodes; - for (var i = 0; i < ch.length; i++) - { - var thisCh = ch.item(i); if (!thisCh.tagName) continue; - thisTag = thisCh.tagName.toUpperCase(); - - if (thisTag == 'SPAN') - { - var parkwds = ','+ thisCh.innerHTML.replace(/\s*/g,"") +','; - - for (var k = 0; k < orkwds.length; k++) - if (parkwds.indexOf(orkwds[k]) >=0 ) - { - deselect(thisCh); selspans.push(thisCh); - thisCh.className = "lbs"; - - openToTop(div, div.className); break; - } - } - else if (thisTag == 'DIV') - { - selectOriginal(thisCh); - } - } - } - - function openToTop(div, divclass) - { - if (!div.parentNode) return; var pdiv = div.parentNode; - - if (!pdiv.className) return; var pclass = pdiv.className; - if (pclass != 'dvo' && pclass != 'dvc') return; - - if (divclass == 'dvc') - { - var ch = pdiv.childNodes; - for (var i = 0; i < ch.length; i++) - { - var btn = ch.item(i); - if (hasTagAndClass(btn, 'INPUT', 'btn')) - if (btn.value == '+') openOrClose(btn); - } - } - - openToTop(pdiv, pclass); - } - - function deselectAll(ev, btn) - { - if (isNotW3C()) return false; - - if (!ev) var ev = window.event; - - var kws = document.getElementById('kwds_string'); - - for (var s in selspans) selspans[s].className = "lbl"; - selspans = new Array; - - document.getElementById('btnOpenOrCloseAll').value = "--"; - - if (!ev.altKey) { kws.value = ''; return; } - - // md_script: the calling HTML should define var kwdswere! - // in SelKwds.xsl, they are typed in by user or fetched from PPT - - var kwdsarray = kwdswere.split(','), allKwds = ''; - - for (var k = 0; k < kwdsarray.length; k++) - { - var kwd = kwdsarray[k].trim(); - if (kwd.substr(0,1) == '-') kwd = kwd.substr(1); - if (kwd != '') allKwds += '§,' + kwd + ','; - } - - if (allKwds == '') return; - - orkwds = allKwds.substr(1).split('§'); - - selectOriginal(btn.parentNode); - - allKwds = getSelectedKeywords(); kws.value = allKwds; - // no copyToClipboard(allKwds); - - allKwds = ','+ allKwds.replace(/\s*/g,"") +','; var missing = ''; - for (k = 0; k < orkwds.length; k++) - if (allKwds.indexOf(orkwds[k]) < 0 ) missing += orkwds[k]; - - if (missing != '') alert('!= ' + missing.replace(/,+/g," ")); - } - - function selectOrDeselect(span, newcl) - { - span.className = newcl; deselect(span); - if (newcl == "lbs") selspans.push(span); - } - - function alsoParents(div, oldcl, newcl) - { - while (div.parentNode) - { - div = div.parentNode; var ch = div.childNodes; - for (var i = 0; i < ch.length; i++) - if (hasTagAndClass(ch.item(i), 'SPAN', oldcl)) - selectOrDeselect(ch.item(i), newcl); - } - } - - function spanClick(span, ev) // md_script: no parents in search - { - var mda = getObj("mda"); if (!ev) ev = window.event; - - if (ev.shiftKey && ev.altKey) - { - makeWindow('', '
    ' + span.parentNode.innerHTML
    -                    .replace(/&/g, "&").replace(/"/g, """)
    -                    .replace(//g, ">") + '
    '); - return; // debugging... - } - - if (ev.ctrlKey || span.className == "lbs") - { - selectOrDeselect(span, "lbl"); // deselect - if (document.selection) document.selection.empty(); - if (ev.altKey) alsoParents(span.parentNode, "lbs", "lbl"); - } - else - { - selectOrDeselect(span, "lbs"); // select (search: no parents) - if (mda && !ev.altKey) alsoParents(span.parentNode, "lbl", "lbs"); - if (!mda && ev.altKey) // mda does not exist in search form - if (span.innerHTML.substr(0, 1) == '-') - span.innerHTML = (', ' + span.innerHTML).replace(/, -/g, ", ").substr(2); - else span.innerHTML = (', ' + span.innerHTML).replace(/, /g, ", -").substr(2); - } - - var allKwds = getSelectedKeywords(); // no copyToClipboard(allKwds); - document.getElementById('kwds_string').value = allKwds; - } - - - var KWDS_ARRAY = new Array, nkw = 0, pU; // alphabetic list popup - - function makeAlphaList(div) // md_script: not used (hopefully) - { - var ch = div.childNodes; - for (var i = 0; i < ch.length; i++) - { - var thisCh = ch.item(i); if (!thisCh.tagName) continue; - thisTag = thisCh.tagName.toUpperCase(); - - if (thisTag == 'SPAN') - { - var parkwds= thisCh.innerHTML.replace(/\s*/g,"").split(','); - for (k in parkwds) KWDS_ARRAY[nkw++] = parkwds[k]; - } - else if (thisTag == 'DIV') makeAlphaList(thisCh); - } - } - - function pU_show(anchor, offsetX, offsetY, defH) // XY: rel. to anchor - { - if (!anchor) return; - - thisx = anchor.offsetLeft; thisy = anchor.offsetTop; - - while ((anchor = anchor.offsetParent)) - { - thisx += anchor.offsetLeft; thisy += anchor.offsetTop; - } - - thisx += offsetX; thisy += offsetY; - - pU.style.left = thisx + "px"; - pU.style.top = thisy + "px"; - pU.style.height = defH; var maxH = pU.offsetHeight; - for (var curH = 20; curH <= maxH; curH += 20) - { - pU.style.height = curH + 'px'; - if (curH >= pU.scrollHeight) break; - } - // scrollHeight can be smaller than current in IE, not in Moz - pU.style.visibility = "visible"; - } - - function pU_hide() - { - if (pU) pU.style.visibility = "hidden"; - } - - function takeTypeIn(kws, oX, oY, defH) - { - if (isNotW3C()) return; - - if (!pU) - { - pU = document.getElementById('popup'); - - if (!KWDS_ARRAY.length) - { - makeAlphaList(document.getElementById('maindiv')); - KWDS_ARRAY.sort(); - } - } - - if (!(curValue = kws.value.toLowerCase())) return; - - var kwLines = ''; - - for (pos = 0; pos < KWDS_ARRAY.length; pos++) - if (KWDS_ARRAY[pos].toLowerCase().indexOf(curValue) == 0) - kwLines += '
    ' + KWDS_ARRAY[pos] + '
    '; - - if (kwLines == '') {pU_hide(); return; } - - pU.innerHTML = kwLines; pU_show(kws, oX, oY, defH); - } - - function pU_clicked(ev) - { - if (!pU) return false; if (!ev) var ev = window.event; - - var t = (ev.srcElement) ? ev.srcElement : ev.originalTarget; - try {var kw = t.innerHTML;} catch(exc) {return false;} // Moz - - while (true) try - { - if (t.id == pU.id) return kw ? kw : true; t = t.parentNode; - } - catch(exc) {return false;} // Moz: t.parentNode uncatched exc. - } - - function pU_select(kw) - { - if (kw === true) return; - - var kws = document.getElementById('kwds_string'); - var maindiv = document.getElementById('maindiv'); - - var ch = maindiv.childNodes; - for (var i = 0; i < ch.length; i++) - { - var btn = ch.item(i); - if (hasTagAndClass(btn, 'INPUT', 'btn')) - if (btn.value == '+') openOrClose(btn); - } - orkwds = new Array(',' + kw + ','); selectOriginal(maindiv); - - kws.value = getSelectedKeywords(); // no copyToClipboard(kws.value); - - pU_hide(); - } - - -// Part 2: Metadata Updates: W3C, IE4 and NS4 browsers - - function isValidChar(ev, pattern, flags) - { - // e.g. onKeyPress="return isValidChar(event, '[a-z]', 'i');" - - if (!ev) var ev = window.event; // PPK, see below - var kc = (ev.keyCode) ? ev.keyCode : ev.which; // PPK - return (new RegExp(pattern, flags)).test(String.fromCharCode(kc)); - - // PPK= Peter-Paul Koch, www.quirksmode.org - } - - function checkValid(inputField, pattern, flags) - { - // e.g. onKeyUp="checkValid(this, '^[a-z]{2,8}$', 'i');" - - var fieldColor = (new RegExp(pattern, flags)).test(inputField.value) ? '#000000' : '#D8366C'; - var fieldStyle = (document.getElementById || document.all) ? - inputField.style : inputField; - if (fieldStyle) fieldStyle.color = fieldColor; - - // OK for all browsers (see devedge.netscape.com - // /library/xref/2003/css-support/css1/mastergrid.html): - // color, background-color (not on NN4), display block/none (NN4?), - // overflow hidden/scroll/auto (not on NN4), - // position relative/static, - // text-align left/right/center, text-indent, - // font-style normal/italic, font-weight normal/bold, - // font-family serif/sans-serif/monospace, - // border-style none/solid/double/groove/ridge/inset/outset. - } - - function getObj(name) // PPK - { - return (document.getElementById) ? document.getElementById(name) - : (document.all) ? document.all[name] // IE4 - : (document.layers) ? document.layers[name] // NS4 - : null; // With NS4, nested layers are not supported! - } - - function spc(path, value) // set pending change in form field mda - { - var mda = getObj("mda"); - if (mda) mda.value += "\n" + path + '=' + value; - } - - function spcSel(path, selbox) // set pending change, language selection - { - var mda = getObj("mda"); - if (mda) mda.value += "\n" + path + '=' + - selbox.options[selbox.selectedIndex].value; - } - - function checkBeforeSubmit(ev) - { - if (!ev) var ev = window.event; - - if (ev.ctrlKey && ev.altKey) - { - var mdt = getObj("mdt"); if (!mdt) return false; - - makeWindow('', '
    ' +
    -                    ('' +
    -                     '  \n\n' +
    -                     mdt.value)
    -                        .replace(/&/g, '&').replace(/"/g, '"')
    -                        .replace(//g, '>') +
    -                    '
    '); - return false; - } - - var kwdsnow = getObj("kwds_string"); if (!kwdsnow) return true; - if (kwdsnow.value == kwdswere) return true; // unchanged - // note: calling HTML should define var kwdswere! - - var language = kwdsnow.title; - - var mda = getObj("mda"); - if (!mda) { alert('? Form does not contain mda'); return false; } - - var kwdsarray = kwdswere.split(','); - - for (var k = 0; k < kwdsarray.length; k++) // delete old - if (kwdsarray[k].trim() != '') - mda.value += "\nmetadata/lom/general/keyword[-1]~"; - - kwdsarray = kwdsnow.value - .replace(/[!-,:-@\[-\^{-~\s]+/g, ',').split(','); - - for (k = 0; k < kwdsarray.length; k++) - { - var newkw = kwdsarray[k].trim(); - if (newkw != '') mda.value += - "\nmetadata/lom/general!keyword" + - "\nmetadata/lom/general/keyword[-1]!string=" + newkw + - "\nmetadata/lom/general/keyword[-1]/string/@language=" + language; - } - - return true; - - } - - function setPendingOperation(op, ev) - { - if (!ev) var ev = window.event; - - var mda = getObj("mda"); - if (!mda) { alert('? Form does not contain mda'); return false; } - - if (op == '!!' || (op == '~~' && confirm(mda.title))) - { - mda.value = op; return true; - } - - return false; - } - - function prepSearch(ev) - { - if (!ev) var ev = window.event; - - var mdsc = getObj("mdsc"); - if (!mdsc) { alert('? Form does not contain mdsc'); return false; } - - var kwdsnow = getObj("kwds_string"); if (!kwdsnow) return true; - if (kwdsnow.value == '') return true; - - if (!KWDS_ARRAY.length) - { - makeAlphaList(getObj('maindiv')); - KWDS_ARRAY.sort(); - } - - var restricttokwds = false, checkbox = getObj("restricttokwds"); - if (checkbox) restricttokwds = checkbox.checked; - - var kwdsarray = kwdsnow.value - .replace(/[!-,:-@\[-\^{-~\s]+/g, ',').split(','); - - for (var k = 0; k < kwdsarray.length; k++) - { - var newkw = kwdsarray[k].trim().toLowerCase(); - - if (newkw != '') - { - var realkw = false; - - if (restricttokwds) - for (pos = 0; pos < KWDS_ARRAY.length; pos++) - if (KWDS_ARRAY[pos].toLowerCase() == newkw) - { realkw = true; break; } - mdsc.value += "\n" + newkw + (realkw ? '-kw' : ''); - - } - } - - return true; - } - - var CRLF = "\n"; // generates clickable tree and populates KWDS_ARRAY - - function traverseKwObj(node, parlev, num) // see KWTREE_OBJECT in md_funcs - { - var curlev = '00' + (num+1), kwn = '', html = ''; - curlev = parlev + curlev.substr(curlev.length-3); - - for (i in (names = node.n.split("_"))) - if (nn = names[i]) { KWDS_ARRAY.push(nn); kwn += ', ' + nn; } - - for (j in node.c) html += traverseKwObj(node.c[j], curlev, Math.abs(j)); - - return (parlev == '') ? html : - '
    ' + CRLF + - '' : - 'lfn" value=" "/>') + ' ' + CRLF + - '' : '>') + - kwn.substr(2) + '' + CRLF + - (node.cm ? '' + node.cm + '' : '') + - html + - '
    ' + CRLF; - } - - -// The End \ No newline at end of file diff --git a/main/metadata/md_styles.css b/main/metadata/md_styles.css deleted file mode 100755 index 84fada5e2e..0000000000 --- a/main/metadata/md_styles.css +++ /dev/null @@ -1,25 +0,0 @@ -/* 2005/01/04 - - Copyright (C) 2005 rene.haentjens@UGent.be - see metadata/md_funcs.php */ - -.bg1 {background-color: #4171B5; font-size: 2pt} -.bg2 {background-color: #666666; font-size: 2pt} -.bg3 {background-color: #E6E6E6; width: 100%} - -.kwl {width: 92%} -.w23 {width: 66%} -.wd1 {width: 15ex} -.wd2 {width: 32ex} -.mda {width: 100%; display: none} -.lgr {background-color: #F0F0F0} - -.dvc {display: none; margin-left: 3ex} -.dvo {display: block; margin-left: 3ex} -.btm {height: 3.5ex; width: 5ex; font-family: monospace; font-size: xx-small} -.btn {height: 3.5ex; width: 3ex; font-family: monospace; font-size: xx-small} -.lfn {height: 3.5ex; width: 3ex; font-family: monospace; font-size: xx-small; visibility: hidden} -.lbl {background-color: #C0C0C0; cursor: pointer} -.lbs {background-color: #B0C4DE; cursor: pointer; border-style: solid; border-width: 1px} -.pup {position:absolute; visibility:hidden; width: 50%; border: 1px solid black; overflow:auto; background-color: #C0C0C0} -.pul {background-color: #FFFFFF} -.wide {width: 99%} \ No newline at end of file diff --git a/main/metadata/mds_mix.htt b/main/metadata/mds_mix.htt deleted file mode 100755 index e734183510..0000000000 --- a/main/metadata/mds_mix.htt +++ /dev/null @@ -1,115 +0,0 @@ - - - - - - - -

    Metadata {-L Search-}

    - -{-P traceinfo-} - -
    - - - - -{-R item C RESULTROW-} - - - - -
         
         
    - -
    -{-R item C RESULTTHUMB-} -
    - -
    - -
    - -
    - - - {-L SearchCrit-}
    - - - - - - - - - - -
    - -{-T keywordscache != empty - -
    - - - -  {-L ClickKw-} - {-P keywordscache-} -
    - -
    - {-L KwHelp-} -
    - -} - -{-T keywordscache == empty -
     
    - -} - -
    - - - - - - -{-D info {-X metadata/lom/lifeCycle/contribute[1]/entity-}-} -{-T info != empty D info {-P info-}, {-X parent/@identifier-}-} -{-T info == empty D info X parent/@identifier-} - - {-P info-}: {-X metadata/lom/general/title-} - Open - MD - {-X @eid-} - - - - - -{-D thumb {-X resource/file[1]/@href-}-}{-E check_is_thumb xxx-} -{-T thumb != empty -{-D info {-X metadata/lom/lifeCycle/contribute[1]/entity-}-} -{-T info != empty D info {-P info-}, {-X parent/@identifier-}-} -{-T info == empty D info X parent/@identifier-} - - -} - - - - - - - - - - - -Expires: Mon, 26 Jul 1997 05:00:00 GMT - - - - - - - - \ No newline at end of file diff --git a/main/metadata/openobject.php b/main/metadata/openobject.php deleted file mode 100755 index 0cf8b0c71e..0000000000 --- a/main/metadata/openobject.php +++ /dev/null @@ -1,32 +0,0 @@ -mdo_url); - -exit; -?> diff --git a/main/metadata/phpdig/CourseKwds_example.js b/main/metadata/phpdig/CourseKwds_example.js deleted file mode 100755 index 051d9cfc4a..0000000000 --- a/main/metadata/phpdig/CourseKwds_example.js +++ /dev/null @@ -1,79 +0,0 @@ -KWTREE_OBJECT = {n:"", ti:"Aquaculture Keywords" -, c:[{n:"organisms", cm:"(more or less in systematical order)" -, c:[{n:"bacteria"}, {n:"yeast", cm:"he<la", pt:"HoHo"}, {n:"alga" -, c:[{n:"seaweed_macroalga" -, c:[{n:"gracilaria"}, {n:"hijikia"}, {n:"laminaria"}, {n:"porphyra_nori"}, {n:"undaria_wakame"}, {n:"macroalgae-nei"}]}, {n:"microalga" -, c:[{n:"chlorella"}, {n:"dunaliella"}, {n:"isochrysis"}, {n:"nannochloropsis"}, {n:"tetraselmis"}, {n:"diatom-nei"}, {n:"microalga-nei"}]}]}, {n:"rotifer" -, c:[{n:"brachionus-plicatilis"}, {n:"rotifer-nei"}]}, {n:"mollusc" -, c:[{n:"abalone_winkle_conch" -, c:[{n:"abalone_haliotis"}, {n:"other-gastropod"}]}, {n:"clam_cockle" -, c:[{n:"hard-clam_mercenaria-mercenaria"}]}, {n:"mussel" -, c:[{n:"mussel_mytilus-edulis"}]}, {n:"oyster" -, c:[{n:"oyster_ostrea-edulis"}, {n:"oyster_crassostrea-gigas"}]}, {n:"scallop_pecten" -, c:[{n:"scallop_argopecten-irradians"}, {n:"scallop_pecten-maximus"}]}, {n:"squid_cuttlefish_octopus" -, c:[{n:"octopus"}, {n:"sepia"}]}, {n:"mollusc-nei" -, c:[{n:"tapes-philippinarum"}]}]}, {n:"crustacean" -, c:[{n:"brine-shrimp_artemia"}, {n:"freshwater-crustacean" -, c:[{n:"crayfish_astacus_cherax"}, {n:"freshwater-prawn_macrobrachium-rosenbergii"}, {n:"freshwater-crustacean-nei"}]}, {n:"crab" -, c:[{n:"mudcrab_scylla"}, {n:"mitten-crab_eriocheir"}, {n:"crab-nei"}]}, {n:"lobster" -, c:[{n:"lobster_homarus"}, {n:"spiny-lobster_panilurus"}, {n:"lobster-nei"}]}, {n:"penaeid-shrimp_scampi" -, c:[{n:"fenneropenaeus-sinensis"}, {n:"penaeus-indicus"}, {n:"kuruma-shrimp_penaeus-japonicus"}, {n:"tiger-prawn_penaeus-monodon"}, {n:"penaeus-semisulcatus"}, {n:"penaeus-stylirostris"}, {n:"litopenaeus-vannamei"}, {n:"penaeid-nei"}]}, {n:"krill_planktonic-crustacean" -, c:[{n:"moina"}, {n:"copepod-nei"}, {n:"daphnia"}]}, {n:"crustacean-nei" -, c:[{n:"mysidopsis-bahia"}]}]}, {n:"fish" -, c:[{n:"carp_cyprinid" -, c:[{n:"common-carp_cyprinus-carpio"}, {n:"grass-carp_ctenopharyngodon-idella"}, {n:"koi-carp"}]}, {n:"eel" -, c:[{n:"european-eel_anguilla-anguilla"}, {n:"japanese-eel_anguilla-japonica"}]}, {n:"flatfish" -, c:[{n:"flounder_paralichthys-olivaceus"}, {n:"halibut_hippoglossus-hippoglossus"}, {n:"sole_pleuronectes"}, {n:"plaice_pleuronectes-platessa"}, {n:"turbot_scophthalmus-maximus"}, {n:"flatfish-nei"}]}, {n:"herring_sardine_anchovy" -, c:[{n:"herring_clupea-harengus"}]}, {n:"salmon_trout_smelt" -, c:[{n:"atlantic-salmon_salmo-salar"}, {n:"pacific-salmon_oncorhynchus-mykiss"}, {n:"rainbow-trout_salmo-gairdneri"}]}, {n:"shark_ray"}, {n:"tuna_bonito_billfish"}, {n:"tilapia_cichlid" -, c:[{n:"nile-tilapia_oreochromis-niloticus"}]}, {n:"freshwater-fish-nei" -, c:[{n:"african-catfish_clarias-gariepinus"}, {n:"catfish-nei"}, {n:"guppy_poecilia-reticulata"}, {n:"heterobranchus-longifilis"}, {n:"pike_esox-lucius"}, {n:"pike-perch_stizostedion-lucioperca"}, {n:"sturgeon_acipenser"}]}, {n:"marine-fish-nei" -, c:[{n:"arctic-charr_salvelinus-alpinus"}, {n:"asian-seabass_lates-calcarifer"}, {n:"atlantic-cod_gadus-morhua"}, {n:"capelin_mallotus-villosus"}, {n:"dentex_dentex-dentex"}, {n:"dolphin-fish_mahimahi_coryphaena-hippurus"}, {n:"grouper_epinephelus"}, {n:"ictalurus"}, {n:"lumpsucker_cyclopterus-lumpus"}, {n:"milkfish_chanos-chanos"}, {n:"mullet_mugil-cephalus"}, {n:"rabbitfish_siganus"}, {n:"red-drum_sciaenops"}, {n:"red-seabream_pagrus-major"}, {n:"rockfish_sebastes"}, {n:"seabass_dicentrarchus-labrax"}, {n:"seabream_sparus-aurata"}, {n:"snapper_lutjanus"}, {n:"yellowtail_seriola"}]}, {n:"ornamental-fish"}, {n:"fish-nei"}]}, {n:"other-aquatic-organism" -, c:[{n:"sponge"}, {n:"coral"}, {n:"aquatic-plants"}, {n:"aquatic-insects"}, {n:"various-worms"}, {n:"pearl_mother-of-pearl"}, {n:"sea-urchin_echinoderm"}, {n:"zooplankton_phytoplankton"}, {n:"aquatic-invertebrate-nei"}, {n:"frog_amphibian"}, {n:"turtle"}, {n:"crocodile_alligator"}, {n:"aquatic-mammal"}, {n:"aquatic-organism-nei"}]}, {n:"non-aquatic-organism", cm:"(such as birds, cattle, ...)"}]}, {n:"culture-aspects" -, c:[{n:"life-stage" -, c:[{n:"cyst"}, {n:"diapause"}, {n:"seed"}, {n:"egg"}, {n:"larva" -, c:[{n:"spat"}, {n:"umbrella"}, {n:"zoea"}, {n:"nauplius"}, {n:"mysis"}, {n:"megalopa"}, {n:"larval-stage-nei"}]}, {n:"post-larva"}, {n:"juvenile_fingerling"}, {n:"adult"}, {n:"broodstock"}, {n:"biomass"}, {n:"life-cycle"}, {n:"other-life-stage"}]}, {n:"nutrition" -, c:[{n:"diet" -, c:[{n:"dry-diet_formulated-diet"}, {n:"microbound-diet_mbd"}, {n:"wet-diet"}, {n:"live-food"}, {n:"diet-type-nei"}]}, {n:"feed-ingredient" -, c:[{n:"nutrient-requirement"}, {n:"protein"}, {n:"lipids_fat"}, {n:"hufa"}, {n:"carbohydrate"}, {n:"mineral"}, {n:"vitamin"}, {n:"fishmeal"}, {n:"energy"}, {n:"feed-additives_enrichment-product"}, {n:"feed-ingredient-nei"}]}, {n:"feed-production" -, c:[{n:"ingredient"}, {n:"formulation"}, {n:"extrusion"}]}, {n:"feeding-biology" -, c:[{n:"feed-intake"}, {n:"feeding-ratio"}, {n:"feed-conversion"}, {n:"digestion"}, {n:"excretion"}]}, {n:"nutritional-aspect-nei"}]}, {n:"culture-system" -, c:[{n:"pond_pond-culture"}, {n:"tank-culture"}, {n:"experimental-installation"}, {n:"batch-culture"}, {n:"flow-through"}, {n:"raceway-system"}, {n:"recirculation-system"}, {n:"pen-culture"}, {n:"floating-cage"}, {n:"raft_long-line"}, {n:"rack-culture_pole-culture"}, {n:"saltwork_salt-pond"}, {n:"backyard-culture"}, {n:"hydroponic-culture"}, {n:"x-----", cm:"main culture principles:"}, {n:"extensive-culture"}, {n:"semi-intensive-culture"}, {n:"intensive-culture"}, {n:"polyculture_integrated-culture"}, {n:"sea-ranching"}, {n:"culture-system-nei"}]}, {n:"culture-step_culture-activity", cm:"(more or less in chronological order)" -, c:[{n:"x-----", cm:"general culture steps:"}, {n:"reproduction_maturation"}, {n:"spawning"}, {n:"hatchery"}, {n:"larviculture"}, {n:"weaning"}, {n:"nursery"}, {n:"grow-out_farming"}, {n:"x-----", cm:"specific culture steps:"}, {n:"pond-construction"}, {n:"pond-preparation_liming_fertilisation"}, {n:"stocking_inoculation"}, {n:"acclimatisation"}, {n:"hatching"}, {n:"decapsulation"}, {n:"enrichment"}, {n:"cold-storage"}, {n:"feeding"}, {n:"sampling"}, {n:"counting"}, {n:"tagging"}, {n:"grading"}, {n:"cleaning_rinsing"}, {n:"harvesting"}, {n:"processing"}, {n:"quality-control"}, {n:"storage_packing_transport"}, {n:"culture-step-nei"}]}, {n:"equipment_infrastructure" -, c:[{n:"tank"}, {n:"bottle_tube"}, {n:"aquarium"}, {n:"substrate_holder"}, {n:"filter_sieve"}, {n:"incubator"}, {n:"hapa"}, {n:"heater"}, {n:"pump"}, {n:"aerator"}, {n:"air-water-lift"}, {n:"feeder"}, {n:"grader"}, {n:"equipment-nei", cm:"(see also 'water treatment' for more equipment)"}]}, {n:"health_disease" -, c:[{n:"treatment_health-management"}, {n:"disinfection_infection"}, {n:"stress"}, {n:"parasitose"}, {n:"bacteria"}, {n:"virus_phage"}, {n:"fungi"}, {n:"nutritional-disease"}, {n:"water-quality-disease"}, {n:"deformity"}, {n:"pesticide"}, {n:"antibiotics"}, {n:"vaccin"}, {n:"probiont"}, {n:"disease-nei"}]}, {n:"water-quality" -, c:[{n:"water-quality-parameter" -, c:[{n:"temperature"}, {n:"oxygen"}, {n:"ph_acidity"}, {n:"salinity"}, {n:"hardness"}, {n:"organic-matter"}, {n:"nitrogen-compound"}, {n:"harmful-substance"}, {n:"pathogen"}, {n:"heavy-metal"}, {n:"water-quality-parameter-nei"}]}, {n:"water-treatment" -, c:[{n:"water-analysis"}, {n:"water-sampling"}, {n:"aerator_oxygenation"}, {n:"filtering"}, {n:"suspended-solids-removal"}, {n:"protein-skimmer"}, {n:"biofilter"}, {n:"nitrification_denitrification"}, {n:"ozonisation_ozonisator"}, {n:"uv-installation"}, {n:"disinfection"}, {n:"degassing"}, {n:"liming"}, {n:"sedimentation"}, {n:"water-treatment-nei"}]}, {n:"water-usage" -, c:[{n:"water-supply"}, {n:"water-discharge"}, {n:"water-reuse_recirculation"}, {n:"green-water"}, {n:"hydrodynamics_circulation"}]}, {n:"water-quality-aspect-nei"}]}, {n:"culture-aspect-nei"}]}, {n:"life-sciences" -, c:[{n:"morphology"}, {n:"biology" -, c:[{n:"life-cycle"}, {n:"growth"}, {n:"survival"}, {n:"dose-response"}]}, {n:"taxonomy_systematics"}, {n:"ecology" -, c:[{n:"ecosystem_food-chain"}, {n:"predator_prey"}, {n:"biodiversity"}, {n:"zoogeography_natural-distribution"}, {n:"environmental-impact"}, {n:"eutrophication"}, {n:"pollution"}, {n:"toxicant_contaminant"}, {n:"ecological-footprint"}, {n:"biotope"}, {n:"indogeneous-species"}, {n:"exogeneous-species"}]}, {n:"chemistry" -, c:[{n:"analysis_chemical-composition"}, {n:"chemical_molecule"}, {n:"hormone"}, {n:"reaction"}]}, {n:"microbiology" -, c:[{n:"microflora"}, {n:"plating_plate-count_cfu"}, {n:"medium_agar"}, {n:"bacteria"}, {n:"virus"}, {n:"pathogen"}, {n:"probiont"}, {n:"opportunistic-bacteria"}, {n:"microbial-technique-nei"}]}, {n:"genetics" -, c:[{n:"qualitative-genetic-technique"}, {n:"quantative-genetic-technique"}, {n:"gene"}, {n:"dna"}, {n:"chromosome"}, {n:"selection_evolution"}, {n:"heritability"}, {n:"inbreeding"}, {n:"domestication"}, {n:"hybridization"}, {n:"ploidy"}, {n:"gynogenesis"}, {n:"androgenesis"}, {n:"population-genetics"}, {n:"gene-mapping"}, {n:"sex-determination-system"}, {n:"genetics-nei"}]}, {n:"immunology"}, {n:"microscopy" -, c:[{n:"dissection"}, {n:"length-measurement"}, {n:"counting"}, {n:"microscopy-nei"}]}]}, {n:"geography" -, c:[{n:"world" -, c:[{n:"europe" -, c:[{n:"belgium"}, {n:"the-netherlands"}, {n:"france"}, {n:"italy"}, {n:"spain_portugal"}, {n:"greece"}, {n:"uk_ireland"}, {n:"norway_sweden_denmark_iceland"}, {n:"european-country-nei"}]}, {n:"former-USSR"}, {n:"africa" -, c:[{n:"egypt"}, {n:"north-africa-nei"}, {n:"kenia"}, {n:"central-africa-nei"}, {n:"south-africa"}]}, {n:"north-and-central-america" -, c:[{n:"canada"}, {n:"usa"}, {n:"utah"}, {n:"mexico"}, {n:"central-american-state-nei"}, {n:"caribbean"}]}, {n:"south-america" -, c:[{n:"brazil"}, {n:"chile"}, {n:"colombia"}, {n:"ecuador"}, {n:"south-america-nei"}]}, {n:"asia" -, c:[{n:"middle-east"}, {n:"india"}, {n:"china"}, {n:"japan"}, {n:"vietnam"}, {n:"thailand"}, {n:"philippines"}, {n:"asian-country-nei"}]}, {n:"oceania" -, c:[{n:"australia"}, {n:"new-zealand"}]}, {n:"arctic_antarctic"}]}, {n:"biotope" -, c:[{n:"ocean_sea"}, {n:"river"}, {n:"bay_lagoon_fjord"}, {n:"coastline_estuary"}, {n:"mangrove"}, {n:"lake"}, {n:"salt-lake_salina"}, {n:"reef"}, {n:"tundra_prairie_savanna"}, {n:"mountain"}, {n:"forest_jungle"}, {n:"cultured-land"}, {n:"biotope-nei"}]}]}, {n:"other-aspects" -, c:[{n:"sectors" -, c:[{n:"education" -, c:[{n:"university_school"}, {n:"students"}, {n:"lecture_course"}, {n:"practical-exercise"}, {n:"training"}, {n:"study-trip"}, {n:"course-material"}, {n:"examination"}, {n:"scholarship_grant"}, {n:"education-nei"}]}, {n:"research" -, c:[{n:"laboratory"}, {n:"institute_university"}, {n:"scientist_researcher"}, {n:"experiment"}, {n:"project"}, {n:"publication"}, {n:"meeting_conference"}, {n:"research-nei"}]}, {n:"trade_business" -, c:[{n:"company"}, {n:"market_shop"}, {n:"trend_prospect"}, {n:"commercial-product"}, {n:"office"}, {n:"retail_distribution"}, {n:"price_money"}, {n:"marketing_publicity"}, {n:"transport"}, {n:"trade-nei"}]}, {n:"production" -, c:[{n:"farm"}, {n:"factory_industry"}, {n:"building_warehouse"}, {n:"machine"}, {n:"production-nei"}]}, {n:"other-sector" -, c:[{n:"organisation_network"}, {n:"government"}, {n:"ngo"}, {n:"development-aid"}, {n:"cooperation"}, {n:"sponsor_funding-agency"}, {n:"insurance"}, {n:"consultancy"}]}, {n:"aquaculture"}, {n:"agriculture"}, {n:"fishery" -, c:[{n:"harvest_catch"}, {n:"fishing-gear"}, {n:"vessel"}, {n:"restocking"}, {n:"by-catch"}, {n:"overfishing"}, {n:"fishery-aspect-nei"}]}]}, {n:"people" -, c:[{n:"researcher"}, {n:"farmer"}, {n:"fisherman"}, {n:"diver"}, {n:"student_teacher"}, {n:"portrait-of-specific-person_group-picture"}]}, {n:"presentation" -, c:[{n:"title"}, {n:"content_overview"}, {n:"introduction_background"}, {n:"methodology"}, {n:"results"}, {n:"advantages_disadvantages"}, {n:"discussion"}, {n:"conclusion"}, {n:"references"}, {n:"aknowledgement_thanks"}, {n:"the-end"}]}, {n:"apparatus" -, c:[{n:"hufa-analysis"}, {n:"balance"}, {n:"blender"}, {n:"kjeldahl"}, {n:"chromatograph"}, {n:"gel-electrophoresis"}, {n:"centrifuge"}, {n:"lyophilisator"}, {n:"refrigerator"}, {n:"oven"}, {n:"pipette"}, {n:"microscope"}, {n:"apparatus-nei"}]}, {n:"information_media" -, c:[{n:"literature"}, {n:"book"}, {n:"journal"}, {n:"publication"}, {n:"news"}, {n:"internet_www"}, {n:"site_links"}, {n:"discussion-list"}, {n:"computer"}, {n:"software"}, {n:"slide"}, {n:"video_dvd_cd-rom"}, {n:"telephone_fax"}, {n:"e-mail"}]}]}, {n:"slide-content" -, c:[{n:"scheme_drawing"}, {n:"graph_chart"}, {n:"table"}, {n:"map"}, {n:"just-text"}, {n:"combination", cm:"(picture combined with map or table or ...)"}, {n:"skip-this-slide", cm:"(Do not copy to SCORM output)"}]}]}; - -document.write(traverseKwObj(KWTREE_OBJECT, '', 0)); KWDS_ARRAY.sort(); \ No newline at end of file diff --git a/main/metadata/phpdig/CourseKwds_example.jsc b/main/metadata/phpdig/CourseKwds_example.jsc deleted file mode 100755 index f755769fa3..0000000000 --- a/main/metadata/phpdig/CourseKwds_example.jsc +++ /dev/null @@ -1,11 +0,0 @@ -<>Search for anything
    -Slide with scheme -Slide with graph -Slide with table -Slide with map
    -Only complete presentations
    -Only literature references - -exclude literature references -Only useful links - -exclude useful links -Exclude references and links \ No newline at end of file diff --git a/main/metadata/phpdig/config.php b/main/metadata/phpdig/config.php deleted file mode 100755 index 821417490a..0000000000 --- a/main/metadata/phpdig/config.php +++ /dev/null @@ -1,450 +0,0 @@ - 'and operator', 'w_whole' => 'exact phrase', 'w_part' => 'or operator' - -define('SEARCH_DEFAULT_LIMIT',10); //results per page - -define('SPIDER_MAX_LIMIT',20); //max recurse levels in spider -define('RESPIDER_LIMIT',5); //recurse respider limit for update -define('LINKS_MAX_LIMIT',20); //max links per each level -define('RELINKS_LIMIT',5); //recurse links limit for an update - -//for limit to directory, URL format must either have file at end or ending slash at end -//e.g., http://www.domain.com/dirs/ (WITH ending slash) or http://www.domain.com/dirs/dirs/index.php -define('LIMIT_TO_DIRECTORY',true); //limit index to given (sub)directory, no sub dirs of dirs are indexed - -define('LIMIT_DAYS',0); //default days before reindex a page -define('SMALL_WORDS_SIZE',2); //words to not index - must be 2 or more -define('MAX_WORDS_SIZE',50); // RH: was 30 //max word size - -define('PHPDIG_EXCLUDE_COMMENT',''); //comment to exclude a page part -define('PHPDIG_INCLUDE_COMMENT',''); //comment to include a page part - // must be on own lines in HTML source - // text within comments not indexed - // links within comments still indexed - -define('PHPDIG_DEFAULT_INDEX',false); //phpDig considers /index or /default - //html, htm, php, asp, phtml as the - //same as '/' - -define('ALLOW_RSS_FEED',false); // Do RSS and display link - if true, set rss dir to 777 -$theenc = PHPDIG_ENCODING; // needs to be same encoding used in index -$theurl = "http://www.phpdig.net/"; // site offering the RSS feed -$thetitle = "PhpDig.net"; // title for site offering the RSS feed -$thedesc = "PhpDig :: Web Spider and Search Engine"; // description of site offering the RSS feed -$thedir = "./rss"; // the rss directory name, no ending slash -$thefile = "search.rss"; // used in rss filenames - -define('PHPDIG_SESSID_REMOVE',true); // remove SIDS or vars from indexed URLS -define('PHPDIG_SESSID_VAR','PHPSESSID,s'); // name of SID or variable to remove - // can be 's' or comma delimited 's,id,var,foo,etc' - -define('APPEND_TITLE_META',false); //append title and meta information to results -define('TITLE_WEIGHT',3); //relative title weight: APPEND_TITLE_META needs to be true - -define('CHUNK_SIZE',1024); //chunk size for regex processing - -define('SUMMARY_LENGTH',500); //length of results summary - -define('TEXT_CONTENT_PATH','text_content/'); //Text content files path -define('CONTENT_TEXT',0); // RH: was 1 //Activates/deactivates the - //storage of text content. -define('PHPDIG_IN_DOMAIN',false); //allows phpdig jump hosts in the same - //domain. If the host is "www.mydomain.tld", - //domain is "mydomain.tld" - -define('PHPDIG_LOGS',true); //write logs -define('SILENCE_404S',true); //silence 404 output - -define('TEMP_FILENAME_LENGTH',8); //filename length of temp files -// if using external tools with extension, use 4 for filename of length 8 - -define('NUMBER_OF_RESULTS_PER_SITE',-1); //max number of results per site - // use -1 to display all results - -define('USE_RENICE_COMMAND','1'); //use renice for process priority - -//---------EXTERNAL TOOLS SETUP -// if set to true is_executable used - set to '0' if is_executable is undefined -define('USE_IS_EXECUTABLE_COMMAND','0'); // RH: was 1 //use is_executable for external binaries - -// if set to true, full path to external binary required -define('PHPDIG_INDEX_MSWORD',false); -define('PHPDIG_PARSE_MSWORD','/usr/local/bin/catdoc'); -define('PHPDIG_OPTION_MSWORD','-s 8859-1'); - -define('PHPDIG_INDEX_PDF',false); -define('PHPDIG_PARSE_PDF','/usr/local/bin/pstotext'); -define('PHPDIG_OPTION_PDF','-cork'); - -define('PHPDIG_INDEX_MSEXCEL',false); -define('PHPDIG_PARSE_MSEXCEL','/usr/local/bin/xls2csv'); -define('PHPDIG_OPTION_MSEXCEL',''); - -define('PHPDIG_INDEX_MSPOWERPOINT',false); -define('PHPDIG_PARSE_MSPOWERPOINT','/usr/local/bin/ppt2text'); -define('PHPDIG_OPTION_MSPOWERPOINT',''); - -//---------EXTERNAL TOOLS EXTENSIONS -// if external binary is not STDOUT or different extension is needed -// for example, use '.txt' if external binary writes to filename.txt -define('PHPDIG_MSWORD_EXTENSION',''); -define('PHPDIG_PDF_EXTENSION',''); -define('PHPDIG_MSEXCEL_EXTENSION',''); -define('PHPDIG_MSPOWERPOINT_EXTENSION',''); - -//---------FTP SETTINGS -define('FTP_ENABLE',0);//enable ftp content for distant PhpDig -define('FTP_HOST',''); //if distant PhpDig, ftp host; -define('FTP_PORT',21); //ftp port -define('FTP_PASV',1); //passive mode -define('FTP_PATH',''); //distant path from the ftp root -define('FTP_TEXT_PATH','text_content');//ftp path to text-content directory -define('FTP_USER',''); -define('FTP_PASS',''); - -//--------CRON SETTINGS -define('CRON_ENABLE',false); -define('CRON_EXEC_FILE','/usr/bin/crontab'); -define('CRON_CONFIG_FILE',ABSOLUTE_SCRIPT_PATH.'/admin/temp/cronfile.txt'); -define('PHPEXEC','/usr/local/bin/php'); -// NOTE: make sure ABSOLUTE_SCRIPT_PATH is the full path up to but not including the admin dir, no ending slash -// NOTE: CRON_ENABLE set to true writes a file at CRON_CONFIG_FILE containing the cron job information -// The CRON_CONFIG_FILE must be 777 permissions if applicable to your OS/setup -// You still need to call the CRON_CONFIG_FILE to run the cron job!!! -// From shell: crontab CRON_CONFIG_FILE to set the cron job: replace CRON_CONFIG_FILE with actual file -// From shell: crontab -l to list and crontab -d to delete - -// regular expression to ban useless external links in index -define('BANNED','^ad\.|banner|doubleclick'); - -// regexp forbidden extensions - return sometimes text/html mime-type !!! -define('FORBIDDEN_EXTENSIONS','\.(rm|ico|cab|swf|css|gz|z|tar|zip|tgz|msi|arj|zoo|rar|r[0-9]+|exe|bin|pkg|rpm|deb|bz2)$'); - -//----------HTML ENTITIES -$spec = array( "&" => "&", - "à" => "�", - "è" => "�", - "ù" => "�", - "ó" => "�", - "é" => "�", - "î" => "�", - "ô" => "�", - "û" => "�", - "ê" => "�", - "ç" => "�", - "œ" => "oe", - ">" => " ", - "<" => " ", - "°" => " ", - "&apos" => "'", - """ => " ", - "â" => "�", - "ï" => "�", - "ë" => "�", - "ä" => "�", - "Ä" => "�", - "Ë" => "�", - "Ï" => "�", - "Ü" => "�", - "ö" => "�", - "ü" => "�", - " " => " ", - "ß" => "�", - "í" => "�", - "®" => " ", - "©" => " ", - "á" => "�", - "Á" => "�", - "ð" => "�", - "Ð" => "�", - "É" => "�", - "Í" => "�", - "Ó" => "�", - "ú" => "�", - "Ú" => "�", - "Þ" => "�", - "þ" => "�", - "Ö" => "�", - "æ" => "�", - "&AELIG" => "�", - "å" => "�", - "Å" => "�", - "ø" => "�", - "Ø" => "�" - ); - -//month names in iso dates -$month_names = array ('jan'=>1, - 'feb'=>2, - 'mar'=>3, - 'apr'=>4, - 'may'=>5, - 'jun'=>6, - 'jul'=>7, - 'aug'=>8, - 'sep'=>9, - 'oct'=>10, - 'nov'=>11, - 'dec'=>12 - ); - -//apache multi indexes parameters -$apache_indexes = array ( "?N=A" => 1, - "?N=D" => 1, - "?M=A" => 1, - "?M=D" => 1, - "?S=A" => 1, - "?S=D" => 1, - "?D=A" => 1, - "?D=D" => 1, - "?C=N&O=A" => 1, - "?C=M&O=A" => 1, - "?C=S&O=A" => 1, - "?C=D&O=A" => 1, - "?C=N&O=D" => 1, - "?C=M&O=D" => 1, - "?C=S&O=D" => 1, - "?C=D&O=D" => 1); - -//includes language file -define('PHPDIG_LANG_CONSTANT',$phpdig_language); // this line for classic -if (is_file("$relative_script_path/locales/$phpdig_language-language.php")) { - include "$relative_script_path/locales/$phpdig_language-language.php"; -} -elseif (is_file("$relative_script_path/locales/en-language.php")) { - include "$relative_script_path/locales/en-language.php"; -} -else { - die("Unable to select language pack.\n"); -} - -//connection to database -if ((!isset($no_connect)) || ($no_connect != 1)) { - if (is_file("$relative_script_path/includes/connect.php")) { - include "$relative_script_path/includes/connect.php"; - } - else { - die("Unable to find connect.php file.\n"); - } -} - -//includes of libraries -if (is_file("$relative_script_path/libs/phpdig_functions.php")) { - include "$relative_script_path/libs/phpdig_functions.php"; -} -else { - die ("Unable to find phpdig_functions.php file.\n"); -} -if (is_file("$relative_script_path/libs/function_phpdig_form.php")) { - include "$relative_script_path/libs/function_phpdig_form.php"; -} -else { - die ("Unable to find function_phpdig_form.php file.\n"); -} -if (is_file("$relative_script_path/libs/mysql_functions.php")) { - include "$relative_script_path/libs/mysql_functions.php"; -} -else { - die ("Unable to find mysql_functions.php file.\n"); -} -if ((!isset($template)) || ((!is_file($template)) && ($template != "array") && ($template != "classic"))) { - die ("Unable to render template file.\n"); -} - -if (!defined('CONFIG_CHECK')) { - exit(); -} - -// parse encodings (create global $phpdigEncode); -phpdigCreateSubstArrays($phpdig_string_subst); -// send encoding if needed -if (!headers_sent()) { - header('Content-type:text/html; Charset='.PHPDIG_ENCODING); -} -// turn off magic_quotes_runtime for escaping purposes -@ini_set('magic_quotes_runtime',false); -// turn off magic_quotes_sybase for escaping purposes -@ini_set('magic_quotes_sybase',false); -if ((!isset($no_connect)) || ($no_connect != 1)) { - phpdigCheckTables($id_connect,array('engine', - 'excludes', - 'keywords', - 'sites', - 'spider', - 'tempspider', - 'logs', - 'clicks', - 'site_page', - 'includes')); -} -?> diff --git a/main/metadata/phpdig/en-language.php b/main/metadata/phpdig/en-language.php deleted file mode 100755 index 508f1505f0..0000000000 --- a/main/metadata/phpdig/en-language.php +++ /dev/null @@ -1,199 +0,0 @@ - 'translation' -$phpdig_mess = array ( -'one_per_line' =>'Enter one link per line', - -'StopSpider' =>'Stop spider', -'id' =>'ID', -'url' =>'URL', -'days' =>'Days', -'links' =>'Links', -'depth' =>'Depth', -'viewRSS' =>'View RSS for this Page', -'powered_by' =>'Powered by PhpDig', -'searchall' =>'Search All', -'wait' =>'Wait... ', -'done' =>'Done!', -'limit' =>'Limit', -'manage' =>'Here you can manage:', -'dayscron' =>'- the number of days crontab waits to reindex (0 = ignore)', -'links_mean' =>'- the max number of links per depth per site (0 = unlimited)', -'depth_mean' =>'- the max search depth per site (0 = none, depth trumps links)', -'max_found' =>'Maximum links found is ((links * depth) + 1) when links is greater than zero.', -'default_vals' =>'Default values', -'use_vals_from' =>'Use values from', -'table_present' =>'table if present and use
    default values if values absent from table?', -'admin_msg_1' =>'- To empty tempspider table click delete button without selecting a site', -'admin_msg_2' =>'- Search depth of zero tries to crawl just that page regardless of links per', -'admin_msg_3' =>'- Set links per depth to the max number of links to check at each depth', -'admin_msg_4' =>'- Links per depth of zero means to check for all links at each seach depth', -'admin_msg_5' =>'- Clean dashes removes \'-\' index pages from blue arrow listings of pages', -'admin_panel' =>'Admin Panel', - -'choose_temp' =>'Choose a template', -'select_site' =>'Select a site to search', -'restart' =>'Restart', -'narrow_path' =>'Narrow Path to Search', -'upd_sites' =>'Update sites', -'upd2' =>'Update Done', -'links_per' =>'Links per', -'yes' =>'yes', -'no' =>'no', -'delete' =>'delete', -'reindex' =>'Re-index', -'back' =>'Back', -'files' =>'files', -'admin' =>'Administration', -'warning' =>'Warning !', -'index_uri' =>'Which URI would you index?', -'spider_depth' =>'Search depth', -'spider_warn' =>'Please ensure that no one else is updating the same site. -A locking mechanism will be included in a later version.', -'site_update' =>'Update a site or one of its branch', -'clean' =>'Clean', -'t_index' =>'index', -'t_dic' =>'dictionary', -'t_stopw' =>'common words', -'t_dash' =>'dashes', - -'update' =>'Update', -'exclude' =>'Delete and exclude branch', -'excludes' =>'Exclude paths', -'tree_found' =>'Found tree', -'update_mess' =>'Re-index or delete a tree ', -'update_warn' =>'Exclude will delete indexed entries', -'update_help' =>'Click on the cross to delete the branch -Click on the green sign to update it -Click on the noway sign to exclude from future indexings', -'branch_start' =>'Select the folder to display on the left side', -'branch_help1' =>'Select there documents to update individually', -'branch_help2' =>'Click on the cross to delete a document -Click on the green sign to reindex it', -'redepth' =>'levels depth', -'branch_warn' =>'Erase is permanent', -'to_admin' =>'to admin interface', -'to_update' =>'to update interface', - -'search' =>'Search', -'results' =>'results', -'display' =>'display', -'w_begin' =>'and operator', -'w_whole' =>'exact phrase', -'w_part' =>'or operator', -'alt_try' =>'Did you mean', - -'limit_to' =>'limit to', -'this_path' =>'this path', -'total' =>'total', -'seconds' =>'seconds', -'w_common_sing' =>'is a very common word and was ignored.', -'w_short_sing' =>'is too short a word and was ignored.', -'w_common_plur' =>'are very common words and were ignored.', -'w_short_plur' =>'are too short of words and were ignored.', -'s_results' =>'search results', -'previous' =>'Previous', -'next' =>'Next', -'on' =>'on', - -'id_start' =>'Site indexing', -'id_end' =>'Indexing complete !', -'id_recent' =>'Was recently indexed', -'num_words' =>'Num words', -'time' =>'time', -'error' =>'Error', -'no_spider' =>'Spider not launched', -'no_site' =>'No such site in database', -'no_temp' =>'No link in temporary table', -'no_toindex' =>'No content indexed', -'double' =>'Duplicate of an existing document', - -'spidering' =>'Spidering in progress...', -'links_more' =>'more new links', -'level' =>'level', -'links_found' =>'links found', -'define_ex' =>'Define exclusions', -'index_all' =>'index all', - -'end' =>'end', -'no_query' =>'Select predefined keywords (recommended) by opening the tree with the [+] button below, or type descriptive words in the inputzone, separated by a comma, or type the first letters of a keyword and use autocomplete. Empty the inputzone to re-use autocomplete', -'pwait' =>'Please wait', -'statistics' =>'Statistics', - -// INSTALL -'slogan' =>'The smallest search engine in the universe : version', -'installation' =>'Installation', -'instructions' =>'Type here the MySql parameters. Specify a valid existing user who can create databases if you choose create or update.', -'hostname' =>'Hostname :', -'port' =>'Port (none = default) :', -'sock' =>'Sock (none = default) :', -'user' =>'User :', -'password' =>'Password :', -'phpdigdatabase' =>'PhpDig database :', -'tablesprefix' =>'Tables prefix :', -'instructions2' =>'* optional. Use lowercase characters, 16 characters max.', -'installdatabase' =>'Install phpdig database', -'error1' =>'Can\'t find connexion template. ', -'error2' =>'Can\'t write connexion template. ', -'error3' =>'Can\'t find init_db.sql file. ', -'error4' =>'Can\'t create tables. ', -'error5' =>'Can\'t find all config database files. ', -'error6' =>'Can\'t create database.
    Verify user\'s rights. ', -'error7' =>'Can\'t connect to database
    Verify connection datas. ', -'createdb' =>'Create database', -'createtables' =>'Create tables only', -'updatedb' =>'Update existing database', -'existingdb' =>'Write only connection parameters', -// CLEANUP_ENGINE -'cleaningindex' =>'Cleaning index', -'enginenotok' =>' index references targeted an inexistent keyword.', -'engineok' =>'Engine is coherent.', -// CLEANUP_KEYWORDS -'cleaningdictionnary' =>'Cleaning dictionary', -'keywordsok' =>'All keywords are in one or more page.', -'keywordsnotok' =>' keywords where not in one page at least.', -// CLEANUP_COMMON -'cleanupcommon' =>'Cleanup common words', -'cleanuptotal' =>'Total ', -'cleaned' =>' cleaned.', -'deletedfor' =>' deleted for ', -// INDEX ADMIN -'digthis' =>'Dig this !', -'databasestatus' =>'DataBase status', -'entries' =>' Entries ', -'updateform' =>'Update form', -'deletesite' =>'Delete site', -// SPIDER -'spiderresults' =>'Spider results', -// STATISTICS -'mostkeywords' =>'Most keywords', -'richestpages' =>'Richest pages', -'mostterms' =>'Most search terms', -'largestresults'=>'Largest results', -'mostempty' =>'Most searchs giving empty results', -'lastqueries' =>'Last search queries', -'lastclicks' =>'Last search clicks', -'responsebyhour'=>'Response time by hour', -// UPDATE -'userpasschanged' =>'User/Password changed !', -'uri' =>'URI : ', -'change' =>'Change', -'root' =>'Root', -'pages' =>' pages', -'locked' => 'Locked', -'unlock' => 'Unlock site', -'onelock' => 'A site is locked, because of spidering. You can\'t do this for now', -// PHPDIG_FORM -'go' =>'Go ...', -// SEARCH_FUNCTION -'noresults' =>'No results' -); -?> diff --git a/main/metadata/phpdig/phpdig_functions.php b/main/metadata/phpdig/phpdig_functions.php deleted file mode 100755 index 515ec7d384..0000000000 --- a/main/metadata/phpdig/phpdig_functions.php +++ /dev/null @@ -1,279 +0,0 @@ - vartype -// Useful for error_reporting E_ALL too, init variables -// usage in script : extract(phpdigHttpVars(array('foobar'=>'string'))); -function phpdigHttpVars($varray=array()) { -$parse_orders = array('_POST','_GET','HTTP_POST_VARS','HTTP_GET_VARS'); -$httpvars = array(); -// extract the right array -if (is_array($varray)) { - foreach($parse_orders as $globname) { - global $$globname; - if (!count($httpvars) && isset($$globname) && is_array($$globname)) { - $httpvars = $$globname; - } - } - // extract or create requested vars - foreach($varray as $varname => $vartype) { - if (in_array($vartype,array('integer','bool','double','float','string','array')) ) { - if (!isset($httpvars[$varname])) { - if (!isset($GLOBALS[$varname])) { - $httpvars[$varname] = false; - } - else { - $httpvars[$varname] = $GLOBALS[$varname]; - } - } - settype($httpvars[$varname],$vartype); - } - } -return $httpvars; -} -} - -/** - * timer for profiling - * @package chamilo.metadata - */ -class phpdigTimer { - var $time = 0; - var $mode = ''; - var $marks = array(); - var $template = ''; - - function phpdigTimer($mode='html') { - $this->time = $this->getTime(); - if ($mode == 'cli') { - $this->template = "%s:\t%0.9f s. \n"; - } - else { - $this->template = "%s%0.9f s. \n"; - } - } - function start($name) { - if (!isset($this->marks[$name])) { - $this->marks[$name]['time'] = $this->getTime(); - $this->marks[$name]['stat'] = 'r'; - } - else if ($this->marks[$name]['stat'] == 's') { - $this->marks[$name]['time'] = $this->getTime()-$this->marks[$name]['time']; - $this->marks[$name]['stat'] = 'r'; - } - } - function stop($name) { - if (isset($this->marks[$name]) && $this->marks[$name]['stat'] == 'r') { - $this->marks[$name]['time'] = $this->getTime()-$this->marks[$name]['time']; - } - else { - $this->marks[$name]['time'] = 0; - } - $this->marks[$name]['stat'] = 's'; - } - function display() { - if ($this->mode != 'cli') { - print "\n"; - } - foreach($this->marks as $name => $value) { - printf($this->template,ucwords($name),$value['time']); - } - if ($this->mode != 'cli') { - print "
    MarkValue
    \n"; - } - } - // increase precision with deltime - function getTime() { - return array_sum(explode(' ',microtime()))-$this->time; - } -} - -//-------------STRING FUNCTIONS - -//================================================= -//returns a localized string -function phpdigMsg($string='') { -global $phpdig_mess; -if (isset($phpdig_mess[$string])) { - return nl2br($phpdig_mess[$string]); -} -else { - return ucfirst($string); -} -} - -//================================================= -//print a localized string -function phpdigPrnMsg($string='') { -global $phpdig_mess; -if (isset($phpdig_mess[$string])) { - print nl2br($phpdig_mess[$string]); -} -else { - print ucfirst($string); -} -} - -//================================================= -//load the common words in an array -function phpdigComWords($file='') -{ -$lines = @file($file); -if (is_array($lines)) - { - while (list($id,$word) = each($lines)) - $common[trim($word)] = 1; - } -else - $common['aaaa'] = 1; -return $common; -} - -//================================================= -//highlight a string part -function phpdigHighlight($ereg='',$string='') -{ -if ($ereg) { - $string = @eregi_replace($ereg,"\\1<^#_>\\2\\3",@eregi_replace($ereg,"\\1<^#_>\\2\\3",$string)); - $string = str_replace("^#_","span class=\"phpdigHighlight\"",str_replace("_#^","span",$string)); - return $string; -} -else { - return null; -} -} - -//================================================= -//replace all characters with an accent -function phpdigStripAccents($chaine,$encoding=PHPDIG_ENCODING) { -global $phpdigEncode; -if (!isset($phpdigEncode[$encoding])) { - $encoding = PHPDIG_ENCODING; -} -// exceptions -if ($encoding == 'iso-8859-1') { - $chaine = str_replace('�','ae',str_replace('�','ae',$chaine)); -} -return( strtr( $chaine,$phpdigEncode[$encoding]['str'],$phpdigEncode[$encoding]['tr']) ); -} - -//========================================== -//Create a ereg for highlighting -function phpdigPregQuotes($chaine,$encoding=PHPDIG_ENCODING) { -global $phpdigEncode; -if (!isset($phpdigEncode[$encoding])) { - $encoding = PHPDIG_ENCODING; -} -$chaine = preg_quote(strtolower(phpdigStripAccents($chaine,$encoding))); -return str_replace($phpdigEncode[$encoding]['char'],$phpdigEncode[$encoding]['ereg'],$chaine); -} - -//================================================= -// Create Useful arrays for different encodings -function phpdigCreateSubstArrays($subststrings) { -$phpdigEncode = array(); -global $phpdigEncode; - -foreach($subststrings as $encoding => $subststring) { - $tempArray = explode(',',$subststring); - if (!isset($phpdigEncode[$encoding])) { - $phpdigEncode[$encoding] = array(); - } - $phpdigEncode[$encoding]['str'] = ''; - $phpdigEncode[$encoding]['tr'] = ''; - $phpdigEncode[$encoding]['char'] = array(); - $phpdigEncode[$encoding]['ereg'] = array(); - foreach ($tempArray as $tempSubstitution) { - $chrs = explode(':',$tempSubstitution); - $phpdigEncode[$encoding]['char'][strtolower($chrs[0])] = strtolower($chrs[0]); - settype($phpdigEncode[$encoding]['ereg'][strtolower($chrs[0])],'string'); - $phpdigEncode[$encoding]['ereg'][strtolower($chrs[0])] .= $chrs[0].$chrs[1]; - for($i=0; $i < strlen($chrs[1]); $i++) { - $phpdigEncode[$encoding]['str'] .= $chrs[1][$i]; - $phpdigEncode[$encoding]['tr'] .= $chrs[0]; - } - } - foreach($phpdigEncode[$encoding]['ereg'] as $id => $ereg) { - $phpdigEncode[$encoding]['ereg'][$id] = '['.$ereg.']'; - } -} -} - -//================================================= -//epure a string from all non alnum words (words can contain &__&��� character) -function phpdigEpureText($text,$min_word_length=2,$encoding=PHPDIG_ENCODING) { -global $phpdig_words_chars; - -$text = phpdigStripAccents(strtolower ($text)); -//no-latin upper to lowercase - now islandic -switch (PHPDIG_ENCODING) { - case 'iso-8859-1': - $text = strtr( $text,'��','��'); - break; -} - -// RH ereg_replace('[^'.$phpdig_words_chars[$encoding].' \'._~@#$:&%/;,=-]+',' ',$text); -$text = ereg_replace('[^'.$phpdig_words_chars[$encoding].' \'._~@#$&%/=-]+',' ',$text); - -// RH ereg_replace('(['.$phpdig_words_chars[$encoding].'])[\'._~@#$:&%/;,=-]+($|[[:space:]]$|[[:space:]]['.$phpdig_words_chars[$encoding].'])','\1 \2',$text); -$text = ereg_replace('(['.$phpdig_words_chars[$encoding].'])[\'._~@#$&%/=-]+($|[[:space:]]$|[[:space:]]['.$phpdig_words_chars[$encoding].'])','\1 \2',$text); - -// the next two repeated lines needed -if ($min_word_length >= 1) { - $text = ereg_replace('[[:space:]][^ ]{1,'.$min_word_length.'}[[:space:]]',' ',' '.$text.' '); - $text = ereg_replace('[[:space:]][^ ]{1,'.$min_word_length.'}[[:space:]]',' ',' '.$text.' '); -} - -$text = ereg_replace('\.{2,}',' ',$text); -$text = ereg_replace('^[[:space:]]*\.+',' ',$text); - -return trim(ereg_replace("[[:space:]]+"," ",$text)); -} - -//-------------SQL FUNCTIONS - -//================================================= -//insert an entry in logs -function phpdigAddLog ($id_connect,$option='start',$includes=array(),$excludes=array(),$num_results=0,$time=0) { - if (!is_array($excludes)) { - $excludes = array(); - } - sort($excludes); - if (!is_array($includes)) { - $includes = array(); - } - sort($includes); - $now = api_get_utc_datetime(); - $query = 'INSERT INTO '.PHPDIG_DB_PREFIX.'logs (l_num,l_mode,l_ts,l_includes,l_excludes,l_time) ' - .'VALUES ('.$num_results.',\''.substr($option,0,1).'\',"' . $now . '",' - .'\''.implode(' ',$includes).'\',\''.implode(' ',$excludes).'\','.(double)$time.')'; - mysql_query($query,$id_connect); - return mysql_insert_id($id_connect); -} - -?> diff --git a/main/metadata/phpdig/search.php b/main/metadata/phpdig/search.php deleted file mode 100755 index 50b4623b24..0000000000 --- a/main/metadata/phpdig/search.php +++ /dev/null @@ -1,295 +0,0 @@ -'string', - 'mdsc'=>'string', 'kwdswere_string'=>'string', // Dokeos - 'refine'=>'integer', - 'refine_url'=>'string', - 'site'=>'string', // set to integer later - 'limite'=>'integer', - 'option'=>'string', - 'lim_start'=>'integer', - 'browse'=>'integer', - 'path'=>'string' - ) - ),EXTR_SKIP); - - $adlog_flag = 0; - $rssdf = ""; -// end of part copied (with some changes) from standard PhpDig search.php - - -// Course keywords - -$_course = api_get_course_info(); $ckw = $_course['path'] . '/CourseKwds.js'; -define('KEYWORDS_CACHE', api_get_path(SYS_COURSE_PATH) . $ckw); - -if (file_exists(KEYWORDS_CACHE)) $kcdt = - htmlspecialchars(date('Y/m/d H:i:s', filemtime(KEYWORDS_CACHE))); - -$keywordscache = $kcdt ? - '' . - '
    (CourseKwds cache: ' . $kcdt . ')' : ''; - - -// Dokeos header - -$nameTools = get_lang('Search'); -$htmlHeadXtra[] = ''; -$htmlHeadXtra[] = ''; -$htmlHeadXtra[] = ' - '; - -Display::display_header($nameTools); echo "\n"; - -echo '', - '

    ', get_lang('Search'), '

    '; - - -// Store new extra criteria (course manager only, see below), or execute -// PhpDig Search and echo result message + table with results + pages bar - -if (!$query_string) $query_string = trim($mdsc); - -$ckwcdt = file_exists($ckwc = KEYWORDS_CACHE . 'c') ? - date('Y/m/d H:i:s', filemtime($ckwc)) : '?'; $pkwc = ''; - -if (substr($query_string, 0, 2) == '<>' && api_is_allowed_to_edit()) -{ - if ($ckwcdt{0} != '?') - { - $fckwc = fopen($ckwc, 'rb'); $pkwc = fread($fckwc, filesize($ckwc)); - fclose($fckwc); unset($fckwc); - } - - if(($fckwc = fopen($ckwc, 'wb'))) - { - fwrite($fckwc, $query_string); fclose($fckwc); unset($fckwc); - $ckwcdt = file_exists($ckwc) ? - date('Y/m/d H:i:s', filemtime($ckwc)) : '? Write Error'; - } - else $ckwcdt = '? Open Error'; - - $phpdigSearchResults = array('result_message' => $ckw . 'c: ' . $ckwcdt, - 'pages_bar' => '', 'results' => array()); -} -else -{ - $phpdigSearchResults = phpdigSearch($id_connect, $query_string, $option, - $refine, $refine_url, $lim_start, $limite, $browse, $site, $path, - $relative_script_path, $template, $adlog_flag, $rssdf, $template_demo); -} - -$result_message = ''; $hits = 11; - -if ($result_message = $phpdigSearchResults['result_message']) - if (($cspos = strpos($result_message, ', ')) !== FALSE) - if (($sppos = strpos($result_message, ' ', $cspos += 2)) !== FALSE) - if (is_numeric($total = substr($result_message, $cspos, $sppos-$cspos))) - $hits = (int) $total; - -if (!($pages_bar = $phpdigSearchResults['pages_bar'])) $hits = 0; - -if ($result_message == phpdigMsg('noresults')) $result_message .= ' '.phpdigMsg('on').' "'.htmlspecialchars($query_string,ENT_QUOTES).'"'; - -echo $result_message, '

    ', "\n"; - -if ($phpdigSearchResults['results']) foreach ($phpdigSearchResults['results'] as $searchResult) -{ - $url = $searchResult['complete_path']; - - if (ereg("/[^?/]*\\?.*thumb=", $url)) - { - // direct URL: $thumburl = ereg_replace("/[^?/]*\\?.*thumb=", "/", $url); - $thumburl = ereg_replace("\\?.*thumb=", "?th=", $url); // via index.php - } - else - { - $thumburl = "tpl_img/link.gif"; - } - - echo '', "\n"; -} - -echo '
    ', $searchResult['link_title'], - '
    ', $searchResult['text'], '

    '; - -if ($result_message && ($hits > 10)) - echo "Results page ", str_replace('?template_demo=', - '?kwdswere_string=' . urlencode($kwdswere_string), $pages_bar), '

    '; - -/* Extra criteria: A course manager can define and edit them in the TEXTAREA. - If he types in something as in the example below, and clicks 'Go', the new - criteria are stored and the old ones are displayed. So it is easy to - restore the old ones. To confirm the new ones, empty the TEXTAREA. - -<>This selection empties extra criteria -Label -Descriptive text - -*/ - -$tdhtm = ''; - -function tdhtm($xc) -{ - $eol = '
    '; if ($xc{0} == '<') $xc = substr($xc, 1); - - if (($eov = strpos($xc, '>')) === FALSE) - $value = $label = $xc; - else - { - $value = substr($xc, 0, $eov); $label = substr($xc, $eov+1); - - if (($eot = strpos($label, '<')) !== FALSE) - { - $eol = substr($label, $eot); $label = substr($label, 0, $eot); - } - } - - return '' . - htmlspecialchars($label) . '' . $eol; -} - -if ($ckwcdt{0} != '?') // there is a file with extra criteria -{ - $fckwc = fopen($ckwc, 'rb'); - foreach (explode("\n", fread($fckwc, filesize($ckwc))) as $xc) - $tdhtm .= "\n" . tdhtm($xc); - fclose($fckwc); unset($fckwc); -} - -// Search criteria form and keywords tree -?> - -
    - - - -
    - - - - - - -
    - - ', htmlspecialchars($pkwc), ''; - else echo ''; - ?> - - - -
    - - - -
    - -
    -
    - -
    -   - Keywords-restrictive search
    - - - -   -
    - -
    - -
    - -
    - - diff --git a/main/metadata/phpdig/search_function.php b/main/metadata/phpdig/search_function.php deleted file mode 100755 index 43f9540ae5..0000000000 --- a/main/metadata/phpdig/search_function.php +++ /dev/null @@ -1,785 +0,0 @@ -start('All'); - -// init variables -global $phpdig_words_chars,$maxweight; -settype($maxweight,'integer'); -$ignore = ''; -$ignore_common = ''; -$ignore_message = ''; -$ignore_commess = ''; -$wheresite = ''; -$wherepath = ''; -$table_results = ''; -$final_result = ''; -$search_time = 0; -$strings = ''; -$num_tot = 0; -$leven_final = ""; -$exclude = array(); -$nav_bar = ''; -$pages_bar = ''; - -$mtime = explode(' ',microtime()); -$start_time = $mtime[0]+$mtime[1]; - -$timer->start('All backend'); -$timer->start('parsing strings'); - -if (!$option) { - $option = SEARCH_DEFAULT_MODE; -} -if (!in_array($option,array('start','any','exact'))) { - return 0; -} -// the query was filled -if ($query_string) { - -$common_words = phpdigComWords("$relative_script_path/includes/common_words.txt"); - -$like_start = array( "start" => "", // is empty - "any" => "", // was a percent - "exact" => "" // is empty - ); -$like_end = array( "start" => "%", // is a percent - "any" => "%", // is a percent - "exact" => "%" // was empty - ); -$like_operator = array( "start" => "like", // is a like - "any" => "like", // is a like - "exact" => "like" // was an = - ); - -if ($refine) { - $wheresite = "AND spider.site_id = $site "; - if (($path) && (strlen($path) > 0)) { - $wherepath = "AND spider.path like '$my_path' "; - } - $refine_url = "&refine=1&site=$site&path=".urlencode($path); -} -else { - $refine_url = ""; -} - -settype ($lim_start,"integer"); -if ($lim_start < 0) { - $lim_start = 0; -} - -$n_words = count(explode(" ",$query_string)); - -$ncrit = 0; -$tin = "0"; - -if (!get_magic_quotes_gpc()) { - $query_to_parse = addslashes($query_string); -} -else { - $query_to_parse = $query_string; -} -$my_query_string_link = stripslashes($query_to_parse); - -$query_to_parse = str_replace('_','\_',$query_to_parse); // avoid '_' in the query -$query_to_parse = str_replace('%','\%',$query_to_parse); // avoid '%' in the query -$query_to_parse = str_replace('\"',' ',$query_to_parse); // avoid '"' in the query - -$query_to_parse = phpdigStripAccents(strtolower($query_to_parse)); //made all lowercase - -// RH query_chars = "[^".$phpdig_words_chars[PHPDIG_ENCODING]." \'.\_~@#$:&\%/;,=-]+"; // epure chars \'._~@#$:&%/;,=- -$what_query_chars = "[^".$phpdig_words_chars[PHPDIG_ENCODING]." \'._~@#$&%/=-]+"; // epure chars \'._~@#$&%/=- - -if (eregi($what_query_chars,$query_to_parse)) { - $query_to_parse = eregi_replace($what_query_chars," ",$query_to_parse); -} - -$query_to_parse = ereg_replace('(['.$phpdig_words_chars[PHPDIG_ENCODING].'])[\'.\_~@#$:&\%/;,=-]+($|[[:space:]]$|[[:space:]]['.$phpdig_words_chars[PHPDIG_ENCODING].'])','\1 \2',$query_to_parse); - -$query_to_parse = trim(ereg_replace(" +"," ",$query_to_parse)); // no more than 1 blank - -$query_for_strings = $query_to_parse; -$query_for_phrase = $query_to_parse; -$test_short = $query_to_parse; -$query_to_parse2 = explode(" ",$query_to_parse); -usort($query_to_parse2, "phpdigByLength"); -$query_to_parse = implode(" ",$query_to_parse2); -if (isset($query_to_parse2)) { unset($query_to_parse2); } - -if (SMALL_WORDS_SIZE >= 1) { -$ignore_short_flag = 0; -$test_short_counter = 0; -$test_short2 = explode(" ",$test_short); -for ($i=0; $i 0)) { - $test_short2[$i].=" "; - $test_short_counter++; - $test_short3[] = $test_short2[$i]; - } -} -$test_short = implode(" ",$test_short3); -if (isset($test_short2)) { unset($test_short2); } -if (isset($test_short3)) { unset($test_short3); } - - $regs = array(); // for use with ereg() - while (ereg('( [^ ]{1,'.SMALL_WORDS_SIZE.'} )|( [^ ]{1,'.SMALL_WORDS_SIZE.'})$|^([^ ]{1,'.SMALL_WORDS_SIZE.'} )',$test_short,$regs)) { - for ($n=1; $n<=3; $n++) { - if (($regs[$n]) || ($regs[$n] == 0)) { - $ignore_short_flag++; - if (!eregi("\"".trim(stripslashes($regs[$n]))."\", ",$ignore)) { - $ignore .= "\"".trim(stripslashes($regs[$n]))."\", "; - } - $test_short = trim(str_replace($regs[$n],"",$test_short)); - } - } - } - if (strlen($test_short) <= SMALL_WORDS_SIZE) { - if (!eregi("\"".$test_short."\", ",$ignore)) { - $ignore_short_flag++; - $ignore .= "\"".stripslashes($test_short)."\", "; - } - $test_short = trim(str_replace($test_short,"",$test_short)); - } -} - -$ignore = str_replace("\"\", ","",$ignore); - -if ($option != "exact") { - if (($ignore) && ($ignore_short_flag > 1) && ($test_short_counter > 1)) { - $ignore_message = $ignore.' '.phpdigMsg('w_short_plur'); - } - elseif ($ignore) { - $ignore_message = $ignore.' '.phpdigMsg('w_short_sing'); - } -} - -$ignore_common_flag = 0; -while (ereg("(-)?([^ ]{".(SMALL_WORDS_SIZE+1).",}).*",$query_for_strings,$regs)) { - $query_for_strings = trim(str_replace($regs[2],"",$query_for_strings)); - if (!isset($common_words[stripslashes($regs[2])])) { - if ($regs[1] == '-') { - $exclude[$ncrit] = $regs[2]; - $query_for_phrase = trim(str_replace("-".$regs[2],"",$query_for_phrase)); - } - else { - $strings[$ncrit] = $regs[2]; - } - $kconds[$ncrit] = ''; - if ($option != 'any') { - $kconds[$ncrit] .= " AND k.twoletters = '".addslashes(substr(str_replace('\\','',$regs[2]),0,2))."' "; - } - $kconds[$ncrit] .= " AND k.keyword ".$like_operator[$option]." '".$like_start[$option].$regs[2].$like_end[$option]."' "; - $ncrit++; - } - else { - $ignore_common_flag++; - $ignore_common .= "\"".stripslashes($regs[2])."\", "; - } -} - -if ($option != "exact") { - if (($ignore_common) && ($ignore_common_flag > 1)) { - $ignore_commess = $ignore_common.' '.phpdigMsg('w_common_plur'); - } - elseif ($ignore_common) { - $ignore_commess = $ignore_common.' '.phpdigMsg('w_common_sing'); - } -} - -$timer->stop('parsing strings'); - -if ($ncrit && is_array($strings)) { - $query = "SET OPTION SQL_BIG_SELECTS = 1"; - mysql_query($query,$id_connect); - - $my_spider2site_array = array(); - $my_sitecount_array = array(); - - for ($n = 0; $n < $ncrit; $n++) { - $timer->start('spider queries'); - - $query = "SELECT spider.spider_id,sum(weight) as weight, spider.site_id - FROM ".PHPDIG_DB_PREFIX."keywords as k,".PHPDIG_DB_PREFIX."engine as engine, ".PHPDIG_DB_PREFIX."spider as spider - WHERE engine.key_id = k.key_id - ".$kconds[$n]." - AND engine.spider_id = spider.spider_id $wheresite $wherepath - GROUP BY spider.spider_id,spider.site_id "; - - $result = mysql_query($query,$id_connect); - $num_res_temp = mysql_num_rows($result); - - $timer->stop('spider queries'); - $timer->start('spider fills'); - - if ($num_res_temp > 0) { - if (!isset($exclude[$n])) { - $num_res[$n] = $num_res_temp; - while (list($spider_id,$weight,$site_id) = mysql_fetch_array($result)) { - $s_weight[$n][$spider_id] = $weight; - $my_spider2site_array[$spider_id] = $site_id; - $my_sitecount_array[$site_id] = 0; - } - } - else { - $num_exclude[$n] = $num_res_temp; - while (list($spider_id,$weight) = mysql_fetch_array($result)) { - $s_exclude[$n][$spider_id] = 1; - } - mysql_free_result($result); - } - } - elseif (!isset($exclude[$n])) { - $num_res[$n] = 0; - $s_weight[$n][0] = 0; - } - $timer->stop('spider fills'); - } - - $timer->start('reorder results'); - - if ($option != "any") { - if (is_array($num_res)) { - asort ($num_res); - list($id_most) = each($num_res); - reset ($s_weight[$id_most]); - while (list($spider_id,$weight) = each($s_weight[$id_most])) { - $weight_tot = 1; - reset ($num_res); - while(list($n) = each($num_res)) { - settype($s_weight[$n][$spider_id],'integer'); - $weight_tot *= sqrt($s_weight[$n][$spider_id]); - } - if ($weight_tot > 0) { - $final_result[$spider_id]=$weight_tot; - } - } - } - } - else { - if (is_array($num_res)) { - asort ($num_res); - while (list($spider_id,$site_id) = each($my_spider2site_array)) { - $weight_tot = 0; - reset ($num_res); - while(list($n) = each($num_res)) { - settype($s_weight[$n][$spider_id],'integer'); - $weight_tot += sqrt($s_weight[$n][$spider_id]); - } - if ($weight_tot > 0) { - $final_result[$spider_id]=$weight_tot; - } - } - } - } - - if (isset($num_exclude) && is_array($num_exclude)) { - while (list($id) = each($num_exclude)) { - while(list($spider_id) = each($s_exclude[$id])) { - if (isset($final_result[$spider_id])) { unset($final_result[$spider_id]); } - } - } - } - - if ($option == "exact") { - if ((is_array($final_result)) && (count($final_result) > 0)) { - $exact_phrase_flag = 0; - arsort($final_result); - reset($final_result); - $query_for_phrase_array = explode(" ",$query_for_phrase); - $reg_strings = str_replace('@#@',' ',phpdigPregQuotes(str_replace('\\','',implode('@#@',$query_for_phrase_array)))); - $stop_regs = "[][(){}[:blank:]=&?!&#%\$�*@+%:;,/\.'\"]"; - $reg_strings = "($stop_regs{1}|^)($reg_strings)($stop_regs{1}|\$)"; - while (list($spider_id,$weight) = each($final_result)) { - $content_file = $relative_script_path.'/'.TEXT_CONTENT_PATH.$spider_id.'.txt'; - if (is_file($content_file)) { - $f_handler = fopen($content_file,'r'); - $extract_content = preg_replace("/([ ]{2,}|\n|\r|\r\n)/"," ",fread($f_handler,filesize($content_file))); - if(!eregi($reg_strings,$extract_content)) { - $exact_phrase_flag = 1; - } - fclose($f_handler); - } - if ($exact_phrase_flag == 1) { - if (isset($final_result[$spider_id])) { unset($final_result[$spider_id]); } - $exact_phrase_flag = 0; - } - } - } - } - - if((!$refine) && (NUMBER_OF_RESULTS_PER_SITE != -1)) { - if ((is_array($final_result)) && (count($final_result) > 0)) { - arsort($final_result); - reset($final_result); - while (list($spider_id,$weight) = each($final_result)) { - $site_id = $my_spider2site_array[$spider_id]; - $current_site_counter = $my_sitecount_array[$site_id]; - if ($current_site_counter < NUMBER_OF_RESULTS_PER_SITE) { - $my_sitecount_array[$site_id]++; - } - else { - if (isset($final_result[$spider_id])) { unset($final_result[$spider_id]); } - } - } - } - } - - $timer->stop('reorder results'); -} - -$timer->stop('All backend'); -$timer->start('All display'); - -if ((is_array($final_result)) && (count($final_result) > 0)) { - arsort($final_result); - $lim_start = max(0, $lim_start-($lim_start % $limite)); - $n_start = $lim_start+1; - $num_tot = count($final_result); - - if ($n_start+$limite-1 < $num_tot) { - $n_end = ($lim_start+$limite); - $more_results = 1; - } - else { - $n_end = $num_tot; - $more_results = 0; - } - - if ($n_start > $n_end) { - $n_start = 1; - $n_end = min($num_tot,$limite); - $lim_start = 0; - if ($n_end < $num_tot) { - $more_results = 1; - } - } - - // ereg for text snippets and highlighting - if ($option == "exact") { - $reg_strings = str_replace('@#@',' ',phpdigPregQuotes(str_replace('\\','',implode('@#@',$query_for_phrase_array)))); - } - else { - $reg_strings = str_replace('@#@','|',phpdigPregQuotes(str_replace('\\','',implode('@#@',$strings)))); - } - $stop_regs = "[][(){}[:blank:]=&?!&#%\$�*@+%:;,/\.'\"]"; - - switch($option) { - case 'any': - $reg_strings = "($stop_regs{1}|^)($reg_strings)()"; - break; - case 'exact': - $reg_strings = "($stop_regs{1}|^)($reg_strings)($stop_regs{1}|\$)"; - break; - default: - $reg_strings = "($stop_regs{1}|^)($reg_strings)()"; - } - - $timer->start('Result table'); - - //fill the results table - reset($final_result); - for ($n = 1; $n <= $n_end; $n++) { - list($spider_id,$s_weight) = each($final_result); - if (!$maxweight) { - $maxweight = $s_weight; - } - if ($n >= $n_start) { - $timer->start('Display queries'); - - $query = "SELECT sites.site_url, sites.port, spider.path,spider.file,spider.first_words,sites.site_id,spider.spider_id,spider.last_modified,spider.md5 " - ."FROM ".PHPDIG_DB_PREFIX."spider AS spider, ".PHPDIG_DB_PREFIX."sites AS sites " - ."WHERE spider.spider_id=$spider_id AND sites.site_id = spider.site_id"; - $result = mysql_query($query,$id_connect); - $content = mysql_fetch_array($result,MYSQL_ASSOC); - mysql_free_result($result); - if ($content['port']) { - $content['site_url'] = ereg_replace('/$',':'.$content['port'].'/',$content['site_url']); - } - $weight = sprintf ("%01.2f", (100*$s_weight)/$maxweight); - $url = eregi_replace("([".$phpdig_words_chars[PHPDIG_ENCODING]."])[/]{2,}","\\1/",urldecode($content['site_url'].$content['path'].$content['file'])); - - $js_url = urlencode(eregi_replace("^[a-z]{3,5}://","",$url)); - - $url = str_replace("\"","%22",str_replace("'","%27",str_replace(" ","%20",trim($url)))); - - $l_site = "".htmlspecialchars(urldecode($content['site_url']),ENT_QUOTES).""; - if ($content['path']) { - $content['path'] = urlencode(urldecode($content['path'])); - $content2['path'] = htmlspecialchars(urldecode($content['path']),ENT_QUOTES); - $l_path = ", ".phpdigMsg('this_path')." : ".$content2['path'].""; - } - else { - $content2['path'] = ""; - $l_path=""; - } - - $first_words = ereg_replace('txt-sep +txt-end', 'txt-end', ereg_replace('txt-sep +txt-sep', 'txt-sep', $content['first_words'])); // RH was just: $content['first_words']; - $first_words = str_replace('-kw ', ' ', str_replace('txt-end', "\n", str_replace('txt-sep', '
    ', $first_words))); // RH this line added - - $timer->stop('Display queries'); - $timer->start('Extracts'); - - $extract = ""; - //Try to retrieve matching lines if the content-text is set to 1 - if (CONTENT_TEXT == 1 && DISPLAY_SNIPPETS) { - $content_file = $relative_script_path.'/'.TEXT_CONTENT_PATH.$content['spider_id'].'.txt'; - if (is_file($content_file)) { - $num_extracts = 0; - $my_extract_size = 200; - - $my_filesize_for_while = filesize($content_file); - while (($num_extracts == 0) && ($my_extract_size <= $my_filesize_for_while)) { // *** - - $f_handler = fopen($content_file,'r'); - while($num_extracts < DISPLAY_SNIPPETS_NUM && $extract_content = preg_replace("/([ ]{2,}|\n|\r|\r\n)/"," ",fread($f_handler,$my_extract_size))) { - if(eregi($reg_strings,$extract_content)) { - $match_this_spot = eregi_replace($reg_strings,"\\1<\\2>\\3",$extract_content); - $first_bold_spot = strpos($match_this_spot,"<"); - $first_bold_spot = max($first_bold_spot - round((SNIPPET_DISPLAY_LENGTH / 2),0), 0); - $extract_content = substr($extract_content,$first_bold_spot,max(SNIPPET_DISPLAY_LENGTH, 2 * strlen($query_string))); - $extract .= ' ...'.phpdigHighlight($reg_strings,$extract_content).'... '; - $num_extracts++; - } - } - fclose($f_handler); - - if ($my_extract_size < $my_filesize_for_while) { - $my_extract_size *= 100; - if ($my_extract_size > $my_filesize_for_while) { - $my_extract_size = $my_filesize_for_while; - } - } - else { - $my_extract_size++; - } - - } // ends *** - } - } - - list($title,$text) = explode("\n",$first_words); - - $title = htmlspecialchars(phpdigHighlight($reg_strings,urldecode($title)),ENT_QUOTES); - $title = phpdigSpanReplace($title); - - $timer->stop('Extracts'); - - $table_results[$n] = array ( - 'weight' => $weight, - 'img_tag' => '', - 'page_link' => "".$title."", - 'limit_links' => phpdigMsg('limit_to')." ".$l_site.$l_path, - 'filesize' => sprintf('%.1f',(ereg_replace('.*_([0-9]+)$','\1',$content['md5']))/1024), - 'update_date' => ereg_replace('^([0-9]{4})([0-9]{2})([0-9]{2}).*',PHPDIG_DATE_FORMAT,$content['last_modified']), - 'complete_path' => $url, - 'link_title' => $title - ); - - $table_results[$n]['text'] = ''; - if (DISPLAY_SUMMARY) { - $table_results[$n]['text'] = htmlspecialchars(phpdigHighlight($reg_strings,preg_replace("/([ ]{2,}|\n|\r|\r\n)/"," ",ereg_replace('(@@@.*)','',wordwrap($text, SUMMARY_DISPLAY_LENGTH, '@@@')))),ENT_QUOTES); - $table_results[$n]['text'] = phpdigSpanReplace($table_results[$n]['text']); - } - if (DISPLAY_SUMMARY && DISPLAY_SNIPPETS) { - $table_results[$n]['text'] .= "\n

    \n"; - } - if (DISPLAY_SNIPPETS) { - if ($extract) { - $extract = htmlspecialchars($extract,ENT_QUOTES); - $extract = phpdigSpanReplace($extract); - $table_results[$n]['text'] .= $extract; - } - else if (!$table_results[$n]['text']){ - $table_results[$n]['text'] = htmlspecialchars(phpdigHighlight($reg_strings,preg_replace("/([ ]{2,}|\n|\r|\r\n)/"," ",ereg_replace('(@@@.*)','',wordwrap($text, SUMMARY_DISPLAY_LENGTH, '@@@')))),ENT_QUOTES); - $table_results[$n]['text'] = phpdigSpanReplace($table_results[$n]['text']); - } - } - } - } - - $timer->stop('Result table'); - $timer->start('Final strings'); - - $url_bar = SEARCH_PAGE."?template_demo=$template_demo&browse=1&query_string=".urlencode($my_query_string_link)."$refine_url&limite=$limite&option=$option&lim_start="; - - if ($lim_start > 0) { - $previous_link = $url_bar.($lim_start-$limite); - $nav_bar .= "<<".phpdigMsg('previous')."    \n"; - } - $tot_pages = ceil($num_tot/$limite); - $actual_page = $lim_start/$limite + 1; - $page_inf = max(1,$actual_page - 5); - $page_sup = min($tot_pages,max($actual_page+5,10)); - for ($page = $page_inf; $page <= $page_sup; $page++) { - if ($page == $actual_page) { - $nav_bar .= " $page \n"; - $pages_bar .= " $page \n"; - $link_actual = $url_bar.(($page-1)*$limite); - } - else { - $nav_bar .= " $page \n"; - $pages_bar .= " $page \n"; - } - } - - if ($more_results == 1) { - $next_link = $url_bar.($lim_start+$limite); - $nav_bar .= "    ".phpdigMsg('next').">>\n"; - } - - $mtime = explode(' ',microtime()); - $search_time = sprintf('%01.2f',$mtime[0]+$mtime[1]-$start_time); - $result_message = stripslashes(ucfirst(phpdigMsg('results'))." $n_start-$n_end, $num_tot ".phpdigMsg('total').", ".phpdigMsg('on')." \"".htmlspecialchars($query_string,ENT_QUOTES)."\" ($search_time ".phpdigMsg('seconds').")"); - - $timer->stop('Final strings'); -} -else { - if (is_array($strings)) { - $strings = array_values($strings); - $num_in_strings_arr = count($strings); - } - else { $num_in_strings_arr = 0; } - $leven_final = ""; - $leven_sum = 0; - if (($num_in_strings_arr > 0) && (strlen($path) == 0)) { - for ($i=0; $i<$num_in_strings_arr; $i++) { - $soundex_query = "SELECT keyword FROM ".PHPDIG_DB_PREFIX."keywords WHERE SOUNDEX(CONCAT('Q',keyword)) = SOUNDEX(CONCAT('Q','".$strings[$i]."')) LIMIT 500"; - $soundex_results = mysql_query($soundex_query,$id_connect); - if (mysql_num_rows($soundex_results) > 0) { - $leven_ind = 0; - $leven_amt1 = 256; - $leven_keyword = array(); - while (list($soundex_keyword) = mysql_fetch_array($soundex_results)) { - $leven_amt2 = min(levenshtein(stripslashes($strings[$i]),$soundex_keyword),$leven_amt1); - if (($leven_amt2 < $leven_amt1) && ($leven_amt2 >= 0) && ($leven_amt2 <= 5)) { - $leven_keyword[$leven_ind] = stripslashes($soundex_keyword); - $leven_ind++; - } - $leven_amt1 = $leven_amt2; - } - $leven_count = count($leven_keyword); - $leven_sum = $leven_sum + $leven_amt1; - if ($leven_count > 0) { - $leven_final .= $leven_keyword[$leven_count-1] . " "; - } - if (isset($leven_keyword)) { unset($leven_keyword); } - } - } - } - $num_tot = 0; - $result_message = phpdigMsg('noresults'); - if ((strlen(trim($leven_final)) > 0) && ($leven_sum > 0)) { - $leven_query = trim($leven_final); - $result_message .= ". " . phpdigMsg('alt_try') ." ".htmlspecialchars($leven_query,ENT_QUOTES)."?"; - } -} - -if (isset($tempresult)) { - mysql_free_result($tempresult); -} - -$title_message = phpdigMsg('s_results'); -} -else { - $title_message = 'PhpDig '.PHPDIG_VERSION; - $result_message = phpdigMsg('no_query').'.'; -} - -$timer->start('Logs'); -if (PHPDIG_LOGS && !$browse && !$refine && $adlog_flag == 0) { - if (is_array($final_result)) { - phpdigAddLog ($id_connect,$option,$strings,$exclude,count($final_result),$search_time); - } - else { - phpdigAddLog ($id_connect,$option,$strings,$exclude,0,$search_time); - } -} -$timer->stop('Logs'); - -$timer->start('Template parsing'); - -$powered_by_link = ""; -if (ALLOW_RSS_FEED) { - $powered_by_link .= "".phpdigMsg('viewRSS')."
    "; -} -$powered_by_link .= "".phpdigMsg('powered_by')."
    "; - -if (is_array($strings)) { - $js_string = implode(" ",$strings); -} else { - $js_string = ""; -} -$js_for_clicks = " - -"; - -if ($template == 'array' || is_file($template)) { - $phpdig_version = PHPDIG_VERSION; - $t_mstrings = compact('js_for_clicks','powered_by_link','title_message','phpdig_version','result_message','nav_bar','ignore_message','ignore_commess','pages_bar','previous_link','next_link'); - $t_fstrings = phpdigMakeForm($query_string,$option,$limite,SEARCH_PAGE,$site,$path,'template',$template_demo,$num_tot,$refine); - if ($template == 'array') { - return array_merge($t_mstrings,$t_fstrings,array('results'=>$table_results)); - } - else { - $t_strings = array_merge($t_mstrings,$t_fstrings); - phpdigParseTemplate($template,$t_strings,$table_results); - } -} -else { -?> - - -<?php print $title_message ?> - - - - - -
    -phpdig <?php print PHPDIG_VERSION ?> -
    - -

    -
    -
    -

    -
    -\n"; - print "$n. [".$t_result['weight']." %]  ".$t_result['page_link']."\n
    \n"; - print "".$t_result['limit_links']."\n
    \n"; - print "

    \n"; - print "
    \n"; - print $t_result['text']; - print "
    \n"; - } -} -print "

    \n"; -print $nav_bar; -print "

    \n"; -?> -
    -
    - -
    -
    -Powered by PhpDig   -
    - - -stop('Template parsing'); -$timer->stop('All display'); -$timer->stop('All'); -//$timer->display(); -} - -function phpdigSpanReplace($text) { -$text = str_replace("<br>","
    ",$text); // RH -$text = str_replace("</span>","",$text); -$text = str_replace("<span class="phpdigHighlight">","",$text); -return $text; -} - -function phpdigByLength($a, $b) { -$len_a = strlen($a); -$len_b = strlen($b); -if ($len_a == $len_b) { return 0; } -return ($len_a < $len_b) ? 1 : -1; -} -?> diff --git a/main/metadata/phpdig/update_db_to_1_8_6_from_1_8_3.sql b/main/metadata/phpdig/update_db_to_1_8_6_from_1_8_3.sql deleted file mode 100755 index ee6c2ba7cd..0000000000 --- a/main/metadata/phpdig/update_db_to_1_8_6_from_1_8_3.sql +++ /dev/null @@ -1,35 +0,0 @@ -# Update from the 1.8.3 version to the 1.8.6 version -# Add the table prefix if needed -# --------------------------------- -ALTER TABLE sites ADD COLUMN stopped TINYINT(1) NOT NULL DEFAULT 0; -ALTER TABLE site_page ADD COLUMN days INT(4) NOT NULL DEFAULT 0; -ALTER TABLE site_page ADD COLUMN depth INT(4) NOT NULL DEFAULT 5; -ALTER TABLE site_page CHANGE num_page links INT(4) NOT NULL DEFAULT 5; -DROP TABLE sites_days_upd; -ALTER TABLE spider CHANGE first_words first_words mediumtext NOT NULL; -ALTER TABLE excludes DROP INDEX ex_id; -ALTER TABLE includes DROP INDEX in_id; -ALTER TABLE keywords DROP INDEX key_id; -ALTER TABLE logs DROP INDEX l_id; -ALTER TABLE sites DROP INDEX site_id; -ALTER TABLE spider DROP INDEX spider_id; -ALTER TABLE tempspider DROP INDEX id; - -# Upgrading PhpDig from 1.8.3 to 1.8.6 for VELODLA: -# -# - save a copy of includes/connect.php, config.php -# - make the VELODLA/183phpdig directory inaccessible -# -# - restore the 1.8.6 backup to new directory VELODLA/phpdig-1.8.6 -# - replace phpdig-1.8.6/sql/update_db.sql by this file -# - run VELODLA/phpdig-1.8.6/admin/install.php, select "Update existing database", -# (provide the parameters from the old connect.php) -# - adapt config.php (cfr. old config.php) -# -# - re-apply customizations: search.php, cprgo.gif, simpleplus.html -# function_phpdig_form.php, phpdig_functions.php, search_function.php -# -# - edit md_phpdig.php, line 37 -# - edit VELODLA homepage links (PhpDig admin, Search with PhpDig) - -# - change Metadata_for_Dokeos.html diff --git a/main/metadata/playscormmdset.inc.php b/main/metadata/playscormmdset.inc.php deleted file mode 100755 index 497e6e8841..0000000000 --- a/main/metadata/playscormmdset.inc.php +++ /dev/null @@ -1,215 +0,0 @@ - - -if (!isset($scormid)) exit(); - -define('EID_TYPE', 'Scorm'); -define('BID', EID_TYPE . '.' . $scormid); -getpar('SID', 'Scorm sub-id', '*'); -define('EID_ID', (SID == '*') ? $scormid : $scormid . '.' . SID); -define('EID', EID_TYPE . '.' . EID_ID); -getpar('LFN', 'LanguageFileName', 'md_' . strtolower(EID_TYPE)); -getpar('HTT', 'HTML Template Text filename', 'mdp_' . strtolower(EID_TYPE)); -getpar('WHF', 'With Header and Footer', '0'); -define('DBG', 0); // for template debug info, set to e.g. 10000 -getpar('RNG', 'Slide range', '*'); - -if (RNG == '*' || ($dotdot = strpos(RNG, '..')) === FALSE) - $id_range_first = $id_range_last = ''; -else -{ - $id_range_first = trim(substr(RNG, 0, $dotdot)); - $id_range_last = trim(substr(RNG, $dotdot + 2)); -} - -$urlp = '?dbg=' . urlencode(DBG); -if (LFN != 'md_' . strtolower(EID_TYPE)) $urlp .= '&lfn=' . urlencode(LFN); -if (HTT != 'mdp_' . strtolower(EID_TYPE)) $urlp .= '&lfn=' . urlencode(HTT); -if (WHF != '0') $urlp .= '&whf=' . urlencode(WHF); -if (RNG != '*') $urlp .= '&rng=' . urlencode(RNG); - -// name of the language file that needs to be included -$language_file = LFN; -require('../inc/global.inc.php'); -$nameTools = get_lang('Tool'); - -require(api_get_path(SYS_CODE_PATH) . 'metadata/md_funcs.php'); - -($nameTools && get_lang('Sorry')) - or give_up('Language file ' . LFN . " doesn't define 'Tool' and 'Sorry'"); - -$_course = api_get_course_info(); isset($_course) or give_up(get_lang('Sorry')); - -require(api_get_path(LIBRARY_PATH) . 'xmd.lib.php'); -require(api_get_path(LIBRARY_PATH) . 'xht.lib.php'); - -require(api_get_path(SYS_CODE_PATH) . 'metadata/md_' . strtolower(EID_TYPE) . '.php'); -$mdObj = new mdobject($_course, EID_ID); - -define('DR', $_SERVER['DOCUMENT_ROOT']); -define('SELF', api_get_self()); -define('DIRECTORY', DR . $self = substr(SELF, 0, strrpos(SELF, '/'))); -if (!file_exists(DIRECTORY)) give_up('No such directory: ' . DIRECTORY); - - -// TEMPLATES FILE -------------------------------------------------------------> - -$topdir = strtolower(realpath(DR)); // to stop search for .htt file - -if (strpos(strtolower(realpath(DIRECTORY)), $topdir) !== 0) - give_up('Invalid directory: ' . DIRECTORY); - -chdir(DIRECTORY); - -for ($i = 0; $i < 10; $i++) - if(!file_exists(HTT . '.htt')) - if (strtolower(realpath(getcwd())) == $topdir) {break;} - else chdir('..'); - - -// XML and DB STUFF -----------------------------------------------------------> - -$is_allowed_to_edit = isset($_user['user_id']) && $is_courseMember && api_is_allowed_to_edit(); - -$mdStore = new mdstore($is_allowed_to_edit); - -if (($mdt_rec = $mdStore->mds_get(EID)) === FALSE) // no record, default XML - $mdt = $mdObj->mdo_generate_default_xml_metadata(); -else $mdt = $mdt_rec; - -$xhtxmldoc = new xmddoc(explode("\n", $mdt)); - -(!$xhtxmldoc->error) or give_up($xhtxmldoc->error); - -if (SID == $id_range_first && - ($prv = $xhtxmldoc->xmd_select_single_element('previous')) != -1) - $xhtxmldoc->xmd_remove_element($prv); - -if (SID == $id_range_last && - ($nxt = $xhtxmldoc->xmd_select_single_element('next')) != -1) - $xhtxmldoc->xmd_remove_element($nxt); - -$before_first = $id_range_first ? TRUE : FALSE; $after_last = FALSE; - -foreach ($xhtxmldoc->xmd_select_elements('child') as $chEl) -{ - $chId = $xhtxmldoc->attributes[$chEl]['identifier']; // no get_att yet... - - if ($after_last || - ($before_first = $before_first && $chId != $id_range_first)) - { - $xhtxmldoc->xmd_remove_element($chEl); continue; - } - - if (($mdt_rec = $mdStore->mds_get(BID . '.' . $chId)) === FALSE) - $mdt = $mdObj->mdo_generate_default_xml_metadata(); - else $mdt = $mdt_rec; - - $xhtxmldocchild = new xmddoc(explode("\n", $mdt)); - - (!$xhtxmldocchild->error) or give_up($chId . ': ' . $xhtxmldocchild->error); - - // make stuff below a parameter? copy some already in importmanifest? - $xhtxmldoc->xmd_copy_foreign_child($xhtxmldocchild, - $xhtxmldocchild->xmd_select_single_element('title'), $chEl); - $xhtxmldoc->xmd_copy_foreign_child($xhtxmldocchild, - $xhtxmldocchild->xmd_select_single_element('resource'), $chEl); - - $after_last = $after_last || $chId == $id_range_last; -} - -$xhtDoc = define_htt(HTT . '.htt', $urlp, $_course['path']); -$xhtDoc->xht_xmldoc = $xhtxmldoc; - -$xhtDoc->xht_param['mdt'] = $xhtxmldoc->xmd_xml(); - - -// GENERATE OUTPUT ------------------------------------------------------------> - -foreach (explode("\n", $xhtDoc->htt_array['HTTP']) as $httpXtra) - if ($httpXtra) $httpHeadXtra[] = $httpXtra; - -$xhtDoc->xht_get_lang = 'get_lang'; - -function resource_for($e) {return $e;} // dummy, '=/' not used here -$xhtDoc->xht_resource = 'resource_for'; - -$htmlHeadXtra[] = $xhtDoc->xht_fill_template('HEAD'); - -// $mdObj->mdo_add_breadcrump_nav(); // see 'md_' . EID_TYPE . '.php' -$noPHP_SELF = TRUE; // in breadcrumps - -if (WHF != '0') Display::display_header($nameTools); -else -{ - header('Content-Type: text/html; charset='. $charset); $document_language = 'en'; - if ( isset($httpHeadXtra) && $httpHeadXtra ) - { - foreach($httpHeadXtra as $thisHttpHead) - { - header($thisHttpHead); - } - } - ?> - - - - Scorm package - - - - - - - - -
    - xht_dbgn = DBG; // for template debug info, set to e.g. 10000 -if (($ti = $xhtDoc->xht_param['traceinfo'])) $xhtDoc->xht_param['traceinfo'] = - '
    Trace information
    ' . htmlspecialchars($ti, ENT_QUOTES, $charset); - -echo $xhtDoc->xht_fill_template('METADATA'), "\n"; - -if ($xhtDoc->xht_dbgn) echo $xhtDoc->xht_dbgo; - -if (WHF != '0') -{ - Display::display_footer(); - exit; -} - -?> -
     
    -
    - - diff --git a/main/metadata/search.php b/main/metadata/search.php deleted file mode 100755 index c8416eb1f6..0000000000 --- a/main/metadata/search.php +++ /dev/null @@ -1,149 +0,0 @@ - -require("md_funcs.php"); -getpar('TYPE', 'e.g. Mix', 'Mix'); // note: only 'Mix' is currently working -require('md_' . strtolower(TYPE) . '.php'); -getpar('LFN', 'LanguageFileName', 'md_' . strtolower(TYPE)); -getpar('HTT', 'HTML Template Text filename', 'mds_' . strtolower(TYPE)); -getpar('DBG', 'Debug number', '0'); // set to e.g. 10000 for debuginfo -$urlp = '?type='. urlencode(TYPE); -if (LFN != 'md_' . strtolower(TYPE)) $urlp .= '&lfn=' . urlencode(LFN); -if (HTT != 'mds_' . strtolower(TYPE)) $urlp .= '&htt=' . urlencode(HTT); -if (DBG) $urlp .= '&dbg=' . urlencode(DBG); - -// name of the language file that needs to be included -$language_file = LFN; require("../inc/global.inc.php"); -$this_section=SECTION_COURSES; - -$nameTools = get_lang('Tool'); - -($nameTools && get_lang('Sorry')) - or give_up('Language file ' . LFN . " doesn't define 'Tool' and 'Sorry'"); - -$_course = api_get_course_info(); isset($_course) or give_up(get_lang('Sorry')); - -require(api_get_path(LIBRARY_PATH) . 'xmd.lib.php'); -require(api_get_path(LIBRARY_PATH) . 'xht.lib.php'); - -$xhtDoc = define_htt(HTT . '.htt', $urlp, $_course['path']); - -$xhtDoc->xht_param['type'] = TYPE; - -$xhtDoc->xht_param['index'] = - str_replace('/search.php', '/index.php', api_get_self()); - - -// XML and DB STUFF -----------------------------------------------------------> - -$mdStore = new mdstore(FALSE); // no create DB table from search - -$xhtDoc->xht_get_lang = 'get_lang'; $xhtDoc->xht_xmldoc = new xmddoc(''); -if ($xhtDoc->xht_xmldoc->error) give_up($xhtDoc->xht_xmldoc->error); - -($mdt = $xhtDoc->xht_fill_template('DEFAULT'.TYPE)) - or give_up('No template DEFAULT' . TYPE); - -$xhtDoc->xht_xmldoc = new xmddoc(explode("\n", $mdt)); -if ($xhtDoc->xht_xmldoc->error) give_up($xhtDoc->xht_xmldoc->error); - -$xmlDoc = new xmddoc(''); if ($xmlDoc->error) give_up($xmlDoc->error); - -if (isset($_POST['mdsc'])) // Search criteria -{ - $mdsc = str_replace("\r", "\n", str_replace("\r\n", "\n", - get_magic_quotes_gpc() ? stripslashes($_POST['mdsc']) : $_POST['mdsc'])); - - foreach (explode("\n", $mdsc) as $word) if (($word = trim($word))) - { - $words .= ", " . $word; - - $where .= " AND indexabletext " . ($word{0} != '-' ? - ("LIKE '%".addslashes($word)."%'") : - ("NOT LIKE '%".addslashes(substr($word, 1))."%'")); - } - - if ($where) - { - $whereclause = substr($where, 5); // remove first " AND " - - $xhtDoc->xht_xmldoc->xmd_add_text_element('query', $whereclause); - $xhtDoc->xht_param['traceinfo'] = substr($words, 2); - - $result = $mdStore->mds_get_many('eid,mdxmltext', $whereclause); - - while (($myrow = @Database::fetch_array($result))) - { - // not quite a real manifest, but very much like one... - - $eid = $myrow['eid']; $xmlDoc = new xmddoc($myrow['mdxmltext']); - if ($xmlDoc->error) give_up('Entry '.$eid . ': ' . $xmlDoc->error); - - $mdObj = new mdobject($_course, $eid); // md_mix.php - - $xhtDoc->xht_xmldoc->xmd_copy_foreign_child($xmlDoc); - $newItem = $xhtDoc->xht_xmldoc-> - xmd_select_single_element('item[-1]'); - $xhtDoc->xht_xmldoc->xmd_set_attribute($newItem, 'eid', $eid); - $xhtDoc->xht_xmldoc->xmd_set_attribute($newItem, 'url', - $mdObj->mdo_url); - - if ($mdObj->mdo_type == 'Scorm') - $xhtDoc->xht_xmldoc->xmd_set_attribute($newItem, 'brl', - $mdObj->mdo_base_url); - } - } -} - - -function check_is_thumb($p) // escape function, see mds_mix.htt -{ - global $xhtDoc; if ($p !== FALSE) return ''; // should not happen - - if (!ereg('^pptsl[0-9]+_t\.jpg$', $xhtDoc->xht_param['thumb'])) - $xhtDoc->xht_param['thumb'] = ''; - - return ''; -} - - -// GENERATE OUTPUT ------------------------------------------------------------> - -foreach (explode("\n", $xhtDoc->htt_array['HTTP']) as $httpXtra) - if ($httpXtra) $httpHeadXtra[] = $httpXtra; - -$xhtDoc->xht_get_lang = 'get_lang'; - -function resource_for($e) {return $e;} // dummy, '=/' not used here -$xhtDoc->xht_resource = 'resource_for'; - -$xhtDoc->xht_param['kwdswere_string'] = $_POST['kwdswere_string']; -$htmlHeadXtra[] = $xhtDoc->xht_fill_template('HEAD'); - -// $noPHP_SELF = TRUE; // in breadcrumps - -Display::display_header($nameTools); - -$xhtDoc->xht_dbgn = DBG; // for template debug info, set to e.g. 10000 -if (($ti = $xhtDoc->xht_param['traceinfo'])) $xhtDoc->xht_param['traceinfo'] = - '' . get_lang('Search') . ': ' . htmlspecialchars($ti, ENT_QUOTES, $charset); - -echo $xhtDoc->xht_fill_template('MDSEARCH'), "\n"; - -if ($xhtDoc->xht_dbgn) echo $xhtDoc->xht_dbgo; - -Display::display_footer(); -?> diff --git a/main/metadata/statistics.php b/main/metadata/statistics.php deleted file mode 100755 index f11b13f450..0000000000 --- a/main/metadata/statistics.php +++ /dev/null @@ -1,133 +0,0 @@ - - -require('md_funcs.php'); - -define('EID_TYPE', 'Mix'); -require('md_' . strtolower(EID_TYPE) . '.php'); - -include('../inc/global.inc.php'); -$this_section=SECTION_COURSES; - -$nameTools = get_lang('Tool'); - -($nameTools && get_lang('Sorry')) or give_up( - 'Language file ' . $language_file . " doesn't define 'Tool' and 'Sorry'"); - -$_course = api_get_course_info(); isset($_course) or give_up(get_lang('Sorry')); - -$is_allowed_to_edit = isset($_user['user_id']) && $is_courseMember && api_is_allowed_to_edit(); -if (!$is_allowed_to_edit) give_up(get_lang('Denied')); - -$mdStore = new mdstore(FALSE); // no create from statistics - -require(api_get_path(LIBRARY_PATH) . 'xmd.lib.php'); -require(api_get_path(LIBRARY_PATH) . 'xht.lib.php'); - -$htmldecode = array_flip(get_html_translation_table(HTML_SPECIALCHARS)); - - -// STATISTICS -----------------------------------------------------------------> - -$noPHP_SELF = TRUE; // in breadcrumps -Display::display_header($nameTools); - -echo '

    ', get_lang('Statistics'), '

    ', "\n"; - -$ckw = $_course['path'] . '/CourseKwds.js'; -define('KEYWORDS_CACHE', get_course_path() . $ckw); - -if (!file_exists(KEYWORDS_CACHE)) -{ - echo get_lang('NoKeywords'); - Display::display_footer(); - exit(); -} - -if (!($myFile = @fopen(KEYWORDS_CACHE, 'r'))) -{ - echo get_lang('KwCacheProblem'); - Display::display_footer(); - exit(); -} - -$kwds = array(); $kwcnt = array(); $kwrefs = array(); - -while (($kwline = fgets($myFile))) -{ - if (ereg('�>(.+)<�', $kwline, $regs) || ereg('">(.+)<�', $kwline, $regs)) - foreach (explode(',', $regs[1]) as $kw) - if (!in_array($kw = strtr(trim($kw), $htmldecode), $kwds)) - $kwds []= $kw; -} -fclose($myFile); - -$result = $mdStore->mds_get_many('eid,mdxmltext', '1 = 1'); -echo get_lang('TotalMDEs'), Database::num_rows($result), "
    \n"; - -echo count($kwds), ' ', get_lang('CourseKwds'), '
    ', "\n"; - -while ($row = Database::fetch_array($result)) -{ - $eid = $row['eid']; $curr = ''; $xmltext = $row['mdxmltext']; $offset = 0; - - if (substr($eid, 0, 6) == 'Scorm.') - if (($dotpos = strpos($eid, '.', 6)) && $dotpos + 1 < strlen($eid)) - $curr = substr($eid, 0, $dotpos); - - while (($start = strpos($xmltext, '', $offset))) - if (($start = strpos($xmltext, '">', $start + 9))) - { - if (($stop = strpos($xmltext, ' $start) - { - $kw = strtr(substr($xmltext, $start, $stop-$start), $htmldecode); - if (!in_array($kw, $kwds)) - { - if (!in_array($kw = '!' . $kw, $kwds)) $kwds []= $kw; - $kwrefs[$kw] .= ' ' . ($curr ? - (strpos($kwrefs[$kw], $curr) ? - substr($eid, $dotpos+1) : $eid) : $eid); - } - $kwcnt[$kw] ++; // = $kwcnt[$kw] ? $kwcnt[$kw] + 1 : 1; - $offset = $stop + 19; - } - else $offset = $start + 2; - // lecture - } - else $offset = $start + 9; - - // xmd would be nicer but this is faster... -} - -echo count($kwds), ' ', get_lang('KwdsInMD'), '
    '; sort($kwds); - -$total = 0; foreach ($kwcnt as $kw => $cnt) $total += $cnt; -echo $total, ' ', get_lang('KwdRefs'), "\n"; - -echo '

    ', get_lang('NonCourseKwds'), '

    ', "\n"; - -foreach ($kwds as $kw) - if ($kw{0} == '!') - echo '', htmlspecialchars(api_substr($kw, 1), ENT_QUOTES, $charset), ': ', $kwcnt[$kw], - ': ', htmlspecialchars($kwrefs[$kw], ENT_QUOTES, $charset), "; \n"; - else break; - -echo '

    ', get_lang('KwdsUse'), '

    ', "\n"; - -foreach ($kwds as $kw) - if ($kw{0} != '!') - if (!$kwcnt[$kw]) - echo '', htmlspecialchars($kw, ENT_QUOTES, $charset), "; \n"; - else echo htmlspecialchars($kw, ENT_QUOTES, $charset), ': ', $kwcnt[$kw], "; \n"; - -Display::display_footer(); -?> diff --git a/main/metadata/update_indexabletext.php b/main/metadata/update_indexabletext.php deleted file mode 100755 index 0a90243757..0000000000 --- a/main/metadata/update_indexabletext.php +++ /dev/null @@ -1,67 +0,0 @@ - - -require('md_funcs.php'); - -getpar('EID_TYPE', 'Entry Type'); // e.g. 'Document' or 'Scorm' -define('TPLEN', strlen(EID_TYPE) + 1); - -require('md_' . strtolower(EID_TYPE) . '.php'); - -include('../inc/global.inc.php'); -$this_section=SECTION_COURSES; - -$nameTools = get_lang('Tool'); - -($nameTools && get_lang('Sorry')) or give_up( - 'Language file ' . $language_file . " doesn't define 'Tool' and 'Sorry'"); - -$_course = api_get_course_info(); isset($_course) or give_up(get_lang('Sorry')); - -$is_allowed_to_edit = isset($_user['user_id']) && $is_courseMember && api_is_allowed_to_edit(); -if (!$is_allowed_to_edit) give_up(get_lang('Denied')); - -$mdStore = new mdstore($is_allowed_to_edit); // create table if needed -$mdObj = new mdobject($_course, 0); - -require(api_get_path(LIBRARY_PATH) . 'xmd.lib.php'); -require(api_get_path(LIBRARY_PATH) . 'xht.lib.php'); - -$xhtDoc = $mdObj->mdo_define_htt(); - -$mdObj->mdo_add_breadcrump_nav(); // see 'md_' . EID_TYPE . '.php' -Display::display_header($nameTools); - -// OPERATIONS -----------------------------------------------------------------> - -echo '

    ', htmlspecialchars(EID_TYPE, ENT_QUOTES, $charset), '

    ', "\n"; - -$result = $mdStore->mds_get_many('eid,mdxmltext', "eid LIKE '" . EID_TYPE . ".%'"); -echo get_lang('TotalMDEs'), $total = Database::num_rows($result), "

    \n"; - -if ($total > 100) set_time_limit((int) ($total / 10)); - -while ($row = Database::fetch_array($result)) -{ - $eid = $row['eid']; $xmltext = $row['mdxmltext']; - $xhtDoc->xht_xmldoc = new xmddoc(explode("\n", $xmltext)); - - $mdStore->mds_put($eid, - $xhtDoc->xht_fill_template('INDEXABLETEXT'), 'indexabletext'); - - echo htmlspecialchars($eid, ENT_QUOTES, $charset), ' '; -} - -echo '
    ', htmlspecialchars(EID_TYPE, ENT_QUOTES, $charset), '
    ', "\n"; - -Display::display_footer(); -?> diff --git a/main/newscorm/learnpath_functions.inc.php b/main/newscorm/learnpath_functions.inc.php index 2d522927f6..f5bb2c9f07 100755 --- a/main/newscorm/learnpath_functions.inc.php +++ b/main/newscorm/learnpath_functions.inc.php @@ -1891,177 +1891,6 @@ function xmltagwrite($tagname, $which, $data, $linebreak = 'yes') { return $tag; } -/** - * This function writes the imsmanifest.xml and exports the chapter names - * @param array Array containing filenames - * @param integer Learnpath_id - * @return void - */ -function createimsmanifest($circle1_files, $learnpath_id) { - global $_course, $LPname, $expdir, $LPnamesafe; - //$tbl_learnpath_main, $tbl_learnpath_chapter, $tbl_learnpath_item, - $tbl_learnpath_main = Database :: get_course_table(TABLE_LEARNPATH_MAIN); - $tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM); - $tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER); - - include_once '../metadata/md_funcs.php'; // RH: export metadata - - // Header - // Charset should be dependent on content. - $header = ''."\n\n"; - - $org .= xmltagwrite('metadata', 'open'); - $org .= ' '.xmltagwrite('schema', 'full', 'ADL SCORM'); - $org .= ' '.xmltagwrite('schemaversion', 'full', '1.2'); - $org .= xmltagwrite('metadata', 'close'); - - $defaultorgname = 'default_org'; - - $attributes[0][0] = 'default'; - $attributes[1][0] = $defaultorgname; - $org .= xmltagwrite('organizations', 'open', $attributes); - - $attributes[0][0] = 'identifier'; - $attributes[1][0] = $defaultorgname; - $org .= ' '.xmltagwrite('organization', 'open', $attributes); - - $org .= ' '.xmltagwrite('title', 'full', $LPname); - - // Items list. - $i = 0; - $course_id = api_get_course_int_id(); - - $previous_item_id = '00'; - while ($circle1_files[0][$i]) { - // Check whether we are in the border of two chapters. - //if (!$desc=strpos($circle1_files[2][$i],'scription')) { // This is needed if the descriptions are exported to file. - - $sql = "SELECT * FROM $tbl_learnpath_item WHERE c_id = $course_id AND (id=".$circle1_files[2][$i].")"; - $result = Database::query($sql); - $row = Database::fetch_array($result); - $parent_item_id = $row['parent_item_id']; - - if ($parent_item_id != $previous_item_id) { - // We create the item tag for the chapter (without indifierref). - $sql2 = "SELECT * FROM $tbl_learnpath_chapter WHERE c_id = $course_id AND (id=".$parent_item_id.")"; - $result2 = Database::query($sql2); - $row2 = Database::fetch_array($result2); - $chapter_name = $row2['chapter_name']; - - $attributes = ''; - $attributes[0][] = 'identifier'; - $attributes[1][] = 'chapter_'.$row2['id']; - $attributes[0][] = 'isvisible'; - $attributes[1][] = '1'; - if ($previous_item_id != '00') { - $org .= ' '.xmltagwrite('item', 'close'); - } - - $org .= ' '.xmltagwrite('item', 'open', $attributes); - $org .= ' '.xmltagwrite('title', 'full', $chapter_name); - - if ($row2['chapter_description'] != '') { - // Chapter description. - $attributes = ''; - $attributes[0][] = 'identifier'; - $attributes[1][] = 'chapter_'.$row2['id'].'_desc'; - $attributes[0][] = 'isvisible'; - $attributes[1][] = '1'; - $org .= ' '.xmltagwrite('item', 'open', $attributes); - $org .= ' '.xmltagwrite('title', 'full', ' '.$row2['chapter_description']); - $org .= ' '.xmltagwrite('item', 'close'); - } - } - $previous_item_id = $parent_item_id; - //} - - $attributes = ''; // Item output. - $attributes[0][] = 'identifier'; - $attributes[1][] = 'item_'.$circle1_files[2][$i]; - $attributes[0][] = 'identifierref'; - $attributes[1][] = 'item_ref_'.$circle1_files[2][$i]; - $attributes[0][] = 'isvisible'; - $attributes[1][] = '1'; - $org .= ' '.xmltagwrite('item', 'open', $attributes); - $org .= ' '.xmltagwrite('title', 'full', $circle1_files[1][$i]); - - if ($row['prereq_id'] != '') { - // Item prerequisites. - $attributes = ''; - $attributes[0][] = 'type'; - $attributes[1][] = 'aicc_script'; - $org .= ' '.xmltagwrite('adlcp:prerequisites', 'open', $attributes, 'no_linebreak'); - if ($row['prereq_type'] == 'i') { - $org .= 'item_'.$row['prereq_id']; - } - if ($row['prereq_type'] == 'c') { - $org .= 'chapter_'.$row['prereq_id']; - } - $org .= xmltagwrite('adlcp:prerequisites', 'close', $attributes); - } - - if ($row['description'] != '') { - // Item description. - $attributes = ''; - $attributes[0][] = 'identifier'; - $attributes[1][] = 'item_'.$circle1_files[2][$i].'_desc'; - $attributes[0][] = 'isvisible'; - $attributes[1][] = '1'; - $org .= ' '.xmltagwrite('item', 'open', $attributes); - $org .= ' '.xmltagwrite('title', 'full', ' '.$row['description']); - $org .= ' '.xmltagwrite('item', 'close'); - } - - $mds = new mdstore(true); // RH: export metadata; if no table, create it - if (($mdt = $mds->mds_get($row['item_type'].'.'.$row['item_id']))) - if (($mdo = api_strpos($mdt, '')) && ($mdc = api_strpos($mdt, ''))) - $org .= ' '.api_substr($mdt, $mdo, $mdc - $mdo + 11)."\n"; - - $org .= ' '.xmltagwrite('item', 'close'); - $i ++; - } - - if ($circle1_files) { - $org .= ' '.xmltagwrite('item', 'close'); - } // Not needed in case of a blank path. - $org .= ' '.xmltagwrite('organization', 'close'); - $org .= xmltagwrite('organizations', 'close'); - $org .= xmltagwrite('resources', 'open'); - - // Resources list. - $i = 0; - while ($circle1_files[0][$i]) { - $attributes = ''; - $attributes[0][] = 'identifier'; - $attributes[1][] = 'item_ref_'.$circle1_files[2][$i]; - $attributes[0][] = 'type'; - $attributes[1][] = 'webcontent'; - $attributes[0][] = 'adlcp:scormtype'; - $attributes[1][] = 'sco'; - $attributes[0][] = 'href'; - $attributes[1][] = $circle1_files[0][$i]; - $org .= ' '.xmltagwrite('resource', 'open', $attributes); - - $org .= ' '.xmltagwrite('metadata', 'open'); - $org .= ' '.xmltagwrite('schema', 'full', 'ADL SCORM'); - $org .= ' '.xmltagwrite('schemaversion', 'full', '1.2'); - $org .= ' '.xmltagwrite('metadata', 'close'); - - $attributes = ''; - $attributes[0][] = 'href'; - $attributes[1][] = $circle1_files[0][$i]; - $org .= ' '.xmltagwrite('file', 'open', $attributes); - - $org .= ' '.xmltagwrite('resource', 'close'); - $i ++; - } - - $org .= xmltagwrite('resources', 'close'); - $org .= xmltagwrite('manifest', 'close'); - $manifest = $header.$org; - - exporttofile('imsmanifest.xml', 'Manifest file', '0', $manifest); -} /** * Gets the tags of the file given as parameter diff --git a/main/newscorm/lp_edit.php b/main/newscorm/lp_edit.php index 1c48a591e6..78e42c5fff 100755 --- a/main/newscorm/lp_edit.php +++ b/main/newscorm/lp_edit.php @@ -63,22 +63,6 @@ $form->addElement('text', 'lp_name', api_ucfirst(get_lang('LearnpathTitle')), ar $form->applyFilter('lp_name', 'html_filter'); $form->addRule('lp_name', get_lang('ThisFieldIsRequired'), 'required'); -// Metadata -//$clean_scorm_id=Security::remove_XSS($_GET['lp_id']); -//$metadata_link = ''.get_lang('AddMetadata').''; -//$form->addElement('static', null, get_lang('Metadata'), $metadata_link); - -// Encoding -/* // Chamilo 1.8.8: Deprecated code. -$encoding_select = $form->addElement('select', 'lp_encoding', get_lang('Charset')); -$encodings = array('UTF-8','ISO-8859-1','ISO-8859-15','cp1251','cp1252','KOI8-R','BIG5','GB2312','Shift_JIS','EUC-JP'); -foreach ($encodings as $encoding) { - if (api_equal_encodings($encoding, $_SESSION['oLP']->encoding)) { - $s_selected_encoding = $encoding; - } - $encoding_select->addOption($encoding,$encoding); -} -*/ $form->addElement('hidden', 'lp_encoding'); // Origin From 6d3278cceb485e05d3dc5a1a6b3bf561aa849aa7 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 09:31:22 +0200 Subject: [PATCH 022/159] Remove unused class. --- main/inc/lib/session_handler.class.php | 155 ------------------------- 1 file changed, 155 deletions(-) delete mode 100755 main/inc/lib/session_handler.class.php diff --git a/main/inc/lib/session_handler.class.php b/main/inc/lib/session_handler.class.php deleted file mode 100755 index 6035caf6a3..0000000000 --- a/main/inc/lib/session_handler.class.php +++ /dev/null @@ -1,155 +0,0 @@ -lifetime = 60; // 60 minutes - - $this->connection = array( - 'server' => $_configuration['db_host'], - 'login' => $_configuration['db_user'], - 'password' => $_configuration['db_password'], - 'base' => $_configuration['main_database'] - ); - - $this->connection_handler = false; - } - - /** - * @deprecated don't use - * @return bool - */ - public function sqlConnect() { - - if (!$this->connection_handler) { - $this->connection_handler = @mysql_connect($this->connection['server'], $this->connection['login'], $this->connection['password'], true); - - // The system has not been designed to use special SQL modes that were introduced since MySQL 5 - @mysql_query("set session sql_mode='';", $this->connection_handler); - - @mysql_select_db($this->connection['base'], $this->connection_handler); - - // Initialization of the database connection encoding to be used. - // The internationalization library should be already initialized. - @mysql_query("SET SESSION character_set_server='utf8';", $this->connection_handler); - @mysql_query("SET SESSION collation_server='utf8_general_ci';", $this->connection_handler); - $system_encoding = api_get_system_encoding(); - if (api_is_utf8($system_encoding)) { - // 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. - @mysql_query("SET NAMES 'utf8';", $this->connection_handler); - } else { - @mysql_query("SET CHARACTER SET '" . Database::to_db_encoding($system_encoding) . "';", $this->connection_handler); - } - } - - return $this->connection_handler ? true : false; - } - - public function sqlClose() { - - if ($this->connection_handler) { - mysql_close($this->connection_handler); - $this->connection_handler = false; - return true; - } - - return false; - } - - public function sqlQuery($query, $die_on_error = true) { - - $result = mysql_query($query, $this->connection_handler); - - if ($die_on_error && !$result) { - $this->sqlClose(); - return; - } - - return $result; - } - - public function open($path, $name) { - - $this->session_name = $name; - return true; - } - - public function close() { - return $this->garbage(0) ? true : false; - } - - public function read($sess_id) { - - if ($this->sqlConnect()) { - $result = $this->sqlQuery("SELECT session_value FROM ".$this->connection['base'].".php_session WHERE session_id='$sess_id'"); - - if ($row = mysql_fetch_assoc($result)) { - return $row['session_value']; - } - } - - return ''; - } - - public function write($sess_id, $sess_value) { - $time = time(); - - if ($this->sqlConnect()) { - - $result = $this->sqlQuery("INSERT INTO ".$this->connection['base'].".php_session(session_id,session_name,session_time,session_start,session_value) VALUES('$sess_id','".$this->session_name."','$time','$time','".addslashes($sess_value)."')", false); - - if (!$result) { - $this->sqlQuery("UPDATE ".$this->connection['base'].".php_session SET session_name='".$this->session_name."',session_time='$time',session_value='".addslashes($sess_value)."' WHERE session_id='$sess_id'"); - } - - return true; - } - - return false; - } - - public function destroy($sess_id) { - - if ($this->sqlConnect()) { - $this->sqlQuery("DELETE FROM ".$this->connection['base'].".php_session WHERE session_id='$sess_id'"); - return true; - } - - return false; - } - - public function garbage($lifetime) { - - if ($this->sqlConnect()) { - - $result = $this->sqlQuery("SELECT COUNT(session_id) FROM ".$this->connection['base'].".php_session"); - list($nbr_results) = Database::fetch_row($result); - - if ($nbr_results > 5000) { - $this->sqlQuery("DELETE FROM ".$this->connection['base'].".php_session WHERE session_time<'".strtotime('-'.$this->lifetime.' minutes')."'"); - } - - $this->sqlClose(); - - return true; - } - - return false; - } -} From 59350cbb49e0b81fd3c7a6c26cc9b3cfaffa8e9f Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 09:31:52 +0200 Subject: [PATCH 023/159] Comment code / Format code --- main/inc/lib/diagnoser.lib.php | 2 +- main/newscorm/scormMetadata.class.php | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/main/inc/lib/diagnoser.lib.php b/main/inc/lib/diagnoser.lib.php index b6cbbf16d1..c7915ac906 100755 --- a/main/inc/lib/diagnoser.lib.php +++ b/main/inc/lib/diagnoser.lib.php @@ -225,7 +225,7 @@ 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]', '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]', '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')); diff --git a/main/newscorm/scormMetadata.class.php b/main/newscorm/scormMetadata.class.php index 3309e86e7e..969f4ee454 100755 --- a/main/newscorm/scormMetadata.class.php +++ b/main/newscorm/scormMetadata.class.php @@ -27,11 +27,10 @@ class scormMetadata * @param mixed Depending on the type, can be the DB ID of the learnpath item or the pointer to the element in the imsmanifest.xml file * @return boolean True on success, false on failure */ - public function __construct($type = 'manifest', &$element) { + public function __construct($type = 'manifest', &$element) + { if (isset($element)) { - // Parsing using PHP5 DOMXML methods. - switch ($type) { case 'db': // TODO: Implement this way of metadata object creation. From 0ddc1e8caa7adf60388e973485ac6e1fac8a017e Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 10:07:24 +0200 Subject: [PATCH 024/159] Format code --- main/inc/lib/blog.lib.php | 311 ++++++++++++++++++++------------------ 1 file changed, 162 insertions(+), 149 deletions(-) diff --git a/main/inc/lib/blog.lib.php b/main/inc/lib/blog.lib.php index 5fd5d537c4..df876a778b 100755 --- a/main/inc/lib/blog.lib.php +++ b/main/inc/lib/blog.lib.php @@ -1,19 +1,15 @@ * @author Julio Montoya - Cleaning code - * - */ -/** - * Class - * @package chamilo.blogs */ class Blog { @@ -21,11 +17,12 @@ class Blog * Get the title of a blog * @author Toon Keppens * - * @param Integer $blog_id + * @param int $blog_id * * @return String Blog Title */ - public static function get_blog_title ($blog_id) { + public static function get_blog_title ($blog_id) + { $course_id = api_get_course_int_id(); if(is_numeric($blog_id)) { @@ -51,11 +48,12 @@ class Blog * * @return String Blog description */ - public static function get_blog_subtitle ($blog_id) { - // init + public static function get_blog_subtitle ($blog_id) + { $tbl_blogs = Database::get_course_table(TABLE_BLOGS); - $course_id = api_get_course_int_id(); - $sql = "SELECT blog_subtitle FROM $tbl_blogs WHERE c_id = $course_id AND blog_id ='".intval($blog_id)."'"; + $course_id = api_get_course_int_id(); + $sql = "SELECT blog_subtitle FROM $tbl_blogs + WHERE c_id = $course_id AND blog_id ='".intval($blog_id)."'"; $result = Database::query($sql); $blog = Database::fetch_array($result); return stripslashes($blog['blog_subtitle']); @@ -79,7 +77,8 @@ class Blog // Get blog members $sql = "SELECT user.user_id, user.firstname, user.lastname - FROM " . $tbl_blogs_rel_user . " blogs_rel_user INNER JOIN " . $tbl_users . " user ON blogs_rel_user.user_id = user.user_id + FROM " . $tbl_blogs_rel_user . " blogs_rel_user + INNER JOIN " . $tbl_users . " user ON blogs_rel_user.user_id = user.user_id WHERE blogs_rel_user.c_id = $course_id AND blogs_rel_user.blog_id = '" . (int)$blog_id."'"; $result = Database::query($sql); @@ -112,7 +111,8 @@ class Blog $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS); //verified if exist blog - $sql='SELECT COUNT(*) as count FROM '.$tbl_blogs.' WHERE c_id = '.$course_id.' AND blog_name="'.Database::escape_string($title).'" AND blog_subtitle="'.Database::escape_string($subtitle).'";'; + $sql = 'SELECT COUNT(*) as count FROM '.$tbl_blogs.' + WHERE c_id = '.$course_id.' AND blog_name="'.Database::escape_string($title).'" AND blog_subtitle="'.Database::escape_string($subtitle).'";'; $res=Database::query($sql); $info_count=Database::result($res,0,0); @@ -130,12 +130,12 @@ class Blog // Make first post. :) $sql = "INSERT INTO $tbl_blogs_posts (c_id, title, full_text, date_creation, blog_id, author_id ) - VALUES ($course_id, '".get_lang("Welcome")."', '" . get_lang('FirstPostText')."','".$current_date."', '".Database::escape_string((int)$this_blog_id)."', '".Database::escape_string((int)$_user['user_id'])."');"; + VALUES ($course_id, '".get_lang("Welcome")."', '" . get_lang('FirstPostText')."','".$current_date."', '".Database::escape_string((int)$this_blog_id)."', '".Database::escape_string((int)$_user['user_id'])."');"; Database::query($sql); // Put it on course homepage $sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, session_id) - VALUES ($course_id, '".Database::escape_string($title)."','blog/blog.php?blog_id=".(int)$this_blog_id."','blog.gif','1','0','pastillegris.gif',0,'$session_id')"; + VALUES ($course_id, '".Database::escape_string($title)."','blog/blog.php?blog_id=".(int)$this_blog_id."','blog.gif','1','0','pastillegris.gif',0,'$session_id')"; Database::query($sql); // Subscribe the teacher to this blog @@ -150,8 +150,9 @@ class Blog * @param String $title * @param Text $description */ - public static function edit_blog ($blog_id, $title, $subtitle) { - global $_user; + public static function edit_blog($blog_id, $title, $subtitle) + { + $_user = api_get_user_info(); // Table definitions $tbl_blogs = Database::get_course_table(TABLE_BLOGS); @@ -178,7 +179,8 @@ class Blog * @author Toon Keppens * @param Integer $blog_id */ - public static function delete_blog ($blog_id) { + public static function delete_blog ($blog_id) + { // Init $tbl_blogs = Database::get_course_table(TABLE_BLOGS); $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS); @@ -279,7 +281,6 @@ class Blog $sql = 'INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size, blog_id,comment_id) '. "VALUES ($course_id, '".Database::escape_string($file_name)."', '".$comment."', '".Database::escape_string($new_file_name)."' , '".$last_post_id."', '".intval($_FILES['user_upload']['size'])."', '".$blog_id."', '0' )"; Database::query($sql); - //Display::display_confirmation_message(get_lang('AttachmentUpload')); } } } @@ -296,7 +297,8 @@ class Blog * @param String $full_text * @param Integer $blog_id */ - public static function edit_post ($post_id, $title, $full_text, $blog_id) { + public static function edit_post ($post_id, $title, $full_text, $blog_id) + { // Init $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS); $course_id = api_get_course_int_id(); @@ -310,11 +312,11 @@ class Blog /** * Deletes an article and it's comments * @author Toon Keppens - * @param Integer $blog_id - * @param Integer $post_id + * @param int $blog_id + * @param int $post_id */ - public static function delete_post($blog_id, $post_id) { - // Init + public static function delete_post($blog_id, $post_id) + { $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS); $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS); $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING); @@ -322,15 +324,18 @@ class Blog $course_id = api_get_course_int_id(); // Delete ratings on this comment - $sql = "DELETE FROM $tbl_blogs_rating WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND item_id = '".(int)$post_id."' AND rating_type = 'post'"; + $sql = "DELETE FROM $tbl_blogs_rating + WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND item_id = '".(int)$post_id."' AND rating_type = 'post'"; Database::query($sql); // Delete the post - $sql = "DELETE FROM $tbl_blogs_posts WHERE c_id = $course_id AND post_id = '".(int)$post_id."'"; + $sql = "DELETE FROM $tbl_blogs_posts + WHERE c_id = $course_id AND post_id = '".(int)$post_id."'"; Database::query($sql); // Delete the comments - $sql = "DELETE FROM $tbl_blogs_comments WHERE c_id = $course_id AND post_id = '".(int)$post_id."' AND blog_id = '".(int)$blog_id."'"; + $sql = "DELETE FROM $tbl_blogs_comments + WHERE c_id = $course_id AND post_id = '".(int)$post_id."' AND blog_id = '".(int)$blog_id."'"; Database::query($sql); // Delete posts and attachments @@ -401,7 +406,6 @@ class Blog $sql='INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size,blog_id,comment_id) '. "VALUES ($course_id, '".Database::escape_string($file_name)."', '".$comment."', '".Database::escape_string($new_file_name)."' , '".$post_id."', '".$_FILES['user_upload']['size']."', '".$blog_id."', '".$last_id."' )"; Database::query($sql); - //$message.=' / '.get_lang('AttachmentUpload'); } } } @@ -570,7 +574,8 @@ class Blog * @param Integer $blog_id * @param Integer $task_id */ - public static function delete_task ($blog_id, $task_id) { + public static function delete_task($blog_id, $task_id) + { $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS); $course_id = api_get_course_int_id(); @@ -585,7 +590,7 @@ class Blog * @param Integer $blog_id * @param Integer $assignment_id */ - public static function delete_assigned_task ($blog_id, $task_id, $user_id) + public static function delete_assigned_task($blog_id, $task_id, $user_id) { $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER); $course_id = api_get_course_int_id(); @@ -601,8 +606,9 @@ class Blog * @author Toon Keppens * @return Returns an unsorted list (
      ) with the users' tasks */ - public static function get_personal_task_list () { - global $_user; + public static function get_personal_task_list() + { + $_user = api_get_user_info(); // Init $tbl_blogs = Database::get_course_table(TABLE_BLOGS); @@ -611,8 +617,9 @@ class Blog $course_id = api_get_course_int_id(); - if($_user['user_id']) { - $sql = "SELECT task_rel_user.*, task.title, blog.blog_name FROM $tbl_blogs_tasks_rel_user task_rel_user + if ($_user['user_id']) { + $sql = "SELECT task_rel_user.*, task.title, blog.blog_name + FROM $tbl_blogs_tasks_rel_user task_rel_user INNER JOIN $tbl_blogs_tasks task ON task_rel_user.task_id = task.task_id INNER JOIN $tbl_blogs blog ON task_rel_user.blog_id = blog.blog_id AND blog.blog_id = ".intval($_GET['blog_id'])." @@ -646,7 +653,6 @@ class Blog */ public static function change_blog_visibility($blog_id) { - // Init $tbl_blogs = Database::get_course_table(TABLE_BLOGS); $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST); $course_id = api_get_course_int_id(); @@ -662,16 +668,19 @@ class Blog if($visibility == 1) { // Change visibility state, remove from course home. - $sql = "UPDATE $tbl_blogs SET visibility = '0' WHERE c_id = $course_id AND blog_id ='".(int)$blog_id."' LIMIT 1"; + $sql = "UPDATE $tbl_blogs SET visibility = '0' + WHERE c_id = $course_id AND blog_id ='".(int)$blog_id."' LIMIT 1"; $result = Database::query($sql); - $sql = "DELETE FROM $tbl_tool WHERE c_id = $course_id AND name = '".Database::escape_string($title)."' LIMIT 1"; + $sql = "DELETE FROM $tbl_tool + WHERE c_id = $course_id AND name = '".Database::escape_string($title)."' LIMIT 1"; $result = Database::query($sql); } else { // Change visibility state, add to course home. - $sql = "UPDATE $tbl_blogs SET visibility = '1' WHERE c_id = $course_id AND blog_id ='".(int)$blog_id."' LIMIT 1"; + $sql = "UPDATE $tbl_blogs SET visibility = '1' + WHERE c_id = $course_id AND blog_id ='".(int)$blog_id."' LIMIT 1"; Database::query($sql); $sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, target ) @@ -680,14 +689,13 @@ class Blog } } - /** * Shows the posts of a blog * @author Toon Keppens * * @param Integer $blog_id */ - public static function display_blog_posts ($blog_id, $filter = '1=1', $max_number_of_posts = 20) { + public static function display_blog_posts($blog_id, $filter = '1=1', $max_number_of_posts = 20) { // Init $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS); $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS); @@ -710,7 +718,9 @@ class Blog $limit = 200; while($blog_post = Database::fetch_array($result)) { // Get number of comments - $sql = "SELECT COUNT(1) as number_of_comments FROM $tbl_blogs_comments WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND post_id = '" . (int)$blog_post['post_id']."'"; + $sql = "SELECT COUNT(1) as number_of_comments + FROM $tbl_blogs_comments + WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND post_id = '" . (int)$blog_post['post_id']."'"; $tmp = Database::query($sql); $blog_post_comments = Database::fetch_array($tmp); @@ -769,7 +779,8 @@ class Blog * @param Integer $blog_id * @param String $query_string */ - public static function display_search_results ($blog_id, $query_string) { + public static function display_search_results ($blog_id, $query_string) + { // Init $query_string = Database::escape_string($query_string); $query_string_parts = explode(' ',$query_string); @@ -790,7 +801,8 @@ class Blog * @param Integer $blog_id * @param String $query_string */ - public static function display_day_results ($blog_id, $query_string) { + public static function display_day_results($blog_id, $query_string) + { // Init $date_output = $query_string; $date = explode('-',$query_string); @@ -810,13 +822,14 @@ class Blog * @param Integer $blog_id * @param Integer $post_id */ - public static function display_post ($blog_id, $post_id) { + public static function display_post($blog_id, $post_id) + { // Init $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS); $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS); $tbl_users = Database::get_main_table(TABLE_MAIN_USER); - global $charset,$dateFormatLong; + global $charset, $dateFormatLong; $course_id = api_get_course_int_id(); @@ -833,7 +846,8 @@ class Blog $blog_post = Database::fetch_array($result); // Get number of comments - $sql = "SELECT COUNT(1) as number_of_comments FROM $tbl_blogs_comments WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND post_id = '".(int)$post_id."'"; + $sql = "SELECT COUNT(1) as number_of_comments FROM $tbl_blogs_comments + WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND post_id = '".(int)$post_id."'"; $result = Database::query($sql); $blog_post_comments = Database::fetch_array($result); @@ -882,8 +896,7 @@ class Blog echo ''; // Display comments if there are any - if($blog_post_comments['number_of_comments'] > 0) - { + if($blog_post_comments['number_of_comments'] > 0) { echo '
      '; echo '' . get_lang('Comments') . '
      '; Blog::get_threaded_comments(0, 0, $blog_id, $post_id, $task_id); @@ -908,8 +921,9 @@ class Blog * * @return Boolean success */ - public static function add_rating ($type, $blog_id, $item_id, $rating) { - global $_user; + public static function add_rating($type, $blog_id, $item_id, $rating) + { + $_user = api_get_user_info(); // Init $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING); @@ -946,12 +960,14 @@ class Blog * * @return array() */ - public static function display_rating ($type, $blog_id, $item_id) { + public static function display_rating ($type, $blog_id, $item_id) + { $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING); $course_id = api_get_course_int_id(); // Calculate rating - $sql = "SELECT AVG(rating) as rating FROM $tbl_blogs_rating WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND item_id = '".(int)$item_id."' AND rating_type = '".Database::escape_string($type)."' "; + $sql = "SELECT AVG(rating) as rating FROM $tbl_blogs_rating + WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND item_id = '".(int)$item_id."' AND rating_type = '".Database::escape_string($type)."' "; $result = Database::query($sql); $result = Database::fetch_array($result); return round($result['rating'], 2); @@ -967,8 +983,9 @@ class Blog * *@return String */ - public static function display_rating_form ($type, $blog_id, $post_id, $comment_id = NULL) { - global $_user; + public static function display_rating_form ($type, $blog_id, $post_id, $comment_id = NULL) + { + $_user = api_get_user_info(); $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING); $course_id = api_get_course_int_id(); @@ -1021,7 +1038,8 @@ class Blog * @param Integer $blog_id * @param Integer $post_id */ - public static function get_threaded_comments ($current = 0, $current_level = 0, $blog_id, $post_id, $task_id = 0) { + public static function get_threaded_comments ($current = 0, $current_level = 0, $blog_id, $post_id, $task_id = 0) + { // Init $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS); $tbl_users = Database::get_main_table(TABLE_MAIN_USER); @@ -1512,7 +1530,8 @@ class Blog * @author Toon Keppens * */ - public static function display_assign_task_form ($blog_id) { + public static function display_assign_task_form($blog_id) + { // Init $tbl_users = Database::get_main_table(TABLE_MAIN_USER); $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER); @@ -1532,8 +1551,7 @@ class Blog $result = Database::query($sql); $select_user_list = ''; - while($user = Database::fetch_array($result)) { - $username = api_htmlentities(sprintf(get_lang('LoginX'), $user['username']), ENT_QUOTES); - $select_user_list .= ''; + $options = array(); + while ($user = Database::fetch_array($result)) { + $username = api_htmlentities(sprintf(get_lang('LoginX'), $user['username']), ENT_QUOTES); + $options[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']); } - $select_user_list .= ''; - // Get tasks in this blog / make select list of it $sql = " @@ -1572,109 +1566,50 @@ class Blog WHERE c_id = $course_id AND blog_id = " . (int)$blog_id . " ORDER BY system_task, title"; $result = Database::query($sql); - $select_task_list = ''; - - // form - echo '
      '; - - // form title - echo ''.get_lang('AssignTask').''; - - // user - echo '
      - -
      - '.$select_user_list.' -
      -
      '; - - // task - echo '
      - -
      - '.$select_task_list.' -
      -
      '; - - // date - echo '
      - -
      '; - echo ' - - - - '; - echo '
      -
      '; - - // submit - echo '
      -
      -
      - - - -
      -
      '; + $form = new FormValidator( + 'assign_task', + 'post', + api_get_path( + WEB_CODE_PATH + ).'blog/blog.php?action=manage_tasks&blog_id='.$blog_id + ); + $form->addHeader(get_lang('AssignTask')); + $form->addSelect('task_user_id', get_lang('SelectUser'), $options); + $form->addSelect('task_task_id', get_lang('SelectTask'), $taskOptions); + $form->addDatePicker('task_day', get_lang('SelectTargetDate')); + $form->addHidden('action', ''); + $form->addButtonSave(get_lang('Ok')); + return $form; + } - echo ''; + /** + * Displays assign task form + * @author Toon Keppens + * + */ + public static function display_assign_task_form($blog_id) + { + $form = self::getTaskForm($blog_id); + $form->addHidden('assign_task_submit', 'true'); + $form->display(); echo '
      '; } - /** + /** * Displays assign task form * @author Toon Keppens * */ - public static function display_edit_assigned_task_form ($blog_id, $task_id, $user_id) { + public static function display_edit_assigned_task_form($blog_id, $task_id, $user_id) + { $tbl_users = Database::get_main_table(TABLE_MAIN_USER); $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER); $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS); @@ -1682,9 +1617,6 @@ class Blog $course_id = api_get_course_int_id(); - $year = date("Y"); - global $MonthsLong; - // Get assignd date; $sql = " SELECT target_date @@ -1696,116 +1628,20 @@ class Blog $result = Database::query($sql); $row = Database::fetch_assoc($result); - $old_date = $row['target_date']; - $date = explode('-', $row['target_date']); - - // Get users in this blog / make select list of it - $sql = " - SELECT user.user_id, user.firstname, user.lastname, user.username - FROM $tbl_users user - INNER JOIN $tbl_blogs_rel_user blogs_rel_user ON user.user_id = blogs_rel_user.user_id - WHERE blogs_rel_user.c_id = $course_id AND blogs_rel_user.blog_id = '".(int)$blog_id."'"; - $result = Database::query($sql); - - $select_user_list = ''; - - // Get tasks in this blog / make select list of it - $sql = " - SELECT - blog_id, - task_id, - title, - description, - color, - system_task - FROM " . $tbl_blogs_tasks . " - WHERE c_id = $course_id AND blog_id = " . (int)$blog_id . " - ORDER BY system_task, title"; - $result = Database::query($sql); - - $select_task_list = ''; - - // Display - echo '
      - - - - - - - - - - - - - - - - - - - - - - - - - - -
      ' . get_lang('AssignTask') . '

      ' . get_lang('SelectUser') . ':  ' . $select_user_list . '
      ' . get_lang('SelectTask') . ':  ' . $select_task_list . '
      ' . get_lang('SelectTargetDate') . ':   - - - - - - -
       
      -
      '; + $date = $row['target_date']; + + $defaults = [ + 'task_user_id' => $user_id, + 'task_task_id' => $task_id, + 'task_day' => $date + ]; + $form = self::getTaskForm($blog_id); + $form->addHidden('old_task_id', $task_id); + $form->addHidden('old_user_id', $user_id); + $form->addHidden('old_target_date', $date); + $form->addHidden('assign_task_edit_submit', 'true'); + $form->setDefaults($defaults); + $form->display(); } /** @@ -1816,9 +1652,8 @@ class Blog * @param Integer $task_id * @param Date $target_date */ - public static function assign_task ($blog_id, $user_id, $task_id, $target_date) + public static function assign_task($blog_id, $user_id, $task_id, $target_date) { - $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER); $course_id = api_get_course_int_id(); @@ -1831,10 +1666,10 @@ class Blog AND task_id = " . (int)$task_id . " "; - $result = @Database::query($sql); + $result = Database::query($sql); $row = Database::fetch_assoc($result); - if($row['number'] == 0) { + if ($row['number'] == 0) { $sql = " INSERT INTO " . $tbl_blogs_tasks_rel_user . " ( c_id, @@ -1850,7 +1685,7 @@ class Blog '" . Database::escape_string($target_date) . "' )"; - $result = @Database::query($sql); + $result = Database::query($sql); } } @@ -2039,7 +1874,7 @@ class Blog if(!in_array($user['user_id'],$blog_member_ids)) { $a_infosUser = UserManager :: get_user_info_by_id($user['user_id']); $row = array (); - $row[] = ''; + $row[] = ''; $username = api_htmlentities(sprintf(get_lang('LoginX'), $a_infosUser["username"]), ENT_QUOTES); if ($is_western_name_order) { $row[] = $a_infosUser["firstname"]; @@ -2129,7 +1964,7 @@ class Blog while($myrow = Database::fetch_array($sql_result)) { $row = array (); - $row[] = ''; + $row[] = ''; $username = api_htmlentities(sprintf(get_lang('LoginX'), $myrow["username"]), ENT_QUOTES); if ($is_western_name_order) { $row[] = $myrow["firstname"]; @@ -2161,7 +1996,7 @@ class Blog //Link to register users if($myrow["user_id"] != $_user['user_id']) { - $row[] = "" . get_lang('UnRegister').""; + $row[] = "" . get_lang('UnRegister').""; } else { $row[] = ''; } @@ -2318,38 +2153,34 @@ class Blog if( Database::num_rows($result) > 0) { while($blog_post = Database::fetch_array($result)) { // If the day of this post is not yet in the array, add it. - if(!in_array($blog_post['post_day'], $posts)) + if (!in_array($blog_post['post_day'], $posts)) $posts[] = $blog_post['post_day']; } } // Get tasks for this month - if($_user['user_id']) { + if ($_user['user_id']) { $sql = " SELECT task_rel_user.*, DAYOFMONTH(target_date) as task_day, task.title, blog.blog_name FROM $tbl_blogs_tasks_rel_user task_rel_user INNER JOIN $tbl_blogs_tasks task ON task_rel_user.task_id = task.task_id INNER JOIN $tbl_blogs blog ON task_rel_user.blog_id = blog.blog_id WHERE - task_rel_user.c_id = $course_id AND - task.c_id = $course_id AND - blog.c_id = $course_id AND - task_rel_user.user_id = '".(int)$_user['user_id']."' - AND MONTH(target_date) = '".(int)$month."' - AND YEAR(target_date) = '".(int)$year."' + task_rel_user.c_id = $course_id AND + task.c_id = $course_id AND + blog.c_id = $course_id AND + task_rel_user.user_id = '".(int)$_user['user_id']."' AND + MONTH(target_date) = '".(int)$month."' AND + YEAR(target_date) = '".(int)$year."' ORDER BY target_date ASC"; $result = Database::query($sql); - if (Database::num_rows($result) > 0) - { - while($mytask = Database::fetch_array($result)) - { - + if (Database::num_rows($result) > 0) { + while ($mytask = Database::fetch_array($result)) { $tasks[$mytask['task_day']][$mytask['task_id']]['task_id'] = $mytask['task_id']; $tasks[$mytask['task_day']][$mytask['task_id']]['title'] = $mytask['title']; $tasks[$mytask['task_day']][$mytask['task_id']]['blog_id'] = $mytask['blog_id']; $tasks[$mytask['task_day']][$mytask['task_id']]['blog_name'] = $mytask['blog_name']; $tasks[$mytask['task_day']][$mytask['task_id']]['day'] = $mytask['task_day']; - //echo '
    • '.stripslashes($mytask['title']) . '
    • '; } } } @@ -2358,38 +2189,34 @@ class Blog "\n", "«\n", "", $monthName, " ", $year, "\n", - "»\n", "\n"; + "»\n", ""; echo "\n"; for($ii = 1; $ii < 8; $ii ++) - echo "", $DaysShort[$ii % 7], "\n"; + echo "", $DaysShort[$ii % 7], ""; - echo "\n"; + echo ""; $curday = -1; $today = getdate(); - while($curday <= $numberofdays[$month]) - { - echo "\n"; - - for($ii = 0; $ii < 7; $ii ++) - { - if(($curday == -1) && ($ii == $startdayofweek)) + while ($curday <= $numberofdays[$month]) { + echo ""; + for ($ii = 0; $ii < 7; $ii ++) { + if (($curday == -1) && ($ii == $startdayofweek)) $curday = 1; - if(($curday > 0) && ($curday <= $numberofdays[$month])) { + if (($curday > 0) && ($curday <= $numberofdays[$month])) { $bgcolor = $ii < 5 ? $class="class=\"days_week\"" : $class="class=\"days_weekend\""; $dayheader = "$curday"; - if(($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) - { + if(($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) { $dayheader = "$curday"; $class = "class=\"days_today\""; } - echo "\t"; + echo ""; // If there are posts on this day, create a filter link. if(in_array($curday, $posts)) @@ -2397,30 +2224,24 @@ class Blog else echo $dayheader; - if (count($tasks) > 0) - { - if (is_array($tasks[$curday])) - { + if (count($tasks) > 0) { + if (isset($tasks[$curday]) && is_array($tasks[$curday])) { // Add tasks to calendar - foreach ($tasks[$curday] as $task) - { - echo 'Task'; + foreach ($tasks[$curday] as $task) { + echo ' + Task'; } } } - echo "\n"; - + echo ""; $curday ++; - } - else - echo " \n"; + } else + echo " "; } - - echo "\n"; + echo ""; } - - echo "\n"; + echo ""; } /** From 1dfc67f9890ee9aab12dd4b935f9035079dfa855 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 11:08:49 +0200 Subject: [PATCH 026/159] Add "addDatePicker" and "addDateTimePicker" function shortcuts --- .../lib/formvalidator/FormValidator.class.php | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/main/inc/lib/formvalidator/FormValidator.class.php b/main/inc/lib/formvalidator/FormValidator.class.php index 7beba82db0..12ef525d9d 100755 --- a/main/inc/lib/formvalidator/FormValidator.class.php +++ b/main/inc/lib/formvalidator/FormValidator.class.php @@ -225,6 +225,28 @@ EOT; } } + /** + * @param string $name + * @param string $label + * @param array $attributes + * @return mixed + */ + public function addDatePicker($name, $label, $attributes = []) + { + return $this->addElement('DatePicker', $name, $label, $attributes); + } + + /** + * @param string $name + * @param string $label + * @param array $attributes + * @return mixed + */ + public function addDateTimePicker($name, $label, $attributes = []) + { + return $this->addElement('DateTimePicker', $name, $label, $attributes); + } + /** * @param string $name * @param string $value From 608f9a6b60b7c4028af9fdb994bf207473e7e70e Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 11:09:12 +0200 Subject: [PATCH 027/159] Format code, remove require_once --- certificates/index.php | 6 ------ index.php | 1 - news_list.php | 5 +++-- user.php | 10 ++++------ whoisonline.php | 2 -- whoisonlinesession.php | 5 ----- 6 files changed, 7 insertions(+), 22 deletions(-) diff --git a/certificates/index.php b/certificates/index.php index a3989b50f6..d4440b293a 100755 --- a/certificates/index.php +++ b/certificates/index.php @@ -5,12 +5,7 @@ * @package chamilo.certificate */ -/** - * Initialization - */ - require_once '../main/inc/global.inc.php'; -require_once api_get_path(LIBRARY_PATH).'certificate.lib.php'; $action = isset($_GET['action']) ? $_GET['action'] : null; @@ -35,7 +30,6 @@ switch ($action) { $pageFormat = $pdfParams['orientation'] == 'landscape' ? 'A4-L' : 'A4'; $userInfo = api_get_user_info($certificate->user_id); - $pdfName = replace_dangerous_char(get_lang('Certificate') . ' ' . $userInfo['username']); $pdf = new PDF($pageFormat, $pdfParams['orientation'], $pdfParams); diff --git a/index.php b/index.php index 89dbfb9381..62781c6f74 100755 --- a/index.php +++ b/index.php @@ -13,7 +13,6 @@ define('CHAMILO_HOMEPAGE', true); $cidReset = true; require_once 'main/inc/global.inc.php'; -require_once api_get_path(LIBRARY_PATH).'userportal.lib.php'; require_once 'main/chat/chat_functions.lib.php'; // The section (for the tabs). diff --git a/news_list.php b/news_list.php index 44fa6fc848..498f2a050b 100755 --- a/news_list.php +++ b/news_list.php @@ -6,8 +6,9 @@ require_once 'main/inc/global.inc.php'; $tool_name = get_lang('SystemAnnouncements'); $actions = ''; -if (api_is_platform_admin()) { - $actions = ''.Display::return_icon('edit.png', get_lang('EditSystemAnnouncement'), array(), 32).''; +if (api_is_platform_admin()) { + $actions = ''. + Display::return_icon('edit.png', get_lang('EditSystemAnnouncement'), array(), 32).''; } if (api_is_anonymous()) { diff --git a/user.php b/user.php index a7d3ceb80a..82e6f3d033 100755 --- a/user.php +++ b/user.php @@ -4,17 +4,15 @@ * Clean URls for the Social Network * * The idea is to access to the user info more easily: - * http://campus.chamilo.org/admin instead of + * http://campus.chamilo.org/admin instead of * http://campus.chamilo.org/main/social/profile.php?1 - * To use this you should rename the htaccess to .htaccess and check your + * To use this you should rename the htaccess to .htaccess and check your * virtualhost configuration * * More improvements will come in next versions of Chamilo maybe in the 1.8.8 * @package chamilo.main */ -/** - * Variables definitions and inclusions - */ + $cidReset = true; require_once 'main/inc/global.inc.php'; @@ -43,4 +41,4 @@ if (!empty($array_keys)) { // we cant find your friend header('Location: whoisonline.php'); exit; -} \ No newline at end of file +} diff --git a/whoisonline.php b/whoisonline.php index dc845eec58..a6cffb3fbe 100755 --- a/whoisonline.php +++ b/whoisonline.php @@ -15,8 +15,6 @@ if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) { api_protect_course_script(true); } -require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php'; - $_SESSION['who_is_online_counter'] = 2; $htmlHeadXtra[] = api_get_js('jquery.endless-scroll.js'); diff --git a/whoisonlinesession.php b/whoisonlinesession.php index 26a83c5a3e..7ee4cd5cdf 100755 --- a/whoisonlinesession.php +++ b/whoisonlinesession.php @@ -144,9 +144,4 @@ Display::display_header(get_lang('UserOnlineListSession')); Date: Wed, 1 Apr 2015 11:24:54 +0200 Subject: [PATCH 028/159] Remove unused code. --- main/calendar/calendar.php | 123 ----------- main/calendar/tbl_change.js | 159 -------------- .../formvalidator/Element/calendar_popup.php | 156 -------------- .../formvalidator/Element/tbl_change.js.php | 198 ------------------ main/link/category_form.class.php | 75 ------- main/link/import_csv.class.php | 188 ----------------- main/link/resources/js/main.js | 105 ---------- main/notebook/index.php | 3 - main/notebook/resources/js/proxy.js | 40 ---- main/notebook/resources/js/ui.js | 104 --------- 10 files changed, 1151 deletions(-) delete mode 100755 main/calendar/calendar.php delete mode 100755 main/calendar/tbl_change.js delete mode 100755 main/inc/lib/formvalidator/Element/calendar_popup.php delete mode 100755 main/inc/lib/formvalidator/Element/tbl_change.js.php delete mode 100755 main/link/category_form.class.php delete mode 100755 main/link/import_csv.class.php delete mode 100755 main/link/resources/js/main.js delete mode 100755 main/notebook/resources/js/proxy.js delete mode 100755 main/notebook/resources/js/ui.js diff --git a/main/calendar/calendar.php b/main/calendar/calendar.php deleted file mode 100755 index dbaa8453c7..0000000000 --- a/main/calendar/calendar.php +++ /dev/null @@ -1,123 +0,0 @@ - - - - -Calendar - - - - - - - -
      -
      - - diff --git a/main/calendar/tbl_change.js b/main/calendar/tbl_change.js deleted file mode 100755 index 8104ea1790..0000000000 --- a/main/calendar/tbl_change.js +++ /dev/null @@ -1,159 +0,0 @@ -var day; -var month; -var year; -var hour; -var minute; -var second; -var clock_set = 0; - -/** - * Opens calendar window. - * - * @param string form name - * @param string field name - */ -function openCalendar(form, field) { - window.open("./calendar.php", "calendar", "width=260,height=250,status=no,toolbar=no"); - day = eval("document." + form + "." + field + "day.options["+ "document." + form + "." + field + "day.selectedIndex].value"); - month = eval("document." + form + "." + field + "month.options["+ "document." + form + "." + field + "month.selectedIndex].value"); - month = month-1; - year = eval("document." + form + "." + field + "year.options["+ "document." + form + "." + field + "year.selectedIndex].value"); - formName = form; - fieldName =field; -} - -/** - * Formats number to two digits. - * - * @param int number to format. - */ -function formatNum2(i, valtype) { - f = (i < 10 ? '0' : '') + i; - if (valtype && valtype != '') { - switch(valtype) { - case 'month': - f = (f > 12 ? 12 : f); - break; - - case 'day': - f = (f > 31 ? 31 : f); - break; - } - } - - return f; -} - -/** - * Formats number to four digits. - * - * @param int number to format. - */ -function formatNum4(i) { - return (i < 1000 ? i < 100 ? i < 10 ? '000' : '00' : '0' : '') + i; -} - -/** - * Initializes calendar window. - */ -function initCalendar() { - if (!year && !month && !day) { - day = window.opener.day; - month = window.opener.month; - year = window.opener.year; - if (isNaN(year) || isNaN(month) || isNaN(day) || day == 0) { - dt = new Date(); - year = dt.getFullYear(); - month = dt.getMonth(); - day = dt.getDate(); - } - } else { - /* Moving in calendar */ - if (month > 11) { - month = 0; - year++; - } - if (month < 0) { - month = 11; - year--; - } - } - - if (document.getElementById) { - cnt = document.getElementById("calendar_data"); - } else if (document.all) { - cnt = document.all["calendar_data"]; - } - - cnt.innerHTML = ""; - - str = "" - - //heading table - str += '
      '; - str += '« '; - str += month_names[month]; - str += ' »'; - str += ''; - str += '« '; - str += year; - str += ' »'; - str += '
      '; - - str += ''; - for (i = 0; i < 7; i++) { - str += ""; - } - str += ""; - - var firstDay = new Date(year, month, 1).getDay(); - var lastDay = new Date(year, month + 1, 0).getDate(); - - str += ""; - - dayInWeek = 0; - for (i = 0; i < firstDay; i++) { - str += ""; - dayInWeek++; - } - for (i = 1; i <= lastDay; i++) { - if (dayInWeek == 7) { - str += ""; - dayInWeek = 0; - } - - dispmonth = 1 + month; - actVal = formatNum4(year) + "-" + formatNum2(dispmonth, 'month') + "-" + formatNum2(i, 'day'); - if (i == day) { - style = ' class="selected"'; - } else { - style = ''; - } - str += "" + i + "" - dayInWeek++; - } - for (i = dayInWeek; i < 7; i++) { - str += ""; - } - - str += "
      " + day_names[i] + "
       
       
      "; - - cnt.innerHTML = str; -} - -/** - * Returns date from calendar. - * - * @param string date text - */ -function returnDate(d,m,y) { - cmd = "window.opener.document."+window.opener.formName+"."+window.opener.fieldName+"day.selectedIndex = "+(d-1); - eval(cmd); - cmd = "window.opener.document."+window.opener.formName+"."+window.opener.fieldName+"month.selectedIndex = "+m; - eval(cmd); - date = new Date(); - year = date.getFullYear()-1; - cmd = "window.opener.document."+window.opener.formName+"."+window.opener.fieldName+"year.selectedIndex = "+(y-year); - eval(cmd); - window.close(); -} diff --git a/main/inc/lib/formvalidator/Element/calendar_popup.php b/main/inc/lib/formvalidator/Element/calendar_popup.php deleted file mode 100755 index 8b141184e5..0000000000 --- a/main/inc/lib/formvalidator/Element/calendar_popup.php +++ /dev/null @@ -1,156 +0,0 @@ - - - - -Calendar - - - - - - - -
      -
      - - diff --git a/main/inc/lib/formvalidator/Element/tbl_change.js.php b/main/inc/lib/formvalidator/Element/tbl_change.js.php deleted file mode 100755 index e999cfd9a7..0000000000 --- a/main/inc/lib/formvalidator/Element/tbl_change.js.php +++ /dev/null @@ -1,198 +0,0 @@ - -var day; -var month; -var year; -var hour; -var minute; -var second; -var clock_set = 0; - -/** - * Opens calendar window. - * - * @param string form name - * @param string field name - */ -function openCalendar(form, field) { - formblock= document.getElementById(form); - forminputs = formblock.getElementsByTagName('select'); - var datevalues = new Array(); - var dateindex = 0; - for (i = 0; i < forminputs.length; i++) { - // regex here to check name attribute - var regex = new RegExp(field, "i"); - if (regex.test(forminputs[i].getAttribute('name'))) { - datevalues[dateindex++] = forminputs[i].value; - } - } - window.open("formvalidator/Element/calendar_popup.php", "calendar", "width=260,height=230,status=no"); - day = datevalues[0]; - month = datevalues[1]; - year = datevalues[2]; - - - month--; - formName = form; - fieldName =field; -} - -/** - * Formats number to two digits. - * - * @param int number to format. - */ -function formatNum2(i, valtype) { - f = (i < 10 ? '0' : '') + i; - if (valtype && valtype != '') { - switch(valtype) { - case 'month': - f = (f > 12 ? 12 : f); - break; - - case 'day': - f = (f > 31 ? 31 : f); - break; - } - } - - return f; -} - -/** - * Formats number to four digits. - * - * @param int number to format. - */ -function formatNum4(i) { - return (i < 1000 ? i < 100 ? i < 10 ? '000' : '00' : '0' : '') + i; -} - -/** - * Initializes calendar window. - */ -function initCalendar() { - if (!year && !month && !day) { - day = window.opener.day; - month = window.opener.month; - year = window.opener.year; - if (isNaN(year) || isNaN(month) || isNaN(day) || day == 0) { - dt = new Date(); - year = dt.getFullYear(); - month = dt.getMonth(); - day = dt.getDate(); - } - } else { - /* Moving in calendar */ - if (month > 11) { - month = 0; - year++; - } - if (month < 0) { - month = 11; - year--; - } - } - - if (document.getElementById) { - cnt = document.getElementById("calendar_data"); - } else if (document.all) { - cnt = document.all["calendar_data"]; - } - - cnt.innerHTML = ""; - - str = "" - - //heading table - str += '
      '; - str += ' '; - str += month_names[month]; - str += ' '; - str += ''; - str += ' '; - str += year; - str += ' '; - str += '
      '; - - str += ''; - for (i = 0; i < 7; i++) { - str += ""; - } - str += ""; - - var firstDay = new Date(year, month, 1).getDay(); - var lastDay = new Date(year, month + 1, 0).getDate(); - - str += ""; - - dayInWeek = 0; - for (i = 0; i < firstDay; i++) { - str += ""; - dayInWeek++; - } - for (i = 1; i <= lastDay; i++) { - if (dayInWeek == 7) { - str += ""; - dayInWeek = 0; - } - - dispmonth = 1 + month; - actVal = formatNum4(year) + "-" + formatNum2(dispmonth, 'month') + "-" + formatNum2(i, 'day'); - if (i == day) { - style = ' class="selected"'; - } else { - style = ''; - } - str += "
      " + i + "
      " - dayInWeek++; - } - for (i = dayInWeek; i < 7; i++) { - str += "
      "; - } - - str += "
      " + day_names[i] + "
       
       
      "; - - cnt.innerHTML = str; -} - -/** - * Returns date from calendar. - * - * @param string date text - */ -function returnDate(d,m,y) { - - formblock= window.opener.document.getElementById(window.opener.formName); - forminputs = formblock.getElementsByTagName('select'); - var datevalues = new Array(); - var dateindex = 0; - for (i = 0; i < forminputs.length; i++) { - // regex here to check name attribute - var regex = new RegExp(window.opener.fieldName, "i"); - if (regex.test(forminputs[i].getAttribute('name'))) { - datevalues[dateindex] = forminputs[i]; - dateindex++; - window.close(); - } - } - datevalues[0].selectedIndex = (d-1) ; - datevalues[1].selectedIndex = m; - - date = new Date(); - - //Selecting the first option of the year - year = datevalues[2].options[0].value; - - datevalues[2].selectedIndex = y - year; - for(i = 0; i<= 3; i++) { - attributes = datevalues[i].attributes; - for (attr=0; attr for the Univesity of Genevas - * @license /license.txt - */ -class CategoryForm extends \FormValidator -{ - - protected $category; - - function __construct($form_name = 'category', $method = 'post', $action = '', $target = '', $attributes = null, $track_submit = true) - { - parent::__construct($form_name, $method, $action, $target, $attributes, $track_submit); - } - - /** - * - * @return object - */ - public function get_category() - { - return $this->category; - } - - public function set_category($value) - { - $this->category = $value; - } - /** - * - * @param \Link\LinkCategory $category - */ - function init($category = null) - { - $this->set_category($category); - - $defaults = array(); - $defaults['category_title'] = $category->category_title; - $defaults['category_description'] = $category->description; - - $this->addElement('hidden', 'c_id', $category->c_id); - $this->addElement('hidden', 'id', $category->id); - $this->addElement('hidden', 'session_id', $category->session_id); - - $form_name = $category->id ? get_lang('ModifyCategory') : get_lang('AddCategory'); - $this->addHeader($form_name); - $this->addText('category_title', get_lang('Title')); - $this->addRule('category_title', get_lang('Required'), 'required'); - - $this->addElement('textarea', 'category_description', get_lang('Description')); - $this->addElement('button', 'save', get_lang('Save'), array('class' => 'btn save')); - $this->setDefaults($defaults); - } - - function update_model() - { - $values = $this->exportValues(); - $category = $this->get_category(); - $category->category_title = $values['category_title']; - $category->description = $values['category_description']; - } -} diff --git a/main/link/import_csv.class.php b/main/link/import_csv.class.php deleted file mode 100755 index 3739ae4524..0000000000 --- a/main/link/import_csv.class.php +++ /dev/null @@ -1,188 +0,0 @@ - - */ -class ImportCsv -{ - - protected $c_id; - protected $session_id; - protected $path; - protected $links_imported = 0; - protected $links_skipped = 0; - protected $update_existing_entries = false; - - public function __construct($c_id, $session_id, $path, $update_existing_entries = false) - { - $this->c_id = $c_id; - $this->session_id = $session_id; - $this->path = $path; - $this->update_existing_entries = $update_existing_entries; - } - - public function get_path() - { - return $this->path; - } - - public function get_c_id() - { - return $this->c_id; - } - - public function get_session_id() - { - return $this->session_id; - } - - public function get_links_imported() - { - return $this->links_imported; - } - - public function get_links_skipped() - { - return $this->links_skipped; - } - - public function get_update_existing_entries() - { - return $this->update_existing_entries; - } - - /** - * Read file and returns an array filled up with its' content. - * - * @return array of objects - */ - public function get_data() - { - $result = array(); - - $path = $this->path; - if (!is_readable($path)) { - return array(); - } - - $items = \Import::csv_reader($path); - foreach ($items as $item) { - $item = (object) $item; - $url = isset($item->url) ? trim($item->url) : ''; - $title = isset($item->title) ? trim($item->title) : ''; - $description = isset($item->description) ? trim($item->description) : ''; - $target = isset($item->target) ? trim($item->target) : ''; - $category_title = isset($item->category_title) ? trim($item->category_title) : ''; - $category_description = isset($item->category_description) ? trim($item->category_description) : ''; - if (empty($url)) { - continue; - } - if ($category_title) { - $category_title = \Security::remove_XSS($category_title); - $category_description = \Security::remove_XSS($category_description); - } else { - $category_description = ''; - } - - $url = \Security::remove_XSS($url); - $title = \Security::remove_XSS($title); - $description = \Security::remove_XSS($description); - $target = \Security::remove_XSS($target); - - $item->url = $url; - $item->title = $title; - $item->description = $description; - $item->target = $target; - $item->category_title = $category_title; - $item->category_description = $category_description; - $result[] = $item; - } - return $result; - } - - public function run() - { - $path = $this->path; - if (!is_readable($path)) { - return false; - } - $this->links_imported = 0; - $this->links_skipped = 0; - - $items = $this->get_data(); - foreach ($items as $item) { - $url = $item->url; - $title = $item->title; - $description = $item->description; - $target = $item->target; - $category_title = $item->category_title; - $category_description = $item->category_description; - - if ($category_title) { - $category = $this->ensure_category($category_title, $category_description); - } - - $link = $this->find_link_by_url($url); - if ($link && $this->update_existing_entries == false) { - $this->links_skipped++; - continue; - } - if (empty($link)) { - $link = new Link(); - $link->c_id = $this->c_id; - $link->session_id = $this->session_id; - $link->url = $url; - } - - $link->title = $title; - $link->description = $description; - $link->target = $target; - $link->category_id = $category ? $category->id : 0; - $repo = LinkRepository::instance(); - $repo->save($link); - $this->links_imported++; - } - } - - public function ensure_category($title, $description = '') - { - $c_id = $this->c_id; - $session_id = $this->session_id; - $repo = LinkCategoryRepository::instance(); - $result = $repo->find_one_by_course_and_name($c_id, $session_id, $title); - if (empty($result)) { - $result = new LinkCategory(); - $result->c_id = $c_id; - $result->category_title = $title; - $result->description = $description; - $result->session_id = $session_id; - $repo->save($result); - } - return $result; - } - - public function find_link_by_url($url) - { - $c_id = $this->c_id; - $session_id = $this->session_id; - $repo = LinkRepository::instance(); - $link = $repo->find_one_by_course_and_url($c_id, $session_id, $url); - return $link; - } - -} diff --git a/main/link/resources/js/main.js b/main/link/resources/js/main.js deleted file mode 100755 index b4cd8e7f2b..0000000000 --- a/main/link/resources/js/main.js +++ /dev/null @@ -1,105 +0,0 @@ - -function Proxy() {}; - -Proxy.prototype.root = function(){ - return www + '/main/inc/ajax/link.ajax.php'; -} - -Proxy.prototype.post = function(data, f){ - if(typeof(sec_token)!=='undefined'){ - data.sec_token = sec_token; - } - $.post(this.root(), data, f, 'json'); -} - -var Link = new Proxy(); - -Link.hide = function(c_id, id, f) -{ - var data = { - c_id: c_id, - id: id, - action: 'hide_link' - }; - this.post(data, f); -}; - -Link.show = function(c_id, id, f) -{ - var data = { - c_id: c_id, - id: id, - action: 'show_link' - }; - this.post(data, f); -}; - -Link.del = function(c_id, id, f) -{ - var data = { - c_id: c_id, - id: id, - action: 'delete_link' - }; - this.post(data, f); -}; - -Link.delete_by_course = function(c_id, session_id, f) -{ - var data = { - c_id: c_id, - session_id: session_id, - action: 'delete_by_course' - }; - this.post(data, f); -}; - -Link.sort = function(c_id, ids, f){ - var data = { - c_id: c_id, - ids: ids, - action: 'sort_links' - }; - this.post(data, f); -}; - -Link.validate = function(c_id, id, f) -{ - var data = { - c_id: c_id, - id: id, - action: 'validate_link' - }; - this.post(data, f); -}; - - - -var LinkCategory = new Proxy(); - -LinkCategory.del = function(c_id, id, f) -{ - var data = { - c_id: c_id, - id: id, - action: 'delete_category' - }; - this.post(data, f); -}; - -LinkCategory.sort = function(c_id, ids, f){ - var data = { - c_id: c_id, - ids: ids, - action: 'sort_categories' - }; - this.post(data, f); -}; - - -var message = {}; - -message.update = function(data){ - text = typeof(data)=='string' ? data : data.message; - $('#messages').html(text) -} \ No newline at end of file diff --git a/main/notebook/index.php b/main/notebook/index.php index e595143b10..6b2b8398de 100755 --- a/main/notebook/index.php +++ b/main/notebook/index.php @@ -5,9 +5,6 @@ * @author Christian Fasanando, initial version * @author Patrick Cool , Ghent University, Belgium, refactoring and tighter integration */ -/** - * Code - */ // Including the global initialization file require_once '../inc/global.inc.php'; diff --git a/main/notebook/resources/js/proxy.js b/main/notebook/resources/js/proxy.js deleted file mode 100755 index ceff94b0ab..0000000000 --- a/main/notebook/resources/js/proxy.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Define a client proxy for ajax calls. - */ - - -function Proxy() {}; - -Proxy.prototype.root = function(){ - return context.ajax; -} - -Proxy.prototype.post = function(data, f){ - if(typeof(context)!=='undefined' && typeof(context.sec_token)!=='undefined'){ - data.sec_token = context.sec_token; - } - $.post(this.root(), data, f, 'json'); -} - - -var notebook = new Proxy(); - -notebook.remove = function(c_id, id, f) -{ - var data = { - c_id: c_id, - id: id, - action: 'remove' - }; - this.post(data, f); -}; - -notebook.remove_by_course = function(c_id, session_id, f) -{ - var data = { - c_id: c_id, - session_id: session_id, - action: 'remove_by_course' - }; - this.post(data, f); -}; diff --git a/main/notebook/resources/js/ui.js b/main/notebook/resources/js/ui.js deleted file mode 100755 index 69a61fbbd2..0000000000 --- a/main/notebook/resources/js/ui.js +++ /dev/null @@ -1,104 +0,0 @@ -/** - * User interface objects. - */ - -var message = {}; - -message.update = function(data){ - var text = typeof(data)=='string' ? data : data.message; - $('#messages').html(text); -} - -message.error = function(data){ - text = typeof(data)=='string' ? data : data.message; - if(! text){ - return; - } - $('#messages').html('
      ' + text + '
      '); -} - -message.info = function(data){ - text = typeof(data)=='string' ? data : data.message; - if(! text){ - return; - } - $('#messages').html('
      ' + text + '
      '); -} - -message.confirmation = function(data){ - text = typeof(data)=='string' ? data : data.message; - if(! text){ - return; - } - $('#messages').html('
      ' + text + '
      '); -} - -message.warning = function(data){ - text = typeof(data)=='string' ? data : data.message; - if(! text){ - return; - } - $('#messages').html('
      ' + text + '
      '); -} - - -var ui = {}; - -ui.message = message; - -ui.loading = function(btn){ - $(btn).addClass("loading"); -}; - -ui.done = function(btn){ - $(btn).removeClass("loading"); -}; - -ui.confirm = function(){ - if(!window.confirm(lang.ConfirmYourChoice)){ - return false; - } else { - return true; - } -}; - -ui.remove = function(name, btn){ - if(!this.confirm()){ - return false; - } - - var item = $('#'+name); - var id = item.attr('data-id'); - var c_id = item.attr('data-c_id'); - - var f = function(data){ - if(data.success){ - item.remove(); - } - message.update(data); - ui.done(btn); - }; - ui.loading(btn); - ui.proxy.remove(c_id, id, f); -}; - -ui.remove_by_course = function(name, btn){ - if(!this.confirm()){ - return false; - } - - var item = $('#'+name); - var c_id = item.attr('data-c_id'); - var session_id = item.attr('data-session_id'); - - var f = function(data){ - if(data.success){ - item.remove(); - } - message.update(data); - ui.done(btn); - }; - ui.loading(btn); - ui.proxy.remove_by_course(c_id, session_id, f); - -}; \ No newline at end of file From b253e614523ad929addedced764d6eba784c491e Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 12:26:55 +0200 Subject: [PATCH 029/159] Remove unused code. --- main/admin/usergroups.php | 2 -- main/exercice/calculated_answer.class.php | 1 - main/exercice/freeanswer.class.php | 1 - main/newscorm/learnpath.class.php | 1 - main/newscorm/lp_edit.php | 3 +-- 5 files changed, 1 insertion(+), 7 deletions(-) diff --git a/main/admin/usergroups.php b/main/admin/usergroups.php index 70eed68b07..2e81a13597 100755 --- a/main/admin/usergroups.php +++ b/main/admin/usergroups.php @@ -104,9 +104,7 @@ if (isset($_GET['action']) && $_GET['action'] == 'add') { // Setting the form elements $form->addElement('header', get_lang('Add')); $form->addElement('text', 'name', get_lang('Name'), array('size' => '70', 'id' => 'name')); - //$form->applyFilter('note_title', 'html_filter'); $form->addHtmlEditor('description', get_lang('Description'), false, false, array('Width' => '95%', 'Height' => '250')); - //$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="add"'); $form->addButtonCreate(get_lang('Add')); // Setting the rules diff --git a/main/exercice/calculated_answer.class.php b/main/exercice/calculated_answer.class.php index 11baef8259..4a6512a9c7 100644 --- a/main/exercice/calculated_answer.class.php +++ b/main/exercice/calculated_answer.class.php @@ -162,7 +162,6 @@ class CalculatedAnswer extends Question global $text, $class; // setting the save button here and not in the question class.php - //$form->addElement('style_submit_button', 'submitQuestion', $text, 'class="'.$class.'"'); $form->addButtonSave($text, 'submitQuestion'); if (!empty($this->id)) { diff --git a/main/exercice/freeanswer.class.php b/main/exercice/freeanswer.class.php index 7d6cdb7efe..c7762b97d9 100755 --- a/main/exercice/freeanswer.class.php +++ b/main/exercice/freeanswer.class.php @@ -32,7 +32,6 @@ class FreeAnswer extends Question $form->addElement('text', 'weighting', get_lang('Weighting'), array('class' => 'span1')); global $text, $class; // setting the save button here and not in the question class.php - //$form->addElement('style_submit_button', 'submitQuestion', $text, 'class="' . $class . '"'); $form->addButtonSave($text, 'submitQuestion'); if (!empty($this->id)) { $form->setDefaults(array('weighting' => float_format($this->weighting, 1))); diff --git a/main/newscorm/learnpath.class.php b/main/newscorm/learnpath.class.php index 7c7f39ead2..16ddc9defc 100755 --- a/main/newscorm/learnpath.class.php +++ b/main/newscorm/learnpath.class.php @@ -7572,7 +7572,6 @@ class learnpath } } - //$form->addElement('style_submit_button', 'submit_button', $text, 'class="' . $class . '"'); $form->addButtonSave($text, 'submit_button'); $renderer = $form->defaultRenderer(); $renderer->setElementTemplate('
            {label}
      {element}', 'content_lp'); diff --git a/main/newscorm/lp_edit.php b/main/newscorm/lp_edit.php index 78e42c5fff..e6f457dc96 100755 --- a/main/newscorm/lp_edit.php +++ b/main/newscorm/lp_edit.php @@ -188,8 +188,7 @@ if ($enableLpExtraFields) { $extra = $extraField->addElements($form, $_SESSION['oLP']->get_id()); } -//Submit button -//$form->addElement('style_submit_button', 'Submit',get_lang('SaveLPSettings'),'class="save"'); +// Submit button $form->addButtonSave(get_lang('SaveLPSettings')); // Hidden fields From e952291c189a90b56ea67d7d947b989f55a0333c Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 12:41:28 +0200 Subject: [PATCH 030/159] Add intval, fix PHP warnings. --- main/admin/course_request_accepted.php | 35 +++++++++++++++---------- main/admin/course_request_rejected.php | 36 ++++++++++++++------------ main/admin/course_request_review.php | 14 +++++----- 3 files changed, 49 insertions(+), 36 deletions(-) diff --git a/main/admin/course_request_accepted.php b/main/admin/course_request_accepted.php index c5a461caf4..35cc259023 100755 --- a/main/admin/course_request_accepted.php +++ b/main/admin/course_request_accepted.php @@ -23,8 +23,8 @@ api_protect_admin_script(); $course_validation_feature = api_get_setting('course_validation') == 'true'; // Filltering passed to this page parameters. -$delete_course_request = intval($_GET['delete_course_request']); -$message = trim(Security::remove_XSS(stripslashes(urldecode($_GET['message'])))); +$delete_course_request = isset($_GET['delete_course_request']) ? intval($_GET['delete_course_request']) : ''; +$message = isset($_GET['message']) ? trim(Security::remove_XSS(stripslashes(urldecode($_GET['message'])))) : ''; $is_error_message = !empty($_GET['is_error_message']); if ($course_validation_feature) { @@ -84,17 +84,28 @@ function get_request_data($from, $number_of_items, $column, $direction) $keyword = isset($_GET['keyword']) ? Database::escape_string(trim($_GET['keyword'])) : null; $course_request_table = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST); - $sql = "SELECT id AS col0, - code AS col1, - title AS col2, - category_code AS col3, - tutor_name AS col4, - request_date AS col5, - id AS col6 - FROM $course_request_table WHERE status = ".COURSE_REQUEST_ACCEPTED; + $from = intval($from); + $number_of_items = intval($number_of_items); + $column = intval($column); + $direction = !in_array(strtolower(trim($direction)), ['asc','desc']) ? 'asc' : $direction; + + $sql = "SELECT + id AS col0, + code AS col1, + title AS col2, + category_code AS col3, + tutor_name AS col4, + request_date AS col5, + id AS col6 + FROM $course_request_table + WHERE status = ".COURSE_REQUEST_ACCEPTED; if ($keyword != '') { - $sql .= " AND (title LIKE '%".$keyword."%' OR code LIKE '%".$keyword."%' OR visual_code LIKE '%".$keyword."%')"; + $sql .= " AND ( + title LIKE '%".$keyword."%' OR + code LIKE '%".$keyword."%' OR + visual_code LIKE '%".$keyword."%' + )"; } $sql .= " ORDER BY col$column $direction "; $sql .= " LIMIT $from,$number_of_items"; @@ -149,7 +160,6 @@ $form->addButtonSearch(get_lang('Search')); // The action bar. echo ''; @@ -159,7 +169,6 @@ echo ''; // Create a sortable table with the course data. $table = new SortableTable('course_requests_accepted', 'get_number_of_requests', 'get_request_data', 5, 20, 'DESC'); -//$table->set_additional_parameters($parameters); $table->set_header(0, '', false); $table->set_header(1, get_lang('Code')); $table->set_header(2, get_lang('Title')); diff --git a/main/admin/course_request_rejected.php b/main/admin/course_request_rejected.php index d9b27ce6ac..d780af15c6 100755 --- a/main/admin/course_request_rejected.php +++ b/main/admin/course_request_rejected.php @@ -23,12 +23,12 @@ api_protect_admin_script(); $course_validation_feature = api_get_setting('course_validation') == 'true'; // Filltering passed to this page parameters. -$accept_course_request = intval($_GET['accept_course_request']); -$delete_course_request = intval($_GET['delete_course_request']); -$request_info = intval($_GET['request_info']); -$message = trim(Security::remove_XSS(stripslashes(urldecode($_GET['message'])))); +$accept_course_request = isset($_GET['accept_course_request']) ? intval($_GET['accept_course_request']) : ''; +$delete_course_request = isset($_GET['delete_course_request']) ? intval($_GET['delete_course_request']) : ''; +$request_info = isset($_GET['request_info']) ? intval($_GET['request_info']) : ''; +$message = isset($_GET['message']) ? trim(Security::remove_XSS(stripslashes(urldecode($_GET['message'])))) : ''; $is_error_message = !empty($_GET['is_error_message']); -$keyword = Database::escape_string(trim($_GET['keyword'])); +$keyword = isset($_GET['keyword']) ? Database::escape_string(trim($_GET['keyword'])) : ''; if ($course_validation_feature) { @@ -109,17 +109,23 @@ function get_number_of_requests() { */ function get_request_data($from, $number_of_items, $column, $direction) { global $keyword; - $course_request_table = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST); - $sql = "SELECT id AS col0, - code AS col1, - title AS col2, - category_code AS col3, - tutor_name AS col4, - request_date AS col5, - id AS col6 - FROM $course_request_table WHERE status = ".COURSE_REQUEST_REJECTED; + $from = intval($from); + $number_of_items = intval($number_of_items); + $column = intval($column); + $direction = !in_array(strtolower(trim($direction)), ['asc','desc']) ? 'asc' : $direction; + + $sql = "SELECT + id AS col0, + code AS col1, + title AS col2, + category_code AS col3, + tutor_name AS col4, + request_date AS col5, + id AS col6 + FROM $course_request_table + WHERE status = ".COURSE_REQUEST_REJECTED; if ($keyword != '') { $sql .= " AND (title LIKE '%".$keyword."%' OR code LIKE '%".$keyword."%' OR visual_code LIKE '%".$keyword."%')"; @@ -182,7 +188,6 @@ $form->addButtonSearch(get_lang('Search')); // The action bar. echo ''; @@ -192,7 +197,6 @@ echo ''; // Create a sortable table with the course data. $table = new SortableTable('course_requests_rejected', 'get_number_of_requests', 'get_request_data', 5, 20, 'DESC'); -//$table->set_additional_parameters($parameters); $table->set_header(0, '', false); $table->set_header(1, get_lang('Code')); $table->set_header(2, get_lang('Title')); diff --git a/main/admin/course_request_review.php b/main/admin/course_request_review.php index eb3bb572ef..3c02851924 100755 --- a/main/admin/course_request_review.php +++ b/main/admin/course_request_review.php @@ -24,13 +24,13 @@ api_protect_admin_script(); $course_validation_feature = api_get_setting('course_validation') == 'true'; // Filltering passed to this page parameters. -$accept_course_request = intval($_GET['accept_course_request']); -$reject_course_request = intval($_GET['reject_course_request']); -$request_info = intval($_GET['request_info']); -$delete_course_request = intval($_GET['delete_course_request']); -$message = trim(Security::remove_XSS(stripslashes(urldecode($_GET['message'])))); -$is_error_message = !empty($_GET['is_error_message']); -$keyword = Database::escape_string(trim($_GET['keyword'])); +$accept_course_request = isset($_GET['accept_course_request']) ? intval($_GET['accept_course_request']) : ''; +$reject_course_request = isset($_GET['reject_course_request']) ? intval($_GET['reject_course_request']) : ''; +$request_info = isset($_GET['request_info']) ? intval($_GET['request_info']) : ''; +$delete_course_request = isset($_GET['delete_course_request']) ? intval($_GET['delete_course_request']) : ''; +$message = isset($_GET['message']) ? trim(Security::remove_XSS(stripslashes(urldecode($_GET['message'])))) : ''; +$is_error_message = isset($_GET['is_error_message']) ? !empty($_GET['is_error_message']) : ''; +$keyword = isset($_GET['keyword']) ? Database::escape_string(trim($_GET['keyword'])) : ''; if ($course_validation_feature) { From e9a5a41107504c9c23471096edc93c41ac7de4cc Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 13:12:26 +0200 Subject: [PATCH 031/159] Remove require_once --- .../advanced_subscription/src/AdvancedSubscriptionPlugin.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php b/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php index ec4fc3be34..a942df8c2a 100644 --- a/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php +++ b/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php @@ -86,9 +86,9 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface ) ) ); + if (empty($result)) { - require_once api_get_path(LIBRARY_PATH).'extra_field.lib.php'; - $extraField = new Extrafield('user'); + $extraField = new ExtraField('user'); $extraField->save(array( 'field_type' => 1, 'field_variable' => 'area', From 54d74e2222497238e14de29143d9e129c4a2a5f5 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 13:38:00 +0200 Subject: [PATCH 032/159] Fix fatal error if plugin was not installed. --- main/inc/lib/hook/HookEvent.php | 1 + main/inc/lib/hook/HookObserver.php | 3 ++- .../src/AdvancedSubscriptionPlugin.php | 26 ++++++++++++------- .../createdrupaluser/src/CreateDrupalUser.php | 15 +++++++---- .../src/HookCreateDrupalUser.php | 4 +-- 5 files changed, 32 insertions(+), 17 deletions(-) diff --git a/main/inc/lib/hook/HookEvent.php b/main/inc/lib/hook/HookEvent.php index 8180b38545..b173b68d06 100644 --- a/main/inc/lib/hook/HookEvent.php +++ b/main/inc/lib/hook/HookEvent.php @@ -23,6 +23,7 @@ abstract class HookEvent implements HookEventInterface /** * Construct Method * @param string $eventName + * * @throws Exception */ protected function __construct($eventName) diff --git a/main/inc/lib/hook/HookObserver.php b/main/inc/lib/hook/HookObserver.php index cedfe483c8..226b1ddacb 100644 --- a/main/inc/lib/hook/HookObserver.php +++ b/main/inc/lib/hook/HookObserver.php @@ -34,7 +34,7 @@ abstract class HookObserver implements HookObserverInterface /** * Return the singleton instance of Hook observer. * If Hook Management plugin is not enabled, will return NULL - * @return static + * @return HookObserver */ public static function create() { @@ -45,6 +45,7 @@ abstract class HookObserver implements HookObserverInterface } else { try { $class = get_called_class(); + return new $class; } catch (Exception $e) { diff --git a/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php b/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php index a942df8c2a..37edd43aaa 100644 --- a/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php +++ b/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php @@ -1,12 +1,12 @@ uninstallHook(); - // Note: Keeping area field data is intended so it will not be removed - $this->uninstallDatabase(); + $setting = api_get_setting('advanced_subscription'); + if (!empty($setting)) { + $this->uninstallHook(); + // Note: Keeping area field data is intended so it will not be removed + $this->uninstallDatabase(); + } } /** @@ -830,6 +833,7 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface $count = Database::select('COUNT(*)', $advancedSubscriptionQueueTable, $where); $count = $count[0]['COUNT(*)']; } + return $count; } @@ -863,6 +867,7 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface * Return the status from user in queue to session subscription * @param int $userId * @param int $sessionId + * * @return bool|int */ public function getQueueStatus($userId, $sessionId) @@ -969,6 +974,7 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface if (isset($sessionArray['banner'])) { $sessionArray['banner'] = api_get_path(WEB_CODE_PATH) . $sessionArray['banner']; } + return $sessionArray; } @@ -979,13 +985,12 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface * Get status message * @param int $status * @param bool $isAble + * * @return string */ public function getStatusMessage($status, $isAble = true) { - $message = ''; - switch ($status) - { + switch ($status) { case ADVANCED_SUBSCRIPTION_QUEUE_STATUS_NO_QUEUE: if ($isAble) { $message = $this->get_lang('AdvancedSubscriptionNoQueueIsAble'); @@ -1010,7 +1015,6 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface break; default: $message = sprintf($this->get_lang('AdvancedSubscriptionQueueDefault'), $status); - } return $message; @@ -1019,11 +1023,13 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface /** * Return the url to go to session * @param $sessionId + * * @return string */ public function getSessionUrl($sessionId) { $url = api_get_path(WEB_CODE_PATH) . 'session/?session_id=' . intval($sessionId); + return $url; } @@ -1044,12 +1050,14 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface 'is_connected=' . 1 . '&' . 'profile_completed=' . intval($params['profile_completed']) . '&' . 'v=' . $this->generateHash($params); + return $url; } /** * Return the list of student, in queue used by admin view * @param int $sessionId + * * @return array */ public function listAllStudentsInQueueBySession($sessionId) diff --git a/plugin/createdrupaluser/src/CreateDrupalUser.php b/plugin/createdrupaluser/src/CreateDrupalUser.php index 0f41abd815..40924a0e3d 100644 --- a/plugin/createdrupaluser/src/CreateDrupalUser.php +++ b/plugin/createdrupaluser/src/CreateDrupalUser.php @@ -9,7 +9,6 @@ */ class CreateDrupalUser extends Plugin implements HookPluginInterface { - /** * Class constructor */ @@ -56,8 +55,9 @@ class CreateDrupalUser extends Plugin implements HookPluginInterface */ public function installHook() { - $hook = HookCreateDrupalUser::create(); - HookCreateUser::create()->attach($hook); + /** @var HookCreateDrupalUser $observer */ + $observer = HookCreateDrupalUser::create(); + HookCreateUser::create()->attach($observer); } /** @@ -65,8 +65,13 @@ class CreateDrupalUser extends Plugin implements HookPluginInterface */ public function uninstallHook() { - $hook = HookCreateDrupalUser::create(); - HookCreateUser::create()->detach($hook); + /** @var HookCreateDrupalUser $observer */ + $observer = HookCreateDrupalUser::create(); + $event = HookCreateUser::create(); + + if ($event) { + $event->detach($observer); + } } } diff --git a/plugin/createdrupaluser/src/HookCreateDrupalUser.php b/plugin/createdrupaluser/src/HookCreateDrupalUser.php index 3ae11ca0b2..6c9d21d8af 100644 --- a/plugin/createdrupaluser/src/HookCreateDrupalUser.php +++ b/plugin/createdrupaluser/src/HookCreateDrupalUser.php @@ -2,6 +2,7 @@ /* For licensing terms, see /license.txt */ /** + * Class HookCreateDrupalUser * Hook to create an user in Drupal website * * @author Angel Fernando Quiroz Campos @@ -9,9 +10,8 @@ */ class HookCreateDrupalUser extends HookObserver implements HookCreateUserObserverInterface { - /** - * Class constructor + * Constructor */ public function __construct() { From 1a25bc7c4de8f01079cca5de02fe0ff6424c6fd9 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 13:38:22 +0200 Subject: [PATCH 033/159] Fix fatal error. --- main/inc/lib/plugin.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main/inc/lib/plugin.class.php b/main/inc/lib/plugin.class.php index 3bd14ac4dc..0af1b48b7f 100755 --- a/main/inc/lib/plugin.class.php +++ b/main/inc/lib/plugin.class.php @@ -424,7 +424,7 @@ class Plugin $result = Database::query($sql); if (!Database::num_rows($result)) { $tool_link = "$plugin_name/start.php"; - $visibility = string2binary(api_get_setting('course_create_active_tools', $plugin_name)); + $visibility = AddCourse::string2binary(api_get_setting('course_create_active_tools', $plugin_name)); $sql = "INSERT INTO $t_tool VALUES ($courseId, NULL, '$plugin_name', '$tool_link', '$plugin_name.png',' ".$visibility."','0', 'squaregrey.gif','NO','_self','plugin','0')"; Database::query($sql); From 5c3e02b47e4dd76e2f8d4ee258b3e28733a350c7 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 14:22:34 +0200 Subject: [PATCH 034/159] Fix PHP warnings - Use constants of class SmsPlugin to call SMS types. The SmsPlugin is a common class for clockwork and Kannel. Code is now more simple. Add SmsPluginLibraryInterface --- main/dropbox/dropbox_functions.inc.php | 3 +- main/inc/ajax/user_manager.ajax.php | 5 +- main/inc/lib/SmsPlugin.php | 144 ++++++++++++++++++ main/inc/lib/SmsPluginLibraryInterface.php | 43 ++++++ main/inc/lib/add_course.lib.inc.php | 7 +- main/inc/lib/api.lib.php | 12 +- main/inc/lib/course.lib.php | 3 +- main/inc/lib/course_request.lib.php | 48 +++--- main/inc/lib/plugin.lib.php | 49 +++++- main/inc/lib/usermanager.lib.php | 3 +- main/user/user_add.php | 10 +- main/work/work.lib.php | 3 +- plugin/clockworksms/config.php | 1 - plugin/clockworksms/lib/clockworksms.lib.php | 123 ++++++++------- .../lib/clockworksms_plugin.class.php | 138 +---------------- plugin/kannelsms/lib/kannelsms.lib.php | 91 ++++++----- .../kannelsms/lib/kannelsms_plugin.class.php | 137 +---------------- 17 files changed, 390 insertions(+), 430 deletions(-) create mode 100644 main/inc/lib/SmsPlugin.php create mode 100644 main/inc/lib/SmsPluginLibraryInterface.php diff --git a/main/dropbox/dropbox_functions.inc.php b/main/dropbox/dropbox_functions.inc.php index 7e8ccbbca1..8092e42e12 100755 --- a/main/dropbox/dropbox_functions.inc.php +++ b/main/dropbox/dropbox_functions.inc.php @@ -879,9 +879,8 @@ function store_add_dropbox() if ($b_send_mail) { foreach ($new_work_recipients as $recipient_id) { $recipent_temp = UserManager :: get_user_info_by_id($recipient_id); - $plugin = new AppPlugin(); $additionalParameters = array( - 'smsType' => constant($plugin->getSMSPluginName().'::NEW_FILE_SHARED_COURSE_BY'), + 'smsType' => SmsPlugin::NEW_FILE_SHARED_COURSE_BY, 'userId' => $recipient_id, 'courseTitle' => $_course['title'], 'userUsername' => $recipent_temp['username'] diff --git a/main/inc/ajax/user_manager.ajax.php b/main/inc/ajax/user_manager.ajax.php index fbff6ae91c..e294fdc9c4 100755 --- a/main/inc/ajax/user_manager.ajax.php +++ b/main/inc/ajax/user_manager.ajax.php @@ -94,9 +94,8 @@ switch ($action) { //$emailbody.=get_lang('Problem'). "\n\n". get_lang('SignatureFormula'); $emailbody.=api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator'); - $plugin = new AppPlugin(); - $additionalParameters = array( - 'smsType' => constant($plugin->getSMSPluginName().'::ACCOUNT_APPROVED_CONNECT'), + $additionalParameters = array( + 'smsType' => SmsPlugin::ACCOUNT_APPROVED_CONNECT, 'userId' => $user_id ); diff --git a/main/inc/lib/SmsPlugin.php b/main/inc/lib/SmsPlugin.php new file mode 100644 index 0000000000..b588dd6982 --- /dev/null +++ b/main/inc/lib/SmsPlugin.php @@ -0,0 +1,144 @@ +get_handler_field_info_by_field_variable('mobile_phone_number'); + + if (empty($extraFieldInfo)) { + $extraField->save(array( + 'field_type' => 1, + 'field_variable' => 'mobile_phone_number', + 'field_display_text' => $this->get_lang('mobile_phone_number'), + 'field_default_value' => null, + 'field_order' => 2, + 'field_visible' => 1, + 'field_changeable' => 1, + 'field_filter' => null + )); + } + } + + /** + * install (installs the plugin) + * @return void + */ + public function install() + { + $this->addMobilePhoneNumberField(); + } +} diff --git a/main/inc/lib/SmsPluginLibraryInterface.php b/main/inc/lib/SmsPluginLibraryInterface.php new file mode 100644 index 0000000000..5ad6800575 --- /dev/null +++ b/main/inc/lib/SmsPluginLibraryInterface.php @@ -0,0 +1,43 @@ + constant( - $plugin->getSMSPluginName( - ) . '::NEW_COURSE_BEEN_CREATED' - ), + 'smsType' => SmsPlugin::NEW_COURSE_BEEN_CREATED, 'userId' => $user_id, 'courseName' => $title, 'creatorUsername' => $userInfo['username'] diff --git a/main/inc/lib/api.lib.php b/main/inc/lib/api.lib.php index 7d39789989..8f47aec2b2 100644 --- a/main/inc/lib/api.lib.php +++ b/main/inc/lib/api.lib.php @@ -8017,13 +8017,11 @@ function api_mail_html( return 0; } - $plugin = new AppPlugin(); - $installedPluginsList = $plugin->getInstalledPluginListObject(); - foreach ($installedPluginsList as $installedPlugin) { - if ($installedPlugin->isMailPlugin and array_key_exists("smsType", $additionalParameters)) { - $className = str_replace("Plugin", "", get_class($installedPlugin)); - $smsObject = new $className; - $smsObject->send($additionalParameters); + if (!empty($additionalParameters)) { + $plugin = new AppPlugin(); + $smsPlugin = $plugin->getSMSPluginLibrary(); + if ($smsPlugin) { + $smsPlugin->send($additionalParameters); } } diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php index 8176e136a5..f9e75b0189 100755 --- a/main/inc/lib/course.lib.php +++ b/main/inc/lib/course.lib.php @@ -2465,9 +2465,8 @@ class CourseManager api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS); $email_admin = api_get_setting('emailAdministrator'); - $plugin = new AppPlugin(); $additionalParameters = array( - 'smsType' => constant($plugin->getSMSPluginName() . '::NEW_USER_SUBSCRIBED_COURSE'), + 'smsType' => SmsPlugin::NEW_USER_SUBSCRIBED_COURSE, 'userId' => $tutor['user_id'], 'userUsername' => $student['username'], 'courseCode' => $course_code diff --git a/main/inc/lib/course_request.lib.php b/main/inc/lib/course_request.lib.php index 573e6c9518..8370c9d5a1 100755 --- a/main/inc/lib/course_request.lib.php +++ b/main/inc/lib/course_request.lib.php @@ -59,7 +59,6 @@ class CourseRequestManager $user_id, $exemplary_content ) { - global $_configuration; $wanted_code = trim($wanted_code); $user_id = (int)$user_id; $exemplary_content = (bool)$exemplary_content ? 1 : 0; @@ -95,7 +94,8 @@ class CourseRequestManager $db_name = isset($keys['currentCourseDbName']) ? $keys['currentCourseDbName'] : null; $directory = $keys['currentCourseRepository']; - $sql = sprintf('INSERT INTO %s ( + $sql = sprintf( + 'INSERT INTO %s ( code, user_id, directory, db_name, course_language, title, description, category_code, tutor_name, visual_code, request_date, @@ -104,23 +104,37 @@ class CourseRequestManager "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", - "%s", "%s", "%s", "%s", "%s");', Database::get_main_table(TABLE_MAIN_COURSE_REQUEST), - Database::escape_string($code), Database::escape_string($user_id), Database::escape_string($directory), Database::escape_string($db_name), - Database::escape_string($course_language), Database::escape_string($title), Database::escape_string($description), Database::escape_string($category_code), - Database::escape_string($tutor_name), Database::escape_string($visual_code), Database::escape_string($request_date), - Database::escape_string($objetives), Database::escape_string($target_audience), Database::escape_string($status), Database::escape_string($info), Database::escape_string($exemplary_content)); + "%s", "%s", "%s", "%s", "%s");', + Database::get_main_table(TABLE_MAIN_COURSE_REQUEST), + Database::escape_string($code), + Database::escape_string($user_id), + Database::escape_string($directory), + Database::escape_string($db_name), + Database::escape_string($course_language), + Database::escape_string($title), + Database::escape_string($description), + Database::escape_string($category_code), + Database::escape_string($tutor_name), + Database::escape_string($visual_code), + Database::escape_string($request_date), + Database::escape_string($objetives), + Database::escape_string($target_audience), + Database::escape_string($status), + Database::escape_string($info), + Database::escape_string($exemplary_content) + ); + $result_sql = Database::query($sql); if (!$result_sql) { return false; } + $last_insert_id = Database::insert_id(); // E-mail notifications. // E-mail language: The platform language seems to be the best choice. - //$email_language = $course_language; - //$email_language = api_get_interface_language(); $email_language = api_get_setting('platformLanguage'); $email_subject = sprintf(get_lang('CourseRequestEmailSubject', null, $email_language), '['.api_get_setting('siteName').']', $code); @@ -149,10 +163,9 @@ class CourseRequestManager $recipient_email_admin = get_setting('emailAdministrator'); $userInfo = api_get_user_info($user_id); - $plugin = new AppPlugin(); - $className = $plugin->getSMSPluginName(); + $additionalParameters = array( - 'smsType' => constant($className.'::NEW_COURSE_SUGGESTED_TEACHER'), + 'smsType' => SmsPlugin::NEW_COURSE_SUGGESTED_TEACHER, 'userId' => $user_id, 'userUsername' => $userInfo['username'] ); @@ -189,7 +202,7 @@ class CourseRequestManager $recipient_email_teacher = $sender_email_teacher; $additionalParameters = array( - 'smsType' => constant($className.'::COURSE_OPENING_REQUEST_CODE_REGISTERED'), + 'smsType' => SmsPlugin::COURSE_OPENING_REQUEST_CODE_REGISTERED, 'userId' => $user_info['user_id'], 'courseCode' => $wanted_code ); @@ -469,9 +482,8 @@ class CourseRequestManager $recipient_email = $user_info['mail']; $extra_headers = 'Bcc: '.$sender_email; - $plugin = new AppPlugin(); $additionalParameters = array( - 'smsType' => constant($plugin->getSMSPluginName().'::COURSE_OPENING_REQUEST_CODE_APPROVED'), + 'smsType' => SmsPlugin::COURSE_OPENING_REQUEST_CODE_APPROVED, 'userId' => $user_id, 'courseCode' => $course_info['code'] ); @@ -548,9 +560,8 @@ class CourseRequestManager $recipient_email = $user_info['mail']; $extra_headers = 'Bcc: '.$sender_email; - $plugin = new AppPlugin(); $additionalParameters = array( - 'smsType' => constant($plugin->getSMSPluginName().'::COURSE_OPENING_REQUEST_CODE_REJECTED'), + 'smsType' => SmsPlugin::COURSE_OPENING_REQUEST_CODE_REJECTED, 'userId' => $user_id, 'courseCode' => $code ); @@ -626,9 +637,8 @@ class CourseRequestManager $recipient_email = $user_info['mail']; $extra_headers = 'Bcc: '.$sender_email; - $plugin = new AppPlugin(); $additionalParameters = array( - 'smsType' => constant($plugin->getSMSPluginName().'::COURSE_OPENING_REQUEST_CODE'), + 'smsType' => SmsPlugin::COURSE_OPENING_REQUEST_CODE, 'userId' => $user_id, 'courseCode' => $code ); diff --git a/main/inc/lib/plugin.lib.php b/main/inc/lib/plugin.lib.php index 4b4b70eba0..758dfe1c48 100755 --- a/main/inc/lib/plugin.lib.php +++ b/main/inc/lib/plugin.lib.php @@ -29,7 +29,7 @@ class AppPlugin public $installedPluginListObject = array(); /** - * + * Constructor */ public function __construct() { @@ -183,6 +183,7 @@ class AppPlugin } else { $urlId = intval($urlId); } + // First call the custom uninstall to allow full access to global settings $pluginPath = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/uninstall.php'; if (is_file($pluginPath) && is_readable($pluginPath)) { @@ -271,7 +272,8 @@ class AppPlugin } /** - * Loads the translation files inside a plugin if exists. It loads by default english see the hello world plugin + * Loads the translation files inside a plugin if exists. + * It loads by default english see the hello world plugin * * @param string $plugin_name * @@ -350,11 +352,11 @@ class AppPlugin $_template['plugin_info'] = $plugin_info; } - //Setting the plugin info available in the template if exists + // Setting the plugin info available in the template if exists $template->assign($plugin_name, $_template); - //Loading the Twig template plugin files if exists + // Loading the Twig template plugin files if exists $template_list = array(); if (isset($plugin_info) && isset($plugin_info['templates'])) { $template_list = $plugin_info['templates']; @@ -372,6 +374,7 @@ class AppPlugin } } } + return true; } @@ -422,6 +425,7 @@ class AppPlugin } $plugin_info['settings'] = $settings_filtered; $plugin_data[$plugin_name] = $plugin_info; + return $plugin_info; } } @@ -464,7 +468,19 @@ class AppPlugin public function add_to_region($plugin, $region) { $access_url_id = api_get_current_access_url_id(); - api_add_setting($plugin, $region, $plugin, 'region', 'Plugins', $plugin, null, null, null, $access_url_id, 1); + api_add_setting( + $plugin, + $region, + $plugin, + 'region', + 'Plugins', + $plugin, + null, + null, + null, + $access_url_id, + 1 + ); } /** @@ -516,7 +532,7 @@ class AppPlugin ICON_SIZE_SMALL ); } - //$icon = null; + $form->addElement('html', '

      '.$icon.' '.Security::remove_XSS($pluginTitle).'

      '); $groups = array(); @@ -555,6 +571,7 @@ class AppPlugin $courseSettings = array_merge($courseSettings, $pluginCourseSetting); } } + return $courseSettings; } @@ -591,13 +608,31 @@ class AppPlugin * Get first SMS plugin name * @return string|boolean */ - public function getSMSPluginName() { + public function getSMSPluginName() + { $installedPluginsList = $this->getInstalledPluginListObject(); foreach ($installedPluginsList as $installedPlugin) { if ($installedPlugin->isMailPlugin) { + return get_class($installedPlugin); } } + + return false; + } + + /** + * @return SmsPluginLibraryInterface + */ + public function getSMSPluginLibrary() + { + $className = $this->getSMSPluginName(); + $className = str_replace("Plugin", "", $className); + + if (class_exists($className)) { + return new $className; + } + return false; } } diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php index 72691c2dfe..f233324f94 100755 --- a/main/inc/lib/usermanager.lib.php +++ b/main/inc/lib/usermanager.lib.php @@ -238,10 +238,9 @@ class UserManager EventsDispatcher::events('user_registration', $values); } else { $phoneNumber = isset($extra['mobile_phone_number']) ? $extra['mobile_phone_number'] : null; - $plugin = new AppPlugin(); $additionalParameters = array( - 'smsType' => constant($plugin->getSMSPluginName().':: WELCOME_LOGIN_PASSWORD'), + 'smsType' => SmsPlugin::WELCOME_LOGIN_PASSWORD, 'userId' => $return, 'mobilePhoneNumber' => $phoneNumber, 'password' => $original_password diff --git a/main/user/user_add.php b/main/user/user_add.php index f00c2af9d8..4430a4da84 100755 --- a/main/user/user_add.php +++ b/main/user/user_add.php @@ -186,21 +186,17 @@ if($register) { } } - if ($courseRegSucceed) - { + if ($courseRegSucceed) { $emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname_form, $lastname_form)).",\n".get_lang('OneResp')." $currentCourseName ".get_lang('RegYou')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : $username_form\n".get_lang('Pass').": $password_form\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is').": ".$portal_url."\n".get_lang('Problem')."\n".get_lang('SignatureFormula').",\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')." \nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email').": ".api_get_setting('emailAdministrator')."\n"; $message = get_lang('TheU')." ".stripslashes(api_get_person_name($firstname_form, $lastname_form))." ".get_lang('AddedToCourse')."".get_lang('BackUser')."\n"; - } - else - { + } else { $emailbody = get_lang('Dear')." ".api_get_person_name($firstname_form, $lastname_form).",\n ".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".get_lang('Username')." : $username_form\n".get_lang('Pass').": $password_form\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is').": ".$portal_url."\n".get_lang('Problem')."\n".get_lang('SignatureFormula').",\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')." \nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email').": ".api_get_setting('emailAdministrator')."\n"; $message = stripslashes(api_get_person_name($firstname_form, $lastname_form))." ".get_lang('AddedU'); } - $plugin = new AppPlugin(); $additionalParameters = array( - 'smsType' => constant($plugin->getSMSPluginName().'::BEEN_SUBSCRIBED_COURSE'), + 'smsType' => SmsPlugin::BEEN_SUBSCRIBED_COURSE, 'userId' => $user_id, 'courseTitle' => $currentCourseName ); diff --git a/main/work/work.lib.php b/main/work/work.lib.php index b90f94e40a..c9061ecce6 100755 --- a/main/work/work.lib.php +++ b/main/work/work.lib.php @@ -2527,9 +2527,8 @@ function send_email_on_homework_creation($course_id) $emailbody .= get_lang('HomeworkHasBeenCreatedForTheCourse')." ".$course_id.". "."\n\n".get_lang('PleaseCheckHomeworkPage'); $emailbody .= "\n\n".api_get_person_name($currentUser["firstname"], $currentUser["lastname"]); - $plugin = new AppPlugin(); $additionalParameters = array( - 'smsType' => constant($plugin->getSMSPluginName().'::ASSIGNMENT_BEEN_CREATED_COURSE'), + 'smsType' => SmsPlugin::ASSIGNMENT_BEEN_CREATED_COURSE, 'userId' => $student["user_id"], 'courseTitle' => $course_id ); diff --git a/plugin/clockworksms/config.php b/plugin/clockworksms/config.php index 52017f034b..fd2a790e06 100755 --- a/plugin/clockworksms/config.php +++ b/plugin/clockworksms/config.php @@ -8,7 +8,6 @@ * @author Imanol Losada */ require_once __DIR__ . '/../../main/inc/global.inc.php'; -require_once api_get_path(LIBRARY_PATH).'plugin.class.php'; require_once 'lib/clockworksms.lib.php'; require_once 'vendor/clockworksms_api.php'; diff --git a/plugin/clockworksms/lib/clockworksms.lib.php b/plugin/clockworksms/lib/clockworksms.lib.php index d8d2c5312d..daef0384fc 100755 --- a/plugin/clockworksms/lib/clockworksms.lib.php +++ b/plugin/clockworksms/lib/clockworksms.lib.php @@ -4,14 +4,14 @@ /** * Class Clockworksms * This script handles incoming SMS information, process it and sends an SMS if everything is right - * + * * @package chamilo.plugin.clockworksms.lib * @author Imanol Losada * * Clockworksms-Chamilo connector class */ -class Clockworksms +class Clockworksms implements SmsPluginLibraryInterface { public $apiKey; public $api; @@ -35,7 +35,9 @@ class Clockworksms if ($clockWorkSMSPlugin == true) { $this->apiKey = $clockWorkSMSApiKey; // Setting Clockworksms api - define('CONFIG_SECURITY_API_KEY', $this->apiKey); + if (!defined('CONFIG_SECURITY_API_KEY')) { + define('CONFIG_SECURITY_API_KEY', $this->apiKey); + } $trimmedApiKey = trim(CONFIG_SECURITY_API_KEY); if (!empty($trimmedApiKey)) { $this->api = new Clockwork(CONFIG_SECURITY_API_KEY); @@ -52,22 +54,24 @@ class Clockworksms $emailbody = 'Key cannot be blank'; $sender_name = $recipient_name; $email_admin = $email_form; - api_mail_html($recipient_name, $email_form, $emailsubject, $emailbody, $sender_name, $email_admin); + api_mail_html( + $recipient_name, + $email_form, + $emailsubject, + $emailbody, + $sender_name, + $email_admin + ); } $this->plugin_enabled = true; } } /** - * getMobilePhoneNumberById (retrieves a user mobile phone number by user id) - * @param int User id - * @return int User's mobile phone number + * @inheritdoc */ - private function getMobilePhoneNumberById($userId) + public function getMobilePhoneNumberById($userId) { - require_once api_get_path(LIBRARY_PATH).'extra_field.lib.php'; - require_once api_get_path(LIBRARY_PATH).'extra_field_value.lib.php'; - $mobilePhoneNumberExtraField = new ExtraField('user'); $mobilePhoneNumberExtraField = $mobilePhoneNumberExtraField->get_handler_field_info_by_field_variable('mobile_phone_number'); @@ -93,10 +97,11 @@ class Clockworksms { $trimmedKey = trim(CONFIG_SECURITY_API_KEY); if (!empty($trimmedKey)) { + $phoneExists = array_key_exists("mobilePhoneNumber", $additionalParameters); + $to = $phoneExists ? $additionalParameters['mobilePhoneNumber'] : $this->getMobilePhoneNumberById($additionalParameters['userId']); + $message = array( - "to" => array_key_exists("mobilePhoneNumber",$additionalParameters) ? - $additionalParameters['mobilePhoneNumber'] : - $this->getMobilePhoneNumberById($additionalParameters['userId']), + "to" => $to, "message" => $this->getSms($additionalParameters) ); @@ -104,7 +109,7 @@ class Clockworksms $result = $this->api->send($message); // Commented for future message logging / tracking purposes - /*if( $result["success"] ) { + /*if ($result["success"]) { echo "Message sent - ID: " . $result["id"]; } else { echo "Message failed - Error: " . $result["error_message"]; @@ -166,8 +171,8 @@ class Clockworksms $tool_name = $plugin->get_lang('plugin_title'); $tpl = new Template($tool_name); - switch (constant('ClockworksmsPlugin::'.$additionalParameters['smsType'])) { - case ClockworksmsPlugin::WELCOME_LOGIN_PASSWORD: + switch ($additionalParameters['smsType']) { + case SmsPlugin::WELCOME_LOGIN_PASSWORD: $userInfo = api_get_user_info($additionalParameters['userId']); return $this->buildSms( $plugin, @@ -181,7 +186,7 @@ class Clockworksms ) ); break; - case ClockworksmsPlugin::NEW_FILE_SHARED_COURSE_BY: + case SmsPlugin::NEW_FILE_SHARED_COURSE_BY: return $this->buildSms( $plugin, $tpl, @@ -194,7 +199,7 @@ class Clockworksms ) ); break; - case ClockworksmsPlugin::ACCOUNT_APPROVED_CONNECT: + case SmsPlugin::ACCOUNT_APPROVED_CONNECT: return $this->buildSms( $plugin, $tpl, @@ -206,7 +211,7 @@ class Clockworksms ) ); break; - case ClockworksmsPlugin::NEW_COURSE_BEEN_CREATED: + case SmsPlugin::NEW_COURSE_BEEN_CREATED: return $this->buildSms( $plugin, $tpl, @@ -219,7 +224,7 @@ class Clockworksms ) ); break; - case ClockworksmsPlugin::NEW_USER_SUBSCRIBED_COURSE: + case SmsPlugin::NEW_USER_SUBSCRIBED_COURSE: return $this->buildSms( $plugin, $tpl, @@ -232,7 +237,7 @@ class Clockworksms ) ); break; - case ClockworksmsPlugin::NEW_COURSE_SUGGESTED_TEACHER: + case SmsPlugin::NEW_COURSE_SUGGESTED_TEACHER: return $this->buildSms( $plugin, $tpl, @@ -244,7 +249,7 @@ class Clockworksms ) ); break; - case ClockworksmsPlugin::COURSE_OPENING_REQUEST_CODE_REGISTERED: + case SmsPlugin::COURSE_OPENING_REQUEST_CODE_REGISTERED: return $this->buildSms( $plugin, $tpl, @@ -256,7 +261,7 @@ class Clockworksms ) ); break; - case ClockworksmsPlugin::COURSE_OPENING_REQUEST_CODE_APPROVED: + case SmsPlugin::COURSE_OPENING_REQUEST_CODE_APPROVED: return $this->buildSms( $plugin, $tpl, @@ -268,7 +273,7 @@ class Clockworksms ) ); break; - case ClockworksmsPlugin::COURSE_OPENING_REQUEST_CODE_REJECTED: + case SmsPlugin::COURSE_OPENING_REQUEST_CODE_REJECTED: return $this->buildSms( $plugin, $tpl, @@ -280,7 +285,7 @@ class Clockworksms ) ); break; - case ClockworksmsPlugin::COURSE_OPENING_REQUEST_CODE: + case SmsPlugin::COURSE_OPENING_REQUEST_CODE: return $this->buildSms( $plugin, $tpl, @@ -292,7 +297,7 @@ class Clockworksms ) ); break; - case ClockworksmsPlugin::BEEN_SUBSCRIBED_COURSE: + case SmsPlugin::BEEN_SUBSCRIBED_COURSE: return $this->buildSms( $plugin, $tpl, @@ -304,7 +309,7 @@ class Clockworksms ) ); break; - case ClockworksmsPlugin::ASSIGNMENT_BEEN_CREATED_COURSE: + case SmsPlugin::ASSIGNMENT_BEEN_CREATED_COURSE: return $this->buildSms( $plugin, $tpl, @@ -317,7 +322,7 @@ class Clockworksms ); break; // Message types to be implemented. Fill the array parameter with arguments. - /*case ClockworksmsPlugin::ACCOUNT_CREATED_UPDATED_LOGIN_PASSWORD: + /*case SmsPlugin::ACCOUNT_CREATED_UPDATED_LOGIN_PASSWORD: return $this->buildSms( $plugin, $tpl, @@ -328,7 +333,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::PASSWORD_UPDATED_LOGIN_PASSWORD: + /*case SmsPlugin::PASSWORD_UPDATED_LOGIN_PASSWORD: return $this->buildSms( $plugin, $tpl, @@ -339,7 +344,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::REQUESTED_PASSWORD_CHANGE: + /*case SmsPlugin::REQUESTED_PASSWORD_CHANGE: return $this->buildSms( $plugin, $tpl, @@ -350,7 +355,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::RECEIVED_NEW_PERSONAL_MESSAGES: + /*case SmsPlugin::RECEIVED_NEW_PERSONAL_MESSAGES: return $this->buildSms( $plugin, $tpl, @@ -361,7 +366,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::NEW_USER_PENDING_APPROVAL: + /*case SmsPlugin::NEW_USER_PENDING_APPROVAL: return $this->buildSms( $plugin, $tpl, @@ -372,7 +377,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::POSTED_FORUM_COURSE: + /*case SmsPlugin::POSTED_FORUM_COURSE: return $this->buildSms( $plugin, $tpl, @@ -383,7 +388,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::CHECK_EMAIL_CONNECT_MORE_INFO: + /*case SmsPlugin::CHECK_EMAIL_CONNECT_MORE_INFO: return $this->buildSms( $plugin, $tpl, @@ -394,7 +399,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::STUDENT_ANSWERED_TEST: + /*case SmsPlugin::STUDENT_ANSWERED_TEST: return $this->buildSms( $plugin, $tpl, @@ -405,7 +410,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::STUDENT_ANSWERED_TEST_OPEN_QUESTION: + /*case SmsPlugin::STUDENT_ANSWERED_TEST_OPEN_QUESTION: return $this->buildSms( $plugin, $tpl, @@ -416,7 +421,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::STUDENT_ANSWERED_TEST_VOICE_QUESTION: + /*case SmsPlugin::STUDENT_ANSWERED_TEST_VOICE_QUESTION: return $this->buildSms( $plugin, $tpl, @@ -427,7 +432,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::ANSWER_OPEN_QUESTION_TEST_REVIEWED: + /*case SmsPlugin::ANSWER_OPEN_QUESTION_TEST_REVIEWED: return $this->buildSms( $plugin, $tpl, @@ -438,7 +443,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::NEW_THREAD_STARTED_FORUM: + /*case SmsPlugin::NEW_THREAD_STARTED_FORUM: return $this->buildSms( $plugin, $tpl, @@ -449,7 +454,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::NEW_ANSWER_POSTED_FORUM: + /*case SmsPlugin::NEW_ANSWER_POSTED_FORUM: return $this->buildSms( $plugin, $tpl, @@ -460,7 +465,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::NEW_SYSTEM_ANNOUNCEMENT_ADDED: + /*case SmsPlugin::NEW_SYSTEM_ANNOUNCEMENT_ADDED: return $this->buildSms( $plugin, $tpl, @@ -471,7 +476,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::TEST_NEW_SYSTEM_ANNOUNCEMENT_ADDED: + /*case SmsPlugin::TEST_NEW_SYSTEM_ANNOUNCEMENT_ADDED: return $this->buildSms( $plugin, $tpl, @@ -482,7 +487,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::SYSTEM_ANNOUNCEMENT_UPDATE: + /*case SmsPlugin::SYSTEM_ANNOUNCEMENT_UPDATE: return $this->buildSms( $plugin, $tpl, @@ -493,7 +498,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::TEST_SYSTEM_ANNOUNCEMENT_UPDATE: + /*case SmsPlugin::TEST_SYSTEM_ANNOUNCEMENT_UPDATE: return $this->buildSms( $plugin, $tpl, @@ -504,7 +509,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::USER_UPLOADED_ASSIGNMENT_COURSE_STUDENT_SUBMITS_PAPER: + /*case SmsPlugin::USER_UPLOADED_ASSIGNMENT_COURSE_STUDENT_SUBMITS_PAPER: return $this->buildSms( $plugin, $tpl, @@ -515,7 +520,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::USER_UPLOADED_ASSIGNMENT_CHECK_STUDENT_SUBMITS_PAPER: + /*case SmsPlugin::USER_UPLOADED_ASSIGNMENT_CHECK_STUDENT_SUBMITS_PAPER: return $this->buildSms( $plugin, $tpl, @@ -526,7 +531,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::USER_UPLOADED_ASSIGNMENT_COURSE: + /*case SmsPlugin::USER_UPLOADED_ASSIGNMENT_COURSE: return $this->buildSms( $plugin, $tpl, @@ -537,7 +542,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::USER_UPLOADED_ASSIGNMENT_CHECK: + /*case SmsPlugin::USER_UPLOADED_ASSIGNMENT_CHECK: return $this->buildSms( $plugin, $tpl, @@ -548,7 +553,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::SUBSCRIBED_SESSION: + /*case SmsPlugin::SUBSCRIBED_SESSION: return $this->buildSms( $plugin, $tpl, @@ -559,7 +564,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::SUBSCRIBED_SESSION_CSV: + /*case SmsPlugin::SUBSCRIBED_SESSION_CSV: return $this->buildSms( $plugin, $tpl, @@ -570,7 +575,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::USER_SUGGESTED_BE_FRIENDS: + /*case SmsPlugin::USER_SUGGESTED_BE_FRIENDS: return $this->buildSms( $plugin, $tpl, @@ -581,7 +586,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::USER_ANSWERED_INBOX_MESSAGE: + /*case SmsPlugin::USER_ANSWERED_INBOX_MESSAGE: return $this->buildSms( $plugin, $tpl, @@ -592,7 +597,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::BEEN_INVITED_JOIN_GROUP: + /*case SmsPlugin::BEEN_INVITED_JOIN_GROUP: return $this->buildSms( $plugin, $tpl, @@ -603,7 +608,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::MESSAGES_SENT_EDITED_GROUP_EDITED: + /*case SmsPlugin::MESSAGES_SENT_EDITED_GROUP_EDITED: return $this->buildSms( $plugin, $tpl, @@ -614,7 +619,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::MESSAGES_SENT_EDITED_GROUP_ADDED: + /*case SmsPlugin::MESSAGES_SENT_EDITED_GROUP_ADDED: return $this->buildSms( $plugin, $tpl, @@ -625,7 +630,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::BEEN_INVITED_COMPLETE_SURVEY_COURSE: + /*case SmsPlugin::BEEN_INVITED_COMPLETE_SURVEY_COURSE: return $this->buildSms( $plugin, $tpl, @@ -636,7 +641,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::REMINDER_ASSIGNMENT_COURSE_DUE: + /*case SmsPlugin::REMINDER_ASSIGNMENT_COURSE_DUE: return $this->buildSms( $plugin, $tpl, @@ -647,7 +652,7 @@ class Clockworksms ) ); break;*/ - /*case ClockworksmsPlugin::USER_DETAILS_MODIFIED: + /*case SmsPlugin::USER_DETAILS_MODIFIED: return $this->buildSms( $plugin, $tpl, diff --git a/plugin/clockworksms/lib/clockworksms_plugin.class.php b/plugin/clockworksms/lib/clockworksms_plugin.class.php index 12bbacfcfb..c8635aaa8f 100755 --- a/plugin/clockworksms/lib/clockworksms_plugin.class.php +++ b/plugin/clockworksms/lib/clockworksms_plugin.class.php @@ -4,59 +4,13 @@ /** * Class ClockworksmsPlugin * This script contains SMS type constants and basic plugin functions - * + * * @package chamilo.plugin.clockworksms.lib * @author Imanol Losada + * @author Julio Montoya - Refactor code */ -class ClockworksmsPlugin extends Plugin +class ClockworksmsPlugin extends SmsPlugin { - const WELCOME_LOGIN_PASSWORD = 0; - const NEW_FILE_SHARED_COURSE_BY = 1; - const ACCOUNT_APPROVED_CONNECT = 2; - const NEW_COURSE_BEEN_CREATED = 3; - const NEW_USER_SUBSCRIBED_COURSE = 4; - const NEW_COURSE_SUGGESTED_TEACHER = 5; - const COURSE_OPENING_REQUEST_CODE_REGISTERED = 6; - const COURSE_OPENING_REQUEST_CODE_APPROVED = 7; - const COURSE_OPENING_REQUEST_CODE_REJECTED = 8; - const COURSE_OPENING_REQUEST_CODE = 9; - const BEEN_SUBSCRIBED_COURSE = 10; - const ASSIGNMENT_BEEN_CREATED_COURSE = 11; - const ACCOUNT_CREATED_UPDATED_LOGIN_PASSWORD = 12; - const PASSWORD_UPDATED_LOGIN_PASSWORD = 13; - const REQUESTED_PASSWORD_CHANGE = 14; - const RECEIVED_NEW_PERSONAL_MESSAGES = 15; - const NEW_USER_PENDING_APPROVAL = 16; - const POSTED_FORUM_COURSE = 17; - const CHECK_EMAIL_CONNECT_MORE_INFO = 18; - const STUDENT_ANSWERED_TEST = 19; - const STUDENT_ANSWERED_TEST_OPEN_QUESTION = 20; - const STUDENT_ANSWERED_TEST_VOICE_QUESTION = 21; - const ANSWER_OPEN_QUESTION_TEST_REVIEWED = 22; - const NEW_THREAD_STARTED_FORUM = 23; - const NEW_ANSWER_POSTED_FORUM = 24; - const NEW_SYSTEM_ANNOUNCEMENT_ADDED = 25; - const TEST_NEW_SYSTEM_ANNOUNCEMENT_ADDED = 26; - const SYSTEM_ANNOUNCEMENT_UPDATE = 27; - const TEST_SYSTEM_ANNOUNCEMENT_UPDATE = 28; - const USER_UPLOADED_ASSIGNMENT_COURSE_STUDENT_SUBMITS_PAPER = 29; - const USER_UPLOADED_ASSIGNMENT_CHECK_STUDENT_SUBMITS_PAPER = 30; - const USER_UPLOADED_ASSIGNMENT_COURSE = 31; - const USER_UPLOADED_ASSIGNMENT_CHECK = 32; - const SUBSCRIBED_SESSION = 33; - const SUBSCRIBED_SESSION_CSV = 34; - const USER_SUGGESTED_BE_FRIENDS = 35; - const USER_ANSWERED_INBOX_MESSAGE = 36; - const BEEN_INVITED_JOIN_GROUP = 37; - const MESSAGES_SENT_EDITED_GROUP_EDITED = 38; - const MESSAGES_SENT_EDITED_GROUP_ADDED = 39; - const BEEN_INVITED_COMPLETE_SURVEY_COURSE = 40; - const REMINDER_ASSIGNMENT_COURSE_DUE = 41; - const USER_DETAILS_MODIFIED = 42; - - public $isCoursePlugin = true; - public $isMailPlugin = true; - /** * create (a singleton function that ensures ClockworksmsPlugin instance is * created only once. If it is already created, it returns the instance) @@ -72,7 +26,7 @@ class ClockworksmsPlugin extends Plugin * Constructor * @return void */ - protected function __construct() + public function __construct() { $fields = array('tool_enable' => 'boolean', 'api_key' => 'text'); $smsTypeOptions = $this->getSmsTypeOptions(); @@ -82,91 +36,7 @@ class ClockworksmsPlugin extends Plugin parent::__construct('0.1', 'Imanol Losada', $fields); } - /** - * addMobilePhoneNumberField (adds a mobile phone number field if it is not - * already created) - * @return void - */ - private function addMobilePhoneNumberField() - { - $result = Database::select('mobile_phone_number', 'user_field'); - if (empty($result)) { - require_once api_get_path(LIBRARY_PATH).'extra_field.lib.php'; - $extraField = new Extrafield('user'); - $extraField->save(array( - 'field_type' => 1, - 'field_variable' => 'mobile_phone_number', - 'field_display_text' => $this->get_lang('mobile_phone_number'), - 'field_default_value' => null, - 'field_order' => 2, - 'field_visible' => 1, - 'field_changeable' => 1, - 'field_filter' => null - )); - } - } - - /** - * getSmsTypeOptions (returns all SMS types) - * @return array SMS types - */ - private function getSmsTypeOptions() - { - return array( - 'MessageWelcomeXLoginXPasswordX', - 'MessageXNewFileSharedCourseXByX', - 'MessageXAccountApprovedConnectX', - 'MessageXNewCourseXBeenCreatedX', - 'MessageXNewUserXSubscribedCourseX', - 'MessageXNewCourseSuggestedTeacherX', - 'MessageXCourseOpeningRequestCodeXRegistered', - 'MessageXCourseOpeningRequestCourseCodeXApproved', - 'MessageXRequestOpenCourseCodeXReject', - 'MessageXCourseOpeningRequestCourseCodeX', - 'MessageXBeenSubscribedCourseX', - 'MessageXAssignmentBeenCreatedCourseX', - 'MessageXAccountCreatedUpdatedLoginXPasswordX', - 'MessageXPasswordUpdatedLoginXPasswordX', - 'MessageXRequestedPasswordChange', - 'MessageXReceivedNewPersonalMessages', - 'MessageXNewUserXPendingApproval', - 'MessageXXPostedForumXCourseX', - 'MessageXXXCheckEmailConnectMoreInfo', - 'MessageXXStudentXAnsweredTestX', - 'MessageXXStudentXAnsweredTestXOpenQuestion', - 'MessageXXStudentXAnsweredTestXVoiceQuestion', - 'MessageXXAnswerOpenQuestionTestXReviewed', - 'MessageXXNewThreadXStartedForumX', - 'MessageXXNewAnswerPostedXForumX', - 'MessageXXNewSystemAnnouncementAdded', - 'MessageXTestXNewSystemAnnouncementAdded', - 'MessageXXSystemAnnouncementUpdate', - 'MessageXTestXSystemAnnouncementUpdate', - 'MessageXUserXUploadedAssignmentXCourseXStudentSubmitsPaper', - 'MessageXUserXUploadedAssignmentXCheckXStudentSubmitsPaper', - 'MessageXUserXUploadedAssignmentXCourseX', - 'MessageXUserXUploadedAssignmentXCheckX', - 'MessageXSubscribedSessionX', - 'MessageXSubscribedSessionXCSV', - 'MessageXUserXSuggestedBeFriends', - 'MessageXUserXAnsweredInboxMessage', - 'MessageXBeenInvitedJoinGroupX', - 'MessageXMessagesSentEditedGroupXEdited', - 'MessageXMessagesSentEditedGroupXAdded', - 'MessageXBeenInvitedCompleteSurveyXCourseX', - 'MessageXReminderAssignmentXCourseXDue', - 'MessageXUserDetailsModified' - ); - } - /** - * install (installs the plugin) - * @return void - */ - public function install() - { - $this->addMobilePhoneNumberField(); - } /** * install (uninstalls the plugin and removes all plugin's tables and/or rows) * @return void diff --git a/plugin/kannelsms/lib/kannelsms.lib.php b/plugin/kannelsms/lib/kannelsms.lib.php index 84a61cf3af..b32589f822 100644 --- a/plugin/kannelsms/lib/kannelsms.lib.php +++ b/plugin/kannelsms/lib/kannelsms.lib.php @@ -10,8 +10,7 @@ * * Kannelsms-Chamilo connector class */ - -class Kannelsms +class Kannelsms implements SmsPluginLibraryInterface { public $api; public $hostAddress; @@ -45,7 +44,7 @@ class Kannelsms * @param int $userId User id * @return int User's mobile phone number */ - private function getMobilePhoneNumberById($userId) + public function getMobilePhoneNumberById($userId) { $mobilePhoneNumberExtraField = new ExtraField('user'); $mobilePhoneNumberExtraField = $mobilePhoneNumberExtraField->get_handler_field_info_by_field_variable('mobile_phone_number'); @@ -153,7 +152,7 @@ class Kannelsms $tpl = new Template($tool_name); switch ($additionalParameters['smsType']) { - case KannelsmsPlugin::WELCOME_LOGIN_PASSWORD: + case SmsPlugin::WELCOME_LOGIN_PASSWORD: $userInfo = api_get_user_info($additionalParameters['userId']); return $this->buildSms( $plugin, @@ -167,7 +166,7 @@ class Kannelsms ) ); break; - case KannelsmsPlugin::NEW_FILE_SHARED_COURSE_BY: + case SmsPlugin::NEW_FILE_SHARED_COURSE_BY: return $this->buildSms( $plugin, $tpl, @@ -180,7 +179,7 @@ class Kannelsms ) ); break; - case KannelsmsPlugin::ACCOUNT_APPROVED_CONNECT: + case SmsPlugin::ACCOUNT_APPROVED_CONNECT: return $this->buildSms( $plugin, $tpl, @@ -192,7 +191,7 @@ class Kannelsms ) ); break; - case KannelsmsPlugin::NEW_COURSE_BEEN_CREATED: + case SmsPlugin::NEW_COURSE_BEEN_CREATED: return $this->buildSms( $plugin, $tpl, @@ -205,7 +204,7 @@ class Kannelsms ) ); break; - case KannelsmsPlugin::NEW_USER_SUBSCRIBED_COURSE: + case SmsPlugin::NEW_USER_SUBSCRIBED_COURSE: return $this->buildSms( $plugin, $tpl, @@ -218,7 +217,7 @@ class Kannelsms ) ); break; - case KannelsmsPlugin::NEW_COURSE_SUGGESTED_TEACHER: + case SmsPlugin::NEW_COURSE_SUGGESTED_TEACHER: return $this->buildSms( $plugin, $tpl, @@ -230,7 +229,7 @@ class Kannelsms ) ); break; - case KannelsmsPlugin::COURSE_OPENING_REQUEST_CODE_REGISTERED: + case SmsPlugin::COURSE_OPENING_REQUEST_CODE_REGISTERED: return $this->buildSms( $plugin, $tpl, @@ -242,7 +241,7 @@ class Kannelsms ) ); break; - case KannelsmsPlugin::COURSE_OPENING_REQUEST_CODE_APPROVED: + case SmsPlugin::COURSE_OPENING_REQUEST_CODE_APPROVED: return $this->buildSms( $plugin, $tpl, @@ -254,7 +253,7 @@ class Kannelsms ) ); break; - case KannelsmsPlugin::COURSE_OPENING_REQUEST_CODE_REJECTED: + case SmsPlugin::COURSE_OPENING_REQUEST_CODE_REJECTED: return $this->buildSms( $plugin, $tpl, @@ -266,7 +265,7 @@ class Kannelsms ) ); break; - case KannelsmsPlugin::COURSE_OPENING_REQUEST_CODE: + case SmsPlugin::COURSE_OPENING_REQUEST_CODE: return $this->buildSms( $plugin, $tpl, @@ -278,7 +277,7 @@ class Kannelsms ) ); break; - case KannelsmsPlugin::BEEN_SUBSCRIBED_COURSE: + case SmsPlugin::BEEN_SUBSCRIBED_COURSE: return $this->buildSms( $plugin, $tpl, @@ -290,7 +289,7 @@ class Kannelsms ) ); break; - case KannelsmsPlugin::ASSIGNMENT_BEEN_CREATED_COURSE: + case SmsPlugin::ASSIGNMENT_BEEN_CREATED_COURSE: return $this->buildSms( $plugin, $tpl, @@ -303,7 +302,7 @@ class Kannelsms ); break; // Message types to be implemented. Fill the array parameter with arguments. - /*case KannelsmsPlugin::ACCOUNT_CREATED_UPDATED_LOGIN_PASSWORD: + /*case SmsPlugin::ACCOUNT_CREATED_UPDATED_LOGIN_PASSWORD: return $this->buildSms( $plugin, $tpl, @@ -314,7 +313,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::PASSWORD_UPDATED_LOGIN_PASSWORD: + /*case SmsPlugin::PASSWORD_UPDATED_LOGIN_PASSWORD: return $this->buildSms( $plugin, $tpl, @@ -325,7 +324,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::REQUESTED_PASSWORD_CHANGE: + /*case SmsPlugin::REQUESTED_PASSWORD_CHANGE: return $this->buildSms( $plugin, $tpl, @@ -336,7 +335,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::RECEIVED_NEW_PERSONAL_MESSAGES: + /*case SmsPlugin::RECEIVED_NEW_PERSONAL_MESSAGES: return $this->buildSms( $plugin, $tpl, @@ -347,7 +346,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::NEW_USER_PENDING_APPROVAL: + /*case SmsPlugin::NEW_USER_PENDING_APPROVAL: return $this->buildSms( $plugin, $tpl, @@ -358,7 +357,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::POSTED_FORUM_COURSE: + /*case SmsPlugin::POSTED_FORUM_COURSE: return $this->buildSms( $plugin, $tpl, @@ -369,7 +368,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::CHECK_EMAIL_CONNECT_MORE_INFO: + /*case SmsPlugin::CHECK_EMAIL_CONNECT_MORE_INFO: return $this->buildSms( $plugin, $tpl, @@ -380,7 +379,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::STUDENT_ANSWERED_TEST: + /*case SmsPlugin::STUDENT_ANSWERED_TEST: return $this->buildSms( $plugin, $tpl, @@ -391,7 +390,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::STUDENT_ANSWERED_TEST_OPEN_QUESTION: + /*case SmsPlugin::STUDENT_ANSWERED_TEST_OPEN_QUESTION: return $this->buildSms( $plugin, $tpl, @@ -402,7 +401,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::STUDENT_ANSWERED_TEST_VOICE_QUESTION: + /*case SmsPlugin::STUDENT_ANSWERED_TEST_VOICE_QUESTION: return $this->buildSms( $plugin, $tpl, @@ -413,7 +412,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::ANSWER_OPEN_QUESTION_TEST_REVIEWED: + /*case SmsPlugin::ANSWER_OPEN_QUESTION_TEST_REVIEWED: return $this->buildSms( $plugin, $tpl, @@ -424,7 +423,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::NEW_THREAD_STARTED_FORUM: + /*case SmsPlugin::NEW_THREAD_STARTED_FORUM: return $this->buildSms( $plugin, $tpl, @@ -435,7 +434,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::NEW_ANSWER_POSTED_FORUM: + /*case SmsPlugin::NEW_ANSWER_POSTED_FORUM: return $this->buildSms( $plugin, $tpl, @@ -446,7 +445,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::NEW_SYSTEM_ANNOUNCEMENT_ADDED: + /*case SmsPlugin::NEW_SYSTEM_ANNOUNCEMENT_ADDED: return $this->buildSms( $plugin, $tpl, @@ -457,7 +456,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::TEST_NEW_SYSTEM_ANNOUNCEMENT_ADDED: + /*case SmsPlugin::TEST_NEW_SYSTEM_ANNOUNCEMENT_ADDED: return $this->buildSms( $plugin, $tpl, @@ -468,7 +467,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::SYSTEM_ANNOUNCEMENT_UPDATE: + /*case SmsPlugin::SYSTEM_ANNOUNCEMENT_UPDATE: return $this->buildSms( $plugin, $tpl, @@ -479,7 +478,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::TEST_SYSTEM_ANNOUNCEMENT_UPDATE: + /*case SmsPlugin::TEST_SYSTEM_ANNOUNCEMENT_UPDATE: return $this->buildSms( $plugin, $tpl, @@ -490,7 +489,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::USER_UPLOADED_ASSIGNMENT_COURSE_STUDENT_SUBMITS_PAPER: + /*case SmsPlugin::USER_UPLOADED_ASSIGNMENT_COURSE_STUDENT_SUBMITS_PAPER: return $this->buildSms( $plugin, $tpl, @@ -501,7 +500,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::USER_UPLOADED_ASSIGNMENT_CHECK_STUDENT_SUBMITS_PAPER: + /*case SmsPlugin::USER_UPLOADED_ASSIGNMENT_CHECK_STUDENT_SUBMITS_PAPER: return $this->buildSms( $plugin, $tpl, @@ -512,7 +511,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::USER_UPLOADED_ASSIGNMENT_COURSE: + /*case SmsPlugin::USER_UPLOADED_ASSIGNMENT_COURSE: return $this->buildSms( $plugin, $tpl, @@ -523,7 +522,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::USER_UPLOADED_ASSIGNMENT_CHECK: + /*case SmsPlugin::USER_UPLOADED_ASSIGNMENT_CHECK: return $this->buildSms( $plugin, $tpl, @@ -534,7 +533,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::SUBSCRIBED_SESSION: + /*case SmsPlugin::SUBSCRIBED_SESSION: return $this->buildSms( $plugin, $tpl, @@ -545,7 +544,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::SUBSCRIBED_SESSION_CSV: + /*case SmsPlugin::SUBSCRIBED_SESSION_CSV: return $this->buildSms( $plugin, $tpl, @@ -556,7 +555,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::USER_SUGGESTED_BE_FRIENDS: + /*case SmsPlugin::USER_SUGGESTED_BE_FRIENDS: return $this->buildSms( $plugin, $tpl, @@ -567,7 +566,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::USER_ANSWERED_INBOX_MESSAGE: + /*case SmsPlugin::USER_ANSWERED_INBOX_MESSAGE: return $this->buildSms( $plugin, $tpl, @@ -578,7 +577,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::BEEN_INVITED_JOIN_GROUP: + /*case SmsPlugin::BEEN_INVITED_JOIN_GROUP: return $this->buildSms( $plugin, $tpl, @@ -589,7 +588,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::MESSAGES_SENT_EDITED_GROUP_EDITED: + /*case SmsPlugin::MESSAGES_SENT_EDITED_GROUP_EDITED: return $this->buildSms( $plugin, $tpl, @@ -600,7 +599,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::MESSAGES_SENT_EDITED_GROUP_ADDED: + /*case SmsPlugin::MESSAGES_SENT_EDITED_GROUP_ADDED: return $this->buildSms( $plugin, $tpl, @@ -611,7 +610,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::BEEN_INVITED_COMPLETE_SURVEY_COURSE: + /*case SmsPlugin::BEEN_INVITED_COMPLETE_SURVEY_COURSE: return $this->buildSms( $plugin, $tpl, @@ -622,7 +621,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::REMINDER_ASSIGNMENT_COURSE_DUE: + /*case SmsPlugin::REMINDER_ASSIGNMENT_COURSE_DUE: return $this->buildSms( $plugin, $tpl, @@ -633,7 +632,7 @@ class Kannelsms ) ); break;*/ - /*case KannelsmsPlugin::USER_DETAILS_MODIFIED: + /*case SmsPlugin::USER_DETAILS_MODIFIED: return $this->buildSms( $plugin, $tpl, diff --git a/plugin/kannelsms/lib/kannelsms_plugin.class.php b/plugin/kannelsms/lib/kannelsms_plugin.class.php index eaf6b65a00..ece978cc61 100644 --- a/plugin/kannelsms/lib/kannelsms_plugin.class.php +++ b/plugin/kannelsms/lib/kannelsms_plugin.class.php @@ -4,59 +4,13 @@ /** * Class KannelsmsPlugin * This script contains SMS type constants and basic plugin functions - * + * * @package chamilo.plugin.kannelsms.lib * @author Imanol Losada + * @author Julio Montoya Refactor code */ -class KannelsmsPlugin extends Plugin +class KannelsmsPlugin extends SmsPlugin { - const WELCOME_LOGIN_PASSWORD = 0; - const NEW_FILE_SHARED_COURSE_BY = 1; - const ACCOUNT_APPROVED_CONNECT = 2; - const NEW_COURSE_BEEN_CREATED = 3; - const NEW_USER_SUBSCRIBED_COURSE = 4; - const NEW_COURSE_SUGGESTED_TEACHER = 5; - const COURSE_OPENING_REQUEST_CODE_REGISTERED = 6; - const COURSE_OPENING_REQUEST_CODE_APPROVED = 7; - const COURSE_OPENING_REQUEST_CODE_REJECTED = 8; - const COURSE_OPENING_REQUEST_CODE = 9; - const BEEN_SUBSCRIBED_COURSE = 10; - const ASSIGNMENT_BEEN_CREATED_COURSE = 11; - const ACCOUNT_CREATED_UPDATED_LOGIN_PASSWORD = 12; - const PASSWORD_UPDATED_LOGIN_PASSWORD = 13; - const REQUESTED_PASSWORD_CHANGE = 14; - const RECEIVED_NEW_PERSONAL_MESSAGES = 15; - const NEW_USER_PENDING_APPROVAL = 16; - const POSTED_FORUM_COURSE = 17; - const CHECK_EMAIL_CONNECT_MORE_INFO = 18; - const STUDENT_ANSWERED_TEST = 19; - const STUDENT_ANSWERED_TEST_OPEN_QUESTION = 20; - const STUDENT_ANSWERED_TEST_VOICE_QUESTION = 21; - const ANSWER_OPEN_QUESTION_TEST_REVIEWED = 22; - const NEW_THREAD_STARTED_FORUM = 23; - const NEW_ANSWER_POSTED_FORUM = 24; - const NEW_SYSTEM_ANNOUNCEMENT_ADDED = 25; - const TEST_NEW_SYSTEM_ANNOUNCEMENT_ADDED = 26; - const SYSTEM_ANNOUNCEMENT_UPDATE = 27; - const TEST_SYSTEM_ANNOUNCEMENT_UPDATE = 28; - const USER_UPLOADED_ASSIGNMENT_COURSE_STUDENT_SUBMITS_PAPER = 29; - const USER_UPLOADED_ASSIGNMENT_CHECK_STUDENT_SUBMITS_PAPER = 30; - const USER_UPLOADED_ASSIGNMENT_COURSE = 31; - const USER_UPLOADED_ASSIGNMENT_CHECK = 32; - const SUBSCRIBED_SESSION = 33; - const SUBSCRIBED_SESSION_CSV = 34; - const USER_SUGGESTED_BE_FRIENDS = 35; - const USER_ANSWERED_INBOX_MESSAGE = 36; - const BEEN_INVITED_JOIN_GROUP = 37; - const MESSAGES_SENT_EDITED_GROUP_EDITED = 38; - const MESSAGES_SENT_EDITED_GROUP_ADDED = 39; - const BEEN_INVITED_COMPLETE_SURVEY_COURSE = 40; - const REMINDER_ASSIGNMENT_COURSE_DUE = 41; - const USER_DETAILS_MODIFIED = 42; - - public $isCoursePlugin = true; - public $isMailPlugin = true; - /** * create (a singleton function that ensures KannelsmsPlugin instance is * created only once. If it is already created, it returns the instance) @@ -88,91 +42,6 @@ class KannelsmsPlugin extends Plugin parent::__construct('0.1', 'Imanol Losada', $fields); } - /** - * addMobilePhoneNumberField (adds a mobile phone number field if it is not - * already created) - * @return void - */ - private function addMobilePhoneNumberField() - { - $result = Database::select('mobile_phone_number', 'user_field'); - if (empty($result)) { - require_once api_get_path(LIBRARY_PATH).'extra_field.lib.php'; - $extraField = new Extrafield('user'); - $extraField->save(array( - 'field_type' => 1, - 'field_variable' => 'mobile_phone_number', - 'field_display_text' => $this->get_lang('mobile_phone_number'), - 'field_default_value' => null, - 'field_order' => 2, - 'field_visible' => 1, - 'field_changeable' => 1, - 'field_filter' => null - )); - } - } - - /** - * getSmsTypeOptions (returns all SMS types) - * @return array SMS types - */ - private function getSmsTypeOptions() - { - return array( - 'MessageWelcomeXLoginXPasswordX', - 'MessageXNewFileSharedCourseXByX', - 'MessageXAccountApprovedConnectX', - 'MessageXNewCourseXBeenCreatedX', - 'MessageXNewUserXSubscribedCourseX', - 'MessageXNewCourseSuggestedTeacherX', - 'MessageXCourseOpeningRequestCodeXRegistered', - 'MessageXCourseOpeningRequestCourseCodeXApproved', - 'MessageXRequestOpenCourseCodeXReject', - 'MessageXCourseOpeningRequestCourseCodeX', - 'MessageXBeenSubscribedCourseX', - 'MessageXAssignmentBeenCreatedCourseX', - 'MessageXAccountCreatedUpdatedLoginXPasswordX', - 'MessageXPasswordUpdatedLoginXPasswordX', - 'MessageXRequestedPasswordChange', - 'MessageXReceivedNewPersonalMessages', - 'MessageXNewUserXPendingApproval', - 'MessageXXPostedForumXCourseX', - 'MessageXXXCheckEmailConnectMoreInfo', - 'MessageXXStudentXAnsweredTestX', - 'MessageXXStudentXAnsweredTestXOpenQuestion', - 'MessageXXStudentXAnsweredTestXVoiceQuestion', - 'MessageXXAnswerOpenQuestionTestXReviewed', - 'MessageXXNewThreadXStartedForumX', - 'MessageXXNewAnswerPostedXForumX', - 'MessageXXNewSystemAnnouncementAdded', - 'MessageXTestXNewSystemAnnouncementAdded', - 'MessageXXSystemAnnouncementUpdate', - 'MessageXTestXSystemAnnouncementUpdate', - 'MessageXUserXUploadedAssignmentXCourseXStudentSubmitsPaper', - 'MessageXUserXUploadedAssignmentXCheckXStudentSubmitsPaper', - 'MessageXUserXUploadedAssignmentXCourseX', - 'MessageXUserXUploadedAssignmentXCheckX', - 'MessageXSubscribedSessionX', - 'MessageXSubscribedSessionXCSV', - 'MessageXUserXSuggestedBeFriends', - 'MessageXUserXAnsweredInboxMessage', - 'MessageXBeenInvitedJoinGroupX', - 'MessageXMessagesSentEditedGroupXEdited', - 'MessageXMessagesSentEditedGroupXAdded', - 'MessageXBeenInvitedCompleteSurveyXCourseX', - 'MessageXReminderAssignmentXCourseXDue', - 'MessageXUserDetailsModified' - ); - } - - /** - * install (installs the plugin) - * @return void - */ - public function install() - { - $this->addMobilePhoneNumberField(); - } /** * install (uninstalls the plugin and removes all plugin's tables and/or rows) * @return void From 988df72aedea662071a98769f9befdf1dd6af737 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 14:22:46 +0200 Subject: [PATCH 035/159] Minor - format code. --- main/admin/course_add.php | 10 ++++------ main/create_course/add_course.php | 16 +++++++++++++--- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/main/admin/course_add.php b/main/admin/course_add.php index ca02ca6ce0..4e82909c8a 100755 --- a/main/admin/course_add.php +++ b/main/admin/course_add.php @@ -140,13 +140,11 @@ $form->setDefaults($values); // Validate the form if ($form->validate()) { - $course = $form->exportValues(); - $teacher_id = $course['tutor_id']; - $course_teachers = $course['course_teachers']; - + $course = $form->exportValues(); + $teacher_id = isset($course['tutor_id']) ? $course['tutor_id'] : ''; + $course_teachers = isset($course['course_teachers']) ? $course['course_teachers'] : null; $course['disk_quota'] = $course['disk_quota']*1024*1024; - - $course['exemplary_content'] = empty($course['exemplary_content']) ? false : true; + $course['exemplary_content'] = empty($course['exemplary_content']) ? false : true; $course['teachers'] = $course_teachers; $course['user_id'] = $teacher_id; $course['wanted_code'] = $course['visual_code']; diff --git a/main/create_course/add_course.php b/main/create_course/add_course.php index 9db04f6b22..dddb445a5d 100755 --- a/main/create_course/add_course.php +++ b/main/create_course/add_course.php @@ -220,11 +220,21 @@ if ($form->validate()) { } else { $message = Display :: return_message(get_lang('CourseCreationFailed'), 'error', false); // Display the form. - $content = $form->return_form(); + $content = $form->returnForm(); } } else { // Create a request for a new course. - $request_id = CourseRequestManager::create_course_request($wanted_code, $title, $description, $category_code, $course_language, $objetives, $target_audience, api_get_user_id(), $exemplary_content); + $request_id = CourseRequestManager::create_course_request( + $wanted_code, + $title, + $description, + $category_code, + $course_language, + $objetives, + $target_audience, + api_get_user_id(), + $exemplary_content + ); if ($request_id) { $course_request_info = CourseRequestManager::get_course_request_info($request_id); @@ -249,7 +259,7 @@ if ($form->validate()) { $message = Display :: return_message(get_lang('Explanation')); } // Display the form. - $content = $form->return_form(); + $content = $form->returnForm(); } $tpl->assign('message', $message); From a53ce590832f266f9d6f9ebfeb65a0d3ce227d22 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 14:24:07 +0200 Subject: [PATCH 036/159] Use template instead of DB value. --- plugin/clockworksms/lib/clockworksms.lib.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plugin/clockworksms/lib/clockworksms.lib.php b/plugin/clockworksms/lib/clockworksms.lib.php index daef0384fc..f42924233d 100755 --- a/plugin/clockworksms/lib/clockworksms.lib.php +++ b/plugin/clockworksms/lib/clockworksms.lib.php @@ -138,7 +138,8 @@ class Clockworksms implements SmsPluginLibraryInterface ) ); - if (empty($result)) { + //if (empty($result)) { + if (0) { $tpl->assign('message', ''); } else { $templatePath = 'clockworksms/sms_templates/'; From f1f820426f590b42c3fbea6877096cd2cc48e4f1 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 1 Apr 2015 14:33:37 +0200 Subject: [PATCH 037/159] Minor - fix icons. --- main/admin/course_request_accepted.php | 6 ++++-- main/admin/course_request_rejected.php | 6 +++--- main/admin/course_request_review.php | 4 ++-- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/main/admin/course_request_accepted.php b/main/admin/course_request_accepted.php index 35cc259023..e15b221273 100755 --- a/main/admin/course_request_accepted.php +++ b/main/admin/course_request_accepted.php @@ -126,8 +126,10 @@ function get_request_data($from, $number_of_items, $column, $direction) function modify_filter($id) { $code = CourseRequestManager::get_course_request_code($id); - $result = ''.Display::return_icon('edit.gif', get_lang('Edit'), array('style' => 'vertical-align: middle;')).''. - ' '.Display::return_icon('delete.gif', get_lang('DeleteThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ACourseRequestWillBeDeleted'), $code), ENT_QUOTES)).'\')) return false;')).''; + $result = ''. + Display::return_icon('edit.png', get_lang('Edit'), array('style' => 'vertical-align: middle;')).''. + ' '. + Display::return_icon('delete.png', get_lang('DeleteThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ACourseRequestWillBeDeleted'), $code), ENT_QUOTES)).'\')) return false;')).''; return $result; } diff --git a/main/admin/course_request_rejected.php b/main/admin/course_request_rejected.php index d780af15c6..5f8e20ff0e 100755 --- a/main/admin/course_request_rejected.php +++ b/main/admin/course_request_rejected.php @@ -148,12 +148,12 @@ function get_request_data($from, $number_of_items, $column, $direction) { */ function modify_filter($id) { $code = CourseRequestManager::get_course_request_code($id); - $result = ''.Display::return_icon('edit.gif', get_lang('Edit'), array('style' => 'vertical-align: middle;')).''. - ' '.Display::return_icon('action_accept.gif', get_lang('AcceptThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ANewCourseWillBeCreated'), $code), ENT_QUOTES)).'\')) return false;')).''; + $result = ''.Display::return_icon('edit.png', get_lang('Edit'), array('style' => 'vertical-align: middle;')).''. + ' '.Display::return_icon('accept.png', get_lang('AcceptThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ANewCourseWillBeCreated'), $code), ENT_QUOTES)).'\')) return false;')).''; if (!CourseRequestManager::additional_info_asked($id)) { $result .= ' '.Display::return_icon('request_info.gif', get_lang('AskAdditionalInfo'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('AdditionalInfoWillBeAsked'), $code), ENT_QUOTES)).'\')) return false;')).''; } - $result .= ' '.Display::return_icon('delete.gif', get_lang('DeleteThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ACourseRequestWillBeDeleted'), $code), ENT_QUOTES)).'\')) return false;')).''; + $result .= ' '.Display::return_icon('delete.png', get_lang('DeleteThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ACourseRequestWillBeDeleted'), $code), ENT_QUOTES)).'\')) return false;')).''; return $result; } diff --git a/main/admin/course_request_review.php b/main/admin/course_request_review.php index 3c02851924..886cc17a59 100755 --- a/main/admin/course_request_review.php +++ b/main/admin/course_request_review.php @@ -188,14 +188,14 @@ function email_filter($teacher) function modify_filter($id) { $code = CourseRequestManager::get_course_request_code($id); - $result = ''.Display::return_icon('edit.gif', get_lang('Edit'), array('style' => 'vertical-align: middle;')).''. + $result = ''.Display::return_icon('edit.png', get_lang('Edit'), array('style' => 'vertical-align: middle;')).''. ' '.Display::return_icon('accept.png', get_lang('AcceptThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ANewCourseWillBeCreated'), $code), ENT_QUOTES)).'\')) return false;'),16).''. ' '.Display::return_icon('error.png', get_lang('RejectThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ACourseRequestWillBeRejected'), $code), ENT_QUOTES)).'\')) return false;'),16).''; if (!CourseRequestManager::additional_info_asked($id)) { $result .= ' '.Display::return_icon('request_info.gif', get_lang('AskAdditionalInfo'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('AdditionalInfoWillBeAsked'), $code), ENT_QUOTES)).'\')) return false;')).''; } if (DELETE_ACTION_ENABLED) { - $result .= ' '.Display::return_icon('delete.gif', get_lang('DeleteThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ACourseRequestWillBeDeleted'), $code), ENT_QUOTES)).'\')) return false;')).''; + $result .= ' '.Display::return_icon('delete.png', get_lang('DeleteThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ACourseRequestWillBeDeleted'), $code), ENT_QUOTES)).'\')) return false;')).''; } return $result; From 5f46223f5267f7686e90d7ddd5ebcc5e42a28d34 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 2 Apr 2015 08:31:21 +0200 Subject: [PATCH 038/159] Remove unused tables #7597 --- index.php | 5 - main/inc/lib/database.constants.inc.php | 7 - main/inc/lib/stats.lib.inc.php | 593 ---------------------- main/inc/lib/tracking.lib.php | 3 - tests/main/inc/lib/stats.lib.inc.test.php | 157 ------ 5 files changed, 765 deletions(-) delete mode 100755 main/inc/lib/stats.lib.inc.php delete mode 100755 tests/main/inc/lib/stats.lib.inc.test.php diff --git a/index.php b/index.php index 62781c6f74..7c0a1cddc2 100755 --- a/index.php +++ b/index.php @@ -94,11 +94,6 @@ if (!empty($_POST['submitAuth'])) { Database::free_result($result_last_login); //Event::event_login(); - if (api_is_platform_admin()) { - // decode all open event informations and fill the track_c_* tables - include api_get_path(LIBRARY_PATH).'stats.lib.inc.php'; - decodeOpenInfos(); - } } // End login -- if ($_POST['submitAuth']) } else { diff --git a/main/inc/lib/database.constants.inc.php b/main/inc/lib/database.constants.inc.php index 29a94174b1..612d7abdc8 100755 --- a/main/inc/lib/database.constants.inc.php +++ b/main/inc/lib/database.constants.inc.php @@ -138,14 +138,7 @@ define('TABLE_STATISTIC_TRACK_E_DEFAULT', 'track_e_default'); define('TABLE_STATISTIC_TRACK_E_UPLOADS', 'track_e_uploads'); define('TABLE_STATISTIC_TRACK_E_HOTSPOT', 'track_e_hotspot'); define('TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY', 'track_e_item_property'); -define('TABLE_STATISTIC_TRACK_E_OPEN', 'track_e_open'); - define('TABLE_STATISTIC_TRACK_FILTERED_TERMS', 'track_filtered_terms'); -define('TABLE_STATISTIC_TRACK_C_BROWSERS', 'track_c_browsers'); -define('TABLE_STATISTIC_TRACK_C_COUNTRIES', 'track_c_countries'); -define('TABLE_STATISTIC_TRACK_C_OS', 'track_c_os'); -define('TABLE_STATISTIC_TRACK_C_PROVIDERS', 'track_c_providers'); -define('TABLE_STATISTIC_TRACK_C_REFERERS', 'track_c_referers'); //Course catalog stats see #4191 define('TABLE_STATISTIC_TRACK_COURSE_RANKING', 'track_course_ranking'); diff --git a/main/inc/lib/stats.lib.inc.php b/main/inc/lib/stats.lib.inc.php deleted file mode 100755 index 560bb305ed..0000000000 --- a/main/inc/lib/stats.lib.inc.php +++ /dev/null @@ -1,593 +0,0 @@ - - * @desc uses $TABLETRACK_OPEN to split recorded - information, to count occurences (for os, provider,...) - and to increment the number of occurrences of each - different element into the corresponding tables - */ -function decodeOpenInfos() { - global $TABLETRACK_OPEN; - // record initial value of ignore_user_abort - $ignore = ignore_user_abort(); - // prevent script from being stopped while executing, the following can be considered - // as a transaction - ignore_user_abort(1) ; - // we take the last event id to prevent miss of some recorded event - // only processed record have to be cleaned - $now = api_get_utc_datetime(); - $sql = "SELECT open_id - FROM $TABLETRACK_OPEN - WHERE open_date <= '$now' - ORDER BY open_id DESC - LIMIT 1"; - //$processBegin = StatsUtils::getOneResult($sql); - $query = Database::query($sql); - $res = @Database::fetch_array($query); - $processBegin = $res[0]; - // process - - //--Providers And Countries-------------------------------------------// - - $sql = "SELECT open_remote_host - FROM $TABLETRACK_OPEN - WHERE open_remote_host != '' - AND open_id <= '".$processBegin."' "; - $query = Database::query($sql); - - if(Database::num_rows($query) != 0) { - // load list of countries - $list_countries = loadCountries(); - - while ($row = Database::fetch_row ($query)) { - $remote_host = $row[0]; - /*****Provider*****/ - //extract provider - $provider = extractProvider( $remote_host ); - // add or increment provider in the providers array - $providers_array = addProvider( $provider,$providers_array ); - - /*****Countries*****/ - // extract country - $country = extractCountry( $remote_host, $list_countries ); - // increment country in the countries table - $countries_array = addCountry( $country, $countries_array ); - } - // update tables - fillProvidersTable( $providers_array ); - fillCountriesTable( $countries_array ); - } - // provider and countries done - //--Browsers and OS---------------------------------------------------// - $sql = "SELECT open_agent - FROM $TABLETRACK_OPEN - WHERE open_remote_host != '' - AND open_id <= '".$processBegin."' "; - $query =Database::query( $sql ); - if(Database::num_rows($query) != 0) { - // load lists - // of browsers - $list_browsers = loadBrowsers(); - // of OS - $list_os = loadOs(); - while ($row = Database::fetch_row ($query)) { - $agent = $row[0]; - /*****Browser and OS*****/ - // extract browser and OS - list( $browser,$os ) = split( "[|]",extractAgent( $agent , $list_browsers , $list_os ) ); - // increment browser and OS in the corresponding arrays - $browsers_array = addBrowser( $browser , $browsers_array ); - $os_array = addOs( $os , $os_array ); - } - fillBrowsersTable( $browsers_array ); - fillOsTable( $os_array ); - } - // browsers and OS done - - //--Referers----------------------------------------------------------// - - $sql = "SELECT open_referer - FROM $TABLETRACK_OPEN - WHERE open_referer != '' - AND open_id <= '".$processBegin."' "; - $query = Database::query( $sql ); - - if(Database::num_rows($query) != 0) { - $i=0; - while ($row = Database::fetch_row ($query)) { - $ref = $row[0]; - $referers_array = addReferer( $ref , $referers_array ); - } - fillReferersTable( $referers_array ); - } - // referers done - //-------------------------------------------------------------------// - // end of process - // cleaning of $TABLETRACK_OPEN table - cleanProcessedRecords($processBegin); - // reset to the initial value - ignore_user_abort($ignore); -} - -/* - * - * Utils - * - */ - -/** - * @author Sebastien Piraux - * @param limit : all records BEFORE $limit will be affected - * @desc this function will delete the remote_host, user_agent - and referer rows from the track_open table recorded before - the date $limit. OPTIMIZE is called to get back the memory - espaces deleted - */ -function cleanProcessedRecords( $limit ) { - global $TABLETRACK_OPEN; - $limit = Database::escape_string($limit); - $sql = "UPDATE $TABLETRACK_OPEN - SET open_remote_host = '', - open_agent = '', - open_referer ='' - WHERE open_id <= '".$limit."'"; - $query = Database::query( $sql ); - Database::query("OPTIMIZE TABLE $TABLETRACK_OPEN"); -} - -/** - * Provider - * - **/ - -/** - * @author Sebastien Piraux - * @param remhost : must be @getHostByAddr($_SERVER['REMOTE_ADDR'] - * @desc this function will extract the provider name from a given - remote host and record this occurence in the corresponding - table - */ -function extractProvider($remhost) { - if($remhost == "Unknown") - return $remhost; - $explodedRemhost = explode(".", $remhost); - $provider = $explodedRemhost[sizeof( $explodedRemhost )-2] - ."." - .$explodedRemhost[sizeof( $explodedRemhost )-1]; - - if($provider == "co.uk" || $provider == "co.jp") - return $explodedRemhost[sizeof( $explodedRemhost )-3].$provider; - else return $provider; -} - - -/** - * @author Sebastien Piraux - * @param provider : name of the provider - * @param providers_array : list of providers and their counter - * @desc this function will : - - if the provider is already in the array it will increment - the corresponding value - - if the provider doesn't exist it will be added and set to 1 - */ -function addProvider($provider,$providers_array) { - if(isset($providers_array[$provider])) { - // add one unity to this provider occurrences - $providers_array[$provider] = $providers_array[$provider] + 1; - } else { - // first occurrence of this provider - $providers_array[$provider] = 1; - } - return $providers_array; -} - -/** - * @author Sebastien Piraux - * @param providers_array : list of providers and their counter - * @desc update the providers'table with new values - */ -function fillProvidersTable($providers_array) { - global $TABLESTATS_PROVIDERS; - - if(is_array($providers_array)) { - foreach ( $providers_array as $prov=>$number ) { - $sql = "SELECT counter - FROM ".$TABLESTATS_PROVIDERS." - WHERE provider = '".$prov."'"; - $res = Database::query($sql); - - // if this provider already exists in the DB - if($row = Database::num_rows($res)) { - // update - $sql2 = "UPDATE $TABLESTATS_PROVIDERS - SET counter = counter + '$number' - WHERE provider = '".$prov."'"; - } else { - // insert - $sql2 = "INSERT INTO $TABLESTATS_PROVIDERS - (provider,counter) - VALUES ('".$prov."','".$number."')"; - } - Database::query($sql2);; - } - } -} - -/*************************************************************************** - * - * Country - * - ***************************************************************************/ - -/** - * @author Sebastien Piraux - * @return a 2D array filled with code and name of countries - * @desc This function is used to build an array containing - countries informations - */ -function loadCountries() { - global $TABLESTATS_COUNTRIES; - $sql = "SELECT code, country - FROM $TABLESTATS_COUNTRIES"; - $res = Database::query($sql); - $i = 0 ; - if (Database::num_rows($res) > 0){ - while ($row = Database::fetch_array($res)) { - $list_countries[$i][0] = $row["code"]; - $list_countries[$i][1] = $row["country"]; - $i++; - } - } - Database::free_result($res); - return $list_countries; -} - -/** - * @author Sebastien Piraux - * @param remhost : must be @getHostByAddr($_SERVER['REMOTE_ADDR'] - * @param list_countries : list of countries -__- - * @return Name of the country or "Unknown" if not found - * @desc this function will extract the country from a given remote - host and increment the good value in the corresponding table - */ -function extractCountry($remhost,$list_countries) { - if($remhost == "Unknown") - return $remhost; - // country code is the last value of remote host - $explodedRemhost = explode(".",$remhost); - $countryCode = $explodedRemhost[sizeof( $explodedRemhost )-1]; - for($i = 0 ; $i < sizeof( $list_countries );$i++) { - if($list_countries[$i][0] == $countryCode) - return $list_countries[$i][1]; - } -} - -/** - * @author Sebastien Piraux - * @param country : name of the country or 'Unknown' - * @param countries_array : list of countries and their - number of occurence - * @desc this function will increment number of occurrence - for $country in the countries' tables - */ -function addCountry($country,$countries_array) { - if(isset($countries_array[$country])) { - // add one unity to this provider occurrences - $countries_array[$country] = $countries_array[$country] + 1; - } else { - // first occurrence of this provider - $countries_array[$country] = 1; - } - return $countries_array; -} - -/** - * @author Sebastien Piraux - * @param countries_array : list of countries and their counter - * @desc update the countries'table with new values - */ -function fillCountriesTable($countries_array) { - global $TABLESTATS_COUNTRIES; - if(is_array($countries_array)) { - foreach ( $countries_array as $country=>$number ) { - // update - $sql = "UPDATE $TABLESTATS_COUNTRIES - SET counter = counter + '$number' - WHERE country = '".$country."'"; - Database::query($sql); - } - } -} - -/*************************************************************************** - * - * Agent : Browser and OS - * - ***************************************************************************/ - -/** - * @author Sebastien Piraux - * @return a 2D array filled with code and name of browsers - * @desc This function is used to build an array containing - browser informations - */ -function loadBrowsers() { - - $buffer = split ("#","Gecko|Gecko#Mozilla/3|Mozilla 3.x#Mozilla/4.0|Mozilla 4.0x#Mozilla/4.5|Mozilla 4.5x#Mozilla/4.6|Mozilla 4.6x#Mozilla/4.7|Mozilla 4.7x#Mozilla/5.0|Mozilla 5.0x#MSIE 1.2|MSIE 1.2#MSIE 3.01|MSIE 3.x#MSIE 3.02|MSIE 3.x#MSIE 4.0|MSIE 4.x#MSIE 4.01|MSIE 4.x#MSIE 4.5|MSIE 4.5#MSIE 5.0b1|MSIE 5.0x#MSIE 5.0b2|MSIE 5.0x#MSIE 5.0|MSIE 5.0x#MSIE 5.01|MSIE 5.0x#MSIE 5.1|MSIE 5.1#MSIE 5.1b1|MSIE 5.1#MSIE 5.5|MSIE 5.5#MSIE 5.5b1|MSIE 5.5#MSIE 5.5b2|MSIE 5.5#MSIE 6.0|MSIE 6#MSIE 6.0b|MSIE 6#MSIE 6.5a|MSIE 6.5#Lynx/2.8.0|Lynx 2#Lynx/2.8.1|Lynx 2#Lynx/2.8.2|Lynx 2#Lynx/2.8.3|Lynx 2#Lynx/2.8.4|Lynx 2#Lynx/2.8.5|Lynx 2#HTTrack 3.0x|HTTrack#OmniWeb/4.0.1|OmniWeb#Opera 3.60|Opera 3.60#Opera 4.0|Opera 4#Opera 4.01|Opera 4#Opera 4.02|Opera 4#Opera 5|Opera 5#Opera/3.60|Opera 3.60#Opera/4|Opera 4#Opera/5|Opera 5#Opera/6|Opera 6#Opera 6|Opera 6#Netscape6|NS 6#Netscape/6|NS 6#Netscape7|NS 7#Netscape/7|NS 7#Konqueror/2.0|Konqueror 2#Konqueror/2.0.1|Konqueror 2#Konqueror/2.1|Konqueror 2#Konqueror/2.1.1|Konqueror 2#Konqueror/2.1.2|Konqueror 2#Konqueror/2.2|Konqueror 2#Teleport Pro|Teleport Pro#WebStripper|WebStripper#WebZIP|WebZIP#Netcraft Web|NetCraft#Googlebot|Googlebot#WebCrawler|WebCrawler#InternetSeer|InternetSeer#ia_archiver|ia archiver"); - - //$list_browser[x][0] is the name of browser as in $_SERVER['HTTP_USER_AGENT'] - //$list_browser[x][1] is the name of browser that will be used in display and tables - $i=0; - foreach( $buffer as $buffer1 ) { - list ( $list_browsers[$i][0], $list_browsers[$i][1]) = split ('[|]', $buffer1 ); - $i++; - } - return $list_browsers; -} - -/** - * @author Sebastien Piraux - * @return a 2D array filled with code and name of OS - * @desc This function is used to build an array containing - OS informations - */ -function loadOs() { - $buffer = split ("#","Windows 95|Win 95#Windows_95|Win 95#Windows 98|Win 98#Windows NT|Win NT#Windows NT 5.0|Win 2000#Windows NT 5.1|Win XP#Windows 2000|Win 2000#Windows XP|Win XP#Windows ME|Win Me#Win95|Win 95#Win98|Win 98#WinNT|Win NT#linux-2.2|Linux 2#Linux|Linux#Linux 2|Linux 2#Macintosh|Mac#Mac_PPC|Mac#Mac_PowerPC|Mac#SunOS 5|SunOS 5#SunOS 6|SunOS 6#FreeBSD|FreeBSD#beOS|beOS#InternetSeer|InternetSeer#Googlebot|Googlebot#Teleport Pro|Teleport Pro"); - $i=0; - foreach( $buffer as $buffer1 ) { - list ( $list_os[$i][0], $list_os[$i][1]) = split ('[|]', $buffer1 ); - $i+=1; - } - return $list_os; -} - -/** - * @author Sebastien Piraux - * @param remhost : must be $_SERVER['HTTP_USER_AGENT'] - * @param list_browsers : browsers list :x - * @param list_os : os list :x - * @return a string formatted like : browser|OS - browser and OS are the 'viewable' names - * @desc this function will extract browser and OS from - $_SERVER['HTTP_USER_AGENT'] - */ -function extractAgent( $user_agent, $list_browsers, $list_os ) { - // default values, if nothing corresponding found - $viewable_browser = "Unknown"; - $viewable_os = "Unknown"; - - // search for corresponding pattern in $_SERVER['HTTP_USER_AGENT'] - // for browser - for($i = 0; $i < count( $list_browsers ); $i++) { - $pos = strpos( $user_agent, $list_browsers[$i][0] ); - if( $pos !== false ) { - $viewable_browser = $list_browsers[$i][1]; - } - } - - // for os - for($i = 0; $i < count($list_os); $i++) { - $pos = strpos( $user_agent, $list_os[$i][0] ); - if( $pos !== false ) { - $viewable_os = $list_os[$i][1]; - } - } - return $viewable_browser."|".$viewable_os; - -} - -/** - * @author Sebastien Piraux - * @param browser : name of the browser or 'Unknown' - * @param browsers_array : - * @desc this function will : - - if the browser is already in the table it will increment - the corresponding value - - if the browser doesn't exist it will be added and set to 1 - */ -function addBrowser($browser,$browsers_array) { - if(isset( $browsers_array[$browser])) { - // add one unity to this provider occurrences - $browsers_array[$browser] = $browsers_array[$browser] + 1; - } else { - // first occurrence of this provider - $browsers_array[$browser] = 1; - } - return $browsers_array; -} - -/** - * @author Sebastien Piraux - * @param os : name of the OS or 'Unknown' - * @param os_array : list of os and number of occurences - * @desc this function will : - - if the os is already in the table it will increment - the corresponding value - - if the os doesn't exist it will be added and set to 1 - */ -function addOs($os,$os_array) { - if(isset($os_array[$os])) { - // add one unity to this provider occurrences - $os_array[$os] = $os_array[$os] + 1; - } else { - // first occurrence of this provider - $os_array[$os] = 1; - } - return $os_array; -} - -/** - * @author Sebastien Piraux - * @param browsers_array : list of browsers and their counter - * @desc update the browsers'table with new values - */ -function fillBrowsersTable($browsers_array) { - global $TABLESTATS_BROWSERS; - if (is_array($browsers_array)) { - foreach ( $browsers_array as $browser=>$number ) { - $sql = "SELECT counter - FROM $TABLESTATS_BROWSERS - WHERE browser = '".$browser."'"; - $res = Database::query($sql); - - // if this provider already exists in the DB - if($row = Database::num_rows($res)) { - // update - $sql2 = "UPDATE $TABLESTATS_BROWSERS - SET counter = counter + '$number' - WHERE browser = '".$browser."'"; - } else { - // insert - $sql2 = "INSERT INTO $TABLESTATS_BROWSERS - (browser,counter) - VALUES ('".$browser."','".$number."')"; - } - Database::query($sql2); - } - } -} - -/** - * @author Sebastien Piraux - * @param os_array : list of os and their counter - * @desc update the os'table with new values - */ -function fillOsTable($os_array) { - global $TABLESTATS_OS; - if (is_array($os_array)) { - foreach ($os_array as $os=>$number) { - $sql = "SELECT counter - FROM $TABLESTATS_OS - WHERE os = '".$os."'"; - $res = Database::query($sql); - - // if this provider already exists in the DB - if($row = Database::num_rows($res)) { - // update - $sql2 = "UPDATE $TABLESTATS_OS - SET counter = counter + '$number' - WHERE os = '".$os."'"; - } else { - // insert - $sql2 = "INSERT INTO $TABLESTATS_OS - (os,counter) - VALUES ('".$os."','".$number."')"; - } - Database::query($sql2); - } - } -} - -/*************************************************************************** - * - * Referers - * - ***************************************************************************/ - -/** - * @author Sebastien Piraux - * @param referer : name of the referer - * @param referers_array : list of referer and number of occurences - * @desc this function will : - - if the referer is already in the table it will increment - the corresponding value - - if the referer doesn't exist it will be added and set to 1 -*/ -function addReferer($referer,$referers_array) { - if(isset($referers_array[$referer])) { - // add one unity to this provider occurrences - $referers_array[$referer] = $referers_array[$referer] + 1; - } else { - // first occurrence of this provider - $referers_array[$referer] = 1; - } - return $referers_array; -} - -/** - * @author Sebastien Piraux - * @param referers_array : list of referers and their counter - * @desc update the referers'table with new values -*/ -function fillReferersTable($referers_array) { - global $TABLESTATS_REFERERS; - if (is_array($referers_array)) { - foreach ( $referers_array as $referer=>$number ) { - $sql = "SELECT counter - FROM $TABLESTATS_REFERERS - WHERE referer = '".$referer."'"; - $res = Database::query($sql); - - // if this provider already exists in the DB - if($row = Database::num_rows($res)) { - // update - $sql2 = "UPDATE $TABLESTATS_REFERERS - SET counter = counter + '$number' - WHERE referer = '".$referer."'"; - } else { - // insert - $sql2 = "INSERT INTO $TABLESTATS_REFERERS - (referer,counter) - VALUES ('".$referer."','".$number."')"; - } - Database::query($sql2); - } - } -} diff --git a/main/inc/lib/tracking.lib.php b/main/inc/lib/tracking.lib.php index 3edecf8e47..6a8267bc2d 100755 --- a/main/inc/lib/tracking.lib.php +++ b/main/inc/lib/tracking.lib.php @@ -3766,9 +3766,6 @@ class Tracking 'user' => 'upload_user_id', 'start_date'=> 'upload_date', ), - #TABLE_STATISTIC_TRACK_E_HOTSPOT, - #TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY, - #TABLE_STATISTIC_TRACK_E_OPEN, ); $error_sql = ''; diff --git a/tests/main/inc/lib/stats.lib.inc.test.php b/tests/main/inc/lib/stats.lib.inc.test.php deleted file mode 100755 index b0c66b6f0a..0000000000 --- a/tests/main/inc/lib/stats.lib.inc.test.php +++ /dev/null @@ -1,157 +0,0 @@ -UnitTestCase('System stats library - main/inc/lib/stats.lib.test.php'); - } - - function testaddBrowser() { - $browser=''; - $browsers_array=array(); - $res=addBrowser($browser,$browsers_array); - $this->assertTrue(is_array($res)); - } - - function testaddCountry(){ - $country=''; - $countries_array=array(); - $res=addCountry($country,$countries_array); - $this->assertTrue(is_array($res)); - //var_dump($res); - } - - function testaddOs() { - $os=''; - $os_array=array(); - $res=addOs($os,$os_array); - $this->assertTrue(is_array($res)); - //var_dump($res); - } - - function testaddProvider() { - $provider=''; - $providers_array=array(); - $res=addProvider($provider,$providers_array); - $this->assertTrue(is_array($res)); - //var_dump($res); - } - - function testaddReferer() { - $referer=''; - $referers_array=array(); - $res=addReferer($referer,$referers_array); - $this->assertTrue(is_array($res)); - //var_dump($res); - } - - function testcleanProcessedRecords() { - global $TABLETRACK_OPEN; - $limit=''; - $res=cleanProcessedRecords($limit); - if(!is_null($res)) $this->assertTrue(is_string($res)); - //var_dump($res); - } - - function testdecodeOpenInfos() { // 3 excepciones - //ob_start(); - global $_course, $TABLETRACK_OPEN, $_configuration; - $TABLETRACK_OPEN = $_configuration['statistics_database'].".track_e_open"; - $ignore = ignore_user_abort(); - $res=decodeOpenInfos(); - //ob_end_clean(); - if (!is_null($res)){ - $this->assertTrue(is_null($res)); - $this->assertTrue(is_numeric($ignore)); - //var_dump($res); - } - } - - function testextractAgent() { - $user_agent=$_SERVER['HTTP_USER_AGENT']; - $list_browsers=array(); - $list_os=array(); - $res=extractAgent($user_agent, $list_browsers, $list_os ); - $this->assertTrue(is_string($res)); - //var_dump($res); - } - - function testextractCountry() { - $remhost= @getHostByAddr($_SERVER['REMOTE_ADDR']); - $list_countries=array(); - $res=extractCountry($remhost,$list_countries); - if(!is_null($res))$this->assertTrue(is_string($res)); - //var_dump($res); - } - - function testextractProvider() { - $remhost=@getHostByAddr($_SERVER['REMOTE_ADDR']); - $res=extractProvider($remhost); - if(!is_null($res))$this->assertTrue(is_string($res)); - //var_dump($res); - } - - function testfillBrowsersTable() { - global $TABLESTATS_BROWSERS; - $browsers_array=array(); - $res=fillBrowsersTable($browsers_array); - if(!is_null($res)) $this->assertTrue(is_array($res)); - //var_dump($res); - } - - function testfillCountriesTable() { - global $TABLESTATS_COUNTRIES,$_configuration; - $TABLESTATS_COUNTRIES = $_configuration['statistics_database'].".track_c_countries"; - $countries_array=array(); - $res=fillCountriesTable($countries_array); - $this->assertTrue(is_null($res)); - //var_dump($res); - } - - function testfillOsTable() { - global $TABLESTATS_OS; - $os_array=array(); - $res=fillOsTable($os_array); - $this->assertTrue(is_null($res)); - //var_dump($res); - } - - function testfillProvidersTable() { - global $TABLESTATS_PROVIDERS; - $providers_array=array(); - $res=fillProvidersTable($providers_array); - $this->assertTrue(is_null($res)); - //var_dump($res); - } - - function testfillReferersTable() { - global $TABLESTATS_REFERERS; - $referers_array=array(); - $res=fillReferersTable($referers_array); - $this->assertTrue(is_null($res)); - //var_dump($res); - } - - function testloadBrowsers() { - $res=loadBrowsers(); - $this->assertTrue(is_array($res)); - //var_dump($res); - } - - function testloadCountries() { - global $TABLESTATS_COUNTRIES,$_configuration; - $TABLESTATS_COUNTRIES = $_configuration['statistics_database'].".track_c_countries"; - $res=loadCountries(); - if (!is_null($res)){ - $this->assertTrue(is_array($res)); - } - //var_dump($res); - } - - function testloadOs() { - $res=loadOs(); - $this->assertTrue(is_array($res)); - //var_dump($res); - } -} -?> From cb9e5d7b00884912f02ba12e046b3ec0d54359e5 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 2 Apr 2015 12:06:57 +0200 Subject: [PATCH 039/159] Add isAdmin option. --- main/admin/user_add.php | 6 ++--- main/inc/lib/usermanager.lib.php | 42 +++++++++++++++++++------------- 2 files changed, 27 insertions(+), 21 deletions(-) diff --git a/main/admin/user_add.php b/main/admin/user_add.php index 23588d62b5..4141875381 100755 --- a/main/admin/user_add.php +++ b/main/admin/user_add.php @@ -339,7 +339,8 @@ if( $form->validate()) { $hr_dept_id, $extra, null, - $send_mail + $send_mail, + $platform_admin ); Security::clear_token(); @@ -379,9 +380,6 @@ if( $form->validate()) { foreach ($extra as $key => $value) { UserManager::update_extra_field_value($user_id, $key, $value); } - if ($platform_admin) { - UserManager::add_user_as_admin($user_id); - } $message = get_lang('UserAdded'); } if (isset($user['submit_plus'])) { diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php index f233324f94..292b84c20c 100755 --- a/main/inc/lib/usermanager.lib.php +++ b/main/inc/lib/usermanager.lib.php @@ -44,22 +44,25 @@ class UserManager * Creates a new user for the platform * @author Hugues Peeters , * @author Roan Embrechts - * @param string Firstname - * @param string Lastname - * @param int Status (1 for course tutor, 5 for student, 6 for anonymous) - * @param string e-mail address - * @param string Login - * @param string Password - * @param string Any official code (optional) - * @param string User language (optional) - * @param string Phone number (optional) - * @param string Picture URI (optional) - * @param string Authentication source (optional, defaults to 'platform', dependind on constant) - * @param string Account expiration date (optional, defaults to null) - * @param int Whether the account is enabled or disabled by default - * @param int The department of HR in which the user is registered (optional, defaults to 0) - * @param array Extra fields - * @param string Encrypt method used if password is given encrypted. Set to an empty string by default + * @param string Firstname + * @param string Lastname + * @param int Status (1 for course tutor, 5 for student, 6 for anonymous) + * @param string e-mail address + * @param string Login + * @param string Password + * @param string Any official code (optional) + * @param string User language (optional) + * @param string Phone number (optional) + * @param string Picture URI (optional) + * @param string Authentication source (optional, defaults to 'platform', dependind on constant) + * @param string Account expiration date (optional, defaults to null) + * @param int Whether the account is enabled or disabled by default + * @param int The department of HR in which the user is registered (optional, defaults to 0) + * @param array Extra fields + * @param string Encrypt method used if password is given encrypted. Set to an empty string by default + * @param bool $send_mail + * @param bool $isAdmin + * * @return mixed new user id - if the new user creation succeeds, false otherwise * @desc The function tries to retrieve user id from the session. * If it exists, the current user id is the creator id. If a problem arises, @@ -84,7 +87,8 @@ class UserManager $hr_dept_id = 0, $extra = null, $encrypt_method = '', - $send_mail = false + $send_mail = false, + $isAdmin = false ) { $currentUserId = api_get_user_id(); $hook = HookCreateUser::create(); @@ -206,6 +210,10 @@ class UserManager $sql = "UPDATE $table_user SET user_id = $return WHERE id = $return"; Database::query($sql); + if ($isAdmin) { + UserManager::add_user_as_admin($userId); + } + if (api_get_multiple_access_url()) { UrlManager::add_user_to_url($return, api_get_current_access_url_id()); } else { From a41da17ef15c0e4a5c7e85ef2f25f6162ae77dbb Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 2 Apr 2015 13:37:23 +0200 Subject: [PATCH 040/159] Remove unused file. --- main/install/country_data.csv | 264 ---------------------------------- 1 file changed, 264 deletions(-) delete mode 100755 main/install/country_data.csv diff --git a/main/install/country_data.csv b/main/install/country_data.csv deleted file mode 100755 index 749c097860..0000000000 --- a/main/install/country_data.csv +++ /dev/null @@ -1,264 +0,0 @@ -1,'ac','Ascension (ile)',0,, -2,'ad','Andorre',0, -3,'ae','Emirats Arabes Unis',0, -4,'af','Afghanistan',0, -5,'ag','Antigua et Barbuda',0, -6,'ai','Anguilla',0, -7,'al','Albanie',0, -8,'am','Arménie',0, -9,'an','Antilles Neerlandaises',0, -10,'ao','Angola',0, -11,'aq','Antarctique',0, -12,'ar','Argentine',0, -13,'as','American Samoa',0, -14,'au','Australie',0, -15,'aw','Aruba',0, -16,'az','Azerbaijan',0, -17,'ba','Bosnie Herzegovine',0, -18,'bb','Barbade',0, -19,'bd','Bangladesh',0, -20,'be','Belgique',0, -21,'bf','Burkina Faso',0, -22,'bg','Bulgarie',0, -23,'bh','Bahrain',0, -24,'bi','Burundi',0, -25,'bj','Benin',0, -26,'bm','Bermudes',0, -27,'bn','Brunei Darussalam',0, -28,'bo','Bolivie',0, -29,'br','Brésil',0, -30,'bs','Bahamas',0, -31,'bt','Bhoutan',0, -32,'bv','Bouvet (ile)',0, -33,'bw','Botswana',0, -34,'by','Biélorussie',0, -35,'bz','Bélize',0, -36,'ca','Canada',0, -37,'cc','Cocos (Keeling) iles',0, -38,'cd','Congo,(République démocratique du)',0, -39,'cf','Centrafricaine (République )',0, -40,'cg','Congo',0, -41,'ch','Suisse',0, -42,'ci','Cote d\'Ivoire',0, -43,'ck','Cook (iles)',0, -44,'cl','Chili',0, -45,'cm','Cameroun',0, -46,'cn','Chine',0, -47,'co','Colombie',0, -48,'cr','Costa Rica',0, -49,'cu','Cuba',0, -50,'cv','Cap Vert',0, -51,'cx','Christmas (ile)',0, -52,'cy','Chypre',0, -53,'cz','Tchéque (République)',0, -54,'de','Allemagne',0, -55,'dj','Djibouti',0, -56,'dk','Danemark',0, -57,'dm','Dominique',0, -58,'do','Dominicaine (république)',0, -59,'dz','Algérie',0, -60,'ec','Equateur',0, -61,'ee','Estonie',0, -62,'eg','Egypte',0, -63,'eh','Sahara Occidental',0, -64,'er','Erythrée',0, -65,'es','Espagne',0, -66,'et','Ethiopie',0, -67,'fi','Finlande',0, -68,'fj','Fiji',0, -69,'fk','Falkland (Malouines) iles',0, -70,'fm','Micronésie',0, -71,'fo','Faroe (iles)',0, -72,'fr','France',0, -73,'ga','Gabon',0, -74,'gd','Grenade',0, -75,'ge','Géorgie',0, -76,'gf','Guyane Française',0, -77,'gg','Guernsey',0, -78,'gh','Ghana',0, -79,'gi','Gibraltar',0, -80,'gl','Groenland',0, -81,'gm','Gambie',0, -82,'gn','Guinée',0, -83,'gp','Guadeloupe',0, -84,'gq','Guinée Equatoriale',0, -85,'gr','Grèce',0, -86,'gs','Georgie du sud et iles Sandwich du sud',0, -87,'gt','Guatemala',0, -88,'gu','Guam',0, -89,'gw','Guinée-Bissau',0, -90,'gy','Guyana',0, -91,'hk','Hong Kong',0, -92,'hm','Heard et McDonald (iles)',0, -93,'hn','Honduras',0, -94,'hr','Croatie',0, -95,'ht','Haiti',0, -96,'hu','Hongrie',0, -97,'id','Indonésie',0, -98,'ie','Irlande',0, -99,'il','Israël',0, -100,'im','Ile de Man',0, -101,'in','Inde',0, -102,'io','Territoire Britannique de l\'Océan Indien',0, -103,'iq','Iraq',0, -104,'ir','Iran',0, -105,'is','Islande',0, -106,'it','Italie',0, -107,'je','Jersey',0, -108,'jm','Jamaïque',0, -109,'jo','Jordanie',0, -110,'jp','Japon',0, -111,'ke','Kenya',0, -112,'kg','Kirgizstan',0, -113,'kh','Cambodge',0, -114,'ki','Kiribati',0, -115,'km','Comores',0, -116,'kn','Saint Kitts et Nevis',0, -117,'kp','Corée du nord',0, -118,'kr','Corée du sud',0, -119,'kw','Koweït',0, -120,'ky','Caïmanes (iles)',0, -121,'kz','Kazakhstan',0, -122,'la','Laos',0, -123,'lb','Liban',0, -124,'lc','Sainte Lucie',0, -125,'li','Liechtenstein',0, -126,'lk','Sri Lanka',0, -127,'lr','Liberia',0, -128,'ls','Lesotho',0, -129,'lt','Lituanie',0, -130,'lu','Luxembourg',0, -131,'lv','Latvia',0, -132,'ly','Libyan Arab Jamahiriya',0, -133,'ma','Maroc',0, -134,'mc','Monaco',0, -135,'md','Moldavie',0, -136,'mg','Madagascar',0, -137,'mh','Marshall (iles)',0, -138,'mk','Macédoine',0, -139,'ml','Mali',0, -140,'mm','Myanmar',0, -141,'mn','Mongolie',0, -142,'mo','Macao',0, -143,'mp','Mariannes du nord (iles)',0, -144,'mq','Martinique',0, -145,'mr','Mauritanie',0, -146,'ms','Montserrat',0, -147,'mt','Malte',0, -148,'mu','Maurice (ile)',0, -149,'mv','Maldives',0, -150,'mw','Malawi',0, -151,'mx','Mexique',0, -152,'my','Malaisie',0, -153,'mz','Mozambique',0, -154,'na','Namibie',0, -155,'nc','Nouvelle Calédonie',0, -156,'ne','Niger',0, -157,'nf','Norfolk (ile)',0, -158,'ng','Nigéria',0, -159,'ni','Nicaragua',0, -160,'nl','Pays Bas',0, -161,'no','Norvège',0, -162,'np','Népal',0, -163,'nr','Nauru',0, -164,'nu','Niue',0, -165,'nz','Nouvelle Zélande',0, -166,'om','Oman',0, -167,'pa','Panama',0, -168,'pe','Pérou',0, -169,'pf','Polynésie Française',0, -170,'pg','Papouasie Nouvelle Guinée',0, -171,'ph','Philippines',0, -172,'pk','Pakistan',0, -173,'pl','Pologne',0, -174,'pm','St. Pierre et Miquelon',0, -175,'pn','Pitcairn (ile)',0, -176,'pr','Porto Rico',0, -177,'pt','Portugal',0, -178,'pw','Palau',0, -179,'py','Paraguay',0, -180,'qa','Qatar',0, -181,'re','Réunion (ile de la)',0, -182,'ro','Roumanie',0, -183,'ru','Russie',0, -184,'rw','Rwanda',0, -185,'sa','Arabie Saoudite',0, -186,'sb','Salomon (iles)',0, -187,'sc','Seychelles',0, -188,'sd','Soudan',0, -189,'se','Suède',0, -190,'sg','Singapour',0, -191,'sh','St. Hélène',0, -192,'si','Slovénie',0, -193,'sj','Svalbard et Jan Mayen (iles)',0, -194,'sk','Slovaquie',0, -195,'sl','Sierra Leone',0, -196,'sm','Saint Marin',0, -197,'sn','Sénégal',0, -198,'so','Somalie',0, -199,'sr','Suriname',0, -200,'st','Sao Tome et Principe',0, -201,'sv','Salvador',0, -202,'sy','Syrie',0, -203,'sz','Swaziland',0, -204,'tc','Turks et Caïques (iles)',0, -205,'td','Tchad',0, -206,'tf','Territoires Français du sud',0, -207,'tg','Togo',0, -208,'th','Thailande',0, -209,'tj','Tajikistan',0, -210,'tk','Tokelau',0, -211,'tm','Turkménistan',0, -212,'tn','Tunisie',0, -213,'to','Tonga',0, -214,'tp','Timor Oriental',0, -215,'tr','Turquie',0, -216,'tt','Trinidad et Tobago',0, -217,'tv','Tuvalu',0, -218,'tw','Taiwan',0, -219,'tz','Tanzanie',0, -220,'ua','Ukraine',0, -221,'ug','Ouganda',0, -222,'uk','Royaume Uni',0, -223,'gb','Royaume Uni',0, -224,'um','US Minor Outlying (iles)',0, -225,'us','Etats Unis',0, -226,'uy','Uruguay',0, -227,'uz','Ouzbékistan',0, -228,'va','Vatican',0, -229,'vc','Saint Vincent et les Grenadines',0, -230,'ve','Venezuela',0, -231,'vg','Vierges Britaniques (iles)',0, -232,'vi','Vierges USA (iles)',0, -233,'vn','Viêt Nam',0, -234,'vu','Vanuatu',0, -235,'wf','Wallis et Futuna (iles)',0, -236,'ws','Western Samoa',0, -237,'ye','Yemen',0, -238,'yt','Mayotte',0, -239,'yu','Yugoslavie',0, -240,'za','Afrique du Sud',0, -241,'zm','Zambie',0, -242,'zr','Zaïre',0, -243,'zw','Zimbabwe',0, -244,'com','.COM',0, -245,'net','.NET',0, -246,'org','.ORG',0, -247,'edu','Education',0, -248,'int','.INT',0, -249,'arpa','.ARPA',0, -250,'at','Autriche',0, -251,'gov','Gouvernement',0, -252,'mil','Militaire',0, -253,'su','Ex U.R.S.S.',0, -254,'reverse','Reverse',0, -255,'biz','Businesses',0, -256,'info','.INFO',0, -257,'name','.NAME',0, -258,'pro','.PRO',0, -259,'coop','.COOP',0, -260,'aero','.AERO',0, -261,'museum','.MUSEUM',0, -262,'tv','.TV',0, -263,'ws','Web site',0, -264,'--','Unknown',0, \ No newline at end of file From a2f08ce50ef1fe2ebb24d5a0cef05a7c396bfacd Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 2 Apr 2015 13:38:15 +0200 Subject: [PATCH 041/159] Use doctrine entities to create Database. --- main/inc/lib/database.lib.php | 18 + main/install/data.sql | 150 +++ main/install/index.php | 295 +++--- main/install/install.lib.php | 743 ++++++++++++-- main/install/install_db.inc.php | 36 +- .../CoreBundle/Entity/AccessUrlRelSession.php | 80 ++ .../CoreBundle/Entity/AccessUrlRelUser.php | 80 ++ src/Chamilo/CoreBundle/Entity/Admin.php | 65 ++ .../Entity/AnnouncementRelGroup.php | 80 ++ src/Chamilo/CoreBundle/Entity/Block.php | 185 ++++ .../CoreBundle/Entity/CourseCategory.php | 245 +++++ src/Chamilo/CoreBundle/Entity/CourseField.php | 305 ++++++ .../CoreBundle/Entity/CourseFieldOptions.php | 185 ++++ .../CoreBundle/Entity/CourseFieldValues.php | 155 +++ .../CoreBundle/Entity/CourseModule.php | 215 ++++ .../CoreBundle/Entity/CourseRelClass.php | 80 ++ .../CoreBundle/Entity/CourseRelUser.php | 2 +- .../CoreBundle/Entity/CourseRequest.php | 515 ++++++++++ src/Chamilo/CoreBundle/Entity/CourseType.php | 155 +++ .../CoreBundle/Entity/EventEmailTemplate.php | 185 ++++ src/Chamilo/CoreBundle/Entity/EventSent.php | 125 +++ .../CoreBundle/Entity/GradeComponents.php | 155 +++ src/Chamilo/CoreBundle/Entity/GradeModel.php | 185 ++++ .../CoreBundle/Entity/GradebookCategory.php | 455 +++++++++ .../Entity/GradebookCertificate.php | 185 ++++ .../CoreBundle/Entity/GradebookEvaluation.php | 365 +++++++ .../CoreBundle/Entity/GradebookLink.php | 305 ++++++ .../Entity/GradebookLinkevalLog.php | 275 ++++++ .../CoreBundle/Entity/GradebookResult.php | 155 +++ .../CoreBundle/Entity/GradebookResultLog.php | 185 ++++ .../Entity/GradebookScoreDisplay.php | 155 +++ .../CoreBundle/Entity/GroupRelGroup.php | 125 +++ src/Chamilo/CoreBundle/Entity/GroupRelTag.php | 95 ++ .../CoreBundle/Entity/GroupRelUser.php | 125 +++ src/Chamilo/CoreBundle/Entity/Groups.php | 245 +++++ src/Chamilo/CoreBundle/Entity/HookCall.php | 185 ++++ src/Chamilo/CoreBundle/Entity/HookEvent.php | 95 ++ .../CoreBundle/Entity/HookObserver.php | 125 +++ src/Chamilo/CoreBundle/Entity/Language.php | 214 ++++ src/Chamilo/CoreBundle/Entity/Legal.php | 230 +++++ src/Chamilo/CoreBundle/Entity/Message.php | 305 ++++++ .../CoreBundle/Entity/MessageAttachment.php | 185 ++++ .../CoreBundle/Entity/Notification.php | 245 +++++ .../CoreBundle/Entity/OpenidAssociation.php | 245 +++++ .../CoreBundle/Entity/PersonalAgenda.php | 275 ++++++ .../Entity/PersonalAgendaRepeat.php | 155 +++ .../Entity/PersonalAgendaRepeatNot.php | 80 ++ src/Chamilo/CoreBundle/Entity/PhpSession.php | 155 +++ src/Chamilo/CoreBundle/Entity/Promotion.php | 215 ++++ .../CoreBundle/Entity/SearchEngineRef.php | 185 ++++ .../CoreBundle/Entity/SessionField.php | 305 ++++++ .../CoreBundle/Entity/SessionFieldOptions.php | 185 ++++ .../CoreBundle/Entity/SessionFieldValues.php | 155 +++ .../CoreBundle/Entity/SettingsCurrent.php | 395 ++++++++ .../CoreBundle/Entity/SettingsOptions.php | 125 +++ .../CoreBundle/Entity/SharedSurvey.php | 335 +++++++ .../Entity/SharedSurveyQuestion.php | 275 ++++++ .../Entity/SharedSurveyQuestionOption.php | 155 +++ src/Chamilo/CoreBundle/Entity/Skill.php | 215 ++++ .../CoreBundle/Entity/SkillProfile.php | 95 ++ .../CoreBundle/Entity/SkillRelGradebook.php | 125 +++ .../CoreBundle/Entity/SkillRelProfile.php | 95 ++ .../CoreBundle/Entity/SkillRelSkill.php | 155 +++ .../CoreBundle/Entity/SkillRelUser.php | 215 ++++ .../CoreBundle/Entity/SpecificField.php | 95 ++ .../CoreBundle/Entity/SpecificFieldValues.php | 185 ++++ .../CoreBundle/Entity/SysAnnouncement.php | 305 ++++++ src/Chamilo/CoreBundle/Entity/SysCalendar.php | 215 ++++ .../CoreBundle/Entity/SystemTemplate.php | 155 +++ src/Chamilo/CoreBundle/Entity/Tag.php | 125 +++ src/Chamilo/CoreBundle/Entity/Templates.php | 215 ++++ .../CoreBundle/Entity/TrackCBrowsers.php | 95 ++ .../CoreBundle/Entity/TrackCCountries.php | 125 +++ src/Chamilo/CoreBundle/Entity/TrackCOs.php | 95 ++ .../CoreBundle/Entity/TrackCProviders.php | 95 ++ .../CoreBundle/Entity/TrackCReferers.php | 95 ++ .../CoreBundle/Entity/TrackCourseRanking.php | 245 +++++ .../CoreBundle/Entity/TrackEAccess.php | 215 ++++ .../CoreBundle/Entity/TrackEAttempt.php | 395 ++++++++ .../CoreBundle/Entity/TrackEAttemptCoeff.php | 95 ++ .../Entity/TrackEAttemptRecording.php | 245 +++++ .../CoreBundle/Entity/TrackECourseAccess.php | 245 +++++ .../CoreBundle/Entity/TrackEDefault.php | 245 +++++ .../CoreBundle/Entity/TrackEDownloads.php | 185 ++++ .../CoreBundle/Entity/TrackEExercises.php | 575 +++++++++++ .../CoreBundle/Entity/TrackEHotpotatoes.php | 215 ++++ .../CoreBundle/Entity/TrackEHotspot.php | 275 ++++++ .../CoreBundle/Entity/TrackEItemProperty.php | 275 ++++++ .../CoreBundle/Entity/TrackELastaccess.php | 185 ++++ src/Chamilo/CoreBundle/Entity/TrackELinks.php | 185 ++++ src/Chamilo/CoreBundle/Entity/TrackELogin.php | 155 +++ .../CoreBundle/Entity/TrackEOnline.php | 215 ++++ src/Chamilo/CoreBundle/Entity/TrackEOpen.php | 155 +++ .../CoreBundle/Entity/TrackEUploads.php | 215 ++++ .../CoreBundle/Entity/TrackStoredValues.php | 185 ++++ .../Entity/TrackStoredValuesStack.php | 215 ++++ src/Chamilo/CoreBundle/Entity/User.php | 845 ++++++++++++++++ src/Chamilo/CoreBundle/Entity/UserApiKey.php | 275 ++++++ .../CoreBundle/Entity/UserCourseCategory.php | 125 +++ src/Chamilo/CoreBundle/Entity/UserField.php | 305 ++++++ .../CoreBundle/Entity/UserFieldOptions.php | 185 ++++ .../CoreBundle/Entity/UserFieldValues.php | 155 +++ .../Entity/UserFriendRelationType.php | 65 ++ .../CoreBundle/Entity/UserRelCourseVote.php | 185 ++++ .../CoreBundle/Entity/UserRelEventType.php | 95 ++ src/Chamilo/CoreBundle/Entity/UserRelTag.php | 95 ++ src/Chamilo/CoreBundle/Entity/UserRelUser.php | 155 +++ .../CoreBundle/Entity/UsergroupRelCourse.php | 95 ++ .../Entity/UsergroupRelQuestion.php | 155 +++ .../CoreBundle/Entity/UsergroupRelSession.php | 95 ++ .../CourseBundle/Entity/CAnnouncement.php | 260 +++++ .../Entity/CAnnouncementAttachment.php | 230 +++++ .../CourseBundle/Entity/CAttendance.php | 320 ++++++ .../Entity/CAttendanceCalendar.php | 170 ++++ .../Entity/CAttendanceCalendarRelGroup.php | 125 +++ .../CourseBundle/Entity/CAttendanceResult.php | 170 ++++ .../CourseBundle/Entity/CAttendanceSheet.php | 142 +++ .../Entity/CAttendanceSheetLog.php | 230 +++++ src/Chamilo/CourseBundle/Entity/CBlog.php | 230 +++++ .../CourseBundle/Entity/CBlogAttachment.php | 290 ++++++ .../CourseBundle/Entity/CBlogComment.php | 320 ++++++ src/Chamilo/CourseBundle/Entity/CBlogPost.php | 230 +++++ .../CourseBundle/Entity/CBlogRating.php | 230 +++++ .../CourseBundle/Entity/CBlogRelUser.php | 112 +++ src/Chamilo/CourseBundle/Entity/CBlogTask.php | 230 +++++ .../CourseBundle/Entity/CBlogTaskRelUser.php | 174 ++++ .../CourseBundle/Entity/CCalendarEvent.php | 290 ++++++ .../Entity/CCalendarEventAttachment.php | 230 +++++ .../Entity/CCalendarEventRepeat.php | 200 ++++ .../Entity/CCalendarEventRepeatNot.php | 112 +++ .../CourseBundle/Entity/CChatConnected.php | 204 ++++ .../Entity/CCourseDescription.php | 230 +++++ .../CourseBundle/Entity/CCourseSetting.php | 320 ++++++ src/Chamilo/CourseBundle/Entity/CDocument.php | 290 ++++++ .../CourseBundle/Entity/CDropboxCategory.php | 230 +++++ .../CourseBundle/Entity/CDropboxFeedback.php | 200 ++++ .../CourseBundle/Entity/CDropboxFile.php | 380 ++++++++ .../CourseBundle/Entity/CDropboxPerson.php | 112 +++ .../CourseBundle/Entity/CDropboxPost.php | 232 +++++ .../CourseBundle/Entity/CForumAttachment.php | 230 +++++ .../CourseBundle/Entity/CForumCategory.php | 230 +++++ .../CourseBundle/Entity/CForumForum.php | 680 +++++++++++++ .../CourseBundle/Entity/CForumMailcue.php | 176 ++++ .../Entity/CForumNotification.php | 208 ++++ .../CourseBundle/Entity/CForumPost.php | 380 ++++++++ .../CourseBundle/Entity/CForumThread.php | 530 ++++++++++ .../Entity/CForumThreadQualify.php | 260 +++++ .../Entity/CForumThreadQualifyLog.php | 260 +++++ src/Chamilo/CourseBundle/Entity/CGlossary.php | 200 ++++ .../CourseBundle/Entity/CGroupCategory.php | 500 ++++++++++ .../CourseBundle/Entity/CGroupInfo.php | 204 ++-- .../CourseBundle/Entity/CGroupRelTutor.php | 140 +++ .../CourseBundle/Entity/CGroupRelUser.php | 200 ++++ .../CourseBundle/Entity/CItemProperty.php | 470 +++++++++ src/Chamilo/CourseBundle/Entity/CLink.php | 320 ++++++ .../CourseBundle/Entity/CLinkCategory.php | 200 ++++ src/Chamilo/CourseBundle/Entity/CLp.php | 920 ++++++++++++++++++ src/Chamilo/CourseBundle/Entity/CLpItem.php | 740 ++++++++++++++ .../CourseBundle/Entity/CLpItemView.php | 410 ++++++++ .../CourseBundle/Entity/CLpIvInteraction.php | 380 ++++++++ .../CourseBundle/Entity/CLpIvObjective.php | 290 ++++++ src/Chamilo/CourseBundle/Entity/CLpView.php | 260 +++++ src/Chamilo/CourseBundle/Entity/CNotebook.php | 320 ++++++ .../CourseBundle/Entity/COnlineConnected.php | 110 +++ .../CourseBundle/Entity/COnlineLink.php | 140 +++ .../CourseBundle/Entity/CPermissionGroup.php | 170 ++++ .../CourseBundle/Entity/CPermissionTask.php | 170 ++++ .../CourseBundle/Entity/CPermissionUser.php | 170 ++++ src/Chamilo/CourseBundle/Entity/CQuiz.php | 710 ++++++++++++++ .../CourseBundle/Entity/CQuizAnswer.php | 410 ++++++++ .../CourseBundle/Entity/CQuizQuestion.php | 350 +++++++ .../Entity/CQuizQuestionCategory.php | 140 +++ .../Entity/CQuizQuestionOption.php | 170 ++++ .../Entity/CQuizQuestionRelCategory.php | 110 +++ .../CourseBundle/Entity/CQuizRelQuestion.php | 142 +++ src/Chamilo/CourseBundle/Entity/CResource.php | 200 ++++ src/Chamilo/CourseBundle/Entity/CRole.php | 170 ++++ .../CourseBundle/Entity/CRoleGroup.php | 172 ++++ .../CourseBundle/Entity/CRolePermissions.php | 206 ++++ src/Chamilo/CourseBundle/Entity/CRoleUser.php | 142 +++ .../Entity/CStudentPublication.php | 680 +++++++++++++ .../Entity/CStudentPublicationAssignment.php | 230 +++++ .../Entity/CStudentPublicationComment.php | 215 ++++ .../Entity/CStudentPublicationRelDocument.php | 125 +++ .../Entity/CStudentPublicationRelUser.php | 125 +++ src/Chamilo/CourseBundle/Entity/CSurvey.php | 920 ++++++++++++++++++ .../CourseBundle/Entity/CSurveyAnswer.php | 230 +++++ .../CourseBundle/Entity/CSurveyGroup.php | 170 ++++ .../CourseBundle/Entity/CSurveyInvitation.php | 320 ++++++ .../CourseBundle/Entity/CSurveyQuestion.php | 410 ++++++++ .../Entity/CSurveyQuestionOption.php | 230 +++++ src/Chamilo/CourseBundle/Entity/CThematic.php | 230 +++++ .../CourseBundle/Entity/CThematicAdvance.php | 260 +++++ .../CourseBundle/Entity/CThematicPlan.php | 200 ++++ src/Chamilo/CourseBundle/Entity/CTool.php | 322 +----- .../CourseBundle/Entity/CToolIntro.php | 142 +++ .../CourseBundle/Entity/CUserinfoContent.php | 230 +++++ .../CourseBundle/Entity/CUserinfoDef.php | 200 ++++ src/Chamilo/CourseBundle/Entity/CWiki.php | 830 ++++++++++++++++ src/Chamilo/CourseBundle/Entity/CWikiConf.php | 470 +++++++++ .../CourseBundle/Entity/CWikiDiscuss.php | 230 +++++ .../CourseBundle/Entity/CWikiMailcue.php | 202 ++++ src/Chamilo/CourseBundle/Entity/Career.php | 185 ++++ src/Chamilo/CourseBundle/Entity/Chat.php | 185 ++++ src/Chamilo/CourseBundle/Entity/ClassItem.php | 95 ++ src/Chamilo/CourseBundle/Entity/ClassUser.php | 80 ++ src/Chamilo/UserBundle/Entity/User.php | 4 +- 207 files changed, 47562 insertions(+), 624 deletions(-) create mode 100644 main/install/data.sql create mode 100644 src/Chamilo/CoreBundle/Entity/AccessUrlRelSession.php create mode 100644 src/Chamilo/CoreBundle/Entity/AccessUrlRelUser.php create mode 100644 src/Chamilo/CoreBundle/Entity/Admin.php create mode 100644 src/Chamilo/CoreBundle/Entity/AnnouncementRelGroup.php create mode 100644 src/Chamilo/CoreBundle/Entity/Block.php create mode 100644 src/Chamilo/CoreBundle/Entity/CourseCategory.php create mode 100644 src/Chamilo/CoreBundle/Entity/CourseField.php create mode 100644 src/Chamilo/CoreBundle/Entity/CourseFieldOptions.php create mode 100644 src/Chamilo/CoreBundle/Entity/CourseFieldValues.php create mode 100644 src/Chamilo/CoreBundle/Entity/CourseModule.php create mode 100644 src/Chamilo/CoreBundle/Entity/CourseRelClass.php create mode 100644 src/Chamilo/CoreBundle/Entity/CourseRequest.php create mode 100644 src/Chamilo/CoreBundle/Entity/CourseType.php create mode 100644 src/Chamilo/CoreBundle/Entity/EventEmailTemplate.php create mode 100644 src/Chamilo/CoreBundle/Entity/EventSent.php create mode 100644 src/Chamilo/CoreBundle/Entity/GradeComponents.php create mode 100644 src/Chamilo/CoreBundle/Entity/GradeModel.php create mode 100644 src/Chamilo/CoreBundle/Entity/GradebookCategory.php create mode 100644 src/Chamilo/CoreBundle/Entity/GradebookCertificate.php create mode 100644 src/Chamilo/CoreBundle/Entity/GradebookEvaluation.php create mode 100644 src/Chamilo/CoreBundle/Entity/GradebookLink.php create mode 100644 src/Chamilo/CoreBundle/Entity/GradebookLinkevalLog.php create mode 100644 src/Chamilo/CoreBundle/Entity/GradebookResult.php create mode 100644 src/Chamilo/CoreBundle/Entity/GradebookResultLog.php create mode 100644 src/Chamilo/CoreBundle/Entity/GradebookScoreDisplay.php create mode 100644 src/Chamilo/CoreBundle/Entity/GroupRelGroup.php create mode 100644 src/Chamilo/CoreBundle/Entity/GroupRelTag.php create mode 100644 src/Chamilo/CoreBundle/Entity/GroupRelUser.php create mode 100644 src/Chamilo/CoreBundle/Entity/Groups.php create mode 100644 src/Chamilo/CoreBundle/Entity/HookCall.php create mode 100644 src/Chamilo/CoreBundle/Entity/HookEvent.php create mode 100644 src/Chamilo/CoreBundle/Entity/HookObserver.php create mode 100644 src/Chamilo/CoreBundle/Entity/Language.php create mode 100644 src/Chamilo/CoreBundle/Entity/Legal.php create mode 100644 src/Chamilo/CoreBundle/Entity/Message.php create mode 100644 src/Chamilo/CoreBundle/Entity/MessageAttachment.php create mode 100644 src/Chamilo/CoreBundle/Entity/Notification.php create mode 100644 src/Chamilo/CoreBundle/Entity/OpenidAssociation.php create mode 100644 src/Chamilo/CoreBundle/Entity/PersonalAgenda.php create mode 100644 src/Chamilo/CoreBundle/Entity/PersonalAgendaRepeat.php create mode 100644 src/Chamilo/CoreBundle/Entity/PersonalAgendaRepeatNot.php create mode 100644 src/Chamilo/CoreBundle/Entity/PhpSession.php create mode 100644 src/Chamilo/CoreBundle/Entity/Promotion.php create mode 100644 src/Chamilo/CoreBundle/Entity/SearchEngineRef.php create mode 100644 src/Chamilo/CoreBundle/Entity/SessionField.php create mode 100644 src/Chamilo/CoreBundle/Entity/SessionFieldOptions.php create mode 100644 src/Chamilo/CoreBundle/Entity/SessionFieldValues.php create mode 100644 src/Chamilo/CoreBundle/Entity/SettingsCurrent.php create mode 100644 src/Chamilo/CoreBundle/Entity/SettingsOptions.php create mode 100644 src/Chamilo/CoreBundle/Entity/SharedSurvey.php create mode 100644 src/Chamilo/CoreBundle/Entity/SharedSurveyQuestion.php create mode 100644 src/Chamilo/CoreBundle/Entity/SharedSurveyQuestionOption.php create mode 100644 src/Chamilo/CoreBundle/Entity/Skill.php create mode 100644 src/Chamilo/CoreBundle/Entity/SkillProfile.php create mode 100644 src/Chamilo/CoreBundle/Entity/SkillRelGradebook.php create mode 100644 src/Chamilo/CoreBundle/Entity/SkillRelProfile.php create mode 100644 src/Chamilo/CoreBundle/Entity/SkillRelSkill.php create mode 100644 src/Chamilo/CoreBundle/Entity/SkillRelUser.php create mode 100644 src/Chamilo/CoreBundle/Entity/SpecificField.php create mode 100644 src/Chamilo/CoreBundle/Entity/SpecificFieldValues.php create mode 100644 src/Chamilo/CoreBundle/Entity/SysAnnouncement.php create mode 100644 src/Chamilo/CoreBundle/Entity/SysCalendar.php create mode 100644 src/Chamilo/CoreBundle/Entity/SystemTemplate.php create mode 100644 src/Chamilo/CoreBundle/Entity/Tag.php create mode 100644 src/Chamilo/CoreBundle/Entity/Templates.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackCBrowsers.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackCCountries.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackCOs.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackCProviders.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackCReferers.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackCourseRanking.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEAccess.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEAttempt.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEAttemptCoeff.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEAttemptRecording.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackECourseAccess.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEDefault.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEDownloads.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEExercises.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEHotpotatoes.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEHotspot.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEItemProperty.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackELastaccess.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackELinks.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackELogin.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEOnline.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEOpen.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackEUploads.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackStoredValues.php create mode 100644 src/Chamilo/CoreBundle/Entity/TrackStoredValuesStack.php create mode 100644 src/Chamilo/CoreBundle/Entity/User.php create mode 100644 src/Chamilo/CoreBundle/Entity/UserApiKey.php create mode 100644 src/Chamilo/CoreBundle/Entity/UserCourseCategory.php create mode 100644 src/Chamilo/CoreBundle/Entity/UserField.php create mode 100644 src/Chamilo/CoreBundle/Entity/UserFieldOptions.php create mode 100644 src/Chamilo/CoreBundle/Entity/UserFieldValues.php create mode 100644 src/Chamilo/CoreBundle/Entity/UserFriendRelationType.php create mode 100644 src/Chamilo/CoreBundle/Entity/UserRelCourseVote.php create mode 100644 src/Chamilo/CoreBundle/Entity/UserRelEventType.php create mode 100644 src/Chamilo/CoreBundle/Entity/UserRelTag.php create mode 100644 src/Chamilo/CoreBundle/Entity/UserRelUser.php create mode 100644 src/Chamilo/CoreBundle/Entity/UsergroupRelCourse.php create mode 100644 src/Chamilo/CoreBundle/Entity/UsergroupRelQuestion.php create mode 100644 src/Chamilo/CoreBundle/Entity/UsergroupRelSession.php create mode 100644 src/Chamilo/CourseBundle/Entity/CAnnouncement.php create mode 100644 src/Chamilo/CourseBundle/Entity/CAnnouncementAttachment.php create mode 100644 src/Chamilo/CourseBundle/Entity/CAttendance.php create mode 100644 src/Chamilo/CourseBundle/Entity/CAttendanceCalendar.php create mode 100644 src/Chamilo/CourseBundle/Entity/CAttendanceCalendarRelGroup.php create mode 100644 src/Chamilo/CourseBundle/Entity/CAttendanceResult.php create mode 100644 src/Chamilo/CourseBundle/Entity/CAttendanceSheet.php create mode 100644 src/Chamilo/CourseBundle/Entity/CAttendanceSheetLog.php create mode 100644 src/Chamilo/CourseBundle/Entity/CBlog.php create mode 100644 src/Chamilo/CourseBundle/Entity/CBlogAttachment.php create mode 100644 src/Chamilo/CourseBundle/Entity/CBlogComment.php create mode 100644 src/Chamilo/CourseBundle/Entity/CBlogPost.php create mode 100644 src/Chamilo/CourseBundle/Entity/CBlogRating.php create mode 100644 src/Chamilo/CourseBundle/Entity/CBlogRelUser.php create mode 100644 src/Chamilo/CourseBundle/Entity/CBlogTask.php create mode 100644 src/Chamilo/CourseBundle/Entity/CBlogTaskRelUser.php create mode 100644 src/Chamilo/CourseBundle/Entity/CCalendarEvent.php create mode 100644 src/Chamilo/CourseBundle/Entity/CCalendarEventAttachment.php create mode 100644 src/Chamilo/CourseBundle/Entity/CCalendarEventRepeat.php create mode 100644 src/Chamilo/CourseBundle/Entity/CCalendarEventRepeatNot.php create mode 100644 src/Chamilo/CourseBundle/Entity/CChatConnected.php create mode 100644 src/Chamilo/CourseBundle/Entity/CCourseDescription.php create mode 100644 src/Chamilo/CourseBundle/Entity/CCourseSetting.php create mode 100644 src/Chamilo/CourseBundle/Entity/CDocument.php create mode 100644 src/Chamilo/CourseBundle/Entity/CDropboxCategory.php create mode 100644 src/Chamilo/CourseBundle/Entity/CDropboxFeedback.php create mode 100644 src/Chamilo/CourseBundle/Entity/CDropboxFile.php create mode 100644 src/Chamilo/CourseBundle/Entity/CDropboxPerson.php create mode 100644 src/Chamilo/CourseBundle/Entity/CDropboxPost.php create mode 100644 src/Chamilo/CourseBundle/Entity/CForumAttachment.php create mode 100644 src/Chamilo/CourseBundle/Entity/CForumCategory.php create mode 100644 src/Chamilo/CourseBundle/Entity/CForumForum.php create mode 100644 src/Chamilo/CourseBundle/Entity/CForumMailcue.php create mode 100644 src/Chamilo/CourseBundle/Entity/CForumNotification.php create mode 100644 src/Chamilo/CourseBundle/Entity/CForumPost.php create mode 100644 src/Chamilo/CourseBundle/Entity/CForumThread.php create mode 100644 src/Chamilo/CourseBundle/Entity/CForumThreadQualify.php create mode 100644 src/Chamilo/CourseBundle/Entity/CForumThreadQualifyLog.php create mode 100644 src/Chamilo/CourseBundle/Entity/CGlossary.php create mode 100644 src/Chamilo/CourseBundle/Entity/CGroupCategory.php create mode 100644 src/Chamilo/CourseBundle/Entity/CGroupRelTutor.php create mode 100644 src/Chamilo/CourseBundle/Entity/CGroupRelUser.php create mode 100644 src/Chamilo/CourseBundle/Entity/CItemProperty.php create mode 100644 src/Chamilo/CourseBundle/Entity/CLink.php create mode 100644 src/Chamilo/CourseBundle/Entity/CLinkCategory.php create mode 100644 src/Chamilo/CourseBundle/Entity/CLp.php create mode 100644 src/Chamilo/CourseBundle/Entity/CLpItem.php create mode 100644 src/Chamilo/CourseBundle/Entity/CLpItemView.php create mode 100644 src/Chamilo/CourseBundle/Entity/CLpIvInteraction.php create mode 100644 src/Chamilo/CourseBundle/Entity/CLpIvObjective.php create mode 100644 src/Chamilo/CourseBundle/Entity/CLpView.php create mode 100644 src/Chamilo/CourseBundle/Entity/CNotebook.php create mode 100644 src/Chamilo/CourseBundle/Entity/COnlineConnected.php create mode 100644 src/Chamilo/CourseBundle/Entity/COnlineLink.php create mode 100644 src/Chamilo/CourseBundle/Entity/CPermissionGroup.php create mode 100644 src/Chamilo/CourseBundle/Entity/CPermissionTask.php create mode 100644 src/Chamilo/CourseBundle/Entity/CPermissionUser.php create mode 100644 src/Chamilo/CourseBundle/Entity/CQuiz.php create mode 100644 src/Chamilo/CourseBundle/Entity/CQuizAnswer.php create mode 100644 src/Chamilo/CourseBundle/Entity/CQuizQuestion.php create mode 100644 src/Chamilo/CourseBundle/Entity/CQuizQuestionCategory.php create mode 100644 src/Chamilo/CourseBundle/Entity/CQuizQuestionOption.php create mode 100644 src/Chamilo/CourseBundle/Entity/CQuizQuestionRelCategory.php create mode 100644 src/Chamilo/CourseBundle/Entity/CQuizRelQuestion.php create mode 100644 src/Chamilo/CourseBundle/Entity/CResource.php create mode 100644 src/Chamilo/CourseBundle/Entity/CRole.php create mode 100644 src/Chamilo/CourseBundle/Entity/CRoleGroup.php create mode 100644 src/Chamilo/CourseBundle/Entity/CRolePermissions.php create mode 100644 src/Chamilo/CourseBundle/Entity/CRoleUser.php create mode 100644 src/Chamilo/CourseBundle/Entity/CStudentPublication.php create mode 100644 src/Chamilo/CourseBundle/Entity/CStudentPublicationAssignment.php create mode 100644 src/Chamilo/CourseBundle/Entity/CStudentPublicationComment.php create mode 100644 src/Chamilo/CourseBundle/Entity/CStudentPublicationRelDocument.php create mode 100644 src/Chamilo/CourseBundle/Entity/CStudentPublicationRelUser.php create mode 100644 src/Chamilo/CourseBundle/Entity/CSurvey.php create mode 100644 src/Chamilo/CourseBundle/Entity/CSurveyAnswer.php create mode 100644 src/Chamilo/CourseBundle/Entity/CSurveyGroup.php create mode 100644 src/Chamilo/CourseBundle/Entity/CSurveyInvitation.php create mode 100644 src/Chamilo/CourseBundle/Entity/CSurveyQuestion.php create mode 100644 src/Chamilo/CourseBundle/Entity/CSurveyQuestionOption.php create mode 100644 src/Chamilo/CourseBundle/Entity/CThematic.php create mode 100644 src/Chamilo/CourseBundle/Entity/CThematicAdvance.php create mode 100644 src/Chamilo/CourseBundle/Entity/CThematicPlan.php create mode 100644 src/Chamilo/CourseBundle/Entity/CToolIntro.php create mode 100644 src/Chamilo/CourseBundle/Entity/CUserinfoContent.php create mode 100644 src/Chamilo/CourseBundle/Entity/CUserinfoDef.php create mode 100644 src/Chamilo/CourseBundle/Entity/CWiki.php create mode 100644 src/Chamilo/CourseBundle/Entity/CWikiConf.php create mode 100644 src/Chamilo/CourseBundle/Entity/CWikiDiscuss.php create mode 100644 src/Chamilo/CourseBundle/Entity/CWikiMailcue.php create mode 100644 src/Chamilo/CourseBundle/Entity/Career.php create mode 100644 src/Chamilo/CourseBundle/Entity/Chat.php create mode 100644 src/Chamilo/CourseBundle/Entity/ClassItem.php create mode 100644 src/Chamilo/CourseBundle/Entity/ClassUser.php diff --git a/main/inc/lib/database.lib.php b/main/inc/lib/database.lib.php index fcb2f7233f..2dfc5cc73c 100755 --- a/main/inc/lib/database.lib.php +++ b/main/inc/lib/database.lib.php @@ -19,6 +19,7 @@ class Database * @var EntityManager */ private static $em; + private static $connection; /** * @param EntityManager $em @@ -28,6 +29,22 @@ class Database self::$em = $em; } + /** + * @param Connection $connection + */ + public function setConnection(Connection $connection) + { + self::$connection = $connection; + } + + /** + * @return Connection + */ + public function getConnection() + { + return self::$connection; + } + /** * @return EntityManager */ @@ -133,6 +150,7 @@ class Database api_get_path(SYS_PATH)."vendor/gedmo/doctrine-extensions/lib" ); + $this->setConnection($entityManager->getConnection()); $this->setManager($entityManager); // A MySQL-specific implementation. diff --git a/main/install/data.sql b/main/install/data.sql new file mode 100644 index 0000000000..96c4f278cf --- /dev/null +++ b/main/install/data.sql @@ -0,0 +1,150 @@ + +INSERT INTO language (original_name, english_name, isocode, dokeos_folder, available) VALUES +('العربية','arabic','ar','arabic',0), +('Asturianu','asturian','ast','asturian',0), +('বাংলা','bengali','bn','bengali',0), +('Български','bulgarian','bg','bulgarian',1), +('Bosanski','bosnian','bs','bosnian',1), +('Català','catalan','ca','catalan',0), +('中文(简体)','simpl_chinese','zh','simpl_chinese',0), +('繁體中文','trad_chinese','zh-TW','trad_chinese',0), +('Česky','czech','cs','czech',0), +('Dansk','danish','da','danish',0), +('دری','dari','prs','dari',0), +('Deutsch','german','de','german',1), +('Ελληνικά','greek','el','greek',0), +('English','english','en','english',1), +('Español','spanish','es','spanish',1), +('Esperanto','esperanto','eo','esperanto',0), +('Euskara','basque','eu','basque',0), +('فارسی','persian','fa','persian',0), +('Français','french','fr','french',1), +('Furlan','friulian','fur','friulian',0), +('Galego','galician','gl','galician',0), +('ქართული','georgian','ka','georgian',0), +('Hrvatski','croatian','hr','croatian',0), +('עברית','hebrew','he','hebrew',0), +('हिन्दी','hindi','hi','hindi',0), +('Bahasa Indonesia','indonesian','id','indonesian',1), +('Italiano','italian','it','italian',1), +('한국어','korean','ko','korean',0), +('Latviešu','latvian','lv','latvian',0), +('Lietuvių','lithuanian','lt','lithuanian',0), +('Македонски','macedonian','mk','macedonian',0), +('Magyar','hungarian','hu','hungarian',1), +('Bahasa Melayu','malay','ms','malay',0), +('Nederlands','dutch','nl','dutch',1), +('日本語','japanese','ja','japanese',0), +('Norsk','norwegian','no','norwegian',0), +('Occitan','occitan','oc','occitan',0), +('پښتو','pashto','ps','pashto',0), +('Polski','polish','pl','polish',0), +('Português europeu','portuguese','pt','portuguese',1), +('Português do Brasil','brazilian','pt-BR','brazilian',1), +('Română','romanian','ro','romanian',0), +('Runasimi','quechua_cusco','qu','quechua_cusco',0), +('Русский','russian','ru','russian',0), +('Slovenčina','slovak','sk','slovak',0), +('Slovenščina','slovenian','sl','slovenian',1), +('الصومالية','somali','so','somali',0), +('Srpski','serbian','sr','serbian',0), +('Suomi','finnish','fi','finnish',0), +('Svenska','swedish','sv','swedish',0), +('ไทย','thai','th','thai',0), +('Türkçe','turkish','tr','turkish',0), +('Українська','ukrainian','uk','ukrainian',0), +('Tiếng Việt','vietnamese','vi','vietnamese',0), +('Kiswahili','swahili','sw','swahili',0), +('Yorùbá','yoruba','yo','yoruba',0); + + +INSERT INTO course_category VALUES (1,'Language skills','LANG',NULL,1,0,'TRUE','TRUE'),(2,'PC Skills','PC',NULL,2,0,'TRUE','TRUE'),(3,'Projects','PROJ',NULL,3,0,'TRUE','TRUE'); + +INSERT INTO course_module VALUES +(1,'calendar_event','calendar/agenda.php','agenda.gif',1,1,'basic'), +(2,'link','link/link.php','links.gif',4,1,'basic'), +(3,'document','document/document.php','documents.gif',3,1,'basic'), +(4,'student_publication','work/work.php','works.gif',3,2,'basic'), +(5,'announcement','announcements/announcements.php','valves.gif',2,1,'basic'), +(6,'user','user/user.php','members.gif',2,3,'basic'), +(7,'forum','forum/index.php','forum.gif',1,2,'basic'), +(8,'quiz','exercice/exercice.php','quiz.gif',2,2,'basic'), +(9,'group','group/group.php','group.gif',3,3,'basic'), +(10,'course_description','course_description/','info.gif',1,3,'basic'), +(11,'chat','chat/chat.php','chat.gif',0,0,'external'), +(12,'dropbox','dropbox/index.php','dropbox.gif',4,2,'basic'), +(13,'tracking','tracking/courseLog.php','statistics.gif',1,3,'courseadmin'), +(14,'homepage_link','link/link.php?action=addlink','npage.gif',1,1,'courseadmin'), +(15,'course_setting','course_info/infocours.php','reference.gif',1,1,'courseadmin'), +(16,'External','','external.gif',0,0,'external'), +(17,'AddedLearnpath','','scormbuilder.gif',0,0,'external'), +(18,'conference','conference/index.php?type=conference','conf.gif',0,0,'external'), +(19,'conference','conference/index.php?type=classroom','conf.gif',0,0,'external'), +(20,'learnpath','newscorm/lp_controller.php','scorms.gif',5,1,'basic'), +(21,'blog','blog/blog.php','blog.gif',1,2,'basic'), +(22,'blog_management','blog/blog_admin.php','blog_admin.gif',1,2,'courseadmin'), +(23,'course_maintenance','course_info/maintenance.php','backup.gif',2,3,'courseadmin'), +(24,'survey','survey/survey_list.php','survey.gif',2,1,'basic'), +(25,'wiki','wiki/index.php','wiki.gif',2,3,'basic'), +(26,'gradebook','gradebook/index.php','gradebook.gif',2,2,'basic'), +(27,'glossary','glossary/index.php','glossary.gif',2,1,'basic'), +(28,'notebook','notebook/index.php','notebook.gif',2,1,'basic'), +(29,'attendance','attendance/index.php','attendance.gif',2,1,'basic'), +(30,'course_progress','course_progress/index.php','course_progress.gif',2,1,'basic'); + +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES (1, 'legal_accept','Legal',0,0); +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES (1, 'already_logged_in','Already logged in',0,0); +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES (1, 'update_type','Update script type',0,0); +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES (10, 'tags','tags',0,0); +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES (1, 'rssfeeds','RSS',0,0); +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES (1, 'dashboard', 'Dashboard', 0, 0); +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES (11, 'timezone', 'Timezone', 0, 0); +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable, field_default_value) values (4, 'mail_notify_invitation', 'MailNotifyInvitation',1,1,'1'); +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable, field_default_value) values (4, 'mail_notify_message', 'MailNotifyMessage',1,1,'1'); +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable, field_default_value) values (4, 'mail_notify_group_message','MailNotifyGroupMessage',1,1,'1'); +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES (1, 'user_chat_status','User chat status',0,0); +INSERT INTO user_field (field_type, field_variable, field_display_text, field_visible, field_changeable) VALUES (1, 'google_calendar_url','Google Calendar URL',0,0); + +INSERT INTO user_field_options (field_id, option_value, option_display_text, option_order) values (8, '1', 'AtOnce',1); +INSERT INTO user_field_options (field_id, option_value, option_display_text, option_order) values (8, '8', 'Daily',2); +INSERT INTO user_field_options (field_id, option_value, option_display_text, option_order) values (8, '0', 'No',3); + +INSERT INTO user_field_options (field_id, option_value, option_display_text, option_order) values (9, '1', 'AtOnce',1); +INSERT INTO user_field_options (field_id, option_value, option_display_text, option_order) values (9, '8', 'Daily',2); +INSERT INTO user_field_options (field_id, option_value, option_display_text, option_order) values (9, '0', 'No',3); + +INSERT INTO user_field_options (field_id, option_value, option_display_text, option_order) values (10, '1', 'AtOnce',1); +INSERT INTO user_field_options (field_id, option_value, option_display_text, option_order) values (10, '8', 'Daily',2); +INSERT INTO user_field_options (field_id, option_value, option_display_text, option_order) values (10, '0', 'No',3); + +INSERT INTO access_url(url, description, active, created_by) VALUES ('http://localhost/',' ',1,1); + +-- Adding admin to the first portal +INSERT INTO access_url_rel_user VALUES(1, 1); + +-- Adding the platform templates + + +INSERT INTO user_friend_relation_type (id,title) +VALUES +(1,'SocialUnknow'), +(2,'SocialParent'), +(3,'SocialFriend'), +(4,'SocialGoodFriend'), +(5,'SocialEnemy'), +(6,'SocialDeleted'); + +INSERT INTO course_field (field_type, field_variable, field_display_text, field_default_value, field_visible, field_changeable) values (1, 'special_course', 'Special course', '', 1 , 1); + +INSERT INTO skill (name) VALUES ('Root'); + +INSERT INTO skill_rel_skill VALUES(1, 1, 0, 0, 0); + +INSERT INTO course_type (id, name) VALUES (1, 'All tools'); +INSERT INTO course_type (id, name) VALUES (2, 'Entry exam'); + +UPDATE settings_current SET selected_value = '1.10.0.35' WHERE variable = 'chamilo_database_version'; + + + + diff --git a/main/install/index.php b/main/install/index.php index dada882862..266b0a77a8 100755 --- a/main/install/index.php +++ b/main/install/index.php @@ -17,6 +17,9 @@ /* CONSTANTS */ use \ChamiloSession as Session; +use Chamilo\UserBundle\Entity\User; + +require_once __DIR__.'/../../vendor/autoload.php'; define('SYSTEM_INSTALLATION', 1); define('INSTALL_TYPE_UPDATE', 'update'); @@ -31,17 +34,12 @@ require_once '../inc/lib/api.lib.php'; api_check_php_version('../inc/'); -/* INITIALIZATION SECTION */ +/* INITIALIZATION SECTION */ ob_implicit_flush(true); session_start(); - -require_once api_get_path(SYS_PATH).'vendor/autoload.php'; require_once api_get_path(LIBRARY_PATH).'database.constants.inc.php'; -require_once api_get_path(LIBRARY_PATH).'database.lib.php'; require_once 'install.lib.php'; -require_once 'install.class.php'; -require_once 'i_database.class.php'; // This value is use in database::query in order to prompt errors in the error log (course databases) Database::$log_queries = true; @@ -104,7 +102,7 @@ error_reporting(E_ALL); @set_time_limit(0); // Upgrading from any subversion of 1.9 -$update_from_version_8 = array('1.9.0', '1.9.2','1.9.4','1.9.6', '1.9.6.1', '1.9.8', '1.9.8.1', '1.9.8.2', '1.9.10'); +$update_from_version_8 = array('1.9.0', '1.9.2','1.9.4','1.9.6', '1.9.6.1', '1.9.8', '1.9.8.1', '1.9.8.2', '1.9.10', '1.9.10.2'); $my_old_version = ''; if (empty($tmp_version)) { @@ -182,15 +180,10 @@ if ($installType == 'update' && in_array($my_old_version, $update_from_version_8 } if (!isset($_GET['running'])) { - - $dbHostForm = 'localhost'; + $dbHostForm = 'localhost'; $dbUsernameForm = 'root'; - $dbPassForm = ''; - $dbPrefixForm = ''; - $dbNameForm = 'chamilo'; - $dbStatsForm = 'chamilo'; - $dbScormForm = 'chamilo'; - $dbUserForm = 'chamilo'; + $dbPassForm = ''; + $dbNameForm = 'chamilo'; // Extract the path to append to the url if Chamilo is not installed on the web root directory. $urlAppendPath = api_remove_trailing_slash(api_get_path(REL_PATH)); @@ -216,15 +209,13 @@ if (!isset($_GET['running'])) { $institutionUrlForm = 'http://www.chamilo.org'; $languageForm = api_get_interface_language(); - $checkEmailByHashSent = 0; + $checkEmailByHashSent = 0; $ShowEmailnotcheckedToStudent = 1; - $userMailCanBeEmpty = 1; - $allowSelfReg = 1; - $allowSelfRegProf = 1; - $enableTrackingForm = 1; - $singleDbForm = 0; - $encryptPassForm = 'sha1'; - $session_lifetime = 360000; + $userMailCanBeEmpty = 1; + $allowSelfReg = 1; + $allowSelfRegProf = 1; + $encryptPassForm = 'sha1'; + $session_lifetime = 360000; } else { foreach ($_POST as $key => $val) { $magic_quotes_gpc = ini_get('magic_quotes_gpc'); @@ -286,25 +277,10 @@ if ($encryptPassForm == '1') { '; } elseif (@$_POST['step1'] || $badUpdatePath) { diff --git a/main/install/install.lib.php b/main/install/install.lib.php index 27fddd210c..af8b52dbbc 100755 --- a/main/install/install.lib.php +++ b/main/install/install.lib.php @@ -1865,9 +1865,7 @@ function installSettings( $allowTeacherSelfRegistration ) { $sql = " - INSERT INTO settings_current - (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) - VALUES + INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('Institution',NULL,'textfield','Platform','$organizationName','InstitutionTitle','InstitutionComment','platform',NULL, 1), ('InstitutionUrl',NULL,'textfield','Platform','$organizationUrl','InstitutionUrlTitle','InstitutionUrlComment',NULL,NULL, 1), ('siteName',NULL,'textfield','Platform','$campusName','SiteNameTitle','SiteNameComment',NULL,NULL, 1), @@ -2167,8 +2165,7 @@ function installSettings( ('prevent_session_admins_to_manage_all_users', NULL, 'radio', 'Session', 'false', 'PreventSessionAdminsToManageAllUsersTitle', 'PreventSessionAdminsToManageAllUsersComment', NULL, NULL, 1), ('documents_default_visibility_defined_in_course', NULL,'radio','Tools','false','DocumentsDefaultVisibilityDefinedInCourseTitle','DocumentsDefaultVisibilityDefinedInCourseComment',NULL, NULL, 1), ('enabled_mathjax', NULL, 'radio', 'Editor', 'false', 'EnableMathJaxTitle', 'EnableMathJaxComment', NULL, NULL, 0), - ('chamilo_database_version', NULL, 'textfield',NULL, '0', 'DatabaseVersion','', NULL, NULL, 0); - "; + ('chamilo_database_version', NULL, 'textfield',NULL, '0', 'DatabaseVersion','', NULL, NULL, 0);"; Database::query($sql); $sql = "INSERT INTO settings_options (variable, value, display_text) VALUES From fcd95308545bb53123aba3e7cff97cffac6e744b Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 3 Apr 2015 16:11:27 +0200 Subject: [PATCH 056/159] Replace course_code with c_id --- main/admin/add_courses_to_session.php | 4 +- main/admin/ldap_synchro.php | 26 ++++----- main/admin/resume_session.php | 15 +++--- main/admin/session_course_edit.php | 17 +++--- main/admin/session_course_list.php | 12 +++-- main/admin/session_course_user.php | 15 ++++-- main/admin/session_course_user_list.php | 17 ++++-- main/admin/session_export.php | 54 +++++++++++-------- main/admin/session_import.php | 31 +++++------ main/inc/lib/course.lib.php | 4 +- main/inc/lib/urlmanager.lib.php | 2 +- .../Migrations/Schema/v1/Version110.php | 4 +- 12 files changed, 117 insertions(+), 84 deletions(-) diff --git a/main/admin/add_courses_to_session.php b/main/admin/add_courses_to_session.php index 3f0d135247..80c6bd6859 100755 --- a/main/admin/add_courses_to_session.php +++ b/main/admin/add_courses_to_session.php @@ -118,7 +118,7 @@ if ($ajax_search) { $sql="SELECT code, title, visual_code, id_session FROM $tbl_course course INNER JOIN $tbl_session_rel_course session_rel_course - ON course.code = session_rel_course.course_code + ON course.id = session_rel_course.c_id AND session_rel_course.id_session = ".intval($sessionId)." ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title"; @@ -129,7 +129,7 @@ if ($ajax_search) { $sql="SELECT code, title, visual_code, id_session FROM $tbl_course course INNER JOIN $tbl_session_rel_course session_rel_course - ON course.code = session_rel_course.course_code + ON course.id = session_rel_course.c_id AND session_rel_course.id_session = ".intval($sessionId)." INNER JOIN $tbl_course_rel_access_url url_course ON (url_course.c_id = course.id) WHERE access_url_id = $access_url_id diff --git a/main/admin/ldap_synchro.php b/main/admin/ldap_synchro.php index 5cc1a53cc6..6cee744514 100755 --- a/main/admin/ldap_synchro.php +++ b/main/admin/ldap_synchro.php @@ -124,27 +124,27 @@ foreach($Sessions as $session){ print "> $name_session: ".count($UserAdd).get_lang('Added').' '.get_lang('And').' '.count($UserUpdate).' '.get_lang('Modified')."\n"; } - // Une fois les utilisateurs importer dans la base des utilisateurs, on peux les affecter a� la session - $result=Database::query("SELECT course_code FROM $tbl_session_rel_course " . - "WHERE id_session='$id_session'"); + // Une fois les utilisateurs importer dans la base des utilisateurs, on peux les affecter la session + $result=Database::query("SELECT id, course_code FROM $tbl_session_rel_course WHERE id_session='$id_session'"); $CourseList=array(); - while($row=Database::fetch_array($result)) - { - $CourseList[]=$row['course_code']; + while($row=Database::fetch_array($result)) { + $CourseList[]= $row['id']; } - foreach($CourseList as $enreg_course) - { + + foreach ($CourseList as $enreg_course) { // On ajoute la relation entre l'utilisateur et le cours - foreach($UserList as $enreg_user) - { - Database::query("INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$enreg_user')"); + foreach ($UserList as $enreg_user) { + $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,c_id,id_user) + VALUES('$id_session','$enreg_course','$enreg_user')"; + Database::query($sql); } $sql = "SELECT COUNT(id_user) as nbUsers " . "FROM $tbl_session_rel_course_rel_user " . - "WHERE id_session='$id_session' AND course_code='$enreg_course'"; + "WHERE id_session='$id_session' AND c_id='$enreg_course'"; $rs = Database::query($sql); list($nbr_users) = Database::fetch_array($rs); - $sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'"; + $sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users + WHERE id_session='$id_session' AND c_id = '$enreg_course'"; Database::query($sql); } // On ajoute la relation entre l'utilisateur et la session diff --git a/main/admin/resume_session.php b/main/admin/resume_session.php index 26b5699b32..3b16bd3c14 100755 --- a/main/admin/resume_session.php +++ b/main/admin/resume_session.php @@ -290,10 +290,10 @@ if ($session['nbr_courses'] == 0) { $orderBy = "ORDER BY position"; - $sql = "SELECT code,title,visual_code, nbr_users - FROM $tbl_course, $tbl_session_rel_course + $sql = "SELECT c.id, code,title, visual_code, nbr_users + FROM $tbl_course c , $tbl_session_rel_course WHERE - course_code = code AND + c_id = c.id AND id_session='$sessionId' $orderBy"; @@ -305,11 +305,12 @@ if ($session['nbr_courses'] == 0) { //select the number of users $sql = "SELECT count(*) - FROM $tbl_session_rel_user sru, $tbl_session_rel_course_rel_user srcru + FROM $tbl_session_rel_user sru, + $tbl_session_rel_course_rel_user srcru WHERE srcru.id_user = sru.id_user AND srcru.id_session = sru.id_session AND - srcru.course_code = '".Database::escape_string($course['code'])."' AND + srcru.c_id = '".intval($course['id'])."' AND sru.relation_type <> ".SESSION_RELATION_TYPE_RRHH." AND srcru.id_session = '".intval($sessionId)."'"; @@ -318,12 +319,12 @@ if ($session['nbr_courses'] == 0) { // Get coachs of the courses in session - $sql = "SELECT user.lastname,user.firstname,user.username + $sql = "SELECT user.lastname,user.firstname, user.username FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user WHERE session_rcru.id_user = user.user_id AND session_rcru.id_session = '".intval($sessionId)."' AND - session_rcru.course_code ='".Database::escape_string($course['code'])."' AND + session_rcru.c_id ='".intval($course['id'])."' AND session_rcru.status=2"; $rs = Database::query($sql); diff --git a/main/admin/session_course_edit.php b/main/admin/session_course_edit.php index 3e3856b2b3..542528c520 100755 --- a/main/admin/session_course_edit.php +++ b/main/admin/session_course_edit.php @@ -23,13 +23,18 @@ $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE); $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $course_info = api_get_course_info($_REQUEST['course_code']); +$courseId = $course_info['id']; $tool_name = $course_info['name']; +$sql = "SELECT s.name, c.title + FROM $tbl_session_course sc,$tbl_session s,$tbl_course c + WHERE + sc.id_session=s.id AND + sc.course_code = c.code AND + sc.id_session='$id_session' AND + sc.c_id ='".intval($courseId)."'"; +$result = Database::query($sql); -$result = Database::query("SELECT s.name, c.title FROM $tbl_session_course sc,$tbl_session s,$tbl_course c -WHERE sc.id_session=s.id AND sc.course_code=c.code AND sc -.id_session='$id_session' AND sc.course_code='".Database::escape_string($course_code)."'"); - -if (!list($session_name,$course_title)=Database::fetch_row($result)) { +if (!list($session_name,$course_title) = Database::fetch_row($result)) { header('Location: session_course_list.php?id_session='.$id_session); exit(); } @@ -45,7 +50,7 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { // get all tutor by course_code in the session $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user - WHERE id_session = '$id_session' AND course_code = '".Database::escape_string($course_code)."' AND status = 2"; + WHERE id_session = '$id_session' AND c_id = '".intval($courseId)."' AND status = 2"; $rs_coachs = Database::query($sql); $coachs_course_session = array(); diff --git a/main/admin/session_course_list.php b/main/admin/session_course_list.php index 341738206b..c034c97274 100755 --- a/main/admin/session_course_list.php +++ b/main/admin/session_course_list.php @@ -43,9 +43,9 @@ if ($action == 'delete') { } $idChecked = $my_temp; $idChecked="'".implode("','", $idChecked)."'"; - $result = Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND course_code IN($idChecked)"); + $result = Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND c_id IN($idChecked)"); $nbr_affected_rows=Database::affected_rows($result); - Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code IN($idChecked)"); + Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND c_id IN($idChecked)"); Database::query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'"); } header('Location: '.api_get_self().'?id_session='.$id_session.'&sort='.$sort); @@ -55,7 +55,9 @@ if ($action == 'delete') { $limit = 20; $from = $page * $limit; -$sql = "SELECT code, title, nbr_users FROM $tbl_session_rel_course, $tbl_course WHERE course_code=code AND id_session='$id_session' ORDER BY $sort LIMIT $from,".($limit+1); +$sql = "SELECT code, title, nbr_users FROM $tbl_session_rel_course, $tbl_course + WHERE c_id = id AND id_session='$id_session' + ORDER BY $sort LIMIT $from,".($limit+1); $result=Database::query($sql); $Courses=Database::store_result($result); $tool_name = api_htmlentities($session_name,ENT_QUOTES,$charset).' : '.get_lang('CourseListInSession'); @@ -78,12 +80,12 @@ $tableHeader[] = array(get_lang('Actions')); $tableCourses = array(); foreach($Courses as $key=>$enreg) { $course = array(); - $course[] = ''; + $course[] = ''; $course[] = api_htmlentities($enreg['title'],ENT_QUOTES,$charset); $course[] = ''.$enreg['nbr_users'].' '.get_lang('Users').''; $course[] = ''.Display::return_icon('course_home.gif', get_lang('Course')).' '.Display::return_icon('edit.gif', get_lang('Edit')).' - '.Display::return_icon('delete.gif', get_lang('Delete')).''; + '.Display::return_icon('delete.gif', get_lang('Delete')).''; $tableCourses[] = $course; } echo '
      '; diff --git a/main/admin/session_course_user.php b/main/admin/session_course_user.php index 1a712fbe4f..91bc6b4c02 100755 --- a/main/admin/session_course_user.php +++ b/main/admin/session_course_user.php @@ -59,10 +59,14 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { } $sql="SELECT distinct code - FROM $tbl_course course LEFT JOIN $tbl_session_rel_course session_rel_course - ON course.code = session_rel_course.course_code inner join $tbl_session_rel_course_rel_user as srcru - ON (srcru.id_session = session_rel_course.id_session) - WHERE id_user = $id_user and session_rel_course.id_session = $id_session"; + FROM $tbl_course course + LEFT JOIN $tbl_session_rel_course session_rel_course + ON course.id = session_rel_course.c_id + INNER JOIN $tbl_session_rel_course_rel_user as srcru + ON (srcru.id_session = session_rel_course.id_session) + WHERE + id_user = $id_user AND + session_rel_course.id_session = $id_session"; $rs = Database::query($sql); $existingCourses = Database::store_result($rs); @@ -70,7 +74,8 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { header('Location: session_course_user.php?id_session='.$id_session.'&id_user='.$id_user.'&msg='.get_lang('MaybeYouWantToDeleteThisUserFromSession')); exit; } - foreach($CourseList as $enreg_course) { + + foreach ($CourseList as $enreg_course) { $exists = false; foreach($existingCourses as $existingCourse) { if($enreg_course == $existingCourse['course_code']) { diff --git a/main/admin/session_course_user_list.php b/main/admin/session_course_user_list.php index c5a78c5367..0ed4e76a29 100755 --- a/main/admin/session_course_user_list.php +++ b/main/admin/session_course_user_list.php @@ -22,7 +22,10 @@ if (empty($id_session )) { api_not_allowed(); } -$course_code = Database::escape_string(trim($_GET['course_code'])); +$course_code = Database::escape_string(trim($_GET['course_code'])); +$courseInfo = api_get_course_info($course_code); +$courseId = $courseInfo['id']; + $page = isset($_GET['page']) ? intval($_GET['page']) : null; $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null; $default_sort = api_sort_by_first_name() ? 'firstname':'lastname'; @@ -42,8 +45,8 @@ if (is_array($idChecked)) { $sql = "SELECT s.name, c.title FROM $tbl_session_rel_course src INNER JOIN $tbl_session s ON s.id = src.id_session - INNER JOIN $tbl_course c ON c.code = src.course_code - WHERE src.id_session='$id_session' AND src.course_code='$course_code' "; + INNER JOIN $tbl_course c ON c.id = src.c_id + WHERE src.id_session='$id_session' AND src.c_id='$courseId' "; $result = Database::query($sql); if (!list($session_name,$course_title) = Database::fetch_row($result)) { @@ -58,9 +61,13 @@ switch ($action) { $idChecked = implode(',',$idChecked); } if (!empty($idChecked)) { - $result = Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='".$course_code."' AND id_user IN($idChecked)"); + $sql = "DELETE FROM $tbl_session_rel_course_rel_user + WHERE id_session='$id_session' AND c_id='".$courseId."' AND id_user IN($idChecked)"; + $result = Database::query($sql); $nbr_affected_rows = Database::affected_rows($result); - Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$id_session' AND course_code='".$course_code."'"); + $sql = "UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows + WHERE id_session='$id_session' AND c_id='".$courseId."'"; + Database::query($sql); } header('Location: '.api_get_self().'?id_session='.$id_session.'&course_code='.urlencode($course_code).'&sort='.$sort); exit(); diff --git a/main/admin/session_export.php b/main/admin/session_export.php index 7c452e96ef..e7fab7d1c7 100755 --- a/main/admin/session_export.php +++ b/main/admin/session_export.php @@ -154,23 +154,26 @@ if ($_POST['formSent']) { $add .= $users; //courses - $sql = "SELECT DISTINCT $tbl_course.code - FROM $tbl_course - INNER JOIN $tbl_session_course_user - ON $tbl_course.code = $tbl_session_course_user.course_code - AND $tbl_session_course_user.id_session = '".$row['id']."'"; + $sql = "SELECT DISTINCT c.code, sc.id, c_id + FROM $tbl_course c + INNER JOIN $tbl_session_course_user sc + ON c.id = sc.c_id + AND sc.id_session = '".$row['id']."'"; $rsCourses = Database::query($sql); $courses = ''; - while($rowCourses = Database::fetch_array($rsCourses)){ + while ($rowCourses = Database::fetch_array($rsCourses)){ // get coachs from a course $sql = "SELECT u.username FROM $tbl_session_course_user scu - INNER JOIN $tbl_user u ON u.user_id = scu.id_user - WHERE scu.course_code = '{$rowCourses['code']}' - AND scu.id_session = '".$row['id']."' AND scu.status = 2 "; + INNER JOIN $tbl_user u + ON u.user_id = scu.id_user + WHERE + scu.c_id = '{$rowCourses['c_id']}' AND + scu.id_session = '".$row['id']."' AND + scu.status = 2 "; $rs_coachs = Database::query($sql); $coachs = array(); @@ -180,11 +183,10 @@ if ($_POST['formSent']) { $coachs = implode(",",$coachs); - if($cvs){ + if ($cvs) { $courses .= str_replace(';',',',$rowCourses['code']); $courses .= '['.str_replace(';',',',$coachs).']['; - } - else { + } else { $courses .= "\t\t\n"; $courses .= "\t\t\t$rowCourses[code]\n"; $courses .= "\t\t\t$coachs\n"; @@ -193,26 +195,34 @@ if ($_POST['formSent']) { // rel user courses $sql = "SELECT DISTINCT u.username FROM $tbl_session_course_user scu - INNER JOIN $tbl_session_user su ON scu.id_user = su.id_user AND scu.id_session = su.id_session AND su.relation_type<>".SESSION_RELATION_TYPE_RRHH." + INNER JOIN $tbl_session_user su + ON + scu.id_user = su.id_user AND + scu.id_session = su.id_session AND + su.relation_type<>".SESSION_RELATION_TYPE_RRHH." INNER JOIN $tbl_user u ON scu.id_user = u.user_id - AND scu.course_code='".$rowCourses['code']."' + AND scu.c_id='".$rowCourses['c_id']."' AND scu.id_session='".$row['id']."'"; $rsUsersCourse = Database::query($sql); $userscourse = ''; - while($rowUsersCourse = Database::fetch_array($rsUsersCourse)){ - - if($cvs){ + while ($rowUsersCourse = Database::fetch_array($rsUsersCourse)){ + if ($cvs) { $userscourse .= str_replace(';',',',$rowUsersCourse['username']).','; - } - else { + } else { $courses .= "\t\t\t$rowUsersCourse[username]\n"; } } - if($cvs){ - if(!empty($userscourse)) - $userscourse = api_substr($userscourse , 0, api_strlen($userscourse)-1); + + if ($cvs) { + if (!empty($userscourse)) { + $userscourse = api_substr( + $userscourse, + 0, + api_strlen($userscourse) - 1 + ); + } $courses .= $userscourse.']|'; } diff --git a/main/admin/session_import.php b/main/admin/session_import.php index f06ef1e0c0..9062b04eed 100755 --- a/main/admin/session_import.php +++ b/main/admin/session_import.php @@ -315,15 +315,15 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { if (CourseManager::course_exists($course_code)) { // If the course exists we continue. $course_info = CourseManager::get_course_information($course_code); + $courseId = $course_info['c_id']; $session_course_relation = SessionManager::relation_session_course_exist($session_id, $course_code); if (!$session_course_relation) { $sql_course = "INSERT INTO $tbl_session_course SET - course_code = '$course_code', + c_id = '$courseId', id_session='$session_id'"; $rs_course = Database::query($sql_course); - $course_info = api_get_course_info($course['code']); - SessionManager::installCourse($id_session, $course_info['real_id']); + SessionManager::installCourse($id_session, $courseId); } $course_coaches = explode(',', $node_course->Coach); @@ -335,7 +335,7 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { if ($coach_id !== false) { $sql = "INSERT IGNORE INTO $tbl_session_course_user SET id_user='$coach_id', - course_code='$course_code', + c_id = '$courseId', id_session = '$session_id', status = 2 "; $rs_coachs = Database::query($sql); @@ -360,7 +360,7 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { // Adding to session_rel_user_rel_course table. $sql = "INSERT IGNORE INTO $tbl_session_course_user SET id_user='$user_id', - course_code='$course_code', + c_id='$courseId', id_session = '$session_id'"; $rs_users = Database::query($sql); $users_in_course_counter++; @@ -368,8 +368,8 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { $error_message .= get_lang('UserDoesNotExist').' : '.$username.'
      '; } } - $update_session_course = "UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='$course_code'"; - Database::query($update_session_course); + $sql = "UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE c_id='$courseId'"; + Database::query($sql); $inserted_in_course[$course_code] = $course_info['title']; } @@ -382,13 +382,15 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { if ($vcourse['code'] == $course_code) { // Ignore, this has already been inserted. } else { + $course_info = api_get_course_info($course['code']); + $courseId = $course_info['real_id']; $sql_course = "INSERT INTO $tbl_session_course SET - course_code = '".$vcourse['code']."', + c_id = '".$courseId."', id_session='$session_id'"; $rs_course = Database::query($sql_course); - $course_info = api_get_course_info($course['code']); - SessionManager::installCourse($id_session, $course_info['real_id']); + + SessionManager::installCourse($id_session, $courseId); $course_coaches = explode(",",$node_course->Coach); @@ -399,7 +401,7 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { if ($coach_id !== false) { $sql = "INSERT IGNORE INTO $tbl_session_course_user SET id_user='$coach_id', - course_code='{$vcourse['code']}', + c_id = $courseId, id_session = '$session_id', status = 2 "; $rs_coachs = Database::query($sql); @@ -424,7 +426,7 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { // Adding to session_rel_user_rel_course table. $sql = "INSERT IGNORE INTO $tbl_session_course_user SET id_user='$user_id', - course_code='{$vcourse['code']}', + c_id ='$courseId', id_session = '$session_id'"; $rs_users = Database::query($sql); $users_in_course_counter++; @@ -432,10 +434,9 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { $error_message .= get_lang('UserDoesNotExist').' : '.$username.'
      '; } } - $update_session_course = "UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='$course_code'"; - Database::query($update_session_course); + $sql = "UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE c_id='$courseId'"; + Database::query($sql); $inserted_in_course[$course_code] = $course_info['title']; - } $inserted_in_course[$vcourse['code']] = $vcourse['title']; } diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php index a5f83dd0b1..e3faab4ed3 100755 --- a/main/inc/lib/course.lib.php +++ b/main/inc/lib/course.lib.php @@ -3270,10 +3270,10 @@ class CourseManager $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE); $sessionId = intval($sessionId); $user_id = intval($user_id); - $select = "SELECT DISTINCT *, id as real_id "; + $select = "SELECT DISTINCT *, c.id as real_id "; if ($getCount) { - $select = "SELECT COUNT(DISTINCT id) as count"; + $select = "SELECT COUNT(DISTINCT c.id) as count"; } $whereConditions = null; diff --git a/main/inc/lib/urlmanager.lib.php b/main/inc/lib/urlmanager.lib.php index 4c0c537fe5..46d169202e 100755 --- a/main/inc/lib/urlmanager.lib.php +++ b/main/inc/lib/urlmanager.lib.php @@ -368,7 +368,7 @@ class UrlManager public static function relation_url_course_exist($courseId, $urlId) { $table_url_rel_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE); - $sql= "SELECT course_code FROM $table_url_rel_course + $sql= "SELECT c_id FROM $table_url_rel_course WHERE access_url_id = ".intval($urlId)." AND c_id = '".intval($courseId)."'"; $result = Database::query($sql); diff --git a/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php b/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php index 9059a922b2..32a12a2e39 100644 --- a/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php +++ b/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php @@ -81,6 +81,7 @@ class Version110 extends AbstractMigration $this->addSql("ALTER TABLE session MODIFY COLUMN name char(100) NOT NULL DEFAULT ''"); $this->addSql("ALTER TABLE course_rel_user ADD COLUMN c_id int default NULL"); $this->addSql("ALTER TABLE course_field_values ADD COLUMN c_id int default NULL"); + $this->addSql("ALTER TABLE session_rel_course_rel_user ADD COLUMN c_id int default NULL"); $this->addSql("UPDATE course_rel_user SET c_id = (SELECT id FROM course WHERE code = course_code)"); @@ -120,7 +121,8 @@ class Version110 extends AbstractMigration $this->addSql("UPDATE track_e_online SET c_id = (SELECT id FROM course WHERE code = course)"); $this->addSql("UPDATE track_e_attempt SET c_id = (SELECT id FROM course WHERE code = course_code)"); $this->addSql("UPDATE course_field_values SET c_id = (SELECT id FROM course WHERE code = course_code)"); - + $this->addSql("UPDATE session_rel_course_rel_user SET c_id = (SELECT id FROM course WHERE code = course_code)"); + $this->addSql("UPDATE session_rel_course SET c_id = (SELECT id FROM course WHERE code = course_code)"); //$this->addSql("UPDATE settings_current SET selected_value = '1.10.0.35' WHERE variable = 'chamilo_database_version'"); From 60c81ffea58dc86cac60fee1feee478817147e84 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 3 Apr 2015 16:11:48 +0200 Subject: [PATCH 057/159] Add missing file from 1.9.x --- main/inc/lib/api.lib.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/main/inc/lib/api.lib.php b/main/inc/lib/api.lib.php index e93ba96196..c0ac210830 100644 --- a/main/inc/lib/api.lib.php +++ b/main/inc/lib/api.lib.php @@ -8084,3 +8084,17 @@ function apiIsSystemInstalled() $version = $settingsRow['selected_value']; return array('installed' => 1, 'message' => $version); } + +/** + * Limit the access to Session Admins wheen the limit_session_admin_role + * configuration variable is set to true + */ +function api_protect_limit_for_session_admin() +{ + if ( + api_is_session_admin() && + api_get_configuration_value('limit_session_admin_role') + ) { + api_not_allowed(true); + } +} From 59ad2c869ba139ea1bee1a3c07783d8798268a41 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 3 Apr 2015 16:12:06 +0200 Subject: [PATCH 058/159] Minor - format code --- whoisonlinesession.php | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/whoisonlinesession.php b/whoisonlinesession.php index 7ee4cd5cdf..4a7edbb643 100755 --- a/whoisonlinesession.php +++ b/whoisonlinesession.php @@ -47,27 +47,28 @@ Display::display_header(get_lang('UserOnlineListSession')); $session_is_coach = array(); if (isset($_user['user_id']) && $_user['user_id'] != '') { $_user['user_id'] = intval($_user['user_id']); - $result = Database::query("SELECT DISTINCT id, - name, - date_start, - date_end - FROM $tbl_session as session - INNER JOIN $tbl_session_course_user as srcru - ON srcru.id_user = ".$_user['user_id']." AND srcru.status=2 - AND session.id = srcru.id_session - ORDER BY date_start, date_end, name"); + $sql = "SELECT DISTINCT id, + name, + date_start, + date_end + FROM $tbl_session as session + INNER JOIN $tbl_session_course_user as srcru + ON srcru.id_user = ".$_user['user_id']." AND srcru.status=2 + AND session.id = srcru.id_session + ORDER BY date_start, date_end, name"; + $result = Database::query($sql); while ($session = Database:: fetch_array($result)) { $session_is_coach[$session['id']] = $session; } $sql = "SELECT DISTINCT id, - name, - date_start, - date_end - FROM $tbl_session as session - WHERE session.id_coach = ".$_user['user_id']." - ORDER BY date_start, date_end, name"; + name, + date_start, + date_end + FROM $tbl_session as session + WHERE session.id_coach = ".$_user['user_id']." + ORDER BY date_start, date_end, name"; $result = Database::query($sql); while ($session = Database:: fetch_array($result)) { $session_is_coach[$session['id']] = $session; From 32d0c31f297ec7171ea41668c33d5ada76b35443 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 3 Apr 2015 16:12:15 +0200 Subject: [PATCH 059/159] Add missing c_id. --- .../CoreBundle/Entity/CourseFieldValues.php | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/src/Chamilo/CoreBundle/Entity/CourseFieldValues.php b/src/Chamilo/CoreBundle/Entity/CourseFieldValues.php index 258ba5804b..4b604576df 100644 --- a/src/Chamilo/CoreBundle/Entity/CourseFieldValues.php +++ b/src/Chamilo/CoreBundle/Entity/CourseFieldValues.php @@ -40,6 +40,14 @@ class CourseFieldValues */ private $tms; + /** + * @var integer + * + * @ORM\Column(name="c_id", type="integer", nullable=false) + */ + private $cId; + + /** * @var integer * @@ -49,8 +57,6 @@ class CourseFieldValues */ private $id; - - /** * Set courseCode * @@ -152,4 +158,28 @@ class CourseFieldValues { return $this->id; } + + /** + * Set cId + * + * @param integer $cId + * @return CAnnouncement + */ + public function setCId($cId) + { + $this->cId = $cId; + + return $this; + } + + /** + * Get cId + * + * @return integer + */ + public function getCId() + { + return $this->cId; + } + } From dc56c87bfdc790f8ccecc88d55b3937003a459ab Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 7 Apr 2015 16:00:06 +0200 Subject: [PATCH 060/159] Updating DB --- src/Chamilo/CoreBundle/Entity/Session.php | 78 +++++++++++++++++++ .../CoreBundle/Entity/SessionCategory.php | 5 +- .../CoreBundle/Entity/SessionRelCourse.php | 24 ++++++ .../CoreBundle/Entity/SessionRelUser.php | 11 ++- .../Migrations/Schema/v1/Version110.php | 32 +++++++- 5 files changed, 144 insertions(+), 6 deletions(-) diff --git a/src/Chamilo/CoreBundle/Entity/Session.php b/src/Chamilo/CoreBundle/Entity/Session.php index c985377646..a733398598 100644 --- a/src/Chamilo/CoreBundle/Entity/Session.php +++ b/src/Chamilo/CoreBundle/Entity/Session.php @@ -50,6 +50,43 @@ class Session */ private $name; + /** + * @var string + * + * @ORM\Column(name="description", type="text", nullable=true, unique=false) + */ + private $description; + + /** + * @var string + * + * @ORM\Column(name="show_description", type="boolean", nullable=true) + */ + private $showDescription; + + /** + * @var integer + * + * @ORM\Column(name="duration", type="integer", nullable=true) + */ + private $duration; + + /** + * @return int + */ + public function getDuration() + { + return $this->duration; + } + + /** + * @param int $duration + */ + public function setDuration($duration) + { + $this->duration = $duration; + } + /** * @var integer * @@ -224,6 +261,24 @@ class Session $this->courses = new ArrayCollection(); $this->users = new ArrayCollection(); $this->userCourseSubscriptions = new ArrayCollection(); + $this->showDescription = 0; + $this->category = null; + } + + /** + * @return string + */ + public function getShowDescription() + { + return $this->showDescription; + } + + /** + * @param string $showDescription + */ + public function setShowDescription($showDescription) + { + $this->showDescription = $showDescription; } /** @@ -468,6 +523,29 @@ class Session return $this->name; } + /** + * Set description + * + * @param string $description + * @return Groups + */ + public function setDescription($description) + { + $this->description = $description; + + return $this; + } + + /** + * Get description + * + * @return string + */ + public function getDescription() + { + return $this->description; + } + /** * Set nbrCourses * diff --git a/src/Chamilo/CoreBundle/Entity/SessionCategory.php b/src/Chamilo/CoreBundle/Entity/SessionCategory.php index d4fa92147e..aa66b011bc 100644 --- a/src/Chamilo/CoreBundle/Entity/SessionCategory.php +++ b/src/Chamilo/CoreBundle/Entity/SessionCategory.php @@ -18,7 +18,7 @@ class SessionCategory * * @ORM\Column(name="id", type="integer", precision=0, scale=0, nullable=false, unique=false) * @ORM\Id - * @ORM\GeneratedValue(strategy="AUTO") + * @ORM\GeneratedValue */ private $id; @@ -54,6 +54,9 @@ class SessionCategory **/ protected $session; + /** + * @return string + */ public function __toString() { return (string) $this->name; diff --git a/src/Chamilo/CoreBundle/Entity/SessionRelCourse.php b/src/Chamilo/CoreBundle/Entity/SessionRelCourse.php index 275b70cb8c..b8a4ab60a6 100644 --- a/src/Chamilo/CoreBundle/Entity/SessionRelCourse.php +++ b/src/Chamilo/CoreBundle/Entity/SessionRelCourse.php @@ -41,6 +41,13 @@ class SessionRelCourse */ protected $course; + /** + * @var integer + * + * @ORM\Column(name="position", type="integer", nullable=false) + */ + private $position; + /** * Constructor */ @@ -123,4 +130,21 @@ class SessionRelCourse { return $this->nbrUsers; } + + /** + * @return int + */ + public function getPosition() + { + return $this->position; + } + + /** + * @param int $position + */ + public function setPosition($position) + { + $this->position = $position; + } + } diff --git a/src/Chamilo/CoreBundle/Entity/SessionRelUser.php b/src/Chamilo/CoreBundle/Entity/SessionRelUser.php index cef2749903..c2db3dbdfc 100644 --- a/src/Chamilo/CoreBundle/Entity/SessionRelUser.php +++ b/src/Chamilo/CoreBundle/Entity/SessionRelUser.php @@ -24,6 +24,15 @@ class SessionRelUser 1 => 'drh' ); + /** + * @var integer + * + * @ORM\Column(name="id", type="integer") + * @ORM\Id + * @ORM\GeneratedValue + */ + private $relationType; + /** * @ORM\ManyToOne(targetEntity="Session", inversedBy="users", cascade={"persist"}) * @ORM\JoinColumn(name="id_session", referencedColumnName="id") @@ -40,8 +49,6 @@ class SessionRelUser * @var integer * * @ORM\Column(name="relation_type", type="integer", precision=0, scale=0, nullable=false, unique=false) - * @ORM\Id - * @ORM\GeneratedValue(strategy="NONE") */ private $relationType; diff --git a/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php b/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php index 32a12a2e39..93f3c489eb 100644 --- a/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php +++ b/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php @@ -12,6 +12,10 @@ use Doctrine\DBAL\Migrations\AbstractMigration, */ class Version110 extends AbstractMigration { + /** + * @param Schema $schema + * @throws \Doctrine\DBAL\Schema\SchemaException + */ public function up(Schema $schema) { // Use $schema->createTable @@ -54,7 +58,7 @@ class Version110 extends AbstractMigration $this->addSql("ALTER TABLE skill ADD COLUMN criteria text DEFAULT ''"); $this->addSql("ALTER TABLE gradebook_category ADD COLUMN generate_certificates TINYINT NOT NULL DEFAULT 0"); $this->addSql("ALTER TABLE track_e_access ADD COLUMN c_id int NOT NULL"); - //$this->addSql("ALTER TABLE track_e_default ADD COLUMN c_id int NOT NULL"); //already added in 1.9.x + $this->addSql("ALTER TABLE track_e_lastaccess ADD COLUMN c_id int NOT NULL"); $this->addSql("ALTER TABLE track_e_exercices ADD COLUMN c_id int NOT NULL"); $this->addSql("ALTER TABLE track_e_downloads ADD COLUMN c_id int NOT NULL"); @@ -85,6 +89,28 @@ class Version110 extends AbstractMigration $this->addSql("UPDATE course_rel_user SET c_id = (SELECT id FROM course WHERE code = course_code)"); + // Add iid + $tables = [ + 'c_group_info', + 'c_course_setting', + 'c_tool', + 'c_group_info', + 'c_document', + 'c_item_property' + ]; + + foreach ($tables as $table) { + $this->addSql("ALTER TABLE $table MODIFY COLUMN id int unsigned DEFAULT NULL"); + $this->addSql("ALTER TABLE $table MODIFY COLUMN c_id int unsigned DEFAULT NULL"); + $this->addSql("ALTER TABLE $table DROP PRIMARY KEY"); + $this->addSql("ALTER TABLE $table ADD COLUMN iid int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT"); + } + + $this->addSql("ALTER TABLE session_rel_user MODIFY COLUMN relation_type int unsigned DEFAULT 0"); + $this->addSql("ALTER TABLE session_rel_user DROP PRIMARY KEY"); + $this->addSql("ALTER TABLE session_rel_user ADD COLUMN id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT"); + + // Course $this->addSql("ALTER TABLE c_survey ADD COLUMN visible_results INT UNSIGNED DEFAULT 0"); $this->addSql("ALTER TABLE c_survey_invitation ADD COLUMN group_id INT NOT NULL"); @@ -124,8 +150,6 @@ class Version110 extends AbstractMigration $this->addSql("UPDATE session_rel_course_rel_user SET c_id = (SELECT id FROM course WHERE code = course_code)"); $this->addSql("UPDATE session_rel_course SET c_id = (SELECT id FROM course WHERE code = course_code)"); - //$this->addSql("UPDATE settings_current SET selected_value = '1.10.0.35' WHERE variable = 'chamilo_database_version'"); - $this->addSql("DELETE FROM settings_current WHERE variable = 'wcag_anysurfer_public_pages'"); $this->addSql("DELETE FROM settings_options WHERE variable = 'wcag_anysurfer_public_pages'"); $this->addSql("DELETE FROM settings_current WHERE variable = 'advanced_filemanager'"); @@ -170,6 +194,8 @@ class Version110 extends AbstractMigration $this->addSql("DROP TABLE track_c_referers"); //$this->addSql('ALTER TABLE user DROP COLUMN user_id'); + + //$this->addSql("UPDATE settings_current SET selected_value = '1.10.0.35' WHERE variable = 'chamilo_database_version'"); } public function down(Schema $schema) From 83e3494c02ab1c23ef8e00ff8d4d2244e2a7c4ad Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Tue, 7 Apr 2015 16:00:45 +0200 Subject: [PATCH 061/159] Replace course_code with c_id --- main/admin/add_courses_to_session.php | 31 +- main/admin/add_users_to_session.php | 18 +- main/admin/course_edit.php | 8 +- main/admin/course_information.php | 5 +- main/admin/resume_session.php | 20 +- main/admin/session_course_edit.php | 17 +- main/admin/session_import.php | 2 +- main/admin/teacher_time_report.php | 6 +- main/admin/user_information.php | 2 +- main/attendance/attendance_controller.php | 2 +- main/attendance/attendance_sheet.php | 2 +- main/course_info/legal.php | 2 +- main/cron/create_course_sessions.php | 2 +- main/cron/import_csv.php | 9 +- main/document/document_quota.php | 4 +- main/exercice/exercise_show.php | 2 +- main/gradebook/lib/fe/displaygradebook.php | 3 +- main/inc/ajax/course.ajax.php | 2 +- main/inc/lib/AnnouncementEmail.php | 7 +- main/inc/lib/AnnouncementManager.php | 2 +- main/inc/lib/add_course.lib.inc.php | 271 ++++++--------- main/inc/lib/api.lib.php | 92 ++++-- main/inc/lib/attendance.lib.php | 3 +- main/inc/lib/course.lib.php | 144 ++++---- main/inc/lib/document.lib.php | 10 +- main/inc/lib/pdf.lib.php | 2 +- main/inc/lib/sessionmanager.lib.php | 366 ++++++++++++--------- main/inc/lib/template.lib.php | 8 +- main/inc/lib/tracking.lib.php | 182 ++++++---- main/inc/lib/usermanager.lib.php | 29 +- main/inc/lib/userportal.lib.php | 2 +- main/mySpace/myStudents.php | 2 +- main/session/index.php | 6 +- main/tracking/courseLog.php | 4 +- main/tracking/exams.php | 2 +- main/webservices/webservice_session.php | 3 +- main/work/work.lib.php | 2 +- tests/scripts/course2session.php | 2 +- 38 files changed, 692 insertions(+), 584 deletions(-) diff --git a/main/admin/add_courses_to_session.php b/main/admin/add_courses_to_session.php index 80c6bd6859..96ff7afc75 100755 --- a/main/admin/add_courses_to_session.php +++ b/main/admin/add_courses_to_session.php @@ -115,7 +115,7 @@ $ajax_search = $add_type == 'unique' ? true : false; $nosessionCourses = $sessionCourses = array(); if ($ajax_search) { - $sql="SELECT code, title, visual_code, id_session + $sql="SELECT course.id, code, title, visual_code, id_session FROM $tbl_course course INNER JOIN $tbl_session_rel_course session_rel_course ON course.id = session_rel_course.c_id @@ -126,7 +126,7 @@ if ($ajax_search) { $tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE); $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1){ - $sql="SELECT code, title, visual_code, id_session + $sql="SELECT course.id, code, title, visual_code, id_session FROM $tbl_course course INNER JOIN $tbl_session_rel_course session_rel_course ON course.id = session_rel_course.c_id @@ -141,25 +141,27 @@ if ($ajax_search) { $Courses = Database::store_result($result); foreach ($Courses as $course) { - $sessionCourses[$course['code']] = $course ; + $sessionCourses[$course['id']] = $course ; } } else { - $sql = "SELECT code, title, visual_code, id_session + $sql = "SELECT course.id, code, title, visual_code, id_session FROM $tbl_course course LEFT JOIN $tbl_session_rel_course session_rel_course - ON course.code = session_rel_course.course_code - AND session_rel_course.id_session = ".intval($sessionId)." + ON + course.id = session_rel_course.c_id AND + session_rel_course.id_session = ".intval($sessionId)." ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title"; if (api_is_multiple_url_enabled()) { $tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE); $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1){ - $sql="SELECT code, title, visual_code, id_session + $sql="SELECT course.id, code, title, visual_code, id_session FROM $tbl_course course LEFT JOIN $tbl_session_rel_course session_rel_course - ON course.code = session_rel_course.course_code - AND session_rel_course.id_session = ".intval($sessionId)." + ON + course.id = session_rel_course.c_id AND + session_rel_course.id_session = ".intval($sessionId)." INNER JOIN $tbl_course_rel_access_url url_course ON (url_course.c_id = course.id) WHERE access_url_id = $access_url_id ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title"; @@ -169,9 +171,9 @@ if ($ajax_search) { $Courses = Database::store_result($result); foreach ($Courses as $course) { if ($course['id_session'] == $sessionId) { - $sessionCourses[$course['code']] = $course ; + $sessionCourses[$course['id']] = $course ; } else { - $nosessionCourses[$course['code']] = $course ; + $nosessionCourses[$course['id']] = $course ; } } } @@ -199,9 +201,10 @@ unset($Courses); ?>
      - +
      : - + : - +
      '.get_lang('EditSessionCourses').''; ?> - + + diff --git a/main/admin/session_course_user_list.php b/main/admin/session_course_user_list.php index 43858741df..76809db05a 100755 --- a/main/admin/session_course_user_list.php +++ b/main/admin/session_course_user_list.php @@ -58,11 +58,11 @@ switch ($action) { case 'delete': if (is_array($idChecked) && count($idChecked)>0) { array_map('intval', $idChecked); - $idChecked = implode(',',$idChecked); + $idChecked = implode(',', $idChecked); } if (!empty($idChecked)) { $sql = "DELETE FROM $tbl_session_rel_course_rel_user - WHERE session_id='$id_session' AND c_id='".$courseId."' AND id_user IN($idChecked)"; + WHERE session_id='$id_session' AND c_id='".$courseId."' AND user_id IN($idChecked)"; $result = Database::query($sql); $nbr_affected_rows = Database::affected_rows($result); $sql = "UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows @@ -84,7 +84,7 @@ $limit = 20; $from = $page * $limit; $is_western_name_order = api_is_western_name_order(); $sql = "SELECT DISTINCT - u.user_id,".($is_western_name_order ? 'u.firstname, u.lastname' : 'u.lastname, u.firstname').", u.username, scru.id_user as is_subscribed + u.user_id,".($is_western_name_order ? 'u.firstname, u.lastname' : 'u.lastname, u.firstname').", u.username, scru.user_id as is_subscribed FROM $tbl_session_rel_user s INNER JOIN $tbl_user u ON (u.user_id=s.user_id) LEFT JOIN $tbl_session_rel_course_rel_user scru diff --git a/main/admin/session_export.php b/main/admin/session_export.php index d6d333a8e4..12e08d277e 100755 --- a/main/admin/session_export.php +++ b/main/admin/session_export.php @@ -171,7 +171,7 @@ if ($_POST['formSent']) { $sql = "SELECT u.username FROM $tbl_session_course_user scu INNER JOIN $tbl_user u - ON u.user_id = scu.id_user + ON u.user_id = scu.user_id WHERE scu.c_id = '{$rowCourses['c_id']}' AND scu.session_id = '".$row['id']."' AND @@ -199,7 +199,7 @@ if ($_POST['formSent']) { FROM $tbl_session_course_user scu INNER JOIN $tbl_session_user su ON - scu.user_id = su.id_user AND + scu.user_id = su.user_id AND scu.session_id = su.session_id AND su.relation_type<>".SESSION_RELATION_TYPE_RRHH." INNER JOIN $tbl_user u diff --git a/main/admin/session_import.php b/main/admin/session_import.php index 137422d457..5e38352df5 100755 --- a/main/admin/session_import.php +++ b/main/admin/session_import.php @@ -334,7 +334,7 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { $coach_id = UserManager::get_user_id_from_username($course_coach); if ($coach_id !== false) { $sql = "INSERT IGNORE INTO $tbl_session_course_user SET - id_user='$coach_id', + user_id='$coach_id', c_id = '$courseId', session_id = '$session_id', status = 2 "; @@ -400,7 +400,7 @@ if (isset($_POST['formSent']) && $_POST['formSent']) { $coach_id = UserManager::get_user_id_from_username($course_coach); if ($coach_id !== false) { $sql = "INSERT IGNORE INTO $tbl_session_course_user SET - id_user='$coach_id', + user_id='$coach_id', c_id = $courseId, session_id = '$session_id', status = 2 "; diff --git a/main/auth/ldap/authldap.php b/main/auth/ldap/authldap.php index c30796ffcf..30d62b943c 100755 --- a/main/auth/ldap/authldap.php +++ b/main/auth/ldap/authldap.php @@ -567,7 +567,7 @@ function ldap_add_user_to_session($UserList, $id_session) { "(session_id,c_id,user_id) VALUES ". "('$id_session','$enreg_course','$enreg_user')"); } - $sql = "SELECT COUNT(id_user) as nbUsers ". + $sql = "SELECT COUNT(user_id) as nbUsers ". " FROM $tbl_session_rel_course_rel_user " . " WHERE session_id='$id_session' ". " AND c_id='$enreg_course'"; @@ -585,7 +585,7 @@ function ldap_add_user_to_session($UserList, $id_session) { " VALUES('$id_session','$enreg_user')"); } // We update the number of users in the session - $sql = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_user ". + $sql = "SELECT COUNT(user_id) as nbUsers FROM $tbl_session_rel_user ". " WHERE session_id='$id_session' ". " AND relation_type<>".SESSION_RELATION_TYPE_RRHH." "; $rs = Database::query($sql); diff --git a/main/chat/chat_whoisonline.php b/main/chat/chat_whoisonline.php index 03f83eb3b1..d9efa3eb83 100755 --- a/main/chat/chat_whoisonline.php +++ b/main/chat/chat_whoisonline.php @@ -51,13 +51,14 @@ if (!empty($course)) { if (empty($session_id)) { $query = "SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri,email,t3.status FROM $tbl_user t1, $tbl_chat_connected t2, $tbl_course_user t3 - WHERE t2.c_id = $course_id AND - t1.user_id=t2.user_id AND - t3.user_id=t2.user_id AND - t3.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND - t3.c_id = '".$courseInfo['id']."' AND - t2.last_connection>'".$date_inter."' $extra_condition - ORDER BY username"; + WHERE + t2.c_id = $course_id AND + t1.user_id=t2.user_id AND + t3.user_id=t2.user_id AND + t3.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND + t3.c_id = '".$courseInfo['id']."' AND + t2.last_connection>'".$date_inter."' $extra_condition + ORDER BY username"; $result = Database::query($query); $users = Database::store_result($result); } else { @@ -66,9 +67,11 @@ if (!empty($course)) { FROM $tbl_user t1, $tbl_chat_connected t2, $tbl_session_course_user t3 WHERE t2.c_id = $course_id AND - t1.user_id=t2.user_id AND t3.id_user=t2.user_id AND + t1.user_id=t2.user_id AND t3.user_id=t2.user_id AND t3.session_id = '".$session_id."' AND - t3.course_code = '".$_course['sysCode']."' AND t2.last_connection>'".$date_inter."' $extra_condition ORDER BY username"; + t3.c_id = '".$_course['real_id']."' AND + t2.last_connection>'".$date_inter."' $extra_condition + ORDER BY username"; $result = Database::query($query); while ($learner = Database::fetch_array($result)) { $users[$learner['user_id']] = $learner; @@ -77,8 +80,14 @@ if (!empty($course)) { // select session coach $query = "SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri,email FROM $tbl_user t1,$tbl_chat_connected t2,$tbl_session t3 - WHERE t2.c_id = $course_id AND - t1.user_id=t2.user_id AND t3.id_coach=t2.user_id AND t3.id = '".$session_id."' AND t2.last_connection>'".$date_inter."' $extra_condition ORDER BY username"; + WHERE + t2.c_id = $course_id AND + t1.user_id=t2.user_id AND + t3.id_coach=t2.user_id AND + t3.id = '".$session_id."' AND + t2.last_connection > '".$date_inter."' + $extra_condition + ORDER BY username"; $result = Database::query($query); if ($coach = Database::fetch_array($result)) { $users[$coach['user_id']] = $coach; @@ -90,7 +99,7 @@ if (!empty($course)) { WHERE t2.c_id = $course_id AND t1.user_id=t2.user_id - AND t3.id_user=t2.user_id AND t3.status=2 + AND t3.user_id =t2.user_id AND t3.status=2 AND t3.session_id = '".$session_id."' AND t3.c_id = '".$course_id."' AND t2.last_connection>'".$date_inter."' $extra_condition diff --git a/main/cron/remind_course_expiration.php b/main/cron/remind_course_expiration.php index 7f8d99dcd8..39792100ca 100644 --- a/main/cron/remind_course_expiration.php +++ b/main/cron/remind_course_expiration.php @@ -47,11 +47,11 @@ $usersToBeReminded = array(); foreach ($sessions as $sessionId => $userIds) { $userId = 0; - $userIds = $userIds ? " AND id_user NOT IN (".implode(",", $userIds).")" : null; + $userIds = $userIds ? " AND sessionUser.user_id NOT IN (".implode(",", $userIds).")" : null; $query = "SELECT sessionUser.session_id, sessionUser.user_id, session.name, session.date_end FROM ". Database::get_main_table(TABLE_MAIN_SESSION_USER)." AS sessionUser - INNER JOIN ".Database::get_main_table(TABLE_MAIN_SESSION). - " AS session ON sessionUser.session_id = session.id + INNER JOIN ".Database::get_main_table(TABLE_MAIN_SESSION)." AS session + ON sessionUser.session_id = session.id WHERE session_id = $sessionId$userIds"; $result = Database::query($query); while ($row = Database::fetch_array($result)) { diff --git a/main/exercice/exercise_reminder.php b/main/exercice/exercise_reminder.php index 9038cb5e49..22c274ca73 100755 --- a/main/exercice/exercise_reminder.php +++ b/main/exercice/exercise_reminder.php @@ -4,7 +4,7 @@ * Exercise reminder overview * Then it shows the results on the screen. * @package chamilo.exercise -* @author Julio Montoya Armas switchable fill in blank option added +* @author Julio Montoya switchable fill in blank option added */ require_once '../inc/global.inc.php'; diff --git a/main/exercice/exercise_result.php b/main/exercice/exercise_result.php index dab853844f..b131a77271 100755 --- a/main/exercice/exercise_result.php +++ b/main/exercice/exercise_result.php @@ -10,7 +10,7 @@ * @package chamilo.exercise * @author Olivier Brouckaert, main author * @author Roan Embrechts, some refactoring -* @author Julio Montoya Armas switchable fill in blank option added +* @author Julio Montoya switchable fill in blank option added * * @todo split more code up in functions, move functions to library? */ diff --git a/main/exercice/exercise_show.php b/main/exercice/exercise_show.php index 3064352f7e..219b0ed89e 100755 --- a/main/exercice/exercise_show.php +++ b/main/exercice/exercise_show.php @@ -4,7 +4,7 @@ /** * Shows the exercise results * - * @author Julio Montoya Armas Added switchable fill in blank option added + * @author Julio Montoya - Added switchable fill in blank option added * @version $Id: exercise_show.php 22256 2009-07-20 17:40:20Z ivantcholakov $ * @package chamilo.exercise * @todo remove the debug code and use the general debug library @@ -56,7 +56,7 @@ if (empty($id)) { if (api_is_course_session_coach( api_get_user_id(), - api_get_course_id(), + api_get_course_int_id(), api_get_session_id() )) { if (!api_coach_can_edit_view_results(api_get_course_int_id(), api_get_session_id())) { diff --git a/main/exercice/result.php b/main/exercice/result.php index 766bcaab44..4147cd6125 100755 --- a/main/exercice/result.php +++ b/main/exercice/result.php @@ -3,7 +3,7 @@ /** * Shows the exercise results * - * @author Julio Montoya Armas - Simple exercise result page + * @author Julio Montoya - Simple exercise result page * */ require_once '../inc/global.inc.php'; diff --git a/main/forum/forumfunction.inc.php b/main/forum/forumfunction.inc.php index 553af44f4f..f731b179dc 100755 --- a/main/forum/forumfunction.inc.php +++ b/main/forum/forumfunction.inc.php @@ -1974,13 +1974,13 @@ function get_thread_users_qualify($thread_id) FROM $t_posts post , $t_users user, $t_session_rel_user session_rel_user_rel_course, $t_qualify qualify WHERE poster_id = user.user_id AND post.poster_id = qualify.user_id - AND user.user_id = session_rel_user_rel_course.id_user + AND user.user_id = session_rel_user_rel_course.user_id AND session_rel_user_rel_course.status<>'2' - AND session_rel_user_rel_course.id_user NOT IN ($user_to_avoid) + AND session_rel_user_rel_course.user_id NOT IN ($user_to_avoid) AND qualify.thread_id = '".Database::escape_string($thread_id)."' AND post.thread_id = '".Database::escape_string($thread_id)."' AND session_id = '".api_get_session_id()."' - AND course_code = '".$course_code."' AND + AND session_rel_user_rel_course.c_id = '".$course_id."' AND qualify.c_id = $course_id AND post.c_id = $course_id $orderby "; @@ -2054,12 +2054,12 @@ function get_thread_users_not_qualify($thread_id) FROM $t_posts post , $t_users user, $t_session_rel_user session_rel_user_rel_course WHERE poster_id = user.user_id AND user.user_id NOT IN (".$cad.") - AND user.user_id = session_rel_user_rel_course.id_user + AND user.user_id = session_rel_user_rel_course.user_id AND session_rel_user_rel_course.status<>'2' - AND session_rel_user_rel_course.id_user NOT IN ($user_to_avoid) + AND session_rel_user_rel_course.user_id NOT IN ($user_to_avoid) AND post.thread_id = '".Database::escape_string($thread_id)."' AND session_id = '".api_get_session_id()."' - AND course_code = '".$course_code."' AND post.c_id = $course_id $orderby "; + AND session_rel_user_rel_course.c_id = '".$course_id."' AND post.c_id = $course_id $orderby "; } else { $sql = "SELECT DISTINCT user.user_id, user.lastname, user.firstname, post.thread_id FROM $t_posts post, $t_users user,$t_course_user course_user diff --git a/main/gradebook/lib/GradebookUtils.php b/main/gradebook/lib/GradebookUtils.php index d35e070af6..ddca492fc4 100644 --- a/main/gradebook/lib/GradebookUtils.php +++ b/main/gradebook/lib/GradebookUtils.php @@ -960,7 +960,7 @@ class GradebookUtils $sql = "SELECT user.user_id, user.username, lastname, firstname, official_code FROM $tbl_session_course_user as scru, $tbl_user as user WHERE - scru.id_user=user.user_id AND + scru.user_id = user.user_id AND scru.status=0 AND scru.c_id='$courseId' AND session_id ='$current_session' diff --git a/main/gradebook/lib/be/result.class.php b/main/gradebook/lib/be/result.class.php index bab7daef10..0fae4f85b4 100755 --- a/main/gradebook/lib/be/result.class.php +++ b/main/gradebook/lib/be/result.class.php @@ -98,12 +98,12 @@ class Result $sql_course_rel_user = ''; if ($sessionId) { - $sql = 'SELECT c_id, id_user as user_id, status + $sql = 'SELECT c_id, user_id as user_id, status FROM ' . $tbl_session_rel_course_user . ' WHERE - status=0 AND - c_id="' . api_get_course_int_id() . '" AND - session_id=' . $sessionId; + status= 0 AND + c_id = "' . api_get_course_int_id() . '" AND + session_id = ' . $sessionId; } else { $sql = 'SELECT c_id, user_id, status FROM ' . $tbl_course_rel_course . ' diff --git a/main/inc/lib/api.lib.php b/main/inc/lib/api.lib.php index 9eef7fcc2f..a2f3b4c175 100644 --- a/main/inc/lib/api.lib.php +++ b/main/inc/lib/api.lib.php @@ -2388,7 +2388,7 @@ function api_get_coachs_from_course($session_id = 0, $courseId = '') u.username FROM $tbl_user u, $tbl_session_course_user scu WHERE - u.user_id = scu.id_user AND + u.user_id = scu.user_id AND scu.session_id = '$session_id' AND scu.c_id = '$courseId' AND scu.status = 2"; @@ -2694,29 +2694,30 @@ function api_get_user_platform_status($user_id = null) { /** * @param int $user_id - * @param string $course_code + * @param int $courseId * @param int $session_id * @return bool */ -function api_is_course_session_coach($user_id, $course_code, $session_id) +function api_is_course_session_coach($user_id, $courseId, $session_id) { - $session_table = Database::get_main_table(TABLE_MAIN_SESSION); + $session_table = Database::get_main_table(TABLE_MAIN_SESSION); $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $user_id = intval($user_id); $session_id = intval($session_id); - $course_code = Database::escape_string($course_code); + $courseId = intval($courseId); $sql = "SELECT DISTINCT id FROM $session_table INNER JOIN $session_rel_course_rel_user_table session_rc_ru ON session.id = session_rc_ru.session_id WHERE - session_rc_ru.id_user = '".$user_id."' AND - session_rc_ru.course_code = '$course_code' AND + session_rc_ru.user_id = '".$user_id."' AND + session_rc_ru.c_id = '$courseId' AND session_rc_ru.status = 2 AND session_rc_ru.session_id = '$session_id'"; $result = Database::query($sql); + return Database::num_rows($result) > 0; } @@ -2756,7 +2757,7 @@ function api_is_coach($session_id = 0, $courseId = null, $check_student_view = t $sql = "SELECT DISTINCT s.id, name, date_start, date_end FROM $session_table s INNER JOIN $session_rel_course_rel_user_table session_rc_ru - ON session_rc_ru.session_id = s.id AND session_rc_ru.id_user = '".$userId."' + ON session_rc_ru.session_id = s.id AND session_rc_ru.user_id = '".$userId."' WHERE session_rc_ru.c_id = '$courseId' AND session_rc_ru.status = 2 AND @@ -5410,10 +5411,8 @@ function api_is_course_visible_for_user($userid = null, $cid = null) { tutor_id, status, role FROM $tbl_course_user WHERE - user_id = '$userid' - AND - relation_type <> '".COURSE_RELATION_TYPE_RRHH."' - AND + user_id = '$userid' AND + relation_type <> '".COURSE_RELATION_TYPE_RRHH."' AND c_id = $courseId LIMIT 1"; @@ -5424,10 +5423,11 @@ function api_is_course_visible_for_user($userid = null, $cid = null) { $cuData = Database::fetch_array($result); $_courseUser['role'] = $cuData['role']; - $is_courseMember = true; - $is_courseTutor = ($cuData['tutor_id' ] == 1); - $is_courseAdmin = ($cuData['status'] == 1); + $is_courseMember = true; + $is_courseTutor = ($cuData['tutor_id'] == 1); + $is_courseAdmin = ($cuData['status'] == 1); } + if (!$is_courseAdmin) { // This user has no status related to this course. // Is it the session coach or the session admin? @@ -5441,7 +5441,7 @@ function api_is_course_visible_for_user($userid = null, $cid = null) { $tbl_session as session INNER JOIN $tbl_session_course ON session_rel_course.session_id = session.id - AND session_rel_course.course_code = '$cid' + AND session_rel_course.c_id = '$courseId' LIMIT 1"; $result = Database::query($sql); @@ -5467,7 +5467,7 @@ function api_is_course_visible_for_user($userid = null, $cid = null) { // Check if the current user is the course coach. $sql = "SELECT 1 FROM $tbl_session_course - WHERE session_rel_course.course_code = '$cid' + WHERE session_rel_course.c_id = '$courseId' AND session_rel_course.id_coach = '$userid' LIMIT 1"; @@ -5484,7 +5484,8 @@ function api_is_course_visible_for_user($userid = null, $cid = null) { $tbl_user = Database :: get_main_table(TABLE_MAIN_USER); $sql = "SELECT status FROM $tbl_user - WHERE user_id = $userid LIMIT 1"; + WHERE user_id = $userid + LIMIT 1"; $result = Database::query($sql); @@ -5496,18 +5497,19 @@ function api_is_course_visible_for_user($userid = null, $cid = null) { } else { // Check if the user is a student is this session. $sql = "SELECT id - FROM $tbl_session_course_user - WHERE id_user = '$userid' - AND course_code = '$cid' + FROM $tbl_session_course_user + WHERE + user_id = '$userid' AND + c_id = '$courseId' LIMIT 1"; if (Database::num_rows($result) > 0) { // This user haa got a recorded state for this course. while ($row = Database::fetch_array($result)) { - $is_courseMember = true; - $is_courseTutor = false; - $is_courseAdmin = false; - $is_sessionAdmin = false; + $is_courseMember = true; + $is_courseTutor = false; + $is_courseAdmin = false; + $is_sessionAdmin = false; } } } @@ -5525,6 +5527,7 @@ function api_is_course_visible_for_user($userid = null, $cid = null) { case COURSE_VISIBILITY_HIDDEN: return $is_platformAdmin; } + return false; } diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php index 68af31cc23..3d575e6f58 100755 --- a/main/inc/lib/course.lib.php +++ b/main/inc/lib/course.lib.php @@ -445,15 +445,16 @@ class CourseManager // Delete in table session_rel_course_rel_user $sql = "DELETE FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " - WHERE session_id ='" . $session_id . "' AND - c_id = '" . $course_id . "' AND - id_user IN ($user_ids)"; + WHERE + session_id ='" . $session_id . "' AND + c_id = '" . $course_id . "' AND + user_id IN ($user_ids)"; Database::query($sql); foreach ($user_list as $uid) { // check if a user is register in the session with other course - $sql = "SELECT id_user FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " - WHERE session_id='$session_id' AND id_user='$uid'"; + $sql = "SELECT user_id FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " + WHERE session_id='$session_id' AND user_id='$uid'"; $rs = Database::query($sql); if (Database::num_rows($rs) == 0) { @@ -461,7 +462,7 @@ class CourseManager $sql = "DELETE FROM " . Database::get_main_table(TABLE_MAIN_SESSION_USER) . " WHERE session_id ='" . $session_id . "' AND - user_id ='$uid' AND + user_id = '$uid' AND relation_type<>" . SESSION_RELATION_TYPE_RRHH . ""; Database::query($sql); } @@ -1074,19 +1075,19 @@ class CourseManager $tableSessionCourseUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $sql = 'SELECT 1 FROM ' . $tableSessionCourseUser . - ' WHERE id_user = ' . $user_id . ' ' . $condition_course; + ' WHERE user_id = ' . $user_id . ' ' . $condition_course; if (Database::num_rows(Database::query($sql)) > 0) { return true; } $sql = 'SELECT 1 FROM ' . $tableSessionCourseUser . - ' WHERE id_user = ' . $user_id . ' AND status=2 ' . $condition_course; + ' WHERE user_id = ' . $user_id . ' AND status=2 ' . $condition_course; if (Database::num_rows(Database::query($sql)) > 0) { return true; } $sql = 'SELECT 1 FROM ' . Database::get_main_table(TABLE_MAIN_SESSION) . - ' WHERE id=' . $session_id . ' AND id_coach=' . $user_id; + ' WHERE id = ' . $session_id . ' AND id_coach=' . $user_id; if (Database::num_rows(Database::query($sql)) > 0) { return true; @@ -1160,29 +1161,29 @@ class CourseManager // Is he/she subscribed to the session's course? // A user? - if (Database::num_rows(Database::query("SELECT id_user - FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " - WHERE session_id='" . $session_id . "' - AND id_user='$user_id'")) + if (Database::num_rows(Database::query("SELECT user_id + FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " + WHERE session_id='" . $session_id . "' + AND user_id ='$user_id'")) ) { return true; } // A course coach? - if (Database::num_rows(Database::query("SELECT id_user - FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " - WHERE session_id='" . $session_id . "' - AND id_user = '$user_id' AND status = 2 - AND course_code='$course_code'")) + if (Database::num_rows(Database::query("SELECT user_id + FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " + WHERE session_id='" . $session_id . "' + AND user_id = '$user_id' AND status = 2 + AND course_code='$course_code'")) ) { return true; } // A session coach? if (Database::num_rows(Database::query("SELECT id_coach - FROM " . Database::get_main_table(TABLE_MAIN_SESSION) . " AS session - WHERE session.id='" . $session_id . "' - AND id_coach='$user_id'")) + FROM " . Database::get_main_table(TABLE_MAIN_SESSION) . " AS session + WHERE session.id='" . $session_id . "' + AND id_coach='$user_id'")) ) { return true; } @@ -1285,7 +1286,7 @@ class CourseManager $sql .= ' FROM ' . Database::get_main_table(TABLE_MAIN_USER) . ' as user '; $sql .= " LEFT JOIN ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " as session_course_user ON - user.user_id = session_course_user.id_user AND + user.user_id = session_course_user.user_id AND $courseCondition $sessionCondition INNER JOIN $course_table course ON session_course_user.c_id = course.id @@ -1621,7 +1622,7 @@ class CourseManager $where = array(); if (!empty($session_id)) { $sql .= ' LEFT JOIN ' . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . ' as session_course_user - ON user.user_id = session_course_user.id_user + ON user.user_id = session_course_user.user_id AND session_course_user.c_id = "' . $courseId . '" AND session_course_user.session_id = ' . $session_id; @@ -1676,11 +1677,11 @@ class CourseManager $users = array(); // We get the coach for the given course in a given session. - $sql = 'SELECT id_user FROM ' . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . + $sql = 'SELECT user_id FROM ' . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . ' WHERE session_id ="' . $session_id . '" AND c_id="' . $courseId . '" AND status = 2'; $rs = Database::query($sql); while ($user = Database::fetch_array($rs)) { - $user_info = api_get_user_info($user['id_user']); + $user_info = api_get_user_info($user['user_id']); $user_info['status'] = $user['status']; $user_info['role'] = $user['role']; $user_info['tutor_id'] = $user['tutor_id']; @@ -1761,7 +1762,7 @@ class CourseManager $sql_query = "SELECT * FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " scu $joinSession - INNER JOIN $userTable u ON scu.id_user = u.user_id + INNER JOIN $userTable u ON scu.user_id = u.user_id WHERE scu.c_id = '$courseId' AND scu.status <> 2"; if (!empty($date_from) && !empty($date_to)) { @@ -1887,7 +1888,7 @@ class CourseManager $sql = "SELECT DISTINCT u.user_id,u.lastname,u.firstname,u.username FROM $tbl_user u, $tbl_session_course_user scu WHERE - u.user_id = scu.id_user AND + u.user_id = scu.user_id AND scu.session_id = '$session_id' AND scu.c_id = '$courseId' AND scu.status = 2"; @@ -2610,7 +2611,7 @@ class CourseManager if ($include_sessions === true) { $sql = "SELECT DISTINCT(c.code), c.id as real_id FROM " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " s, " . Database::get_main_table(TABLE_MAIN_COURSE) . " c - WHERE id_user = $user_id AND s.c_id = c.id"; + WHERE user_id = $user_id AND s.c_id = c.id"; $r = Database::query($sql); while ($row = Database::fetch_array($r, 'ASSOC')) { if (!in_array($row['real_id'], $codes)) { @@ -2697,7 +2698,7 @@ class CourseManager $courseId = intval($courseId); $session_id = intval($session_id); - $sql = "SELECT id_user + $sql = "SELECT user_id FROM $tbl_session_course_user WHERE session_id = '$session_id' AND @@ -2710,7 +2711,7 @@ class CourseManager $user_ids = array(); while ($row = Database::fetch_array($rs)) { - $user_ids[] = $row['id_user']; + $user_ids[] = $row['user_id']; } $sql = "SELECT firstname, lastname, email FROM $tbl_user @@ -4378,7 +4379,7 @@ class CourseManager } else { $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $sql = "SELECT legal_agreement FROM $table - WHERE id_user = $user_id AND c_id ='$courseId' AND id_session = $session_id"; + WHERE user_id = $user_id AND c_id ='$courseId' AND session_id = $session_id"; $result = Database::query($sql); if (Database::num_rows($result) > 0) { $result = Database::fetch_array($result); @@ -4423,7 +4424,7 @@ class CourseManager } else { $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $sql = "UPDATE $table SET legal_agreement = '1' - WHERE id_user = $user_id AND c_id = '$courseId' AND id_session = $session_id"; + WHERE user_id = $user_id AND c_id = '$courseId' AND session_id = $session_id"; Database::query($sql); } } @@ -5664,7 +5665,7 @@ class CourseManager public static function getCoursesWithoutSession($startDate = null, $endDate = null, $includeClosed = false) { $dateConditional = ($startDate && $endDate) ? - " WHERE id_session IN (SELECT id FROM " . Database::get_main_table(TABLE_MAIN_SESSION) . + " WHERE session_id IN (SELECT id FROM " . Database::get_main_table(TABLE_MAIN_SESSION) . " WHERE date_start = '$startDate' AND date_end = '$endDate')" : null; $visibility = ($includeClosed ? '' : 'visibility NOT IN (0, 4) AND '); diff --git a/main/inc/lib/document.lib.php b/main/inc/lib/document.lib.php index 47725fd994..ce0104f584 100755 --- a/main/inc/lib/document.lib.php +++ b/main/inc/lib/document.lib.php @@ -1511,7 +1511,7 @@ class DocumentManager //note the extra / at the end of doc_path to match every path in the document table that is part of the document path $session_id = intval($session_id); - $condition = "AND id_session IN ('$session_id', '0') "; + $condition = "AND session_id IN ('$session_id', '0') "; // The " d.filetype='file' " let the user see a file even if the folder is hidden see #2198 /* @@ -3229,7 +3229,7 @@ class DocumentManager $tbl_doc = Database::get_course_table(TABLE_DOCUMENT); $tbl_item_prop = Database::get_course_table(TABLE_ITEM_PROPERTY); - $condition_session = " AND (id_session = '$session_id' OR id_session = '0' )"; + $condition_session = " AND (session_id = '$session_id' OR id_session = '0' )"; $add_folder_filter = null; if (!empty($filter_by_folder)) { diff --git a/main/inc/lib/exercise.lib.php b/main/inc/lib/exercise.lib.php index 3613843a19..d2d5c7eb8d 100644 --- a/main/inc/lib/exercise.lib.php +++ b/main/inc/lib/exercise.lib.php @@ -2795,7 +2795,7 @@ class ExerciseLib } else { $courseCondition = " INNER JOIN $courseUserSession cu - ON cu.c_id = c.id AND cu.id_user = exe_user_id"; + ON cu.c_id = c.id AND cu.user_id = exe_user_id"; $courseConditionWhere = " AND cu.status = 0 "; } @@ -2870,7 +2870,7 @@ class ExerciseLib } else { $courseCondition = " INNER JOIN $courseUserSession cu - ON cu.c_id = c.id AND cu.id_user = exe_user_id"; + ON cu.c_id = c.id AND cu.user_id = exe_user_id"; $courseConditionWhere = " AND cu.status = 0 "; } @@ -2959,7 +2959,7 @@ class ExerciseLib } else { $courseCondition = " INNER JOIN $courseUserSession cu - ON cu.course_code = a.course_code AND cu.id_user = exe_user_id"; + ON cu.c_id = a.c_id AND cu.user_id = exe_user_id"; $courseConditionWhere = " AND cu.status = 0 "; } diff --git a/main/inc/lib/login.lib.php b/main/inc/lib/login.lib.php index 72953fa5fe..5893d731d8 100755 --- a/main/inc/lib/login.lib.php +++ b/main/inc/lib/login.lib.php @@ -558,13 +558,14 @@ class Login $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER); //Session coach, session admin, course coach admin - $sql = "SELECT session.id_coach, session_admin_id, session_rcru.id_user - FROM $tbl_session session, $tbl_session_course_user session_rcru - WHERE session_rcru.session_id = session.id AND - session_rcru.course_code = '$_cid' AND - session_rcru.id_user = '$user_id' AND - session_rcru.session_id = $session_id AND - session_rcru.status = 2"; + $sql = "SELECT session.id_coach, session_admin_id, session_rcru.user_id + FROM $tbl_session session, $tbl_session_course_user session_rcru + WHERE + session_rcru.session_id = session.id AND + session_rcru.course_code = '$_cid' AND + session_rcru.user_id = '$user_id' AND + session_rcru.session_id = $session_id AND + session_rcru.status = 2"; $result = Database::query($sql); $row = Database::store_result($result); @@ -579,16 +580,17 @@ class Login $is_sessionAdmin = true; } else { //Im a coach or a student? - $sql = "SELECT id_user, status FROM " . $tbl_session_course_user . " - WHERE course_code = '$_cid' AND - id_user = '" . $user_id . "' AND - id_session = '" . $session_id . "' - LIMIT 1"; + $sql = "SELECT user_id, status + FROM " . $tbl_session_course_user . " + WHERE + c_id = '$_cid' AND + user_id = '" . $user_id . "' AND + session_id = '" . $session_id . "' + LIMIT 1"; $result = Database::query($sql); if (Database::num_rows($result)) { $row = Database::fetch_array($result, 'ASSOC'); - $session_course_status = $row['status']; switch ($session_course_status) { diff --git a/main/inc/lib/myspace.lib.php b/main/inc/lib/myspace.lib.php index 1a3a69d5f3..3df04cb783 100644 --- a/main/inc/lib/myspace.lib.php +++ b/main/inc/lib/myspace.lib.php @@ -348,19 +348,38 @@ class MySpace $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $tbl_sessions = Database::get_main_table(TABLE_MAIN_SESSION); - $sqlCoachs = "SELECT DISTINCT scu.id_user as id_coach, user_id, lastname, firstname, MAX(login_date) as login_date - FROM $tbl_user, $tbl_session_course_user scu, $tbl_track_login - WHERE scu.id_user=user_id AND scu.status=2 AND login_user_id=user_id - GROUP BY user_id "; + $sqlCoachs = "SELECT DISTINCT + scu.user_id as id_coach, + u.id as user_id, + lastname, + firstname, + MAX(login_date) as login_date + FROM $tbl_user u, $tbl_session_course_user scu, $tbl_track_login + WHERE + scu.user_id = u.id AND scu.status=2 AND login_user_id=u.id + GROUP BY user_id "; if (api_is_multiple_url_enabled()) { $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION); $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { - $sqlCoachs = "SELECT DISTINCT scu.id_user as id_coach, user_id, lastname, firstname, MAX(login_date) as login_date - FROM $tbl_user, $tbl_session_course_user scu, $tbl_track_login , $tbl_session_rel_access_url session_rel_url - WHERE scu.id_user=user_id AND scu.status=2 AND login_user_id=user_id AND access_url_id = $access_url_id AND session_rel_url.session_id=id_session - GROUP BY user_id "; + $sqlCoachs = "SELECT DISTINCT + scu.user_id as id_coach, + u.id as user_id, + lastname, + firstname, + MAX(login_date) as login_date + FROM $tbl_user u, + $tbl_session_course_user scu, + $tbl_track_login , + $tbl_session_rel_access_url session_rel_url + WHERE + scu.user_id = u.id AND + scu.status = 2 AND + login_user_id = u.id AND + access_url_id = $access_url_id AND + session_rel_url.session_id = scu.session_id + GROUP BY u.id"; } } if (!empty($order[$tracking_column])) { @@ -374,20 +393,24 @@ class MySpace $global_coaches[$coach['user_id']] = $coach; } - $sql_session_coach = 'SELECT session.id_coach, user_id, lastname, firstname, MAX(login_date) as login_date - FROM '.$tbl_user.','.$tbl_sessions.' as session,'.$tbl_track_login.' - WHERE id_coach=user_id AND login_user_id=user_id - GROUP BY user_id - ORDER BY login_date '.$tracking_direction; + $sql_session_coach = 'SELECT session.id_coach, u.id as user_id, lastname, firstname, MAX(login_date) as login_date + FROM '.$tbl_user.' u ,'.$tbl_sessions.' as session,'.$tbl_track_login.' + WHERE id_coach = u.id AND login_user_id = u.id + GROUP BY u.id + ORDER BY login_date '.$tracking_direction; if (api_is_multiple_url_enabled()) { $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION); $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { - $sql_session_coach = 'SELECT session.id_coach, user_id, lastname, firstname, MAX(login_date) as login_date - FROM '.$tbl_user.','.$tbl_sessions.' as session,'.$tbl_track_login.' , '.$tbl_session_rel_access_url.' as session_rel_url - WHERE id_coach=user_id AND login_user_id=user_id AND access_url_id = '.$access_url_id.' AND session_rel_url.session_id=session.id - GROUP BY user_id + $sql_session_coach = 'SELECT session.id_coach, u.id as user_id, lastname, firstname, MAX(login_date) as login_date + FROM '.$tbl_user.' u ,'.$tbl_sessions.' as session, '.$tbl_track_login.' , '.$tbl_session_rel_access_url.' as session_rel_url + WHERE + id_coach = u.id AND + login_user_id = u.id AND + access_url_id = '.$access_url_id.' AND + session_rel_url.session_id = session.id + GROUP BY u.id ORDER BY login_date '.$tracking_direction; } } @@ -1601,11 +1624,11 @@ class MySpace // course code $return .= ' '.$row->title.''; // get the users in the course - $sql = "SELECT user_id + $sql = "SELECT u.user_id FROM $tbl_user AS u INNER JOIN $tbl_session_rel_course_rel_user AS scu - ON u.user_id = scu.id_user - WHERE scu.session_id = '".$session_id."' AND scu.course_code = '".$courseCode."';"; + ON u.user_id = scu.user_id + WHERE scu.session_id = '".$session_id."' AND scu.c_id = '".$courseId."'"; $result_users = Database::query($sql); $time_spent = 0; $progress = 0; @@ -1760,10 +1783,11 @@ class MySpace $csv_row[] = $session_title; $csv_row[] = $row->title; // get the users in the course - $sql = "SELECT user_id FROM $tbl_user AS u + $sql = "SELECT scu.user_id + FROM $tbl_user AS u INNER JOIN $tbl_session_rel_course_rel_user AS scu - ON u.user_id = scu.id_user - WHERE scu.session_id = '".$session_id."' AND scu.course_code = '".$row->code."';"; + ON u.user_id = scu.user_id + WHERE scu.session_id = '".$session_id."' AND scu.c_id = '".$courseId."'"; $result_users = Database::query($sql); $time_spent = 0; $progress = 0; @@ -1783,14 +1807,28 @@ class MySpace $progress += $progress_tmp[0]; $nb_progress_lp += $progress_tmp[1]; $score_tmp = Tracking :: get_avg_student_score($row_user->user_id, $row->code, array(), $session_id, true); - if(is_array($score_tmp)) { + if (is_array($score_tmp)) { $score += $score_tmp[0]; $nb_score_lp += $score_tmp[1]; } - $nb_messages += Tracking::count_student_messages($row_user->user_id, $row->code, $session_id); - $nb_assignments += Tracking::count_student_assignments($row_user->user_id, $row->code, $session_id); + $nb_messages += Tracking::count_student_messages( + $row_user->user_id, + $row->code, + $session_id + ); + + $nb_assignments += Tracking::count_student_assignments( + $row_user->user_id, + $row->code, + $session_id + ); - $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row_user->user_id, $courseId, $session_id, false); + $last_login_date_tmp = Tracking:: get_last_connection_date_on_the_course( + $row_user->user_id, + $courseId, + $session_id, + false + ); if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned. $last_login_date = $last_login_date_tmp; } else if($last_login_date_tmp != false && $last_login_date == false) { // TODO: Repeated previous condition. To be cleaned. @@ -2081,13 +2119,13 @@ class MySpace FROM $tbl_course_user as course_rel_user WHERE course_rel_user.status='5' AND - course_rel_user.c_id='$courseId'"; + course_rel_user.c_id = '$courseId'"; } else { - $sql = "SELECT id_user as user_id FROM $tbl_session_course_user srcu + $sql = "SELECT user_id FROM $tbl_session_course_user srcu WHERE - srcu.course_code='$course_code' AND - id_session = '$session_id' AND - srcu.status<>2"; + c_id = '$courseId' AND + session_id = '$session_id' AND + status<>2"; } $rs = Database::query($sql); $users = array(); @@ -2290,10 +2328,10 @@ class MySpace /** * Checks whether a username has been already subscribed in a session. * @param string a given username - * @param array the array with the course list codes + * @param array the array with the course list id * @param the session id * @return 0 if the user is not subscribed otherwise it returns the user_id of the given username - * @author Julio Montoya Armas + * @author Julio Montoya */ public static function user_available_in_session($username, $course_list, $id_session) { @@ -2301,15 +2339,17 @@ class MySpace $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $id_session = intval($id_session); $username = Database::escape_string($username); - foreach($course_list as $enreg_course) { - $sql_select = " SELECT u.user_id FROM $tbl_session_rel_course_rel_user rel INNER JOIN $table_user u - ON (rel.id_user=u.user_id) - WHERE - rel.session_id='$id_session' AND - u.status='5' AND - u.username ='$username' AND - rel.course_code='$enreg_course'"; - $rs = Database::query($sql_select); + foreach ($course_list as $courseId) { + $courseId = intval($courseId); + $sql = " SELECT u.user_id FROM $tbl_session_rel_course_rel_user rel + INNER JOIN $table_user u + ON (rel.user_id = u.user_id) + WHERE + rel.session_id='$id_session' AND + u.status='5' AND + u.username ='$username' AND + rel.c_id='$courseId'"; + $rs = Database::query($sql); if (Database::num_rows($rs) > 0) { return Database::result($rs, 0, 0); } else { @@ -2319,14 +2359,19 @@ class MySpace } /** - This function checks whether some users in the uploaded file repeated and creates unique usernames if necesary. - A case: Within the file there is an user repeted twice (Julio Montoya / Julio Montoya) and the username fields are empty. - Then, this function would create unique usernames based on the first and the last name. Two users wiould be created - jmontoya and jmontoya2. - Of course, if in the database there is a user with the name jmontoya, the newly created two users registered would be jmontoya2 and jmontoya3. - @param $users list of users - @author Julio Montoya Armas + * This function checks whether some users in the uploaded file + * repeated and creates unique usernames if necesary. + * A case: Within the file there is an user repeted twice (Julio Montoya / Julio Montoya) + * and the username fields are empty. + * Then, this function would create unique usernames based on the first and the last name. + * Two users wiould be created - jmontoya and jmontoya2. + * Of course, if in the database there is a user with the name jmontoya, + * the newly created two users registered would be jmontoya2 and jmontoya3. + * @param $users list of users + * @author Julio Montoya Armas */ - function check_all_usernames($users, $course_list, $id_session) { + function check_all_usernames($users, $course_list, $id_session) + { $table_user = Database::get_main_table(TABLE_MAIN_USER); $usernames = array(); $new_users = array(); @@ -2365,20 +2410,21 @@ class MySpace } /** - * This functions checks whether there are users that are already registered in the DB by different creator than the current coach. + * This functions checks whether there are users that are already + * registered in the DB by different creator than the current coach. * @param string a given username - * @param array the array with the course list codes + * @param array the array with the course list ids * @param the session id * @author Julio Montoya Armas */ - function get_user_creator($users, $course_list, $id_session) { + public function get_user_creator($users) + { $errors = array(); foreach ($users as $index => $user) { // database table definition $table_user = Database::get_main_table(TABLE_MAIN_USER); $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $username = Database::escape_string($user['UserName']); - //echo "
      "; $sql = "SELECT creator_id FROM $table_user WHERE username='$username' "; $rs = Database::query($sql); @@ -2391,6 +2437,7 @@ class MySpace } } } + return $errors; } @@ -2449,10 +2496,10 @@ class MySpace */ public function save_data($users, $course_list, $id_session) { - $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION); - $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE); - $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); - $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER); + $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION); + $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE); + $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); + $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER); $id_session = intval($id_session); $sendMail = $_POST['sendMail'] ? 1 : 0; @@ -2464,7 +2511,18 @@ class MySpace // coach only will registered users $default_status = '5'; if ($user['create'] == '1') { - $user['id'] = UserManager :: create_user($user['FirstName'], $user['LastName'], $default_status, $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], api_get_setting('PlatformLanguage'), $user['PhoneNumber'], ''); + $user['id'] = UserManager:: create_user( + $user['FirstName'], + $user['LastName'], + $default_status, + $user['Email'], + $user['UserName'], + $user['Password'], + $user['OfficialCode'], + api_get_setting('PlatformLanguage'), + $user['PhoneNumber'], + '' + ); $user['added_at_platform'] = 1; } else { $user['id'] = $user['create']; @@ -2483,7 +2541,8 @@ class MySpace $enreg_course = Database::escape_string($enreg_course); foreach ($users as $index => $user) { $userid = intval($user['id']); - $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(session_id, c_id, user_id) VALUES('$id_session','$enreg_course','$userid')"; + $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(session_id, c_id, user_id) + VALUES('$id_session','$enreg_course','$userid')"; $course_session = array('course' => $enreg_course, 'added' => 1); //$user['added_at_session'] = $course_session; $result = Database::query($sql); @@ -2495,10 +2554,12 @@ class MySpace $super_list[] = $new_users; //update the nbr_users field - $sql_select = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user WHERE session_id='$id_session' AND c_id='$enreg_course'"; + $sql_select = "SELECT COUNT(user_id) as nbUsers FROM $tbl_session_rel_course_rel_user + WHERE session_id='$id_session' AND c_id='$enreg_course'"; $rs = Database::query($sql_select); list($nbr_users) = Database::fetch_array($rs); - $sql_update = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE session_id='$id_session' AND c_id='$enreg_course'"; + $sql_update = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users + WHERE session_id='$id_session' AND c_id='$enreg_course'"; Database::query($sql_update); $sql_update = "UPDATE $tbl_session SET nbr_users= '$nbr_users' WHERE id='$id_session'"; diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php index e8dad21954..33069bacf5 100755 --- a/main/inc/lib/sessionmanager.lib.php +++ b/main/inc/lib/sessionmanager.lib.php @@ -279,7 +279,7 @@ class SessionManager ) { $where .= " AND ( s.session_admin_id = $user_id OR - sru.id_user = '$user_id' AND + sru.user_id = '$user_id' AND sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "' ) "; @@ -395,7 +395,7 @@ class SessionManager ) { $where .= " AND ( s.session_admin_id = $user_id OR - sru.id_user = '$user_id' AND + sru.user_id = '$user_id' AND sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "' ) "; @@ -600,7 +600,7 @@ class SessionManager $users = CourseManager :: get_student_list_from_course_code($course_code, true, $sessionId); } */ - $sessionCond = 'and id_session = %s'; + $sessionCond = 'and session_id = %s'; if ($sessionId == 'T') { $sessionCond = ""; } @@ -623,7 +623,7 @@ class SessionManager $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id FROM $session_course_user s - INNER JOIN $user u ON u.user_id = s.id_user + INNER JOIN $user u ON u.user_id = s.user_id $where $order $limit"; @@ -720,7 +720,7 @@ class SessionManager $course = api_get_course_info_by_id($courseId); - $where = " WHERE c_id = '%s' AND s.status <> 2 AND id_session = %s"; + $where = " WHERE c_id = '%s' AND s.status <> 2 AND session_id = %s"; $limit = null; if (!empty($options['limit'])) { @@ -744,7 +744,7 @@ class SessionManager $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id FROM $session_course_user s - INNER JOIN $user u ON u.user_id = s.id_user + INNER JOIN $user u ON u.user_id = s.user_id $where $order $limit"; $sql_query = sprintf($sql, intval($course['real_id']), $sessionId); @@ -867,21 +867,21 @@ class SessionManager //TODO, fix create report without session $queryVariables = array($course['real_id']); if (!empty($sessionId)) { - $where .= ' AND id_session = %s'; + $where .= ' AND session_id = %s'; $queryVariables[] = $sessionId; $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id, s.session_id FROM $session_course_user s INNER JOIN $user u - ON u.user_id = s.id_user + ON u.user_id = s.user_id $where $order $limit"; } else { $sql = "SELECT u.user_id, u.lastname, u.firstname, u.username, u.email, s.c_id, s.session_id FROM $session_course_user s - INNER JOIN $user u ON u.user_id = s.id_user + INNER JOIN $user u ON u.user_id = s.user_id $where $order $limit"; } @@ -1497,9 +1497,9 @@ class SessionManager } Database::query("DELETE FROM $tbl_session WHERE id IN($id_checked)"); - Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session IN($id_checked)"); - Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session IN($id_checked)"); - Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session IN($id_checked)"); + Database::query("DELETE FROM $tbl_session_rel_course WHERE session_id IN($id_checked)"); + Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id IN($id_checked)"); + Database::query("DELETE FROM $tbl_session_rel_user WHERE session_id IN($id_checked)"); Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)"); $sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked'"; @@ -1581,16 +1581,16 @@ class SessionManager } } - $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user - WHERE id_session = '$id_session' AND status = 0"; + $sql = "SELECT user_id FROM $tbl_session_rel_course_rel_user + WHERE session_id = '$id_session' AND status = 0"; $result = Database::query($sql); $existingUsers = array(); while ($row = Database::fetch_array($result)) { - $existingUsers[] = $row['id_user']; + $existingUsers[] = $row['user_id']; } $sql = "SELECT c_id FROM $tbl_session_rel_course - WHERE id_session = '$id_session'"; + WHERE session_id = '$id_session'"; $result = Database::query($sql); $course_list = array(); while ($row = Database::fetch_array($result)) { @@ -1627,17 +1627,17 @@ class SessionManager $nbr_users = 0; $courseId = intval($courseId); - $sql = "SELECT DISTINCT id_user + $sql = "SELECT DISTINCT user_id FROM $tbl_session_rel_course_rel_user WHERE - id_session = '$id_session' AND + session_id = '$id_session' AND c_id = '$courseId' AND status = 0 "; $result = Database::query($sql); $existingUsers = array(); while ($row = Database::fetch_array($result)) { - $existingUsers[] = $row['id_user']; + $existingUsers[] = $row['user_id']; } // Delete existing users @@ -1646,9 +1646,9 @@ class SessionManager if (!in_array($existing_user, $user_list)) { $sql = "DELETE FROM $tbl_session_rel_course_rel_user WHERE - id_session =' $id_session' AND + session_id =' $id_session' AND c_id = '$courseId' AND - id_user = '$existing_user' AND + user_id = '$existing_user' AND status = 0 "; $result = Database::query($sql); if (Database::affected_rows($result)) { @@ -1663,7 +1663,7 @@ class SessionManager foreach ($user_list as $enreg_user) { if (!in_array($enreg_user, $existingUsers)) { $enreg_user = Database::escape_string($enreg_user); - $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (id_session, c_id, id_user, visibility, status) + $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility, status) VALUES('$id_session', '$courseId', '$enreg_user', '$session_visibility', '0')"; $result = Database::query($sql); if (Database::affected_rows($result)) { @@ -1673,21 +1673,21 @@ class SessionManager } // Count users in this session-course relation - $sql = "SELECT COUNT(id_user) as nbUsers + $sql = "SELECT COUNT(user_id) as nbUsers FROM $tbl_session_rel_course_rel_user - WHERE id_session = '$id_session' AND c_id = '$courseId' AND status<>2"; + WHERE session_id = '$id_session' AND c_id = '$courseId' AND status<>2"; $rs = Database::query($sql); list($nbr_users) = Database::fetch_array($rs); // update the session-course relation to add the users total $sql = "UPDATE $tbl_session_rel_course SET nbr_users = $nbr_users - WHERE id_session='$id_session' AND c_id = '$courseId'"; + WHERE session_id ='$id_session' AND c_id = '$courseId'"; Database::query($sql); } // Delete users from the session if ($empty_users === true) { $sql = "DELETE FROM $tbl_session_rel_user - WHERE id_session = $id_session AND relation_type<>" . SESSION_RELATION_TYPE_RRHH . ""; + WHERE session_id = $id_session AND relation_type<>" . SESSION_RELATION_TYPE_RRHH . ""; Database::query($sql); } @@ -1697,7 +1697,7 @@ class SessionManager foreach ($user_list as $enreg_user) { $enreg_user = Database::escape_string($enreg_user); $nbr_users++; - $sql = "INSERT IGNORE INTO $tbl_session_rel_user (relation_type, id_session, id_user) + $sql = "INSERT IGNORE INTO $tbl_session_rel_user (relation_type, session_id, user_id) VALUES (0, '$id_session', '$enreg_user')"; Database::query($sql); } @@ -1745,17 +1745,17 @@ class SessionManager $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); - $sql = "SELECT DISTINCT id_user + $sql = "SELECT DISTINCT user_id FROM $table WHERE - id_session = '$sessionId' AND - c_id='$courseId' + session_id = '$sessionId' AND + c_id = '$courseId' $statusCondition "; $result = Database::query($sql); $existingUsers = array(); while ($row = Database::fetch_array($result)) { - $existingUsers[] = $row['id_user']; + $existingUsers[] = $row['user_id']; } return $existingUsers; @@ -1798,9 +1798,9 @@ class SessionManager $userId = intval($userId); $sql = "DELETE FROM $table WHERE - id_session='$sessionId' AND + session_id='$sessionId' AND c_id = '$courseId' AND - id_user = '$userId' + user_id = '$userId' $statusCondition "; Database::query($sql); @@ -1808,20 +1808,20 @@ class SessionManager if ($updateTotal) { // Count users in this session-course relation - $sql = "SELECT COUNT(id_user) as nbUsers + $sql = "SELECT COUNT(user_id) as nbUsers FROM $table WHERE - id_session='$sessionId' AND + session_id ='$sessionId' AND c_id = '$courseId' AND status <>2"; $result = Database::query($sql); list($userCount) = Database::fetch_array($result); // update the session-course relation to add the users total - $sql = "UPDATE $tableSessionCourse SET - nbr_users = $userCount + $sql = "UPDATE $tableSessionCourse + SET nbr_users = $userCount WHERE - id_session='$sessionId' AND + session_id ='$sessionId' AND c_id = '$courseId'"; Database::query($sql); } @@ -1885,12 +1885,12 @@ class SessionManager foreach ($user_list as $enreg_user) { $enreg_user = intval($enreg_user); // Checking if user exists in session - course - user table. - $sql = "SELECT count(id_user) as count + $sql = "SELECT count(user_id) as count FROM $tbl_session_rel_course_rel_user WHERE - id_session = $session_id AND + session_id = $session_id AND c_id = '$courseId' and - id_user = $enreg_user "; + user_id = $enreg_user "; $result = Database::query($sql); $count = 0; @@ -1900,7 +1900,7 @@ class SessionManager } if ($count == 0) { - $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (id_session, c_id, id_user, visibility) + $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id, visibility) VALUES ('$session_id', '$courseId', '$enreg_user', '$session_visibility')"; $result = Database::query($sql); if (Database::affected_rows($result)) { @@ -1909,9 +1909,9 @@ class SessionManager } // Checking if user exists in session - user table. - $sql = "SELECT count(id_user) as count + $sql = "SELECT count(user_id) as count FROM $tbl_session_rel_user - WHERE id_session = $session_id AND id_user = $enreg_user "; + WHERE session_id = $session_id AND user_id = $enreg_user "; $result = Database::query($sql); $count = 0; @@ -1922,7 +1922,7 @@ class SessionManager if (empty($count)) { // If user is not registered to a session then add it. - $sql = "INSERT IGNORE INTO $tbl_session_rel_user (id_session, id_user) + $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id) VALUES ('$session_id', '$enreg_user')"; Database::query($sql); @@ -1933,14 +1933,15 @@ class SessionManager } // count users in this session-course relation - $sql = "SELECT COUNT(id_user) as nbUsers + $sql = "SELECT COUNT(user_id) as nbUsers FROM $tbl_session_rel_course_rel_user - WHERE id_session='$session_id' AND c_id='$courseId' AND status<>2"; + WHERE session_id ='$session_id' AND c_id='$courseId' AND status<>2"; $rs = Database::query($sql); list($nbr_users) = Database::fetch_array($rs); // update the session-course relation to add the users total - $sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users - WHERE id_session='$session_id' AND c_id = '$courseId'"; + $sql = "UPDATE $tbl_session_rel_course + SET nbr_users=$nbr_users + WHERE session_id='$session_id' AND c_id = '$courseId'"; Database::query($sql); } @@ -1963,8 +1964,8 @@ class SessionManager $delete_sql = "DELETE FROM $tbl_session_rel_user WHERE - id_session = '$session_id' AND - id_user ='$user_id' AND + session_id = '$session_id' AND + user_id ='$user_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH . ""; $result = Database::query($delete_sql); $return = Database::affected_rows($result); @@ -1983,12 +1984,12 @@ class SessionManager $courseId = $course['id']; // Delete user from course $sql = "DELETE FROM $tbl_session_rel_course_rel_user - WHERE id_session='$session_id' AND c_id='$courseId' AND id_user='$user_id'"; + WHERE session_id ='$session_id' AND c_id = '$courseId' AND user_id = '$user_id'"; $result = Database::query($sql); if (Database::affected_rows($result)) { // Update number of users in this relation $sql = "UPDATE $tbl_session_rel_course SET nbr_users = nbr_users - 1 - WHERE id_session='$session_id' AND c_id = '$courseId'"; + WHERE session_id ='$session_id' AND c_id = '$courseId'"; Database::query($sql); } } @@ -2025,16 +2026,16 @@ class SessionManager // Get list of courses subscribed to this session $sql = "SELECT c_id FROM $tbl_session_rel_course - WHERE id_session = $sessionId"; + WHERE session_id = $sessionId"; $rs = Database::query($sql ); $existingCourses = Database::store_result($rs); $nbr_courses = count($existingCourses); // get list of users subscribed to this session - $sql = "SELECT id_user + $sql = "SELECT user_id FROM $tbl_session_rel_user WHERE - id_session = $sessionId AND + session_id = $sessionId AND relation_type<>" . SESSION_RELATION_TYPE_RRHH . ""; $result = Database::query($sql); $user_list = Database::store_result($result); @@ -2047,11 +2048,11 @@ class SessionManager $courseInfo = api_get_course_info($existingCourse['c_id']); $sql = "DELETE FROM $tbl_session_rel_course - WHERE c_id = '" . $existingCourse['c_id'] . "' AND id_session=$sessionId"; + WHERE c_id = '" . $existingCourse['c_id'] . "' AND session_id=$sessionId"; Database::query($sql); $sql = "DELETE FROM $tbl_session_rel_course_rel_user - WHERE c_id = '" . $existingCourse['c_id'] . "' AND id_session=$sessionId"; + WHERE c_id = '" . $existingCourse['c_id'] . "' AND session_id=$sessionId"; Database::query($sql); CourseManager::remove_course_ranking( @@ -2077,7 +2078,7 @@ class SessionManager if (!$exists) { //if the course isn't subscribed yet - $sql = "INSERT INTO $tbl_session_rel_course (id_session, c_id) + $sql = "INSERT INTO $tbl_session_rel_course (session_id, c_id) VALUES ('$sessionId', '$courseId')"; Database::query($sql); @@ -2088,8 +2089,8 @@ class SessionManager // subscribe all the users from the session to this course inside the session $nbr_users = 0; foreach ($user_list as $enreg_user) { - $enreg_user_id = intval($enreg_user['id_user']); - $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (id_session, c_id, id_user) + $enreg_user_id = intval($enreg_user['user_id']); + $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id) VALUES ($sessionId, '$courseId', $enreg_user_id)"; $result = Database::query($sql); if (Database::affected_rows($result)) { @@ -2098,7 +2099,7 @@ class SessionManager } $sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users - WHERE id_session='$sessionId' AND c_id='$courseId'"; + WHERE session_id ='$sessionId' AND c_id='$courseId'"; Database::query($sql); } } @@ -2135,12 +2136,12 @@ class SessionManager // Unsubscribe course $sql = "DELETE FROM $tbl_session_rel_course - WHERE c_id = '$course_id' AND id_session='$session_id'"; + WHERE c_id = '$course_id' AND session_id='$session_id'"; $result = Database::query($sql); $nb_affected = Database::affected_rows($result); $sql = "DELETE FROM $tbl_session_rel_course_rel_user - WHERE c_id = '$course_id' AND id_session='$session_id'"; + WHERE c_id = '$course_id' AND session_id='$session_id'"; Database::query($sql); if ($nb_affected > 0) { @@ -2287,7 +2288,7 @@ class SessionManager $return_value = false; $sql = "SELECT c_id FROM $tbl_session_course WHERE - id_session = " . intval($session_id) . " AND + session_id = " . intval($session_id) . " AND c_id = '" . intval($courseId) . "'"; $result = Database::query($sql); $num = Database::num_rows($result); @@ -2648,7 +2649,8 @@ class SessionManager $tbl_user = Database::get_main_table(TABLE_MAIN_USER); // check if user is a teacher - $sql = "SELECT * FROM $tbl_user WHERE status='1' AND user_id = '$user_id'"; + $sql = "SELECT * FROM $tbl_user + WHERE status='1' AND user_id = '$user_id'"; $rs_check_user = Database::query($sql); @@ -2656,8 +2658,10 @@ class SessionManager if ($nocoach) { // check if user_id exists in session_rel_user (if the user is // subscribed to the session in any manner) - $sql = "SELECT id_user FROM $tbl_session_rel_user - WHERE id_session = '$session_id' AND id_user = '$user_id'"; + $sql = "SELECT user_id FROM $tbl_session_rel_user + WHERE + session_id = '$session_id' AND + user_id = '$user_id' "; $res = Database::query($sql); if (Database::num_rows($res) > 0) { @@ -2666,7 +2670,10 @@ class SessionManager // and then exit $sql = "UPDATE $tbl_session_rel_course_rel_user SET status = 0 - WHERE id_session = '$session_id' AND c_id = '$courseId' AND id_user = '$user_id' "; + WHERE + session_id = '$session_id' AND + c_id = '$courseId' AND + user_id = '$user_id' "; $result = Database::query($sql); if (Database::affected_rows($result) > 0) return true; @@ -2677,7 +2684,10 @@ class SessionManager // he isn't subscribed to a course in this session either // and then exit $sql = "DELETE FROM $tbl_session_rel_course_rel_user - WHERE id_session = '$session_id' AND c_id = '$courseId' AND id_user = '$user_id' "; + WHERE + session_id = '$session_id' AND + c_id = '$courseId' AND + user_id = '$user_id' "; $result = Database::query($sql); if (Database::affected_rows($result) > 0) return true; @@ -2687,14 +2697,20 @@ class SessionManager } else { // Assign user as a coach to course // First check if the user is registered to the course - $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user - WHERE id_session = '$session_id' AND c_id = '$courseId' AND id_user = '$user_id'"; + $sql = "SELECT user_id FROM $tbl_session_rel_course_rel_user + WHERE + session_id = '$session_id' AND + c_id = '$courseId' AND + user_id = '$user_id'"; $rs_check = Database::query($sql); // Then update or insert. if (Database::num_rows($rs_check) > 0) { $sql = "UPDATE $tbl_session_rel_course_rel_user SET status = 2 - WHERE id_session = '$session_id' AND c_id = '$courseId' AND id_user = '$user_id' "; + WHERE + session_id = '$session_id' AND + c_id = '$courseId' AND + user_id = '$user_id' "; $result = Database::query($sql); if (Database::affected_rows($result) > 0) { return true; @@ -2702,7 +2718,7 @@ class SessionManager return false; } } else { - $sql = "INSERT INTO $tbl_session_rel_course_rel_user(id_session, c_id, id_user, status) + $sql = "INSERT INTO $tbl_session_rel_course_rel_user(session_id, c_id, user_id, status) VALUES('$session_id', '$courseId', '$user_id', 2)"; $result = Database::query($sql); if (Database::affected_rows($result) > 0) { @@ -2751,16 +2767,16 @@ class SessionManager // Deleting assigned sessions to hrm_id. if ($removeOldConnections) { if (api_is_multiple_url_enabled()) { - $sql = "SELECT id_session + $sql = "SELECT session_id FROM $tbl_session_rel_user s INNER JOIN $tbl_session_rel_access_url a ON (a.session_id = s.session_id) WHERE - id_user = $userId AND + s.user_id = $userId AND relation_type=" . SESSION_RELATION_TYPE_RRHH . " AND access_url_id = " . api_get_current_access_url_id() . ""; } else { - $sql = "SELECT id_session FROM $tbl_session_rel_user s - WHERE id_user = $userId AND relation_type=" . SESSION_RELATION_TYPE_RRHH . ""; + $sql = "SELECT session_id FROM $tbl_session_rel_user s + WHERE user_id = $userId AND relation_type=" . SESSION_RELATION_TYPE_RRHH . ""; } $result = Database::query($sql); @@ -2768,8 +2784,8 @@ class SessionManager while ($row = Database::fetch_array($result)) { $sql = "DELETE FROM $tbl_session_rel_user WHERE - id_session = {$row['id_session']} AND - id_user = $userId AND + session_id = {$row['session_id']} AND + user_id = $userId AND relation_type=" . SESSION_RELATION_TYPE_RRHH . " "; Database::query($sql); } @@ -2780,7 +2796,7 @@ class SessionManager foreach ($sessions_list as $session_id) { $session_id = intval($session_id); - $sql = "INSERT IGNORE INTO $tbl_session_rel_user (id_session, id_user, relation_type) + $sql = "INSERT IGNORE INTO $tbl_session_rel_user (session_id, user_id, relation_type) VALUES ($session_id, $userId, '" . SESSION_RELATION_TYPE_RRHH . "')"; Database::query($sql); $affected_rows++; @@ -2819,7 +2835,7 @@ class SessionManager INNER JOIN $tbl_session_rel_user sru ON (sru.session_id = s.id) LEFT JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id) WHERE - sru.id_user = '$userId' AND + sru.user_id = '$userId' AND sru.session_id = '$sessionId' AND sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "' AND access_url_id = " . api_get_current_access_url_id() . " @@ -2829,17 +2845,20 @@ class SessionManager INNER JOIN $tbl_session_rel_user sru ON sru.session_id = s.id AND - sru.id_user = '$userId' AND + sru.user_id = '$userId' AND sru.session_id = '$sessionId' AND sru.relation_type = '" . SESSION_RELATION_TYPE_RRHH . "' - "; + "; } + $result = Database::query($sql); if (Database::num_rows($result)) { $row = Database::fetch_array($result, 'ASSOC'); $row['course_list'] = self::get_course_list_by_session_id($sessionId); + return $row; } + return array(); } @@ -2946,13 +2965,13 @@ class SessionManager $tbl_session_rel_user sru WHERE sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND - sru.id_user = $userId"; + sru.user_id = $userId"; break; case COURSEMANAGER: $courseSessionQuery = " SELECT scu.session_id as id FROM $tbl_session_rel_course_rel_user scu - WHERE (scu.status = 2 AND scu.id_user = $userId)"; + WHERE (scu.status = 2 AND scu.user_id = $userId)"; $whereConditions = " OR (s.id_coach = $userId) "; break; @@ -2961,7 +2980,7 @@ class SessionManager FROM $tbl_session_rel_user sru WHERE - sru.id_user = $userId"; + sru.user_id = $userId"; break; } @@ -3008,6 +3027,7 @@ class SessionManager $sessions[$row['id']] = $row; } } + return $sessions; } @@ -3073,6 +3093,7 @@ class SessionManager $courses[$row['id']] = $row; } } + return $courses; } @@ -3286,7 +3307,7 @@ class SessionManager access_url_id FROM $tbl_user u INNER JOIN $tbl_session_rel_user - ON u.user_id = $tbl_session_rel_user.id_user AND + ON u.user_id = $tbl_session_rel_user.user_id AND $tbl_session_rel_user.session_id = $id LEFT OUTER JOIN $table_access_url_user uu ON (uu.user_id = u.user_id) @@ -3340,6 +3361,7 @@ class SessionManager } $sql .= ' ORDER by name'; $result = Database::query($sql); + return Database::store_result($result, 'ASSOC'); } @@ -3367,7 +3389,7 @@ class SessionManager $sql = "SELECT session_rcru.status FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user WHERE - session_rcru.id_user = user.user_id AND + session_rcru.user_id = user.user_id AND session_rcru.session_id = '" . intval($session_id) . "' AND session_rcru.c_id ='" . intval($courseId) . "' AND user.user_id = " . intval($user_id); @@ -3399,7 +3421,7 @@ class SessionManager $tbl_user = Database::get_main_table(TABLE_MAIN_USER); $sql = "SELECT session_rcru.status FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user - WHERE session_rcru.id_user = user.user_id AND + WHERE session_rcru.user_id = user.user_id AND session_rcru.session_id = '" . intval($session_id) . "' AND session_rcru.c_id ='" . intval($courseId) . "' AND user.user_id = " . intval($user_id); @@ -3950,19 +3972,19 @@ class SessionManager // Delete session-user relation only for students $sql = "DELETE FROM $tbl_session_user - WHERE id_session = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH; + WHERE session_id = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH; Database::query($sql); - $sql = "DELETE FROM $tbl_session_course WHERE id_session = '$session_id'"; + $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'"; Database::query($sql); // Delete session-course-user relationships students and coaches. if ($updateCourseCoaches) { - $sql = "DELETE FROM $tbl_session_course_user WHERE id_session = '$session_id' AND status in ('0', '2')"; + $sql = "DELETE FROM $tbl_session_course_user WHERE session_id = '$session_id' AND status in ('0', '2')"; Database::query($sql); } else { // Delete session-course-user relation ships *only* for students. - $sql = "DELETE FROM $tbl_session_course_user WHERE id_session = '$session_id' AND status <> 2"; + $sql = "DELETE FROM $tbl_session_course_user WHERE session_id = '$session_id' AND status <> 2"; Database::query($sql); } } @@ -4036,21 +4058,21 @@ class SessionManager // Delete session-user relation only for students $sql = "DELETE FROM $tbl_session_user - WHERE id_session = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH; + WHERE session_id = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH; Database::query($sql); - $sql = "DELETE FROM $tbl_session_course WHERE id_session = '$session_id'"; + $sql = "DELETE FROM $tbl_session_course WHERE session_id = '$session_id'"; Database::query($sql); // Delete session-course-user relationships students and coaches. if ($updateCourseCoaches) { $sql = "DELETE FROM $tbl_session_course_user - WHERE id_session = '$session_id' AND status in ('0', '2')"; + WHERE session_id = '$session_id' AND status in ('0', '2')"; Database::query($sql); } else { // Delete session-course-user relation ships *only* for students. $sql = "DELETE FROM $tbl_session_course_user - WHERE id_session = '$session_id' AND status <> 2"; + WHERE session_id = '$session_id' AND status <> 2"; Database::query($sql); } } else { @@ -4077,8 +4099,8 @@ class SessionManager $userList[] = $user_id; // Insert new users. $sql = "INSERT IGNORE INTO $tbl_session_user SET - id_user = '$user_id', - id_session = '$session_id'"; + user_id = '$user_id', + session_id = '$session_id'"; Database::query($sql); if ($debug) { $logger->addInfo("Sessions - Adding User #$user_id ($user) to session #$session_id"); @@ -4133,7 +4155,7 @@ class SessionManager // Adding the course to a session. $sql = "INSERT IGNORE INTO $tbl_session_course - SET c_id = '$courseId', id_session='$session_id'"; + SET c_id = '$courseId', session_id='$session_id'"; Database::query($sql); SessionManager::installCourse($session_id, $courseInfo['real_id']); @@ -4365,9 +4387,9 @@ class SessionManager $sessionId = intval($sessionId); $courseId = intval($courseId); - $sql = "SELECT id_user FROM $table + $sql = "SELECT user_id FROM $table WHERE - id_session = '$sessionId' AND + session_id = '$sessionId' AND c_id = '$courseId' AND status = 2"; $result = Database::query($sql); @@ -4416,15 +4438,15 @@ class SessionManager $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $sessionId = intval($sessionId); - $sql = "SELECT DISTINCT id_user + $sql = "SELECT DISTINCT user_id FROM $table - WHERE id_session = '$sessionId' AND status = 2"; + WHERE session_id = '$sessionId' AND status = 2"; $result = Database::query($sql); $coaches = array(); if (Database::num_rows($result) > 0) { while ($row = Database::fetch_array($result)) { - $coaches[] = $row['id_user']; + $coaches[] = $row['user_id']; } } @@ -5192,7 +5214,7 @@ class SessionManager $position[$course['code']] = $course['position']; // Saving current order. $sql = "UPDATE $table SET position = $count - WHERE id_session = $sessionId AND c_id = '".$course['real_id']."'"; + WHERE session_id = $sessionId AND c_id = '".$course['real_id']."'"; Database::query($sql); $count++; } @@ -5225,11 +5247,11 @@ class SessionManager } $sql1 = "UPDATE $table SET position = '".intval($nextOrder)."' - WHERE id_session = $sessionId AND c_id = '".$thisCourseCode."'"; + WHERE session_id = $sessionId AND c_id = '".$thisCourseCode."'"; Database::query($sql1); $sql2 = "UPDATE $table SET position = '".intval($thisOrder)."' - WHERE id_session = $sessionId AND c_id = '".$nextId."'"; + WHERE session_id = $sessionId AND c_id = '".$nextId."'"; Database::query($sql2); return true; @@ -5322,7 +5344,7 @@ class SessionManager $table = Database::get_main_table(TABLE_MAIN_SESSION_USER); $parameters = array('duration' => $duration); - $where = array('id_session = ? AND id_user = ? ' => array($sessionId, $userId)); + $where = array('session_id = ? AND user_id = ? ' => array($sessionId, $userId)); Database::update($table, $parameters, $where); } @@ -5342,7 +5364,8 @@ class SessionManager } $table = Database::get_main_table(TABLE_MAIN_SESSION_USER); - $sql = "SELECT * FROM $table WHERE id_session =$sessionId AND id_user = $userId"; + $sql = "SELECT * FROM $table + WHERE session_id =$sessionId AND user_id = $userId"; $result = Database::query($sql); $values = array(); if (Database::num_rows($result)) { @@ -5367,8 +5390,11 @@ class SessionManager // COUNT(1) actually returns the number of rows from the table (as if // counting the results from the first column) - $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable " - . "WHERE id_session = $sessionId AND id_user = $userId AND relation_type = 0"; + $sql = "SELECT COUNT(1) AS qty FROM $sessionRelUserTable + WHERE + session_id = $sessionId AND + user_id = $userId AND + relation_type = 0"; $result = Database::fetch_assoc(Database::query($sql)); @@ -5500,7 +5526,7 @@ class SessionManager $scuTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $userTable = Database::get_main_table(TABLE_MAIN_USER); - $idResult = Database::select('DISTINCT id_user', $scuTable, array( + $idResult = Database::select('DISTINCT user_id', $scuTable, array( 'where' => array( 'status = ?' => 2 ) @@ -5510,7 +5536,7 @@ class SessionManager foreach ($idResult as $idData) { $userResult = Database::select('user_id, lastname, firstname, username', $userTable, array( 'where' => array( - 'user_id = ?' => $idData['id_user'] + 'user_id = ?' => $idData['user_id'] ) ), 'first'); @@ -5576,7 +5602,7 @@ class SessionManager $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); return Database::select('*', $table, array( 'where' => array( - 'id_user = ? AND ' => $coachId, + 'user_id = ? AND ' => $coachId, 'status = ?' => 2 ) )); @@ -5589,11 +5615,13 @@ class SessionManager */ public static function getTotalUserCoursesInSession($sessionId) { - $sql = "SELECT COUNT(1) as count, u.user_id, scu.status status_in_session, u.status user_status " - . "FROM session_rel_course_rel_user scu " - . "INNER JOIN user u ON scu.id_user = u.user_id " - . "WHERE scu.session_id = " . intval($sessionId) . " " - . "GROUP BY u.user_id"; + $tableUser = Database::get_main_table(TABLE_MAIN_USER); + $tableSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); + $sql = "SELECT COUNT(1) as count, u.user_id, scu.status status_in_session, u.status user_status + FROM $tableSessionRelCourseRelUser scu + INNER JOIN $tableUser u ON scu.user_id = u.user_id + WHERE scu.session_id = " . intval($sessionId) ." + GROUP BY u.user_id"; $result = Database::query($sql); @@ -5805,7 +5833,7 @@ class SessionManager u.lastname AS coach_lastname FROM $courseTable c INNER JOIN $sessionCourseUserTable scu ON c.id = scu.c_id - INNER JOIN $userTable u ON scu.id_user = u.user_id + INNER JOIN $userTable u ON scu.user_id = u.user_id WHERE scu.status = 2 AND scu.session_id IN $sessionIdsString ORDER BY scu.session_id ASC "; $res = Database::query($sql); diff --git a/main/inc/lib/thematic.lib.php b/main/inc/lib/thematic.lib.php index e8aed54d2f..bea5131f97 100755 --- a/main/inc/lib/thematic.lib.php +++ b/main/inc/lib/thematic.lib.php @@ -1037,13 +1037,22 @@ class Thematic // get all thematic advance done $rs_thematic_done = Database::query("SELECT ref FROM $tbl_item_property - WHERE c_id = $course_id AND tool='thematic_advance' AND lastedit_type='ThematicAdvanceDone' AND id_session = $sessionId "); + WHERE c_id = $course_id AND tool='thematic_advance' AND lastedit_type='ThematicAdvanceDone' AND session_id = $sessionId "); if (Database::num_rows($rs_thematic_done) > 0) { while ($row_thematic_done = Database::fetch_array($rs_thematic_done)) { $ref = $row_thematic_done['ref']; if (in_array($ref, $a_thematic_advance_ids)) { continue; } // update items - Database::query("UPDATE $tbl_item_property SET lastedit_date='".api_get_utc_datetime()."', lastedit_type='ThematicAdvanceUpdated', lastedit_user_id = $user_id WHERE c_id = $course_id AND tool='thematic_advance' AND ref=$ref AND id_session = $sessionId "); + $sql = "UPDATE $tbl_item_property SET + lastedit_date='".api_get_utc_datetime()."', + lastedit_type='ThematicAdvanceUpdated', + lastedit_user_id = $user_id + WHERE + c_id = $course_id AND + tool='thematic_advance' AND + ref=$ref AND + session_id = $sessionId "; + Database::query($sql); } } } diff --git a/main/inc/lib/tracking.lib.php b/main/inc/lib/tracking.lib.php index a2672c95be..e18a37cb57 100755 --- a/main/inc/lib/tracking.lib.php +++ b/main/inc/lib/tracking.lib.php @@ -1574,7 +1574,7 @@ class Tracking if ($include_sessions) { $sql = 'SELECT DISTINCT c_id FROM ' . $tbl_session_course_rel_user . ' - WHERE id_user = ' . $user_id; + WHERE user_id = ' . $user_id; $rs = Database::query($sql); $nb_courses += Database::num_rows($rs); } @@ -1871,9 +1871,12 @@ class Tracking $sessionId = intval($sessionId); $courseId = intval($courseId); + $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); + $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION); + //get teachers - $sql = "SELECT scu.session_id, scu.id_user, s.name - FROM session_rel_course_rel_user scu, session s + $sql = "SELECT scu.session_id, scu.user_id, s.name + FROM $sessionCourseUserTable scu, $sessionTable s WHERE scu.session_id = s.id AND scu.status = 2 @@ -1894,11 +1897,11 @@ class Tracking WHERE lastedit_type = 'DocumentAdded' AND c_id = %s AND insert_user_id = %s - AND id_session = %s"; + AND session_id = %s"; $query = sprintf($sql, $courseId, - $teacher['id_user'], - $teacher['id_session'] + $teacher['user_id'], + $teacher['session_id'] ); $rs = Database::query($query); @@ -1913,11 +1916,11 @@ class Tracking WHERE lastedit_type = 'LinkAdded' AND c_id = %s AND insert_user_id = %s - AND id_session = %s"; + AND session_id = %s"; $query = sprintf($sql, $courseId, - $teacher['id_user'], - $teacher['id_session'] + $teacher['user_id'], + $teacher['session_id'] ); $rs = Database::query($query); @@ -1932,11 +1935,11 @@ class Tracking WHERE lastedit_type = 'ForumthreadVisible' AND c_id = %s AND insert_user_id = %s - AND id_session = %s"; + AND session_id = %s"; $query = sprintf($sql, $courseId, - $teacher['id_user'], - $teacher['id_session'] + $teacher['user_id'], + $teacher['session_id'] ); $rs = Database::query($query); @@ -1951,11 +1954,11 @@ class Tracking WHERE lastedit_type = 'WikiAdded' AND c_id = %s AND insert_user_id = %s - AND id_session = %s"; + AND session_id = %s"; $query = sprintf($sql, $courseId, - $teacher['id_user'], - $teacher['id_session'] + $teacher['user_id'], + $teacher['session_id'] ); $rs = Database::query($query); @@ -1971,11 +1974,11 @@ class Tracking AND tool = 'work' AND c_id = %s AND insert_user_id = %s - AND id_session = %s"; + AND session_id = %s"; $query = sprintf($sql, $courseId, - $teacher['id_user'], - $teacher['id_session'] + $teacher['user_id'], + $teacher['session_id'] ); $rs = Database::query($query); @@ -1990,11 +1993,11 @@ class Tracking WHERE lastedit_type = 'AnnouncementAdded' AND c_id = %s AND insert_user_id = %s - AND id_session = %s"; + AND session_id = %s"; $query = sprintf($sql, $courseId, - $teacher['id_user'], - $teacher['id_session'] + $teacher['user_id'], + $teacher['session_id'] ); $rs = Database::query($query); @@ -2003,7 +2006,7 @@ class Tracking $row = Database::fetch_row($rs); $totalAnnouncements = $row[0]; } - $tutor = api_get_user_info($teacher['id_user']); + $tutor = api_get_user_info($teacher['user_id']); $data[] = array( 'course' => $course['title'], 'session' => $teacher['name'], @@ -2660,9 +2663,9 @@ class Tracking $a_students = array (); // At first, courses where $coach_id is coach of the course // - $sql = 'SELECT id_session, c_id + $sql = 'SELECT session_id, c_id FROM ' . $tbl_session_course_user . ' - WHERE id_user=' . $coach_id.' AND status=2'; + WHERE user_id=' . $coach_id.' AND status=2'; if (api_is_multiple_url_enabled()) { $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION); @@ -2673,7 +2676,7 @@ class Tracking INNER JOIN '.$tbl_session_rel_access_url.' sru ON (scu.session_id=sru.session_id) WHERE - scu.id_user=' . $coach_id.' AND + scu.user_id=' . $coach_id.' AND scu.status=2 AND sru.access_url_id = '.$access_url_id; } @@ -2683,12 +2686,12 @@ class Tracking while ($a_courses = Database::fetch_array($result)) { $courseId = $a_courses["c_id"]; - $id_session = $a_courses["id_session"]; + $id_session = $a_courses["session_id"]; - $sql = "SELECT DISTINCT srcru.id_user + $sql = "SELECT DISTINCT srcru.user_id FROM $tbl_session_course_user AS srcru, $tbl_session_user sru WHERE - srcru.id_user = sru.id_user AND + srcru.user_id = sru.user_id AND sru.relation_type<>".SESSION_RELATION_TYPE_RRHH." AND srcru.session_id = sru.session_id AND srcru.c_id = '$courseId' AND @@ -2697,7 +2700,7 @@ class Tracking $rs = Database::query($sql); while ($row = Database::fetch_array($rs)) { - $a_students[$row['id_user']] = $row['id_user']; + $a_students[$row['user_id']] = $row['user_id']; } } @@ -2705,7 +2708,7 @@ class Tracking $sql = 'SELECT session_course_user.user_id FROM ' . $tbl_session_course_user . ' as session_course_user INNER JOIN '.$tbl_session_user.' sru - ON session_course_user.id_user = sru.id_user AND session_course_user.session_id = sru.session_id + ON session_course_user.user_id = sru.user_id AND session_course_user.session_id = sru.session_id INNER JOIN ' . $tbl_session_course . ' as session_course ON session_course.c_id = session_course_user.c_id AND session_course_user.session_id = session_course.session_id @@ -2716,10 +2719,10 @@ class Tracking $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION); $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1){ - $sql = 'SELECT session_course_user.id_user + $sql = 'SELECT session_course_user.user_id FROM ' . $tbl_session_course_user . ' as session_course_user INNER JOIN '.$tbl_session_user.' sru - ON session_course_user.id_user = sru.id_user AND + ON session_course_user.user_id = sru.user_id AND session_course_user.session_id = sru.session_id INNER JOIN ' . $tbl_session_course . ' as session_course ON session_course.c_id = session_course_user.c_id AND @@ -2734,7 +2737,7 @@ class Tracking $result = Database::query($sql); while ($row = Database::fetch_array($result)) { - $a_students[$row['id_user']] = $row['id_user']; + $a_students[$row['user_id']] = $row['user_id']; } return $a_students; @@ -2755,20 +2758,20 @@ class Tracking $a_students = array (); // At first, courses where $coach_id is coach of the course // $sql = 'SELECT c_id FROM ' . $tbl_session_course_user . ' - WHERE id_session="' . $id_session . '" AND id_user=' . $coach_id.' AND status=2'; + WHERE session_id="' . $id_session . '" AND user_id=' . $coach_id.' AND status=2'; $result = Database::query($sql); while ($a_courses = Database::fetch_array($result)) { $courseId = $a_courses["c_id"]; - $sql = "SELECT DISTINCT srcru.id_user + $sql = "SELECT DISTINCT srcru.user_id FROM $tbl_session_course_user AS srcru WHERE c_id = '$courseId' AND - id_session = '" . $id_session . "'"; + session_id = '" . $id_session . "'"; $rs = Database::query($sql); while ($row = Database::fetch_array($rs)) { - $a_students[$row['id_user']] = $row['id_user']; + $a_students[$row['user_id']] = $row['user_id']; } } @@ -2778,12 +2781,12 @@ class Tracking $result = Database::query($sql); //He is the session_coach so we select all the users in the session if (Database::num_rows($result) > 0) { - $sql = 'SELECT DISTINCT srcru.id_user + $sql = 'SELECT DISTINCT srcru.user_id FROM ' . $tbl_session_course_user . ' AS srcru - WHERE id_session="' . $id_session . '"'; + WHERE session_id="' . $id_session . '"'; $result = Database::query($sql); while ($row = Database::fetch_array($result)) { - $a_students[$row['id_user']] = $row['id_user']; + $a_students[$row['user_id']] = $row['user_id']; } } @@ -2807,25 +2810,27 @@ class Tracking // At first, courses where $coach_id is coach of the course // - $sql = 'SELECT 1 FROM ' . $tbl_session_course_user . ' WHERE id_user=' . $coach_id .' AND status=2'; + $sql = 'SELECT 1 FROM ' . $tbl_session_course_user . ' + WHERE user_id=' . $coach_id .' AND status=2'; $result = Database::query($sql); if (Database::num_rows($result) > 0) { return true; } // Then, courses where $coach_id is coach of the session - $sql = 'SELECT session_course_user.id_user + $sql = 'SELECT session_course_user.user_id FROM ' . $tbl_session_course_user . ' as session_course_user INNER JOIN ' . $tbl_session_course . ' as session_course ON session_course.c_id = session_course_user.c_id INNER JOIN ' . $tbl_session . ' as session ON session.id = session_course.session_id AND session.id_coach = ' . $coach_id . ' - WHERE id_user = ' . $student_id; + WHERE user_id = ' . $student_id; $result = Database::query($sql); if (Database::num_rows($result) > 0) { return true; } + return false; } @@ -2854,7 +2859,7 @@ class Tracking FROM ' . $tbl_session_course_user . ' sc INNER JOIN '.$tbl_course.' c ON (c.id = sc.c_id) - WHERE id_user = ' . $coach_id.' AND status = 2'; + WHERE user_id = ' . $coach_id.' AND status = 2'; if (api_is_multiple_url_enabled()) { $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1){ @@ -2865,14 +2870,14 @@ class Tracking INNER JOIN '.$tbl_course_rel_access_url.' cru ON (c.id = cru.c_id) WHERE - scu.id_user=' . $coach_id.' AND + scu.user_id=' . $coach_id.' AND scu.status=2 AND cru.access_url_id = '.$access_url_id; } } if (!empty($id_session)) { - $sql .= ' AND id_session=' . $id_session; + $sql .= ' AND session_id=' . $id_session; } $courseList = array(); @@ -2989,7 +2994,7 @@ class Tracking FROM $tbl_session as session INNER JOIN $tbl_session_course_user as session_course_user ON session.id = session_course_user.session_id AND - session_course_user.id_user= $coach_id AND + session_course_user.user_id= $coach_id AND session_course_user.status=2 INNER JOIN $tbl_session_rel_access_url session_rel_url ON (session.id = session_rel_url.session_id) @@ -3054,7 +3059,7 @@ class Tracking FROM $tbl_session_course sc INNER JOIN $courseTable c sc.c_id = c.id - WHERE id_session= $session_id"; + WHERE session_id= $session_id"; $result = Database::query($sql); @@ -3461,8 +3466,8 @@ class Tracking FROM $tbl_session_course_user sc INNER JOIN $courseTable c WHERE - id_user= $user_id AND - id_session= $id_session"; + user_id= $user_id AND + session_id = $id_session"; $result = Database::query($sql); $courses = array(); while ($row = Database::fetch_array($result)) { @@ -3963,7 +3968,7 @@ class Tracking INNER JOIN $tbl_access_rel_course a ON (a.c_id = c.id) WHERE - user_id = $user_id AND + cu.user_id = $user_id AND relation_type<> ".COURSE_RELATION_TYPE_RRHH." AND access_url_id = ".api_get_current_access_url_id()." ORDER BY title"; @@ -4005,7 +4010,7 @@ class Tracking ON (c.id = cu.c_id) $extraInnerJoin WHERE - id_user = $user_id AND + cu.user_id = $user_id AND access_url_id = ".api_get_current_access_url_id()." $orderBy "; } else { @@ -4016,7 +4021,7 @@ class Tracking INNER JOIN $tbl_course c ON (c.id = cu.c_id) $extraInnerJoin - WHERE id_user = $user_id + WHERE cu.user_id = $user_id $orderBy "; } @@ -5479,7 +5484,7 @@ class TrackingCourseLog WHERE track_resource.c_id = $course_id AND track_resource.insert_user_id = user.user_id AND - id_session = $session_id "; + session_id = $session_id "; if (isset($_GET['keyword'])) { $keyword = Database::escape_string(trim($_GET['keyword'])); @@ -5536,7 +5541,7 @@ class TrackingCourseLog WHERE track_resource.c_id = $course_id AND track_resource.insert_user_id = user.user_id AND - id_session = $session_id "; + session_id = $session_id "; if (isset($_GET['keyword'])) { $keyword = Database::escape_string(trim($_GET['keyword'])); diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php index e5ba68f670..fbc5a2f419 100755 --- a/main/inc/lib/usermanager.lib.php +++ b/main/inc/lib/usermanager.lib.php @@ -393,7 +393,7 @@ class UserManager Database::query($sql); // Unsubscribe user from all courses in sessions - $sql = "DELETE FROM $table_session_course_user WHERE id_user = '".$user_id."'"; + $sql = "DELETE FROM $table_session_course_user WHERE user_id = '".$user_id."'"; Database::query($sql); // If the user was added as a id_coach then set the current admin as coach see BT# @@ -405,7 +405,7 @@ class UserManager Database::query($sql); // Unsubscribe user from all sessions - $sql = "DELETE FROM $table_session_user WHERE id_user = '".$user_id."'"; + $sql = "DELETE FROM $table_session_user WHERE user_id = '".$user_id."'"; Database::query($sql); // Delete user picture @@ -2504,7 +2504,7 @@ class UserManager LEFT JOIN $tbl_session_course_user as session_rel_course_user ON (session_rel_course_user.session_id = session.id) WHERE ( - session_rel_course_user.id_user = $user_id OR + session_rel_course_user.user_id = $user_id OR session.id_coach = $user_id ) ORDER BY session_category_name, name"; @@ -2680,14 +2680,14 @@ class UserManager if (api_is_allowed_to_create_course()) { $sessionListFromCourseCoach = array(); - $sql =" SELECT DISTINCT id_session FROM $tbl_session_course_user - WHERE id_user = $user_id AND status = 2 "; + $sql =" SELECT DISTINCT session_id FROM $tbl_session_course_user + WHERE user_id = $user_id AND status = 2 "; $result = Database::query($sql); if (Database::num_rows($result)) { $result = Database::store_result($result); foreach ($result as $session) { - $sessionListFromCourseCoach[]= $session['id_session']; + $sessionListFromCourseCoach[]= $session['session_id']; } } if (!empty($sessionListFromCourseCoach)) { @@ -2702,8 +2702,8 @@ class UserManager $sql = "SELECT DISTINCT id, name, date_start, date_end FROM $tbl_session_user, $tbl_session WHERE ( - id_session = id AND - id_user = $user_id AND + session_id = id AND + user_id = $user_id AND relation_type <> ".SESSION_RELATION_TYPE_RRHH." ) $coachCourseConditions @@ -2762,7 +2762,7 @@ class UserManager INNER JOIN $tbl_session as session ON session.id = session_course_user.session_id LEFT JOIN $tbl_user as user - ON user.user_id = session_course_user.id_user OR session.id_coach = user.user_id + ON user.user_id = session_course_user.user_id OR session.id_coach = user.user_id WHERE session_course_user.session_id = $id_session AND ( (session_course_user.user_id = $user_id AND session_course_user.status = 2) @@ -2799,13 +2799,13 @@ class UserManager date_end, session.id as session_id, session.name as session_name, - IF((session_course_user.id_user = 3 AND session_course_user.status=2),'2', '5') + IF((session_course_user.user_id = 3 AND session_course_user.status=2),'2', '5') FROM $tbl_session_course_user as session_course_user INNER JOIN $tbl_course AS course ON course.id = session_course_user.c_id AND session_course_user.session_id = $session_id INNER JOIN $tbl_session as session ON session_course_user.session_id = session.id - LEFT JOIN $tbl_user as user ON user.user_id = session_course_user.id_user - WHERE session_course_user.id_user = $user_id + LEFT JOIN $tbl_user as user ON user.user_id = session_course_user.user_id + WHERE session_course_user.user_id = $user_id ORDER BY i"; $course_list_sql_result = Database::query($personal_course_list_sql); @@ -2897,7 +2897,7 @@ class UserManager WHERE s.id = $session_id AND ( - (scu.id_user=$user_id AND scu.status=2) OR + (scu.user_id=$user_id AND scu.status=2) OR s.id_coach = $user_id ) $where_access_url @@ -4308,14 +4308,14 @@ class UserManager "; $sessionConditionsTeacher .= " AND - (scu.status = 2 AND scu.id_user = '$userId') + (scu.status = 2 AND scu.user_id = '$userId') "; $teacherSelect = "UNION ALL ( $select FROM $tbl_user u - INNER JOIN $tbl_session_rel_user sru ON (sru.id_user = u.user_id) + INNER JOIN $tbl_session_rel_user sru ON (sru.user_id = u.user_id) WHERE sru.session_id IN ( SELECT DISTINCT(s.id) FROM $tbl_session s INNER JOIN @@ -4538,7 +4538,7 @@ class UserManager } elseif ($session > 0) { $sql = 'SELECT u.user_id FROM '.$table_user.' u INNER JOIN '.$table_session_course_user.' sru - ON sru.id_user=u.user_id + ON sru.user_id=u.user_id WHERE sru.course_code="'.Database::escape_string($courseCode).'" AND sru.status=2'; @@ -4647,25 +4647,25 @@ class UserManager /** * This function check if the user is a coach inside session course * @param int User id - * @param string Course code + * @param int $courseId * @param int Session id * @return bool True if the user is a coach * */ - public static function is_session_course_coach($user_id, $course_code, $session_id) + public static function is_session_course_coach($user_id, $courseId, $session_id) { $tbl_session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); // Protect data $user_id = intval($user_id); - $course_code = Database::escape_string($course_code); + $courseId = intval($courseId); $session_id = intval($session_id); $result = false; - $sql = "SELECT id_session FROM $tbl_session_course_rel_user + $sql = "SELECT session_id FROM $tbl_session_course_rel_user WHERE - id_session=$session_id AND - course_code='$course_code' AND - id_user = $user_id AND + session_id=$session_id AND + c_id='$courseId' AND + user_id = $user_id AND status = 2 "; $res = Database::query($sql); diff --git a/main/inc/local.inc.php b/main/inc/local.inc.php index 6f488807c9..4927c4022a 100755 --- a/main/inc/local.inc.php +++ b/main/inc/local.inc.php @@ -917,7 +917,8 @@ if (isset($cidReset) && $cidReset) { $_SESSION['_gid'] = intval($_REQUEST['gidReq']); $group_table = Database::get_course_table(TABLE_GROUP); - $sql = "SELECT * FROM $group_table WHERE c_id = ".$_course['real_id']." AND id = '$gidReq'"; + $sql = "SELECT * FROM $group_table + WHERE c_id = ".$_course['real_id']." AND id = '$gidReq'"; $result = Database::query($sql); if (Database::num_rows($result) > 0) { // This group has recorded status related to this course $gpData = Database::fetch_array($result); @@ -1040,9 +1041,9 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) { if (Database::num_rows($result) > 0) { // this user have a recorded state for this course $cuData = Database::fetch_array($result, 'ASSOC'); - $is_courseAdmin = (bool) ($cuData['status'] == 1 ); - $is_courseTutor = (bool) ($cuData['tutor_id' ] == 1 ); - $is_courseMember = true; + $is_courseAdmin = (bool)($cuData['status'] == 1); + $is_courseTutor = (bool)($cuData['tutor_id'] == 1); + $is_courseMember = true; $_courseUser['role'] = $cuData['role']; Session::write('_courseUser', $_courseUser); @@ -1055,18 +1056,19 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) { // This user has no status related to this course // The user is subscribed in a session? The user is a Session coach a Session admin ? - $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION); - $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE); + $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION); + $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE); $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER); // Session coach, session admin or course coach admin - $sql = "SELECT session.id_coach, session_admin_id, session_rcru.id_user + $sql = "SELECT session.id_coach, session_admin_id, session_rcru.user_id FROM $tbl_session session, $tbl_session_course_user session_rcru - WHERE session_rcru.session_id = session.id AND - session_rcru.c_id = '$_cid' AND - session_rcru.id_user = '$user_id' AND - session_rcru.session_id = $session_id AND - session_rcru.status = 2 + WHERE + session_rcru.session_id = session.id AND + session_rcru.c_id = '$_real_cid' AND + session_rcru.user_id = '$user_id' AND + session_rcru.session_id = $session_id AND + session_rcru.status = 2 "; $result = Database::query($sql); @@ -1082,12 +1084,12 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) { $is_sessionAdmin = true; } else { // Am I a session coach for this session? - $sql = "SELECT id, id_coach FROM $tbl_session session ". - "INNER JOIN $tbl_session_course sc ". - "ON sc.session_id = session.id ". - "WHERE session.id = $session_id ". - "AND session.id_coach = $user_id ". - "AND sc.course_code = '$_cid'"; + $sql = "SELECT id, id_coach FROM $tbl_session session + INNER JOIN $tbl_session_course sc + ON sc.session_id = session.id + WHERE session.id = $session_id + AND session.id_coach = $user_id + AND sc.c_id = '$_real_cid'"; $result = Database::query($sql); if (Database::num_rows($result)) { @@ -1098,12 +1100,13 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) { $is_sessionAdmin = false; } else { // Am I a course coach or a student? - $sql = "SELECT cu.id_user, cu.status ". - "FROM $tbl_session_course_user cu ". - "WHERE course_code = '$_cid' AND ". - " cu.id_user = '".$user_id."' AND ". - " cu.session_id = '".$session_id."' ". - "LIMIT 1"; + $sql = "SELECT cu.user_id, cu.status + FROM $tbl_session_course_user cu + WHERE + c_id = '$_real_cid' AND + cu.user_id = '".$user_id."' AND + cu.session_id = '".$session_id."' + LIMIT 1"; $result = Database::query($sql); if (Database::num_rows($result)) { @@ -1114,10 +1117,10 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) { switch ($session_course_status) { case '2': // coach - teacher $_courseUser['role'] = 'Professor'; - $is_courseMember = true; - $is_courseTutor = true; - $is_courseCoach = true; - $is_sessionAdmin = false; + $is_courseMember = true; + $is_courseTutor = true; + $is_courseCoach = true; + $is_sessionAdmin = false; if (api_get_setting('extend_rights_for_coach') == 'true') { $is_courseAdmin = true; @@ -1128,32 +1131,32 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) { break; case '0': //Student $_courseUser['role'] = ''; - $is_courseMember = true; - $is_courseTutor = false; - $is_courseAdmin = false; - $is_courseCoach = false; - $is_sessionAdmin = false; + $is_courseMember = true; + $is_courseTutor = false; + $is_courseAdmin = false; + $is_courseCoach = false; + $is_sessionAdmin = false; Session::write('_courseUser', $_courseUser); break; default: //unregister user $_courseUser['role'] = ''; - $is_courseMember = false; - $is_courseTutor = false; - $is_courseAdmin = false; - $is_sessionAdmin = false; - $is_courseCoach = false; + $is_courseMember = false; + $is_courseTutor = false; + $is_courseAdmin = false; + $is_sessionAdmin = false; + $is_courseCoach = false; Session::erase('_courseUser'); break; } } else { // Unregister user - $is_courseMember = false; - $is_courseTutor = false; - $is_courseAdmin = false; - $is_sessionAdmin = false; - $is_courseCoach = false; + $is_courseMember = false; + $is_courseTutor = false; + $is_courseAdmin = false; + $is_sessionAdmin = false; + $is_courseCoach = false; Session::erase('_courseUser'); } } diff --git a/main/mySpace/coaches.php b/main/mySpace/coaches.php index dae8ff8df6..321b2ab860 100755 --- a/main/mySpace/coaches.php +++ b/main/mySpace/coaches.php @@ -49,27 +49,30 @@ if (isset($_POST['export'])) { if (isset($_GET["id_student"])) { $id_student = intval($_GET["id_student"]); - $sql_coachs = "SELECT DISTINCT srcru.id_user as id_coach" . - "FROM $tbl_session_rel_course_rel_user as srcru " . - "WHERE srcru.id_user='$id_student' AND srcru.status=2"; + $sql_coachs = "SELECT DISTINCT srcru.user_id as id_coach + FROM $tbl_session_rel_course_rel_user as srcru + WHERE srcru.user_id='$id_student' AND srcru.status=2"; } else { if (api_is_platform_admin()) { - $sql_coachs = "SELECT DISTINCT srcru.id_user as id_coach, user_id, lastname, firstname + $sql_coachs = "SELECT DISTINCT + srcru.user_id as id_coach, user_id, lastname, firstname FROM $tbl_user, $tbl_session_rel_course_rel_user srcru - WHERE srcru.id_user=user_id AND srcru.status=2 ".$order_clause; + WHERE + srcru.user_id=user_id AND + srcru.status=2 ".$order_clause; } else { - $sql_coachs = "SELECT DISTINCT id_user as id_coach, $tbl_user.user_id, lastname, firstname + $sql_coachs = "SELECT DISTINCT user_id as id_coach, $tbl_user.user_id, lastname, firstname FROM $tbl_user as user, $tbl_session_rel_course_user as srcu, $tbl_course_user as course_rel_user, $tbl_course as c WHERE - c.id = course_rel_userc_id AND + c.id = course_rel_user.c_id AND c.code = srcu.course_code AND course_rel_user.status='1' AND - course_rel_user.user_id='".intval($_SESSION["_uid"])."' AND - srcu.id_user=user.user_id AND + course_rel_user.user_id='".api_get_user_id()."' AND + srcu.user_id = user.user_id AND srcu.status = 2 ".$order_clause; } diff --git a/main/mySpace/myStudents.php b/main/mySpace/myStudents.php index 969d75c3a0..10e5eee128 100755 --- a/main/mySpace/myStudents.php +++ b/main/mySpace/myStudents.php @@ -255,21 +255,21 @@ while ($row = Database :: fetch_array($rs)) { } // Get the list of sessions where the user is subscribed as student -$sql = 'SELECT id_session, course_code +$sql = 'SELECT session_id, c_id FROM '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).' - WHERE id_user=' . intval($user_info['user_id']); + WHERE user_id=' . intval($user_info['user_id']); $rs = Database::query($sql); $tmp_sessions = array(); while ($row = Database :: fetch_array($rs)) { - $tmp_sessions[] = $row['id_session']; + $tmp_sessions[] = $row['session_id']; if ($drh_can_access_all_courses) { - if (in_array($row['id_session'], $tmp_sessions)) { - $courses_in_session[$row['id_session']][] = $row['course_code']; + if (in_array($row['session_id'], $tmp_sessions)) { + $courses_in_session[$row['session_id']][] = $row['c_id']; } } else { - if (isset($courses_in_session_by_coach[$row['id_session']])) { - if (in_array($row['id_session'], $tmp_sessions)) { - $courses_in_session[$row['id_session']][] = $row['course_code']; + if (isset($courses_in_session_by_coach[$row['session_id']])) { + if (in_array($row['session_id'], $tmp_sessions)) { + $courses_in_session[$row['session_id']][] = $row['c_id']; } } } @@ -659,9 +659,10 @@ if (!empty($student_id)) { '; if (!empty($courses)) { - foreach ($courses as $course_code) { - $courseInfo = api_get_course_info($course_code); + foreach ($courses as $courseId) { + $courseInfo = api_get_course_info_by_id($courseId); $courseId = $courseInfo['real_id']; + $course_code = $courseInfo['code']; if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) { $course_info = CourseManager :: get_course_information($course_code); diff --git a/main/mySpace/user_add.php b/main/mySpace/user_add.php index c22c044fa9..519e33aae9 100755 --- a/main/mySpace/user_add.php +++ b/main/mySpace/user_add.php @@ -273,25 +273,29 @@ if ($form->validate()) { $id_session = $user['session_id']; if ($id_session != 0) { - $result = Database::query("SELECT course_code FROM $tbl_session_rel_course WHERE id_session='$id_session'"); + $result = Database::query("SELECT c_id FROM $tbl_session_rel_course WHERE session_id ='$id_session'"); $CourseList=array(); while ($row = Database::fetch_array($result)) { - $CourseList[] = $row['course_code']; + $CourseList[] = $row['c_id']; } foreach ($CourseList as $enreg_course) { - Database::query("INSERT INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$user_id')"); + $sql = "INSERT INTO $tbl_session_rel_course_rel_user(id_session,c_id,user_id) + VALUES('$id_session','$enreg_course','$user_id')"; + Database::query($sql); // updating the total - $sql = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='$enreg_course'"; + $sql = "SELECT COUNT(user_id) as nbUsers FROM $tbl_session_rel_course_rel_user + WHERE session_id ='$id_session' AND c_id='$enreg_course'"; $rs = Database::query($sql); list($nbr_users) = Database::fetch_array($rs); - Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'"); + Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE session_id='$id_session' AND c_id='$enreg_course'"); } - Database::query("INSERT INTO $tbl_session_rel_user(id_session, id_user) VALUES('$id_session','$user_id')"); + Database::query("INSERT INTO $tbl_session_rel_user(session_id, user_id) VALUES('$id_session','$user_id')"); - $sql = "SELECT COUNT(nbr_users) as nbUsers FROM $tbl_session WHERE id='$id_session' "; + $sql = "SELECT COUNT(nbr_users) as nbUsers + FROM $tbl_session WHERE id='$id_session' "; $rs = Database::query($sql); list($nbr_users) = Database::fetch_array($rs); @@ -299,7 +303,6 @@ if ($form->validate()) { } } - $extras = array(); foreach ($user as $key => $value) { if (substr($key, 0, 6) == 'extra_') { diff --git a/main/mySpace/user_import.php b/main/mySpace/user_import.php index 62dbc5848e..b59faed310 100755 --- a/main/mySpace/user_import.php +++ b/main/mySpace/user_import.php @@ -72,13 +72,13 @@ if ($_POST['formSent'] && $_FILES['import_file']['size'] !== 0) { if (!empty($id_session)) { $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE); // Selecting all the courses from the session id requested. - $sql = "SELECT c_id FROM $tbl_session_rel_course WHERE id_session='$id_session'"; + $sql = "SELECT c_id FROM $tbl_session_rel_course WHERE session_id ='$id_session'"; $result = Database::query($sql); $course_list = array(); while ($row = Database::fetch_array($result)) { $course_list[] = $row['c_id']; } - $errors = MySpace::get_user_creator($users, $course_list, $id_session); + $errors = MySpace::get_user_creator($users); $users = MySpace::check_all_usernames($users, $course_list, $id_session); if (count($errors) == 0) { MySpace::save_data($users, $course_list, $id_session); diff --git a/main/social/group_invitation.php b/main/social/group_invitation.php index 70886253ab..4d21ecaac2 100755 --- a/main/social/group_invitation.php +++ b/main/social/group_invitation.php @@ -79,7 +79,8 @@ function search_users($needle, $type) if (!empty($id_session)) { $group_id = intval($group_id); // check id_user from session_rel_user table - $sql = 'SELECT id_user FROM ' . $tbl_group_rel_user . ' WHERE group_id ="' . (int)$group_id . '"'; + $sql = 'SELECT user_id FROM ' . $tbl_group_rel_user . ' + WHERE group_id ="' . (int)$group_id . '"'; $res = Database::query($sql); $user_ids = array(); if (Database::num_rows($res) > 0) { @@ -88,25 +89,27 @@ function search_users($needle, $type) } } if (count($user_ids) > 0) { - $cond_user_id = ' AND user_id NOT IN(' . implode( - ",", - $user_ids - ) . ')'; + $cond_user_id = ' AND user_id NOT IN(' . implode(",", $user_ids ) . ')'; } } if ($type == 'single') { // search users where username or firstname or lastname begins likes $needle - $sql = 'SELECT user_id, username, lastname, firstname FROM ' . $tbl_user . ' user - WHERE (username LIKE "' . $needle . '%" - OR firstname LIKE "' . $needle . '%" - OR lastname LIKE "' . $needle . '%") AND user_id<>"' . $user_anonymous . '"' . - $order_clause . - ' LIMIT 11'; + $sql = 'SELECT user_id, username, lastname, firstname + FROM ' . $tbl_user . ' user + WHERE + ( + username LIKE "' . $needle . '%" OR + firstname LIKE "' . $needle . '%" OR + lastname LIKE "' . $needle . '%" + ) AND user_id <>"' . $user_anonymous . '"' . + $order_clause . + ' LIMIT 11'; } else { $sql = 'SELECT user_id, username, lastname, firstname FROM ' . $tbl_user . ' user - WHERE ' . (api_sort_by_first_name( - ) ? 'firstname' : 'lastname') . ' LIKE "' . $needle . '%" AND user_id<>"' . $user_anonymous . '"' . $cond_user_id . + WHERE + ' . (api_sort_by_first_name() ? 'firstname' : 'lastname') . ' LIKE "' . $needle . '%" AND + user_id<>"' . $user_anonymous . '"' . $cond_user_id . $order_clause; } @@ -117,20 +120,27 @@ function search_users($needle, $type) $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { if ($type == 'single') { - $sql = 'SELECT user.user_id, username, lastname, firstname FROM ' . $tbl_user . ' user - INNER JOIN ' . $tbl_user_rel_access_url . ' url_user ON (url_user.user_id=user.user_id) - WHERE access_url_id = ' . $access_url_id . ' AND (username LIKE "' . $needle . '%" - OR firstname LIKE "' . $needle . '%" - OR lastname LIKE "' . $needle . '%") AND user.user_id<>"' . $user_anonymous . '"' . + $sql = 'SELECT user.user_id, username, lastname, firstname + FROM ' . $tbl_user . ' user + INNER JOIN ' . $tbl_user_rel_access_url . ' url_user ON (url_user.user_id=user.user_id) + WHERE + access_url_id = ' . $access_url_id . ' AND + ( + username LIKE "' . $needle . '%" OR + firstname LIKE "' . $needle . '%" OR + lastname LIKE "' . $needle . '%" + ) AND user.user_id<>"' . $user_anonymous . '"' . $order_clause . ' LIMIT 11'; } else { - $sql = 'SELECT user.user_id, username, lastname, firstname FROM ' . $tbl_user . ' user - INNER JOIN ' . $tbl_user_rel_access_url . ' url_user ON (url_user.user_id=user.user_id) - WHERE access_url_id = ' . $access_url_id . ' - AND ' . (api_sort_by_first_name( - ) ? 'firstname' : 'lastname') . ' LIKE "' . $needle . '%" AND user.user_id<>"' . $user_anonymous . '"' . $cond_user_id . - $order_clause; + $sql = 'SELECT user.user_id, username, lastname, firstname + FROM ' . $tbl_user . ' user + INNER JOIN ' . $tbl_user_rel_access_url . ' url_user ON (url_user.user_id=user.user_id) + WHERE + access_url_id = ' . $access_url_id . ' AND + ' . (api_sort_by_first_name() ? 'firstname' : 'lastname') . ' LIKE "' . $needle . '%" AND + user.user_id<>"' . $user_anonymous . '"' . $cond_user_id . + $order_clause; } } } @@ -266,10 +276,10 @@ if ($ajax_search) { ); $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { - $sql = "SELECT u.user_id, lastname, firstname, username, id_session + $sql = "SELECT u.user_id, lastname, firstname, username, session_id FROM $tbl_user u INNER JOIN $tbl_session_rel_user - ON $tbl_session_rel_user.id_user = u.user_id + ON $tbl_session_rel_user.user_id = u.user_id AND $tbl_session_rel_user.session_id = " . intval($id_session) . " INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id) diff --git a/main/tracking/userLog.php b/main/tracking/userLog.php index 7c4431d66b..80915c1a0f 100755 --- a/main/tracking/userLog.php +++ b/main/tracking/userLog.php @@ -76,7 +76,7 @@ $sql = "SELECT 1 AND ((date_start <= '$now' AND date_end >= '$now') OR (date_start='0000-00-00' AND date_end='0000-00-00')) - WHERE id_session='".api_get_session_id()."' AND course_code='$_cid'"; + WHERE session_id='".api_get_session_id()."' AND course_code='$_cid'"; //echo $sql; $result=Database::query($sql); if(!Database::num_rows($result)){ diff --git a/main/tracking/userlogCSV.php b/main/tracking/userlogCSV.php index c96705d1fa..5c198b9cae 100755 --- a/main/tracking/userlogCSV.php +++ b/main/tracking/userlogCSV.php @@ -71,7 +71,7 @@ $sql = "SELECT 1 AND ((date_start <= '$now' AND date_end >= '$now') OR (date_start='0000-00-00' AND date_end='0000-00-00')) - WHERE id_session='" . $_SESSION['id_session'] . "' AND course_code='$_cid'"; + WHERE session_id='" . $_SESSION['id_session'] . "' AND course_code='$_cid'"; //echo $sql; $result = Database::query($sql); if (!Database::num_rows($result)) { diff --git a/main/user/add_users_to_session.php b/main/user/add_users_to_session.php index 349246b70b..fd7ed256b2 100755 --- a/main/user/add_users_to_session.php +++ b/main/user/add_users_to_session.php @@ -84,7 +84,8 @@ if($_configuration['allow_tutors_to_assign_students_to_session'] == 'true') { if (!empty($id_session)) { $id_session = intval($id_session); // check id_user from session_rel_user table - $sql = 'SELECT id_user FROM '.$tbl_session_rel_user.' WHERE session_id ="'.$id_session.'" AND relation_type<>'.SESSION_RELATION_TYPE_RRHH.' '; + $sql = 'SELECT user_id FROM '.$tbl_session_rel_user.' + WHERE session_id ="'.$id_session.'" AND relation_type<>'.SESSION_RELATION_TYPE_RRHH.' '; $res = Database::query($sql); $user_ids = array(); if (Database::num_rows($res) > 0) { @@ -109,13 +110,20 @@ if($_configuration['allow_tutors_to_assign_students_to_session'] == 'true') { break; case 'multiple': $sql = 'SELECT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user - WHERE '.(api_sort_by_first_name() ? 'firstname' : 'lastname').' LIKE "'.$needle.'%" AND user.status<>'.DRH.' AND user.status<>6 '.$cond_user_id. + WHERE '.(api_sort_by_first_name() ? 'firstname' : 'lastname').' + LIKE "'.$needle.'%" AND + user.status<>'.DRH.' AND + user.status<>6 '.$cond_user_id. $order_clause; break; case 'any_session': - $sql = 'SELECT DISTINCT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user LEFT OUTER JOIN '.$tbl_session_rel_user.' s ON (s.id_user = user.user_id) - WHERE s.id_user IS null AND user.status<>'.DRH.' AND - user.status<>6 '.$cond_user_id. + $sql = 'SELECT DISTINCT user.user_id, username, lastname, firstname + FROM '.$tbl_user.' user + LEFT OUTER JOIN '.$tbl_session_rel_user.' s ON (s.user_id = user.user_id) + WHERE + s.user_id IS NULL AND + user.status <>'.DRH.' AND + user.status <> 6 '.$cond_user_id. $order_clause; break; } @@ -141,12 +149,15 @@ if($_configuration['allow_tutors_to_assign_students_to_session'] == 'true') { $order_clause; break; case 'any_session' : - $sql = 'SELECT DISTINCT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user LEFT OUTER JOIN '.$tbl_session_rel_user.' s ON (s.id_user = user.user_id) - INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id) - WHERE access_url_id = '.$access_url_id.' AND - s.id_user IS null AND - user.status<>'.DRH.' AND - user.status<>6 '.$cond_user_id. + $sql = 'SELECT DISTINCT user.user_id, username, lastname, firstname + FROM '.$tbl_user.' user LEFT OUTER JOIN '.$tbl_session_rel_user.' s + ON (s.user_id = user.user_id) + INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id) + WHERE + access_url_id = '.$access_url_id.' AND + s.user_id IS null AND + user.status<>'.DRH.' AND + user.status<>6 '.$cond_user_id. $order_clause; break; } @@ -265,12 +276,12 @@ if($_configuration['allow_tutors_to_assign_students_to_session'] == 'true') { $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username'; if ($ajax_search) { - $sql = "SELECT user_id, lastname, firstname, username, session_id + $sql = "SELECT u.user_id, lastname, firstname, username, session_id FROM $tbl_user u INNER JOIN $tbl_session_rel_user - ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH." + ON $tbl_session_rel_user.user_id = u.user_id AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH." AND $tbl_session_rel_user.session_id = ".intval($id_session)." - WHERE u.status<>".DRH." AND u.status<>6 $order_clause"; + WHERE u.status<>".DRH." AND u.status<>6 $order_clause"; if (api_is_multiple_url_enabled()) { $tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); @@ -341,18 +352,22 @@ if($_configuration['allow_tutors_to_assign_students_to_session'] == 'true') { } if ($use_extra_fields) { - $sql = "SELECT user_id, lastname, firstname, username, session_id + $sql = "SELECT u.user_id, lastname, firstname, username, session_id FROM $tbl_user u - LEFT JOIN $tbl_session_rel_user - ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.session_id = '$id_session' AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH." - $where_filter AND u.status<>".DRH." AND u.status<>6 - $order_clause"; + LEFT JOIN $tbl_session_rel_user + ON $tbl_session_rel_user.user_id = u.user_id AND + $tbl_session_rel_user.session_id = '$id_session' AND + $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH." + $where_filter AND u.status<>".DRH." AND u.status<>6 + $order_clause"; } else { $sql = "SELECT user_id, lastname, firstname, username, session_id FROM $tbl_user u LEFT JOIN $tbl_session_rel_user - ON $tbl_session_rel_user.id_user = u.user_id AND $tbl_session_rel_user.session_id = '$id_session' AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH." + ON $tbl_session_rel_user.user_id = u.user_id AND + $tbl_session_rel_user.session_id = '$id_session' AND + $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH." WHERE u.status<>".DRH." AND u.status<>6 $order_clause"; } @@ -393,7 +408,7 @@ if($_configuration['allow_tutors_to_assign_students_to_session'] == 'true') { FROM $tbl_user u LEFT JOIN $tbl_session_rel_user ON - $tbl_session_rel_user.id_user = u.user_id AND + $tbl_session_rel_user.user_id = u.id AND $tbl_session_rel_user.session_id = '$id_session' AND $tbl_session_rel_user.relation_type<>".SESSION_RELATION_TYPE_RRHH." WHERE u.status<>".DRH." AND u.status<>6 $order_clause"; diff --git a/main/user/resume_session.php b/main/user/resume_session.php index 11d46a88ad..8dcb55268f 100755 --- a/main/user/resume_session.php +++ b/main/user/resume_session.php @@ -59,7 +59,10 @@ if($_configuration['allow_tutors_to_assign_students_to_session'] == 'true') { $result = UrlManager::add_user_to_url($user_id, $url_id); $user_info = api_get_user_info($user_id); if ($result) { - $message = Display::return_message(get_lang('UserAdded').' '.api_get_person_name($user_info['firstname'], $user_info['lastname']), 'confirm'); + $message = Display::return_message( + get_lang('UserAdded').' '.api_get_person_name($user_info['firstname'], $user_info['lastname']), + 'confirm' + ); } break; case 'delete': @@ -67,16 +70,16 @@ if($_configuration['allow_tutors_to_assign_students_to_session'] == 'true') { if(is_array($idChecked)) { $my_temp = array(); foreach ($idChecked as $id){ - $my_temp[]= Database::escape_string($id);// forcing the escape_string + $courseInfo = api_get_course_info($id); + $my_temp[]= $courseInfo['real_id'];// forcing the escape_string } $idChecked = $my_temp; + $idChecked = "'".implode("','", $idChecked)."'"; - $idChecked="'".implode("','",$idChecked)."'"; - - $result = Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND course_code IN($idChecked)"); + $result = Database::query("DELETE FROM $tbl_session_rel_course WHERE session_id='$id_session' AND c_id IN($idChecked)"); $nbr_affected_rows=Database::affected_rows($result); - Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code IN($idChecked)"); + Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id='$id_session' AND c_id IN($idChecked)"); Database::query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'"); } @@ -87,15 +90,15 @@ if($_configuration['allow_tutors_to_assign_students_to_session'] == 'true') { } if (!empty($_GET['user'])) { - $result = Database::query("DELETE FROM $tbl_session_rel_user WHERE relation_type<>".SESSION_RELATION_TYPE_RRHH." AND id_session='$id_session' AND id_user=".intval($_GET['user'])); + $result = Database::query("DELETE FROM $tbl_session_rel_user WHERE relation_type<>".SESSION_RELATION_TYPE_RRHH." AND session_id ='$id_session' AND user_id=".intval($_GET['user'])); $nbr_affected_rows = Database::affected_rows($result); Database::query("UPDATE $tbl_session SET nbr_users=nbr_users-$nbr_affected_rows WHERE id='$id_session'"); - $result = Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND id_user=".intval($_GET['user'])); + $result = Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id ='$id_session' AND user_id=".intval($_GET['user'])); $nbr_affected_rows=Database::affected_rows($result); - Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$id_session'"); + Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE session_id ='$id_session'"); } break; } @@ -303,7 +306,7 @@ if($_configuration['allow_tutors_to_assign_students_to_session'] == 'true') { $sql = "SELECT u.user_id, lastname, firstname, username, access_url_id FROM $tbl_user u INNER JOIN $tbl_session_rel_user su - ON u.user_id = su.id_user AND su.relation_type<>".SESSION_RELATION_TYPE_RRHH." + ON u.user_id = su.user_id AND su.relation_type<>".SESSION_RELATION_TYPE_RRHH." LEFT OUTER JOIN $table_access_url_user uu ON (uu.user_id = u.user_id) WHERE su.session_id = $id_session AND (access_url_id = $url_id OR access_url_id is null ) $order_clause"; @@ -311,7 +314,7 @@ if($_configuration['allow_tutors_to_assign_students_to_session'] == 'true') { $sql = "SELECT u.user_id, lastname, firstname, username FROM $tbl_user u INNER JOIN $tbl_session_rel_user su - ON u.user_id = su.id_user AND su.relation_type<>".SESSION_RELATION_TYPE_RRHH." + ON u.user_id = su.user_id AND su.relation_type<>".SESSION_RELATION_TYPE_RRHH." AND su.session_id = ".$id_session.$order_clause; } diff --git a/main/user/subscribe_user.php b/main/user/subscribe_user.php index f4a11c085c..4cf2a30463 100755 --- a/main/user/subscribe_user.php +++ b/main/user/subscribe_user.php @@ -237,18 +237,27 @@ function get_number_of_users() $sql = "SELECT COUNT(u.user_id) FROM $user_table u - LEFT JOIN $tbl_session_rel_course_user cu on u.user_id = cu.id_user and course_code='".api_get_course_id()."' AND id_session ='".api_get_session_id()."' - WHERE cu.id_user IS NULL AND u.status=1 AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; + LEFT JOIN $tbl_session_rel_course_user cu + ON + u.user_id = cu.user_id AND + c_id = '".api_get_course_int_id()."' AND + session_id ='".api_get_session_id()."' + WHERE + cu.user_id IS NULL AND + u.status = 1 AND + (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; if ($_configuration['multiple_access_urls']) { $url_access_id = api_get_current_access_url_id(); if ($url_access_id !=-1) { $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); - $sql = "SELECT COUNT(u.user_id) FROM $user_table u - LEFT JOIN $tbl_session_rel_course_user cu on u.user_id = cu.id_user and course_code='".api_get_course_id()."' AND id_session ='".api_get_session_id()."' + $sql = "SELECT COUNT(u.user_id) + FROM $user_table u + LEFT JOIN $tbl_session_rel_course_user cu + ON u.user_id = cu.user_id and cu.c_id = '".api_get_course_int_id()."' AND session_id ='".api_get_session_id()."' INNER JOIN $tbl_url_rel_user as url_rel_user ON (url_rel_user.user_id = u.user_id) - WHERE cu.id_user IS NULL AND access_url_id= $url_access_id AND u.status=1 AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; + WHERE cu.user_id IS NULL AND access_url_id= $url_access_id AND u.status=1 AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; } } } else { @@ -279,24 +288,41 @@ function get_number_of_users() if (api_get_session_id() != 0) { $sql = "SELECT COUNT(u.user_id) FROM $user_table u - LEFT JOIN $tbl_session_rel_course_user cu on u.user_id = cu.id_user and course_code='".api_get_course_id()."' AND id_session ='".api_get_session_id()."' - WHERE cu.id_user IS NULL AND u.status<>".DRH." AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; + LEFT JOIN $tbl_session_rel_course_user cu + ON + u.user_id = cu.user_id AND + c_id='".api_get_course_int_id()."' AND + session_id ='".api_get_session_id()."' + WHERE + cu.user_id IS NULL AND + u.status<>".DRH." AND + (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; + if ($_configuration['multiple_access_urls']) { $url_access_id = api_get_current_access_url_id(); if ($url_access_id !=-1) { $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); $sql = "SELECT COUNT(u.user_id) FROM $user_table u - LEFT JOIN $tbl_session_rel_course_user cu on u.user_id = cu.id_user and course_code='".api_get_course_id()."' AND id_session ='".api_get_session_id()."' + LEFT JOIN $tbl_session_rel_course_user cu + ON + u.user_id = cu.user_id AND + c_id='".api_get_course_int_id()."' AND + session_id ='".api_get_session_id()."' INNER JOIN $tbl_url_rel_user as url_rel_user ON (url_rel_user.user_id = u.user_id) - WHERE cu.id_user IS NULL AND u.status<>".DRH." AND access_url_id= $url_access_id AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; + WHERE + cu.user_id IS NULL AND + u.status<>".DRH." AND + access_url_id= $url_access_id AND + (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; } } } else { $sql = "SELECT COUNT(u.user_id) FROM $user_table u - LEFT JOIN $course_user_table cu on u.user_id = cu.user_id and c_id='".api_get_course_int_id()."'"; + LEFT JOIN $course_user_table cu + ON u.user_id = cu.user_id AND c_id='".api_get_course_int_id()."'"; // we change the SQL when we have a filter if (isset($_GET['subscribe_user_filter_value']) AND @@ -415,8 +441,12 @@ function get_user_data($from, $number_of_items, $column, $direction) $sql = "SELECT $select_fields FROM $user_table u LEFT JOIN $tbl_session_rel_course_user cu - ON u.user_id = cu.id_user AND c_id ='".$courseId."' AND id_session ='".$session_id."' - INNER JOIN $tbl_url_rel_user as url_rel_user ON (url_rel_user.user_id = u.user_id) "; + ON + u.user_id = cu.user_id AND + c_id ='".$courseId."' AND + session_id ='".$session_id."' + INNER JOIN $tbl_url_rel_user as url_rel_user + ON (url_rel_user.user_id = u.user_id) "; // applying the filter of the additional user profile fields if (isset($_GET['subscribe_user_filter_value']) && @@ -428,13 +458,13 @@ function get_user_data($from, $number_of_items, $column, $direction) LEFT JOIN $table_user_field_values field_values ON field_values.user_id = u.user_id WHERE - cu.id_user IS NULL AND + cu.user_id IS NULL AND u.status=1 AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) AND field_values.field_id = '".intval($field_identification[0])."' AND field_values.field_value = '".Database::escape_string($field_identification[1])."'"; } else { - $sql .= "WHERE cu.id_user IS NULL AND u.status=1 AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; + $sql .= "WHERE cu.user_id IS NULL AND u.status=1 AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; } $sql .= " AND access_url_id= $url_access_id"; @@ -500,9 +530,9 @@ function get_user_data($from, $number_of_items, $column, $direction) FROM $user_table u LEFT JOIN $tbl_session_rel_course_user cu ON - u.user_id = cu.id_user AND + u.user_id = cu.user_id AND c_id ='".$courseId."' AND - id_session ='".$session_id."' "; + session_id ='".$session_id."' "; if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) { $sql .= " INNER JOIN $tbl_url_rel_user as url_rel_user ON (url_rel_user.user_id = u.user_id) "; @@ -515,14 +545,14 @@ function get_user_data($from, $number_of_items, $column, $direction) LEFT JOIN $table_user_field_values field_values ON field_values.user_id = u.user_id WHERE - cu.id_user IS NULL AND + cu.user_id IS NULL AND u.status<>".DRH." AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) AND field_values.field_id = '".intval($field_identification[0])."' AND field_values.field_value = '".Database::escape_string($field_identification[1])."'"; } else { $sql .= "WHERE - cu.id_user IS NULL AND + cu.user_id IS NULL AND u.status<>".DRH." AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; } diff --git a/main/user/user.php b/main/user/user.php index b7edd383c5..81fce359d6 100755 --- a/main/user/user.php +++ b/main/user/user.php @@ -190,8 +190,8 @@ if (api_is_allowed_to_edit(null, true)) { if (api_is_multiple_url_enabled()) { $sql_query .= ' , '.Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER).' au '; } - $sql_query .=" WHERE c_id = '$courseId' AND session_course_user.id_user = user.user_id "; - $sql_query .= ' AND id_session = '.$session_id; + $sql_query .=" WHERE c_id = '$courseId' AND session_course_user.user_id = user.user_id "; + $sql_query .= ' AND session_id = '.$session_id; if (api_is_multiple_url_enabled()) { $sql_query .= " AND user.user_id = au.user_id AND access_url_id = $current_access_url_id "; @@ -387,7 +387,7 @@ if (api_is_allowed_to_edit(null, true)) { $sql = 'SELECT '.$tbl_user.'.user_id FROM '.$tbl_user.' user INNER JOIN '.$tbl_session_rel_user.' reluser - ON user.user_id = reluser.id_user AND reluser.relation_type<>'.SESSION_RELATION_TYPE_RRHH.' + ON user.user_id = reluser.user_id AND reluser.relation_type<>'.SESSION_RELATION_TYPE_RRHH.' INNER JOIN '.$tbl_session_rel_course.' rel_course ON rel_course.session_id = reluser.id_session WHERE user.user_id = "'.$user_id.'" diff --git a/main/user/userInfo.php b/main/user/userInfo.php index b6df1ef7e3..d18cd70265 100755 --- a/main/user/userInfo.php +++ b/main/user/userInfo.php @@ -210,7 +210,7 @@ if (api_is_allowed_to_edit(null, true)) { // get information about user id viewed $user_info_viewed = api_get_user_info($userIdViewed); -$is_session_course_coach = UserManager::is_session_course_coach($userIdViewed, $_course['sysCode'], $current_session_id); +$is_session_course_coach = UserManager::is_session_course_coach($userIdViewed, $_course['real_id'], $current_session_id); if ($displayMode == "viewDefEdit") { /* CATEGORIES DEFINITIONS : EDIT */ diff --git a/main/webservices/registration.soap.php b/main/webservices/registration.soap.php index 91d4211cef..48c8a3432d 100755 --- a/main/webservices/registration.soap.php +++ b/main/webservices/registration.soap.php @@ -3783,11 +3783,11 @@ function WSDeleteSession($params) { $sql_session = "DELETE FROM $tbl_session WHERE id = '$idChecked'"; @Database::query($sql_session); - $sql_session_rel_course = "DELETE FROM $tbl_session_rel_course WHERE id_session = '$idChecked'"; + $sql_session_rel_course = "DELETE FROM $tbl_session_rel_course WHERE session_id = '$idChecked'"; @Database::query($sql_session_rel_course); - $sql_session_rel_course_rel_user = "DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session = '$idChecked'"; + $sql_session_rel_course_rel_user = "DELETE FROM $tbl_session_rel_course_rel_user WHERE session_id = '$idChecked'"; @Database::query($sql_session_rel_course_rel_user); - $sql_session_rel_course = "DELETE FROM $tbl_session_rel_user WHERE id_session = '$idChecked'"; + $sql_session_rel_course = "DELETE FROM $tbl_session_rel_user WHERE session_id = '$idChecked'"; @Database::query($sql_session_rel_course); $results[] = 1; continue; @@ -4471,17 +4471,18 @@ function WSSuscribeUsersToSession($params){ continue; } - $sql = "SELECT id_user FROM $tbl_session_rel_user WHERE id_session='$id_session' AND relation_type<>".SESSION_RELATION_TYPE_RRHH.""; + $sql = "SELECT user_id FROM $tbl_session_rel_user + WHERE session_id='$id_session' AND relation_type<>".SESSION_RELATION_TYPE_RRHH.""; $result = Database::query($sql); $existingUsers = array(); while($row = Database::fetch_array($result)){ - $existingUsers[] = $row['id_user']; + $existingUsers[] = $row['user_id']; } - $sql = "SELECT course_code FROM $tbl_session_rel_course WHERE id_session='$id_session'"; + $sql = "SELECT c_id FROM $tbl_session_rel_course WHERE session_id='$id_session'"; $result=Database::query($sql); $CourseList = array(); while($row = Database::fetch_array($result)) { - $CourseList[] = $row['course_code']; + $CourseList[] = $row['c_id']; } foreach ($CourseList as $enreg_course) { @@ -4493,7 +4494,8 @@ function WSSuscribeUsersToSession($params){ foreach ($usersList as $enreg_user) { if(!in_array($enreg_user, $existingUsers)) { $enreg_user = Database::escape_string($enreg_user); - $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$enreg_user')"; + $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(session_id, c_id, user_id) + VALUES('$id_session', '$enreg_course', '$enreg_user')"; $result = Database::query($insert_sql); if (Database::affected_rows($result)) { $nbr_users++; @@ -4501,11 +4503,14 @@ function WSSuscribeUsersToSession($params){ } } // count users in this session-course relation - $sql = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='$enreg_course'"; + $sql = "SELECT COUNT(user_id) as nbUsers + FROM $tbl_session_rel_course_rel_user + WHERE session_id = '$id_session' AND c_id='$enreg_course'"; $rs = Database::query($sql); list($nbr_users) = Database::fetch_array($rs); // update the session-course relation to add the users total - $update_sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'"; + $update_sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users + WHERE session_id='$id_session' AND c_id='$enreg_course'"; Database::query($update_sql); } @@ -4514,7 +4519,7 @@ function WSSuscribeUsersToSession($params){ foreach ($usersList as $enreg_user) { $enreg_user = Database::escape_string($enreg_user); $nbr_users++; - $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_user(id_session, id_user) VALUES('$id_session','$enreg_user')"; + $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_user(session_id, user_id) VALUES('$id_session','$enreg_user')"; Database::query($insert_sql); } // update number of users in the session @@ -4530,7 +4535,11 @@ function WSSuscribeUsersToSession($params){ $count_results = count($results); $output = array(); for($i = 0; $i < $count_results; $i++) { - $output[] = array('original_user_id_values' => $orig_user_id_value[$i], 'original_session_id_value' => $orig_session_id_value[$i], 'result' => $results[$i]); + $output[] = array( + 'original_user_id_values' => $orig_user_id_value[$i], + 'original_session_id_value' => $orig_session_id_value[$i], + 'result' => $results[$i] + ); } return $output; @@ -4745,17 +4754,18 @@ function WSUnsuscribeUsersFromSession($params) { continue; } - $sql = "SELECT id_user FROM $tbl_session_rel_user WHERE id_session='$id_session' AND relation_type<>".SESSION_RELATION_TYPE_RRHH.""; + $sql = "SELECT user_id FROM $tbl_session_rel_user + WHERE session_id ='$id_session' AND relation_type<>".SESSION_RELATION_TYPE_RRHH.""; $result = Database::query($sql); $existingUsers = array(); while($row = Database::fetch_array($result)){ - $existingUsers[] = $row['id_user']; + $existingUsers[] = $row['user_id']; } - $sql = "SELECT course_code FROM $tbl_session_rel_course WHERE id_session='$id_session'"; + $sql = "SELECT c_id FROM $tbl_session_rel_course WHERE session_id='$id_session'"; $result = Database::query($sql); $CourseList = array(); - while($row = Database::fetch_array($result)) { - $CourseList[] = $row['course_code']; + while ($row = Database::fetch_array($result)) { + $CourseList[] = $row['c_id']; } foreach ($CourseList as $enreg_course) { @@ -4766,7 +4776,7 @@ function WSUnsuscribeUsersFromSession($params) { foreach ($existingUsers as $existing_user) { if (!in_array($existing_user, $usersList)) { $sql = "DELETE FROM $tbl_session_rel_course_rel_user - WHERE id_session='$id_session' AND course_code='$enreg_course' AND id_user='$existing_user'"; + WHERE session_id ='$id_session' AND c_id='$enreg_course' AND user_id='$existing_user'"; $result = Database::query($sql); if (Database::affected_rows($result)) { @@ -4775,14 +4785,14 @@ function WSUnsuscribeUsersFromSession($params) { } } // Count users in this session-course relation. - $sql = "SELECT COUNT(id_user) as nbUsers + $sql = "SELECT COUNT(user_id) as nbUsers FROM $tbl_session_rel_course_rel_user - WHERE id_session='$id_session' AND course_code='$enreg_course'"; + WHERE session_id = '$id_session' AND c_id='$enreg_course'"; $rs = Database::query($sql); list($nbr_users) = Database::fetch_array($rs); // update the session-course relation to add the users total $update_sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users - WHERE id_session='$id_session' AND course_code='$enreg_course'"; + WHERE session_id ='$id_session' AND c_id ='$enreg_course'"; Database::query($update_sql); } @@ -4790,7 +4800,10 @@ function WSUnsuscribeUsersFromSession($params) { foreach ($usersList as $enreg_user) { $enreg_user = Database::escape_string($enreg_user); $delete_sql = "DELETE FROM $tbl_session_rel_user - WHERE id_session = '$id_session' AND id_user ='$enreg_user' AND relation_type<>".SESSION_RELATION_TYPE_RRHH.""; + WHERE + session_id = '$id_session' AND + user_id = '$enreg_user' AND + relation_type<>".SESSION_RELATION_TYPE_RRHH.""; $result = Database::query($delete_sql); $return = Database::affected_rows($result); } @@ -4975,14 +4988,18 @@ function WSSuscribeCoursesToSession($params) { $orig_session_id_value = array(); foreach ($coursessessions_params as $coursesession_param) { - $original_session_id_value = $coursesession_param['original_session_id_value']; - $original_session_id_name = $coursesession_param['original_session_id_name']; - $original_course_id_name = $coursesession_param['original_course_id_name']; - $original_course_id_values = $coursesession_param['original_course_id_values']; - $orig_session_id_value[] = $original_session_id_value; + $original_session_id_value = $coursesession_param['original_session_id_value']; + $original_session_id_name = $coursesession_param['original_session_id_name']; + $original_course_id_name = $coursesession_param['original_course_id_name']; + $original_course_id_values = $coursesession_param['original_course_id_values']; + $orig_session_id_value[] = $original_session_id_value; // get session id from original session id - $sql_session = "SELECT session_id FROM $t_sf sf,$t_sfv sfv WHERE sfv.field_id=sf.id AND field_variable='$original_session_id_name' AND field_value='$original_session_id_value'"; + $sql_session = "SELECT session_id FROM $t_sf sf,$t_sfv sfv + WHERE + sfv.field_id=sf.id AND + field_variable='$original_session_id_name' AND + field_value='$original_session_id_value'"; if ($debug) error_log($sql_session); $res_session = Database::query($sql_session); @@ -4996,25 +5013,31 @@ function WSSuscribeCoursesToSession($params) { } // Get course list from row_original_course_id_values - $course_list = array(); + $course_list = []; + $courseCodeList = []; foreach ($original_course_id_values as $row_original_course_list) { $course_code = Database::escape_string($row_original_course_list['course_code']); - $sql_course = "SELECT course_code FROM $t_cf cf, $t_cfv cfv WHERE cfv.field_id=cf.id AND field_variable='$original_course_id_name' AND field_value = '$course_code'"; + $sql_course = "SELECT course_code FROM $t_cf cf, $t_cfv cfv + WHERE cfv.field_id=cf.id AND field_variable='$original_course_id_name' AND field_value = '$course_code'"; $res_course = Database::query($sql_course); $row_course = Database::fetch_row($res_course); + $courseId = null; if (empty($row_course[0])) { continue; // course_code doesn't exist. } else { - $sql = "SELECT code FROM $tbl_course WHERE code ='".$row_course[0]."' AND visibility = '0'"; + $sql = "SELECT id FROM $tbl_course WHERE code ='".$row_course[0]."' AND visibility = '0'"; $resu = Database::query($sql); $r_check_course = Database::fetch_row($resu); if (!empty($r_check_course[0])) { continue; // user_id is not active. } + $courseInfo = api_get_course_info($row_course[0]); + $courseId = $courseInfo['real_id']; } - $course_list[] = $row_course[0]; + $courseCodeList[] = $row_course[0]; + $course_list[] = $courseId; } if (empty($course_list)) { @@ -5022,7 +5045,7 @@ function WSSuscribeCoursesToSession($params) { continue; } - $orig_course_id_value[] = implode(',', $course_list); + $orig_course_id_value[] = implode(',', $courseCodeList); // Get general coach ID $sql = "SELECT id_coach FROM $tbl_session WHERE id='$id_session'"; @@ -5031,17 +5054,17 @@ function WSSuscribeCoursesToSession($params) { $id_coach = $id_coach[0]; // get list of courses subscribed to this session - $sql = "SELECT course_code FROM $tbl_session_rel_course WHERE id_session='$id_session'"; + $sql = "SELECT c_id FROM $tbl_session_rel_course WHERE session_id ='$id_session'"; $rs = Database::query($sql); $existingCourses = Database::store_result($rs); - $nbr_courses=count($existingCourses); + $nbr_courses = count($existingCourses); // get list of users subscribed to this session - $sql= "SELECT id_user FROM $tbl_session_rel_user - WHERE id_session = '$id_session' AND relation_type<>".SESSION_RELATION_TYPE_RRHH.""; - $result=Database::query($sql); - $user_list=Database::store_result($result); + $sql= "SELECT user_id FROM $tbl_session_rel_user + WHERE session_id = '$id_session' AND relation_type<>".SESSION_RELATION_TYPE_RRHH.""; + $result = Database::query($sql); + $user_list = Database::store_result($result); $course_directory = array(); // Pass through the courses list we want to add to the session. @@ -5051,7 +5074,7 @@ function WSSuscribeCoursesToSession($params) { // Check if the course we want to add is already subscribed. foreach ($existingCourses as $existingCourse) { - if ($enreg_course == $existingCourse['course_code']) { + if ($enreg_course == $existingCourse['c_id']) { $exists = true; } } @@ -5059,27 +5082,28 @@ function WSSuscribeCoursesToSession($params) { if (!$exists) { // if the course isn't subscribed yet - $sql_insert_rel_course= "INSERT INTO $tbl_session_rel_course (id_session,course_code) VALUES ('$id_session','$enreg_course')"; - Database::query($sql_insert_rel_course); + $sql = "INSERT INTO $tbl_session_rel_course (session_id, c_id) VALUES ('$id_session','$enreg_course')"; + Database::query($sql); // We add the current course in the existing courses array, to avoid adding another time the current course - $existingCourses[] = array('course_code' => $enreg_course); + $existingCourses[] = array('c_id' => $enreg_course); $nbr_courses++; // subscribe all the users from the session to this course inside the session $nbr_users = 0; foreach ($user_list as $enreg_user) { - $enreg_user_id = Database::escape_string($enreg_user['id_user']); - $sql_insert = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (id_session,course_code,id_user) VALUES ('$id_session','$enreg_course','$enreg_user_id')"; - $result = Database::query($sql_insert); + $enreg_user_id = Database::escape_string($enreg_user['user_id']); + $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (session_id, c_id, user_id) + VALUES ('$id_session','$enreg_course','$enreg_user_id')"; + $result = Database::query($sql); if (Database::affected_rows($result)) { $nbr_users++; } } - Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'"); + Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE session_id='$id_session' AND c_id='$enreg_course'"); - $sql_directory = "SELECT directory FROM $tbl_course WHERE code = '$enreg_course'"; + $sql_directory = "SELECT directory FROM $tbl_course WHERE id = '$enreg_course'"; $res_directory = Database::query($sql_directory); $row_directory = Database::fetch_row($res_directory); $course_directory[] = $row_directory[0]; @@ -5096,7 +5120,11 @@ function WSSuscribeCoursesToSession($params) { $count_results = count($results); $output = array(); for ($i = 0; $i < $count_results; $i++) { - $output[] = array('original_course_id_values' => $orig_course_id_value[$i], 'original_session_id_value' => $orig_session_id_value[$i], 'result' => $results[$i]); + $output[] = array( + 'original_course_id_values' => $orig_course_id_value[$i], + 'original_session_id_value' => $orig_session_id_value[$i], + 'result' => $results[$i] + ); } return $output; } @@ -5220,12 +5248,15 @@ function WSUnsuscribeCoursesFromSession($params) { // Get courses list from row_original_course_id_values $course_list = array(); + $courseIdList = []; foreach ($original_course_id_values as $row_original_course_list) { $course_code = Database::escape_string($row_original_course_list['course_code']); - $sql_course = "SELECT course_code FROM $t_cf cf,$t_cfv cfv WHERE cfv.field_id=cf.id AND field_variable='$original_course_id_name' AND field_value = '$course_code'"; + $sql_course = "SELECT course_code FROM $t_cf cf,$t_cfv cfv + WHERE cfv.field_id=cf.id AND field_variable='$original_course_id_name' AND field_value = '$course_code'"; $res_course = Database::query($sql_course); $row_course = Database::fetch_row($res_course); + $courseId = null; if (empty($row_course[0])) { continue; // Course_code doesn't exist' } else { @@ -5235,8 +5266,10 @@ function WSUnsuscribeCoursesFromSession($params) { if (!empty($r_check_course[0])) { continue; // user_id is not active. } + $courseId = $row_course[0]; } $course_list[] = $row_course[0]; + $courseIdList[] = $courseId; } if (empty($course_list)) { @@ -5246,10 +5279,10 @@ function WSUnsuscribeCoursesFromSession($params) { $orig_course_id_value[] = implode(',', $course_list); - foreach ($course_list as $enreg_course) { - $enreg_course = Database::escape_string($enreg_course); - Database::query("DELETE FROM $tbl_session_rel_course WHERE course_code='$enreg_course' AND id_session='$id_session'"); - $result = Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE course_code='$enreg_course' AND id_session='$id_session'"); + foreach ($courseIdList as $courseId) { + $courseId = intval($courseId); + Database::query("DELETE FROM $tbl_session_rel_course WHERE c_id ='$courseId' AND session_id='$id_session'"); + $result = Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE c_id='$courseId' AND session_id = '$id_session'"); $return = Database::affected_rows($result); } diff --git a/main/work/work.lib.php b/main/work/work.lib.php index 4de34ffa8e..4c2b06aae8 100755 --- a/main/work/work.lib.php +++ b/main/work/work.lib.php @@ -2745,8 +2745,13 @@ function get_list_users_without_publication($task_id, $studentId = null) FROM $table_course_user AS cu, $table_user AS u WHERE u.status != 1 and cu.c_id='".api_get_course_int_id()."' AND u.user_id = cu.user_id"; } else { - $sql_users = "SELECT cu.id_user, u.lastname, u.firstname, u.email FROM $session_course_rel_user AS cu, $table_user AS u - WHERE u.status != 1 and cu.c_id='".api_get_course_int_id()."' AND u.user_id = cu.user_id and cu.session_id = '".$session_id."'"; + $sql_users = "SELECT cu.user_id, u.lastname, u.firstname, u.email + FROM $session_course_rel_user AS cu, $table_user AS u + WHERE + u.status != 1 AND + cu.c_id='".api_get_course_int_id()."' AND + u.user_id = cu.user_id AND + cu.session_id = '".$session_id."'"; } if (!empty($studentId)) { diff --git a/plugin/advanced_subscription/cron/notify_by_mail.php b/plugin/advanced_subscription/cron/notify_by_mail.php index 84446121ac..642c35fdcb 100644 --- a/plugin/advanced_subscription/cron/notify_by_mail.php +++ b/plugin/advanced_subscription/cron/notify_by_mail.php @@ -21,7 +21,7 @@ $sessionExtraFieldValue = new ExtraFieldValue('session'); $joinTables = Database::get_main_table(TABLE_MAIN_SESSION) . ' s INNER JOIN ' . Database::get_main_table(TABLE_MAIN_SESSION_USER) . ' su ON s.id = su.session_id INNER JOIN ' . Database::get_main_table(TABLE_MAIN_USER_REL_USER) . ' uu ON su.user_id = uu.user_id INNER JOIN ' . - Database::get_main_table(TABLE_ADVANCED_SUBSCRIPTION_QUEUE) . ' asq ON su.session_id = asq.session_id AND su.id_user = asq.user_id'; + Database::get_main_table(TABLE_ADVANCED_SUBSCRIPTION_QUEUE) . ' asq ON su.session_id = asq.session_id AND su.user_id = asq.user_id'; $columns = 's.id AS session_id, uu.friend_user_id AS superior_id, uu.user_id AS student_id, asq.id AS queue_id, asq.status AS status'; $conditions = array( 'where' => array( diff --git a/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php b/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php index 6bdb146bde..cfadc48d39 100644 --- a/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php +++ b/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php @@ -1317,13 +1317,15 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface $tSessionField = Database::get_main_table(TABLE_MAIN_SESSION_FIELD); $tSessionFieldValues = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES); $tSessionUser = Database::get_main_table(TABLE_MAIN_SESSION_USER); - $sql = "SELECT s.id FROM $tSession AS s " - . "INNER JOIN $tSessionFieldValues AS sfv ON s.id = sfv.session_id " - . "INNER JOIN $tSessionField AS sf ON sfv.field_id = sf.id " - . "INNER JOIN $tSessionUser AS su ON s.id = su.id_session " - . "WHERE sf.field_variable = 'is_induction_session' " - . "AND su.relation_type = 0 " - . "AND su.id_user = " . intval($userId); + + $sql = "SELECT s.id FROM $tSession AS s + INNER JOIN $tSessionFieldValues AS sfv ON s.id = sfv.session_id + INNER JOIN $tSessionField AS sf ON sfv.field_id = sf.id + INNER JOIN $tSessionUser AS su ON s.id = su.id_session + WHERE + sf.field_variable = 'is_induction_session' AND + su.relation_type = 0 AND + su.user_id = " . intval($userId); $result = Database::query($sql); diff --git a/plugin/buycourses/src/buy_course.lib.php b/plugin/buycourses/src/buy_course.lib.php index e85453fdd8..48da15614f 100644 --- a/plugin/buycourses/src/buy_course.lib.php +++ b/plugin/buycourses/src/buy_course.lib.php @@ -197,7 +197,7 @@ function userSessionList() if ($currentUserId > 0) { $sql = "SELECT 1 FROM $tableSessionRelUser WHERE id_session ='".$rowSession['session_id']."' AND - id_user = $currentUserId"; + user_id = $currentUserId"; $result = Database::query($sql); if (Database::affected_rows($result) > 0) { $rowSession['enrolled'] = "YES"; @@ -314,8 +314,8 @@ function checkUserBuy($parameter, $user, $type = 'COURSE') { $sql = "SELECT 1 FROM %s WHERE %s ='" . Database::escape_string($parameter) . "' AND %s ='" . intval($user) . "';"; $sql = $type === 'SESSION' ? - sprintf($sql, Database::get_main_table(TABLE_MAIN_SESSION_USER), 'id_session', 'id_user') : - sprintf($sql, Database::get_main_table(TABLE_MAIN_COURSE_USER), 'course_code', 'user_id'); + sprintf($sql, Database::get_main_table(TABLE_MAIN_SESSION_USER), 'session_id', 'user_id') : + sprintf($sql, Database::get_main_table(TABLE_MAIN_COURSE_USER), 'c_id', 'user_id'); $result = Database::query($sql); if (Database::affected_rows($result) > 0) { return true; @@ -524,13 +524,13 @@ function sessionInfo($code) //check if the user is enrolled in the current session if ($currentUserId > 0) { $sql = "SELECT 1 FROM $tableSessionRelUser - WHERE id_user = $currentUserId"; + WHERE user_id = $currentUserId"; $result = Database::query($sql); if (Database::affected_rows($result) > 0) { $rowSession['enrolled'] = "YES"; } else { $sql = "SELECT 1 FROM $tableBuySessionTemporal - WHERE user_id='".$currentUserId."';"; + WHERE user_id='".$currentUserId."';"; $result = Database::query($sql); if (Database::affected_rows($result) > 0) { $rowSession['enrolled'] = "TMP"; diff --git a/plugin/buycourses/src/function.php b/plugin/buycourses/src/function.php index d92fb5c59d..30e42ed547 100644 --- a/plugin/buycourses/src/function.php +++ b/plugin/buycourses/src/function.php @@ -119,15 +119,15 @@ if ($_REQUEST['tab'] == 'sessions_filter') { //check if the user is enrolled in the current session if (isset($_SESSION['_user']) || $_SESSION['_user']['user_id'] != '') { $sql = "SELECT 1 FROM $tableSessionRelUser - WHERE id_session='".$rowSession['session_id']."' AND - id_user ='" . $_SESSION['_user']['user_id'] . "';"; + WHERE session_id ='".$rowSession['session_id']."' AND + user_id ='" . api_get_user_id() . "'"; $result = Database::query($sql); if (Database::affected_rows($result) > 0) { $rowSession['enrolled'] = "YES"; } else { $sql = "SELECT 1 FROM $tableBuySessionTemporal WHERE session_id ='".$rowSession['session_id']."' AND - user_id='" . $_SESSION['_user']['user_id'] . "';"; + user_id='" . api_get_user_id() . "'"; $result = Database::query($sql); if (Database::affected_rows($result) > 0) { $rowSession['enrolled'] = "TMP"; @@ -138,7 +138,7 @@ if ($_REQUEST['tab'] == 'sessions_filter') { } else { $sql = "SELECT 1 FROM $tableBuySessionTemporal WHERE session_id ='".$rowSession['session_id']."' AND - user_id='" . $_SESSION['_user']['user_id'] . "';"; + user_id='" . api_get_user_id() . "'"; $result = Database::query($sql); if (Database::affected_rows($result) > 0) { $rowSession['enrolled'] = "TMP"; diff --git a/plugin/resubscription/src/HookResubscription.php b/plugin/resubscription/src/HookResubscription.php index e71b675fba..b7ae09ebd4 100644 --- a/plugin/resubscription/src/HookResubscription.php +++ b/plugin/resubscription/src/HookResubscription.php @@ -40,15 +40,15 @@ class HookResubscription extends HookObserver implements HookResubscribeObserver break; } - $join = " INNER JOIN ".Database::get_main_table(TABLE_MAIN_SESSION)."ON id = id_session"; + $join = " INNER JOIN ".Database::get_main_table(TABLE_MAIN_SESSION)."ON id = session_id"; // User sessions and courses $userSessions = Database::select( - 'id_session, date_end', + 'session_id, date_end', Database::get_main_table(TABLE_MAIN_SESSION_USER).$join, array( 'where' => array( - 'id_user = ? AND date_end >= ?' => array( + 'user_id = ? AND date_end >= ?' => array( api_get_user_id(), $limitDate ) @@ -63,15 +63,15 @@ class HookResubscription extends HookObserver implements HookResubscribeObserver Database::get_main_table(TABLE_MAIN_SESSION_COURSE), array( 'where' => array( - 'id_session = ?' => array( - $userSession['id_session'] + 'session_id = ?' => array( + $userSession['session_id'] ) ) ) ); foreach ($userSessionCourseResult as $userSessionCourse) { - if (!isset($userSessionCourses[$userSessionCourse['course_code']])) { - $userSessionCourses[$userSessionCourse['course_code']] = $userSession['date_end']; + if (!isset($userSessionCourses[$userSessionCourse['c_id']])) { + $userSessionCourses[$userSessionCourse['c_id']] = $userSession['date_end']; } } @@ -79,11 +79,11 @@ class HookResubscription extends HookObserver implements HookResubscribeObserver // Current session and courses $currentSessionCourseResult = Database::select( - 'course_code', + 'c_id', Database::get_main_table(TABLE_MAIN_SESSION_COURSE), array( 'where' => array( - 'id_session = ?' => array( + 'session_id = ?' => array( $data['session_id'] ) ) @@ -92,8 +92,8 @@ class HookResubscription extends HookObserver implements HookResubscribeObserver // Check if current course code matches with one of the users foreach ($currentSessionCourseResult as $currentSessionCourse) { - if (isset($userSessionCourses[$currentSessionCourse['course_code']])) { - $endDate = $userSessionCourses[$currentSessionCourse['course_code']]; + if (isset($userSessionCourses[$currentSessionCourse['c_id']])) { + $endDate = $userSessionCourses[$currentSessionCourse['c_id']]; $resubscriptionDate = gmdate('Y-m-d', strtotime($endDate." +$resubscriptionLimit")); $icon = Display::return_icon('students.gif', get_lang('Student')); $canResubscribeFrom = sprintf(get_plugin_lang('CanResubscribeFromX', 'resubscription'), $resubscriptionDate); diff --git a/tests/main/mySpace/myspace.lib.test.php b/tests/main/mySpace/myspace.lib.test.php index 3541e33ef4..8c356ab4c4 100755 --- a/tests/main/mySpace/myspace.lib.test.php +++ b/tests/main/mySpace/myspace.lib.test.php @@ -136,7 +136,7 @@ class TestMySpaceLib extends UnitTestCase { public function testGetUserCreator() { //ob_start(); - $res = MySpace::get_user_creator($users = array(), $course_list = array(), $id_session = 1); + $res = MySpace::get_user_creator($users = array()); $this->assertTrue(is_array($res)); //ob_end_clean(); //var_dump($res); diff --git a/tests/scripts/detect_deleted_visible_documents.php b/tests/scripts/detect_deleted_visible_documents.php index fb31b09c4c..18f6e764bc 100644 --- a/tests/scripts/detect_deleted_visible_documents.php +++ b/tests/scripts/detect_deleted_visible_documents.php @@ -35,7 +35,7 @@ if (!empty($docs)) { SET visibility = 2 WHERE c_id = $courseId AND - id_session = $sessionId AND + session_id = $sessionId AND ref = $ref AND tool = 'document' "; diff --git a/whoisonlinesession.php b/whoisonlinesession.php index 54bf14d80f..9d361a6c8e 100755 --- a/whoisonlinesession.php +++ b/whoisonlinesession.php @@ -53,7 +53,7 @@ Display::display_header(get_lang('UserOnlineListSession')); date_end FROM $tbl_session as session INNER JOIN $tbl_session_course_user as srcru - ON srcru.id_user = ".$_user['user_id']." AND srcru.status=2 + ON srcru.user_id = ".$_user['user_id']." AND srcru.status=2 AND session.id = srcru.session_id ORDER BY date_start, date_end, name"; $result = Database::query($sql); From 8406c1e1a854c7121dedf25ac8c5d0fa25d331d1 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 9 Apr 2015 15:02:20 +0200 Subject: [PATCH 071/159] Replace id_session with session_id. --- main/admin/add_courses_to_session.php | 14 ++++---- main/admin/add_users_to_session.php | 2 +- main/admin/resume_session.php | 4 +-- main/admin/session_course_edit.php | 16 +++++----- main/admin/session_course_list.php | 20 ++++++++---- main/forum/forumfunction.inc.php | 12 +++++-- main/forum/viewthread_flat.inc.php | 22 +++++++++---- main/inc/lib/AnnouncementManager.php | 46 ++++++++++++++------------- main/inc/lib/course_home.lib.php | 27 +++++++++------- main/inc/lib/document.lib.php | 7 ++-- main/inc/lib/glossary.lib.php | 17 +++++----- main/inc/lib/link.lib.php | 4 +-- main/inc/lib/sessionmanager.lib.php | 9 ++++-- 13 files changed, 115 insertions(+), 85 deletions(-) diff --git a/main/admin/add_courses_to_session.php b/main/admin/add_courses_to_session.php index 216a7f3152..b6b6e52a9f 100755 --- a/main/admin/add_courses_to_session.php +++ b/main/admin/add_courses_to_session.php @@ -172,13 +172,14 @@ if ($ajax_search) { $result = Database::query($sql); $Courses = Database::store_result($result); foreach ($Courses as $course) { - if ($course['id_session'] == $sessionId) { + if ($course['session_id'] == $sessionId) { $sessionCourses[$course['id']] = $course ; } else { $nosessionCourses[$course['id']] = $course ; } } } + unset($Courses); ?>
      > @@ -202,16 +203,13 @@ unset($Courses); } else { ?>
      - + - + +
      ".SESSION_RELATION_TYPE_RRHH." AND srcru.session_id = '".intval($sessionId)."'"; @@ -323,7 +323,7 @@ if ($session['nbr_courses'] == 0) { // Get coachs of the courses in session - $sql = "SELECT user.lastname,user.firstname, user.username + $sql = "SELECT user.lastname, user.firstname, user.username FROM $tbl_session_rel_course_rel_user session_rcru, $tbl_user user WHERE session_rcru.user_id = user.user_id AND diff --git a/main/admin/session_course_edit.php b/main/admin/session_course_edit.php index 2ee0eed6c8..7b6911a503 100755 --- a/main/admin/session_course_edit.php +++ b/main/admin/session_course_edit.php @@ -12,21 +12,21 @@ $id_session = intval($_GET['id_session']); SessionManager::protect_session_edit($id_session); $course_code = $_GET['course_code']; -$formSent=0; -$errorMsg=''; +$formSent = 0; +$errorMsg = ''; // Database Table Definitions -$tbl_user = Database::get_main_table(TABLE_MAIN_USER); -$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE); -$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION); -$tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE); +$tbl_user = Database::get_main_table(TABLE_MAIN_USER); +$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE); +$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION); +$tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE); $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $course_info = api_get_course_info($_REQUEST['course_code']); -$courseId = $course_info['id']; +$courseId = $course_info['real_id']; $tool_name = $course_info['name']; $sql = "SELECT s.name, c.title - FROM $tbl_session_course sc,$tbl_session s,$tbl_course c + FROM $tbl_session_course sc, $tbl_session s,$tbl_course c WHERE sc.session_id=s.id AND sc.c_id = c.id AND diff --git a/main/admin/session_course_list.php b/main/admin/session_course_list.php index 34613f6e47..cd760062be 100755 --- a/main/admin/session_course_list.php +++ b/main/admin/session_course_list.php @@ -55,9 +55,11 @@ if ($action == 'delete') { $limit = 20; $from = $page * $limit; -$sql = "SELECT code, title, nbr_users FROM $tbl_session_rel_course, $tbl_course - WHERE c_id = id AND session_id='$id_session' - ORDER BY $sort LIMIT $from,".($limit+1); +$sql = "SELECT c.id, c.code, c.title, nbr_users + FROM $tbl_session_rel_course, $tbl_course c + WHERE c_id = c.id AND session_id='$id_session' + ORDER BY $sort + LIMIT $from,".($limit+1); $result=Database::query($sql); $Courses=Database::store_result($result); $tool_name = api_htmlentities($session_name,ENT_QUOTES,$charset).' : '.get_lang('CourseListInSession'); @@ -78,14 +80,18 @@ $tableHeader[] = array(get_lang('NbUsers')); $tableHeader[] = array(get_lang('Actions')); $tableCourses = array(); -foreach($Courses as $key=>$enreg) { + +foreach ($Courses as $key=>$enreg) { $course = array(); $course[] = ''; $course[] = api_htmlentities($enreg['title'],ENT_QUOTES,$charset); $course[] = ''.$enreg['nbr_users'].' '.get_lang('Users').''; - $course[] = ''.Display::return_icon('course_home.gif', get_lang('Course')).' - '.Display::return_icon('edit.gif', get_lang('Edit')).' - '.Display::return_icon('delete.gif', get_lang('Delete')).''; + $course[] = ''. + Display::return_icon('course_home.gif', get_lang('Course')).' + '. + Display::return_icon('edit.png', get_lang('Edit')).' + '. + Display::return_icon('delete.png', get_lang('Delete')).''; $tableCourses[] = $course; } echo ''; diff --git a/main/forum/forumfunction.inc.php b/main/forum/forumfunction.inc.php index f731b179dc..40afe1daa1 100755 --- a/main/forum/forumfunction.inc.php +++ b/main/forum/forumfunction.inc.php @@ -1239,7 +1239,7 @@ function get_forum_categories($id = '') $session_id = api_get_session_id(); $course_id = api_get_course_int_id(); - $condition_session = api_get_session_condition($session_id, true, true); + $condition_session = api_get_session_condition($session_id, true, true, 'forum_categories.session_id'); $condition_session .= " AND forum_categories.c_id = $course_id AND item_properties.c_id = $course_id"; if (empty($id)) { @@ -1368,7 +1368,7 @@ function get_forums( $session_id = $sessionId; } - $condition_session = api_get_session_condition($session_id, true, false, 'id_session'); + $condition_session = api_get_session_condition($session_id, true, false, 'item_properties.session_id'); $course_id = $course_info['real_id']; $forum_list = array(); @@ -1512,7 +1512,13 @@ function get_forums( // Select the last post and the poster (note: this is probably no longer needed). $sql4 = "SELECT - post.post_id, post.forum_id, post.poster_id, post.poster_name, post.post_date, users.lastname, users.firstname + post.post_id, + post.forum_id, + post.poster_id, + post.poster_name, + post.post_date, + users.lastname, + users.firstname FROM $table_posts post, $table_users users WHERE forum_id = ".intval($id)." AND diff --git a/main/forum/viewthread_flat.inc.php b/main/forum/viewthread_flat.inc.php index 79c6b2b910..5e0de98e97 100755 --- a/main/forum/viewthread_flat.inc.php +++ b/main/forum/viewthread_flat.inc.php @@ -56,7 +56,11 @@ if (isset($current_thread['thread_id'])) { $id_attach = !empty($attachment_list)?$attachment_list['id']:''; // The user who posted it can edit his thread only if the course admin allowed this in the properties of the forum // The course admin him/herself can do this off course always - if ( GroupManager::is_tutor_of_group(api_get_user_id(), $group_id) OR ($current_forum['allow_edit']==1 AND $row['user_id']==$_user['user_id']) or (api_is_allowed_to_edit(false,true) && !(api_is_course_coach() && $current_forum['session_id']!=$_SESSION['id_session']))) { + if ( + GroupManager::is_tutor_of_group(api_get_user_id(), $group_id) || + ($current_forum['allow_edit']==1 AND $row['user_id']==$_user['user_id']) || + (api_is_allowed_to_edit(false,true) && !(api_is_course_coach() && $current_forum['session_id']!=$_SESSION['id_session'])) + ) { if (api_is_allowed_to_session_edit(false,true)) { if ($locked == false) { echo "".Display::return_icon('edit.png',get_lang('Edit'), array(), ICON_SIZE_SMALL).""; @@ -65,7 +69,7 @@ if (isset($current_thread['thread_id'])) { } if ($origin != 'learnpath') { - if (GroupManager::is_tutor_of_group(api_get_user_id(), $group_id) OR api_is_allowed_to_edit(false,true) && !(api_is_course_coach() && $current_forum['session_id']!=$_SESSION['id_session'])) { + if (GroupManager::is_tutor_of_group(api_get_user_id(), $group_id) || api_is_allowed_to_edit(false,true) && !(api_is_course_coach() && $current_forum['session_id']!=$_SESSION['id_session'])) { if ($locked == false) { echo "".Display::return_icon('delete.png', get_lang('Delete'),array(), ICON_SIZE_SMALL).""; } @@ -94,8 +98,10 @@ if (isset($current_thread['thread_id'])) { } } - if (($current_forum_category && $current_forum_category['locked']==0) AND $current_forum['locked']==0 AND $current_thread['locked']==0 OR api_is_allowed_to_edit(false,true)) { - if ($_user['user_id'] OR ($current_forum['allow_anonymous']==1 AND !$_user['user_id'])) { + if (($current_forum_category && $current_forum_category['locked']==0) && + $current_forum['locked']==0 && $current_thread['locked']==0 || api_is_allowed_to_edit(false,true) + ) { + if ($_user['user_id'] || ($current_forum['allow_anonymous']==1 && !$_user['user_id'])) { if (!api_is_anonymous() && api_is_allowed_to_session_edit(false,true)) { echo ''.Display :: return_icon('message_reply_forum.png', get_lang('ReplyToMessage')).""; echo ''.Display :: return_icon('quote.gif', get_lang('QuoteMessage')).""; @@ -114,12 +120,12 @@ if (isset($current_thread['thread_id'])) { } echo ""; // prepare the notification icon - if (isset($whatsnew_post_info[$current_forum['forum_id']][$current_thread['thread_id']][$row['post_id']]) and !empty($whatsnew_post_info[$current_forum['forum_id']][$current_thread['thread_id']][$row['post_id']]) and !empty($whatsnew_post_info[$_GET['forum']][$row['thread_id']])) { + if (isset($whatsnew_post_info[$current_forum['forum_id']][$current_thread['thread_id']][$row['post_id']]) && !empty($whatsnew_post_info[$current_forum['forum_id']][$current_thread['thread_id']][$row['post_id']]) and !empty($whatsnew_post_info[$_GET['forum']][$row['thread_id']])) { $post_image=Display::return_icon('forumpostnew.gif'); } else { $post_image=Display::return_icon('forumpost.gif'); } - if ($row['post_notification']=='1' AND $row['poster_id']==$_user['user_id']) { + if ($row['post_notification']=='1' && $row['poster_id']==$_user['user_id']) { $post_image.=Display::return_icon('forumnotification.gif',get_lang('YouWillBeNotified')); } // The post title @@ -151,7 +157,9 @@ if (isset($current_thread['thread_id'])) { echo Display::return_icon('attachment.gif',get_lang('Attachment')); echo ' '.$user_filename.' '; - if (($current_forum['allow_edit']==1 AND $row['user_id']==$_user['user_id']) or (api_is_allowed_to_edit(false,true) && !(api_is_course_coach() && $current_forum['session_id']!=$_SESSION['id_session']))) { + if (($current_forum['allow_edit']==1 && $row['user_id']==$_user['user_id']) || + (api_is_allowed_to_edit(false,true) && !(api_is_course_coach() && $current_forum['session_id']!=$_SESSION['id_session'])) + ) { echo '  '.Display::return_icon('delete.png',get_lang('Delete'), array(), ICON_SIZE_SMALL).'
      '; } echo ''.$attachment['comment'].''; diff --git a/main/inc/lib/AnnouncementManager.php b/main/inc/lib/AnnouncementManager.php index 2fbd551858..21ebb9b20b 100755 --- a/main/inc/lib/AnnouncementManager.php +++ b/main/inc/lib/AnnouncementManager.php @@ -1284,7 +1284,7 @@ class AnnouncementManager $user_id = api_get_user_id(); $group_id = api_get_group_id(); $session_id = api_get_session_id(); - $condition_session = api_get_session_condition($session_id, true, true); + $condition_session = api_get_session_condition($session_id, true, true, 'announcement.session_id'); $course_id = api_get_course_int_id(); $_course = api_get_course_info(); @@ -1606,7 +1606,7 @@ class AnnouncementManager $_course = api_get_course_info(); $session_id = api_get_session_id(); $userId = api_get_user_id(); - $condition_session = api_get_session_condition($session_id, true, true); + $condition_session = api_get_session_condition($session_id, true, true, 'announcement.session_id'); if (api_is_allowed_to_edit(false,true)) { // check teacher status @@ -1619,13 +1619,14 @@ class AnnouncementManager } $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id FROM $tbl_announcement announcement, $tbl_item_property ip - WHERE announcement.c_id = $course_id AND - ip.c_id = $course_id AND - announcement.id = ip.ref AND - ip.tool = 'announcement' AND - ip.visibility <> '2' - $group_condition - $condition_session + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref AND + ip.tool = 'announcement' AND + ip.visibility <> '2' + $group_condition + $condition_session GROUP BY ip.ref ORDER BY display_order DESC LIMIT 0,$maximum"; @@ -1642,7 +1643,7 @@ class AnnouncementManager "OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))) "; } else { $cond_user_id = " AND (ip.lastedit_user_id = '".$userId."' - OR ip.to_group_id IN (0, ".api_get_group_id()."))"; + OR ip.to_group_id IN (0, ".api_get_group_id()."))"; } } else { if (api_get_group_id() == 0) { @@ -1701,24 +1702,25 @@ class AnnouncementManager // the user is not identiefied => show only the general announcements $sql="SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id - FROM $tbl_announcement announcement, $tbl_item_property ip - WHERE - announcement.c_id = $course_id AND - ip.c_id = $course_id AND - announcement.id = ip.ref - AND ip.tool='announcement' - AND ip.visibility='1' - AND ip.to_group_id='0' - $condition_session - GROUP BY ip.ref - ORDER BY display_order DESC - LIMIT 0,$maximum"; + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref + AND ip.tool='announcement' + AND ip.visibility='1' + AND ip.to_group_id='0' + $condition_session + GROUP BY ip.ref + ORDER BY display_order DESC + LIMIT 0,$maximum"; } } } } $result = Database::query($sql); + return Database::num_rows($result); } } diff --git a/main/inc/lib/course_home.lib.php b/main/inc/lib/course_home.lib.php index 1abaffc23c..d6469653f9 100755 --- a/main/inc/lib/course_home.lib.php +++ b/main/inc/lib/course_home.lib.php @@ -443,7 +443,7 @@ class CourseHome // Condition for the session $session_id = api_get_session_id(); $course_id = api_get_course_int_id(); - $condition_session = api_get_session_condition($session_id, true, true); + $condition_session = api_get_session_condition($session_id, true, true, 't.session_id'); switch ($course_tool_category) { case TOOL_STUDENT_VIEW: @@ -452,37 +452,38 @@ class CourseHome $condition_display_tools = ' WHERE (visibility = 1 AND (category = "authoring" OR category = "interaction" OR category = "plugin") OR (name = "'.TOOL_TRACKING.'") ) '; } $sql = "SELECT * - FROM $course_tool_table + FROM $course_tool_table t $condition_display_tools AND c_id = $course_id $condition_session ORDER BY id"; $result = Database::query($sql); break; case TOOL_AUTHORING: - $sql = "SELECT * FROM $course_tool_table + $sql = "SELECT * FROM $course_tool_table t WHERE category = 'authoring' AND c_id = $course_id $condition_session ORDER BY id"; $result = Database::query($sql); break; case TOOL_INTERACTION: - $sql = "SELECT * FROM $course_tool_table + $sql = "SELECT * FROM $course_tool_table t WHERE category = 'interaction' AND c_id = $course_id $condition_session ORDER BY id"; $result = Database::query($sql); break; case TOOL_ADMIN_VISIBLE: - $sql = "SELECT * FROM $course_tool_table + $sql = "SELECT * FROM $course_tool_table t WHERE category = 'admin' AND visibility ='1' AND c_id = $course_id $condition_session ORDER BY id"; $result = Database::query($sql); break; case TOOL_ADMIN_PLATFORM: - $sql = "SELECT * FROM $course_tool_table - WHERE category = 'admin' AND c_id = $course_id $condition_session ORDER BY id"; + $sql = "SELECT * FROM $course_tool_table t + WHERE category = 'admin' AND c_id = $course_id $condition_session + ORDER BY id"; $result = Database::query($sql); break; case TOOL_DRH: - $sql = "SELECT * FROM $course_tool_table + $sql = "SELECT * FROM $course_tool_table t WHERE name IN ('tracking') AND c_id = $course_id $condition_session ORDER BY id"; $result = Database::query($sql); @@ -490,7 +491,7 @@ class CourseHome case TOOL_COURSE_PLUGIN: //Other queries recover id, name, link, image, visibility, admin, address, added_tool, target, category and session_id // but plugins are not present in the tool table, only globally and inside the course_settings table once configured - $sql = "SELECT * FROM $course_tool_table + $sql = "SELECT * FROM $course_tool_table t WHERE category = 'plugin' AND c_id = $course_id $condition_session ORDER BY id"; $result = Database::query($sql); @@ -553,6 +554,8 @@ class CourseHome $course_link_table = Database::get_course_table(TABLE_LINK); $course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY); + $condition_session = api_get_session_condition($session_id, true, true, 'tip.session_id'); + switch ($course_tool_category) { case TOOL_AUTHORING: $sql_links = "SELECT tl.*, tip.visibility @@ -576,7 +579,8 @@ class CourseHome case TOOL_STUDENT_VIEW: $sql_links = "SELECT tl.*, tip.visibility FROM $course_link_table tl - LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id + LEFT JOIN $course_item_property_table tip + ON tip.tool='link' AND tip.ref=tl.id WHERE tl.c_id = $course_id AND tip.c_id = $course_id AND @@ -585,7 +589,8 @@ class CourseHome case TOOL_ADMIN: $sql_links = "SELECT tl.*, tip.visibility FROM $course_link_table tl - LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id + LEFT JOIN $course_item_property_table tip + ON tip.tool='link' AND tip.ref=tl.id WHERE tl.c_id = $course_id AND tip.c_id = $course_id AND diff --git a/main/inc/lib/document.lib.php b/main/inc/lib/document.lib.php index ce0104f584..32904c8e6e 100755 --- a/main/inc/lib/document.lib.php +++ b/main/inc/lib/document.lib.php @@ -541,7 +541,7 @@ class DocumentManager // Condition for the session $sessionId = api_get_session_id(); - $condition_session = " AND (id_session = '$sessionId' OR (id_session = '0') )"; + $condition_session = " AND (last.session_id = '$sessionId' OR (last.session_id = '0') )"; $condition_session .= self::getSessionFolderFilters($originalPath, $sessionId); $sharedCondition = null; @@ -739,7 +739,7 @@ class DocumentManager if ($can_see_invisible) { // condition for the session $session_id = api_get_session_id(); - $condition_session = api_get_session_condition($session_id); + $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id'); $show_users_condition = ""; if (api_get_setting('show_users_folders') == 'false') { $show_users_condition = " AND docs.path NOT LIKE '%shared_folder%'"; @@ -760,7 +760,8 @@ class DocumentManager last.to_group_id = " . $to_group_id . " AND docs.path NOT LIKE '%shared_folder%' AND docs.path NOT LIKE '%_DELETED_%' AND - last.visibility <> 2 $condition_session "; + last.visibility <> 2 + $condition_session "; } else { $sql = "SELECT DISTINCT docs.id, path FROM $TABLE_ITEMPROPERTY AS last diff --git a/main/inc/lib/glossary.lib.php b/main/inc/lib/glossary.lib.php index 779a33ceac..2cf7320069 100755 --- a/main/inc/lib/glossary.lib.php +++ b/main/inc/lib/glossary.lib.php @@ -422,23 +422,24 @@ class GlossaryManager //condition for the session $session_id = api_get_session_id(); - $condition_session = api_get_session_condition($session_id, true, true); + $condition_session = api_get_session_condition($session_id, true, true, 'glossary.session_id'); $column = intval($column); if (!in_array($direction,array('DESC', 'ASC'))) { $direction = 'ASC'; } - $from = intval($from); - $number_of_items = intval($number_of_items); + $from = intval($from); + $number_of_items = intval($number_of_items); $sql = "SELECT glossary.name as col0, glossary.description as col1, $col2 - glossary.session_id as session_id + glossary.session_id FROM $t_glossary glossary, $t_item_propery ip - WHERE glossary.glossary_id = ip.ref AND - tool = '".TOOL_GLOSSARY."' $condition_session AND - glossary.c_id = ".api_get_course_int_id()." AND - ip.c_id = ".api_get_course_int_id()." + WHERE + glossary.glossary_id = ip.ref AND + tool = '".TOOL_GLOSSARY."' $condition_session AND + glossary.c_id = ".api_get_course_int_id()." AND + ip.c_id = ".api_get_course_int_id()." ORDER BY col$column $direction LIMIT $from,$number_of_items"; $res = Database::query($sql); diff --git a/main/inc/lib/link.lib.php b/main/inc/lib/link.lib.php index 729c4670ae..0ce6118ea4 100755 --- a/main/inc/lib/link.lib.php +++ b/main/inc/lib/link.lib.php @@ -790,7 +790,7 @@ class Link extends Model $tblItemProperty = Database:: get_course_table(TABLE_ITEM_PROPERTY); $courseId = intval($courseId); // Condition for the session. - $sessionCondition = api_get_session_condition($sessionId, true, true); + $sessionCondition = api_get_session_condition($sessionId, true, true, 'linkcat.session_id'); // Getting links $sql = "SELECT *, linkcat.id @@ -859,7 +859,7 @@ class Link extends Model // Condition for the session. $session_id = api_get_session_id(); - $condition_session = api_get_session_condition($session_id, true, true); + $condition_session = api_get_session_condition($session_id, true, true, 'link.session_id'); $catid = intval($catid); $course_id = api_get_course_int_id(); diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php index 33069bacf5..6298f12853 100755 --- a/main/inc/lib/sessionmanager.lib.php +++ b/main/inc/lib/sessionmanager.lib.php @@ -1445,7 +1445,9 @@ class SessionManager $values['id_coach'] = $id_coach; $values['nb_days_access_before_beginning'] = $nb_days_acess_before; $values['nb_days_access_after_end'] = $nb_days_acess_after; - $values['session_category_id'] = $id_session_category; + if (!empty($id_session_category)) { + $values['session_category_id'] = $id_session_category; + } $values['description'] = $description; $values['show_description'] = intval($showDescription); $values['visibility'] = $id_visibility; @@ -2048,11 +2050,11 @@ class SessionManager $courseInfo = api_get_course_info($existingCourse['c_id']); $sql = "DELETE FROM $tbl_session_rel_course - WHERE c_id = '" . $existingCourse['c_id'] . "' AND session_id=$sessionId"; + WHERE c_id = '" . $existingCourse['c_id'] . "' AND session_id = $sessionId"; Database::query($sql); $sql = "DELETE FROM $tbl_session_rel_course_rel_user - WHERE c_id = '" . $existingCourse['c_id'] . "' AND session_id=$sessionId"; + WHERE c_id = '" . $existingCourse['c_id'] . "' AND session_id = $sessionId"; Database::query($sql); CourseManager::remove_course_ranking( @@ -2108,6 +2110,7 @@ class SessionManager SET nbr_courses = $nbr_courses WHERE id = '$sessionId'"; Database::query($sql); + exit; } /** From b0f7a0c9931e7067a78789253c3abfc07bc68185 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 9 Apr 2015 15:02:44 +0200 Subject: [PATCH 072/159] Remove course.db_name calls. --- main/inc/lib/auth.lib.php | 24 ++++++++++++------- main/inc/lib/usermanager.lib.php | 22 ++++++++--------- main/inc/lib/userportal.lib.php | 2 -- .../lib/search_course_widget.class.php | 9 ++++--- 4 files changed, 31 insertions(+), 26 deletions(-) diff --git a/main/inc/lib/auth.lib.php b/main/inc/lib/auth.lib.php index cd84bb388a..e9f60c2505 100755 --- a/main/inc/lib/auth.lib.php +++ b/main/inc/lib/auth.lib.php @@ -54,20 +54,28 @@ class Auth // Secondly we select the courses that are in a category (user_course_cat<>0) and sort these according to the sort of the category $user_id = intval($user_id); - $sql = "SELECT course.code k, course.visual_code vc, course.subscribe subscr, course.unsubscribe unsubscr, - course.title i, course.tutor_name t, course.db_name db, course.directory dir, course_rel_user.status status, - course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat + $sql = "SELECT + course.code k, + course.visual_code vc, + course.subscribe subscr, + course.unsubscribe unsubscr, + course.title i, + course.tutor_name t, + course.directory dir, + course_rel_user.status status, + course_rel_user.sort sort, + course_rel_user.user_course_cat user_course_cat FROM $TABLECOURS course, $TABLECOURSUSER course_rel_user - WHERE course.id = course_rel_user.c_id - AND course_rel_user.relation_type<>" . COURSE_RELATION_TYPE_RRHH . " - AND course_rel_user.user_id = '" . $user_id . "' $without_special_courses + WHERE + course.id = course_rel_user.c_id AND + course_rel_user.relation_type<>" . COURSE_RELATION_TYPE_RRHH . " AND + course_rel_user.user_id = '" . $user_id . "' $without_special_courses ORDER BY course_rel_user.sort ASC"; $result = Database::query($sql); $courses = array(); while ($row = Database::fetch_array($result)) { //we only need the database name of the course $courses[] = array( - 'db' => $row['db'], 'code' => $row['k'], 'visual_code' => $row['vc'], 'title' => $row['i'], @@ -139,7 +147,7 @@ class Auth $sql = "SELECT course.code, course.visual_code, course.subscribe subscr, course.unsubscribe unsubscr, - course.title title, course.tutor_name tutor, course.db_name, course.directory, course_rel_user.status status, + course.title title, course.tutor_name tutor, course.directory, course_rel_user.status status, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat FROM $TABLECOURS course, $TABLECOURSUSER course_rel_user diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php index fbc5a2f419..90d14a98ca 100755 --- a/main/inc/lib/usermanager.lib.php +++ b/main/inc/lib/usermanager.lib.php @@ -3999,17 +3999,17 @@ class UserManager $course_list = array(); if (!empty($code_special_courses)) { - $course_list_sql = "SELECT course.code k, course.directory d, course.visual_code c, course.db_name db, course.title i, course.tutor_name t, course.course_language l, course_rel_user.status s, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat - FROM ".$tbl_course_user." course_rel_user - LEFT JOIN ".$tbl_course." course - ON course.id = course_rel_user.c_id - LEFT JOIN ".$tbl_user_course_category." user_course_category - ON course_rel_user.user_course_cat = user_course_category.id - $join_access_url - WHERE $code_special_courses $where_access_url - GROUP BY course.code - ORDER BY user_course_category.sort,course.title,course_rel_user.sort ASC"; - $course_list_sql_result = Database::query($course_list_sql); + $sql = "SELECT course.code k, course.directory d, course.visual_code c, course.title i, course.tutor_name t, course.course_language l, course_rel_user.status s, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat + FROM ".$tbl_course_user." course_rel_user + LEFT JOIN ".$tbl_course." course + ON course.id = course_rel_user.c_id + LEFT JOIN ".$tbl_user_course_category." user_course_category + ON course_rel_user.user_course_cat = user_course_category.id + $join_access_url + WHERE $code_special_courses $where_access_url + GROUP BY course.code + ORDER BY user_course_category.sort,course.title,course_rel_user.sort ASC"; + $course_list_sql_result = Database::query($sql); while ($result_row = Database::fetch_array($course_list_sql_result)) { $course_list[] = $result_row; } diff --git a/main/inc/lib/userportal.lib.php b/main/inc/lib/userportal.lib.php index c47e314006..ced1db24c8 100755 --- a/main/inc/lib/userportal.lib.php +++ b/main/inc/lib/userportal.lib.php @@ -668,7 +668,6 @@ class IndexManager course.unsubscribe unsubscr, course.title i, course.tutor_name t, - course.db_name db, course.directory dir, course_rel_user.status status, course_rel_user.sort sort, @@ -686,7 +685,6 @@ class IndexManager while ($row = Database::fetch_array($result)) { // We only need the database name of the course. $courses[$row['k']] = array( - 'db' => $row['db'], 'code' => $row['k'], 'visual_code' => $row['vc'], 'title' => $row['i'], diff --git a/plugin/search_course/lib/search_course_widget.class.php b/plugin/search_course/lib/search_course_widget.class.php index 590e796302..bba3d9ca71 100755 --- a/plugin/search_course/lib/search_course_widget.class.php +++ b/plugin/search_course/lib/search_course_widget.class.php @@ -390,19 +390,17 @@ EOT; $user_id = intval($user_id); $sql_select_courses = "SELECT course.code k, course.visual_code vc, course.subscribe subscr, course.unsubscribe unsubscr, - course.title i, course.tutor_name t, course.db_name db, course.directory dir, course_rel_user.status status, + course.title i, course.tutor_name t, course.directory dir, course_rel_user.status status, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat FROM $course_table course, $user_course_table course_rel_user WHERE course.id = course_rel_user.c_id AND course_rel_user.user_id = $user_id ORDER BY course_rel_user.sort ASC"; $result = array(); - $resultset = api_sql_query($sql_select_courses, __FILE__, __LINE__); - while ($row = Database::fetch_array($resultset)) - { + $resultset = api_sql_query($sql_select_courses); + while ($row = Database::fetch_array($resultset)) { $code = $row['k']; $result[$code] = array( - 'db' => $row['db'], 'code' => $code, 'visual_code' => $row['vc'], 'title' => $row['i'], @@ -414,6 +412,7 @@ EOT; 'sort' => $row['sort'], 'user_course_category' => $row['user_course_cat']); } + return $result; } From 15be99a991423917b8aea74c1ca1a26a6a336d67 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 9 Apr 2015 15:18:05 +0200 Subject: [PATCH 073/159] Fix queries. --- main/inc/lib/course.lib.php | 14 +++++++------- main/inc/lib/document.lib.php | 9 +++++---- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php index 3d575e6f58..b37c81b434 100755 --- a/main/inc/lib/course.lib.php +++ b/main/inc/lib/course.lib.php @@ -1276,20 +1276,20 @@ class CourseManager $sessionCondition = " session_course_user.session_id IN ('$sessionIdListTostring') "; } - $courseCondition = " course.code = '".$course_code."' AND "; + $courseCondition = " course.code = '".$course_code."' "; if (!empty($courseCodeList)) { $courseCodeListForSession = array_map(array('Database', 'escape_string'), $courseCodeList); $courseCodeListForSession = implode('","', $courseCodeListForSession); - $courseCondition = ' course.code IN ("' . $courseCodeListForSession . '") AND '; + $courseCondition = ' course.code IN ("' . $courseCodeListForSession . '") '; } $sql .= ' FROM ' . Database::get_main_table(TABLE_MAIN_USER) . ' as user '; $sql .= " LEFT JOIN ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " as session_course_user ON user.user_id = session_course_user.user_id AND - $courseCondition $sessionCondition - INNER JOIN $course_table course ON session_course_user.c_id = course.id + INNER JOIN $course_table course ON session_course_user.c_id = course.id AND + $courseCondition INNER JOIN $sessionTable session ON session_course_user.session_id = session.id "; $where[] = ' session_course_user.c_id IS NOT NULL '; @@ -1330,10 +1330,10 @@ class CourseManager $sql .= ' LEFT JOIN ' . Database::get_main_table(TABLE_MAIN_COURSE_USER) . ' as course_rel_user ON user.user_id = course_rel_user.user_id AND course_rel_user.relation_type <> ' . COURSE_RELATION_TYPE_RRHH . ' '; + $sql .= " INNER JOIN $course_table course ON course_rel_user.c_id = course.id "; + if (!empty($course_code)) { $sql .= ' AND course_rel_user.c_id="' . $courseId . '"'; - } else { - $sql .= " INNER JOIN $course_table course ON course_rel_user.c_id = course.id "; } $where[] = ' course_rel_user.c_id IS NOT NULL '; @@ -4939,7 +4939,7 @@ class CourseManager } } if (!empty($accessUrlId) && $accessUrlId == intval($accessUrlId)) { - $sql = "SELECT count(id) FROM $tableCourse c, $tableCourseRelAccessUrl u + $sql = "SELECT count(c.id) FROM $tableCourse c, $tableCourseRelAccessUrl u WHERE c.id = u.c_id AND u.access_url_id = $accessUrlId AND diff --git a/main/inc/lib/document.lib.php b/main/inc/lib/document.lib.php index 32904c8e6e..7569360600 100755 --- a/main/inc/lib/document.lib.php +++ b/main/inc/lib/document.lib.php @@ -807,7 +807,7 @@ class DocumentManager // No invisible folders // Condition for the session $session_id = api_get_session_id(); - $condition_session = api_get_session_condition($session_id); + $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id'); //get visible folders $sql = "SELECT DISTINCT docs.id, path FROM @@ -817,7 +817,8 @@ class DocumentManager docs.filetype = 'folder' AND last.tool = '" . TOOL_DOCUMENT . "' AND last.to_group_id = " . $to_group_id . " AND - last.visibility = 1 $condition_session AND + last.visibility = 1 + $condition_session AND last.c_id = {$_course['real_id']} AND docs.c_id = {$_course['real_id']} "; $result = Database::query($sql); @@ -828,7 +829,7 @@ class DocumentManager // Condition for the session $session_id = api_get_session_id(); - $condition_session = api_get_session_condition($session_id); + $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id'); //get invisible folders $sql = "SELECT DISTINCT docs.id, path FROM $TABLE_ITEMPROPERTY AS last, $TABLE_DOCUMENT AS docs @@ -845,7 +846,7 @@ class DocumentManager while ($row = Database::fetch_array($result, 'ASSOC')) { //condition for the session $session_id = api_get_session_id(); - $condition_session = api_get_session_condition($session_id); + $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id'); //get visible folders in the invisible ones -> they are invisible too $sql = "SELECT DISTINCT docs.id, path FROM $TABLE_ITEMPROPERTY AS last, $TABLE_DOCUMENT AS docs From f46b72ddd80a607d1c4acb52c50939637d32014b Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 9 Apr 2015 16:30:10 +0200 Subject: [PATCH 074/159] Minor - fix query. --- main/inc/lib/course.lib.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php index b37c81b434..5b9128c168 100755 --- a/main/inc/lib/course.lib.php +++ b/main/inc/lib/course.lib.php @@ -1801,7 +1801,7 @@ class CourseManager $courseId = $courseInfo['real_id']; $sql = "SELECT DISTINCT - u.id, + u.id as user_id, u.lastname, u.firstname, u.email, @@ -1816,7 +1816,7 @@ class CourseManager $rs = Database::query($sql); $teachers = array(); while ($teacher = Database::fetch_array($rs)) { - $teachers[$teacher['id']] = $teacher; + $teachers[$teacher['user_id']] = $teacher; } return $teachers; @@ -1835,6 +1835,7 @@ class CourseManager $add_link_to_profile = false ) { $teacher_list = self::get_teacher_list_from_course_code($course_code); + $teacher_string = ''; $list = array(); if (!empty($teacher_list)) { From 9374e43095a51d07cb2dc932e4acc7a0ada95399 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 9 Apr 2015 16:57:56 +0200 Subject: [PATCH 075/159] Use DataImport class. --- composer.json | 3 +- main/course_progress/thematic_controller.php | 38 ++++++--- main/inc/lib/import.lib.php | 84 +++++--------------- 3 files changed, 49 insertions(+), 76 deletions(-) diff --git a/composer.json b/composer.json index ff94435af5..2f6f0ef419 100755 --- a/composer.json +++ b/composer.json @@ -67,7 +67,8 @@ "bower-asset/modernizr": "2.8.*", "bower-asset/jqueryui-timepicker-addon": "1.5.*", "ramsey/array_column": "~1.1", - "patchwork/utf8": "~1.2" + "patchwork/utf8": "~1.2", + "ddeboer/data-import": "@stable" }, "require-dev": { "behat/behat": "2.5.*@stable", diff --git a/main/course_progress/thematic_controller.php b/main/course_progress/thematic_controller.php index 7bb540fea6..f7c6b87991 100755 --- a/main/course_progress/thematic_controller.php +++ b/main/course_progress/thematic_controller.php @@ -113,7 +113,7 @@ class ThematicController case 'thematic_import_select': break; case 'thematic_import': - $csv_import_array = Import::csv_to_array($_FILES['file']['tmp_name'], 'horizontal'); + $csv_import_array = Import::csv_to_array($_FILES['file']['tmp_name']); if (isset($_POST['replace']) && $_POST['replace']) { // Remove current thematic. @@ -126,22 +126,35 @@ class ThematicController // Import the progress. $current_thematic = null; - foreach ($csv_import_array as $data) { - foreach ($data as $key => $item) { - if ($key == 'title') { - $thematic->set_thematic_attributes(null, $item[0], $item[1], api_get_session_id()); + foreach ($csv_import_array as $item) { + $key = $item['type']; + switch ($key) { + case 'title': + $thematic->set_thematic_attributes(null, $item['data1'], $item['data2'], api_get_session_id()); $current_thematic = $thematic->thematic_save(); $description_type = 0; - } - if ($key == 'plan') { - $thematic->set_thematic_plan_attributes($current_thematic, $item[0], $item[1], $description_type); + break; + case 'plan': + $thematic->set_thematic_plan_attributes( + $current_thematic, + $item['data1'], + $item['data2'], + $description_type + ); $thematic->thematic_plan_save(); $description_type++; - } - if ($key == 'progress') { - $thematic->set_thematic_advance_attributes(null, $current_thematic, 0, $item[2], $item[0], $item[1]); + break; + case 'progress': + $thematic->set_thematic_advance_attributes( + null, + $current_thematic, + 0, + $item['data3'], + $item['data1'], + $item['data2'] + ); $thematic->thematic_advance_save(); - } + break; } } $action = 'thematic_details'; @@ -149,6 +162,7 @@ class ThematicController case 'thematic_export': $list = $thematic->get_thematic_list(); $csv = array(); + $csv[] = array('type', 'data1', 'data2', 'data3'); foreach ($list as $theme) { $csv[] = array('title', $theme['title'], $theme['content']); $data = $thematic->get_thematic_plan_data($theme['id']); diff --git a/main/inc/lib/import.lib.php b/main/inc/lib/import.lib.php index 52d068b8de..c95966c357 100755 --- a/main/inc/lib/import.lib.php +++ b/main/inc/lib/import.lib.php @@ -1,6 +1,10 @@ setHeaderRowNumber(0); + } + + return $csvReader; } /** @@ -40,68 +51,15 @@ class Import * * @deprecated use cvs_reader instead */ - static function csv_to_array($filename, $csv_order = 'vertical') { - $result = array(); - - // Encoding detection. - - $handle = fopen($filename, 'r'); - if ($handle === false) { - return $result; - } - $buffer = array(); - $i = 0; - while (!feof($handle) && $i < 200) { - // We assume that 200 lines are enough for encoding detection. - $buffer[] = fgets($handle); - $i++; - } - fclose($handle); - $buffer = implode("\n", $buffer); - $from_encoding = api_detect_encoding($buffer); - unset($buffer); - - // Reading the file, parsing and importing csv data. - - $handle = fopen($filename, 'r'); - if ($handle === false) { - return $result; - } - - if ($csv_order == 'vertical') { - $keys = api_fgetcsv($handle, null, ';'); - foreach ($keys as $key => &$key_value) { - $key_value = api_to_system_encoding($key_value, $from_encoding); - } - } + static function csv_to_array($filename) + { + $csvReader = self::csv_reader($filename); - while (($row_tmp = api_fgetcsv($handle, null, ';')) !== false) { - $row = array(); - // Avoid empty lines in csv - if (is_array($row_tmp) && count($row_tmp) > 0 && $row_tmp[0] != '') { - if (!is_null($row_tmp[0])) { - if ($csv_order == 'vertical') { - foreach ($row_tmp as $index => $value) { - $row[$keys[$index]] = api_to_system_encoding($value, $from_encoding); - } - } else { - $first = null; - $count = 1; - foreach ($row_tmp as $index => $value) { - if ($count == 1) { - $first = $value; - } else { - $row[$first][] = api_to_system_encoding($value, $from_encoding); - } - $count++; - } - } - $result[] = $row; - } - } - } + $workflow = new Workflow($csvReader); + $resultArray = []; + $writer = new ArrayWriter($resultArray); + $result = $workflow->addWriter($writer)->process(); - fclose($handle); - return $result; + return $resultArray; } } From fd3d8c90d1ff5cabed4024ea76a8e1700e2a9f56 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 9 Apr 2015 16:58:13 +0200 Subject: [PATCH 076/159] Fix queries --- main/admin/session_export.php | 119 +++++++++++++++---------------- main/inc/lib/usermanager.lib.php | 6 +- 2 files changed, 62 insertions(+), 63 deletions(-) diff --git a/main/admin/session_export.php b/main/admin/session_export.php index 12e08d277e..95328358b3 100755 --- a/main/admin/session_export.php +++ b/main/admin/session_export.php @@ -17,22 +17,21 @@ $formSent = 0; $errorMsg = ''; // Database Table Definitions -$tbl_user = Database::get_main_table(TABLE_MAIN_USER); -$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE); -$tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER); -$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION); -$tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER); -$tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE); -$tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); +$tbl_user = Database::get_main_table(TABLE_MAIN_USER); +$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE); +$tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER); +$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION); +$tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER); +$tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE); +$tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); $archivePath = api_get_path(SYS_ARCHIVE_PATH); -$archiveURL = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive='; +$archiveURL = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive='; -$tool_name = get_lang('ExportSessionListXMLCSV'); +$tool_name = get_lang('ExportSessionListXMLCSV'); global $_configuration; - $interbreadcrumb[] = array('url' => 'index.php',"name" => get_lang('PlatformAdmin')); set_time_limit(0); @@ -42,72 +41,72 @@ if ($_POST['formSent']) { $file_type = ($_POST['file_type'] == 'csv')?'csv':'xml'; $session_id = $_POST['session_id']; if (empty($session_id)) { - $sql = "SELECT id,name,id_coach,username,date_start,date_end,visibility,session_category_id FROM $tbl_session INNER JOIN $tbl_user - ON $tbl_user.user_id = $tbl_session.id_coach ORDER BY id"; - + $sql = "SELECT + s.id, + name, + id_coach, + username, + date_start, + date_end, + visibility, + session_category_id + FROM $tbl_session s + INNER JOIN $tbl_user + ON $tbl_user.user_id = s.id_coach + ORDER BY id"; - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION); $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1){ - $sql = "SELECT id, name,id_coach,username,date_start,date_end,visibility,session_category_id FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url - ON (s.id= session_rel_url.session_id) INNER JOIN $tbl_user u ON (u.user_id = s.id_coach) - WHERE access_url_id = $access_url_id - ORDER BY id"; - + $sql = "SELECT s.id, name,id_coach,username,date_start,date_end,visibility,session_category_id + FROM $tbl_session s + INNER JOIN $tbl_session_rel_access_url as session_rel_url + ON (s.id= session_rel_url.session_id) + INNER JOIN $tbl_user u ON (u.user_id = s.id_coach) + WHERE access_url_id = $access_url_id + ORDER BY id"; } } - $result=Database::query($sql); - } - else - { - $sql = "SELECT id,name,username,date_start,date_end,visibility,session_category_id - FROM $tbl_session + + $result = Database::query($sql); + } else { + $sql = "SELECT s.id,name,username,date_start,date_end,visibility,session_category_id + FROM $tbl_session s INNER JOIN $tbl_user - ON $tbl_user.user_id = $tbl_session.id_coach + ON $tbl_user.user_id = s.id_coach WHERE id='$session_id'"; - $result = Database::query($sql); - } - if(Database::num_rows($result)) - { - if(!file_exists($archivePath)) - { + if (Database::num_rows($result)) { + if (!file_exists($archivePath)) { mkdir($archivePath, api_get_permissions_for_new_directories(), true); } - if(!file_exists($archivePath.'index.html')) - { - $fp=fopen($archivePath.'index.html','w'); - + if (!file_exists($archivePath.'index.html')) { + $fp = fopen($archivePath.'index.html','w'); fputs($fp,''); - fclose($fp); } $archiveFile='export_sessions_'.$session_id.'_'.date('Y-m-d_H-i-s').'.'.$file_type; - while( file_exists($archivePath.$archiveFile)) - { + while( file_exists($archivePath.$archiveFile)) { $archiveFile='export_users_'.$session_id.'_'.date('Y-m-d_H-i-s').'_'.uniqid('').'.'.$file_type; } - $fp=fopen($archivePath.$archiveFile,'w'); - if($file_type == 'csv') - { + $fp = fopen($archivePath.$archiveFile, 'w'); + + if ($file_type == 'csv') { $cvs = true; fputs($fp,"SessionName;Coach;DateStart;DateEnd;Visibility;SessionCategory;Users;Courses;\n"); - } - else - { + } else { $cvs = false; fputs($fp, "\n\n"); } - while($row=Database::fetch_array($result)) - { + while($row=Database::fetch_array($result)) { $add = ''; $row['name'] = str_replace(';',',',$row['name']); $row['username'] = str_replace(';',',',$row['username']); @@ -115,10 +114,9 @@ if ($_POST['formSent']) { $row['date_end'] = str_replace(';',',',$row['date_end']); $row['visibility'] = str_replace(';',',',$row['visibility']); $row['session_category'] = str_replace(';',',',$row['session_category_id']); - if($cvs){ + if ($cvs) { $add.= $row['name'].';'.$row['username'].';'.$row['date_start'].';'.$row['date_end'].';'.$row['visibility'].';'.$row['session_category'].';'; - } - else { + } else { $add = "\t\n" ."\t\t$row[name]\n" ."\t\t$row[username]\n" @@ -139,7 +137,7 @@ if ($_POST['formSent']) { $rsUsers = Database::query($sql); $users = ''; - while($rowUsers = Database::fetch_array($rsUsers)){ + while ($rowUsers = Database::fetch_array($rsUsers)){ if($cvs){ $users .= str_replace(';',',',$rowUsers['username']).'|'; } @@ -147,7 +145,8 @@ if ($_POST['formSent']) { $users .= "\t\t$rowUsers[username]\n"; } } - if(!empty($users) && $cvs) + + if (!empty($users) && $cvs) $users = api_substr($users , 0, api_strlen($users)-1); if($cvs) @@ -165,8 +164,7 @@ if ($_POST['formSent']) { $rsCourses = Database::query($sql); $courses = ''; - while ($rowCourses = Database::fetch_array($rsCourses)){ - + while ($rowCourses = Database::fetch_array($rsCourses)) { // get coachs from a course $sql = "SELECT u.username FROM $tbl_session_course_user scu @@ -238,7 +236,7 @@ if ($_POST['formSent']) { $courses = api_substr($courses , 0, api_strlen($courses)-1); $add .= $courses; - if($cvs) { + if ($cvs) { $breakline = api_is_windows_os()?"\r\n":"\n"; $add .= ";$breakline"; } else { @@ -263,13 +261,14 @@ Display::display_header($tool_name); $sql = "SELECT id, name FROM $tbl_session ORDER BY name"; if ($_configuration['multiple_access_urls']) { - $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION); + $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION); $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1){ - $sql = "SELECT id, name FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url - ON (s.id= session_rel_url.session_id) - WHERE access_url_id = $access_url_id - ORDER BY name"; + $sql = "SELECT s.id, name FROM $tbl_session s + INNER JOIN $tbl_session_rel_access_url as session_rel_url + ON (s.id = session_rel_url.session_id) + WHERE access_url_id = $access_url_id + ORDER BY name"; } } $result = Database::query($sql); diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php index 90d14a98ca..d2b565e773 100755 --- a/main/inc/lib/usermanager.lib.php +++ b/main/inc/lib/usermanager.lib.php @@ -2699,10 +2699,10 @@ class UserManager // Get the list of sessions where the user is subscribed // This is divided into two different queries $sessions = array(); - $sql = "SELECT DISTINCT id, name, date_start, date_end - FROM $tbl_session_user, $tbl_session + $sql = "SELECT DISTINCT s.id, name, date_start, date_end + FROM $tbl_session_user, $tbl_session s WHERE ( - session_id = id AND + session_id = s.id AND user_id = $user_id AND relation_type <> ".SESSION_RELATION_TYPE_RRHH." ) From c8ef4daf908020378b8256c341fdc5ace5db1d67 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 9 Apr 2015 17:48:07 +0200 Subject: [PATCH 077/159] Change function names and implementation. --- composer.json | 3 +- main/admin/add_users_to_usergroup.php | 2 +- main/admin/user_export.php | 4 +- main/admin/user_information.php | 2 +- main/admin/usergroup_export.php | 2 +- main/course_progress/thematic_controller.php | 2 +- main/glossary/index.php | 2 +- main/gradebook/gradebook_view_result.php | 4 +- main/group/group_overview.php | 6 +- main/inc/ajax/model.ajax.php | 2 +- main/inc/lib/export.lib.inc.php | 91 +++++++++----------- main/mySpace/index.php | 2 +- main/mySpace/myStudents.php | 2 +- main/mySpace/student.php | 2 +- main/mySpace/teachers.php | 2 +- main/mySpace/users.php | 2 +- main/tracking/courseLog.php | 2 +- main/tracking/course_log_tools.php | 2 +- main/tracking/lp_results_by_user.php | 2 +- main/user/user.php | 4 +- plugin/ticket/src/myticket.php | 2 +- plugin/ticket/src/tutor.php | 2 +- tests/main/inc/lib/export.lib.inc.test.php | 6 +- 23 files changed, 70 insertions(+), 80 deletions(-) diff --git a/composer.json b/composer.json index 2f6f0ef419..3e3c2651b0 100755 --- a/composer.json +++ b/composer.json @@ -68,7 +68,8 @@ "bower-asset/jqueryui-timepicker-addon": "1.5.*", "ramsey/array_column": "~1.1", "patchwork/utf8": "~1.2", - "ddeboer/data-import": "@stable" + "ddeboer/data-import": "@stable", + "phpoffice/phpexcel": "~1.8" }, "require-dev": { "behat/behat": "2.5.*@stable", diff --git a/main/admin/add_users_to_usergroup.php b/main/admin/add_users_to_usergroup.php index b337a2ed31..ec55dfab99 100755 --- a/main/admin/add_users_to_usergroup.php +++ b/main/admin/add_users_to_usergroup.php @@ -132,7 +132,7 @@ if (isset($_GET['action']) && $_GET['action'] == 'export') { $data[] = array($user['username'], $groupInfo['name']); } $filename = 'export_user_class_' . api_get_local_time(); - Export::export_table_csv($data, $filename); + Export::arrayToCsv($data, $filename); exit; } } diff --git a/main/admin/user_export.php b/main/admin/user_export.php index ed124b3ce3..f58e1db6f1 100755 --- a/main/admin/user_export.php +++ b/main/admin/user_export.php @@ -126,11 +126,11 @@ if ($form->validate()) { switch($file_type) { case 'xml': - Export::export_table_xml($data,$filename,'Contact','Contacts'); + Export::arrayToXml($data, $filename, 'Contact', 'Contacts'); exit; break; case 'csv': - Export::export_table_csv($data,$filename); + Export::arrayToCsv($data,$filename); exit; break; } diff --git a/main/admin/user_information.php b/main/admin/user_information.php index 56085a4fb8..6287e3e9ce 100755 --- a/main/admin/user_information.php +++ b/main/admin/user_information.php @@ -394,7 +394,7 @@ if (isset($_GET['action'])) { } break; case 'export': - Export :: export_table_csv_utf8($csvContent, 'user_information_'.$user); + Export :: arrayToCsv($csvContent, 'user_information_'.$user); exit; break; } diff --git a/main/admin/usergroup_export.php b/main/admin/usergroup_export.php index 0bfe5a35e1..98df29476d 100755 --- a/main/admin/usergroup_export.php +++ b/main/admin/usergroup_export.php @@ -28,7 +28,7 @@ if ($form->validate()) { $data = $userGroup->getDataToExport(); $data = array_merge($header, $data); $filename = 'export_classes_'.api_get_local_time(); - Export::export_table_csv($data, $filename); + Export::arrayToCsv($data, $filename); exit; } diff --git a/main/course_progress/thematic_controller.php b/main/course_progress/thematic_controller.php index f7c6b87991..692a6a2a2a 100755 --- a/main/course_progress/thematic_controller.php +++ b/main/course_progress/thematic_controller.php @@ -178,7 +178,7 @@ class ThematicController } } } - Export::export_table_csv($csv); + Export::arrayToCsv($csv); exit; // Don't continue building a normal page. return; diff --git a/main/glossary/index.php b/main/glossary/index.php index 6e6f03bed2..bd80e9ad65 100755 --- a/main/glossary/index.php +++ b/main/glossary/index.php @@ -75,7 +75,7 @@ if (isset($_GET['action']) && $_GET['action'] == 'export') { $list[] = array ($line[0], $line[1]); } $filename = 'glossary_course_'.api_get_course_id(); - Export::export_table_csv_utf8($list, $filename); + Export::arrayToCsv($list, $filename); } if (isset($_GET['action']) && $_GET['action'] == 'export_to_pdf') { GlossaryManager::export_to_pdf(); diff --git a/main/gradebook/gradebook_view_result.php b/main/gradebook/gradebook_view_result.php index 0ebb994897..b37ce3d553 100755 --- a/main/gradebook/gradebook_view_result.php +++ b/main/gradebook/gradebook_view_result.php @@ -328,11 +328,11 @@ if (isset($_GET['export'])) { switch ($file_type) { case 'xml' : - Export :: export_table_xml($alldata, $filename, 'Result', 'XMLResults'); + Export :: arrayToXml($alldata, $filename, 'Result', 'XMLResults'); exit; break; case 'csv' : - Export :: export_table_csv($alldata, $filename); + Export :: arrayToCsv($alldata, $filename); exit; break; } diff --git a/main/group/group_overview.php b/main/group/group_overview.php index d8f8576afb..b7849cb35a 100755 --- a/main/group/group_overview.php +++ b/main/group/group_overview.php @@ -34,7 +34,7 @@ if (isset($_GET['action'])) { switch ($_GET['action']) { case 'export_all': $data = GroupManager::exportCategoriesAndGroupsToArray(null, true); - Export::export_table_csv($data); + Export::arrayToCsv($data); exit; break; case 'export_pdf': @@ -53,12 +53,12 @@ if (isset($_GET['action'])) { switch ($_GET['type']) { case 'csv': - Export::export_table_csv($data); + Export::arrayToCsv($data); exit; break; case 'xls': if (!empty($data)) { - Export::export_table_xls($data); + Export::arrayToXls($data); exit; } break; diff --git a/main/inc/ajax/model.ajax.php b/main/inc/ajax/model.ajax.php index 31a428fbf1..0184ab0a27 100755 --- a/main/inc/ajax/model.ajax.php +++ b/main/inc/ajax/model.ajax.php @@ -1509,7 +1509,7 @@ if (in_array($action, $allowed_actions)) { default: //TODO add date if exists $file_name = (!empty($action)) ? $action : 'company_report'; - Export::export_table_csv($array, $file_name); + Export::arrayToCsv($array, $file_name); break; } exit; diff --git a/main/inc/lib/export.lib.inc.php b/main/inc/lib/export.lib.inc.php index d68b9031d5..26672fbde9 100755 --- a/main/inc/lib/export.lib.inc.php +++ b/main/inc/lib/export.lib.inc.php @@ -1,6 +1,13 @@ $row) { - $line = ''; - if (is_array($row)) { - foreach ($row as $value) { - $line .= '"'.str_replace('"', '""', $value).'";'; - } - } - @fwrite($handle, $line."\n"); - } - } - @fclose($handle); - DocumentManager :: file_send_for_download($file, true, $filename.'.csv'); - - return false; - } - /** * Export tabular data to CSV-file * @param array $data * @param string $filename */ - public static function export_table_csv_utf8($data, $filename = 'export') + public static function arrayToCsv($data, $filename = 'export') { - if(empty($data)) { + if (empty($data)) { return false; } - $path = Chamilo::temp_file(); - $converter = new Utf8Encoder(null, true); - $file = FileWriter::create($path, $converter); - $file = CsvWriter::create($file); - foreach ($data as $row) { - $file->put($row); - } - $file->close(); - DocumentManager::file_send_for_download($path, false, $filename.'.csv'); - unlink($path); + + $reader = new ArrayReader($data); + + // Create the workflow from the reader + $workflow = new Workflow($reader); + + $filePath = api_get_path(SYS_ARCHIVE_PATH).uniqid('').'.csv'; + + $file = new \SplFileObject($filePath, 'w'); + $writer = new CsvWriter($file); + $workflow->addWriter($writer); + $workflow->process(); +exit; + DocumentManager::file_send_for_download($filePath, false, $filename.'.csv'); exit; + } /** @@ -68,20 +54,22 @@ class Export * @param array $data * @param string $filename */ - public static function export_table_xls($data, $filename = 'export', $encoding = 'utf-8') + public static function arrayToXls($data, $filename = 'export', $encoding = 'utf-8') { - $file = api_get_path(SYS_ARCHIVE_PATH).uniqid('').'.xls'; - $handle = fopen($file, 'a+'); - $systemEncoding = api_get_system_encoding(); - foreach ($data as $row) { - $string = implode("\t", $row); - if ($encoding != 'utf-8') { - $string = api_convert_encoding($string, $encoding, $systemEncoding); - } - fwrite($handle, $string."\n"); + $filePath = api_get_path(SYS_ARCHIVE_PATH).uniqid('').'.xls'; + + $file = new \SplFileObject($filePath, 'w'); + $writer = new ExcelWriter($file); + $writer->prepare(); + + foreach ($data as $index => $row) { + $writer->writeItem($row); } - fclose($handle); - DocumentManager::file_send_for_download($file, false, $filename.'.xls'); + + $writer->finish(); + + DocumentManager::file_send_for_download($filePath, false, $filename.'.xls'); + exit; } /** @@ -112,6 +100,7 @@ class Export fclose($handle); DocumentManager::file_send_for_download($file, false, $filename.'.xls'); } + /** * Export tabular data to XML-file * @param array Simple array of data to put in XML @@ -120,7 +109,7 @@ class Export * @param string Name of the root element. A root element should always be given. * @param string Encoding in which the data is provided */ - public static function export_table_xml($data, $filename = 'export', $item_tagname = 'item', $wrapper_tagname = null, $encoding = null) + public static function arrayToXml($data, $filename = 'export', $item_tagname = 'item', $wrapper_tagname = null, $encoding = null) { if (empty($encoding)) { $encoding = api_get_system_encoding(); diff --git a/main/mySpace/index.php b/main/mySpace/index.php index b0e323c3f7..7e39e1e8cd 100755 --- a/main/mySpace/index.php +++ b/main/mySpace/index.php @@ -397,7 +397,7 @@ if ($export_csv) { // Send the csv file if asked if ($export_csv) { ob_end_clean(); - Export :: export_table_csv($csv_content, 'reporting_index'); + Export :: arrayToCsv($csv_content, 'reporting_index'); exit; } diff --git a/main/mySpace/myStudents.php b/main/mySpace/myStudents.php index 10e5eee128..105c8b3f16 100755 --- a/main/mySpace/myStudents.php +++ b/main/mySpace/myStudents.php @@ -1158,7 +1158,7 @@ if (!empty($student_id)) { } if ($export_csv) { ob_end_clean(); - Export :: export_table_csv($csv_content, 'reporting_student'); + Export :: arrayToCsv($csv_content, 'reporting_student'); exit; } diff --git a/main/mySpace/student.php b/main/mySpace/student.php index ad2f57e040..aaecfabcf9 100755 --- a/main/mySpace/student.php +++ b/main/mySpace/student.php @@ -283,7 +283,7 @@ if ($export_csv) { } $csv_content = array_merge($csv_header, $content); ob_end_clean(); - Export :: export_table_csv($csv_content, 'reporting_student_list'); + Export :: arrayToCsv($csv_content, 'reporting_student_list'); exit; } else { Display::display_header($nameTools); diff --git a/main/mySpace/teachers.php b/main/mySpace/teachers.php index 9c83992fcd..b82ee6be22 100755 --- a/main/mySpace/teachers.php +++ b/main/mySpace/teachers.php @@ -260,7 +260,7 @@ if ($export_csv) { } $csv_content = array_merge($csv_header, $content); ob_end_clean(); - Export :: export_table_csv($csv_content, 'reporting_teacher_list'); + Export :: arrayToCsv($csv_content, 'reporting_teacher_list'); exit; } else { Display::display_header($nameTools); diff --git a/main/mySpace/users.php b/main/mySpace/users.php index 76c90dbddf..47af4bffaf 100755 --- a/main/mySpace/users.php +++ b/main/mySpace/users.php @@ -271,7 +271,7 @@ if ($export_csv) { } $csv_content = array_merge($csv_header, $content); ob_end_clean(); - Export :: export_table_csv($csv_content, 'reporting_student_list'); + Export :: arrayToCsv($csv_content, 'reporting_student_list'); exit; } else { Display::display_header($nameTools); diff --git a/main/tracking/courseLog.php b/main/tracking/courseLog.php index f3b2a056c6..08fba574ec 100755 --- a/main/tracking/courseLog.php +++ b/main/tracking/courseLog.php @@ -517,7 +517,7 @@ if ($export_csv) { ob_end_clean(); array_unshift($csv_content, $csv_headers); // Adding headers before the content. - Export::export_table_csv($csv_content, 'reporting_student_list'); + Export::arrayToCsv($csv_content, 'reporting_student_list'); exit; } Display::display_footer(); diff --git a/main/tracking/course_log_tools.php b/main/tracking/course_log_tools.php index 5b5988914b..9715db4e90 100755 --- a/main/tracking/course_log_tools.php +++ b/main/tracking/course_log_tools.php @@ -335,7 +335,7 @@ echo '
      '; // send the csv file if asked if ($export_csv) { ob_end_clean(); - Export :: export_table_csv($csv_content, 'reporting_course_tools'); + Export :: arrayToCsv($csv_content, 'reporting_course_tools'); exit; } diff --git a/main/tracking/lp_results_by_user.php b/main/tracking/lp_results_by_user.php index a3e3b3e24e..f1c9cbb89d 100755 --- a/main/tracking/lp_results_by_user.php +++ b/main/tracking/lp_results_by_user.php @@ -222,7 +222,7 @@ function export_complete_report_csv($filename, $array) { $header[] = array(get_lang('Course'),get_lang('LearningPath'), get_lang('Exercise'), get_lang('User'),get_lang('Attempt'), get_lang('Date'),get_lang('Results')); if (!empty($array)) { $array = array_merge($header, $array); - Export :: export_table_csv($array, $filename); + Export :: arrayToCsv($array, $filename); } exit; /* diff --git a/main/user/user.php b/main/user/user.php index 81fce359d6..ed93d43bff 100755 --- a/main/user/user.php +++ b/main/user/user.php @@ -347,10 +347,10 @@ if (api_is_allowed_to_edit(null, true)) { switch ($_GET['type']) { case 'csv' : - Export::export_table_csv($a_users); + Export::arrayToCsv($a_users); exit; case 'xls' : - Export::export_table_xls($a_users); + Export::arrayToXls($a_users); exit; case 'pdf' : $header_attributes = array( diff --git a/plugin/ticket/src/myticket.php b/plugin/ticket/src/myticket.php index 177297fca9..a0e79494e4 100755 --- a/plugin/ticket/src/myticket.php +++ b/plugin/ticket/src/myticket.php @@ -183,7 +183,7 @@ if (isset($_GET['action'])) { ); $data[] = $ticket_rem; } - Export::export_table_xls($data, $plugin->get_lang('Tickets')); + Export::arrayToXls($data, $plugin->get_lang('Tickets')); exit; break; case 'close_tickets': diff --git a/plugin/ticket/src/tutor.php b/plugin/ticket/src/tutor.php index 91512309f8..84505721b6 100755 --- a/plugin/ticket/src/tutor.php +++ b/plugin/ticket/src/tutor.php @@ -95,7 +95,7 @@ function save() { $course_code = api_get_course_id(); $results = initializeReport($course_code); if (isset($_GET['action'])) { - Export::export_table_xls($results['export'], "COURSE_USER_REPORT" . $course_code); + Export::arrayToXls($results['export'], "COURSE_USER_REPORT" . $course_code); } else { Display::display_header(); api_protect_course_script(); diff --git a/tests/main/inc/lib/export.lib.inc.test.php b/tests/main/inc/lib/export.lib.inc.test.php index 3e28597323..5996decb13 100755 --- a/tests/main/inc/lib/export.lib.inc.test.php +++ b/tests/main/inc/lib/export.lib.inc.test.php @@ -22,7 +22,7 @@ class TestExport extends UnitTestCase { $data = array(); // can only be tested if headers were not sent ob_start(); - $res = Export::export_table_csv($data, $filename = 'export'); + $res = Export::arrayToCsv($data, $filename = 'export'); $this->assertFalse($res); ob_end_clean(); } @@ -32,7 +32,7 @@ class TestExport extends UnitTestCase { $data = array(); $filename = 'export'; ob_start(); - $res=Export::export_table_xls($data,$filename); + $res=Export::arrayToXls($data,$filename); $this->assertFalse($res); ob_end_clean(); } @@ -44,7 +44,7 @@ class TestExport extends UnitTestCase { $wrapper_tagname = null; $encoding=null; ob_start(); - $res=Export::export_table_xml($data,$filename,$item_tagname, + $res=Export::arrayToXml($data,$filename,$item_tagname, $wrapper_tagname,$encoding); $this->assertFalse($res); ob_end_clean(); From f918c5bfd86e0da644b913251f88ac095a1c9399 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Thu, 9 Apr 2015 18:37:51 +0200 Subject: [PATCH 078/159] Fix csv export + remove unused classes. --- main/inc/lib/export.lib.inc.php | 18 +- .../lib/system/io/csv_object_writer.class.php | 129 ------------- main/inc/lib/system/io/csv_reader.class.php | 170 ---------------- main/inc/lib/system/io/csv_writer.class.php | 100 ---------- main/inc/lib/system/io/file_reader.class.php | 182 ------------------ main/inc/lib/system/io/file_writer.class.php | 81 -------- 6 files changed, 8 insertions(+), 672 deletions(-) delete mode 100755 main/inc/lib/system/io/csv_object_writer.class.php delete mode 100755 main/inc/lib/system/io/csv_reader.class.php delete mode 100755 main/inc/lib/system/io/csv_writer.class.php delete mode 100755 main/inc/lib/system/io/file_reader.class.php delete mode 100755 main/inc/lib/system/io/file_writer.class.php diff --git a/main/inc/lib/export.lib.inc.php b/main/inc/lib/export.lib.inc.php index 26672fbde9..9f33b9eef8 100755 --- a/main/inc/lib/export.lib.inc.php +++ b/main/inc/lib/export.lib.inc.php @@ -4,6 +4,7 @@ use Ddeboer\DataImport\Writer\ExcelWriter; use Ddeboer\DataImport\Writer\CsvWriter; use Ddeboer\DataImport\Workflow; + use Ddeboer\DataImport\Reader\CsvReader; use Ddeboer\DataImport\Reader\ArrayReader; use Ddeboer\DataImport\Writer\ArrayWriter; @@ -32,21 +33,18 @@ class Export return false; } - $reader = new ArrayReader($data); + $filePath = api_get_path(SYS_ARCHIVE_PATH).uniqid('').'.csv'; - // Create the workflow from the reader - $workflow = new Workflow($reader); + $writer = new CsvWriter(); + $writer->setStream(fopen($filePath, 'w')); - $filePath = api_get_path(SYS_ARCHIVE_PATH).uniqid('').'.csv'; + foreach($data as $item) { + $writer->writeItem($item); + } + $writer->finish(); - $file = new \SplFileObject($filePath, 'w'); - $writer = new CsvWriter($file); - $workflow->addWriter($writer); - $workflow->process(); -exit; DocumentManager::file_send_for_download($filePath, false, $filename.'.csv'); exit; - } /** diff --git a/main/inc/lib/system/io/csv_object_writer.class.php b/main/inc/lib/system/io/csv_object_writer.class.php deleted file mode 100755 index 4765ff486d..0000000000 --- a/main/inc/lib/system/io/csv_object_writer.class.php +++ /dev/null @@ -1,129 +0,0 @@ -property_name_1 = 'name 1'; - * $object->property_name_2 = 'name 2'; - * - * $map = array( 'property_name_1' => 'Header title 1', - * 'property_name_2' => 'Header title 2'); - * - * $writer = CsvObjectWriter::create($map, 'temp'); - * $writer->add($object); - * - * Output - * - * "Header title 1";"Header title 2" - * "name 1";"name 2" - * - * @license /licence.txt - * @author Laurent Opprecht - */ -class CsvObjectWriter extends CsvWriter -{ - - /** - * - * @param string|object $stream - * @return CsvWriter - */ - static function create($stream, $map = '*', $delimiter = ';', $enclosure = '"') - { - return new self($stream, $map = '*', $map, $delimiter, $enclosure); - } - - protected $map = '*'; - protected $headers_written = false; - - function __construct($stream, $map = '*', $delimiter = ';', $enclosure = '"') - { - parent::__construct($stream, $delimiter, $enclosure); - $this->map = $map; - } - - public function get_map() - { - return $this->map; - } - - /** - * - * @param object $item - * @return boolean - */ - public function put($item) - { - $data = $this->convert($item); - if (empty($data)) { - return false; - } - $this->writer_headers(); - parent::put($data); - return true; - } - - /** - * Convert object to array of data - * @param object $object - * @return array - */ - protected function convert($item) - { - $result = array(); - $map = $this->map; - if ($map == '*') { - return (array) $item; - } - foreach ($map as $key => $value) { - $result[$key] = isset($item->{$key}) ? $item->{$key} : ''; - } - return $result; - } - - /** - * - * @param array $items - */ - public function add_all($items) - { - foreach ($items as $item) { - $this->add($item); - } - } - - /** - * - * @param array|object $item - */ - public function add($item) - { - if (is_array($item)) { - $this->add_all($item); - return; - } - $this->put($item); - } - - protected function writer_headers() - { - if ($this->headers_written) { - return; - } - $this->headers_written = true; - - $map = $this->map; - if (!is_array($map)) { - return; - } - - $headers = array(); - foreach ($map as $key => $value) { - $headers[] = $value; - } - parent::put($headers); - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/io/csv_reader.class.php b/main/inc/lib/system/io/csv_reader.class.php deleted file mode 100755 index 5a0ffd9265..0000000000 --- a/main/inc/lib/system/io/csv_reader.class.php +++ /dev/null @@ -1,170 +0,0 @@ -$value){ - * echo "$key : $value"; - * } - * } - * - * - * - * @copyright (c) 2012 University of Geneva - * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html - * @author Laurent Opprecht - */ -class CsvReader implements Iterator -{ - - /** - * - * @param string|FileReader $stream - * @param string $delimiter - * @param string $enclosure - * @return CsvReader - */ - static function create($stream, $delimiter = ';', $enclosure = '"') - { - return new self($stream, $delimiter, $enclosure); - } - - protected $stream = null; - protected $headers = array(); - protected $delimiter = ''; - protected $enclosure = ''; - protected $current = false; - protected $index = -1; - - function __construct($stream, $delimiter = ';', $enclosure = '"') - { - $this->stream = $stream; - $this->delimiter = $delimiter ? substr($delimiter, 0, 1) : ';'; - $this->enclosure = $enclosure ? substr($enclosure, 0, 1) : '"'; - } - - function get_delimiter() - { - return $this->delimiter; - } - - function get_enclosure() - { - return $this->enclosure; - } - - function headers() - { - return $this->headers; - } - - /** - * @return FileReader - */ - function stream() - { - if (is_string($this->stream)) { - $this->stream = new FileReader($this->stream); - } - return $this->stream; - } - - protected function decode($line) - { - if (empty($line)) { - return array(); - } - $data = api_str_getcsv($line, $this->get_delimiter(), $this->get_enclosure()); - if ($this->headers) { - $result = array(); - foreach ($data as $index => $value) { - $key = isset($this->headers[$index]) ? $this->headers[$index] : false; - if ($key) { - $result[$key] = $value; - } else { - $result[] = $value; - } - } - } else { - $result = $data; - } - return $result; - } - - /** - * Returns the next non empty line - * - * @return boolean|string - */ - protected function next_line() - { - while (true) { - $line = $this->stream()->next(); - if ($line === false) { - return false; - } else if ($line) { - return $line; - } - } - return false; - } - - public function current() - { - return $this->current; - } - - public function key() - { - return $this->index; - } - - public function next() - { - if (empty($this->headers)) { - $line = $this->next_line(); - $this->headers = $this->decode($line); - } - $line = $this->next_line(); - if ($line) { - $this->current = $this->decode($line); - $this->index++; - } else { - $this->current = false; - } - return $this->current; - } - - public function rewind() - { - $this->stream()->rewind(); - $line = $this->stream()->current(); - if (empty($line)) { - $line = $this->next_line(); - } - $this->headers = $this->decode($line); - $this->index = -1; - $this->next(); - } - - public function valid() - { - return $this->current !== false; - } - - function __clone() - { - $this->stream()->rewind(); - $this->current = false; - $this->index = -1; - $this->headers = array(); - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/io/csv_writer.class.php b/main/inc/lib/system/io/csv_writer.class.php deleted file mode 100755 index b2737332d6..0000000000 --- a/main/inc/lib/system/io/csv_writer.class.php +++ /dev/null @@ -1,100 +0,0 @@ -put($headers); - * $writer->put($line_1); - * $writer->put($line_2); - * - * @copyright (c) 2012 University of Geneva - * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html - * @author Laurent Opprecht - */ -class CsvWriter -{ - - /** - * - * @param string|object $stream - * @return CsvWriter - */ - static function create($stream, $delimiter = ';', $enclosure = '"') - { - return new self($stream, $delimiter, $enclosure); - } - - protected $stream = null; - protected $delimiter = ''; - protected $enclosure = ''; - - function __construct($stream, $delimiter = ';', $enclosure = '"') - { - $this->stream = $stream; - $this->delimiter = $delimiter ? substr($delimiter, 0, 1) : ';';; - $this->enclosure = $enclosure ? substr($enclosure, 0, 1) : '"';; - } - - function get_delimiter() - { - return $this->delimiter; - } - - function get_enclosure() - { - return $this->enclosure; - } - - function get_stream(){ - return $this->stream; - } - - /** - * - * @return FileWriter - */ - protected function stream() - { - if (is_string($this->stream)) { - $this->stream = new FileWriter($this->stream); - } - return $this->stream; - } - - function write($items) - { - $items = is_array($items) ? $items : func_get_args(); - $this->put($items); - } - - function writeln($items) - { - $items = is_array($items) ? $items : func_get_args(); - $this->put($items); - } - - function put($items) - { - $items = is_array($items) ? $items : func_get_args(); - $enclosure = $this->enclosure; - $fields = array(); - foreach ($items as $item) { - $fields[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $item) . $enclosure; - } - - $delimiter = $this->delimiter; - $line = implode($delimiter, $fields); - $this->stream()->writeln($line); - } - - function close() - { - if (is_object($this->stream)) { - $this->stream->close(); - } - $this->stream = null; - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/io/file_reader.class.php b/main/inc/lib/system/io/file_reader.class.php deleted file mode 100755 index 7673da2ca1..0000000000 --- a/main/inc/lib/system/io/file_reader.class.php +++ /dev/null @@ -1,182 +0,0 @@ - - */ -class FileReader implements Iterator -{ - - const EOL = "\n"; - - /** - * - * @param string $path - * @return FileReader - */ - static function create($path, $converter = null) - { - return new self($path, $converter); - } - - /** - * Returns the file encoding - * - * @return Encoding - */ - static function detect_encoding($path) - { - $abstract = array(); - // We assume that 200 lines are enough for encoding detection. - // here we must get at the raw data so we don't use other functions - // it's not possible to read x chars as this would not be safe with utf - // (chars may be split in the middle) - $handle = fopen($path, 'r'); - - $i = 0; - while (($line = fgets($handle)) !== false && $i < 200) { - $i++; - $abstract[] = $line; - } - fclose($handle); - $abstract = implode($abstract); - return Encoding::detect_encoding($abstract); - } - - protected $path = ''; - protected $handle = null; - protected $current = false; - protected $index = -1; - protected $converter = null; - - function __construct($path, $converter = null) - { - if (empty($converter)) { - $encoding = self::detect_encoding($path); - $converter = $encoding->decoder(); - } - $this->path = $path; - $this->converter = $converter; - } - - /** - * - * @return Converter - */ - function get_converter() - { - return $this->converter; - } - - function handle() - { - if (is_null($this->handle)) { - $this->handle = fopen($this->path, 'r'); - } - return $this->handle; - } - - /** - * Read at most $count lines. - * - * @param int $count - * @return array - */ - function read_lines($count) - { - $result; - $i = 0; - foreach ($this as $line) { - if ($i >= $count) { - return $result; - } - $i++; - $result[] = $line; - } - return $result; - } - - function read_line() - { - return $this->next(); - } - - function close() - { - if (is_resource($this->handle)) { - fclose($this->handle); - } - $this->handle = null; - } - - protected function convert($text) - { - return $this->converter->convert($text); - } - - public function current() - { - return $this->current; - } - - public function key() - { - return $this->index; - } - - public function next() - { - $handle = $this->handle(); - if($handle === false) - { - $this->current = false; - return false; - } - $line = fgets($handle); - if ($line !== false) { - $line = rtrim($line, "\r\n"); - $line = $this->convert($line); - $this->index++; - } - $this->current = $line; - return $this->current; - } - - public function rewind() - { - $this->converter->reset(); - if ($handle = $this->handle()) { - rewind($handle); - } - $this->current = false; - $this->index = -1; - $this->next(); - } - - public function valid() - { - return $this->current !== false; - } - - function __clone() - { - $this->handle = null; - $this->current = false; - $this->index = -1; - $this->converter->reset(); - } - -} \ No newline at end of file diff --git a/main/inc/lib/system/io/file_writer.class.php b/main/inc/lib/system/io/file_writer.class.php deleted file mode 100755 index 0a56aa0e72..0000000000 --- a/main/inc/lib/system/io/file_writer.class.php +++ /dev/null @@ -1,81 +0,0 @@ - - */ -class FileWriter -{ - - /** - * - * @param string $path - * @param Converter $converter - * @return FileWriter - */ - static function create($path, $converter = null) - { - return new self($path, $converter); - } - - const EOL = "\n"; - - protected $path = ''; - protected $handle = null; - protected $converter = null; - - /** - * - * @param string $path - * @param Encoding $encoding - */ - function __construct($path, $converter = null) - { - $this->path = $path; - $this->converter = $converter ? $converter : Encoding::utf8()->encoder(); - } - - /** - * - * @return Converter - */ - function get_converter() - { - return $this->converter; - } - - protected function handle() - { - if (is_null($this->handle)) { - $this->handle = fopen($this->path, 'a+'); - } - return $this->handle; - } - - function write($text) - { - fwrite($this->handle(), $this->convert($text)); - } - - function writeln($text) - { - fwrite($this->handle(), $this->convert($text) . self::EOL); - } - - function close() - { - if (is_resource($this->handle)) { - fclose($this->handle); - } - $this->handle = null; - } - - protected function convert($text) - { - return $this->converter->convert($text); - } - -} \ No newline at end of file From 98ae4567b295fbcae9f8ad1d107707acb2d32622 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 08:36:21 +0200 Subject: [PATCH 079/159] Add license + id can be null --- src/Chamilo/CourseBundle/Entity/CAnnouncement.php | 2 +- .../CourseBundle/Entity/CAnnouncementAttachment.php | 2 +- src/Chamilo/CourseBundle/Entity/CAttendance.php | 2 +- .../CourseBundle/Entity/CAttendanceCalendar.php | 3 ++- .../Entity/CAttendanceCalendarRelGroup.php | 3 ++- .../CourseBundle/Entity/CAttendanceResult.php | 3 ++- .../CourseBundle/Entity/CAttendanceSheetLog.php | 3 ++- src/Chamilo/CourseBundle/Entity/CBlogAttachment.php | 2 +- src/Chamilo/CourseBundle/Entity/CBlogComment.php | 1 + src/Chamilo/CourseBundle/Entity/CBlogRating.php | 1 + src/Chamilo/CourseBundle/Entity/CBlogRelUser.php | 1 + src/Chamilo/CourseBundle/Entity/CBlogTask.php | 1 + .../CourseBundle/Entity/CBlogTaskRelUser.php | 13 +++++++------ src/Chamilo/CourseBundle/Entity/CCalendarEvent.php | 2 +- .../Entity/CCalendarEventAttachment.php | 3 ++- .../CourseBundle/Entity/CCalendarEventRepeat.php | 1 + src/Chamilo/CourseBundle/Entity/CChatConnected.php | 2 +- .../CourseBundle/Entity/CCourseDescription.php | 3 ++- src/Chamilo/CourseBundle/Entity/CCourseSetting.php | 2 +- src/Chamilo/CourseBundle/Entity/CDocument.php | 2 +- .../CourseBundle/Entity/CDropboxCategory.php | 1 + .../CourseBundle/Entity/CDropboxFeedback.php | 1 + src/Chamilo/CourseBundle/Entity/CDropboxFile.php | 3 ++- src/Chamilo/CourseBundle/Entity/CDropboxPerson.php | 1 + src/Chamilo/CourseBundle/Entity/CDropboxPost.php | 1 + .../CourseBundle/Entity/CForumAttachment.php | 3 ++- src/Chamilo/CourseBundle/Entity/CForumCategory.php | 1 + src/Chamilo/CourseBundle/Entity/CForumForum.php | 1 + src/Chamilo/CourseBundle/Entity/CForumMailcue.php | 3 ++- .../CourseBundle/Entity/CForumNotification.php | 3 ++- src/Chamilo/CourseBundle/Entity/CForumPost.php | 1 + src/Chamilo/CourseBundle/Entity/CForumThread.php | 1 + .../CourseBundle/Entity/CForumThreadQualify.php | 3 ++- .../CourseBundle/Entity/CForumThreadQualifyLog.php | 4 ++-- src/Chamilo/CourseBundle/Entity/CGlossary.php | 1 + src/Chamilo/CourseBundle/Entity/CGroupCategory.php | 4 ++-- src/Chamilo/CourseBundle/Entity/CGroupInfo.php | 2 +- src/Chamilo/CourseBundle/Entity/CGroupRelTutor.php | 3 ++- src/Chamilo/CourseBundle/Entity/CGroupRelUser.php | 4 ++-- src/Chamilo/CourseBundle/Entity/CItemProperty.php | 2 +- src/Chamilo/CourseBundle/Entity/CLink.php | 3 ++- src/Chamilo/CourseBundle/Entity/CLinkCategory.php | 4 ++-- src/Chamilo/CourseBundle/Entity/CLp.php | 4 ++-- src/Chamilo/CourseBundle/Entity/CLpItem.php | 3 ++- src/Chamilo/CourseBundle/Entity/CLpItemView.php | 3 ++- .../CourseBundle/Entity/CLpIvInteraction.php | 3 ++- src/Chamilo/CourseBundle/Entity/CLpIvObjective.php | 3 ++- src/Chamilo/CourseBundle/Entity/CLpView.php | 3 ++- src/Chamilo/CourseBundle/Entity/CNotebook.php | 1 + .../CourseBundle/Entity/COnlineConnected.php | 1 + src/Chamilo/CourseBundle/Entity/COnlineLink.php | 4 ++-- .../CourseBundle/Entity/CPermissionGroup.php | 3 +-- src/Chamilo/CourseBundle/Entity/CPermissionTask.php | 3 ++- src/Chamilo/CourseBundle/Entity/CPermissionUser.php | 4 ++-- src/Chamilo/CourseBundle/Entity/CQuiz.php | 4 ++-- src/Chamilo/CourseBundle/Entity/CQuizAnswer.php | 3 ++- src/Chamilo/CourseBundle/Entity/CQuizQuestion.php | 3 ++- .../CourseBundle/Entity/CQuizQuestionCategory.php | 3 ++- .../CourseBundle/Entity/CQuizQuestionOption.php | 4 ++-- .../Entity/CQuizQuestionRelCategory.php | 1 + .../CourseBundle/Entity/CQuizRelQuestion.php | 1 + src/Chamilo/CourseBundle/Entity/CResource.php | 4 ++-- src/Chamilo/CourseBundle/Entity/CRole.php | 1 + src/Chamilo/CourseBundle/Entity/CRoleGroup.php | 4 ++-- .../CourseBundle/Entity/CRolePermissions.php | 4 ++-- src/Chamilo/CourseBundle/Entity/CRoleUser.php | 1 + .../CourseBundle/Entity/CStudentPublication.php | 3 ++- .../Entity/CStudentPublicationAssignment.php | 3 ++- .../Entity/CStudentPublicationComment.php | 4 ++-- .../Entity/CStudentPublicationRelDocument.php | 4 ++-- .../Entity/CStudentPublicationRelUser.php | 3 ++- src/Chamilo/CourseBundle/Entity/CSurvey.php | 1 + src/Chamilo/CourseBundle/Entity/CSurveyAnswer.php | 1 + src/Chamilo/CourseBundle/Entity/CSurveyGroup.php | 4 ++-- .../CourseBundle/Entity/CSurveyInvitation.php | 1 + src/Chamilo/CourseBundle/Entity/CSurveyQuestion.php | 1 + .../CourseBundle/Entity/CSurveyQuestionOption.php | 1 + src/Chamilo/CourseBundle/Entity/CThematic.php | 3 ++- .../CourseBundle/Entity/CThematicAdvance.php | 3 ++- src/Chamilo/CourseBundle/Entity/CThematicPlan.php | 4 ++-- src/Chamilo/CourseBundle/Entity/CTool.php | 2 +- src/Chamilo/CourseBundle/Entity/CToolIntro.php | 4 ++-- .../CourseBundle/Entity/CUserinfoContent.php | 3 ++- src/Chamilo/CourseBundle/Entity/CUserinfoDef.php | 3 ++- src/Chamilo/CourseBundle/Entity/CWiki.php | 3 ++- src/Chamilo/CourseBundle/Entity/CWikiConf.php | 1 + src/Chamilo/CourseBundle/Entity/CWikiDiscuss.php | 4 ++-- src/Chamilo/CourseBundle/Entity/CWikiMailcue.php | 4 ++-- 88 files changed, 143 insertions(+), 87 deletions(-) diff --git a/src/Chamilo/CourseBundle/Entity/CAnnouncement.php b/src/Chamilo/CourseBundle/Entity/CAnnouncement.php index 028ea00a8d..3732728abb 100644 --- a/src/Chamilo/CourseBundle/Entity/CAnnouncement.php +++ b/src/Chamilo/CourseBundle/Entity/CAnnouncement.php @@ -25,7 +25,7 @@ class Announcement /** * @var integer * - * @ORM\Column(name="id", type="integer") + * @ORM\Column(name="id", type="integer", nullable=true) */ private $id; diff --git a/src/Chamilo/CourseBundle/Entity/CAnnouncementAttachment.php b/src/Chamilo/CourseBundle/Entity/CAnnouncementAttachment.php index 750f237021..85e24641e0 100644 --- a/src/Chamilo/CourseBundle/Entity/CAnnouncementAttachment.php +++ b/src/Chamilo/CourseBundle/Entity/CAnnouncementAttachment.php @@ -25,7 +25,7 @@ class CAnnouncementAttachment /** * @var integer * - * @ORM\Column(name="id", type="integer") + * @ORM\Column(name="id", type="integer", nullable=true) */ private $id; diff --git a/src/Chamilo/CourseBundle/Entity/CAttendance.php b/src/Chamilo/CourseBundle/Entity/CAttendance.php index 907cb22189..8edf4534e2 100644 --- a/src/Chamilo/CourseBundle/Entity/CAttendance.php +++ b/src/Chamilo/CourseBundle/Entity/CAttendance.php @@ -32,7 +32,7 @@ class CAttendance /** * @var integer * - * @ORM\Column(name="id", type="integer") + * @ORM\Column(name="id", type="integer", nullable=true) */ private $id; diff --git a/src/Chamilo/CourseBundle/Entity/CAttendanceCalendar.php b/src/Chamilo/CourseBundle/Entity/CAttendanceCalendar.php index 945957b750..e5fc345ca1 100644 --- a/src/Chamilo/CourseBundle/Entity/CAttendanceCalendar.php +++ b/src/Chamilo/CourseBundle/Entity/CAttendanceCalendar.php @@ -1,4 +1,5 @@ Date: Fri, 10 Apr 2015 08:46:58 +0200 Subject: [PATCH 080/159] Remove deprecated functions --- main/admin/configure_inscription.php | 2 +- main/admin/skill_badge_create.php | 2 +- main/admin/skill_badge_list.php | 2 +- main/auth/cas/authcas.php | 24 +-- main/auth/inscription.php | 2 +- main/auth/shibboleth/app/shibboleth.class.php | 20 +- .../db/shibboleth_upgrade.class.php | 6 +- main/exercice/exercise.class.php | 2 +- main/forum/forumfunction.inc.php | 2 +- main/forum/viewforum.php | 2 +- main/inc/lib/api.lib.php | 176 ------------------ main/inc/lib/banner.lib.php | 2 +- main/inc/lib/course_request.lib.php | 8 +- main/inc/lib/sessionmanager.lib.php | 2 +- plugin/buycourses/src/inscription.php | 2 +- plugin/clockworksms/lib/clockworksms.lib.php | 2 +- .../lib/search_course_widget.class.php | 7 +- tests/main/inc/lib/main_api.lib.test.php | 19 -- 18 files changed, 43 insertions(+), 239 deletions(-) diff --git a/main/admin/configure_inscription.php b/main/admin/configure_inscription.php index 7cc36bbbb2..16f48c5c20 100755 --- a/main/admin/configure_inscription.php +++ b/main/admin/configure_inscription.php @@ -59,7 +59,7 @@ if (!empty($_SESSION['user_language_choice'])) { } elseif (!empty($_SESSION['_user']['language'])) { $lang = $_SESSION['_user']['language']; } else { - $lang = get_setting('platformLanguage'); + $lang = api_get_setting('platformLanguage'); } // ----- Ensuring availability of main files in the corresponding language ----- diff --git a/main/admin/skill_badge_create.php b/main/admin/skill_badge_create.php index b7b8450096..e05d1a4d4c 100644 --- a/main/admin/skill_badge_create.php +++ b/main/admin/skill_badge_create.php @@ -95,7 +95,7 @@ $interbreadcrumb = array( ); $tpl = new Template(get_lang('CreateBadge')); -$tpl->assign('platformAdminEmail', get_setting('emailAdministrator')); +$tpl->assign('platformAdminEmail', api_get_setting('emailAdministrator')); $tpl->assign('skill', $skill); $contentTemplate = $tpl->get_template('skill/badge_create.tpl'); diff --git a/main/admin/skill_badge_list.php b/main/admin/skill_badge_list.php index 303ecfcfef..59501fb1cc 100644 --- a/main/admin/skill_badge_list.php +++ b/main/admin/skill_badge_list.php @@ -39,7 +39,7 @@ $interbreadcrumb = array( $tpl = new Template(get_lang('Skills')); $tpl->assign('errorMessage', $errorMessage); -$tpl->assign('platformAdminEmail', get_setting('emailAdministrator')); +$tpl->assign('platformAdminEmail', api_get_setting('emailAdministrator')); $tpl->assign('skills', $skills); $contentTemplate = $tpl->get_template('skill/badge_list.tpl'); diff --git a/main/auth/cas/authcas.php b/main/auth/cas/authcas.php index 66a31c29ad..853f83f10d 100755 --- a/main/auth/cas/authcas.php +++ b/main/auth/cas/authcas.php @@ -16,7 +16,7 @@ require_once(api_get_path(SYS_PATH).'main/auth/external_login/functions.inc.php' * **/ function cas_configured() { - global $cas_auth_ver, $cas_auth_server, $cas_auth_port, $cas_auth_uri; + global $cas_auth_ver, $cas_auth_server, $cas_auth_port, $cas_auth_uri; $res = false; if (!empty($cas_auth_ver) && !empty($cas_auth_server) && !empty($cas_auth_port)) { $res = true; @@ -33,7 +33,7 @@ function cas_configured() { function cas_is_authenticated() { - global $cas_auth_ver, $cas_auth_server, $cas_auth_port, $cas_auth_uri; + global $cas_auth_ver, $cas_auth_server, $cas_auth_port, $cas_auth_uri; global $PHPCAS_CLIENT; global $logout; @@ -42,13 +42,13 @@ function cas_is_authenticated() } - if (!is_object($PHPCAS_CLIENT) ) + if (!is_object($PHPCAS_CLIENT) ) { phpCAS::client($cas_auth_ver,$cas_auth_server,$cas_auth_port,$cas_auth_uri); phpCAS::setNoCasServerValidation(); } - $auth = phpCAS::checkAuthentication(); - + $auth = phpCAS::checkAuthentication(); + if ($auth) { $login= trim(phpCAS::getUser()); /* @@ -85,7 +85,7 @@ function cas_is_authenticated() if (!$logout){ // get user info from username $tab_user_info = UserManager::get_user_info($login); - + // user found in the chamilo database if (is_array($tab_user_info)) { // if option is on we update user automatically from ldap server @@ -105,13 +105,13 @@ function cas_is_authenticated() // if option is on we can ADD user automatically from ldap server or by modify own profil $user_added = false; switch (api_get_setting("cas_add_user_activate")) { - case PLATFORM_AUTH_SOURCE : + case PLATFORM_AUTH_SOURCE : // user will have to modify firstname, lastname, email in chamilo profil edit $userdata = get_lang("EditInProfil"); UserManager::create_user($userdata, $userdata, '5', $userdata, $login, 'casplaceholder', '','','','',CAS_AUTH_SOURCE); $user_added = $login; break; - case LDAP_AUTH_SOURCE : + case LDAP_AUTH_SOURCE : // user info are read from ldap connexion // get user info from ldap server // user has already been authenticated by CAS @@ -137,8 +137,8 @@ function cas_is_authenticated() // "FROM $user_table ". // "WHERE username = '$login' "; // -// $result = api_sql_query($sql,__FILE__,__LINE__); -// if(mysql_num_rows($result) == 0) { +// $result = Database::query($sql,__FILE__,__LINE__); +// if(mysql_num_rows($result) == 0) { // require_once(api_get_path(SYS_PATH).'main/inc/lib/usermanager.lib.php'); // $rnumber=rand(0,256000); // UserManager::create_user($firstName, $lastName, $status, $email, $login, md5('casplaceholder'.$rnumber), $official_code='',$language='',$phone='',$picture_uri='',$auth_source = PLATFORM_AUTH_SOURCE); @@ -153,8 +153,8 @@ function cas_is_authenticated() // } return $login; } - else - { + else + { return false; } } diff --git a/main/auth/inscription.php b/main/auth/inscription.php index b68efbabe0..de0e856d7a 100755 --- a/main/auth/inscription.php +++ b/main/auth/inscription.php @@ -30,7 +30,7 @@ if (!empty($_SESSION['user_language_choice'])) { } elseif (!empty($_SESSION['_user']['language'])) { $user_selected_language = $_SESSION['_user']['language']; } else { - $user_selected_language = get_setting('platformLanguage'); + $user_selected_language = api_get_setting('platformLanguage'); } $form = new FormValidator('registration'); diff --git a/main/auth/shibboleth/app/shibboleth.class.php b/main/auth/shibboleth/app/shibboleth.class.php index b5a81ba20e..4d54a7b59a 100755 --- a/main/auth/shibboleth/app/shibboleth.class.php +++ b/main/auth/shibboleth/app/shibboleth.class.php @@ -98,7 +98,7 @@ class Shibboleth /* * Tests if the user tried to login directly in a protected course before to come here * (this variable could be set in the modified code of /chamilo/inc/lib/main_api.lib.php) - * + * * Note: * this part was added to give the possibility to access Chamilo directly on a course URL from a link diplayed in a portal. * This is not a direct Shibboleth related functionnality, but this could be used in a shibbolethized @@ -109,7 +109,7 @@ class Shibboleth */ } if ($url) { - //needed to log the user in his courses. Normally it is done by visiting /chamilo/index.php + //needed to log the user in his courses. Normally it is done by visiting /chamilo/index.php // $include_path = api_get_path(INCLUDE_PATH); // require("$include_path/local.inc.php"); // @@ -160,7 +160,7 @@ class Shibboleth /** * Infer the rights/status the user can have in Chamilo based on his affiliation attribute * - * @param ShibbolethUser $user + * @param ShibbolethUser $user * @return The Chamilo user status, one of TEACHER, STUDENT or UNKNOWN */ public static function infer_user_status($user) @@ -200,9 +200,9 @@ class Shibboleth /** * Return true if the user can ask for a greater status than student. * This happens for staff members. - * + * * @param ShibbolethUser $user - * @return boolean + * @return boolean */ public static function infer_status_request($user) { @@ -242,9 +242,9 @@ class Shibboleth $signagure = << $value) { - $last_post_info_of_forum = get_last_post_information($key, is_allowed_to_edit()); + $last_post_info_of_forum = get_last_post_information($key, api_is_allowed_to_edit()); $forum_list[$key]['last_post_id'] = $last_post_info_of_forum['last_post_id']; $forum_list[$key]['last_poster_id'] = $last_post_info_of_forum['last_poster_id']; $forum_list[$key]['last_post_date'] = $last_post_info_of_forum['last_post_date']; diff --git a/main/forum/viewforum.php b/main/forum/viewforum.php index 4d39f048d1..fb23ce9c06 100755 --- a/main/forum/viewforum.php +++ b/main/forum/viewforum.php @@ -381,7 +381,7 @@ if (is_array($threads)) { echo ''.Display::tag('span', api_get_person_name($row['firstname'], $row['lastname']), array("title"=>api_htmlentities($poster_username, ENT_QUOTES))).''; } - $last_post_info = get_last_post_by_thread($row['c_id'], $row['thread_id'], $row['forum_id'], is_allowed_to_edit()); + $last_post_info = get_last_post_by_thread($row['c_id'], $row['thread_id'], $row['forum_id'], api_is_allowed_to_edit()); $last_post = null; if ($last_post_info) { diff --git a/main/inc/lib/api.lib.php b/main/inc/lib/api.lib.php index a2f3b4c175..9bfb3d36aa 100644 --- a/main/inc/lib/api.lib.php +++ b/main/inc/lib/api.lib.php @@ -4326,14 +4326,6 @@ function api_string_2_boolean($string) { return false; } -/** - * Too keep BC - * @deprecated use api_string_2_boolean - */ -function string_2_boolean($string) { - return api_string_2_boolean($string); -} - /** * Determines the number of plugins installed for a given location */ @@ -4342,21 +4334,6 @@ function api_number_of_plugins($location) { return isset($_plugins[$location]) && is_array($_plugins[$location]) ? count($_plugins[$location]) : 0; } -/** - * Including the necessary plugins. - * @author Patrick Cool , Ghent University - * @deprecated use AppPlugin::get_all_plugin_contents_by_region function - */ -function api_plugin($location) { - global $_plugins; - if (isset($_plugins[$location]) && is_array($_plugins[$location])) { - foreach ($_plugins[$location] as $this_plugin) { - include api_get_path(SYS_PLUGIN_PATH)."$this_plugin/index.php"; - } - } - return false; -} - /** * Checks to see wether a certain plugin is installed. * @return boolean true if the plugin is installed, false otherwise. @@ -6018,159 +5995,6 @@ function shorten($input, $length = 15, $encoding = null) { return api_trunc_str($input, $length, '...', false, $encoding); } -/** - * DEPRECATED, use api_get_setting instead - */ -function get_setting($variable, $key = NULL) { - global $_setting; - return api_get_setting($variable, $key); -} - -/** - * deprecated: use api_is_allowed_to_edit() instead - */ -function is_allowed_to_edit() { - return api_is_allowed_to_edit(); -} - -/** - * deprecated: 19-SEP-2009: Use api_get_path(TO_SYS, $url) instead. - */ -function api_url_to_local_path($url) { - return api_get_path(TO_SYS, $url); -} - -/** - * @deprecated 27-SEP-2009: Use Database::store_result($result) instead. - */ -function api_store_result($result) { - return Database::store_result($result); -} - -/** - * @deprecated 28-SEP-2009: Use Database::query($query, $file, $line) instead. - */ -function api_sql_query($query, $file = '', $line = 0) { - return Database::query($query, $file, $line); -} - -/** - * @deprecated 25-JAN-2010: See api_mail() and api_mail_html(), mail.lib.inc.php - * - * Send an email. - * - * Wrapper function for the standard php mail() function. Change this function - * to your needs. The parameters must follow the same rules as the standard php - * mail() function. Please look at the documentation on http://php.net/manual/en/function.mail.php - * @param string $to - * @param string $subject - * @param string $message - * @param string $additional_headers - * @param string $additionalParameters - * @author Ivan Tcholakov, 04-OCT-2009, a reworked version of this function. - * @link http://www.dokeos.com/forum/viewtopic.php?t=15557 - */ -function api_send_mail($to, $subject, $message, $additional_headers = null, $additionalParameters = array()) -{ - if (empty($platform_email['SMTP_FROM_NAME'])) { - $platform_email['SMTP_FROM_NAME'] = api_get_person_name( - api_get_setting('administratorName'), - api_get_setting('administratorSurname'), - null, - PERSON_NAME_EMAIL_ADDRESS - ); - } - - if (empty($platform_email['SMTP_FROM_EMAIL'])) { - $platform_email['SMTP_FROM_EMAIL'] = api_get_setting('emailAdministrator'); - } - - $matches = array(); - if (preg_match('/([^<]*)<(.+)>/si', $to, $matches)) { - $recipient_name = trim($matches[1]); - $recipient_email = trim($matches[2]); - } else { - $recipient_name = ''; - $recipient_email = trim($to); - } - - $sender_name = ''; - $sender_email = ''; - $extra_headers = $additional_headers; - - // Regular expression to test for valid email address. - // This should actually be revised to use the complete RFC3696 description. - // http://tools.ietf.org/html/rfc3696#section-3 - //$regexp = "^[0-9a-z_\.+-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z][0-9a-z-]*[0-9a-z]\.)+[a-z]{2,3})$"; // Deprecated, 13-OCT-2010. - - $mail = new PHPMailer(); - $mail->CharSet = $platform_email['SMTP_CHARSET']; - $mail->Mailer = $platform_email['SMTP_MAILER']; - $mail->Host = $platform_email['SMTP_HOST']; - $mail->Port = $platform_email['SMTP_PORT']; - - if ($platform_email['SMTP_AUTH']) { - $mail->SMTPAuth = 1; - $mail->Username = $platform_email['SMTP_USER']; - $mail->Password = $platform_email['SMTP_PASS']; - } - - $mail->Priority = 3; // 5 = low, 1 = high - $mail->AddCustomHeader('Errors-To: '.$platform_email['SMTP_FROM_EMAIL']); - $mail->IsHTML(0); - $mail->SMTPKeepAlive = true; - - // Attachments. - // $mail->AddAttachment($path); - // $mail->AddAttachment($path, $filename); - - if ($sender_email != '') { - $mail->From = $sender_email; - $mail->Sender = $sender_email; - } else { - $mail->From = $platform_email['SMTP_FROM_EMAIL']; - $mail->Sender = $platform_email['SMTP_FROM_EMAIL']; - } - - if ($sender_name != '') { - $mail->FromName = $sender_name; - } else { - $mail->FromName = $platform_email['SMTP_FROM_NAME']; - } - $mail->Subject = $subject; - $mail->Body = $message; - - // Only valid address are to be accepted. - if (api_valid_email($recipient_email)) { - $mail->AddAddress($recipient_email, $recipient_name); - } - - if ($extra_headers != '') { - $mail->AddCustomHeader($extra_headers); - } - - // Send mail. - if (!$mail->Send()) { - return 0; - } - - $plugin = new AppPlugin(); - $installedPluginsList = $plugin->getInstalledPluginListObject(); - foreach ($installedPluginsList as $installedPlugin) { - if ($installedPlugin->isMailPlugin and array_key_exists("smsType", $additionalParameters)) { - $className = str_replace("Plugin", "", get_class($installedPlugin)); - $smsObject = new $className; - $smsObject->send($additionalParameters); - } - } - - // Clear all the addresses. - $mail->ClearAddresses(); - return 1; -} - -/* END OF DEPRECATED FUNCTIONS SECTION */ - /** * Function used to protect a "global" admin script. diff --git a/main/inc/lib/banner.lib.php b/main/inc/lib/banner.lib.php index 471866da6b..ee5e7389dd 100755 --- a/main/inc/lib/banner.lib.php +++ b/main/inc/lib/banner.lib.php @@ -378,7 +378,7 @@ function return_menu() { } elseif (!empty($_SESSION['_user']['language'])) { $lang = $_SESSION['_user']['language']; } else { - $lang = get_setting('platformLanguage'); + $lang = api_get_setting('platformLanguage'); } //Preparing home folder for multiple urls diff --git a/main/inc/lib/course_request.lib.php b/main/inc/lib/course_request.lib.php index 8370c9d5a1..282b954325 100755 --- a/main/inc/lib/course_request.lib.php +++ b/main/inc/lib/course_request.lib.php @@ -160,7 +160,7 @@ class CourseRequestManager $sender_name_teacher = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS); $sender_email_teacher = $user_info['mail']; $recipient_name_admin = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS); - $recipient_email_admin = get_setting('emailAdministrator'); + $recipient_email_admin = api_get_setting('emailAdministrator'); $userInfo = api_get_user_info($user_id); @@ -477,7 +477,7 @@ class CourseRequestManager $email_body .= "\n".get_lang('CourseRequestLegalNote', null, $email_language)."\n"; $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS); - $sender_email = get_setting('emailAdministrator'); + $sender_email = api_get_setting('emailAdministrator'); $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS); $recipient_email = $user_info['mail']; $extra_headers = 'Bcc: '.$sender_email; @@ -555,7 +555,7 @@ class CourseRequestManager $email_body .= "\n".get_lang('CourseRequestLegalNote', null, $email_language)."\n"; $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS); - $sender_email = get_setting('emailAdministrator'); + $sender_email = api_get_setting('emailAdministrator'); $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS); $recipient_email = $user_info['mail']; $extra_headers = 'Bcc: '.$sender_email; @@ -632,7 +632,7 @@ class CourseRequestManager $email_body .= "\n".get_lang('CourseRequestLegalNote', null, $email_language)."\n"; $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS); - $sender_email = get_setting('emailAdministrator'); + $sender_email = api_get_setting('emailAdministrator'); $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS); $recipient_email = $user_info['mail']; $extra_headers = 'Bcc: '.$sender_email; diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php index 6298f12853..170f5b9686 100755 --- a/main/inc/lib/sessionmanager.lib.php +++ b/main/inc/lib/sessionmanager.lib.php @@ -1604,7 +1604,7 @@ class SessionManager if (is_array($user_list) && count($user_list) > 0) { foreach ($user_list as $user_id) { if (!in_array($user_id, $existingUsers)) { - $subject = '[' . get_setting('siteName') . '] ' . get_lang('YourReg') . ' ' . get_setting('siteName'); + $subject = '[' . api_get_setting('siteName') . '] ' . get_lang('YourReg') . ' ' . api_get_setting('siteName'); $user_info = api_get_user_info($user_id); $content = get_lang('Dear') . " " . stripslashes($user_info['complete_name']) . ",\n\n" . sprintf(get_lang('YouAreRegisterToSessionX'), $session_name) . " \n\n" . get_lang('Address') . " " . get_setting('siteName') . " " . get_lang('Is') . " : " . api_get_path(WEB_PATH) . "\n\n" . get_lang('Problem') . "\n\n" . get_lang('SignatureFormula') . ",\n\n" . get_setting('administratorName') . " " . get_setting('administratorSurname') . "\n" . get_lang('Manager') . " " . get_setting('siteName') . "\nT. " . get_setting('administratorTelephone') . "\n" . get_lang('Email') . " : " . get_setting('emailAdministrator'); MessageManager::send_message( diff --git a/plugin/buycourses/src/inscription.php b/plugin/buycourses/src/inscription.php index f414759bfe..503b66458c 100644 --- a/plugin/buycourses/src/inscription.php +++ b/plugin/buycourses/src/inscription.php @@ -19,7 +19,7 @@ if (!empty($_SESSION['user_language_choice'])) { } elseif (!empty($_SESSION['_user']['language'])) { $user_selected_language = $_SESSION['_user']['language']; } else { - $user_selected_language = get_setting('platformLanguage'); + $user_selected_language = api_get_setting('platformLanguage'); } $form = new FormValidator('registration'); diff --git a/plugin/clockworksms/lib/clockworksms.lib.php b/plugin/clockworksms/lib/clockworksms.lib.php index f42924233d..4fd7bb281c 100755 --- a/plugin/clockworksms/lib/clockworksms.lib.php +++ b/plugin/clockworksms/lib/clockworksms.lib.php @@ -49,7 +49,7 @@ class Clockworksms implements SmsPluginLibraryInterface null, PERSON_NAME_EMAIL_ADDRESS ); - $email_form = get_setting('emailAdministrator'); + $email_form = api_get_setting('emailAdministrator'); $emailsubject = 'Clockworksms error'; $emailbody = 'Key cannot be blank'; $sender_name = $recipient_name; diff --git a/plugin/search_course/lib/search_course_widget.class.php b/plugin/search_course/lib/search_course_widget.class.php index bba3d9ca71..806ece533b 100755 --- a/plugin/search_course/lib/search_course_widget.class.php +++ b/plugin/search_course/lib/search_course_widget.class.php @@ -354,9 +354,8 @@ EOT; EOT; $result = array(); - $resultset = api_sql_query($sql, __FILE__, __LINE__); - while ($row = Database::fetch_array($resultset)) - { + $resultset = Database::query($sql); + while ($row = Database::fetch_array($resultset)) { $code = $row['code']; $result[$code] = array( 'code' => $code, @@ -397,7 +396,7 @@ EOT; AND course_rel_user.user_id = $user_id ORDER BY course_rel_user.sort ASC"; $result = array(); - $resultset = api_sql_query($sql_select_courses); + $resultset = Database::query($sql_select_courses); while ($row = Database::fetch_array($resultset)) { $code = $row['k']; $result[$code] = array( diff --git a/tests/main/inc/lib/main_api.lib.test.php b/tests/main/inc/lib/main_api.lib.test.php index 5d0cc3f2fc..1ea64a1aea 100755 --- a/tests/main/inc/lib/main_api.lib.test.php +++ b/tests/main/inc/lib/main_api.lib.test.php @@ -494,16 +494,6 @@ class TestMainApi extends UnitTestCase { $this->assertTrue($cssdir); } - function testApiSendMail(){ - $to= 'chamilotest@beeznest.com'; - $subject='Hello'; - $message='test message'; - $res=api_send_mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null); - $this->assertTrue(is_numeric($res)); - //var_dump($res); - //var_dump($send_mail); - } - function testApiMaxSortValue(){ $user_course_category=1; $user_id =1; @@ -527,15 +517,6 @@ class TestMainApi extends UnitTestCase { $this->assertTrue($_plugins[$location]); } - function testApiPlugin(){ - global $_plugins; - $location=2; - $_plugins[$location]=1; - $res1 = api_plugin($location); - $this->assertFalse($res1); - $this->assertTrue($_plugins[$location]); - } - function testApiIsPluginInstalled(){ $plugin_name = false; $plugin_list = true; From 4935f93d7763d2974bea05b5930b48c627032c8f Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 08:55:45 +0200 Subject: [PATCH 081/159] Replace id with real_id. Because "id" is the "course code" ... --- main/admin/session_course_user_list.php | 2 +- main/admin/session_list.php | 3 +- main/auth/courses_controller.php | 4 +- main/chat/chat_whoisonline.php | 2 +- main/gradebook/lib/GradebookUtils.php | 2 +- main/gradebook/lib/be/category.class.php | 2 +- main/gradebook/lib/be/evaluation.class.php | 2 +- main/gradebook/lib/be/exerciselink.class.php | 6 +-- main/gradebook/lib/fe/displaygradebook.php | 2 +- main/inc/ajax/course.ajax.php | 4 +- main/inc/lib/api.lib.php | 2 +- main/inc/lib/auth.lib.php | 47 +++++++++++--------- main/inc/lib/course.lib.php | 29 ++++++------ main/inc/lib/document.lib.php | 2 +- main/inc/lib/myspace.lib.php | 4 +- main/inc/lib/tracking.lib.php | 2 +- main/inc/lib/usermanager.lib.php | 2 +- main/webservices/registration.soap.php | 5 ++- 18 files changed, 65 insertions(+), 57 deletions(-) diff --git a/main/admin/session_course_user_list.php b/main/admin/session_course_user_list.php index 76809db05a..37670da4cb 100755 --- a/main/admin/session_course_user_list.php +++ b/main/admin/session_course_user_list.php @@ -24,7 +24,7 @@ if (empty($id_session )) { $course_code = Database::escape_string(trim($_GET['course_code'])); $courseInfo = api_get_course_info($course_code); -$courseId = $courseInfo['id']; +$courseId = $courseInfo['real_id']; $page = isset($_GET['page']) ? intval($_GET['page']) : null; $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null; diff --git a/main/admin/session_list.php b/main/admin/session_list.php index da7ebc2de4..41b3f4f890 100755 --- a/main/admin/session_list.php +++ b/main/admin/session_list.php @@ -49,8 +49,9 @@ $courseId = isset($_GET['course_id']) ? $_GET['course_id'] : null; if (!empty($courseId)) { $courseInfo = api_get_course_info_by_id($courseId); $parents = getParentsToString($courseInfo['categoryCode']); - $courseList[] = array('id' => $courseInfo['id'], 'text' => $parents.$courseInfo['title']); + $courseList[] = array('id' => $courseInfo['code'], 'text' => $parents.$courseInfo['title']); } + $sessionFilter->addElement('select_ajax', 'course_name', get_lang('SearchCourse'), null, array('url' => $url, 'defaults' => $courseList)); $url = api_get_self(); $actions = ' diff --git a/main/auth/courses_controller.php b/main/auth/courses_controller.php index 5070c0fec0..5cf4ddaea6 100755 --- a/main/auth/courses_controller.php +++ b/main/auth/courses_controller.php @@ -246,9 +246,9 @@ class CoursesController public function change_course_category($course_code, $category_id) { $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; - $result = $this->model->store_changecoursecategory($courseId, $category_id); + $result = $this->model->updateCourseCategory($courseId, $category_id); $message = ''; if ($result) { $message = get_lang('EditCourseCategorySucces'); diff --git a/main/chat/chat_whoisonline.php b/main/chat/chat_whoisonline.php index d9efa3eb83..86f38f164d 100755 --- a/main/chat/chat_whoisonline.php +++ b/main/chat/chat_whoisonline.php @@ -56,7 +56,7 @@ if (!empty($course)) { t1.user_id=t2.user_id AND t3.user_id=t2.user_id AND t3.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND - t3.c_id = '".$courseInfo['id']."' AND + t3.c_id = '".$courseInfo['real_id']."' AND t2.last_connection>'".$date_inter."' $extra_condition ORDER BY username"; $result = Database::query($query); diff --git a/main/gradebook/lib/GradebookUtils.php b/main/gradebook/lib/GradebookUtils.php index ddca492fc4..da75c3f7d2 100644 --- a/main/gradebook/lib/GradebookUtils.php +++ b/main/gradebook/lib/GradebookUtils.php @@ -954,7 +954,7 @@ class GradebookUtils $current_session = api_get_session_id(); $courseCode = Database::escape_string($courseCode); $courseInfo = api_get_course_info($courseCode); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; if (!empty($current_session)) { $sql = "SELECT user.user_id, user.username, lastname, firstname, official_code diff --git a/main/gradebook/lib/be/category.class.php b/main/gradebook/lib/be/category.class.php index c85e9c1abd..84764db1fa 100755 --- a/main/gradebook/lib/be/category.class.php +++ b/main/gradebook/lib/be/category.class.php @@ -776,7 +776,7 @@ class Category implements GradebookItem $parent = Category::load($parent); $code = $parent[0]->get_course_code(); $courseInfo = api_get_course_info($code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; if (isset($code) && $code != '0') { $main_course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER); $sql .= ' AND user_id IN ( diff --git a/main/gradebook/lib/be/evaluation.class.php b/main/gradebook/lib/be/evaluation.class.php index d8dcd26f28..5db1937e2e 100755 --- a/main/gradebook/lib/be/evaluation.class.php +++ b/main/gradebook/lib/be/evaluation.class.php @@ -442,7 +442,7 @@ class Evaluation implements GradebookItem $parent = Category::load($parent); $code = $parent[0]->get_course_code(); $courseInfo = api_get_course_info($code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; if (isset($code) && $code != '0') { $main_course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER); diff --git a/main/gradebook/lib/be/exerciselink.class.php b/main/gradebook/lib/be/exerciselink.class.php index 9af1eab7ef..ff3c0c231d 100755 --- a/main/gradebook/lib/be/exerciselink.class.php +++ b/main/gradebook/lib/be/exerciselink.class.php @@ -305,10 +305,10 @@ class ExerciseLink extends AbstractLink $user_id = api_get_user_id(); $course_code = $this->get_course_code(); $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; - $status_user=api_get_status_of_user_in_course($user_id, $courseId); - $session_id =api_get_session_id(); + $status_user = api_get_status_of_user_in_course($user_id, $courseId); + $session_id = api_get_session_id(); $url = api_get_path(WEB_CODE_PATH).'gradebook/exercise_jump.php?session_id='.$session_id.'&cidReq='.$this->get_course_code().'&gradebook=view&exerciseId='.$this->get_ref_id().'&type='.$this->get_type(); if ((!api_is_allowed_to_edit() && $this->calc_score(api_get_user_id()) == null) || $status_user!=1) { diff --git a/main/gradebook/lib/fe/displaygradebook.php b/main/gradebook/lib/fe/displaygradebook.php index 3922bee2f2..a0620eac59 100755 --- a/main/gradebook/lib/fe/displaygradebook.php +++ b/main/gradebook/lib/fe/displaygradebook.php @@ -304,7 +304,7 @@ class DisplayGradebook $user_id = api_get_user_id(); $course_code = $my_category['course_code']; $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; $status_user = api_get_status_of_user_in_course($user_id, $courseId); diff --git a/main/inc/ajax/course.ajax.php b/main/inc/ajax/course.ajax.php index 9c3820f913..278ef93483 100755 --- a/main/inc/ajax/course.ajax.php +++ b/main/inc/ajax/course.ajax.php @@ -84,9 +84,9 @@ switch ($action) { } $results[] = array( - 'id' => $courseInfo['id'], + 'id' => $courseInfo['code'], 'text' => $title - ); + ); } echo json_encode($results); } else { diff --git a/main/inc/lib/api.lib.php b/main/inc/lib/api.lib.php index 9bfb3d36aa..d116d10b50 100644 --- a/main/inc/lib/api.lib.php +++ b/main/inc/lib/api.lib.php @@ -5350,7 +5350,7 @@ function api_is_course_visible_for_user($userid = null, $cid = null) { $cid = Database::escape_string($cid); $courseInfo = api_get_course_info($cid); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; global $is_platformAdmin; diff --git a/main/inc/lib/auth.lib.php b/main/inc/lib/auth.lib.php index e9f60c2505..9ab7eae920 100755 --- a/main/inc/lib/auth.lib.php +++ b/main/inc/lib/auth.lib.php @@ -168,18 +168,18 @@ class Auth } /** - * stores the changes in a course category (moving a course to a different course category) - * @param string $courseId + * stores the changes in a course category + * (moving a course to a different course category) + * @param int $courseId * @param int Category id * @return bool True if it success */ - public function store_changecoursecategory($courseId, $newcategory) + public function updateCourseCategory($courseId, $newcategory) { $courseId = intval($courseId); $newcategory = intval($newcategory); $current_user = api_get_user_id(); - $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER); $max_sort_value = api_max_sort_value($newcategory, $current_user); $sql = "UPDATE $TABLECOURSUSER SET @@ -239,24 +239,24 @@ class Auth } if (count($target_course) > 0 && count($source_course) > 0) { - - $courseInfo = api_get_course_info($source_course['code']); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; + + $sql = "UPDATE $TABLECOURSUSER + SET sort='" . $target_course['sort'] . "' + WHERE + c_id = '" . $courseId . "' AND + user_id = '" . $current_user_id . "' AND + relation_type<>" . COURSE_RELATION_TYPE_RRHH; + $result1 = Database::query($sql); + + $sql = "UPDATE $TABLECOURSUSER SET sort='" . $source_course['sort'] . "' + WHERE + c_id ='" . $courseId . "' AND + user_id='" . $current_user_id . "' AND + relation_type<>" . COURSE_RELATION_TYPE_RRHH; + $result2 = Database::query($sql); - $sql_update1 = "UPDATE $TABLECOURSUSER - SET sort='" . $target_course['sort'] . "' - WHERE - c_id = '" . $courseId . "' AND - user_id = '" . $current_user_id . "' AND - relation_type<>" . COURSE_RELATION_TYPE_RRHH; - $sql_update2 = "UPDATE $TABLECOURSUSER SET sort='" . $source_course['sort'] . "' - WHERE - c_id ='" . $courseId . "' AND - user_id='" . $current_user_id . "' AND - relation_type<>" . COURSE_RELATION_TYPE_RRHH; - $result1 = Database::query($sql_update2); - $result2 = Database::query($sql_update1); if (Database::affected_rows($result1) && Database::affected_rows($result2)) { $result = true; } @@ -395,13 +395,16 @@ class Auth $result = true; $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; // we check (once again) if the user is not course administrator // because the course administrator cannot unsubscribe himself // (s)he can only delete the course $sql = "SELECT * FROM $tbl_course_user - WHERE user_id='" . $current_user_id . "' AND c_id ='" . $courseId . "' AND status='1' "; + WHERE + user_id='" . $current_user_id . "' AND + c_id ='" . $courseId . "' AND + status='1' "; $result_check = Database::query($sql); $number_of_rows = Database::num_rows($result_check); if ($number_of_rows > 0) { diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php index 5b9128c168..a6643c44d6 100755 --- a/main/inc/lib/course.lib.php +++ b/main/inc/lib/course.lib.php @@ -323,7 +323,7 @@ class CourseManager public static function get_user_in_course_status($user_id, $course_code) { $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; $result = Database::fetch_array( Database::query( @@ -545,7 +545,7 @@ class CourseManager $course_code = Database::escape_string($course_code); $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; $courseCode = $courseInfo['code']; $userCourseCategoryId = intval($userCourseCategoryId); @@ -1010,7 +1010,7 @@ class CourseManager return false; } - $courseId = intval($courseInfo['id']); + $courseId = intval($courseInfo['real_id']); $table = Database::get_main_table(TABLE_MAIN_COURSE_USER); $sql = "SELECT * FROM $table @@ -1051,7 +1051,7 @@ class CourseManager $condition_course = ''; if (isset($course_code)) { $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; $condition_course = ' AND c_id = ' . $courseId; } @@ -1111,15 +1111,17 @@ class CourseManager } $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; $result = Database::query( 'SELECT status FROM ' . Database::get_main_table(TABLE_MAIN_COURSE_USER) . ' WHERE c_id="' . $courseId . '" and user_id="' . $user_id . '"' ); + if (Database::num_rows($result) > 0) { return Database::result($result, 0, 'status') == 1; } + return false; } @@ -1616,15 +1618,16 @@ class CourseManager $course_code = Database::escape_string($course_code); $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; $sql = 'SELECT DISTINCT count(*) as count FROM ' . Database::get_main_table(TABLE_MAIN_USER) . ' as user '; $where = array(); if (!empty($session_id)) { $sql .= ' LEFT JOIN ' . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . ' as session_course_user - ON user.user_id = session_course_user.user_id - AND session_course_user.c_id = "' . $courseId . '" - AND session_course_user.session_id = ' . $session_id; + ON + user.user_id = session_course_user.user_id AND + session_course_user.c_id = "' . $courseId . '" AND + session_course_user.session_id = ' . $session_id; $where[] = ' session_course_user.c_id IS NOT NULL '; } else { @@ -1729,7 +1732,7 @@ class CourseManager $session_id = intval($session_id); $course_code = Database::escape_string($course_code); $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; $students = array(); @@ -3166,7 +3169,7 @@ class CourseManager if (is_array($courses_list)) { foreach ($courses_list as $course_code) { $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; $sql = "INSERT IGNORE INTO $tbl_course_rel_user(c_id, user_id, status, relation_type) VALUES('$courseId', $hr_manager_id, '" . DRH . "', '" . COURSE_RELATION_TYPE_RRHH . "')"; $result = Database::query($sql); @@ -4354,7 +4357,7 @@ class CourseManager $session_id = intval($session_id); $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; // Course legal $enabled = api_get_plugin_setting('courselegal', 'tool_enable'); @@ -4415,7 +4418,7 @@ class CourseManager $session_id = intval($session_id); $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; if (empty($session_id)) { $table = Database::get_main_table(TABLE_MAIN_COURSE_USER); diff --git a/main/inc/lib/document.lib.php b/main/inc/lib/document.lib.php index 7569360600..f53792b7ca 100755 --- a/main/inc/lib/document.lib.php +++ b/main/inc/lib/document.lib.php @@ -3231,7 +3231,7 @@ class DocumentManager $tbl_doc = Database::get_course_table(TABLE_DOCUMENT); $tbl_item_prop = Database::get_course_table(TABLE_ITEM_PROPERTY); - $condition_session = " AND (session_id = '$session_id' OR id_session = '0' )"; + $condition_session = " AND (session_id = '$session_id' OR session_id = '0' )"; $add_folder_filter = null; if (!empty($filter_by_folder)) { diff --git a/main/inc/lib/myspace.lib.php b/main/inc/lib/myspace.lib.php index 3df04cb783..c76cd0dfb3 100644 --- a/main/inc/lib/myspace.lib.php +++ b/main/inc/lib/myspace.lib.php @@ -1239,7 +1239,7 @@ class MySpace { $course_code = $row[0]; $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; // the table header $return = ''; @@ -2110,7 +2110,7 @@ class MySpace while ($row_course = Database::fetch_row($res)) { $course_code = $row_course[0]; $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; $avg_assignments_in_course = $avg_messages_in_course = $nb_students_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = $avg_score_in_exercise = 0; // students directly subscribed to the course diff --git a/main/inc/lib/tracking.lib.php b/main/inc/lib/tracking.lib.php index e18a37cb57..cdb85340b6 100755 --- a/main/inc/lib/tracking.lib.php +++ b/main/inc/lib/tracking.lib.php @@ -3494,7 +3494,7 @@ class Tracking $now = api_get_utc_datetime(); $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; if ($session_id != 0) { $inner = ' INNER JOIN '.$tbl_session_course_user.' session_course_user diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php index d2b565e773..600d71acff 100755 --- a/main/inc/lib/usermanager.lib.php +++ b/main/inc/lib/usermanager.lib.php @@ -4515,7 +4515,7 @@ class UserManager $table_user = Database::get_main_table(TABLE_MAIN_USER); $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER); $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; $courseCode = $courseInfo['code']; if ($session == 0 || is_null($session)) { diff --git a/main/webservices/registration.soap.php b/main/webservices/registration.soap.php index 48c8a3432d..664ca21518 100755 --- a/main/webservices/registration.soap.php +++ b/main/webservices/registration.soap.php @@ -4286,13 +4286,14 @@ function WSUnsubscribeUserFromCourse($params) { $course_code = $row_course[0]; $courseInfo = api_get_course_info($course_code); - $courseId = $courseInfo['id']; + $courseId = $courseInfo['real_id']; if (empty($course_code)) { $results[] = 0; continue; } else { - $sql = "SELECT code FROM $table_course WHERE code ='$course_code' AND visibility = '0'"; + $sql = "SELECT code FROM $table_course + WHERE code ='$course_code' AND visibility = '0'"; $resul = Database::query($sql); $r_check_code = Database::fetch_row($resul); if (!empty($r_check_code[0])) { From 054d7ce7bfdf08e5373f31be8f863f60c24f60ae Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 10:31:30 +0200 Subject: [PATCH 082/159] Use abstract so we can call entities. --- main/install/index.php | 2 +- main/install/install.lib.php | 9 +- .../Migrations/AbstractMigrationChamilo.php | 28 +++ .../Migrations/Schema/v1/Version110.php | 164 +++++++++++++++++- 4 files changed, 197 insertions(+), 6 deletions(-) create mode 100644 src/Chamilo/CoreBundle/Migrations/AbstractMigrationChamilo.php diff --git a/main/install/index.php b/main/install/index.php index 6f4d36ac0f..eb922783c7 100755 --- a/main/install/index.php +++ b/main/install/index.php @@ -652,7 +652,7 @@ if (@$_POST['step2']) { Database::query("ALTER TABLE c_survey MODIFY COLUMN anonymous char(10) NOT NULL default '0'"); // Migrate using the file Version110.php - migrate('110', 1, $dbNameForm, $dbUsernameForm, $dbPassForm, $dbHostForm); + migrate('110', 1, $dbNameForm, $dbUsernameForm, $dbPassForm, $dbHostForm, $manager); include 'update-files-1.9.0-1.10.0.inc.php'; // Only updates the configuration.inc.php with the new version include 'update-configuration.inc.php'; diff --git a/main/install/install.lib.php b/main/install/install.lib.php index af8b52dbbc..f17dae2e13 100755 --- a/main/install/install.lib.php +++ b/main/install/install.lib.php @@ -2492,7 +2492,7 @@ function installSettings( Database::query($sql); } -function migrate($to, $chamiloVersion, $dbNameForm, $dbUsernameForm, $dbPassForm, $dbHostForm) +function migrate($to, $chamiloVersion, $dbNameForm, $dbUsernameForm, $dbPassForm, $dbHostForm, $manager) { $debug = true; // Config doctrine migrations @@ -2520,7 +2520,14 @@ function migrate($to, $chamiloVersion, $dbNameForm, $dbUsernameForm, $dbPassForm $config->setMigrationsDirectory(api_get_path(SYS_PATH).'src/Chamilo/CoreBundle/Migrations/Schema/v'.$chamiloVersion); // Load your migrations $config->registerMigrationsFromDirectory($config->getMigrationsDirectory()); + $migration = new \Doctrine\DBAL\Migrations\Migration($config); + $migrations = $config->getMigrations(); + + foreach ($migrations as $migration) { + $migration->setEntityManager($manager); + } + //$to = 'Version110'; // Retrieve SQL queries that should be run to migrate you schema to $to version, if $to == null - schema will be migrated to latest version $versions = $migration->getSql($to); diff --git a/src/Chamilo/CoreBundle/Migrations/AbstractMigrationChamilo.php b/src/Chamilo/CoreBundle/Migrations/AbstractMigrationChamilo.php new file mode 100644 index 0000000000..a6c2efc0b0 --- /dev/null +++ b/src/Chamilo/CoreBundle/Migrations/AbstractMigrationChamilo.php @@ -0,0 +1,28 @@ +manager = $manager; + } + + /** + * @return EntityManager + */ + public function getEntityManager() + { + return $this->manager; + } +} diff --git a/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php b/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php index d12928026d..1d70c9e06d 100644 --- a/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php +++ b/src/Chamilo/CoreBundle/Migrations/Schema/v1/Version110.php @@ -3,14 +3,14 @@ namespace Chamilo\CoreBundle\Migrations\Schema\v1; -use Doctrine\DBAL\Migrations\AbstractMigration, +use Chamilo\CoreBundle\Migrations\AbstractMigrationChamilo, Doctrine\DBAL\Schema\Schema; /** * Class Core * @package Chamilo\CoreBundle\Migrations\Schema\v1 */ -class Version110 extends AbstractMigration +class Version110 extends AbstractMigrationChamilo { /** * @param Schema $schema @@ -306,7 +306,6 @@ class Version110 extends AbstractMigration $this->addSql("ALTER TABLE c_quiz_question_rel_category DROP PRIMARY KEY"); $this->addSql("ALTER TABLE c_quiz_question_rel_category ADD COLUMN iid int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT"); - $this->addSql("ALTER TABLE session_rel_user MODIFY COLUMN id_session int unsigned DEFAULT NULL"); $this->addSql("ALTER TABLE session_rel_user MODIFY COLUMN id_user int unsigned DEFAULT NULL"); @@ -324,7 +323,6 @@ class Version110 extends AbstractMigration $table = $schema->getTable('c_item_property'); $table->renameColumn('id_session', 'session_id'); - $this->addSql("ALTER TABLE session_rel_user DROP PRIMARY KEY"); $this->addSql("ALTER TABLE session_rel_user ADD COLUMN id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT"); @@ -441,6 +439,12 @@ class Version110 extends AbstractMigration $this->addSql("DELETE FROM settings_options WHERE variable = 'show_glossary_in_extra_tools'"); $schema->renameTable('track_e_exercices', 'track_e_exercises'); + + $this->addSql("UPDATE c_student_publication SET date_of_qualification = NULL WHERE date_of_qualification = '0000-00-00 00:00:00'"); + $this->addSql("UPDATE c_student_publication SET sent_date = NULL WHERE sent_date = '0000-00-00 00:00:00'"); + + $this->addSql("UPDATE c_student_publication_assignment SET expires_on = NULL WHERE expires_on = '0000-00-00 00:00:00'"); + $this->addSql("UPDATE c_student_publication_assignment SET ends_on = NULL WHERE ends_on = '0000-00-00 00:00:00'"); } public function postUp(Schema $schema) @@ -462,6 +466,158 @@ class Version110 extends AbstractMigration $this->addSql("DROP TABLE track_c_providers"); $this->addSql("DROP TABLE track_c_referers"); + // Fix ids + /* + // Fix c_lp_item + $connection = $this->connection; + + $sql = "SELECT * FROM c_lp_item"; + $result = $connection->fetchAll($sql); + foreach ($result as $item) { + $courseId = $item['c_id']; + $iid = $item['iid']; + $ref = $item['ref']; + $sql = null; + + switch ($item['item_type']) { + case TOOL_LINK: + $sql = "SELECT * c_link WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_STUDENTPUBLICATION: + $sql = "SELECT * c_student_publication WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_QUIZ: + $sql = "SELECT * c_quiz WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_DOCUMENT: + $sql = "SELECT * c_document WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_FORUM: + $sql = "SELECT * c_forum_forum WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case 'thread': + $sql = "SELECT * c_forum_thread WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + } + + if (!empty($sql)) { + $sql = "UPDATE c_lp_item SET ref = $newId WHERE iid = $iid"; + $connection->executeQuery($sql); + } + } + + // Fix c_item_property + + $sql = "SELECT * FROM c_item_property"; + $result = $connection->fetchAll($sql); + foreach ($result as $item) { + $courseId = $item['c_id']; + $sessionId = intval($item['session_id']); + $iid = $item['iid']; + $ref = $item['ref']; + $sql = null; + + switch ($item['tool']) { + case TOOL_LINK: + $sql = "SELECT * c_link WHERE c_id = $courseId AND id = $ref "; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_STUDENTPUBLICATION: + $sql = "SELECT * c_student_publication WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_QUIZ: + $sql = "SELECT * c_quiz WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_DOCUMENT: + $sql = "SELECT * c_document WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_FORUM: + $sql = "SELECT * c_forum_forum WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case 'thread': + $sql = "SELECT * c_forum_thread WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + } + + if (!empty($sql)) { + $sql = "UPDATE c_item_property SET ref = $newId WHERE iid = $iid"; + $connection->executeQuery($sql); + } + } + + // Fix gradebook_link + $sql = "SELECT * FROM gradebook_link"; + $result = $connection->fetchAll($sql); + foreach ($result as $item) { + $courseId = $item['c_id']; + $ref = $item['ref_id']; + $sql = null; + + switch ($item['tool']) { + case TOOL_LINK: + $sql = "SELECT * c_link WHERE c_id = $courseId AND id = $ref "; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_STUDENTPUBLICATION: + $sql = "SELECT * c_student_publication WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_QUIZ: + $sql = "SELECT * c_quiz WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_DOCUMENT: + $sql = "SELECT * c_document WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case TOOL_FORUM: + $sql = "SELECT * c_forum_forum WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + case 'thread': + $sql = "SELECT * c_forum_thread WHERE c_id = $courseId AND id = $ref"; + $data = $connection->fetchArray($sql); + $newId = $data['iid']; + break; + } + + if (!empty($sql)) { + $sql = "UPDATE c_item_property SET ref_id = $newId WHERE iid = $iid"; + $connection->executeQuery($sql); + } + } + + + */ + //$this->addSql('ALTER TABLE user DROP COLUMN user_id'); //$this->addSql("UPDATE settings_current SET selected_value = '1.10.0.35' WHERE variable = 'chamilo_database_version'"); From 9d54652cc4db45efc8e3595710dc4598f667832d Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 10:31:48 +0200 Subject: [PATCH 083/159] Remove use of 0000-00-00 00:00:00 --- main/work/work.lib.php | 41 ++++++++++++++++------------------------- 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/main/work/work.lib.php b/main/work/work.lib.php index 4c2b06aae8..d93dbf016b 100755 --- a/main/work/work.lib.php +++ b/main/work/work.lib.php @@ -724,7 +724,7 @@ function display_student_publications_list( if (!empty($homework)) { // use original utc value saved previously to avoid doubling the utc-to-local conversion ($homework['expires_on'] might have been tainted) - $row[] = !empty($utc_expiry_time) && $utc_expiry_time != '0000-00-00 00:00:00' ? api_get_local_time($utc_expiry_time): '-'; + $row[] = !empty($utc_expiry_time) ? api_get_local_time($utc_expiry_time): '-'; } else { $row[] = '-'; } @@ -1399,8 +1399,7 @@ function insert_all_directory_in_course_table($base_work_dir) active = '1', accepted = '1', filetype = 'folder', - post_group_id = '".$group_id."', - sent_date = '0000-00-00 00:00:00' "; + post_group_id = '".$group_id."'"; Database::query($sql); } } @@ -1755,7 +1754,7 @@ function getWorkListStudent( continue; } $work['type'] = Display::return_icon('work.png'); - $work['expires_on'] = $work['expires_on'] == '0000-00-00 00:00:00' ? null : api_get_local_time($work['expires_on']); + $work['expires_on'] = empty($work['expires_on']) ? null : api_get_local_time($work['expires_on']); if (empty($work['title'])) { $work['title'] = basename($work['url']); @@ -1869,7 +1868,7 @@ function getWorkListTeacher( while ($work = Database::fetch_array($result, 'ASSOC')) { $workId = $work['id']; $work['type'] = Display::return_icon('work.png'); - $work['expires_on'] = $work['expires_on'] == '0000-00-00 00:00:00' ? null : api_get_local_time($work['expires_on']); + $work['expires_on'] = empty($work['expires_on']) ? null : api_get_local_time($work['expires_on']); $totalUsers = getStudentSubscribedToWork( $workId, @@ -2329,7 +2328,6 @@ function get_work_user_list( $time_expires = api_strtotime($work_assignment['expires_on'], 'UTC'); if (!empty($work_assignment['expires_on']) && - $work_assignment['expires_on'] != '0000-00-00 00:00:00' && $time_expires && ($time_expires < api_strtotime($work['sent_date'], 'UTC'))) { $add_string = Display::label(get_lang('Expired'), 'important'); } @@ -3667,14 +3665,10 @@ function getWorkDateValidationStatus($homework) { if (!empty($homework)) { - if ($homework['expires_on'] != '0000-00-00 00:00:00' || - $homework['ends_on'] != '0000-00-00 00:00:00' - ) { + if (!empty($homework['expires_on']) || !empty($homework['ends_on'])) { $time_now = time(); - if (!empty($homework['expires_on']) && - $homework['expires_on'] != '0000-00-00 00:00:00' - ) { + if (!empty($homework['expires_on'])) { $time_expires = api_strtotime($homework['expires_on'], 'UTC'); $difference = $time_expires - $time_now; if ($difference < 0) { @@ -3682,17 +3676,13 @@ function getWorkDateValidationStatus($homework) { } } - if (empty($homework['expires_on']) || - $homework['expires_on'] == '0000-00-00 00:00:00' - ) { + if (empty($homework['expires_on'])) { $has_expired = false; } - if (!empty($homework['ends_on']) && - $homework['ends_on'] != '0000-00-00 00:00:00' - ) { - $time_ends = api_strtotime($homework['ends_on'], 'UTC'); - $difference2 = $time_ends - $time_now; + if (!empty($homework['ends_on'])) { + $time_ends = api_strtotime($homework['ends_on'], 'UTC'); + $difference2 = $time_ends - $time_now; if ($difference2 < 0) { $has_ended = true; } @@ -4024,18 +4014,19 @@ function addDir($params, $user_id, $courseInfo, $group_id, $session_id) qualification = '".($params['qualification'] != '' ? Database::escape_string($params['qualification']) : '') ."', parent_id = '', qualificator_id = '', - date_of_qualification = '0000-00-00 00:00:00', weight = '".Database::escape_string($params['weight'])."', session_id = '".$session_id."', allow_text_assignment = '".Database::escape_string($params['allow_text_assignment'])."', contains_file = 0, user_id = '".$user_id."'"; - - Database::query($sql); + Database::query($sql);date_of_qualification // Add the directory $id = Database::insert_id(); + $sql = "UPDATE $work_table SET id = $id WHERE iid = $id"; + Database::query($sql); + if ($id) { // Folder created api_item_property_update( @@ -4171,8 +4162,8 @@ function updatePublicationAssignment($workId, $params, $courseInfo, $groupId) } $qualification = isset($params['qualification']) && !empty($params['qualification']) ? 1 : 0; - $expiryDate = isset($params['enableExpiryDate']) && $params['enableExpiryDate'] == 1 ? api_get_utc_datetime($params['expires_on']) : '0000-00-00 00:00:00'; - $endDate = isset($params['enableEndDate']) && $params['enableEndDate'] == 1 ? api_get_utc_datetime($params['ends_on']) : '0000-00-00 00:00:00'; + $expiryDate = isset($params['enableExpiryDate']) && $params['enableExpiryDate'] == 1 ? api_get_utc_datetime($params['expires_on']) : ''; + $endDate = isset($params['enableEndDate']) && $params['enableEndDate'] == 1 ? api_get_utc_datetime($params['ends_on']) : ''; $data = get_work_assignment_by_id($workId, $course_id); From ae05cd20e33817b44b6462969798cb67a1402529 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 12:29:54 +0200 Subject: [PATCH 084/159] Fix function name. --- main/forum/forumfunction.inc.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/main/forum/forumfunction.inc.php b/main/forum/forumfunction.inc.php index 20b1a9bcf7..25aa43c975 100755 --- a/main/forum/forumfunction.inc.php +++ b/main/forum/forumfunction.inc.php @@ -1,5 +1,6 @@ Date: Fri, 10 Apr 2015 12:30:51 +0200 Subject: [PATCH 085/159] Use bootstrap tab instead of jquery-ui. --- main/document/upload.php | 2 +- main/inc/lib/display.lib.php | 27 +++++++++++++++++++------ main/newscorm/lp_add_item.php | 12 ++++------- main/template/default/layout/footer.tpl | 7 +++++++ 4 files changed, 33 insertions(+), 15 deletions(-) diff --git a/main/document/upload.php b/main/document/upload.php index 873996dc3f..1c2ddfeef9 100755 --- a/main/document/upload.php +++ b/main/document/upload.php @@ -78,8 +78,8 @@ $(function () { return $('
      ' + file.name + '<\/td> ' + file.size + ' <\/td>  ' + file.result + ' <\/td> <\/tr>'); } }); - $('#tabs').tabs(); }); + "; // Variables diff --git a/main/inc/lib/display.lib.php b/main/inc/lib/display.lib.php index 36818b39d9..779a5a38e9 100755 --- a/main/inc/lib/display.lib.php +++ b/main/inc/lib/display.lib.php @@ -1018,21 +1018,36 @@ class Display $lis = ''; $i = 1; foreach ($header_list as $item) { - $item =self::tag('a', $item, array('href'=>'#'.$id.'-'.$i)); - $lis .=self::tag('li', $item, $ul_attributes); + $active = ''; + if ($i == 1) { + $active = ' active'; + } + $item = self::tag('a', $item, array('href'=>'#'.$id.'-'.$i, 'role'=> 'tab')); + $ul_attributes['data-toggle'] = 'tab'; + $ul_attributes['role'] = 'presentation'; + $ul_attributes['class'] = $active; + $lis .= self::tag('li', $item, $ul_attributes); $i++; } - $ul = self::tag('ul',$lis); + $ul = self::tag('ul', $lis, ['class' => 'nav nav-tabs', 'role'=> 'tablist']); $i = 1; $divs = ''; foreach ($content_list as $content) { - $content = self::tag('p',$content); - $divs .=self::tag('div', $content, array('id'=>$id.'-'.$i)); + $active = ''; + if ($i == 1) { + $active = ' active'; + } + $divs .= self::tag('div', $content, array('id'=> $id.'-'.$i, 'class' => 'tab-pane '.$active, 'role' => 'tabpanel')); $i++; } + $attributes['id'] = $id; - $main_div = self::tag('div',$ul.$divs, $attributes); + $attributes['role'] = 'tabpanel'; + $attributes['class'] = 'tab-wrapper'; + + $main_div = self::tag('div', $ul.self::tag('div', $divs, ['class' => 'tab-content']), $attributes); + return $main_div ; } diff --git a/main/newscorm/lp_add_item.php b/main/newscorm/lp_add_item.php index d9be65a53d..e349e346dc 100755 --- a/main/newscorm/lp_add_item.php +++ b/main/newscorm/lp_add_item.php @@ -48,9 +48,6 @@ $(function() { load_cbo($(\'#idParent\').val()); } } - //Loads LP item tabs - - $("#resource_tab").tabs(); $(\'.lp_resource_element\').click(function() { window.location.href = $(\'a\', this).attr(\'href\'); }); @@ -99,14 +96,14 @@ $interbreadcrumb[] = array('url' => api_get_self()."?action=build&lp_id=$learnpa switch ($type) { case 'chapter': - $interbreadcrumb[]= array ('url' => 'lp_controller.php?action=add_item&type=step&lp_id='.$learnPath->get_id(), 'name' => get_lang('NewStep')); - $interbreadcrumb[]= array ('url' => '#', 'name' => get_lang('NewChapter')); + $interbreadcrumb[]= array('url' => 'lp_controller.php?action=add_item&type=step&lp_id='.$learnPath->get_id(), 'name' => get_lang('NewStep')); + $interbreadcrumb[]= array('url' => '#', 'name' => get_lang('NewChapter')); break; case 'document': - $interbreadcrumb[]= array ('url' => 'lp_controller.php?action=add_item&type=step&lp_id='.$learnPath->get_id(), 'name' => get_lang('NewStep')); + $interbreadcrumb[]= array('url' => 'lp_controller.php?action=add_item&type=step&lp_id='.$learnPath->get_id(), 'name' => get_lang('NewStep')); break; default: - $interbreadcrumb[]= array ('url' => '#', 'name' => get_lang('NewStep')); + $interbreadcrumb[]= array('url' => '#', 'name' => get_lang('NewStep')); break; } @@ -194,7 +191,6 @@ if (in_array($message, array('ItemUpdated'))) { } if (isset($new_item_id) && is_numeric($new_item_id)) { - switch ($type) { case 'chapter': echo $learnPath->display_manipulate($new_item_id, $_POST['type']); diff --git a/main/template/default/layout/footer.tpl b/main/template/default/layout/footer.tpl index 365bc729e2..38097a82e5 100755 --- a/main/template/default/layout/footer.tpl +++ b/main/template/default/layout/footer.tpl @@ -90,6 +90,13 @@ $.datepicker.setDefaults($.datepicker.regional["{{ locale }}"]); $.datepicker.regional["local"] = $.datepicker.regional["{{ locale }}"]; + $('.tab-wrapper a').click(function (e) { + e.preventDefault() + $(this).tab('show'); + + //$('#tabs a:first').tab('show') // Select first tab + }) + /** * Advanced options * Usage From 16d222f740630ec43061078cc69d32bff54394ce Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 12:32:03 +0200 Subject: [PATCH 086/159] Format code --- main/admin/user_move_stats.php | 4 ++-- main/document/create_document.php | 11 ++++++----- main/document/document.php | 1 - main/document/edit_document.php | 7 +++++-- main/inc/lib/api.lib.php | 5 +++-- main/newscorm/lp_add.php | 18 ++++++++++-------- main/newscorm/lp_controller.php | 7 +++---- main/work/work.php | 2 ++ 8 files changed, 31 insertions(+), 24 deletions(-) diff --git a/main/admin/user_move_stats.php b/main/admin/user_move_stats.php index 921e457eb6..394addc087 100755 --- a/main/admin/user_move_stats.php +++ b/main/admin/user_move_stats.php @@ -359,8 +359,8 @@ if (isset($_REQUEST['load_ajax'])) { $created_dir = '/'.$created_dir; $now = api_get_utc_datetime(); //Creating directory - $sql_add_publication = "INSERT INTO " . $TBL_STUDENT_PUBLICATION . " SET " . - "url = '".$created_dir."', + $sql_add_publication = "INSERT INTO " . $TBL_STUDENT_PUBLICATION . " SET + url = '".$created_dir."', c_id = $course_id, title = '".$parent_data['title']."', description = '".$parent_data['description']." folder_moved_from_session_id_$origin_session_id ', diff --git a/main/document/create_document.php b/main/document/create_document.php index 274018ad4d..55d88bc266 100755 --- a/main/document/create_document.php +++ b/main/document/create_document.php @@ -182,9 +182,7 @@ if (!is_dir($filepath)) { $to_group_id = 0; if (!$is_certificate_mode) { - $req_gid = null; if (api_is_in_group()) { - $req_gid = '&gidReq='.api_get_group_id(); $interbreadcrumb[] = array ("url" => "../group/group_space.php?".api_get_cidreq(), "name" => get_lang('GroupSpace')); $noPHP_SELF = true; $to_group_id = api_get_group_id(); @@ -193,7 +191,7 @@ if (!$is_certificate_mode) { api_not_allowed(true); } } - $interbreadcrumb[] = array("url" => "./document.php?curdirpath=".urlencode($dir).$req_gid, "name" => get_lang('Documents')); + $interbreadcrumb[] = array("url" => "./document.php?curdirpath=".urlencode($dir)."&".api_get_cidreq(), "name" => get_lang('Documents')); } else { $interbreadcrumb[]= array('url' => '../gradebook/'.$_SESSION['gradebook_dest'], 'name' => get_lang('Gradebook')); } @@ -291,7 +289,9 @@ $folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is // If we are not in the certificates creation, display a folder chooser for the // new document created -if (!$is_certificate_mode && !DocumentManager::is_my_shared_folder($userId, $dir, $current_session_id)) { +if (!$is_certificate_mode && + !DocumentManager::is_my_shared_folder($userId, $dir, $current_session_id) +) { $folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is_allowed_to_edit); $parent_select = $form->addElement('select', 'curdirpath', array(null, get_lang('DestinationDirectory'))); @@ -323,7 +323,8 @@ if (!$is_certificate_mode && !DocumentManager::is_my_shared_folder($userId, $dir } $folder_sql = implode("','", $escaped_folders); - $sql = "SELECT * FROM $doc_table WHERE c_id = $course_id AND filetype='folder' AND path IN ('".$folder_sql."')"; + $sql = "SELECT * FROM $doc_table + WHERE c_id = $course_id AND filetype='folder' AND path IN ('".$folder_sql."')"; $res = Database::query($sql); $folder_titles = array(); while ($obj = Database::fetch_object($res)) { diff --git a/main/document/document.php b/main/document/document.php index a461acc392..179e55f965 100755 --- a/main/document/document.php +++ b/main/document/document.php @@ -1216,7 +1216,6 @@ if ($is_allowed_to_edit || $dirForm = null; - /* CREATE DIRECTORY */ //Only teacher and all users into their group and any user into his/her shared folder if ($is_allowed_to_edit || diff --git a/main/document/edit_document.php b/main/document/edit_document.php index 6b9008e371..01bb04684b 100755 --- a/main/document/edit_document.php +++ b/main/document/edit_document.php @@ -170,7 +170,7 @@ if (!api_is_allowed_to_edit()) { Event::event_access_tool(TOOL_DOCUMENT); //TODO:check the below code and his funcionality -if (!is_allowed_to_edit()) { +if (!api_is_allowed_to_edit()) { if (DocumentManager::check_readonly($course_info, $user_id, $file)) { api_not_allowed(); } @@ -184,13 +184,16 @@ if (isset($_POST['comment'])) { // Fixing the path if it is wrong $comment = Database::escape_string(trim($_POST['comment'])); $title = Database::escape_string(trim($_POST['title'])); - //Just in case see BT#3525 + + // Just in case see BT#3525 if (empty($title)) { $title = $documen_data['title']; } + if (empty($title)) { $title = get_document_title($_POST['filename']); } + if (!empty($document_id)) { $query = "UPDATE $dbTable SET comment='".$comment."', title='".$title."' WHERE c_id = $course_id AND id = ".$document_id; Database::query($query); diff --git a/main/inc/lib/api.lib.php b/main/inc/lib/api.lib.php index d116d10b50..873b979c1c 100644 --- a/main/inc/lib/api.lib.php +++ b/main/inc/lib/api.lib.php @@ -4300,7 +4300,7 @@ function api_max_sort_value($user_course_category, $user_id) WHERE user_id='".intval($user_id)."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." AND - user_course_cat='".Database::escape_string($user_course_category)."'"; + user_course_cat='".intval($user_course_category)."'"; $result_max = Database::query($sql); if (Database::num_rows($result_max) == 1) { $row_max = Database::fetch_array($result_max); @@ -6723,7 +6723,8 @@ function api_is_global_chat_enabled() * @todo Fix tool_visible_by_default_at_creation labels * @todo Add sessionId parameter to avoid using context */ -function api_set_default_visibility($item_id, $tool_id, $group_id = null) { +function api_set_default_visibility($item_id, $tool_id, $group_id = null) +{ $original_tool_id = $tool_id; switch ($tool_id) { diff --git a/main/newscorm/lp_add.php b/main/newscorm/lp_add.php index f146193e7c..6b552535c2 100755 --- a/main/newscorm/lp_add.php +++ b/main/newscorm/lp_add.php @@ -47,19 +47,20 @@ function activate_end_date() { $is_allowed_to_edit = api_is_allowed_to_edit(null, true); -$isStudentView = isset($_REQUEST['isStudentView']) ? $_REQUEST['isStudentView'] : null; -$learnpath_id = isset($_REQUEST['lp_id']) ? $_REQUEST['lp_id'] : null; +$isStudentView = isset($_REQUEST['isStudentView']) ? $_REQUEST['isStudentView'] : null; +$learnpath_id = isset($_REQUEST['lp_id']) ? $_REQUEST['lp_id'] : null; /* MAIN CODE */ // Using the resource linker as a tool for adding resources to the learning path. if ($action == 'add' && $type == 'learnpathitem') { - $htmlHeadXtra[] = ""; + $htmlHeadXtra[] = ""; } if ((!$is_allowed_to_edit) || ($isStudentView)) { //error_log('New LP - User not authorized in lp_add.php'); header('location:lp_controller.php?action=view&lp_id='.$learnpath_id); + exit; } // From here on, we are admin because of the previous condition, so don't check anymore. @@ -68,7 +69,7 @@ if ((!$is_allowed_to_edit) || ($isStudentView)) { - all the functions not available for students - always available in this case (page only shown to admin) */ if (isset($_SESSION['gradebook'])){ - $gradebook = $_SESSION['gradebook']; + $gradebook = $_SESSION['gradebook']; } if (!empty($gradebook) && $gradebook=='view') { @@ -83,7 +84,8 @@ $interbreadcrumb[] = array('url' => 'lp_controller.php?action=list', 'name' => g Display::display_header(get_lang('LearnpathAddLearnpath'), 'Path'); echo ''; Display::display_normal_message(get_lang('AddLpIntro'), false); @@ -95,7 +97,7 @@ if ($_POST AND empty($_REQUEST['lp_name'])) { $form = new FormValidator('lp_add', 'post', 'lp_controller.php'); // Form title -$form->addElement('header', null, get_lang('AddLpToStart')); +$form->addElement('header', get_lang('AddLpToStart')); // Title $form->addElement('text', 'lp_name', api_ucfirst(get_lang('LPName')), array('autofocus' => 'autofocus')); @@ -124,8 +126,8 @@ $form->addElement('html',''); $defaults['activate_start_date_check'] = 1; -$defaults['publicated_on'] = date('Y-m-d 08:00:00'); -$defaults['expired_on'] = date('Y-m-d 08:00:00',time()+86400); +$defaults['publicated_on'] = date('Y-m-d 08:00:00'); +$defaults['expired_on'] = date('Y-m-d 08:00:00',time()+86400); $form->setDefaults($defaults); $form->addButtonCreate(get_lang('CreateLearningPath')); diff --git a/main/newscorm/lp_controller.php b/main/newscorm/lp_controller.php index 320d732a76..cfd19c4566 100755 --- a/main/newscorm/lp_controller.php +++ b/main/newscorm/lp_controller.php @@ -497,16 +497,15 @@ switch ($action) { $_SESSION['post_time'] = $_REQUEST['post_time']; if (isset($_REQUEST['activate_start_date_check']) && $_REQUEST['activate_start_date_check'] == 1) { - $publicated_on = $_REQUEST['publicated_on']; + $publicated_on = $_REQUEST['publicated_on']; } else { $publicated_on = null; } if (isset($_REQUEST['activate_end_date_check']) && $_REQUEST['activate_end_date_check'] == 1) { - $expired_on = $_REQUEST['expired_on']; - $expired_on = $expired_on['Y'].'-'.$expired_on['F'].'-'.$expired_on['d'].' '.$expired_on['H'].':'.$expired_on['i'].':00'; + $expired_on = $_REQUEST['expired_on']; } else { - $expired_on = null; + $expired_on = null; } $new_lp_id = learnpath::add_lp( diff --git a/main/work/work.php b/main/work/work.php index e764163195..f26bb4973d 100755 --- a/main/work/work.php +++ b/main/work/work.php @@ -172,6 +172,7 @@ switch ($action) { $form->addButtonCreate(get_lang('CreateDirectory')); if ($form->validate()) { + $result = addDir( $_POST, $user_id, @@ -179,6 +180,7 @@ switch ($action) { $group_id, $id_session ); + if ($result) { $message = Display::return_message(get_lang('DirectoryCreated'), 'success'); } else { From 7a489632236c74413270b9ec95eafbaf734133c2 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 12:32:54 +0200 Subject: [PATCH 087/159] Fix queries. --- main/inc/lib/course.lib.php | 14 +++++---- main/inc/lib/document.lib.php | 35 +++++++++++++---------- main/user/subscribe_user.php | 54 +++++++++++++++++++++++------------ main/user/user.php | 9 +++--- 4 files changed, 69 insertions(+), 43 deletions(-) diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php index a6643c44d6..43c1b88b51 100755 --- a/main/inc/lib/course.lib.php +++ b/main/inc/lib/course.lib.php @@ -669,7 +669,7 @@ class CourseManager * @return boolean true if subscription succeeds, boolean false otherwise. * @assert ('', '') === false */ - public static function add_user_to_course($user_id, $course_code, $status = STUDENT) + public static function add_user_to_course($user_id, $course_code, $status = STUDENT, $userCourseCategoryId = 0) { $debug = false; $user_table = Database::get_main_table(TABLE_MAIN_USER); @@ -723,7 +723,8 @@ class CourseManager 'c_id' => $courseId, 'user_id' => $user_id, 'status' => $status, - 'sort' => $max_sort + 1 + 'sort' => $max_sort + 1, + 'user_course_cat' => $userCourseCategoryId ]; $insertId = Database::insert($course_user_table, $params); @@ -3743,8 +3744,10 @@ class CourseManager while ($row = Database::fetch_array($result)) { // We simply display the title of the category. $params = array( - 'icon' => Display::return_icon('folder_yellow.png', api_htmlentities($row['title']), array(), - ICON_SIZE_LARGE), + 'icon' => Display::return_icon( + 'folder_yellow.png', + api_htmlentities($row['title']), array(), ICON_SIZE_LARGE + ), 'title' => $row['title'], 'class' => 'table_user_course_category' ); @@ -3759,6 +3762,7 @@ class CourseManager // Step 2: We display the course without a user category. $courseInCategory = self:: display_courses_in_category(0, $load_dirs); + $html .= $courseInCategory['html']; $courseCount += $courseInCategory['course_count']; @@ -3809,7 +3813,7 @@ class CourseManager course.id = course_rel_user.c_id AND url.c_id = course.id AND course_rel_user.user_id = '" . $user_id . "' AND - course_rel_user.user_course_cat='" . $user_category_id . "' + course_rel_user.user_course_cat = '" . $user_category_id . "' $without_special_courses "; // If multiple URL access mode is enabled, only fetch courses diff --git a/main/inc/lib/document.lib.php b/main/inc/lib/document.lib.php index f53792b7ca..c6e13b40e2 100755 --- a/main/inc/lib/document.lib.php +++ b/main/inc/lib/document.lib.php @@ -3184,7 +3184,7 @@ class DocumentManager $overwrite_url = null, $showInvisibleFiles = false, $showOnlyFolders = false, - $folderId = 0 + $folderId = false ) { if (empty($course_info['real_id']) || empty($course_info['code']) || !is_array($course_info)) { return ''; @@ -3231,7 +3231,7 @@ class DocumentManager $tbl_doc = Database::get_course_table(TABLE_DOCUMENT); $tbl_item_prop = Database::get_course_table(TABLE_ITEM_PROPERTY); - $condition_session = " AND (session_id = '$session_id' OR session_id = '0' )"; + $condition_session = " AND (last.session_id = '$session_id' OR last.session_id = '0' )"; $add_folder_filter = null; if (!empty($filter_by_folder)) { @@ -3261,7 +3261,8 @@ class DocumentManager } } - if ($folderId !== 0) { + $parentData = []; + if ($folderId !== false) { $parentData = self::get_document_data_by_id($folderId, $course_info['code']); if (!empty($parentData)) { $cleanedPath = $parentData['path']; @@ -3285,7 +3286,6 @@ class DocumentManager } $levelCondition = null; - if ($folderId === false) { $levelCondition = " AND docs.path NOT LIKE'/%/%'"; } @@ -3334,6 +3334,7 @@ class DocumentManager // If you want to debug it, I advise you to do "echo" on the eval statements. $newResources = array(); + if (!empty($resources) && $user_in_course) { foreach ($resources as $resource) { $is_visible = self::is_visible_by_id( @@ -3351,16 +3352,20 @@ class DocumentManager } $label = get_lang('Documents'); + + $documents = []; if ($folderId === false) { $documents[$label] = array( 'id' => 0, 'files' => $newResources ); } else { - $documents[$parentData['title']] = array( - 'id' => intval($folderId), - 'files' => $newResources - ); + if (!empty($parentData)) { + $documents[$parentData['title']] = array( + 'id' => intval($folderId), + 'files' => $newResources + ); + } } $write_result = self::write_resources_tree( @@ -3618,7 +3623,6 @@ class DocumentManager } $return .= ''; - $return .= ' '; $return .= ''.$title.''; $return .= ''; @@ -5768,15 +5772,16 @@ class DocumentManager public static function create_dir_form($dirId) { global $document_id; - $form = new FormValidator('create_dir_form', 'post', api_get_self().'?'.api_get_cidreq(), '', null, false); + $form = new FormValidator('create_dir_form', 'post', api_get_self().'?'.api_get_cidreq()); $form->addElement('hidden', 'create_dir', 1); $form->addElement('hidden', 'dir_id', intval($document_id)); $form->addElement('hidden', 'id', intval($dirId)); - $form->addElement('header', '', get_lang('CreateDir')); - $form->addElement('text', 'dirname', get_lang('NewDir'), array('autofocus' => 'autofocus')); - $form->addButtonCreate(get_lang('CreateFolder'), 'submit'); - $new_folder_text = $form->returnForm(); - return $new_folder_text; + $form->addElement('header', get_lang('CreateDir')); + $form->addText('dirname', get_lang('NewDir'), array('autofocus' => 'autofocus')); + $form->addButtonCreate(get_lang('CreateFolder')); + + return $form->returnForm(); + } /** diff --git a/main/user/subscribe_user.php b/main/user/subscribe_user.php index 4cf2a30463..fc0e99b017 100755 --- a/main/user/subscribe_user.php +++ b/main/user/subscribe_user.php @@ -77,12 +77,20 @@ $list_not_register_user=''; if (isset($_REQUEST['register'])) { if ($type =='teacher') { if (!empty($current_session_id)) { - $result_simple_sub = SessionManager::set_coach_to_course_session($_REQUEST['user_id'], $current_session_id, $_course['sysCode']); + $result_simple_sub = SessionManager::set_coach_to_course_session( + $_REQUEST['user_id'], + $current_session_id, + $_course['code'] + ); } else { - $result_simple_sub = CourseManager :: subscribe_user($_REQUEST['user_id'], $_course['sysCode'], COURSEMANAGER); + $result_simple_sub = CourseManager:: subscribe_user( + $_REQUEST['user_id'], + $_course['code'], + COURSEMANAGER + ); } } else { - $result_simple_sub=CourseManager :: subscribe_user($_REQUEST['user_id'], $_course['sysCode']); + $result_simple_sub = CourseManager :: subscribe_user($_REQUEST['user_id'], $_course['code']); } $user_id_temp = $_SESSION['session_user_id']; @@ -106,7 +114,7 @@ if (isset($_REQUEST['register'])) { if (isset ($_POST['action'])) { switch ($_POST['action']) { - case 'subscribe' : + case 'subscribe': if (is_array($_POST['user'])) { foreach ($_POST['user'] as $index => $user_id) { $user_id=intval($user_id); @@ -118,12 +126,12 @@ if (isset ($_POST['action'])) { $_course['sysCode'] ); } else { - $is_suscribe[] = CourseManager::subscribe_user($user_id, $_course['sysCode'],COURSEMANAGER); + $is_suscribe[] = CourseManager::subscribe_user($user_id, $_course['code'],COURSEMANAGER); } } else { - $is_suscribe[]=CourseManager::subscribe_user($user_id, $_course['sysCode']); + $is_suscribe[] = CourseManager::subscribe_user($user_id, $_course['code']); } - $is_suscribe_user_id[]=$user_id; + $is_suscribe_user_id[] = $user_id; } } @@ -132,8 +140,8 @@ if (isset ($_POST['action'])) { unset($_SESSION['session_user_id']); unset($_SESSION['session_user_name']); - $counter=0; - $is_suscribe_counter=count($is_suscribe_user_id); + $counter = 0; + $is_suscribe_counter = count($is_suscribe_user_id); $list_register_user=''; @@ -181,7 +189,12 @@ $is_western_name_order = api_is_western_name_order(); $sort_by_first_name = api_sort_by_first_name(); // Build table -$table = new SortableTable('subscribe_users', 'get_number_of_users', 'get_user_data', ($is_western_name_order xor $sort_by_first_name) ? 3 : 2); +$table = new SortableTable( + 'subscribe_users', + 'get_number_of_users', + 'get_user_data', + ($is_western_name_order xor $sort_by_first_name) ? 3 : 2 +); $parameters['keyword'] = $keyword; $parameters['type'] = $type; $table->set_additional_parameters($parameters); @@ -247,7 +260,7 @@ function get_number_of_users() u.status = 1 AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $url_access_id = api_get_current_access_url_id(); if ($url_access_id !=-1) { $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); @@ -257,7 +270,12 @@ function get_number_of_users() ON u.user_id = cu.user_id and cu.c_id = '".api_get_course_int_id()."' AND session_id ='".api_get_session_id()."' INNER JOIN $tbl_url_rel_user as url_rel_user ON (url_rel_user.user_id = u.user_id) - WHERE cu.user_id IS NULL AND access_url_id= $url_access_id AND u.status=1 AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; + WHERE + cu.user_id IS NULL AND + access_url_id= $url_access_id AND + u.status = 1 AND + (u.official_code <> 'ADMIN' OR u.official_code IS NULL) + "; } } } else { @@ -298,7 +316,7 @@ function get_number_of_users() u.status<>".DRH." AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $url_access_id = api_get_current_access_url_id(); if ($url_access_id !=-1) { $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); @@ -340,7 +358,7 @@ function get_number_of_users() $sql .= "WHERE cu.user_id IS NULL AND u.status<>".DRH." "; } - if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $url_access_id = api_get_current_access_url_id(); if ($url_access_id !=-1) { @@ -534,7 +552,7 @@ function get_user_data($from, $number_of_items, $column, $direction) c_id ='".$courseId."' AND session_id ='".$session_id."' "; - if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $sql .= " INNER JOIN $tbl_url_rel_user as url_rel_user ON (url_rel_user.user_id = u.user_id) "; } @@ -557,7 +575,7 @@ function get_user_data($from, $number_of_items, $column, $direction) (u.official_code <> 'ADMIN' OR u.official_code IS NULL) "; } - if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $sql .= "AND access_url_id = $url_access_id"; } @@ -586,10 +604,8 @@ function get_user_data($from, $number_of_items, $column, $direction) //showing only the courses of the current Chamilo access_url_id - if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) { - + if (api_is_multiple_url_enabled()) { if ($url_access_id !=-1) { - $sql = "SELECT $select_fields FROM $user_table u LEFT JOIN $course_user_table cu diff --git a/main/user/user.php b/main/user/user.php index ed93d43bff..917ad3ebd6 100755 --- a/main/user/user.php +++ b/main/user/user.php @@ -384,14 +384,15 @@ if (api_is_allowed_to_edit(null, true)) { $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE); $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER); - $sql = 'SELECT '.$tbl_user.'.user_id + $sql = 'SELECT user.user_id FROM '.$tbl_user.' user INNER JOIN '.$tbl_session_rel_user.' reluser ON user.user_id = reluser.user_id AND reluser.relation_type<>'.SESSION_RELATION_TYPE_RRHH.' INNER JOIN '.$tbl_session_rel_course.' rel_course - ON rel_course.session_id = reluser.id_session - WHERE user.user_id = "'.$user_id.'" - AND rel_course.c_id = "'.$courseId.'"'; + ON rel_course.session_id = reluser.session_id + WHERE + user.user_id = "'.$user_id.'" AND + rel_course.c_id = "'.$courseId.'"'; $result = Database::query($sql); $row = Database::fetch_array($result, 'ASSOC'); From 9cd693a6a9e6edfd99872f4f3696dbec5894424d Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 12:33:23 +0200 Subject: [PATCH 088/159] Dates can be null. --- main/work/edit.php | 16 ++---- main/work/edit_work.php | 5 +- main/work/student_work.php | 2 +- main/work/work.lib.php | 55 ++++++++++++++----- .../Entity/CStudentPublication.php | 4 +- .../Entity/CStudentPublicationAssignment.php | 4 +- 6 files changed, 53 insertions(+), 33 deletions(-) diff --git a/main/work/edit.php b/main/work/edit.php index 7b0ee4d69e..5c9d0f4e99 100755 --- a/main/work/edit.php +++ b/main/work/edit.php @@ -71,13 +71,11 @@ if (!api_is_allowed_to_edit()) { if (!empty($my_folder_data)) { $homework = get_work_assignment_by_id($my_folder_data['id']); - if ($homework['expires_on'] != '0000-00-00 00:00:00' || - $homework['ends_on'] != '0000-00-00 00:00:00' - ) { + if (!empty($homework['expires_on'] || !empty($homework['ends_on'])) { $time_now = time(); if (!empty($homework['expires_on']) && - $homework['expires_on'] != '0000-00-00 00:00:00' + !empty($homework['expires_on']) ) { $time_expires = api_strtotime($homework['expires_on'], 'UTC'); $difference = $time_expires - $time_now; @@ -86,15 +84,11 @@ if (!empty($my_folder_data)) { } } - if (empty($homework['expires_on']) || - $homework['expires_on'] == '0000-00-00 00:00:00' - ) { + if (empty($homework['expires_on'])) { $has_expired = false; } - if (!empty($homework['ends_on']) && - $homework['ends_on'] != '0000-00-00 00:00:00' - ) { + if (!empty($homework['ends_on'])) { $time_ends = api_strtotime($homework['ends_on'], 'UTC'); $difference2 = $time_ends - $time_now; if ($difference2 < 0) { @@ -102,7 +96,7 @@ if (!empty($my_folder_data)) { } } - $ends_on = api_convert_and_format_date($homework['ends_on']); + $ends_on = api_convert_and_format_date($homework['ends_on']); $expires_on = api_convert_and_format_date($homework['expires_on']); } } diff --git a/main/work/edit_work.php b/main/work/edit_work.php index 361a7eeedb..59d7952955 100755 --- a/main/work/edit_work.php +++ b/main/work/edit_work.php @@ -64,7 +64,7 @@ if (Gradebook::is_active()) { $defaults['category_id'] = ''; } -if ($homework['expires_on'] != '0000-00-00 00:00:00') { +if (!empty($homework['expires_on'])) { $homework['expires_on'] = api_get_local_time($homework['expires_on']); $there_is_a_expire_date = true; $defaults['enableExpiryDate'] = true; @@ -73,7 +73,7 @@ if ($homework['expires_on'] != '0000-00-00 00:00:00') { $there_is_a_expire_date = false; } -if ($homework['ends_on'] != '0000-00-00 00:00:00') { +if (!empty($homework['ends_on'])) { $homework['ends_on'] = api_get_local_time($homework['ends_on']); $there_is_a_end_date = true; $defaults['enableEndDate'] = true; @@ -108,6 +108,7 @@ if ($form->validate()) { } if ($editCheck) { + var_dump($params);exit; updateWork($workId, $params, $courseInfo, $sessionId); updatePublicationAssignment($workId, $params, $courseInfo, $groupId); updateDirName($workData, $params['new_dir']); diff --git a/main/work/student_work.php b/main/work/student_work.php index 18750a1f56..07bfb83e27 100755 --- a/main/work/student_work.php +++ b/main/work/student_work.php @@ -156,7 +156,7 @@ foreach ($workPerUser as $work) { $column++; $table->setCellContents($row, $column, $userResult['sent_date']); $column++; - $dateQualification = !empty($workExtraData['expires_on']) && $workExtraData['expires_on'] != '0000-00-00 00:00:00' ? api_get_local_time($workExtraData['expires_on']) : '-'; + $dateQualification = !empty($workExtraData['expires_on']) ? api_get_local_time($workExtraData['expires_on']) : '-'; $table->setCellContents($row, $column, $dateQualification); $column++; diff --git a/main/work/work.lib.php b/main/work/work.lib.php index d93dbf016b..c31ef37625 100755 --- a/main/work/work.lib.php +++ b/main/work/work.lib.php @@ -1599,12 +1599,12 @@ function get_count_work($work_id, $onlyMeUserId = null, $notMeUserId = null) $is_allowed_to_edit = api_is_allowed_to_edit(null, true); $session_id = api_get_session_id(); - $condition_session = api_get_session_condition($session_id); + $condition_session = api_get_session_condition($session_id, true, false, 'work.session_id'); - $course_id = api_get_course_int_id(); - $group_id = api_get_group_id(); - $course_info = api_get_course_info(api_get_course_id()); - $work_id = intval($work_id); + $course_id = api_get_course_int_id(); + $group_id = api_get_group_id(); + $course_info = api_get_course_info(api_get_course_id()); + $work_id = intval($work_id); if (!empty($group_id)) { // set to select only messages posted by the user's group @@ -2188,7 +2188,7 @@ function get_work_user_list( $work_data = get_work_data_by_id($work_id); $is_allowed_to_edit = api_is_allowed_to_edit() || api_is_coach(); - $condition_session = api_get_session_condition($session_id); + $condition_session = api_get_session_condition($session_id, true, false, 'work.session_id'); $locked = api_resource_is_locked_by_gradebook($work_id, LINK_STUDENTPUBLICATION); $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh( @@ -2325,10 +2325,17 @@ function get_work_user_list( $work['qualification_score'] = $work['qualification']; $add_string = ''; - $time_expires = api_strtotime($work_assignment['expires_on'], 'UTC'); + + $time_expires = ''; + if (!empty($work_assignment['expires_on'])) { + $time_expires = api_strtotime( + $work_assignment['expires_on'], + 'UTC' + ); + } if (!empty($work_assignment['expires_on']) && - $time_expires && ($time_expires < api_strtotime($work['sent_date'], 'UTC'))) { + !empty($time_expires) && ($time_expires < api_strtotime($work['sent_date'], 'UTC'))) { $add_string = Display::label(get_lang('Expired'), 'important'); } @@ -3929,12 +3936,15 @@ function processWorkForm($workInfo, $values, $courseInfo, $sessionId, $groupId, Database::query($sql); $workId = Database::insert_id(); + $sql = "UPDATE $work_table SET id = $workId WHERE iid = $workId "; + Database::query($sql); + if ($workId) { if (array_key_exists('filename', $workInfo) && !empty($filename)) { $filename = Database::escape_string($filename); $sql = "UPDATE $work_table SET filename = '$filename' - WHERE c_id = $courseId AND id = $workId"; + WHERE iid = $workId"; Database::query($sql); } @@ -3942,7 +3952,7 @@ function processWorkForm($workInfo, $values, $courseInfo, $sessionId, $groupId, $documentId = isset($values['document_id']) ? intval($values['document_id']) : 0; $sql = "UPDATE $work_table SET document_id = '$documentId' - WHERE c_id = $courseId AND id = $workId"; + WHERE iid = $workId"; Database::query($sql); } api_item_property_update( @@ -4019,7 +4029,7 @@ function addDir($params, $user_id, $courseInfo, $group_id, $session_id) allow_text_assignment = '".Database::escape_string($params['allow_text_assignment'])."', contains_file = 0, user_id = '".$user_id."'"; - Database::query($sql);date_of_qualification + Database::query($sql); // Add the directory $id = Database::insert_id(); @@ -4111,7 +4121,7 @@ function updatePublicationAssignment($workId, $params, $courseInfo, $groupId) $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT); $workTable = Database::get_course_table(TABLE_STUDENT_PUBLICATION); $workId = intval($workId); - $time = time(); + $time = api_get_utc_datetime(); $course_id = $courseInfo['real_id']; // Insert into agenda @@ -4123,7 +4133,7 @@ function updatePublicationAssignment($workId, $params, $courseInfo, $groupId) // Setting today date $date = $end_date = $time; - if (!empty($params['enableExpiryDate'])) { + if (isset($params['enableExpiryDate'])) { $end_date = $params['expires_on']; $date = $end_date; } @@ -4168,14 +4178,28 @@ function updatePublicationAssignment($workId, $params, $courseInfo, $groupId) $data = get_work_assignment_by_id($workId, $course_id); if (empty($data)) { + $expiryDateCondition = ''; + if (!empty($expiryDate)) { + $expiryDateCondition = "expires_on = '".Database::escape_string($expiryDate)."', "; + } else { + $expiryDateCondition = "expires_on = null, "; + } + + $endOnCondition = ''; + if (!empty($endDate)) { + $endOnCondition = "ends_on = '".Database::escape_string($endDate)."', "; + } else { + $endOnCondition = "ends_on = null, "; + } $sql = "INSERT INTO $table SET c_id = $course_id , - expires_on = '".Database::escape_string($expiryDate)."', - ends_on = '".Database::escape_string($endDate)."', + $expiryDateCondition + $endOnCondition add_to_calendar = $agendaId, enable_qualification = '$qualification', publication_id = '$workId'"; + Database::query($sql); $my_last_id = Database::insert_id(); @@ -4185,6 +4209,7 @@ function updatePublicationAssignment($workId, $params, $courseInfo, $groupId) view_properties = 1 WHERE c_id = $course_id AND id = $workId"; Database::query($sql); + exit; } else { $sql = "UPDATE $table SET expires_on = '".$expiryDate."', diff --git a/src/Chamilo/CourseBundle/Entity/CStudentPublication.php b/src/Chamilo/CourseBundle/Entity/CStudentPublication.php index fdcfbe1c9e..88ba7d215f 100644 --- a/src/Chamilo/CourseBundle/Entity/CStudentPublication.php +++ b/src/Chamilo/CourseBundle/Entity/CStudentPublication.php @@ -88,7 +88,7 @@ class CStudentPublication /** * @var \DateTime * - * @ORM\Column(name="sent_date", type="datetime", nullable=false) + * @ORM\Column(name="sent_date", type="datetime", nullable=true) */ private $sentDate; @@ -123,7 +123,7 @@ class CStudentPublication /** * @var \DateTime * - * @ORM\Column(name="date_of_qualification", type="datetime", nullable=false) + * @ORM\Column(name="date_of_qualification", type="datetime", nullable=true) */ private $dateOfQualification; diff --git a/src/Chamilo/CourseBundle/Entity/CStudentPublicationAssignment.php b/src/Chamilo/CourseBundle/Entity/CStudentPublicationAssignment.php index 733753966f..b798f2d35a 100644 --- a/src/Chamilo/CourseBundle/Entity/CStudentPublicationAssignment.php +++ b/src/Chamilo/CourseBundle/Entity/CStudentPublicationAssignment.php @@ -39,14 +39,14 @@ class CStudentPublicationAssignment /** * @var \DateTime * - * @ORM\Column(name="expires_on", type="datetime", nullable=false) + * @ORM\Column(name="expires_on", type="datetime", nullable=true) */ private $expiresOn; /** * @var \DateTime * - * @ORM\Column(name="ends_on", type="datetime", nullable=false) + * @ORM\Column(name="ends_on", type="datetime", nullable=true) */ private $endsOn; From be3d64de74b0553f15eefcb1c75303e93923d361 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 12:33:44 +0200 Subject: [PATCH 089/159] Remove jquery ui tab call. --- main/session/index.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/main/session/index.php b/main/session/index.php index ec4d90a756..f9806b3f19 100755 --- a/main/session/index.php +++ b/main/session/index.php @@ -566,9 +566,6 @@ $(function() { echo Display::grid_js('exercises', '', $column_exercise, $column_exercise_model, $extra_params_exercise, $my_real_array); } ?> - // Generate tabs with jquery-ui - $('#tabs').tabs(); - $( "#sub_tab" ).tabs(); }); From 28598e3494640466dcb6839af6dd00ccde672ce4 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 12:34:08 +0200 Subject: [PATCH 090/159] When inserting an item save the id based in the iid --- main/inc/lib/fileUpload.lib.php | 3 +++ main/inc/lib/link.lib.php | 3 +++ main/newscorm/learnpath.class.php | 14 +++++++++++--- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/main/inc/lib/fileUpload.lib.php b/main/inc/lib/fileUpload.lib.php index 11cae86237..7fd68e4202 100755 --- a/main/inc/lib/fileUpload.lib.php +++ b/main/inc/lib/fileUpload.lib.php @@ -1228,6 +1228,9 @@ function add_document( if (Database::query($sql)) { $documentId = Database::insert_id(); + $sql = "UPDATE $table_document SET id = $documentId WHERE iid = $documentId"; + Database::query($sql); + if ($documentId) { if ($save_visibility) { api_set_default_visibility($documentId, TOOL_DOCUMENT, $group_id); diff --git a/main/inc/lib/link.lib.php b/main/inc/lib/link.lib.php index 0ce6118ea4..5260ed99dd 100755 --- a/main/inc/lib/link.lib.php +++ b/main/inc/lib/link.lib.php @@ -192,6 +192,9 @@ class Link extends Model $catlinkstatus = get_lang('LinkAdded'); Database:: query($sql); $link_id = Database:: insert_id(); + // iid + $sql = "UPDATE $tbl_link SET id = $link_id WHERE iid = $link_id"; + Database:: query($sql); if ($link_id) { api_set_default_visibility($link_id, TOOL_LINK); diff --git a/main/newscorm/learnpath.class.php b/main/newscorm/learnpath.class.php index 16ddc9defc..7a0433aac5 100755 --- a/main/newscorm/learnpath.class.php +++ b/main/newscorm/learnpath.class.php @@ -760,14 +760,22 @@ class learnpath } $sql = "INSERT INTO $tbl_lp (c_id, lp_type,name,description,path,default_view_mod, default_encoding,display_order,content_maker,content_local,js_lib,session_id, created_on, publicated_on, expired_on) " . - "VALUES ($course_id, $type,'$name','$description','','embedded','UTF-8','$dsp','Chamilo','local','','".$session_id."', '".api_get_utc_datetime()."' , '".$publicated_on."' , '".$expired_on."')"; - + "VALUES ($course_id, $type,'$name','$description','','embedded','UTF-8','$dsp','Chamilo','local','','".$session_id."', '".api_get_utc_datetime()."' , '".$publicated_on."' , '".$expired_on."')"; Database::query($sql); $id = Database :: insert_id(); if ($id > 0) { + $sql = "UPDATE $tbl_lp SET id = $id WHERE iid = $id"; + Database::query($sql); + $course_info = api_get_course_info(); // Insert into item_property. - api_item_property_update($course_info, TOOL_LEARNPATH, $id, 'LearnpathAdded', api_get_user_id()); + api_item_property_update( + $course_info, + TOOL_LEARNPATH, + $id, + 'LearnpathAdded', + api_get_user_id() + ); api_set_default_visibility($id, TOOL_LEARNPATH); return $id; } From 929e262c9350eb2a3e0ce73917043f1f89e093c8 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 14:04:57 +0200 Subject: [PATCH 091/159] Replacing OR with ||, updating id based in iid. --- main/inc/lib/document.lib.php | 2 +- main/inc/lib/elfinder/templates.php | 10 +- main/newscorm/learnpath.class.php | 236 ++++++++++++++++---------- main/newscorm/learnpathItem.class.php | 46 +++-- main/newscorm/lp_controller.php | 1 + 5 files changed, 185 insertions(+), 110 deletions(-) diff --git a/main/inc/lib/document.lib.php b/main/inc/lib/document.lib.php index c6e13b40e2..7a26e96022 100755 --- a/main/inc/lib/document.lib.php +++ b/main/inc/lib/document.lib.php @@ -1513,7 +1513,7 @@ class DocumentManager //note the extra / at the end of doc_path to match every path in the document table that is part of the document path $session_id = intval($session_id); - $condition = "AND session_id IN ('$session_id', '0') "; + $condition = "AND d.session_id IN ('$session_id', '0') "; // The " d.filetype='file' " let the user see a file even if the folder is hidden see #2198 /* diff --git a/main/inc/lib/elfinder/templates.php b/main/inc/lib/elfinder/templates.php index 8e970c0d17..20d7568c6b 100644 --- a/main/inc/lib/elfinder/templates.php +++ b/main/inc/lib/elfinder/templates.php @@ -11,7 +11,9 @@ $table = Database::get_main_table(TABLE_MAIN_SYSTEM_TEMPLATE); $sql = "SELECT * FROM $table"; $result = Database::query($sql); $templates = Database::store_result($result, 'ASSOC'); -$editor = new CkEditor(); -$templates = $editor->simpleFormatTemplates($templates); -$template->assign('templates', $templates); -$template->display('default/javascript/editor/ckeditor/templates.tpl'); +if (!empty($templates)) { + $editor = new CkEditor(); + $templates = $editor->simpleFormatTemplates($templates); + $template->assign('templates', $templates); + $template->display('default/javascript/editor/ckeditor/templates.tpl'); +} diff --git a/main/newscorm/learnpath.class.php b/main/newscorm/learnpath.class.php index 7a0433aac5..4dc0b8d187 100755 --- a/main/newscorm/learnpath.class.php +++ b/main/newscorm/learnpath.class.php @@ -120,6 +120,7 @@ class learnpath error_log('New LP - learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0); } $res = Database::query($sql); + if (Database::num_rows($res) > 0) { $this->lp_id = $lp_id; $row = Database::fetch_array($res); @@ -144,11 +145,11 @@ class learnpath $this->ref = $row['ref']; if ($row['publicated_on'] != '0000-00-00 00:00:00') { - $this->publicated_on = $row['publicated_on']; + $this->publicated_on = $row['publicated_on']; } if ($row['expired_on'] != '0000-00-00 00:00:00') { - $this->expired_on = $row['expired_on']; + $this->expired_on = $row['expired_on']; } if ($this->type == 2) { if ($row['force_commit'] == 1) { @@ -169,7 +170,7 @@ class learnpath return false; } else { - $user_info = api_get_user_info($user_id); + $user_info = api_get_user_info($user_id); if (!empty($user_info)) { $this->user_id = $user_info['user_id']; } else { @@ -214,6 +215,11 @@ class learnpath VALUES ($course_id, $lp_id, $user_id, 1, $session_id)"; Database::query($sql); $this->lp_view_id = Database::insert_id(); + + $sql = "UPDATE $lp_table SET id = ".$this->lp_view_id." WHERE iid = ".$this->lp_view_id; + + Database::query($sql); + if ($this->debug > 2) { error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - inserting new lp_view: ' . $sql_ins, 0); } @@ -318,50 +324,73 @@ class learnpath if (!empty($lp_item_id_list)) { $lp_item_id_list_to_string = implode("','", $lp_item_id_list); + if (!empty($lp_item_id_list_to_string)) { + // Get last viewing vars. + $lp_item_view_table = Database:: get_course_table( + TABLE_LP_ITEM_VIEW + ); + // This query should only return one or zero result. + $sql = "SELECT lp_item_id, status + FROM $lp_item_view_table + WHERE + c_id = $course_id AND + lp_view_id = ".$this->lp_view_id." AND + lp_item_id IN ('".$lp_item_id_list_to_string."') + ORDER BY view_count DESC "; - // Get last viewing vars. - $lp_item_view_table = Database :: get_course_table(TABLE_LP_ITEM_VIEW); - // This query should only return one or zero result. - $sql = "SELECT lp_item_id, status - FROM $lp_item_view_table - WHERE - c_id = $course_id AND - lp_view_id = ".$this->lp_view_id." AND - lp_item_id IN ('".$lp_item_id_list_to_string."') - ORDER BY view_count DESC "; - - if ($this->debug > 2) { - error_log('New LP - learnpath::__construct() - Selecting item_views: ' . $sql, 0); - } + if ($this->debug > 2) { + error_log( + 'New LP - learnpath::__construct() - Selecting item_views: '.$sql, + 0 + ); + } - $status_list = array(); - $res = Database::query($sql); - while ($row = Database :: fetch_array($res) ) { - $status_list[$row['lp_item_id']] = $row['status']; - } + $status_list = array(); + $res = Database::query($sql); + while ($row = Database:: fetch_array($res)) { + $status_list[$row['lp_item_id']] = $row['status']; + } - foreach ($lp_item_id_list as $item_id) { - if (isset($status_list[$item_id])) { - $status = $status_list[$item_id]; - if (is_object($this->items[$item_id])) { - $this->items[$item_id]->set_status($status); - if (empty($status)) { - $this->items[$item_id]->set_status($this->default_status); - } - } - } else { - if (!api_is_invitee()) { + foreach ($lp_item_id_list as $item_id) { + if (isset($status_list[$item_id])) { + $status = $status_list[$item_id]; if (is_object($this->items[$item_id])) { - $this->items[$item_id]->set_status($this->default_status); + $this->items[$item_id]->set_status($status); + if (empty($status)) { + $this->items[$item_id]->set_status( + $this->default_status + ); + } } - // Add that row to the lp_item_view table so that we have something to show in the stats page. - $sql = "INSERT INTO $lp_item_view_table (c_id, lp_item_id, lp_view_id, view_count, status) - VALUES ($course_id, ".$item_id . "," . $this->lp_view_id . ", 1, 'not attempted')"; - if ($this->debug > 2) { - error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - Inserting blank item_view : ' . $sql_ins, 0); + } else { + if (!api_is_invitee()) { + if (is_object($this->items[$item_id])) { + $this->items[$item_id]->set_status( + $this->default_status + ); + } + + // Add that row to the lp_item_view table so that we have something to show in the stats page. + $sql = "INSERT INTO $lp_item_view_table (c_id, lp_item_id, lp_view_id, view_count, status) + VALUES ($course_id, ".$item_id.",".$this->lp_view_id.", 1, 'not attempted')"; + + if ($this->debug > 2) { + error_log( + 'New LP - learnpath::__construct() '.__LINE__.' - Inserting blank item_view : '.$sql_ins, + 0 + ); + } + $this->items[$item_id]->set_lp_view( + $this->lp_view_id, + $course_id + ); + + Database::query($sql); + $insertId = Database::insert_id(); + + $sql = "UPDATE $lp_item_view_table SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); } - $this->items[$item_id]->set_lp_view($this->lp_view_id, $course_id); - Database::query($sql); } } } @@ -558,46 +587,39 @@ class learnpath $new_item_id = Database::insert($tbl_lp_item, $params); + $sql = "UPDATE $tbl_lp_item SET id = $new_item_id WHERE iid = $new_item_id"; + Database::query($sql); + if ($this->debug > 2) { - error_log('New LP - Inserting dokeos_chapter: ' . $new_item_id, 0); + error_log('New LP - Inserting chapter: ' . $new_item_id, 0); } if ($new_item_id) { // Update the item that should come after the new item. - $sql_update_next = " - UPDATE " . $tbl_lp_item . " - SET previous_item_id = " . $new_item_id . " - WHERE c_id = $course_id AND id = " . $next; - - Database::query($sql_update_next); - - // Update the item that should be before the new item. - $sql_update_previous = " - UPDATE " . $tbl_lp_item . " - SET next_item_id = " . $new_item_id . " - WHERE c_id = $course_id AND id = " . $tmp_previous; - - Database::query($sql_update_previous); + $sql = " UPDATE $tbl_lp_item SET + previous_item_id = $new_item_id, + next_item_id = $new_item_id, + id = $new_item_id + WHERE iid = $new_item_id"; + Database::query($sql); // Update all the items after the new item. - $sql_update_order = " - UPDATE " . $tbl_lp_item . " - SET display_order = display_order + 1 - WHERE - c_id = $course_id AND - lp_id = " . $this->get_id() . " AND - id <> " . $new_item_id . " AND - parent_item_id = " . $parent . " AND - display_order > " . $display_order; - - Database::query($sql_update_order); + $sql = "UPDATE " . $tbl_lp_item . " + SET display_order = display_order + 1 + WHERE + c_id = $course_id AND + lp_id = " . $this->get_id() . " AND + id <> " . $new_item_id . " AND + parent_item_id = " . $parent . " AND + display_order > " . $display_order; + Database::query($sql); // Update the item that should come after the new item. - $sql_update_ref = "UPDATE " . $tbl_lp_item . " - SET ref = " . $new_item_id . " - WHERE c_id = $course_id AND id = " . $new_item_id; - Database::query($sql_update_ref); + $sql = "UPDATE " . $tbl_lp_item . " + SET ref = " . $new_item_id . " + WHERE c_id = $course_id AND id = " . $new_item_id; + Database::query($sql); // Upload audio. if (!empty($_FILES['mp3']['name'])) { @@ -638,6 +660,7 @@ class learnpath api_get_session_id() ); } + $file_path = handle_uploaded_document( $_course, $_FILES['mp3'], @@ -657,8 +680,8 @@ class learnpath // Store the mp3 file in the lp_item table. $sql = "UPDATE $tbl_lp_item SET - audio = '" . Database::escape_string($file) . "' - WHERE id = '" . intval($new_item_id) . "'"; + audio = '" . Database::escape_string($file) . "' + WHERE id = '" . intval($new_item_id) . "'"; Database::query($sql); } } @@ -759,8 +782,8 @@ class learnpath $dsp = $row[0] + 1; } - $sql = "INSERT INTO $tbl_lp (c_id, lp_type,name,description,path,default_view_mod, default_encoding,display_order,content_maker,content_local,js_lib,session_id, created_on, publicated_on, expired_on) " . - "VALUES ($course_id, $type,'$name','$description','','embedded','UTF-8','$dsp','Chamilo','local','','".$session_id."', '".api_get_utc_datetime()."' , '".$publicated_on."' , '".$expired_on."')"; + $sql = "INSERT INTO $tbl_lp (c_id, lp_type,name,description,path,default_view_mod, default_encoding,display_order,content_maker,content_local,js_lib,session_id, created_on, publicated_on, expired_on) + VALUES ($course_id, $type,'$name','$description','','embedded','UTF-8','$dsp','Chamilo','local','','".$session_id."', '".api_get_utc_datetime()."' , '".$publicated_on."' , '".$expired_on."')"; Database::query($sql); $id = Database :: insert_id(); if ($id > 0) { @@ -989,10 +1012,10 @@ class learnpath return false; } - $lp = Database :: get_course_table(TABLE_LP_MAIN); - $lp_item = Database :: get_course_table(TABLE_LP_ITEM); - $lp_view = Database :: get_course_table(TABLE_LP_VIEW); - $lp_item_view = Database :: get_course_table(TABLE_LP_ITEM_VIEW); + $lp = Database:: get_course_table(TABLE_LP_MAIN); + $lp_item = Database:: get_course_table(TABLE_LP_ITEM); + $lp_view = Database:: get_course_table(TABLE_LP_VIEW); + $lp_item_view = Database:: get_course_table(TABLE_LP_ITEM_VIEW); // Delete lp item id. foreach ($this->items as $id => $dummy) { @@ -1007,7 +1030,7 @@ class learnpath $sql = "DELETE FROM $lp_view WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id; //if ($this->debug > 2) { error_log('New LP - Deleting views bound to lp '.$this->lp_id.': '.$sql_del_view, 0); } Database::query($sql); - + exit; self::toggle_publish($this->lp_id, 'i'); //if ($this->debug > 2) { error_log('New LP - Deleting lp '.$this->lp_id.' of type '.$this->type, 0); } @@ -2881,12 +2904,19 @@ class learnpath * @return array * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP) */ - public static function get_iv_interactions_array($lp_iv_id = 0) + public static function get_iv_interactions_array($lp_iv_id) { $course_id = api_get_course_int_id(); - $list = array (); + $list = array(); $table = Database :: get_course_table(TABLE_LP_IV_INTERACTION); - $sql = "SELECT * FROM $table WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id ORDER BY order_id ASC"; + + if (empty($lp_iv_id)) { + return array(); + } + + $sql = "SELECT * FROM $table + WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id + ORDER BY order_id ASC"; $res = Database::query($sql); $num = Database :: num_rows($res); if ($num > 0) { @@ -3332,12 +3362,17 @@ class learnpath } $file = ''; - $lp_table = Database::get_course_table(TABLE_LP_MAIN); - $lp_item_table = Database::get_course_table(TABLE_LP_ITEM); + $lp_table = Database::get_course_table(TABLE_LP_MAIN); + $lp_item_table = Database::get_course_table(TABLE_LP_ITEM); $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW); $item_id = intval($item_id); - $sql = "SELECT l.lp_type as ltype, l.path as lpath, li.item_type as litype, li.path as lipath, li.parameters as liparams + $sql = "SELECT + l.lp_type as ltype, + l.path as lpath, + li.item_type as litype, + li.path as lipath, + li.parameters as liparams FROM $lp_table l INNER JOIN $lp_item_table li ON (li.lp_id = l.id AND l.c_id = $course_id AND li.c_id = $course_id ) @@ -3636,6 +3671,9 @@ class learnpath Database::query($sql); $id = Database :: insert_id(); $this->lp_view_id = $id; + + $sql = "UPDATE $lp_view_table SET id = $id WHERE iid = $id"; + Database::query($sql); } return $this->lp_view_id; @@ -4171,9 +4209,17 @@ class learnpath //if ($this->debug > 2) { error_log('New LP - '.$sql.' - '.$num, 0); } if (($set_visibility == 'i') && ($num > 0)) { $sql = "DELETE FROM $tbl_tool WHERE c_id = ".$course_id." AND (link='$link' and image='scormbuilder.gif' $session_condition)"; + Database::query($sql); + } elseif (($set_visibility == 'v') && ($num == 0)) { $sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES ($course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)"; + Database::query($sql); + + $insertId = Database::insert_id(); + $sql = "UPDATE $tbl_tool SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); + } elseif (($set_visibility == 'v') && ($num > 0)) { $sql = "UPDATE $tbl_tool SET c_id = $course_id, @@ -4186,11 +4232,12 @@ class learnpath added_tool = 0, session_id = $session_id WHERE c_id = ".$course_id." AND (link='$link' and image='scormbuilder.gif' $session_condition)"; + Database::query($sql); } else { // Parameter and database incompatible, do nothing, exit. return false; } - Database::query($sql); + } /** @@ -4214,13 +4261,18 @@ class learnpath $session_id = api_get_session_id(); $course_id = api_get_course_int_id(); $lp_view_table = Database :: get_course_table(TABLE_LP_VIEW); - $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) " . - "VALUES ($course_id, " . $this->lp_id . "," . $this->get_user_id() . "," . ($this->attempt + 1) . ", $session_id)"; + $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) + VALUES ($course_id, " . $this->lp_id . "," . $this->get_user_id() . "," . ($this->attempt + 1) . ", $session_id)"; if ($this->debug > 2) { error_log('New LP - Inserting new lp_view for restart: ' . $sql, 0); } $res = Database::query($sql); - if ($view_id = Database :: insert_id($res)) { + $view_id = Database::insert_id(); + + $sql = "UPDATE $lp_view_table SET id = $view_id WHERE iid = $view_id"; + Database::query($sql); + + if ($view_id) { $this->lp_view_id = $view_id; $this->attempt = $this->attempt + 1; } else { @@ -4233,6 +4285,7 @@ class learnpath $this->items[$index]->set_lp_view($this->lp_view_id); } $this->first(); + return true; } @@ -7466,7 +7519,8 @@ class learnpath reset($arrLP); } - $arrHide = array (); + $arrHide = array(); + $s_selected_position = null; //POSITION for ($i = 0; $i < count($arrLP); $i++) { diff --git a/main/newscorm/learnpathItem.class.php b/main/newscorm/learnpathItem.class.php index 780b8e0e6e..d8bb6201ef 100755 --- a/main/newscorm/learnpathItem.class.php +++ b/main/newscorm/learnpathItem.class.php @@ -290,7 +290,7 @@ class learnpathItem $this->current_stop_time = time(); $type = $this->get_type(); if ($type != 'sco') { - if ($type == TOOL_QUIZ or $type == TOOL_HOTPOTATOES) { + if ($type == TOOL_QUIZ || $type == TOOL_HOTPOTATOES) { $this->get_status( true, true @@ -348,6 +348,7 @@ class learnpathItem $di->remove_document($this->search_did); } } + return true; } @@ -591,8 +592,8 @@ class learnpathItem $row = Database::fetch_array($res); $lp_iv_id = $row[0]; $iva_table = Database::get_course_table(TABLE_LP_IV_INTERACTION); - $iva_sql = "SELECT * FROM $iva_table " . - "WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id "; + $iva_sql = "SELECT * FROM $iva_table + WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id "; $res_sql = Database::query($iva_sql); while ($row = Database::fetch_array($res_sql)) { $this->interactions[$row['interaction_id']] = array( @@ -1923,7 +1924,7 @@ class learnpathItem $this->current_start_time = time(); } //$this->current_stop_time=time(); - if (time() < $this->current_stop_time or $this->current_stop_time == 0 + if (time() < $this->current_stop_time || $this->current_stop_time == 0 ) { if (self::debug > 2) { error_log( @@ -2227,7 +2228,7 @@ class learnpathItem } else { if (isset($items[$refs_list[$list[0]]])) { $status = $items[$refs_list[$list[0]]]->get_status(true); - $returnstatus = ($status == $this->possible_status[2]) OR ($status == $this->possible_status[3]); + $returnstatus = ($status == $this->possible_status[2]) || ($status == $this->possible_status[3]); if (empty($this->prereq_alert) && !$returnstatus) { $this->prereq_alert = get_lang('LearnpathPrereqNotCompleted'); } @@ -2491,7 +2492,7 @@ class learnpathItem // 1. Checking the status in current items. $status = $items[$refs_list[$prereqs_string]]->get_status(true); - $returnstatus = $status == $this->possible_status[2] OR $status == $this->possible_status[3]; + $returnstatus = $status == $this->possible_status[2] || $status == $this->possible_status[3]; if (!$returnstatus) { if (self::debug > 1) { @@ -2656,7 +2657,7 @@ class learnpathItem ); $status = $status_array[0]; - $returnstatus = (($status == $this->possible_status[2]) OR ($status == $this->possible_status[3])); + $returnstatus = ($status == $this->possible_status[2]) || ($status == $this->possible_status[3]); if (!$returnstatus && empty($this->prereq_alert)) { $this->prereq_alert = get_lang( 'LearnpathPrereqNotCompleted' @@ -2742,7 +2743,7 @@ class learnpathItem } if (isset($items[$refs_list[$list[0]]])) { $status = $items[$refs_list[$list[0]]]->get_status(true); - $returnstatus = (($status == 'completed') OR ($status == 'passed')); + $returnstatus = (($status == 'completed') || ($status == 'passed')); if (!$returnstatus && empty($this->prereq_alert)) { $this->prereq_alert = get_lang( 'LearnpathPrereqNotCompleted' @@ -3305,7 +3306,7 @@ class learnpathItem if (self::debug > 0) { error_log('learnpathItem::set_max_score(' . $score . ')', 0); } - if (is_int($score) or $score == '') { + if (is_int($score) || $score == '') { $this->view_max_score = $score; if (self::debug > 1) { error_log( @@ -3669,7 +3670,7 @@ class learnpathItem * @return boolean True or false on error */ public function write_objectives_to_db() - { + {error_log('ddd'); if (self::debug > 0) { error_log('learnpathItem::write_objectives_to_db()', 0); } @@ -3740,9 +3741,13 @@ class learnpathItem 'status' => $objective[1], 'score_raw' => $objective[2], 'score_min' => $objective[4], - 'score_max' =>$objective[3] + 'score_max' => $objective[3] ); - Database::insert($iva_table, $params); + + $insertId = Database::insert($iva_table, $params); + + $sql = "UPDATE $iva_table SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); } } } @@ -3796,7 +3801,7 @@ class learnpathItem } if ((($save === false && $this->type == 'sco') || - ($this->type == 'sco' && ($credit == 'no-credit' OR $mode == 'review' OR $mode == 'browse'))) && + ($this->type == 'sco' && ($credit == 'no-credit' || $mode == 'review' || $mode == 'browse'))) && ($this->seriousgame_mode != 1 && $this->type == 'sco') ) { if (self::debug > 1) { @@ -3840,6 +3845,10 @@ class learnpathItem ); } $this->db_item_view_id = Database::insert($item_view_table, $params); + + $sql = "UPDATE $item_view_table SET id = ".$this->db_item_view_id." WHERE iid = ".$this->db_item_view_id; + Database::query($sql); + $inserted = true; } @@ -3883,6 +3892,10 @@ class learnpathItem } $this->db_item_view_id = Database::insert($item_view_table, $params); + + $sql = "UPDATE $item_view_table SET id = ".$this->db_item_view_id." WHERE iid = ".$this->db_item_view_id; + Database::query($sql); + } else { if ($this->type == 'hotpotatoes') { $params = array( @@ -4156,12 +4169,17 @@ class learnpathItem 'result' => $interaction[6], 'latency' => $interaction[7] ); - Database::insert($iva_table, $params); + + $insertId = Database::insert($iva_table, $params); + + $sql = "UPDATE $iva_table SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); } } } } } + if (self::debug > 2) { error_log('End of learnpathItem::write_to_db()', 0); } diff --git a/main/newscorm/lp_controller.php b/main/newscorm/lp_controller.php index cfd19c4566..defea9baa2 100755 --- a/main/newscorm/lp_controller.php +++ b/main/newscorm/lp_controller.php @@ -298,6 +298,7 @@ if (!$lp_found || (!empty($_REQUEST['lp_id']) && $_SESSION['oLP']->get_id() != $ $sel = "SELECT lp_type FROM $lp_table WHERE c_id = $course_id AND id = $lp_id"; if ($debug > 0) error_log('New LP - querying '.$sel, 0); $res = Database::query($sel); + if (Database::num_rows($res)) { $row = Database::fetch_array($res); $type = $row['lp_type']; From 62beaf2735d252b817de9806cd3b4fa5d2f2e621 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 14:05:53 +0200 Subject: [PATCH 092/159] Minor - remove exit --- main/newscorm/learnpath.class.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/main/newscorm/learnpath.class.php b/main/newscorm/learnpath.class.php index 4dc0b8d187..be734c529c 100755 --- a/main/newscorm/learnpath.class.php +++ b/main/newscorm/learnpath.class.php @@ -1028,12 +1028,10 @@ class learnpath Database::query($sql); $sql = "DELETE FROM $lp_view WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id; - //if ($this->debug > 2) { error_log('New LP - Deleting views bound to lp '.$this->lp_id.': '.$sql_del_view, 0); } Database::query($sql); - exit; + self::toggle_publish($this->lp_id, 'i'); - //if ($this->debug > 2) { error_log('New LP - Deleting lp '.$this->lp_id.' of type '.$this->type, 0); } if ($this->type == 2 || $this->type == 3) { // This is a scorm learning path, delete the files as well. $sql = "SELECT path FROM $lp WHERE c_id = ".$course_id." AND id = " . $this->lp_id; From 52144e08c68379433e7f00bccbaa5bbdcd8c1826 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 14:31:09 +0200 Subject: [PATCH 093/159] While inserting an obj update the id based in iid. --- main/course_progress/index.php | 9 ++- main/forum/forumfunction.inc.php | 48 +++++++++++--- main/inc/lib/AnnouncementManager.php | 93 ++++++++++++++++------------ main/inc/lib/attendance.lib.php | 30 ++++++++- main/inc/lib/glossary.lib.php | 13 +++- main/inc/lib/link.lib.php | 5 +- main/inc/lib/thematic.lib.php | 24 ++++--- 7 files changed, 160 insertions(+), 62 deletions(-) diff --git a/main/course_progress/index.php b/main/course_progress/index.php index c2238176b6..a2045090e3 100755 --- a/main/course_progress/index.php +++ b/main/course_progress/index.php @@ -78,7 +78,7 @@ $thematic = new Thematic(); // thematic controller object $thematic_controller = new ThematicController(); - +$thematic_data = []; if (!empty($thematic_id)) { // thematic data by id $thematic_data = $thematic->get_thematic_list($thematic_id); @@ -197,7 +197,12 @@ if ($action == 'thematic_details') { } if ($action == 'thematic_plan_list' || $action == 'thematic_plan_delete') { $interbreadcrumb[] = array ('url' => 'index.php?'.api_get_cidreq().'&action='.$_SESSION['thematic_control'], 'name' => get_lang('ThematicControl')); - $interbreadcrumb[] = array ('url' => '#', 'name' => get_lang('ThematicPlan').' ('.$thematic_data['title'].') '); + if (!empty($thematic_data)) { + $interbreadcrumb[] = array( + 'url' => '#', + 'name' => get_lang('ThematicPlan').' ('.$thematic_data['title'].') ' + ); + } } if ($action == 'thematic_plan_add' || $action == 'thematic_plan_edit') { $interbreadcrumb[] = array ('url' => 'index.php?'.api_get_cidreq().'&action='.$_SESSION['thematic_control'], 'name' => get_lang('ThematicControl')); diff --git a/main/forum/forumfunction.inc.php b/main/forum/forumfunction.inc.php index 25aa43c975..a91379e602 100755 --- a/main/forum/forumfunction.inc.php +++ b/main/forum/forumfunction.inc.php @@ -529,7 +529,7 @@ function store_forumcategory($values) cat_comment='".Database::escape_string($values['forum_category_comment'])."' WHERE c_id = $course_id AND cat_id= ".intval($values['forum_category_id']).""; Database::query($sql); - Database::insert_id(); + api_item_property_update( api_get_course_info(), TOOL_FORUM_CATEGORY, @@ -543,6 +543,10 @@ function store_forumcategory($values) VALUES (".$course_id.", '".$clean_cat_title."','".Database::escape_string($values['forum_category_comment'])."','".Database::escape_string($new_max)."','".Database::escape_string($session_id)."')"; Database::query($sql); $last_id = Database::insert_id(); + + $sql = "UPDATE $table_categories SET cat_id = $last_id WHERE iid = $last_id"; + Database::query($sql); + if ($last_id > 0) { api_item_property_update( api_get_course_info(), @@ -702,6 +706,10 @@ function store_forum($values) Database::query($sql); $last_id = Database::insert_id(); if ($last_id > 0) { + + $sql = "UPDATE $table_forums SET forum_id = $last_id WHERE iid = $last_id"; + Database::query($sql); + api_item_property_update($_course, TOOL_FORUM, $last_id, 'ForumAdded', api_get_user_id(), $group_id); api_set_default_visibility($last_id, TOOL_FORUM, $group_id); } @@ -1847,7 +1855,7 @@ function get_post_information($post_id) $table_users = Database :: get_main_table(TABLE_MAIN_USER); $course_id = api_get_course_int_id(); - $sql = "SELECT * FROM ".$table_posts."posts, ".$table_users." users + $sql = "SELECT * FROM ".$table_posts." posts, ".$table_users." users WHERE c_id = $course_id AND posts.poster_id=users.user_id AND @@ -2219,10 +2227,10 @@ function store_thread($current_forum, $values) '".Database::escape_string(stripslashes(isset($values['poster_name']) ? $values['poster_name'] : null))."', '".Database::escape_string($post_date)."', '".Database::escape_string(isset($values['thread_sticky']) ? $values['thread_sticky'] : null)."',". - "'".Database::escape_string(stripslashes($values['calification_notebook_title']))."',". - "'".Database::escape_string($values['numeric_calification'])."',". - "'".Database::escape_string($values['weight_calification'])."',". - "'".api_get_session_id()."')"; + "'".Database::escape_string(stripslashes($values['calification_notebook_title']))."',". + "'".Database::escape_string($values['numeric_calification'])."',". + "'".Database::escape_string($values['weight_calification'])."',". + "'".api_get_session_id()."')"; Database::query($sql); $last_thread_id = Database::insert_id(); @@ -2252,6 +2260,10 @@ function store_thread($current_forum, $values) } if ($last_thread_id) { + + $sql = "UPDATE $table_threads SET thread_id = $last_thread_id WHERE iid = $last_thread_id"; + Database::query($sql); + api_item_property_update($_course, TOOL_FORUM_THREAD, $last_thread_id, 'ForumThreadAdded', api_get_user_id()); // If the forum properties tell that the posts have to be approved we have to put the whole thread invisible, // because otherwise the students will see the thread and not the post in the thread. @@ -2282,6 +2294,11 @@ function store_thread($current_forum, $values) Database::query($sql); $last_post_id = Database::insert_id(); + if ($last_post_id) { + $sql = "UPDATE $table_posts SET post_id = $last_post_id WHERE iid = $last_post_id"; + Database::query($sql); + } + // Update attached files if (!empty($_POST['file_ids']) && is_array($_POST['file_ids'])) { foreach ($_POST['file_ids'] as $key => $id) { @@ -2533,14 +2550,19 @@ function store_theme_qualify($user_id, $thread_id, $thread_qualify = 0, $qualify $course_id = api_get_course_int_id(); - if ($user_id == strval(intval($user_id)) && $thread_id == strval(intval($thread_id)) && $thread_qualify == strval(floatval($thread_qualify))) { + if ($user_id == strval(intval($user_id)) && + $thread_id == strval(intval($thread_id)) && + $thread_qualify == strval(floatval($thread_qualify)) + ) { // Testing - $sql_string = "SELECT thread_qualify_max FROM ".$table_threads." WHERE c_id = $course_id AND thread_id=".$thread_id.";"; + $sql_string = "SELECT thread_qualify_max FROM ".$table_threads." + WHERE c_id = $course_id AND thread_id=".$thread_id.";"; $res_string = Database::query($sql_string); $row_string = Database::fetch_array($res_string); if ($thread_qualify <= $row_string[0]) { - $sql1 = "SELECT COUNT(*) FROM ".$table_threads_qualify." WHERE c_id = $course_id AND user_id=".$user_id." and thread_id=".$thread_id.";"; + $sql1 = "SELECT COUNT(*) FROM ".$table_threads_qualify." + WHERE c_id = $course_id AND user_id=".$user_id." and thread_id=".$thread_id.";"; $res1 = Database::query($sql1); $row = Database::fetch_array($res1); @@ -2549,6 +2571,10 @@ function store_theme_qualify($user_id, $thread_id, $thread_qualify = 0, $qualify VALUES (".$course_id.", '".$user_id."','".$thread_id."',".(float) $thread_qualify.", '".$qualify_user_id."','".$qualify_time."','".$session_id."')"; $res = Database::query($sql); + $insertId = Database::insert_id(); + $sql = "UPDATE $table_threads_qualify SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); + return $res; } else { $sql1 = "SELECT qualify FROM ".$table_threads_qualify." WHERE c_id = $course_id AND user_id=".$user_id." and thread_id=".$thread_id.";"; @@ -2680,6 +2706,10 @@ function store_qualify_historical( VALUES(".$course_id.", '".$user_id."','".$thread_id."',".(float) $row[0].", '".$qualify_user_id."','".$row[1]."','')"; Database::query($sql1); + $insertId = Database::insert_id(); + $sql = "UPDATE $table_threads_qualify_log SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); + // Update $sql2 = "UPDATE ".$table_threads_qualify." SET qualify=".$current_qualify.",qualify_time='".$current_date."' diff --git a/main/inc/lib/AnnouncementManager.php b/main/inc/lib/AnnouncementManager.php index 21ebb9b20b..f25ae521f7 100755 --- a/main/inc/lib/AnnouncementManager.php +++ b/main/inc/lib/AnnouncementManager.php @@ -348,6 +348,9 @@ class AnnouncementManager $last_id = Database::insert($tbl_announcement, $params); + $sql = "UPDATE $tbl_announcement SET id = $last_id WHERE iid = $last_id"; + Database::query($sql); + if (empty($last_id)) { return false; } else { @@ -460,50 +463,58 @@ class AnnouncementManager //store the attach file $last_id = Database::insert_id(); - if (!empty($file)) { - self::add_announcement_attachment_file($last_id, $file_comment, $file); - } + if ($last_id) { + $sql = "UPDATE $lp_item_view_table SET id = $last_id WHERE iid = $last_id"; + Database::query($sql); - // Store in item_property (first the groups, then the users + if (!empty($file)) { + self::add_announcement_attachment_file( + $last_id, + $file_comment, + $file + ); + } - if (!isset($to_users)) { - // when no user is selected we send it to everyone - $send_to = CourseManager::separateUsersGroups($to); - // storing the selected groups - if (is_array($send_to['groups'])) { - foreach ($send_to['groups'] as $group) { - api_item_property_update( - $_course, - TOOL_ANNOUNCEMENT, - $last_id, - "AnnouncementAdded", - api_get_user_id(), - $group - ); + // Store in item_property (first the groups, then the users + + if (!isset($to_users)) { + // when no user is selected we send it to everyone + $send_to = CourseManager::separateUsersGroups($to); + // storing the selected groups + if (is_array($send_to['groups'])) { + foreach ($send_to['groups'] as $group) { + api_item_property_update( + $_course, + TOOL_ANNOUNCEMENT, + $last_id, + "AnnouncementAdded", + api_get_user_id(), + $group + ); + } } - } - } else { - // the message is sent to everyone, so we set the group to 0 - // storing the selected users - if (is_array($to_users)) { - foreach ($to_users as $user) { - api_item_property_update( - $_course, - TOOL_ANNOUNCEMENT, - $last_id, - "AnnouncementAdded", - api_get_user_id(), - '', - $user - ); + } else { + // the message is sent to everyone, so we set the group to 0 + // storing the selected users + if (is_array($to_users)) { + foreach ($to_users as $user) { + api_item_property_update( + $_course, + TOOL_ANNOUNCEMENT, + $last_id, + "AnnouncementAdded", + api_get_user_id(), + '', + $user + ); + } } } - } - if ($sendToUsersInSession) { - self::addAnnouncementToAllUsersInSessions($last_id); + if ($sendToUsersInSession) { + self::addAnnouncementToAllUsersInSessions($last_id); + } } - return $last_id; } @@ -1191,11 +1202,17 @@ class AnnouncementManager $safe_new_file_name = Database::escape_string($new_file_name); // Storing the attachments if any $sql = 'INSERT INTO ' . $tbl_announcement_attachment . ' (c_id, filename, comment, path, announcement_id, size) ' . - "VALUES ($course_id, '$safe_file_name', '$file_comment', '$safe_new_file_name' , '$announcement_id', '" . intval($file['size']) . "' )"; + "VALUES ($course_id, '$safe_file_name', '$file_comment', '$safe_new_file_name' , '$announcement_id', '" . intval($file['size']) . "' )"; $result = Database::query($sql); + + $insertId = Database::insert_id(); + $sql = "UPDATE $tbl_announcement_attachment SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); + $return = 1; } } + return $return; } diff --git a/main/inc/lib/attendance.lib.php b/main/inc/lib/attendance.lib.php index 7690710287..f619673e29 100755 --- a/main/inc/lib/attendance.lib.php +++ b/main/inc/lib/attendance.lib.php @@ -311,6 +311,10 @@ class Attendance if (!empty($affected_rows)) { // save inside item property table $last_id = Database::insert_id(); + + $sql = "UPDATE $tbl_attendance SET cat_id = $last_id WHERE iid = $last_id"; + Database::query($sql); + api_item_property_update($_course, TOOL_ATTENDANCE, $last_id,"AttendanceAdded", $user_id); } // add link to gradebook @@ -710,6 +714,11 @@ class Attendance attendance_calendar_id = '$calendar_id', presence = 1"; $result = Database::query($sql); + + $insertId = Database::insert_id(); + $sql = "UPDATE $tbl_attendance_sheet SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); + $affected_rows += Database::affected_rows($result); } else { $sql = "UPDATE $tbl_attendance_sheet SET presence = 1 @@ -737,6 +746,11 @@ class Attendance attendance_calendar_id = '$calendar_id', presence = 0"; $result = Database::query($sql); + + $insertId = Database::insert_id(); + $sql = "UPDATE $tbl_attendance_sheet SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); + $affected_rows += Database::affected_rows($result); } else { $sql = "UPDATE $tbl_attendance_sheet SET presence = 0 @@ -840,6 +854,10 @@ class Attendance attendance_id = '$attendance_id', score = '$count_presences'"; Database::query($sql); + + $insertId = Database::insert_id(); + $sql = "UPDATE $tbl_attendance_result SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); } } } @@ -887,6 +905,11 @@ class Attendance $result = Database::query($ins); + $insertId = Database::insert_id(); + + $sql = "UPDATE $tbl_attendance_sheet_log SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); + return Database::affected_rows($result); } @@ -1397,6 +1420,8 @@ class Attendance $id = Database::insert($tbl_attendance_calendar, $params); if ($id) { + $sql = "UPDATE $tbl_attendance_calendar SET id = $id WHERE iid = $id"; + Database::query($sql); $affected_rows++; } $this->addAttendanceCalendarToGroup($id, $course_id, $groupList); @@ -1438,7 +1463,10 @@ class Attendance 'c_id' => $courseId, 'group_id' => $groupId, ); - Database::insert($table, $params); + $insertId = Database::insert($table, $params); + + $sql = "UPDATE $table SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); } } } diff --git a/main/inc/lib/glossary.lib.php b/main/inc/lib/glossary.lib.php index 2cf7320069..03416ecb65 100755 --- a/main/inc/lib/glossary.lib.php +++ b/main/inc/lib/glossary.lib.php @@ -120,14 +120,23 @@ class GlossaryManager '".Database::escape_string($session_id)."' )"; $result = Database::query($sql); - if ($result === false) { return false; } + + if ($result === false) { + return false; + } + $id = Database::insert_id(); + + $sql = "UPDATE $t_glossary SET glossary_id = $id WHERE iid = $id"; + Database::query($sql); + //insert into item_property api_item_property_update(api_get_course_info(), TOOL_GLOSSARY, $id, 'GlossaryAdded', api_get_user_id()); $_SESSION['max_glossary_display'] = GlossaryManager::get_max_glossary_item(); // display the feedback message - if ($message) + if ($message) { Display::display_confirmation_message(get_lang('TermAdded')); + } return $id; } diff --git a/main/inc/lib/link.lib.php b/main/inc/lib/link.lib.php index 5260ed99dd..d857756204 100755 --- a/main/inc/lib/link.lib.php +++ b/main/inc/lib/link.lib.php @@ -348,8 +348,11 @@ class Link extends Model '$session_id' )"; Database:: query($sql); - $linkId = Database:: insert_id(); + // iid + $sql = "UPDATE $tbl_categories SET id = $linkId WHERE iid = $linkId"; + Database:: query($sql); + if ($linkId) { // add link_category visibility // course ID is taken from context in api_set_default_visibility diff --git a/main/inc/lib/thematic.lib.php b/main/inc/lib/thematic.lib.php index bea5131f97..66b29b03b2 100755 --- a/main/inc/lib/thematic.lib.php +++ b/main/inc/lib/thematic.lib.php @@ -296,9 +296,9 @@ class Thematic VALUES ($this->course_int_id, '$title', '$content', 1, ".(intval($max_thematic_item)+1).", $session_id) "; $result = Database::query($sql); $last_id = Database::insert_id(); - if (Database::affected_rows($result)) { - // save inside item property table - $last_id = Database::insert_id(); + if ($last_id) { + $sql = "UPDATE $tbl_thematic SET id = $last_id WHERE iid = $last_id"; + Database::query($sql); api_item_property_update($_course, 'thematic', $last_id,"ThematicAdded", $user_id); } } else { @@ -633,7 +633,7 @@ class Thematic if (in_array($row['thematic_id'], $tmp)) { if ($force_session_id) { if (in_array($row['id'], array_keys($elements))) { - $row['session_id'] = $elements[$row['id']]['id_session']; + $row['session_id'] = $elements[$row['id']]['session_id']; $data[$row['thematic_id']][$row['id']] = $row; } } else { @@ -644,6 +644,7 @@ class Thematic } } } + return $data; } @@ -676,7 +677,10 @@ class Thematic $result = Database::query($sql); $last_id = Database::insert_id(); - if (Database::affected_rows($result)) { + if ($last_id) { + $sql = "UPDATE $tbl_thematic_advance SET id = $last_id WHERE iid = $last_id"; + Database::query($sql); + api_item_property_update($_course, 'thematic_advance', $last_id,"ThematicAdvanceAdded", $user_id); } } else { @@ -868,8 +872,9 @@ class Thematic VALUES ($this->course_int_id, $thematic_id, '$title', '$description', $description_type) "; $result = Database::query($ins); $last_id = Database::insert_id(); - $affected_rows = Database::affected_rows($result); - if ($affected_rows) { + if ($last_id) { + $sql = "UPDATE $tbl_thematic_plan SET id = $last_id WHERE iid = $last_id"; + Database::query($sql); api_item_property_update($_course, 'thematic_plan', $last_id,"ThematicPlanAdded", $user_id); } } @@ -879,8 +884,9 @@ class Thematic VALUES($this->course_int_id, $thematic_id, '$title', '$description', $description_type) "; $result = Database::query($ins); $last_id = Database::insert_id(); - $affected_rows = Database::affected_rows($result); - if ($affected_rows) { + if ($last_id) { + $sql = "UPDATE $tbl_thematic_plan SET id = $last_id WHERE iid = $last_id"; + Database::query($sql); api_item_property_update($_course, 'thematic_plan', $last_id,"ThematicPlanAdded", $user_id); } } From 2738abd54a49ccde5ec51b91887d45463bb15e57 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 16:57:25 +0200 Subject: [PATCH 094/159] Rename survey_manager with SurveyManager + fix queries. --- .../classes/CourseRestorer.class.php | 4 +- main/inc/lib/surveymanager.lib.php | 1 + main/survey/copy_survey.php | 6 +- main/survey/create_new_survey.php | 8 +- main/survey/fillsurvey.php | 6 +- main/survey/generate_link.php | 6 +- main/survey/link.php | 6 +- main/survey/preview.php | 4 +- main/survey/question.php | 4 +- main/survey/reporting.php | 8 +- main/survey/survey.lib.php | 139 +++++++++++++----- main/survey/survey.php | 6 +- main/survey/survey_invitation.php | 4 +- main/survey/survey_invite.php | 2 +- main/survey/survey_list.php | 16 +- main/survey/survey_question.php | 4 +- tests/main/survey/survey.lib.test.php | 88 +++++------ 17 files changed, 188 insertions(+), 124 deletions(-) diff --git a/main/coursecopy/classes/CourseRestorer.class.php b/main/coursecopy/classes/CourseRestorer.class.php index 4a997be11a..f8b8517d0c 100755 --- a/main/coursecopy/classes/CourseRestorer.class.php +++ b/main/coursecopy/classes/CourseRestorer.class.php @@ -1877,9 +1877,9 @@ class CourseRestorer // if the survey is shared => also delete the shared content if (isset($survey_data['survey_share']) && is_numeric($survey_data['survey_share'])) { - survey_manager::delete_survey($survey_data['survey_share'], true,$this->destination_course_id); + SurveyManager::delete_survey($survey_data['survey_share'], true,$this->destination_course_id); } - $return = survey_manager :: delete_survey($survey_data['survey_id'],false,$this->destination_course_id); + $return = SurveyManager :: delete_survey($survey_data['survey_id'],false,$this->destination_course_id); //Insert the new source survey Database::query($sql); diff --git a/main/inc/lib/surveymanager.lib.php b/main/inc/lib/surveymanager.lib.php index 3871d8a8f1..733de3900e 100755 --- a/main/inc/lib/surveymanager.lib.php +++ b/main/inc/lib/surveymanager.lib.php @@ -1,5 +1,6 @@ validate()) { // Exporting the values $values = $form->exportValues(); // Storing the survey - $return = survey_manager::store_survey($values); + $return = SurveyManager::store_survey($values); /* // Deleting the shared survey if the survey is getting unshared (this only happens when editing) if (is_numeric($survey_data['survey_share']) && $values['survey_share']['survey_share'] == 0 && $values['survey_id'] != '') { - survey_manager::delete_survey($survey_data['survey_share'], true); + SurveyManager::delete_survey($survey_data['survey_share'], true); } // Storing the already existing questions and options of a survey that gets shared (this only happens when editing) if ($survey_data['survey_share'] == 0 && $values['survey_share']['survey_share'] !== 0 && $values['survey_id'] != '') { - survey_manager::get_complete_survey_structure($return['id']); + SurveyManager::get_complete_survey_structure($return['id']); } */ if ($return['type'] == 'error') { diff --git a/main/survey/fillsurvey.php b/main/survey/fillsurvey.php index 6f501974fd..a0b5e0eb96 100755 --- a/main/survey/fillsurvey.php +++ b/main/survey/fillsurvey.php @@ -106,7 +106,7 @@ if ($invitationcode == 'auto' && isset($_GET['scode'])) { if (Database :: num_rows($result) > 0) { // Ok // Check availability $row = Database :: fetch_array($result, 'ASSOC'); - $tempdata = survey_manager :: get_survey($row['survey_id']); + $tempdata = SurveyManager :: get_survey($row['survey_id']); //exit if survey not available anymore check_time_availability($tempdata); // Check for double invitation records (insert should be done once) @@ -181,7 +181,7 @@ if (Database::num_rows($result) > 1) { } // Getting the survey information -$survey_data = survey_manager::get_survey($survey_invitation['survey_id']); +$survey_data = SurveyManager::get_survey($survey_invitation['survey_id']); $survey_data['survey_id'] = $survey_invitation['survey_id']; // Storing the answers @@ -552,7 +552,7 @@ if (isset($_POST['finish_survey'])) { Display::display_confirmation_message(get_lang('SurveyFinished')); echo $survey_data['survey_thanks']; - survey_manager::update_survey_answered( + SurveyManager::update_survey_answered( $survey_data, $survey_invitation['user'], $survey_invitation['survey_code'] diff --git a/main/survey/generate_link.php b/main/survey/generate_link.php index 7cde63fcaa..1be4139c19 100755 --- a/main/survey/generate_link.php +++ b/main/survey/generate_link.php @@ -12,18 +12,18 @@ if (empty($survey_id)) { api_not_allowed(true); } -$survey_data = survey_manager::get_survey($survey_id); +$survey_data = SurveyManager::get_survey($survey_id); $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php', 'name' => get_lang('SurveyList')); $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id, 'name' => strip_tags($survey_data['title'])); Display::display_header(get_lang('Survey'), 'Survey'); -if (!survey_manager::survey_generation_hash_available()) { +if (!SurveyManager::survey_generation_hash_available()) { api_not_allowed(true); } -$link = survey_manager::generate_survey_link($survey_id, api_get_course_int_id(), api_get_session_id(), api_get_group_id()); +$link = SurveyManager::generate_survey_link($survey_id, api_get_course_int_id(), api_get_session_id(), api_get_group_id()); echo '
      '; echo '
      '; echo Display::url(get_lang('GenerateSurveyAccessLink'), $link, array('class' => 'btn btn-primary btn-large')); diff --git a/main/survey/link.php b/main/survey/link.php index 5563018f69..015c685feb 100755 --- a/main/survey/link.php +++ b/main/survey/link.php @@ -8,14 +8,14 @@ $survey_id = isset($_REQUEST['i']) ? intval($_REQUEST['i']) : null; if (empty($survey_id)) { api_not_allowed(true); } -if (!survey_manager::survey_generation_hash_available()) { +if (!SurveyManager::survey_generation_hash_available()) { api_not_allowed(true); } $course_info = api_get_course_info_by_id($_REQUEST['c']); -$hash_is_valid = survey_manager::validate_survey_hash($survey_id, $_REQUEST['c'], $_REQUEST['s'], $_REQUEST['g'], $_REQUEST['h']); +$hash_is_valid = SurveyManager::validate_survey_hash($survey_id, $_REQUEST['c'], $_REQUEST['s'], $_REQUEST['g'], $_REQUEST['h']); if ($hash_is_valid && $course_info) { - $survey_data = survey_manager::get_survey($survey_id, null, $course_info['code']); + $survey_data = SurveyManager::get_survey($survey_id, null, $course_info['code']); $invitation_code = api_get_unique_id(); diff --git a/main/survey/preview.php b/main/survey/preview.php index 2db0c72bb1..5e6b41edc6 100755 --- a/main/survey/preview.php +++ b/main/survey/preview.php @@ -52,7 +52,7 @@ if (!isset($_GET['survey_id']) || !is_numeric($_GET['survey_id'])){ // Getting the survey information $survey_id = intval($_GET['survey_id']); -$survey_data = survey_manager::get_survey($survey_id); +$survey_data = SurveyManager::get_survey($survey_id); if (empty($survey_data)) { Display::display_header(get_lang('SurveyPreview')); @@ -68,7 +68,7 @@ if (api_is_allowed_to_edit()) { $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id, 'name' => $urlname); } $courseCode = isset($_GET['cidReq']) ? $_GET['cidReq'] : null; -$surveyAnonymous = survey_manager::get_survey($survey_id, 0, $courseCode); +$surveyAnonymous = SurveyManager::get_survey($survey_id, 0, $courseCode); $surveyAnonymous = $surveyAnonymous['anonymous']; if ($surveyAnonymous == 0 && api_is_anonymous()) { api_not_allowed(true); diff --git a/main/survey/question.php b/main/survey/question.php index 80d35ca9a8..5a6cfcc953 100755 --- a/main/survey/question.php +++ b/main/survey/question.php @@ -48,7 +48,7 @@ $table_user = Database:: get_main_table(TABLE_MAIN_USER); $course_id = api_get_course_int_id(); // Getting the survey information -$surveyData = survey_manager::get_survey($_GET['survey_id']); +$surveyData = SurveyManager::get_survey($_GET['survey_id']); if (empty($surveyData)) { Display :: display_header(get_lang('ToolSurvey')); @@ -146,7 +146,7 @@ if ($_GET['type'] == 'personality') { // We are editing a question if (isset($_GET['question_id']) && !empty($_GET['question_id'])) { - $formData = survey_manager::get_question($_GET['question_id']); + $formData = SurveyManager::get_question($_GET['question_id']); } $formData = $surveyQuestion->preSave($formData); diff --git a/main/survey/reporting.php b/main/survey/reporting.php index 9c6a6e635e..b71c784a11 100755 --- a/main/survey/reporting.php +++ b/main/survey/reporting.php @@ -15,7 +15,7 @@ require_once '../inc/global.inc.php'; $this_section = SECTION_COURSES; $cidReq = api_get_cidreq(); $survey_id = intval($_GET['survey_id']); -$survey_data = survey_manager::get_survey($survey_id); +$survey_data = SurveyManager::get_survey($survey_id); // Export /** @@ -66,7 +66,7 @@ if ($survey_data['anonymous'] == 0) { } else { $people_filled_full_data = false; } -$people_filled = survey_manager::get_people_who_filled_survey( +$people_filled = SurveyManager::get_people_who_filled_survey( $_GET['survey_id'], $people_filled_full_data ); @@ -74,7 +74,7 @@ $people_filled = survey_manager::get_people_who_filled_survey( // Checking the parameters SurveyUtil::check_parameters($people_filled); -$survey_data = survey_manager::get_survey($survey_id); +$survey_data = SurveyManager::get_survey($survey_id); $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh( api_get_user_id(), @@ -99,7 +99,7 @@ $table_user = Database:: get_main_table(TABLE_MAIN_USER); // Getting the survey information -//$survey_data = survey_manager::get_survey($survey_id); +//$survey_data = SurveyManager::get_survey($survey_id); if (empty($survey_data)) { Display :: display_header(get_lang('ToolSurvey')); Display :: display_error_message(get_lang('InvallidSurvey'), false); diff --git a/main/survey/survey.lib.php b/main/survey/survey.lib.php index 19e005e901..68ccf03a89 100755 --- a/main/survey/survey.lib.php +++ b/main/survey/survey.lib.php @@ -2,7 +2,7 @@ /* For licensing terms, see /license.txt */ /** - * Class survey_manager + * Class SurveyManager * @package chamilo.survey * @author Patrick Cool , Ghent University: * cleanup, refactoring and rewriting large parts (if not all) of the code @@ -12,7 +12,7 @@ * @todo move this file to inc/lib * @todo use consistent naming for the functions (save vs store for instance) */ -class survey_manager +class SurveyManager { /** * @param $code @@ -339,12 +339,22 @@ class survey_manager Database::query($sql); $survey_id = Database::insert_id(); if ($survey_id > 0) { + + $sql = "UPDATE $table_survey SET survey_id = $survey_id WHERE iid = $survey_id"; + Database::query($sql); + // Insert into item_property - api_item_property_update(api_get_course_info(), TOOL_SURVEY, $survey_id, 'SurveyAdded', api_get_user_id()); + api_item_property_update( + api_get_course_info(), + TOOL_SURVEY, + $survey_id, + 'SurveyAdded', + api_get_user_id() + ); } if ($values['survey_type'] == 1 && !empty($values['parent_id'])) { - survey_manager::copy_survey($values['parent_id'], $survey_id); + SurveyManager::copy_survey($values['parent_id'], $survey_id); } $return['message'] = 'SurveyCreatedSuccesfully'; @@ -464,6 +474,10 @@ class survey_manager '".$_course['id']."')"; Database::query($sql); $return = Database::insert_id(); + + $sql = "UPDATE $table_survey SET survey_id = $return WHERE iid = $return"; + Database::query($sql); + } else { $sql = "UPDATE $table_survey SET code = '".Database::escape_string($values['survey_code'])."', @@ -524,7 +538,7 @@ class survey_manager Database::query($sql); // Deleting the questions of the survey - survey_manager::delete_all_survey_questions($survey_id, $shared); + SurveyManager::delete_all_survey_questions($survey_id, $shared); // Update into item_property (delete) api_item_property_update($course_info, TOOL_SURVEY, $survey_id, 'SurveyDeleted', api_get_user_id()); @@ -568,8 +582,17 @@ class survey_manager Database::insert($table_survey, $params); $new_survey_id = Database::insert_id(); + $sql = "UPDATE $table_survey SET survey_id = $new_survey_id WHERE iid = $new_survey_id"; + Database::query($sql); + // Insert into item_property - api_item_property_update(api_get_course_info(), TOOL_SURVEY, $new_survey_id, 'SurveyAdded', api_get_user_id()); + api_item_property_update( + api_get_course_info(), + TOOL_SURVEY, + $new_survey_id, + 'SurveyAdded', + api_get_user_id() + ); } else { $new_survey_id = intval($new_survey_id); } @@ -586,6 +609,9 @@ class survey_manager ); $insertId = Database::insert($table_survey_question_group, $params); + $sql = "UPDATE $table_survey_question_group SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); + $group_id[$row['id']] = $insertId; } @@ -609,6 +635,10 @@ class survey_manager 'survey_group_sec2' => $row['survey_group_sec2'] ); $insertId = Database::insert($table_survey_question, $params); + + $sql = "UPDATE $table_survey_question SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); + $question_id[$row['question_id']] = $insertId; } @@ -626,7 +656,10 @@ class survey_manager 'sort' => $row['sort'], 'value' => $row['value'] ); - Database::insert($table_survey_options, $params); + $insertId = Database::insert($table_survey_options, $params); + + $sql = "UPDATE $table_survey_options SET question_option_id = $insertId WHERE iid = $insertId"; + Database::query($sql); } return $new_survey_id; @@ -651,7 +684,7 @@ class survey_manager $course_id = $courseId ? $courseId : api_get_course_int_id(); - $datas = survey_manager::get_survey($survey_id); + $datas = SurveyManager::get_survey($survey_id); $session_where = ''; if (api_get_session_id() != 0) { $session_where = ' AND session_id = "'.api_get_session_id().'" '; @@ -692,7 +725,7 @@ class survey_manager $session_id = $survey_data['session_id']; // Getting a list with all the people who have filled the survey - $people_filled = survey_manager::get_people_who_filled_survey($survey_id, false, $course_id); + $people_filled = SurveyManager::get_people_who_filled_survey($survey_id, false, $course_id); $number = intval(count($people_filled)); @@ -729,8 +762,8 @@ class survey_manager */ public static function get_complete_survey_structure($survey_id, $shared = 0) { - $structure = survey_manager::get_survey($survey_id, $shared); - $structure['questions'] = survey_manager::get_questions($survey_id); + $structure = SurveyManager::get_survey($survey_id, $shared); + $structure['questions'] = SurveyManager::get_questions($survey_id); } /*** @@ -946,11 +979,11 @@ class survey_manager $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION); // Getting all the information of the survey - $survey_data = survey_manager::get_survey($form_content['survey_id']); + $survey_data = SurveyManager::get_survey($form_content['survey_id']); // Storing the question in the shared database if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) { - $shared_question_id = survey_manager::save_shared_question($form_content, $survey_data); + $shared_question_id = SurveyManager::save_shared_question($form_content, $survey_data); $form_content['shared_question_id'] = $shared_question_id; } @@ -998,6 +1031,11 @@ class survey_manager )"; Database::query($sql); $question_id = Database::insert_id(); + + $sql = "UPDATE $tbl_survey_question SET question_id = $question_id + WHERE iid = $question_id"; + Database::query($sql); + $form_content['question_id'] = $question_id; $return_message = 'QuestionAdded'; @@ -1027,7 +1065,9 @@ class survey_manager display = '".Database::escape_string($form_content['horizontalvertical'])."', max_value = '".Database::escape_string($maxScore)."' $additionalsets - WHERE c_id = $course_id AND question_id = ".intval($form_content['question_id'])." + WHERE + c_id = $course_id AND + question_id = ".intval($form_content['question_id'])." "; Database::query($sql); $return_message = 'QuestionUpdated'; @@ -1045,7 +1085,7 @@ class survey_manager } // Storing the options of the question - survey_manager::save_question_options($form_content, $survey_data); + SurveyManager::save_question_options($form_content, $survey_data); } else { $return_message = 'PleasFillAllAnswer'; } @@ -1192,10 +1232,10 @@ class survey_manager Database::query($sql); // Deleting all the options of the questions of the survey - survey_manager::delete_all_survey_questions_options($survey_id, $shared); + SurveyManager::delete_all_survey_questions_options($survey_id, $shared); // Deleting all the answers on this survey - survey_manager::delete_all_survey_answers($survey_id); + SurveyManager::delete_all_survey_answers($survey_id); } /** @@ -1216,7 +1256,7 @@ class survey_manager // Table definitions $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION); if ($shared) { - survey_manager::delete_shared_survey_question($survey_id, $question_id); + SurveyManager::delete_shared_survey_question($survey_id, $question_id); } // Deleting the survey questions @@ -1228,7 +1268,7 @@ class survey_manager Database::query($sql); // Deleting the options of the question of the survey - survey_manager::delete_survey_question_option($survey_id, $question_id, $shared); + SurveyManager::delete_survey_question_option($survey_id, $question_id, $shared); } /** @@ -1249,7 +1289,7 @@ class survey_manager $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION); // First we have to get the shared_question_id - $question_data = survey_manager::get_question($question_id); + $question_data = SurveyManager::get_question($question_id); // Deleting the survey questions $sql = "DELETE FROM $table_survey_question @@ -1282,11 +1322,11 @@ class survey_manager } if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) { - survey_manager::save_shared_question_options($form_content, $survey_data); + SurveyManager::save_shared_question_options($form_content, $survey_data); } // Table definition - $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION); + $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION); // We are editing a question so we first have to remove all the existing options from the database if (is_numeric($form_content['question_id'])) { @@ -1308,6 +1348,14 @@ class survey_manager '".Database::escape_string($values)."', '".Database::escape_string($counter)."')"; Database::query($sql); + + $insertId = Database::insert_id(); + + $sql = "UPDATE $table_survey_question_option + SET question_option_id = $insertId + WHERE iid = $insertId"; + Database::query($sql); + $counter++; } } @@ -1327,19 +1375,20 @@ class survey_manager { if (is_array($form_content) && is_array($form_content['answers'])) { // Table defintion - $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION); + $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION); // We are editing a question so we first have to remove all the existing options from the database - $sql = "DELETE FROM $table_survey_question_option WHERE question_id = '".Database::escape_string($form_content['shared_question_id'])."'"; + $sql = "DELETE FROM $table_survey_question_option + WHERE question_id = '".Database::escape_string($form_content['shared_question_id'])."'"; Database::query($sql); $counter = 1; foreach ($form_content['answers'] as & $answer) { $sql = "INSERT INTO $table_survey_question_option (question_id, survey_id, option_text, sort) VALUES ( - '".Database::escape_string($form_content['shared_question_id'])."', - '".Database::escape_string($survey_data['is_shared'])."', - '".Database::escape_string($answer)."', - '".Database::escape_string($counter)."')"; + '".Database::escape_string($form_content['shared_question_id'])."', + '".Database::escape_string($survey_data['is_shared'])."', + '".Database::escape_string($answer)."', + '".Database::escape_string($counter)."')"; Database::query($sql); $counter++; } @@ -1647,6 +1696,10 @@ class SurveyUtil '".Database::escape_string($option_value)."' )"; Database::query($sql); + $insertId = Database::insert_id(); + + $sql = "UPDATE $table_survey_answer SET answer_id = $insertId WHERE iid = $insertId"; + Database::query($sql); } /** @@ -1661,7 +1714,7 @@ class SurveyUtil $error = false; // Getting the survey data - $survey_data = survey_manager::get_survey($_GET['survey_id']); + $survey_data = SurveyManager::get_survey($_GET['survey_id']); // $_GET['survey_id'] has to be numeric if (!is_numeric($_GET['survey_id'])) { @@ -1669,7 +1722,14 @@ class SurveyUtil } // $_GET['action'] - $allowed_actions = array('overview', 'questionreport', 'userreport', 'comparativereport', 'completereport','deleteuserreport'); + $allowed_actions = array( + 'overview', + 'questionreport', + 'userreport', + 'comparativereport', + 'completereport', + 'deleteuserreport' + ); if (isset($_GET['action']) && !in_array($_GET['action'], $allowed_actions)) { $error = get_lang('ActionNotAllowed'); } @@ -1718,7 +1778,7 @@ class SurveyUtil $action = isset($_GET['action']) ? $_GET['action'] : null; // Getting the number of question - $temp_questions_data = survey_manager::get_questions($_GET['survey_id']); + $temp_questions_data = SurveyManager::get_questions($_GET['survey_id']); // Sorting like they should be displayed and removing the non-answer question types (comment and pagebreak) $my_temp_questions_data = $temp_questions_data == null ? array() : $temp_questions_data; @@ -2995,7 +3055,7 @@ class SurveyUtil $allowed_question_types = array('yesno', 'multiplechoice', 'multipleresponse', 'dropdown', 'percentage', 'score'); // Getting all the questions - $questions = survey_manager::get_questions($_GET['survey_id']); + $questions = SurveyManager::get_questions($_GET['survey_id']); // Actions bar @@ -3047,12 +3107,12 @@ class SurveyUtil // Getting all the information of the x axis if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis'])) { - $question_x = survey_manager::get_question($_GET['xaxis']); + $question_x = SurveyManager::get_question($_GET['xaxis']); } // Getting all the information of the y axis if (isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) { - $question_y = survey_manager::get_question($_GET['yaxis']); + $question_y = SurveyManager::get_question($_GET['yaxis']); } if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis']) && isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) { @@ -3383,7 +3443,7 @@ class SurveyUtil } // Getting the survey information - $survey_data = survey_manager::get_survey($_GET['survey_id']); + $survey_data = SurveyManager::get_survey($_GET['survey_id']); $survey_invitations = SurveyUtil::get_invitations($survey_data['survey_code']); $already_invited = SurveyUtil::get_invited_users($survey_data['code']); @@ -3391,7 +3451,7 @@ class SurveyUtil $exclude_users = array(); if ($remindUnAnswered == 1) { // Remind only unanswered users $reminder = 1; - $exclude_users = survey_manager::get_people_who_filled_survey($_GET['survey_id']); + $exclude_users = SurveyManager::get_people_who_filled_survey($_GET['survey_id']); } $counter = 0; // Nr of invitations "sent" (if sendmail option) @@ -3494,7 +3554,10 @@ class SurveyUtil (!empty($params['user']) || !empty($params['group_id'])) && !empty($params['survey_code']) ) { - return Database::insert($table, $params); + $insertedId = Database::insert($table, $params); + + $sql = "UPDATE $table SET survey_invitation_id = $insertId WHERE iid = $insertId"; + Database::query($sql); } return false; } @@ -3918,7 +3981,7 @@ class SurveyUtil api_is_element_in_the_session(TOOL_SURVEY, $survey_id) ) { $return .= ''.Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).''; - if (survey_manager::survey_generation_hash_available()) { + if (SurveyManager::survey_generation_hash_available()) { $return .= Display::url( Display::return_icon('new_link.png', get_lang('GenerateSurveyAccessLink'),'',ICON_SIZE_SMALL), api_get_path(WEB_CODE_PATH).'survey/generate_link.php?survey_id='.$survey_id.'&'.api_get_cidreq() diff --git a/main/survey/survey.php b/main/survey/survey.php index d4d8c68d5f..61fd907d14 100755 --- a/main/survey/survey.php +++ b/main/survey/survey.php @@ -56,7 +56,7 @@ $interbreadcrumb[] = array ('url' => api_get_path(WEB_CODE_PATH).'survey/survey_ if (isset($_GET['survey_id'])) { $course_code = api_get_course_id(); if ($course_code!=-1) { - $survey_data = survey_manager::get_survey($survey_id); + $survey_data = SurveyManager::get_survey($survey_id); } else { Display :: display_header(get_lang('ToolSurvey')); Display :: display_error_message(get_lang('NotAllowed'), false); @@ -108,11 +108,11 @@ $message_information = isset($_GET['message']) ? Security::remove_XSS($_GET[' if (isset($action)) { if (($action == 'moveup' || $action == 'movedown') && isset($_GET['question_id'])) { - survey_manager::move_survey_question($my_action_survey,$my_question_id_survey,$my_survey_id_survey); + SurveyManager::move_survey_question($my_action_survey,$my_question_id_survey,$my_survey_id_survey); Display::display_confirmation_message(get_lang('SurveyQuestionMoved')); } if ($action == 'delete' AND is_numeric($_GET['question_id'])) { - survey_manager::delete_survey_question($my_survey_id_survey, $my_question_id_survey, $survey_data['is_shared']); + SurveyManager::delete_survey_question($my_survey_id_survey, $my_question_id_survey, $survey_data['is_shared']); } } diff --git a/main/survey/survey_invitation.php b/main/survey/survey_invitation.php index 89fd8874d4..eb823fec40 100755 --- a/main/survey/survey_invitation.php +++ b/main/survey/survey_invitation.php @@ -40,7 +40,7 @@ if (!isset($_GET['survey_id']) OR !is_numeric($_GET['survey_id'])) { } $survey_id = Security::remove_XSS($_GET['survey_id']); -$survey_data = survey_manager::get_survey($survey_id); +$survey_data = SurveyManager::get_survey($survey_id); if (empty($survey_data)) { Display :: display_header($tool_name); @@ -70,7 +70,7 @@ if (!is_numeric($survey_id)) { } // Getting all the people who have filled this survey -$answered_data = survey_manager::get_people_who_filled_survey($survey_id); +$answered_data = SurveyManager::get_people_who_filled_survey($survey_id); if ($survey_data['anonymous'] == 1) { Display::display_normal_message(get_lang('AnonymousSurveyCannotKnowWhoAnswered').' '.count($answered_data).' '.get_lang('PeopleAnswered')); $answered_data = array(); diff --git a/main/survey/survey_invite.php b/main/survey/survey_invite.php index 3e5ae5ff18..c056c63816 100755 --- a/main/survey/survey_invite.php +++ b/main/survey/survey_invite.php @@ -35,7 +35,7 @@ $course_id = api_get_course_int_id(); // Getting the survey information $survey_id = Security::remove_XSS($_GET['survey_id']); -$survey_data = survey_manager::get_survey($survey_id); +$survey_data = SurveyManager::get_survey($survey_id); if (empty($survey_data)) { Display :: display_header(get_lang('ToolSurvey')); Display :: display_error_message(get_lang('InvallidSurvey'), false); diff --git a/main/survey/survey_list.php b/main/survey/survey_list.php index 5580c468e3..53a1ffee7c 100755 --- a/main/survey/survey_list.php +++ b/main/survey/survey_list.php @@ -70,7 +70,7 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') { if ($action == 'copy_survey') { if (api_is_allowed_to_edit()) { - survey_manager::copy_survey($_GET['survey_id']); + SurveyManager::copy_survey($_GET['survey_id']); $message = get_lang('Copied'); header('Location: ' . api_get_path(WEB_CODE_PATH) . 'survey/survey_list.php?' . api_get_cidreq()); exit; @@ -90,7 +90,7 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') { // Action handling: deleting a survey if ($action == 'delete' && isset($_GET['survey_id'])) { // Getting the information of the survey (used for when the survey is shared) - $survey_data = survey_manager::get_survey($_GET['survey_id']); + $survey_data = SurveyManager::get_survey($_GET['survey_id']); if (api_is_course_coach() && intval($_SESSION['id_session']) != $survey_data['session_id']) { // The coach can't delete a survey not belonging to his session api_not_allowed(); @@ -98,10 +98,10 @@ if ($action == 'delete' && isset($_GET['survey_id'])) { } // If the survey is shared => also delete the shared content if (is_numeric($survey_data['survey_share'])) { - survey_manager::delete_survey($survey_data['survey_share'], true); + SurveyManager::delete_survey($survey_data['survey_share'], true); } - $return = survey_manager::delete_survey($_GET['survey_id']); + $return = SurveyManager::delete_survey($_GET['survey_id']); if ($return) { Display::display_confirmation_message(get_lang('SurveyDeleted'), false); @@ -125,7 +125,7 @@ if ($action == 'empty') { exit; } } - $return = survey_manager::empty_survey(intval($_GET['survey_id'])); + $return = SurveyManager::empty_survey(intval($_GET['survey_id'])); if ($return) { Display :: display_confirmation_message(get_lang('SurveyEmptied'), false); } else { @@ -138,13 +138,13 @@ if (isset($_POST['action']) && $_POST['action']) { if (is_array($_POST['id'])) { foreach ($_POST['id'] as $key => & $value) { // getting the information of the survey (used for when the survey is shared) - $survey_data = survey_manager::get_survey($value); + $survey_data = SurveyManager::get_survey($value); // if the survey is shared => also delete the shared content if (is_numeric($survey_data['survey_share'])) { - survey_manager::delete_survey($survey_data['survey_share'], true); + SurveyManager::delete_survey($survey_data['survey_share'], true); } // delete the actual survey - survey_manager::delete_survey($value); + SurveyManager::delete_survey($value); } Display :: display_confirmation_message(get_lang('SurveysDeleted'), false); } else { diff --git a/main/survey/survey_question.php b/main/survey/survey_question.php index cd4fcafec5..6007296bce 100644 --- a/main/survey/survey_question.php +++ b/main/survey/survey_question.php @@ -26,7 +26,7 @@ class survey_question $surveyId = isset($_GET['survey_id']) ? intval($_GET['survey_id']) : null; $toolName = Display::return_icon( - survey_manager::icon_question(Security::remove_XSS($_GET['type'])), + SurveyManager::icon_question(Security::remove_XSS($_GET['type'])), get_lang(ucfirst(Security::remove_XSS($_GET['type']))), array('align' => 'middle', 'height' => '22px') ).' '; @@ -255,7 +255,7 @@ class survey_question if (isset($_POST['buttons']) && isset($_POST['buttons']['save'])) { Session::erase('answer_count'); Session::erase('answer_list'); - $message = survey_manager::save_question( + $message = SurveyManager::save_question( $surveyData, $formData ); diff --git a/tests/main/survey/survey.lib.test.php b/tests/main/survey/survey.lib.test.php index b9a912845c..e15852fc51 100755 --- a/tests/main/survey/survey.lib.test.php +++ b/tests/main/survey/survey.lib.test.php @@ -14,25 +14,25 @@ class TestSurvey extends UnitTestCase { $this->UnitTestCase(''); } - public function setUp() { - $this->smanager = new survey_manager(); + public function setUp() { + $this->smanager = new SurveyManager(); $this->squestion = new question(); $this->syesno = new yesno(); $this->smultiplechoice = new multiplechoice(); $this->spersonality = new personality(); - $this->smultipleresponse = new multipleresponse(); + $this->smultipleresponse = new multipleresponse(); } - public function tearDown() { + public function tearDown() { $this-> smanager = null; $this-> squestion = null; $this-> syesno = null; $this->smultiplechoice = null; $this->personality = null; - $this->multipleresponse = null; + $this->multipleresponse = null; } - - + + public function testStoreSurvey() { global $_user,$cidReq; $values = array( @@ -45,20 +45,20 @@ class TestSurvey extends UnitTestCase { 'survey_introduction' => '', 'survey_thanks' => '', 'survey_type' => '0', - 'parent_id' => '0', - 'submit_survey' => '' - ); + 'parent_id' => '0', + 'submit_survey' => '' + ); $res = $this->smanager->store_survey($values); $this->assertTrue($res); - $this->assertTrue(is_array($res)); + $this->assertTrue(is_array($res)); } - - public function testGetSurvey() { - $course_code = 'COURSETEST'; + + public function testGetSurvey() { + $course_code = 'COURSETEST'; $survey_id=1; $res3 = $this->smanager->get_survey($survey_id,0,$course_code); - $this->assertTrue(is_array($res3)); + $this->assertTrue(is_array($res3)); } public function testStoreSharedSurvey() { @@ -73,9 +73,9 @@ class TestSurvey extends UnitTestCase { 'survey_introduction' => 'introduction', 'survey_thanks' => '', 'survey_type' => '1', - 'parent_id' => '1', - 'submit_survey' => '' - ); + 'parent_id' => '1', + 'submit_survey' => '' + ); $res = $this->smanager->store_shared_survey($values); $this->assertTrue($res); //var_dump($res); @@ -98,19 +98,19 @@ class TestSurvey extends UnitTestCase { $this->assertNotNull($this->squestion->html); //var_dump($res); } - + public function testYesNoCreateForm() { $form_content=array(); $res1 = $this->syesno->create_form($form_content); $this->assertNull($res1); } - public function testMultipleChoiceCreateForm() { + public function testMultipleChoiceCreateForm() { $form_content=array(); $res2 = $this->smultiplechoice->create_form($form_content); - $this->assertNull($res2); + $this->assertNull($res2); } - + public function testPersonalityCreateForm() { $form_content=array(); @@ -125,7 +125,7 @@ class TestSurvey extends UnitTestCase { $this->assertNotNull($this->smultipleresponse->html); $this->assertTrue($this->smultipleresponse->html); } - + public function testQuestionRenderQuestion() { ob_start(); $form_content=array(); @@ -134,7 +134,7 @@ class TestSurvey extends UnitTestCase { $this->assertTrue(is_null($res)); ob_end_clean(); } - + public function testMultipleChoiseRenderQuestion() { ob_start(); $form_content=array(); @@ -143,7 +143,7 @@ class TestSurvey extends UnitTestCase { $this->assertNull($this->smultiplechoice->html); ob_end_clean(); } - + public function testYesNoRenderQuestion() { ob_start(); $form_content=array(); @@ -171,7 +171,7 @@ class TestSurvey extends UnitTestCase { } //save the survey - + public function testCopySurvey() { $parent_survey = Database::escape_string($parent_survey); $new_survey_id = '1'; @@ -204,7 +204,7 @@ class TestSurvey extends UnitTestCase { } //var_dump($res); } - + public function testSaveQuestion() { $form_content=array(); $res = $this->smanager->save_question($form_content); @@ -237,13 +237,13 @@ class TestSurvey extends UnitTestCase { $this->assertNull($res); //var_dump($res); } - + //get the survey public function testGetPeopleWhoFilledSurvey() { $survey_id=1; $all_user_info=false; - $survey_data = survey_manager::get_survey($survey_id); + $survey_data = SurveyManager::get_survey($survey_id); $result = $this->smanager->get_people_who_filled_survey($survey_id,false); $this->assertTrue(is_array($result)); //var_dump($result); @@ -263,9 +263,9 @@ class TestSurvey extends UnitTestCase { $this->assertNull($res); //var_dump($res); } - + //move the survey - + public function testMoveSurveyQuestion() { $direction='moveup'; $survey_question_id=1; @@ -276,23 +276,23 @@ class TestSurvey extends UnitTestCase { } //epmty the survey - + public function testEmpty_survey() { $survey_id=null; $res = $this->smanager->empty_survey($survey_id); $this->assertTrue($res); //var_dump($res); } - + //functions delete - + public function testHandleAction() { $form_content = array(''); $res = $this->squestion->handle_action($form_content); $this->assertTrue(is_array($res)); //var_dump($res); } - + public function testDeleteAllSurveyQuestions() { $survey_id=1; $shared=false; @@ -310,7 +310,7 @@ class TestSurvey extends UnitTestCase { //var_dump($result); //var_dump($res); } - + public function testDeleteSharedSurveyQuestion() { $survey_id=1; $question_id=01; @@ -318,7 +318,7 @@ class TestSurvey extends UnitTestCase { $this->assertTrue(is_null($res)); //var_dump($res); } - + public function testDeleteSurvey() { $survey_id=1; $shared=false; @@ -327,7 +327,7 @@ class TestSurvey extends UnitTestCase { $this->assertTrue($res); //var_dump($res); } - + public function testDeleteAllSurveyQuestionsOptions() { $survey_id=1; $shared=false; @@ -344,7 +344,7 @@ class TestSurvey extends UnitTestCase { if(is_bool($result)) $this->assertTrue(is_bool($result)); $this->assertTrue($result === true || $result===false); - $this->assertTrue($result); + $this->assertTrue($result); //var_dump($result); } @@ -356,9 +356,9 @@ class TestSurvey extends UnitTestCase { $this->assertTrue($res === true || $res === false); //var_dump($res); } - + //Contest the answer - + public function testUpdateSurveyAnswered() { global $user; $survey_code = 'Survey1'; @@ -373,10 +373,10 @@ class TestSurvey extends UnitTestCase { * This functon only is added to the end of the test and the end of the files in the all test. */ /* public function testDeleteCourse() { - global $cidReq; - $resu = CourseManager::delete_course($cidReq); + global $cidReq; + $resu = CourseManager::delete_course($cidReq); }*/ - + } ?> From 2ce3a2367e74e6d58365f44193ed67e710b45e42 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 16:58:39 +0200 Subject: [PATCH 095/159] Update queries using iid. --- main/inc/lib/agenda.lib.php | 22 ++++--- main/inc/lib/groupmanager.lib.php | 57 ++++++------------- main/inc/lib/notebook.lib.php | 11 +++- main/wiki/wiki.inc.php | 31 ++++++++-- .../Entity/CCalendarEventRepeat.php | 1 - .../CourseBundle/Entity/CSurveyInvitation.php | 1 - src/Chamilo/CourseBundle/Entity/CWikiConf.php | 1 - 7 files changed, 67 insertions(+), 57 deletions(-) diff --git a/main/inc/lib/agenda.lib.php b/main/inc/lib/agenda.lib.php index f8f48cf065..e23c626e1a 100644 --- a/main/inc/lib/agenda.lib.php +++ b/main/inc/lib/agenda.lib.php @@ -181,6 +181,9 @@ class Agenda $id = Database::insert($this->tbl_course_agenda, $attributes); if ($id) { + $sql = "UPDATE ".$this->tbl_course_agenda." SET id = $id WHERE iid = $id"; + Database::query($sql); + $groupId = api_get_group_id(); if (!empty($usersToSend)) { @@ -2066,13 +2069,18 @@ class Agenda "VALUES ($course_id, '".$file_name."', '".$comment."', '".$new_file_name."' , '".$eventId."', '".$size."' )"; Database::query($sql); $id = Database::insert_id(); - api_item_property_update( - $courseInfo, - 'calendar_event_attachment', - $id, - 'AgendaAttachmentAdded', - api_get_user_id() - ); + if ($id) { + $sql = "UPDATE $agenda_table_attachment SET id = $id WHERE iid = $id"; + Database::query($sql); + + api_item_property_update( + $courseInfo, + 'calendar_event_attachment', + $id, + 'AgendaAttachmentAdded', + api_get_user_id() + ); + } } } } diff --git a/main/inc/lib/groupmanager.lib.php b/main/inc/lib/groupmanager.lib.php index e4b991525b..fb719f0e2b 100755 --- a/main/inc/lib/groupmanager.lib.php +++ b/main/inc/lib/groupmanager.lib.php @@ -196,6 +196,9 @@ class GroupManager $lastId = Database::insert_id(); if ($lastId) { + $sql = "UPDATE $table_group SET id = $lastId WHERE iid = $lastId"; + Database::query($sql); + $desired_dir_name= '/'.replace_dangerous_char($name,'strict').'_groupdocs'; $my_path = api_get_path(SYS_COURSE_PATH) . $currentCourseRepository . '/document'; @@ -314,41 +317,6 @@ class GroupManager } } - /** - * Create groups from all virtual courses in the given course. - * @deprecated - */ - public static function create_groups_from_virtual_courses() - { - self :: delete_category(self::VIRTUAL_COURSE_CATEGORY); - $id = self :: create_category(get_lang('GroupsFromVirtualCourses'), '', self::TOOL_NOT_AVAILABLE, self::TOOL_NOT_AVAILABLE, 0, 0, 1, 1); - $table_group_cat = Database :: get_course_table(TABLE_GROUP_CATEGORY); - $course_id = api_get_course_int_id(); - - $sql = "UPDATE ".$table_group_cat." SET id=".self::VIRTUAL_COURSE_CATEGORY." WHERE c_id = $course_id AND id=$id"; - Database::query($sql); - $course = api_get_course_info(); - $course['code'] = $course['sysCode']; - $course['title'] = $course['name']; - $virtual_courses = CourseManager :: get_virtual_courses_linked_to_real_course($course['sysCode']); - $group_courses = $virtual_courses; - $group_courses[] = $course; - $ids = array (); - foreach ($group_courses as $index => $group_course) { - $users = CourseManager :: get_user_list_from_course_code($group_course['code']); - $members = array (); - foreach ($users as $index => $user) { - if ($user['status'] == 5 && $user['tutor_id'] == 0) { - $members[] = $user['user_id']; - } - } - $id = self :: create_group($group_course['code'], self::VIRTUAL_COURSE_CATEGORY, 0, count($members)); - self :: subscribe_users($members, $id); - $ids[] = $id; - } - return $ids; - } - /** * Create a group for every class subscribed to the current course * @param int $category_id The category in which the groups should be created @@ -446,9 +414,9 @@ class GroupManager $sql = "DELETE FROM ".$forum_table." WHERE c_id = $course_id AND forum_of_group IN ('".implode("' , '", $group_ids)."')"; - Database::query($sql); + $result = Database::query($sql); - return Database::affected_rows(); + return Database::affected_rows($result); } /** @@ -835,12 +803,18 @@ class GroupManager max_student = '".Database::escape_string($maximum_number_of_students)."' "; Database::query($sql); $categoryId = Database::insert_id(); + + // @todo check if this code do something ... virtual course category? if ($categoryId == self::VIRTUAL_COURSE_CATEGORY) { $sql = "UPDATE ".$table_group_category." SET id = ". ($categoryId +1)." WHERE c_id = $course_id AND id = $categoryId"; Database::query($sql); - return $categoryId +1; + $categoryId = $categoryId +1; } + + $sql = "UPDATE $table_group_category SET id = $categoryId WHERE iid = $categoryId"; + Database::query($sql); + return $categoryId; } @@ -1545,11 +1519,12 @@ class GroupManager $group_id = intval($group_id); $sql = "INSERT INTO ".$table_group_user." (c_id, user_id, group_id) VALUES ('$course_id', '".$user_id."', '".$group_id."')"; - $result &= Database::query($sql); + Database::query($sql); } } } - return $result; + + return true; } /** @@ -1572,7 +1547,7 @@ class GroupManager $group_id = intval($group_id); if (self::can_user_subscribe($user_id, $group_id)) { $sql = "INSERT INTO " . $table_group_tutor . " (c_id, user_id, group_id) - VALUES ('$course_id', '" . $user_id . "', '" . $group_id . "')"; + VALUES ('$course_id', '" . $user_id . "', '" . $group_id . "')"; $result &= Database::query($sql); } } diff --git a/main/inc/lib/notebook.lib.php b/main/inc/lib/notebook.lib.php index 6327c6c711..cfa19781c8 100755 --- a/main/inc/lib/notebook.lib.php +++ b/main/inc/lib/notebook.lib.php @@ -71,8 +71,17 @@ class NotebookManager $id = Database::insert_id(); if ($id > 0) { + $sql = "UPDATE $t_notebook SET notebook_id = $id WHERE iid = $id"; + Database::query($sql); + //insert into item_property - api_item_property_update(api_get_course_info(), TOOL_NOTEBOOK, $id, 'NotebookAdded', api_get_user_id()); + api_item_property_update( + api_get_course_info(), + TOOL_NOTEBOOK, + $id, + 'NotebookAdded', + api_get_user_id() + ); } if (!empty($affected_rows)) { diff --git a/main/wiki/wiki.inc.php b/main/wiki/wiki.inc.php index 25c31abcb6..1dd38b0fb4 100755 --- a/main/wiki/wiki.inc.php +++ b/main/wiki/wiki.inc.php @@ -331,6 +331,9 @@ class Wiki $id = Database::insert_id(); if ($id > 0) { + $sql = "UPDATE $tbl_wiki SET id = $insertId WHERE iid = $insertId"; + Database::query($sql); + //insert into item_property api_item_property_update( api_get_course_info(), @@ -343,14 +346,18 @@ class Wiki } if ($_clean['page_id'] == 0) { - $sql='UPDATE '.$tbl_wiki.' SET page_id="'.$id.'" WHERE c_id = '.$course_id.' AND id="'.$id.'"'; + $sql = 'UPDATE '.$tbl_wiki.' SET page_id="'.$id.'" WHERE c_id = '.$course_id.' AND id="'.$id.'"'; Database::query($sql); } //update wiki config if ($values['reflink'] == 'index' && $_clean['version'] == 1 ) { $sql = "INSERT INTO ".$tbl_wiki_conf." (c_id, page_id, task, feedback1, feedback2, feedback3, fprogress1, fprogress2, fprogress3, max_text, max_version, startdate_assig, enddate_assig, delayedsubmit) - VALUES ($course_id, '".$id."','".$_clean['task']."','".$_clean['feedback1']."','".$_clean['feedback2']."','".$_clean['feedback3']."','".$_clean['fprogress1']."','".$_clean['fprogress2']."','".$_clean['fprogress3']."','".$_clean['max_text']."','".$_clean['max_version']."','".$_clean['startdate_assig']."','".$_clean['enddate_assig']."','".$_clean['delayedsubmit']."')"; + VALUES ($course_id, '".$id."','".$_clean['task']."','".$_clean['feedback1']."','".$_clean['feedback2']."','".$_clean['feedback3']."','".$_clean['fprogress1']."','".$_clean['fprogress2']."','".$_clean['fprogress3']."','".$_clean['max_text']."','".$_clean['max_version']."','".$_clean['startdate_assig']."','".$_clean['enddate_assig']."','".$_clean['delayedsubmit']."')"; + Database::query($sql); + + $sql = "UPDATE $tbl_wiki_conf SET page_id = $survey_id WHERE iid = $survey_id"; + Database::query($sql); } else { $sql = 'UPDATE '.$tbl_wiki_conf.' SET task="'.$_clean['task'].'", @@ -368,9 +375,10 @@ class Wiki WHERE page_id = "'.$_clean['page_id'].'" AND c_id = '.$course_id; + Database::query($sql); } - Database::query($sql); + api_item_property_update($_course, 'wiki', $id, 'WikiAdded', api_get_user_id(), $groupId); self::check_emailcue($_clean['reflink'], 'P', $dtime, $_clean['user_id']); $this->setWikiData($id); @@ -419,8 +427,21 @@ class Wiki Database::query($sql); $id = Database::insert_id(); - api_item_property_update($_course, 'wiki', $id, 'WikiAdded', api_get_user_id(), $r_group_id); - self::check_emailcue($r_reflink, 'P', $r_dtime, $r_user_id); + + if ($id) { + $sql = "UPDATE $tbl_wiki SET id = $id WHERE iid = $id"; + Database::query($sql); + + api_item_property_update( + $_course, + 'wiki', + $id, + 'WikiAdded', + api_get_user_id(), + $r_group_id + ); + self::check_emailcue($r_reflink, 'P', $r_dtime, $r_user_id); + } return get_lang('PageRestored'); } diff --git a/src/Chamilo/CourseBundle/Entity/CCalendarEventRepeat.php b/src/Chamilo/CourseBundle/Entity/CCalendarEventRepeat.php index b33b2de238..e4db8d6e35 100644 --- a/src/Chamilo/CourseBundle/Entity/CCalendarEventRepeat.php +++ b/src/Chamilo/CourseBundle/Entity/CCalendarEventRepeat.php @@ -29,7 +29,6 @@ class CCalendarEventRepeat */ private $calId; - /** * @var integer * diff --git a/src/Chamilo/CourseBundle/Entity/CSurveyInvitation.php b/src/Chamilo/CourseBundle/Entity/CSurveyInvitation.php index d456e459c0..2fdedc8b00 100644 --- a/src/Chamilo/CourseBundle/Entity/CSurveyInvitation.php +++ b/src/Chamilo/CourseBundle/Entity/CSurveyInvitation.php @@ -37,7 +37,6 @@ class CSurveyInvitation */ private $surveyInvitationId; - /** * @var string * diff --git a/src/Chamilo/CourseBundle/Entity/CWikiConf.php b/src/Chamilo/CourseBundle/Entity/CWikiConf.php index e8f5833f25..ff87cd9a21 100644 --- a/src/Chamilo/CourseBundle/Entity/CWikiConf.php +++ b/src/Chamilo/CourseBundle/Entity/CWikiConf.php @@ -38,7 +38,6 @@ class CWikiConf private $pageId; - /** * @var string * From 01fd8167208fb0cef616be91dffe1bc57f262db5 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 16:58:52 +0200 Subject: [PATCH 096/159] Remove unused code. --- main/group/group_creation.php | 6 ------ 1 file changed, 6 deletions(-) diff --git a/main/group/group_creation.php b/main/group/group_creation.php index 26ca6d156e..c2e98af60d 100755 --- a/main/group/group_creation.php +++ b/main/group/group_creation.php @@ -50,12 +50,6 @@ if (isset($_POST['action'])) { header('Location: group.php?action=show_msg&msg='.$msg); exit; break; - case 'create_virtual_groups': - $ids = GroupManager::create_groups_from_virtual_courses(); - $msg = urlencode(count($ids).' '.get_lang('GroupsAdded')); - header('Location: group.php?action=show_msg&msg='.$msg); - exit; - break; case 'create_subgroups': GroupManager::create_subgroups($_POST['base_group'], $_POST['number_of_groups']); $msg = urlencode($_POST['number_of_groups'].' '.get_lang('GroupsAdded')); From 7fbf1d995396394138216832b2b44e1cb451b113 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 10 Apr 2015 16:59:14 +0200 Subject: [PATCH 097/159] Rename survey_manager with SurveyManager --- main/inc/ajax/model.ajax.php | 2 +- main/inc/lib/display.lib.php | 2 +- main/inc/lib/myspace.lib.php | 2 +- main/inc/lib/sessionmanager.lib.php | 6 +++--- main/inc/lib/tracking.lib.php | 4 ++-- main/inc/lib/usermanager.lib.php | 2 +- main/mySpace/myStudents.php | 4 ++-- 7 files changed, 11 insertions(+), 11 deletions(-) diff --git a/main/inc/ajax/model.ajax.php b/main/inc/ajax/model.ajax.php index 0184ab0a27..8cbcdb0f79 100755 --- a/main/inc/ajax/model.ajax.php +++ b/main/inc/ajax/model.ajax.php @@ -1033,7 +1033,7 @@ switch ($action) { 'lastname', ); - $questions = survey_manager::get_questions($surveyId, $courseId); + $questions = SurveyManager::get_questions($surveyId, $courseId); foreach ($questions as $question_id => $question) { diff --git a/main/inc/lib/display.lib.php b/main/inc/lib/display.lib.php index 779a5a38e9..97aca7f17a 100755 --- a/main/inc/lib/display.lib.php +++ b/main/inc/lib/display.lib.php @@ -1418,7 +1418,7 @@ class Display } // If it's a survey, make sure the user's invited. Otherwise drop it. if ($item_property['tool'] == TOOL_SURVEY) { - $survey_info = survey_manager::get_survey($item_property['ref'], 0, $course_code); + $survey_info = SurveyManager::get_survey($item_property['ref'], 0, $course_code); if (!empty($survey_info)) { $invited_users = SurveyUtil::get_invited_users( $survey_info['code'], diff --git a/main/inc/lib/myspace.lib.php b/main/inc/lib/myspace.lib.php index c76cd0dfb3..e9848a8f26 100644 --- a/main/inc/lib/myspace.lib.php +++ b/main/inc/lib/myspace.lib.php @@ -788,7 +788,7 @@ class MySpace get_lang('LastName'), ); //add lessons of course - $questions = survey_manager::get_questions($surveyId, $courseId); + $questions = SurveyManager::get_questions($surveyId, $courseId); foreach ($questions as $question) { $columns[] = $question['question']; diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php index 170f5b9686..253984055d 100755 --- a/main/inc/lib/sessionmanager.lib.php +++ b/main/inc/lib/sessionmanager.lib.php @@ -754,7 +754,7 @@ class SessionManager } //Get survey questions - $questions = survey_manager::get_questions($surveyId, $courseId); + $questions = SurveyManager::get_questions($surveyId, $courseId); //Survey is anonymous? $result = Database::query(sprintf("SELECT anonymous FROM $c_survey WHERE survey_id = %d", $surveyId)); @@ -959,11 +959,11 @@ class SessionManager * Surveys */ $survey_user_list = array(); - $survey_list = survey_manager::get_surveys($course['code'], $sessionId); + $survey_list = SurveyManager::get_surveys($course['code'], $sessionId); $surveys_total = count($survey_list); foreach ($survey_list as $survey) { - $user_list = survey_manager::get_people_who_filled_survey( + $user_list = SurveyManager::get_people_who_filled_survey( $survey['survey_id'], false, $course['real_id'] diff --git a/main/inc/lib/tracking.lib.php b/main/inc/lib/tracking.lib.php index cdb85340b6..9209657888 100755 --- a/main/inc/lib/tracking.lib.php +++ b/main/inc/lib/tracking.lib.php @@ -6070,11 +6070,11 @@ class TrackingCourseLog if (empty($session_id)) { $survey_user_list = array(); - $survey_list = survey_manager::get_surveys($course_code, $session_id); + $survey_list = SurveyManager::get_surveys($course_code, $session_id); $total_surveys = count($survey_list); foreach ($survey_list as $survey) { - $user_list = survey_manager::get_people_who_filled_survey( + $user_list = SurveyManager::get_people_who_filled_survey( $survey['survey_id'], false, $course_info['real_id'] diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php index 600d71acff..3746c816eb 100755 --- a/main/inc/lib/usermanager.lib.php +++ b/main/inc/lib/usermanager.lib.php @@ -466,7 +466,7 @@ class UserManager } // Removing survey invitation - survey_manager::delete_all_survey_invitations_by_user($user_id); + SurveyManager::delete_all_survey_invitations_by_user($user_id); // Delete students works $sql = "DELETE FROM $table_work WHERE user_id = $user_id AND c_id <> 0"; diff --git a/main/mySpace/myStudents.php b/main/mySpace/myStudents.php index 105c8b3f16..f9e18880f2 100755 --- a/main/mySpace/myStudents.php +++ b/main/mySpace/myStudents.php @@ -1041,11 +1041,11 @@ if (!empty($student_id)) { //@when using sessions we do not show the survey list if (empty($session_id)) { - $survey_list = survey_manager::get_surveys($course_code, $session_id); + $survey_list = SurveyManager::get_surveys($course_code, $session_id); $survey_data = array(); foreach($survey_list as $survey) { - $user_list = survey_manager::get_people_who_filled_survey($survey['survey_id'], false, $info_course['real_id']); + $user_list = SurveyManager::get_people_who_filled_survey($survey['survey_id'], false, $info_course['real_id']); $survey_done = Display::return_icon("accept_na.png", get_lang('NoAnswer'), array(), ICON_SIZE_SMALL); if (in_array($student_id, $user_list)) { $survey_done = Display::return_icon("accept.png", get_lang('Answered'), array(), ICON_SIZE_SMALL); From de374ceb997863d2c183e3c7734f80eae0cc8459 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 13 Apr 2015 08:43:32 +0200 Subject: [PATCH 098/159] Fix PHP warning. --- main/course_description/course_description_controller.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/main/course_description/course_description_controller.php b/main/course_description/course_description_controller.php index f86dd590bd..8cfe158607 100644 --- a/main/course_description/course_description_controller.php +++ b/main/course_description/course_description_controller.php @@ -45,6 +45,7 @@ class CourseDescriptionController if (!is_array($data['descriptions'])) { $data['descriptions'] = array($data['descriptions']); } + foreach ($data['descriptions'] as $description) { if (strpos($description, 'set_session_id($session_id); $data = array(); $data['id'] = $id; + $affected_rows = null; + $message = array(); if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST") { if (!empty($_POST['title']) && !empty($_POST['contentDescription'])) { $check = Security::check_token(); From 81cfe895733db7affa723edbe5913d3c7eb884b0 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 13 Apr 2015 08:43:50 +0200 Subject: [PATCH 099/159] Fix queries. --- main/inc/lib/api.lib.php | 71 +++++++--- main/inc/lib/course_description.lib.php | 170 +++++++++++++++++------- main/inc/lib/glossary.lib.php | 19 ++- 3 files changed, 187 insertions(+), 73 deletions(-) diff --git a/main/inc/lib/api.lib.php b/main/inc/lib/api.lib.php index 873b979c1c..9a02bb3570 100644 --- a/main/inc/lib/api.lib.php +++ b/main/inc/lib/api.lib.php @@ -3614,8 +3614,8 @@ function api_item_property_update( $to_user_id = intval($to_user_id); $start_visible = Database::escape_string($start_visible); $end_visible = Database::escape_string($end_visible); - $start_visible = ($start_visible == 0) ? '0000-00-00 00:00:00' : $start_visible; - $end_visible = ($end_visible == 0) ? '0000-00-00 00:00:00' : $end_visible; + $start_visible = $start_visible == 0 ? '0000-00-00 00:00:00' : $start_visible; + $end_visible = $end_visible == 0 ? '0000-00-00 00:00:00' : $end_visible; $to_filter = ''; $time = api_get_utc_datetime(); @@ -3696,9 +3696,15 @@ function api_item_property_update( visibility = '$visibility', session_id = '$session_id' $set_type WHERE $filter"; + $result = Database::query($sql); } else { $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, session_id) VALUES ($course_id, '$tool','$item_id','$time', '$user_id', '$time', '$lastedit_type','$user_id', '$to_value', '$visibility', '$start_visible','$end_visible', '$session_id')"; + $result = Database::query($sql); + + $id = Database::insert_id(); + $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = $id WHERE iid = $id"; + Database::query($sql); } } else { $sql = "UPDATE $TABLE_ITEMPROPERTY @@ -3708,6 +3714,7 @@ function api_item_property_update( lastedit_user_id = '$user_id', visibility='$visibility' $set_type WHERE $filter"; + $result = Database::query($sql); } break; case 'visible' : // Change item to visible. @@ -3733,6 +3740,11 @@ function api_item_property_update( } else { $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, session_id) VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')"; + $result = Database::query($sql); + + $id = Database::insert_id(); + $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = $id WHERE iid = $id"; + Database::query($sql); } } else { $sql = "UPDATE $TABLE_ITEMPROPERTY @@ -3742,6 +3754,7 @@ function api_item_property_update( lastedit_user_id='$user_id', visibility='$visibility' $set_type WHERE $filter"; + $result = Database::query($sql); } break; case 'invisible' : // Change item to invisible. @@ -3764,9 +3777,15 @@ function api_item_property_update( visibility = '$visibility', session_id = '$session_id' $set_type WHERE $filter"; + $result = Database::query($sql); } else { $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, session_id) VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')"; + $result = Database::query($sql); + + $id = Database::insert_id(); + $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = $id WHERE iid = $id"; + Database::query($sql); } } else { $sql = "UPDATE $TABLE_ITEMPROPERTY @@ -3776,6 +3795,7 @@ function api_item_property_update( lastedit_user_id = '$user_id', visibility = '$visibility' $set_type WHERE $filter"; + $result = Database::query($sql); } break; default : // The item will be added or updated. @@ -3787,14 +3807,18 @@ function api_item_property_update( lastedit_date = '$time', lastedit_user_id='$user_id' $set_type WHERE $filter"; + $result = Database::query($sql); } - $result = Database::query($sql); + // Insert if no entries are found (can only happen in case of $lastedit_type switch is 'default'). if (Database::affected_rows($result) == 0) { $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool,ref,insert_date,insert_user_id,lastedit_date,lastedit_type, lastedit_user_id, $to_field, visibility, start_visible, end_visible, session_id) VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')"; $res = Database::query($sql); if (!$res) { + $id = Database::insert_id(); + $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = $id WHERE iid = $id"; + Database::query($sql); return false; } } @@ -4632,7 +4656,22 @@ function copy_folder_course_session( session_id = '$session_id'"; Database::query($sql); $document_id = Database::insert_id(); - api_item_property_update($course_info,TOOL_DOCUMENT,$document_id,'FolderCreated',api_get_user_id(),0,0,null,null,$session_id); + + $sql = "UPDATE $tbl_course_description SET id = $document_id WHERE iid = $document_id"; + Database::query($sql); + + api_item_property_update( + $course_info, + TOOL_DOCUMENT, + $document_id, + 'FolderCreated', + api_get_user_id(), + 0, + 0, + null, + null, + $session_id + ); } } @@ -4960,14 +4999,9 @@ function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url if (Database::num_rows($res) > 0) { // We have a setting for access_url 1, but none for the current one, so create one. $row = Database::fetch_array($res); - $insert = "INSERT INTO $t_settings " . - "(variable,subkey," . - "type,category," . - "selected_value,title," . - "comment,scope," . - "subkeytext,access_url)" . - " VALUES " . - "('".$row['variable']."',".(!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL")."," . + $insert = "INSERT INTO $t_settings (variable, subkey, type,category, selected_value, title, comment, scope, subkeytext, access_url) + VALUES + ('".$row['variable']."',".(!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL")."," . "'".$row['type']."','".$row['category']."'," . "'$value','".$row['title']."'," . "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".(!empty($row['scope']) ? "'".$row['scope']."'" : "NULL")."," . @@ -4989,14 +5023,8 @@ function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url if (Database::num_rows($res) > 0) { // We have a setting for access_url 1, but none for the current one, so create one. $row = Database::fetch_array($res); if ($row['access_url_changeable'] == 1) { - $insert = "INSERT INTO $t_settings " . - "(variable,subkey," . - "type,category," . - "selected_value,title," . - "comment,scope," . - "subkeytext,access_url, access_url_changeable)" . - " VALUES " . - "('".$row['variable']."',". + $insert = "INSERT INTO $t_settings (variable,subkey, type,category, selected_value,title, comment,scope, subkeytext,access_url, access_url_changeable) VALUES + ('".$row['variable']."',". (!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL")."," . "'".$row['type']."','".$row['category']."'," . "'$value','".$row['title']."'," . @@ -5048,7 +5076,8 @@ function api_set_settings_category($category, $value = null, $access_url = 1, $f $res = Database::query($sql); return $res !== false; } else { - $sql = "UPDATE $t_s SET selected_value = NULL WHERE category = '$category' AND access_url = $access_url"; + $sql = "UPDATE $t_s SET selected_value = NULL + WHERE category = '$category' AND access_url = $access_url"; if (is_array($fieldtype) && count($fieldtype)>0) { $sql .= " AND ( "; $i = 0; diff --git a/main/inc/lib/course_description.lib.php b/main/inc/lib/course_description.lib.php index 7b77fc5bb5..147e99eff6 100755 --- a/main/inc/lib/course_description.lib.php +++ b/main/inc/lib/course_description.lib.php @@ -31,12 +31,14 @@ class CourseDescription } /** - * Returns an array of objects of type CourseDescription corresponding to a specific course, without session ids (session id = 0) + * Returns an array of objects of type CourseDescription corresponding to + * a specific course, without session ids (session id = 0) * * @param int Course id * @return array Array of CourseDescriptions */ - public static function get_descriptions($course_id) { + public static function get_descriptions($course_id) + { // Get course code $course_info = api_get_course_info_by_id($course_id); if (!empty($course_info)) { @@ -45,7 +47,8 @@ class CourseDescription return array(); } $t_course_desc = Database::get_course_table(TABLE_COURSE_DESCRIPTION); - $sql = "SELECT * FROM $t_course_desc WHERE c_id = $course_id AND session_id = '0';"; + $sql = "SELECT * FROM $t_course_desc + WHERE c_id = $course_id AND session_id = '0'"; $sql_result = Database::query($sql); $results = array(); while($row = Database::fetch_array($sql_result)) { @@ -72,7 +75,9 @@ class CourseDescription $tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION); $condition_session = api_get_session_condition($this->session_id, true, true); $course_id = api_get_course_int_id(); - $sql = "SELECT * FROM $tbl_course_description WHERE c_id = $course_id $condition_session ORDER BY id "; + $sql = "SELECT * FROM $tbl_course_description + WHERE c_id = $course_id $condition_session + ORDER BY id "; $rs = Database::query($sql); $data = array(); while ($description = Database::fetch_array($rs)) { @@ -86,9 +91,11 @@ class CourseDescription /** * Get all data of course description by session id, * first you must set session_id property with the object CourseDescription + * @deprecated * @return array */ - public function get_description_history($description_type) { + public function get_description_history($description_type) + { $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY); $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY); @@ -119,7 +126,8 @@ class CourseDescription * @param int session id (optional) * @return array */ - public function get_data_by_description_type($description_type, $course_code = '', $session_id = null) { + public function get_data_by_description_type($description_type, $course_code = '', $session_id = null) + { $tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION); $course_id = api_get_course_int_id(); @@ -132,7 +140,8 @@ class CourseDescription $course_id = $course_info['real_id']; } $description_type = intval($description_type); - $sql = "SELECT * FROM $tbl_course_description WHERE c_id = $course_id AND description_type='$description_type' $condition_session "; + $sql = "SELECT * FROM $tbl_course_description + WHERE c_id = $course_id AND description_type='$description_type' $condition_session "; $rs = Database::query($sql); $data = array(); if ($description = Database::fetch_array($rs)) { @@ -143,7 +152,14 @@ class CourseDescription return $data; } - public function get_data_by_id($id, $course_code = '', $session_id = null) { + /** + * @param int $id + * @param string $course_code + * @param int $session_id + * @return array + */ + public function get_data_by_id($id, $course_code = '', $session_id = null) + { $tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION); $course_id = api_get_course_int_id(); @@ -156,7 +172,8 @@ class CourseDescription $course_id = $course_info['real_id']; } $id = intval($id); - $sql = "SELECT * FROM $tbl_course_description WHERE c_id = $course_id AND id='$id' $condition_session "; + $sql = "SELECT * FROM $tbl_course_description + WHERE c_id = $course_id AND id='$id' $condition_session "; $rs = Database::query($sql); $data = array(); if ($description = Database::fetch_array($rs)) { @@ -165,19 +182,23 @@ class CourseDescription $data['description_content'] = $description['content']; $data['progress'] = $description['progress']; } + return $data; } /** - * Get maximum description type by session id, first you must set session_id properties with the object CourseDescription + * Get maximum description type by session id, + * first you must set session_id properties with the object CourseDescription * @return int maximum description time adding one */ - public function get_max_description_type() { + public function get_max_description_type() + { $tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION); $course_id = api_get_course_int_id(); - $sql = "SELECT MAX(description_type) as MAX FROM $tbl_course_description WHERE c_id = $course_id AND session_id='".$this->session_id."'"; + $sql = "SELECT MAX(description_type) as MAX FROM $tbl_course_description + WHERE c_id = $course_id AND session_id='".$this->session_id."'"; $rs = Database::query($sql); $max = Database::fetch_array($rs); $description_type = $max['MAX']+1; @@ -189,7 +210,8 @@ class CourseDescription /** * Insert a description to the course_description table, - * first you must set description_type, title, content, progress and session_id properties with the object CourseDescription + * first you must set description_type, title, content, progress and + * session_id properties with the object CourseDescription * @return int affected rows */ public function insert() @@ -211,16 +233,26 @@ class CourseDescription $last_id = Database::insert_id(); $affected_rows = Database::affected_rows($result); if ($last_id > 0) { + $sql = "UPDATE $tbl_course_description SET id = $last_id WHERE iid = $last_id"; + Database::query($sql); + //insert into item_property - api_item_property_update(api_get_course_info(), TOOL_COURSE_DESCRIPTION, $last_id, 'CourseDescriptionAdded', api_get_user_id()); + api_item_property_update( + api_get_course_info(), + TOOL_COURSE_DESCRIPTION, + $last_id, + 'CourseDescriptionAdded', + api_get_user_id() + ); } - return $affected_rows; + return $affected_rows; } /** * Insert a row like history inside track_e_item_property table - * first you must set description_type, title, content, progress and session_id properties with the object CourseDescription + * first you must set description_type, title, content, progress and + * session_id properties with the object CourseDescription * @param int description type * @return int affected rows */ @@ -243,6 +275,10 @@ class CourseDescription session_id = '".intval($this->session_id)."'"; $result = Database::query($sql); $affected_rows = Database::affected_rows($result); + + $sql = "UPDATE $tbl_course_description SET id = $last_id WHERE iid = $last_id"; + Database::query($sql); + return $affected_rows; } @@ -255,25 +291,32 @@ class CourseDescription { $tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION); $sql = "UPDATE $tbl_course_description SET - title = '".Database::escape_string($this->title)."', - content = '".Database::escape_string($this->content)."', - progress = '".$this->progress."' - WHERE id = '".intval($this->id)."' AND - session_id = '".$this->session_id."' AND - c_id = ".api_get_course_int_id()." - "; + title = '".Database::escape_string($this->title)."', + content = '".Database::escape_string($this->content)."', + progress = '".$this->progress."' + WHERE + id = '".intval($this->id)."' AND + session_id = '".$this->session_id."' AND + c_id = ".api_get_course_int_id(); $result = Database::query($sql); $affected_rows = Database::affected_rows($result); if ($this->id > 0) { //insert into item_property - api_item_property_update(api_get_course_info(), TOOL_COURSE_DESCRIPTION, $this->id, 'CourseDescriptionUpdated', api_get_user_id()); + api_item_property_update( + api_get_course_info(), + TOOL_COURSE_DESCRIPTION, + $this->id, + 'CourseDescriptionUpdated', + api_get_user_id() + ); } return $affected_rows; } /** - * Delete a description, first you must set description_type and session_id properties with the object CourseDescription + * Delete a description, first you must set description_type and session_id + * properties with the object CourseDescription * @return int affected rows */ public function delete() @@ -281,13 +324,23 @@ class CourseDescription $tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION); $course_id = api_get_course_int_id(); $sql = "DELETE FROM $tbl_course_description - WHERE c_id = $course_id AND id = '".intval($this->id)."' AND session_id = '".intval($this->session_id)."'"; + WHERE + c_id = $course_id AND + id = '".intval($this->id)."' AND + session_id = '".intval($this->session_id)."'"; $result = Database::query($sql); $affected_rows = Database::affected_rows($result); if ($this->id > 0) { //insert into item_property - api_item_property_update(api_get_course_info(), TOOL_COURSE_DESCRIPTION, $this->id, 'CourseDescriptionDeleted', api_get_user_id()); + api_item_property_update( + api_get_course_info(), + TOOL_COURSE_DESCRIPTION, + $this->id, + 'CourseDescriptionDeleted', + api_get_user_id() + ); } + return $affected_rows; } @@ -301,7 +354,8 @@ class CourseDescription $tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION); $course_id = api_get_course_int_id(); - $sql = "SELECT id FROM $tbl_course_description WHERE c_id = $course_id AND description_type = '".intval($description_type)."'"; + $sql = "SELECT id FROM $tbl_course_description + WHERE c_id = $course_id AND description_type = '".intval($description_type)."'"; $rs = Database::query($sql); $row = Database::fetch_array($rs); $description_id = $row['id']; @@ -315,12 +369,17 @@ class CourseDescription * @param int Description type (optional) * @return string img html */ - public function get_progress_porcent($with_icon = false, $description_type = THEMATIC_ADVANCE) { + public function get_progress_porcent($with_icon = false, $description_type = THEMATIC_ADVANCE) + { $tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION); $session_id = intval($session_id); $course_id = api_get_course_int_id(); - $sql = "SELECT progress FROM $tbl_course_description WHERE c_id = $course_id AND description_type = '".intval($description_type)."' AND session_id = '".intval($this->session_id)."' "; + $sql = "SELECT progress FROM $tbl_course_description + WHERE + c_id = $course_id AND + description_type = '".intval($description_type)."' AND + session_id = '".intval($this->session_id)."' "; $rs = Database::query($sql); $progress = ''; $img = ''; @@ -361,7 +420,8 @@ class CourseDescription * Get description titles editable by default * @return array */ - public function get_default_description_title_editable() { + public function get_default_description_title_editable() + { $default_description_title_editable = array(); $default_description_title_editable[1] = true; $default_description_title_editable[2] = true; @@ -378,7 +438,8 @@ class CourseDescription * Get description icons by default * @return array */ - public function get_default_description_icon() { + public function get_default_description_icon() + { $default_description_icon = array(); $default_description_icon[1]= 'info.png'; $default_description_icon[2]= 'objective.png'; @@ -396,7 +457,8 @@ class CourseDescription * Get questions by default for help * @return array */ - public function get_default_question() { + public function get_default_question() + { $question = array(); $question[1]= get_lang('GeneralDescriptionQuestions'); $question[2]= get_lang('ObjectivesQuestions'); @@ -413,7 +475,8 @@ class CourseDescription * Get informations by default for help * @return array */ - public function get_default_information() { + public function get_default_information() + { $information = array(); $information[1]= get_lang('GeneralDescriptionInformation'); $information[2]= get_lang('ObjectivesInformation'); @@ -430,7 +493,8 @@ class CourseDescription * Set description id * @return void */ - public function set_id($id) { + public function set_id($id) + { $this->id = $id; } @@ -439,7 +503,8 @@ class CourseDescription * @param int Course ID * @return void */ - public function set_course_id($id) { + public function set_course_id($id) + { $this->course_id = intval($id); } @@ -447,7 +512,8 @@ class CourseDescription * Set description title * @return void */ - public function set_title($title) { + public function set_title($title) + { $this->title = $title; } @@ -455,7 +521,8 @@ class CourseDescription * Set description content * @return void */ - public function set_content($content) { + public function set_content($content) + { $this->content = $content; } @@ -463,7 +530,8 @@ class CourseDescription * Set description session id * @return void */ - public function set_session_id($session_id) { + public function set_session_id($session_id) + { $this->session_id = $session_id; } @@ -471,7 +539,8 @@ class CourseDescription * Set description type * @return void */ - public function set_description_type($description_type) { + public function set_description_type($description_type) + { $this->description_type = $description_type; } @@ -479,7 +548,8 @@ class CourseDescription * Set progress of a description * @return void */ - public function set_progress($progress) { + public function set_progress($progress) + { $this->progress = $progress; } @@ -487,7 +557,8 @@ class CourseDescription * get description id * @return int */ - public function get_id() { + public function get_id() + { return $this->id; } @@ -495,7 +566,8 @@ class CourseDescription * get description title * @return string */ - public function get_title() { + public function get_title() + { return $this->title; } @@ -503,7 +575,8 @@ class CourseDescription * get description content * @return string */ - public function get_content() { + public function get_content() + { return $this->content; } @@ -511,7 +584,8 @@ class CourseDescription * get session id * @return int */ - public function get_session_id() { + public function get_session_id() + { return $this->session_id; } @@ -519,7 +593,8 @@ class CourseDescription * get description type * @return int */ - public function get_description_type() { + public function get_description_type() + { return $this->description_type; } @@ -527,7 +602,8 @@ class CourseDescription * get progress of a description * @return int */ - public function get_progress() { + public function get_progress() + { return $this->progress; } } diff --git a/main/inc/lib/glossary.lib.php b/main/inc/lib/glossary.lib.php index 03416ecb65..8b8cbb7d41 100755 --- a/main/inc/lib/glossary.lib.php +++ b/main/inc/lib/glossary.lib.php @@ -126,12 +126,21 @@ class GlossaryManager } $id = Database::insert_id(); + if ($id) { + + $sql = "UPDATE $t_glossary SET glossary_id = $id WHERE iid = $id"; + Database::query($sql); + + //insert into item_property + api_item_property_update( + api_get_course_info(), + TOOL_GLOSSARY, + $id, + 'GlossaryAdded', + api_get_user_id() + ); + } - $sql = "UPDATE $t_glossary SET glossary_id = $id WHERE iid = $id"; - Database::query($sql); - - //insert into item_property - api_item_property_update(api_get_course_info(), TOOL_GLOSSARY, $id, 'GlossaryAdded', api_get_user_id()); $_SESSION['max_glossary_display'] = GlossaryManager::get_max_glossary_item(); // display the feedback message if ($message) { From 839c6b50fb42536f1291ccfdb8d6e523737a1361 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 13 Apr 2015 09:50:05 +0200 Subject: [PATCH 100/159] Fix search UI see #7539 --- main/css/base.css | 48 +++++++++++++++++++++++++++ main/inc/ajax/online.ajax.php | 8 ++++- main/inc/lib/social.lib.php | 28 ++++++++-------- main/social/search.php | 42 +++++++++++------------ main/template/default/social/home.tpl | 5 +-- whoisonline.php | 34 +++++++++---------- whoisonlinesession.php | 7 ++-- 7 files changed, 111 insertions(+), 61 deletions(-) diff --git a/main/css/base.css b/main/css/base.css index 41496e9e09..c1643b0b75 100755 --- a/main/css/base.css +++ b/main/css/base.css @@ -5768,3 +5768,51 @@ ul.holder li.bit-box{ display: block; } } + + +.src-image { + display: none; +} + +.card { + overflow: hidden; + position: relative; + border: 1px solid #CCC; + border-radius: 8px; + text-align: center; + padding: 0; + /* background-color: #284c79; */ + color: rgb(136, 172, 217); + margin-bottom: 20px; +} + +.card .header-bg { + /* This stretches the canvas across the entire hero unit */ + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 70px; + border-bottom: 1px #FFF solid; + /* This positions the canvas under the text */ + z-index: 1; +} + +.card .avatar { + position: relative; + margin-top: 15px; + z-index: 100; +} + +.card .content { + margin-bottom: 15px; +} + +.card .avatar img { + width: 100px; + height: 100px; + -webkit-border-radius: 50%; + -moz-border-radius: 50%; + border-radius: 50%; + border: 5px solid rgba(0,0,30,0.8); +} diff --git a/main/inc/ajax/online.ajax.php b/main/inc/ajax/online.ajax.php index 9c110bf1c9..4f0cd0a4cf 100755 --- a/main/inc/ajax/online.ajax.php +++ b/main/inc/ajax/online.ajax.php @@ -19,7 +19,13 @@ switch($action) { if (!empty($max_page) && $page <= $max_page) { if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) { - $user_list = who_is_online_in_this_course($page_rows, $images_to_show, api_get_user_id(), api_get_setting('time_limit_whosonline'), $_GET['cidReq']); + $user_list = who_is_online_in_this_course( + $page_rows, + $images_to_show, + api_get_user_id(), + api_get_setting('time_limit_whosonline'), + $_GET['cidReq'] + ); } else { $user_list = who_is_online($page_rows, $images_to_show); } diff --git a/main/inc/lib/social.lib.php b/main/inc/lib/social.lib.php index f9b0b8460f..5334d2e27d 100755 --- a/main/inc/lib/social.lib.php +++ b/main/inc/lib/social.lib.php @@ -928,15 +928,7 @@ class SocialManager extends UserManager $course_url = '&cidReq='.Security::remove_XSS($_GET['cidReq']); } - if ($wrap) { - if ($add_row) { - $html .='
      '; - } - - $html .= '
      '; - - $html .= '
        '; - } + $html .= '
        '; foreach ($user_list as $uid) { $user_info = api_get_user_info($uid); @@ -965,16 +957,26 @@ class SocialManager extends UserManager } $img = ''.$name.''; - $name = ''.$status_icon.$user_status.$name.'
        '; - $html .= '
      • '.$img.'
        '.$name.'
      • '; + $name = ''.$status_icon.$user_status.$name.''; + + $html .= '
        +
        +
        '.$img.'
        +
        + '.$name.' +
        +
        +
        '; + } $counter = $_SESSION['who_is_online_counter']; if ($wrap) { - $html .= '
      '; + $html .= '
      '; } if (count($user_list) >= 9) { - $html .= ''; + $html .= ''; } if ($wrap && $add_row) { $html .= '
      '; diff --git a/main/social/search.php b/main/social/search.php index d9b510bd4d..42331d58f1 100755 --- a/main/social/search.php +++ b/main/social/search.php @@ -68,24 +68,25 @@ if ($query != '' || ($query_vars['search_type']=='1' && count($query_vars)>2) ) $social_right_content .= get_lang('SorryNoResults'); } - $results = '
      '; + $results = '
      '; if (is_array($users) && count($users) > 0) { $results .= Display::page_subheader(get_lang('Users')); - $results .= '
        '; + $results .= '
        '; + $buttonClass = 'btn btn-default btn-sm'; foreach ($users as $user) { - $send_inv = '

        '; + $send_inv = ''; $relation_type = intval(SocialManager::get_relation_between_contacts(api_get_user_id(), $user['user_id'])); $user_info = api_get_user_info($user['user_id'], true); - $url = api_get_path(WEB_PATH).'main/social/profile.php?u='.$user['user_id']; + $url = api_get_path(WEB_PATH).'main/social/profile.php?u='.$user['user_id']; // Show send invitation icon if they are not friends yet if ($relation_type != 3 && $relation_type != 4 && $user['user_id'] != api_get_user_id()) { - $send_inv = ' -

        '; + $send_inv = ' + '.get_lang('SendInvitation').''; } - $send_msg = ' - '; + $send_msg = ' + '.get_lang('SendMessage').''; if (empty($user['picture_uri'])) { $picture['file'] = api_get_path(WEB_CODE_PATH).'img/unknown.jpg'; $img = ''; @@ -109,25 +110,24 @@ if ($query != '' || ($query_vars['search_type']=='1' && count($query_vars)>2) ) $user_info['complete_name'] = Display::url($status_icon.$user_info['complete_name'], $url); $invitations = $user['tag'].$send_inv.$send_msg; - $results .= '
      • -
        -
        - '.$user_info['complete_name'].' -
        -
        -
        - '.$img.' -
        + $results .= '
        +
        + +
        + '.$img.'
        -
        -
        +
        + '.$user_info['complete_name'].' +
        '.$invitations.'
        -
      • '; +
        '; + + } - $results .= '
      '; + $results .= '
      '; $social_right_content .= $results; } diff --git a/main/template/default/social/home.tpl b/main/template/default/social/home.tpl index ac881c5398..d330fe6e96 100644 --- a/main/template/default/social/home.tpl +++ b/main/template/default/social/home.tpl @@ -9,7 +9,7 @@ {{ social_menu_block }} -
      +
      {{ social_search_block }} {{ social_skill_block }} {{ social_group_block }} @@ -17,8 +17,5 @@
      {{ social_auto_extend_link }}
      -
      - -
      {% endblock %} diff --git a/whoisonline.php b/whoisonline.php index a6cffb3fbe..5f62f43de0 100755 --- a/whoisonline.php +++ b/whoisonline.php @@ -66,23 +66,23 @@ $(document).ready(function() { $("#link_load_more_items").click(function() { page = $("#link_load_more_items").attr("data_link"); $.ajax({ - beforeSend: function(objeto) { - $("#display_response_id").html("'.addslashes(get_lang('Loading')).'"); - }, - type: "GET", - url: "main/inc/ajax/online.ajax.php?a=load_online_user", - data: "online_page_nr="+page, - success: function(data) { - $("#display_response_id").html(""); - if (data != "end") { - $("#link_load_more_items").remove(); - var last = $("#online_grid_container li:last"); - last.after(data); - } else { - $("#link_load_more_items").remove(); - } + beforeSend: function(objeto) { + $("#display_response_id").html("'.addslashes(get_lang('Loading')).'"); + }, + type: "GET", + url: "main/inc/ajax/online.ajax.php?a=load_online_user", + data: "online_page_nr="+page, + success: function(data) { + $("#display_response_id").html(""); + if (data != "end") { + $("#link_load_more_items").remove(); + var last = $("#online_grid_container li:last"); + last.after(data); + } else { + $("#link_load_more_items").remove(); } - }); + } + }); }); }); '; @@ -127,7 +127,7 @@ if ((api_get_setting('showonline', 'world') == 'true' && !$_user['user_id']) || if (api_get_setting('allow_social_tool') == 'true') { if (!api_is_anonymous()) { $query = isset($_GET['q']) ? $_GET['q']: null; - $social_right_content .= '
      '.UserManager::get_search_form($query).'
      '; + $social_right_content .= UserManager::get_search_form($query); } } $social_right_content .= SocialManager::display_user_list($user_list); diff --git a/whoisonlinesession.php b/whoisonlinesession.php index 9d361a6c8e..2b80a5debc 100755 --- a/whoisonlinesession.php +++ b/whoisonlinesession.php @@ -4,9 +4,6 @@ * Shows who is online in a specific session * @package chamilo.main */ -/** - * Initialization - */ include_once './main/inc/global.inc.php'; api_block_anonymous_users(); @@ -47,7 +44,7 @@ Display::display_header(get_lang('UserOnlineListSession')); $session_is_coach = array(); if (isset($_user['user_id']) && $_user['user_id'] != '') { $_user['user_id'] = intval($_user['user_id']); - $sql = "SELECT DISTINCT id, + $sql = "SELECT DISTINCT session.id, name, date_start, date_end @@ -62,7 +59,7 @@ Display::display_header(get_lang('UserOnlineListSession')); $session_is_coach[$session['id']] = $session; } - $sql = "SELECT DISTINCT id, + $sql = "SELECT DISTINCT session.id, name, date_start, date_end From 73b52dbc4b999e0826c48e69e1a2a9ec019d16d8 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 13 Apr 2015 11:52:27 +0200 Subject: [PATCH 101/159] Fix queries update id based in iid. --- main/exercice/answer.class.php | 78 ++++--- main/exercice/exercice.php | 19 +- main/exercice/exercise.class.php | 141 +++++++----- main/exercice/exercise_admin.php | 4 +- main/exercice/question.class.php | 281 +++++++++++++++++------- main/exercice/testcategory.class.php | 59 +++-- main/exercice/tests_category.php | 4 +- main/forum/forumfunction.inc.php | 4 +- main/inc/lib/AnnouncementManager.php | 6 +- main/inc/lib/agenda.lib.php | 4 +- main/inc/lib/api.lib.php | 10 +- main/inc/lib/attendance.lib.php | 12 +- main/inc/lib/course_description.lib.php | 4 +- main/inc/lib/database.constants.inc.php | 16 +- main/inc/lib/fileUpload.lib.php | 2 +- main/inc/lib/groupmanager.lib.php | 4 +- main/inc/lib/link.lib.php | 4 +- main/inc/lib/thematic.lib.php | 10 +- main/newscorm/learnpath.class.php | 14 +- main/newscorm/learnpathItem.class.php | 8 +- main/survey/survey.lib.php | 4 +- main/wiki/wiki.inc.php | 4 +- main/work/work.lib.php | 4 +- 23 files changed, 436 insertions(+), 260 deletions(-) diff --git a/main/exercice/answer.class.php b/main/exercice/answer.class.php index 01ce374d98..49b27d9641 100755 --- a/main/exercice/answer.class.php +++ b/main/exercice/answer.class.php @@ -512,21 +512,21 @@ class Answer $c_id = $this->course['real_id']; // inserts new answers into data base $flag = 0; - $sql = "INSERT INTO $TBL_REPONSES (c_id, id, question_id, answer, correct, comment, ponderation, position, hotspot_coordinates, hotspot_type, destination) VALUES "; + $sql = "INSERT INTO $TBL_REPONSES (c_id, question_id, answer, correct, comment, ponderation, position, hotspot_coordinates, hotspot_type, destination) VALUES "; for ($i=1;$i <= $this->new_nbrAnswers; $i++) { - $answer = Database::escape_string($this->new_answer[$i]); - $correct = Database::escape_string($this->new_correct[$i]); - $comment = Database::escape_string($this->new_comment[$i]); - $weighting = Database::escape_string($this->new_weighting[$i]); - $position = Database::escape_string($this->new_position[$i]); - $hotspot_coordinates = Database::escape_string($this->new_hotspot_coordinates[$i]); - $hotspot_type = Database::escape_string($this->new_hotspot_type[$i]); - $destination = Database::escape_string($this->new_destination[$i]); + $answer = Database::escape_string($this->new_answer[$i]); + $correct = Database::escape_string($this->new_correct[$i]); + $comment = Database::escape_string($this->new_comment[$i]); + $weighting = Database::escape_string($this->new_weighting[$i]); + $position = Database::escape_string($this->new_position[$i]); + $hotspot_coordinates = Database::escape_string($this->new_hotspot_coordinates[$i]); + $hotspot_type = Database::escape_string($this->new_hotspot_type[$i]); + $destination = Database::escape_string($this->new_destination[$i]); if (!(isset($this->position[$i]))) { $flag = 1; - $sql.="($c_id, '$i','$questionId','$answer','$correct','$comment','$weighting','$position','$hotspot_coordinates','$hotspot_type','$destination'),"; + $sql .= "($c_id, '$questionId','$answer','$correct','$comment','$weighting','$position','$hotspot_coordinates','$hotspot_type','$destination'),"; } else { // https://support.chamilo.org/issues/6558 // function updateAnswers already escape_string, error if we do it twice. @@ -545,31 +545,39 @@ class Answer } if ($flag == 1) { - $sql = api_substr($sql,0,-1); + $sql = api_substr($sql, 0, -1); Database::query($sql); + $id = Database::insert_id(); + + $sql = "UPDATE $TBL_REPONSES SET id = id_auto WHERE id_auto = $id"; + Database::query($sql); } + if (count($this->position) > $this->new_nbrAnswers) { $i = $this->new_nbrAnswers+1; while ($this->position[$i]) { $position = $this->position[$i]; - $sql = "DELETE FROM $TBL_REPONSES WHERE c_id = {$this->course_id} AND question_id = '".($questionId)."' AND position ='$position'"; + $sql = "DELETE FROM $TBL_REPONSES + WHERE + c_id = {$this->course_id} AND + question_id = '".($questionId)."' AND + position ='$position'"; Database::query($sql); $i++; } - } // moves $new_* arrays - $this->answer=$this->new_answer; - $this->correct=$this->new_correct; - $this->comment=$this->new_comment; - $this->weighting=$this->new_weighting; - $this->position=$this->new_position; - $this->hotspot_coordinates=$this->new_hotspot_coordinates; - $this->hotspot_type=$this->new_hotspot_type; - - $this->nbrAnswers=$this->new_nbrAnswers; - $this->destination=$this->new_destination; + $this->answer = $this->new_answer; + $this->correct = $this->new_correct; + $this->comment = $this->new_comment; + $this->weighting = $this->new_weighting; + $this->position = $this->new_position; + $this->hotspot_coordinates = $this->new_hotspot_coordinates; + $this->hotspot_type = $this->new_hotspot_type; + + $this->nbrAnswers = $this->new_nbrAnswers; + $this->destination = $this->new_destination; // clears $new_* arrays $this->cancel(); @@ -617,7 +625,7 @@ class Answer // if at least one answer if ($this->nbrAnswers) { // inserts new answers into data base - $sql = "INSERT INTO $TBL_REPONSES (c_id, id,question_id,answer,correct,comment, ponderation,position,hotspot_coordinates,hotspot_type,destination) VALUES"; + $sql = "INSERT INTO $TBL_REPONSES (c_id, question_id,answer,correct,comment, ponderation,position,hotspot_coordinates,hotspot_type,destination) VALUES"; $c_id = $course_info['real_id']; for ($i=1;$i <= $this->nbrAnswers;$i++) { @@ -626,24 +634,28 @@ class Answer $this->comment[$i] = DocumentManager::replace_urls_inside_content_html_from_copy_course($this->comment[$i],$this->course['id'], $course_info['id']) ; } - $answer = Database::escape_string($this->answer[$i]); - $correct = Database::escape_string($this->correct[$i]); + $answer = Database::escape_string($this->answer[$i]); + $correct = Database::escape_string($this->correct[$i]); if (self::getQuestionType() == MULTIPLE_ANSWER_TRUE_FALSE || self::getQuestionType() == MULTIPLE_ANSWER_TRUE_FALSE ) { $correct = $fixed_list[intval($correct)]; } - $comment = Database::escape_string($this->comment[$i]); - $weighting = Database::escape_string($this->weighting[$i]); - $position = Database::escape_string($this->position[$i]); - $hotspot_coordinates = Database::escape_string($this->hotspot_coordinates[$i]); - $hotspot_type = Database::escape_string($this->hotspot_type[$i]); - $destination = Database::escape_string($this->destination[$i]); + $comment = Database::escape_string($this->comment[$i]); + $weighting = Database::escape_string($this->weighting[$i]); + $position = Database::escape_string($this->position[$i]); + $hotspot_coordinates = Database::escape_string($this->hotspot_coordinates[$i]); + $hotspot_type = Database::escape_string($this->hotspot_type[$i]); + $destination = Database::escape_string($this->destination[$i]); $sql.="($c_id, '$i','$newQuestionId','$answer','$correct','$comment'," . "'$weighting','$position','$hotspot_coordinates','$hotspot_type','$destination'),"; } $sql = api_substr($sql,0,-1); + Database::query($sql); - } + $id = Database::insert_id(); + $sql = "UPDATE $TBL_REPONSES SET id = id_auto WHERE id_auto = $id"; + Database::query($sql); + } } } diff --git a/main/exercice/exercice.php b/main/exercice/exercice.php index 9d704e96dc..74d249552c 100755 --- a/main/exercice/exercice.php +++ b/main/exercice/exercice.php @@ -364,25 +364,24 @@ $condition_session = api_get_session_condition($session_id, true, true); // Only for administrators if ($is_allowedToEdit) { - $total_sql = "SELECT count(id) as count FROM $TBL_EXERCICES + $total_sql = "SELECT count(iid) as count FROM $TBL_EXERCICES WHERE c_id = $courseId AND active<>'-1' $condition_session "; $sql = "SELECT * FROM $TBL_EXERCICES WHERE c_id = $courseId AND active<>'-1' $condition_session - ORDER BY title LIMIT ".$from.",".$limit; + ORDER BY title + LIMIT ".$from.",".$limit; } else { // Only for students - $total_sql = "SELECT count(id) as count FROM $TBL_EXERCICES + $total_sql = "SELECT count(iid) as count FROM $TBL_EXERCICES WHERE c_id = $courseId AND active = '1' $condition_session "; $sql = "SELECT * FROM $TBL_EXERCICES WHERE c_id = $courseId AND active='1' $condition_session ORDER BY title LIMIT ".$from.",".$limit; } - $result = Database::query($sql); -$exercises_count = Database :: num_rows($result); - $result_total = Database::query($total_sql); + $total_exercises = 0; if (Database :: num_rows($result_total)) { @@ -410,6 +409,7 @@ if ($is_allowedToEdit) { $res = Database::query($sql); $hp_count = Database :: num_rows($res); } + $total = $total_exercises + $hp_count; $token = Security::get_token(); @@ -477,7 +477,7 @@ $exercise_obj = new Exercise(); $list_ordered = null; while ($row = Database :: fetch_array($result, 'ASSOC')) { - $exercise_list[$row['id']] = $row; + $exercise_list[$row['iid']] = $row; } if (isset($list_ordered) && !empty($list_ordered)) { @@ -489,6 +489,7 @@ if (isset($list_ordered) && !empty($list_ordered)) { } $exercise_list = $new_question_list; } + echo '
      '; echo ''; @@ -644,10 +645,10 @@ if (!empty($exercise_list)) { $item = Display::tag('td', $url.' '.$session_img.$lp_blocked); // Count number exercise - teacher - $sql = "SELECT count(*) FROM $TBL_EXERCICE_QUESTION + $sql = "SELECT count(*) count FROM $TBL_EXERCICE_QUESTION WHERE c_id = $courseId AND exercice_id = $my_exercise_id"; $sqlresult = Database::query($sql); - $rowi = Database :: result($sqlresult, 0); + $rowi = Database :: result($sqlresult, 0, 0); if ($session_id == $row['session_id']) { // Settings diff --git a/main/exercice/exercise.class.php b/main/exercice/exercise.class.php index eb7ef5896d..7c80d092ce 100755 --- a/main/exercice/exercise.class.php +++ b/main/exercice/exercise.class.php @@ -752,26 +752,26 @@ class Exercise */ public function save($type_e = '') { - global $_course; - $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST); - - $id = $this->id; - $exercise = $this->exercise; - $description = $this->description; - $sound = $this->sound; - $type = $this->type; - $attempts = $this->attempts; - $feedback_type = $this->feedback_type; - $random = $this->random; - $random_answers = $this->random_answers; - $active = $this->active; - $propagate_neg = $this->propagate_neg; - $review_answers = (isset($this->review_answers) && $this->review_answers) ? 1 : 0; - $randomByCat = $this->randomByCat; - $text_when_finished = $this->text_when_finished; - $display_category_name = intval($this->display_category_name); - $pass_percentage = intval($this->pass_percentage); - $session_id = api_get_session_id(); + $_course = api_get_course_info(); + $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST); + + $id = $this->id; + $exercise = $this->exercise; + $description = $this->description; + $sound = $this->sound; + $type = $this->type; + $attempts = $this->attempts; + $feedback_type = $this->feedback_type; + $random = $this->random; + $random_answers = $this->random_answers; + $active = $this->active; + $propagate_neg = $this->propagate_neg; + $review_answers = isset($this->review_answers) && $this->review_answers ? 1 : 0; + $randomByCat = $this->randomByCat; + $text_when_finished = $this->text_when_finished; + $display_category_name = intval($this->display_category_name); + $pass_percentage = intval($this->pass_percentage); + $session_id = api_get_session_id(); //If direct we do not show results if ($feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) { @@ -847,42 +847,55 @@ class Exercise $end_time = '0000-00-00 00:00:00'; } - $sql = "INSERT INTO $TBL_EXERCICES ( - c_id, start_time, end_time, title, description, sound, type, random, random_answers, active, - results_disabled, max_attempt, feedback_type, expired_time, session_id, review_answers, random_by_category, - text_when_finished, display_category_name, pass_percentage - ) - VALUES( - ".$this->course_id.", - '$start_time','$end_time', - '".Database::escape_string($exercise)."', - '".Database::escape_string($description)."', - '".Database::escape_string($sound)."', - ".intval($type).", - ".intval($random).", - ".intval($random_answers).", - ".intval($active).", - ".intval($results_disabled).", - ".intval($attempts).", - ".intval($feedback_type).", - ".intval($expired_time).", - ".intval($session_id).", - ".intval($review_answers).", - ".intval($randomByCat).", - '".Database::escape_string($text_when_finished)."', - ".intval($display_category_name).", - ".intval($pass_percentage)." - )"; - Database::query($sql); - $this->id = Database::insert_id(); + $params = [ + 'c_id' => $this->course_id, + 'start_time' => $start_time, + 'end_time' => $end_time, + 'title' => $exercise, + 'description' => $description, + 'sound' => $sound, + 'type' => $type, + 'random' => $random, + 'random_answers' => $random_answers, + 'active' => $active, + 'results_disabled' => $results_disabled, + 'max_attempt' => $attempts, + 'feedback_type' => $feedback_type, + 'expired_time' => $expired_time, + 'session_id' => $session_id, + 'review_answers' => $review_answers, + 'random_by_category' => $randomByCat, + 'text_when_finished' => $text_when_finished, + 'display_category_name' => $display_category_name, + 'pass_percentage' => $pass_percentage + ]; + + $this->id = Database::insert($TBL_EXERCICES, $params); + + if ($this->id) { + + $sql = "UPDATE $TBL_EXERCICES SET id = iid WHERE iid = {$this->id} "; + Database::query($sql); - // insert into the item_property table - api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizAdded', api_get_user_id()); - // This function save the quiz again, carefull about start_time and end_time if you remove this line (see above) - api_set_default_visibility($this->id, TOOL_QUIZ, null, true); + // insert into the item_property table + api_item_property_update( + $this->course, + TOOL_QUIZ, + $this->id, + 'QuizAdded', + api_get_user_id() + ); - if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) { - $this->search_engine_save(); + // This function save the quiz again, carefull about start_time + // and end_time if you remove this line (see above) + api_set_default_visibility($this->id, TOOL_QUIZ, null, true); + + if (api_get_setting( + 'search_enabled' + ) == 'true' && extension_loaded('xapian') + ) { + $this->search_engine_save(); + } } } @@ -893,16 +906,16 @@ class Exercise /** * Updates question position */ - function update_question_positions() + public function update_question_positions() { $quiz_question_table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION); //Fixes #3483 when updating order $question_list = $this->selectQuestionList(true); if (!empty($question_list)) { foreach ($question_list as $position => $questionId) { - $sql="UPDATE $quiz_question_table SET - question_order ='".intval($position)."'". - "WHERE c_id = ".$this->course_id." AND question_id = ".intval($questionId)." AND exercice_id=".intval($this->id); + $sql = "UPDATE $quiz_question_table SET + question_order ='".intval($position)."' + WHERE c_id = ".$this->course_id." AND question_id = ".intval($questionId)." AND exercice_id=".intval($this->id); Database::query($sql); } } @@ -928,8 +941,10 @@ class Exercise } } $this->questionList[$pos] = $questionId; + return true; } + return false; } @@ -3951,11 +3966,17 @@ class Exercise $sessionId = api_get_session_id(); $course_id = api_get_course_int_id(); // Save a new quiz - $sql = "INSERT INTO $tbl_quiz (c_id, title, type, random, active, results_disabled, max_attempt, start_time,end_time,feedback_type,expired_time, session_id, propagate_neg) ". - " VALUES('$course_id', '".$title."', $type, $random, $active, $results_disabled, $max_attempt,'','', $feedback, $expired_time, $sessionId, $propagateNegative)"; + $sql = "INSERT INTO $tbl_quiz (c_id, title, type, random, active, results_disabled, max_attempt, start_time,end_time,feedback_type,expired_time, session_id, propagate_neg) + VALUES('$course_id', '".$title."', $type, $random, $active, $results_disabled, $max_attempt,'','', $feedback, $expired_time, $sessionId, $propagateNegative)"; Database::query($sql); $quiz_id = Database::insert_id(); + if ($quiz_id) { + + $sql = "UPDATE $tbl_quiz SET id = iid WHERE iid = {$quiz_id} "; + Database::query($sql); + } + return $quiz_id; } diff --git a/main/exercice/exercise_admin.php b/main/exercice/exercise_admin.php index fdfdd13ff6..be32d59425 100755 --- a/main/exercice/exercise_admin.php +++ b/main/exercice/exercise_admin.php @@ -124,7 +124,7 @@ if ($form->validate()) { } else { // DISPLAY FORM if (isset($_SESSION['gradebook'])) { - $gradebook= $_SESSION['gradebook']; + $gradebook = $_SESSION['gradebook']; } if (!empty($gradebook) && $gradebook=='view') { @@ -134,7 +134,7 @@ if ($form->validate()) { $interbreadcrumb[] = array("url"=>'exercice.php', 'name'=> get_lang('Exercices')); $interbreadcrumb[] = array("url"=>"admin.php?exerciseId=".$objExercise->id, "name" => $objExercise->name); - Display::display_header($nameTools,get_lang('Exercise')); + Display::display_header($nameTools, get_lang('Exercise')); echo '
      '; diff --git a/main/exercice/question.class.php b/main/exercice/question.class.php index 8e2fb4eda3..7026703ea4 100755 --- a/main/exercice/question.class.php +++ b/main/exercice/question.class.php @@ -368,7 +368,8 @@ abstract class Question //$sql = "UPDATE $TBL_QUESTION_REL_CATEGORY SET category_id = $category_id WHERE question_id=$question_id AND c_id=".api_get_course_int_id(); //$res = Database::query($sql); } else { - $sql = "INSERT INTO $TBL_QUESTION_REL_CATEGORY (c_id, question_id, category_id) VALUES (".api_get_course_int_id().", $question_id, $category_id)"; + $sql = "INSERT INTO $TBL_QUESTION_REL_CATEGORY (c_id, question_id, category_id) + VALUES (".api_get_course_int_id().", $question_id, $category_id)"; Database::query($sql); } } @@ -757,11 +758,14 @@ abstract class Question } } else { // creates a new question - $sql = "SELECT max(position) FROM $TBL_QUESTIONS as question, $TBL_EXERCICE_QUESTION as test_question - WHERE question.id = test_question.question_id AND - test_question.exercice_id = ".intval($exerciseId)." AND - question.c_id = $c_id AND - test_question.c_id = $c_id "; + $sql = "SELECT max(position) + FROM $TBL_QUESTIONS as question, + $TBL_EXERCICE_QUESTION as test_question + WHERE + question.id = test_question.question_id AND + test_question.exercice_id = ".intval($exerciseId)." AND + question.c_id = $c_id AND + test_question.c_id = $c_id "; $result = Database::query($sql); $current_position = Database::result($result,0,0); $this->updatePosition($current_position+1); @@ -780,32 +784,56 @@ abstract class Question Database::query($sql); $this->id = Database::insert_id(); + if ($this->id) { - api_item_property_update($this->course, TOOL_QUIZ, $this->id,'QuizQuestionAdded',api_get_user_id()); - - // If hotspot, create first answer - if ($type == HOT_SPOT || $type == HOT_SPOT_ORDER) { - $TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER); - $sql = "INSERT INTO $TBL_ANSWERS (c_id, id, question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type ) - VALUES (".$c_id.", '1', ".intval($this->id).", '', NULL , '', '10' , '1', '0;0|0|0', 'square')"; + $sql = "UPDATE $TBL_QUESTIONS SET id = iid WHERE iid = {$this->id}"; Database::query($sql); - } - if ($type == HOT_SPOT_DELINEATION ) { - $TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER); - $sql="INSERT INTO $TBL_ANSWERS (c_id, id, question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type ) - VALUES (".$c_id.", '1', ".intval($this->id).", '', NULL , '', '10' , '1', '0;0|0|0', 'delineation')"; - Database::query($sql); - } + api_item_property_update( + $this->course, + TOOL_QUIZ, + $this->id, + 'QuizQuestionAdded', + api_get_user_id() + ); - if (api_get_setting('search_enabled')=='true') { - if ($exerciseId != 0) { - $this -> search_engine_edit($exerciseId, TRUE); - } else { - /** - * actually there is *not* an user interface for - * creating questions without a relation with an exercise - */ + // If hotspot, create first answer + if ($type == HOT_SPOT || $type == HOT_SPOT_ORDER) { + $TBL_ANSWERS = Database::get_course_table( + TABLE_QUIZ_ANSWER + ); + $sql = "INSERT INTO $TBL_ANSWERS (c_id, question_id , answer, correct, comment, ponderation, position, hotspot_coordinates, hotspot_type) + VALUES (".$c_id.", ".intval($this->id).", '', NULL , '', '10' , '1', '0;0|0|0', 'square')"; + Database::query($sql); + $id = Database::insert_id(); + + $sql = "UPDATE $TBL_ANSWERS SET id = id_auto WHERE iid = $id"; + Database::query($sql); + } + + if ($type == HOT_SPOT_DELINEATION) { + $TBL_ANSWERS = Database::get_course_table( + TABLE_QUIZ_ANSWER + ); + $sql = "INSERT INTO $TBL_ANSWERS (c_id, question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type ) + VALUES (".$c_id.", ".intval($this->id).", '', NULL , '', '10' , '1', '0;0|0|0', 'delineation')"; + Database::query($sql); + + $id = Database::insert_id(); + + $sql = "UPDATE $TBL_ANSWERS SET id = id_auto WHERE id_auto = $id"; + Database::query($sql); + } + + if (api_get_setting('search_enabled') == 'true') { + if ($exerciseId != 0) { + $this->search_engine_edit($exerciseId, true); + } else { + /** + * actually there is *not* an user interface for + * creating questions without a relation with an exercise + */ + } } } } @@ -1085,22 +1113,30 @@ abstract class Question } else { $course_info = $course_info; } - $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION); + $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION); $TBL_QUESTION_OPTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION); - $question = $this->question; - $description = $this->description; - $weighting = $this->weighting; - $position = $this->position; - $type = $this->type; - $level = intval($this->level); - $extra = $this->extra; + $question = $this->question; + $description = $this->description; + $weighting = $this->weighting; + $position = $this->position; + $type = $this->type; + $level = intval($this->level); + $extra = $this->extra; //Using the same method used in the course copy to transform URLs if ($this->course['id'] != $course_info['id']) { - $description = DocumentManager::replace_urls_inside_content_html_from_copy_course($description, $this->course['id'], $course_info['id']); - $question = DocumentManager::replace_urls_inside_content_html_from_copy_course($question, $this->course['id'], $course_info['id']); + $description = DocumentManager::replace_urls_inside_content_html_from_copy_course( + $description, + $this->course['id'], + $course_info['id'] + ); + $question = DocumentManager::replace_urls_inside_content_html_from_copy_course( + $question, + $this->course['id'], + $course_info['id'] + ); } $course_id = $course_info['real_id']; @@ -1114,28 +1150,44 @@ abstract class Question Database::query($sql); $new_question_id = Database::insert_id(); + if ($new_question_id) { + + $sql = "UPDATE $TBL_QUESTIONS SET id = iid WHERE iid = $new_question_id"; + Database::query($sql); - if (!empty($options)) { - //Saving the quiz_options - foreach ($options as $item) { - $item['question_id'] = $new_question_id; - $item['c_id'] = $course_id; - unset($item['id']); - Database::insert($TBL_QUESTION_OPTIONS, $item); + if (!empty($options)) { + //Saving the quiz_options + foreach ($options as $item) { + $item['question_id'] = $new_question_id; + $item['c_id'] = $course_id; + unset($item['id']); + $id = Database::insert($TBL_QUESTION_OPTIONS, $item); + + $sql = "UPDATE $TBL_QUESTION_OPTIONS SET id = iid WHERE iid = $id"; + Database::query($sql); + } } + + // Duplicates the picture of the hotspot + $this->exportPicture($new_question_id, $course_info); } - // Duplicates the picture of the hotspot - $this->exportPicture($new_question_id, $course_info); return $new_question_id; } + /** + * @return string + */ public function get_question_type_name() { $key = self::$questionTypes[$this->type]; return get_lang($key[1]); } + /** + * @param string $type + * @return null + */ public static function get_question_type($type) { if ($type == ORAL_EXPRESSION && api_get_setting('enable_nanogong') != 'true') { @@ -1144,6 +1196,9 @@ abstract class Question return self::$questionTypes[$type]; } + /** + * @return array + */ public static function get_question_type_list() { if (api_get_setting('enable_nanogong') != 'true') { @@ -1171,6 +1226,7 @@ abstract class Question } } } + return null; } @@ -1426,31 +1482,91 @@ abstract class Question echo '
      '; } - static function saveQuestionOption($question_id, $name, $course_id, $position = 0) { - $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION); - $params['question_id'] = intval($question_id); - $params['name'] = $name; - $params['position'] = $position; - $params['c_id'] = $course_id; + /** + * @param int $question_id + * @param string $name + * @param int $course_id + * @param int $position + * @return bool|int + */ + static function saveQuestionOption($question_id, $name, $course_id, $position = 0) + { + $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION); + $params['question_id'] = intval($question_id); + $params['name'] = $name; + $params['position'] = $position; + $params['c_id'] = $course_id; $result = self::readQuestionOption($question_id, $course_id); $last_id = Database::insert($TBL_EXERCICE_QUESTION_OPTION, $params); + if ($last_id) { + $sql = "UPDATE $TBL_EXERCICE_QUESTION_OPTION SET id = iid WHERE iid = $last_id"; + Database::query($sql); + } + return $last_id; } - static function deleteAllQuestionOptions($question_id, $course_id) { - $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION); - Database::delete($TBL_EXERCICE_QUESTION_OPTION, array('c_id = ? AND question_id = ?'=> array($course_id, $question_id))); + /** + * @param int $question_id + * @param int $course_id + */ + static function deleteAllQuestionOptions($question_id, $course_id) + { + $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION); + Database::delete( + $TBL_EXERCICE_QUESTION_OPTION, + array( + 'c_id = ? AND question_id = ?' => array( + $course_id, + $question_id + ) + ) + ); } - static function updateQuestionOption($id, $params, $course_id) { - $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION); - $result = Database::update($TBL_EXERCICE_QUESTION_OPTION, $params, array('c_id = ? AND id = ?'=>array($course_id, $id))); + /** + * @param int $id + * @param array $params + * @param int $course_id + * @return bool|int + */ + static function updateQuestionOption($id, $params, $course_id) + { + $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table( + TABLE_QUIZ_QUESTION_OPTION + ); + $result = Database::update( + $TBL_EXERCICE_QUESTION_OPTION, + $params, + array('c_id = ? AND id = ?' => array($course_id, $id)) + ); return $result; } - static function readQuestionOption($question_id, $course_id) { - $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION); - $result = Database::select('*', $TBL_EXERCICE_QUESTION_OPTION, array('where'=>array('c_id = ? AND question_id = ?' =>array($course_id, $question_id)), 'order'=>'id ASC')); + /** + * @param int $question_id + * @param int $course_id + * @return array + */ + static function readQuestionOption($question_id, $course_id) + { + $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table( + TABLE_QUIZ_QUESTION_OPTION + ); + $result = Database::select( + '*', + $TBL_EXERCICE_QUESTION_OPTION, + array( + 'where' => array( + 'c_id = ? AND question_id = ?' => array( + $course_id, + $question_id + ) + ), + 'order' => 'id ASC' + ) + ); + return $result; } @@ -1526,10 +1642,13 @@ abstract class Question $level = intval($level); // Get the max position - $sql = "SELECT max(position) as max_position" - ." FROM $tbl_quiz_question q INNER JOIN $tbl_quiz_rel_question r" - ." ON q.id = r.question_id" - ." AND exercice_id = $quiz_id AND q.c_id = $course_id AND r.c_id = $course_id"; + $sql = "SELECT max(position) as max_position + FROM $tbl_quiz_question q INNER JOIN $tbl_quiz_rel_question r + ON + q.id = r.question_id AND + exercice_id = $quiz_id AND + q.c_id = $course_id AND + r.c_id = $course_id"; $rs_max = Database::query($sql); $row_max = Database::fetch_object($rs_max); $max_position = $row_max->max_position +1; @@ -1537,22 +1656,28 @@ abstract class Question // Insert the new question $sql = "INSERT INTO $tbl_quiz_question (c_id, question, description, ponderation, position, type, level) VALUES ($course_id, '".Database::escape_string($question_name)."', '".Database::escape_string($question_description)."', '$max_score', $max_position, $type, $level)"; - Database::query($sql); + // Get the question ID $question_id = Database::insert_id(); + if ($question_id) { + + $sql = "UPDATE $tbl_quiz_question SET id = iid WHERE iid = $id"; + Database::query($sql); + + // Get the max question_order + $sql = "SELECT max(question_order) as max_order + FROM $tbl_quiz_rel_question + WHERE c_id = $course_id AND exercice_id = $quiz_id "; + $rs_max_order = Database::query($sql); + $row_max_order = Database::fetch_object($rs_max_order); + $max_order = $row_max_order->max_order + 1; + // Attach questions to quiz + $sql = "INSERT INTO $tbl_quiz_rel_question (c_id, question_id,exercice_id,question_order) + VALUES($course_id, $question_id, $quiz_id, $max_order)"; + Database::query($sql); + } - // Get the max question_order - $sql = "SELECT max(question_order) as max_order " - ."FROM $tbl_quiz_rel_question WHERE c_id = $course_id AND exercice_id = $quiz_id "; - $rs_max_order = Database::query($sql); - $row_max_order = Database::fetch_object($rs_max_order); - $max_order = $row_max_order->max_order + 1; - // Attach questions to quiz - $sql = "INSERT INTO $tbl_quiz_rel_question " - ."(c_id, question_id,exercice_id,question_order)" - ." VALUES($course_id, $question_id, $quiz_id, $max_order)"; - Database::query($sql); return $question_id; } diff --git a/main/exercice/testcategory.class.php b/main/exercice/testcategory.class.php index e0e2f09181..9264b0a4bf 100755 --- a/main/exercice/testcategory.class.php +++ b/main/exercice/testcategory.class.php @@ -75,19 +75,26 @@ class Testcategory // lets add in BDD if not the same name if ($data_verif['nb'] <= 0) { $c_id = api_get_course_int_id(); - $sql = "INSERT INTO $t_cattable VALUES ('$c_id', '', '$v_name', '$v_description')"; + $sql = "INSERT INTO $t_cattable (c_id, title, description) VALUES ('$c_id','$v_name', '$v_description')"; Database::query($sql); $new_id = Database::insert_id(); - // add test_category in item_property table - $course_code = api_get_course_id(); - $course_info = api_get_course_info($course_code); - api_item_property_update( - $course_info, - TOOL_TEST_CATEGORY, - $new_id, - 'TestCategoryAdded', - api_get_user_id() - ); + + if ($new_id) { + + $sql = "UPDATE $t_cattable SET id = iid WHERE iid = $new_id"; + Database::query($sql); + + // add test_category in item_property table + $course_code = api_get_course_id(); + $course_info = api_get_course_info($course_code); + api_item_property_update( + $course_info, + TOOL_TEST_CATEGORY, + $new_id, + 'TestCategoryAdded', + api_get_user_id() + ); + } return $new_id; } else { @@ -117,7 +124,13 @@ class Testcategory // item_property update $course_code = api_get_course_id(); $course_info = api_get_course_info($course_code); - api_item_property_update($course_info, TOOL_TEST_CATEGORY, $this->id, 'TestCategoryDeleted', api_get_user_id()); + api_item_property_update( + $course_info, + TOOL_TEST_CATEGORY, + $this->id, + 'TestCategoryDeleted', + api_get_user_id() + ); return true; } } @@ -162,6 +175,7 @@ class Testcategory WHERE category_id=$in_id AND c_id=".api_get_course_int_id(); $res = Database::query($sql); $row = Database::fetch_array($res); + return $row['nb']; } @@ -175,11 +189,11 @@ class Testcategory echo ""; } - /** * Return an array of all Category objects in the database - If in_field=="" Return an array of all category objects in the database - Otherwise, return an array of all in_field value in the database (in_field = id or name or description) + * If in_field=="" Return an array of all category objects in the database + * Otherwise, return an array of all in_field value + * in the database (in_field = id or name or description) */ public static function getCategoryListInfo($in_field="", $in_courseid="") { @@ -230,6 +244,7 @@ class Testcategory $data = Database::fetch_array($res); $result = $data['category_id']; } + return $result; } @@ -264,6 +279,7 @@ class Testcategory if (Database::num_rows($res) > 0) { $result = $data['title']; } + return $result; } @@ -276,17 +292,18 @@ class Testcategory public static function getListOfCategoriesIDForTest($in_testid) { // parcourir les questions d'un test, recup les categories uniques dans un tableau - $tabcat = array(); + $result = array(); $quiz = new Exercise(); $quiz->read($in_testid); $tabQuestionList = $quiz->selectQuestionList(); // the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ??? for ($i=1; $i <= count($tabQuestionList); $i++) { - if (!in_array(Testcategory::getCategoryForQuestion($tabQuestionList[$i]), $tabcat)) { - $tabcat[] = Testcategory::getCategoryForQuestion($tabQuestionList[$i]); + if (!in_array(Testcategory::getCategoryForQuestion($tabQuestionList[$i]), $result)) { + $result[] = Testcategory::getCategoryForQuestion($tabQuestionList[$i]); } } - return $tabcat; + + return $result; } /** @@ -666,9 +683,9 @@ class Testcategory $courseId = intval($courseId); if (empty($sessionId)) { - $sessionCondition = api_get_session_condition($sessionId, true, false, 'i.id_session'); + $sessionCondition = api_get_session_condition($sessionId, true, false, 'i.session_id'); } else { - $sessionCondition = api_get_session_condition($sessionId, true, true, 'i.id_session'); + $sessionCondition = api_get_session_condition($sessionId, true, true, 'i.session_id'); } if (empty($courseId)) { diff --git a/main/exercice/tests_category.php b/main/exercice/tests_category.php index 943fda4c0f..247d638a37 100755 --- a/main/exercice/tests_category.php +++ b/main/exercice/tests_category.php @@ -71,7 +71,7 @@ function edit_category_form($in_action) { $form->addElement('header', get_lang('EditCategory')); $form->addElement('hidden', 'category_id'); $form->addElement('text', 'category_name', get_lang('CategoryName'), array('size' => '95')); - $form->addHtmlEditor('category_description', get_lang('CategoryDescription'), false, false, array('ToolbarSet' => 'test_category', 'Width' => '90%', 'Height' => '200')); + $form->addHtmlEditor('category_description', get_lang('CategoryDescription'), false, false, array('ToolbarSet' => 'test_category', 'Height' => '200')); $form->addButtonSave(get_lang('ModifyCategory'), 'SubmitNote'); // setting the defaults @@ -139,7 +139,7 @@ function add_category_form($in_action) { // Setting the form elements $form->addElement('header', get_lang('AddACategory')); $form->addElement('text', 'category_name', get_lang('CategoryName'), array('size' => '95')); - $form->addHtmlEditor('category_description', get_lang('CategoryDescription'), false, false, array('ToolbarSet' => 'test_category', 'Width' => '90%', 'Height' => '200')); + $form->addHtmlEditor('category_description', get_lang('CategoryDescription'), false, false, array('ToolbarSet' => 'test_category', 'Height' => '200')); $form->addButtonCreate(get_lang('AddTestCategory'), 'SubmitNote'); // setting the rules $form->addRule('category_name', get_lang('ThisFieldIsRequired'), 'required'); diff --git a/main/forum/forumfunction.inc.php b/main/forum/forumfunction.inc.php index a91379e602..1f2ce8b1e1 100755 --- a/main/forum/forumfunction.inc.php +++ b/main/forum/forumfunction.inc.php @@ -2572,7 +2572,7 @@ function store_theme_qualify($user_id, $thread_id, $thread_qualify = 0, $qualify $res = Database::query($sql); $insertId = Database::insert_id(); - $sql = "UPDATE $table_threads_qualify SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $table_threads_qualify SET id = iid WHERE iid = $insertId"; Database::query($sql); return $res; @@ -2707,7 +2707,7 @@ function store_qualify_historical( Database::query($sql1); $insertId = Database::insert_id(); - $sql = "UPDATE $table_threads_qualify_log SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $table_threads_qualify_log SET id = iid WHERE iid = $insertId"; Database::query($sql); // Update diff --git a/main/inc/lib/AnnouncementManager.php b/main/inc/lib/AnnouncementManager.php index f25ae521f7..5b5a39626a 100755 --- a/main/inc/lib/AnnouncementManager.php +++ b/main/inc/lib/AnnouncementManager.php @@ -348,7 +348,7 @@ class AnnouncementManager $last_id = Database::insert($tbl_announcement, $params); - $sql = "UPDATE $tbl_announcement SET id = $last_id WHERE iid = $last_id"; + $sql = "UPDATE $tbl_announcement SET id = iid WHERE iid = $last_id"; Database::query($sql); if (empty($last_id)) { @@ -464,7 +464,7 @@ class AnnouncementManager //store the attach file $last_id = Database::insert_id(); if ($last_id) { - $sql = "UPDATE $lp_item_view_table SET id = $last_id WHERE iid = $last_id"; + $sql = "UPDATE $lp_item_view_table SET id = iid WHERE iid = $last_id"; Database::query($sql); if (!empty($file)) { @@ -1206,7 +1206,7 @@ class AnnouncementManager $result = Database::query($sql); $insertId = Database::insert_id(); - $sql = "UPDATE $tbl_announcement_attachment SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $tbl_announcement_attachment SET id = iid WHERE iid = $insertId"; Database::query($sql); $return = 1; diff --git a/main/inc/lib/agenda.lib.php b/main/inc/lib/agenda.lib.php index e23c626e1a..8230fd0e8c 100644 --- a/main/inc/lib/agenda.lib.php +++ b/main/inc/lib/agenda.lib.php @@ -181,7 +181,7 @@ class Agenda $id = Database::insert($this->tbl_course_agenda, $attributes); if ($id) { - $sql = "UPDATE ".$this->tbl_course_agenda." SET id = $id WHERE iid = $id"; + $sql = "UPDATE ".$this->tbl_course_agenda." SET id = iid WHERE iid = $id"; Database::query($sql); $groupId = api_get_group_id(); @@ -2070,7 +2070,7 @@ class Agenda Database::query($sql); $id = Database::insert_id(); if ($id) { - $sql = "UPDATE $agenda_table_attachment SET id = $id WHERE iid = $id"; + $sql = "UPDATE $agenda_table_attachment SET id = iid WHERE iid = $id"; Database::query($sql); api_item_property_update( diff --git a/main/inc/lib/api.lib.php b/main/inc/lib/api.lib.php index 9a02bb3570..6952def4de 100644 --- a/main/inc/lib/api.lib.php +++ b/main/inc/lib/api.lib.php @@ -3703,7 +3703,7 @@ function api_item_property_update( $result = Database::query($sql); $id = Database::insert_id(); - $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = $id WHERE iid = $id"; + $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = iid WHERE iid = $id"; Database::query($sql); } } else { @@ -3743,7 +3743,7 @@ function api_item_property_update( $result = Database::query($sql); $id = Database::insert_id(); - $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = $id WHERE iid = $id"; + $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = iid WHERE iid = $id"; Database::query($sql); } } else { @@ -3784,7 +3784,7 @@ function api_item_property_update( $result = Database::query($sql); $id = Database::insert_id(); - $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = $id WHERE iid = $id"; + $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = iid WHERE iid = $id"; Database::query($sql); } } else { @@ -3817,7 +3817,7 @@ function api_item_property_update( $res = Database::query($sql); if (!$res) { $id = Database::insert_id(); - $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = $id WHERE iid = $id"; + $sql = "UPDATE $TABLE_ITEMPROPERTY SET id = iid WHERE iid = $id"; Database::query($sql); return false; } @@ -4657,7 +4657,7 @@ function copy_folder_course_session( Database::query($sql); $document_id = Database::insert_id(); - $sql = "UPDATE $tbl_course_description SET id = $document_id WHERE iid = $document_id"; + $sql = "UPDATE $tbl_course_description SET id = iid WHERE iid = $document_id"; Database::query($sql); api_item_property_update( diff --git a/main/inc/lib/attendance.lib.php b/main/inc/lib/attendance.lib.php index f619673e29..9c2449f217 100755 --- a/main/inc/lib/attendance.lib.php +++ b/main/inc/lib/attendance.lib.php @@ -716,7 +716,7 @@ class Attendance $result = Database::query($sql); $insertId = Database::insert_id(); - $sql = "UPDATE $tbl_attendance_sheet SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $tbl_attendance_sheet SET id = iid WHERE iid = $insertId"; Database::query($sql); $affected_rows += Database::affected_rows($result); @@ -748,7 +748,7 @@ class Attendance $result = Database::query($sql); $insertId = Database::insert_id(); - $sql = "UPDATE $tbl_attendance_sheet SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $tbl_attendance_sheet SET id = iid WHERE iid = $insertId"; Database::query($sql); $affected_rows += Database::affected_rows($result); @@ -856,7 +856,7 @@ class Attendance Database::query($sql); $insertId = Database::insert_id(); - $sql = "UPDATE $tbl_attendance_result SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $tbl_attendance_result SET id = iid WHERE iid = $insertId"; Database::query($sql); } } @@ -907,7 +907,7 @@ class Attendance $insertId = Database::insert_id(); - $sql = "UPDATE $tbl_attendance_sheet_log SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $tbl_attendance_sheet_log SET id = iid WHERE iid = $insertId"; Database::query($sql); return Database::affected_rows($result); @@ -1420,7 +1420,7 @@ class Attendance $id = Database::insert($tbl_attendance_calendar, $params); if ($id) { - $sql = "UPDATE $tbl_attendance_calendar SET id = $id WHERE iid = $id"; + $sql = "UPDATE $tbl_attendance_calendar SET id = iid WHERE iid = $id"; Database::query($sql); $affected_rows++; } @@ -1465,7 +1465,7 @@ class Attendance ); $insertId = Database::insert($table, $params); - $sql = "UPDATE $table SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $table SET id = iid WHERE iid = $insertId"; Database::query($sql); } } diff --git a/main/inc/lib/course_description.lib.php b/main/inc/lib/course_description.lib.php index 147e99eff6..95c6178b66 100755 --- a/main/inc/lib/course_description.lib.php +++ b/main/inc/lib/course_description.lib.php @@ -233,7 +233,7 @@ class CourseDescription $last_id = Database::insert_id(); $affected_rows = Database::affected_rows($result); if ($last_id > 0) { - $sql = "UPDATE $tbl_course_description SET id = $last_id WHERE iid = $last_id"; + $sql = "UPDATE $tbl_course_description SET id = iid WHERE iid = $last_id"; Database::query($sql); //insert into item_property @@ -276,7 +276,7 @@ class CourseDescription $result = Database::query($sql); $affected_rows = Database::affected_rows($result); - $sql = "UPDATE $tbl_course_description SET id = $last_id WHERE iid = $last_id"; + $sql = "UPDATE $tbl_course_description SET id = iid WHERE iid = $last_id"; Database::query($sql); return $affected_rows; diff --git a/main/inc/lib/database.constants.inc.php b/main/inc/lib/database.constants.inc.php index de52f4ee48..e29c46d429 100755 --- a/main/inc/lib/database.constants.inc.php +++ b/main/inc/lib/database.constants.inc.php @@ -196,14 +196,14 @@ define('TABLE_DROPBOX_FILE', 'dropbox_file'); define('TABLE_DROPBOX_PERSON', 'dropbox_person'); // Course quiz (or test, or exercice) tables -define('TABLE_QUIZ_QUESTION', 'quiz_question'); -define('TABLE_QUIZ_TEST', 'quiz'); -define('TABLE_QUIZ_ORDER', 'quiz_order'); -define('TABLE_QUIZ_ANSWER', 'quiz_answer'); -define('TABLE_QUIZ_TEST_QUESTION', 'quiz_rel_question'); -define('TABLE_QUIZ_QUESTION_OPTION', 'quiz_question_option'); -define('TABLE_QUIZ_QUESTION_CATEGORY', 'quiz_question_category'); -define('TABLE_QUIZ_QUESTION_REL_CATEGORY', 'quiz_question_rel_category'); +define('TABLE_QUIZ_QUESTION', 'quiz_question'); +define('TABLE_QUIZ_TEST', 'quiz'); +define('TABLE_QUIZ_ORDER', 'quiz_order'); +define('TABLE_QUIZ_ANSWER', 'quiz_answer'); +define('TABLE_QUIZ_TEST_QUESTION', 'quiz_rel_question'); +define('TABLE_QUIZ_QUESTION_OPTION', 'quiz_question_option'); +define('TABLE_QUIZ_QUESTION_CATEGORY', 'quiz_question_category'); +define('TABLE_QUIZ_QUESTION_REL_CATEGORY', 'quiz_question_rel_category'); // Linked resource table //@todo table exists? diff --git a/main/inc/lib/fileUpload.lib.php b/main/inc/lib/fileUpload.lib.php index 7fd68e4202..d6dcfad61d 100755 --- a/main/inc/lib/fileUpload.lib.php +++ b/main/inc/lib/fileUpload.lib.php @@ -1228,7 +1228,7 @@ function add_document( if (Database::query($sql)) { $documentId = Database::insert_id(); - $sql = "UPDATE $table_document SET id = $documentId WHERE iid = $documentId"; + $sql = "UPDATE $table_document SET id = iid WHERE iid = $documentId"; Database::query($sql); if ($documentId) { diff --git a/main/inc/lib/groupmanager.lib.php b/main/inc/lib/groupmanager.lib.php index fb719f0e2b..60c19cc9e3 100755 --- a/main/inc/lib/groupmanager.lib.php +++ b/main/inc/lib/groupmanager.lib.php @@ -196,7 +196,7 @@ class GroupManager $lastId = Database::insert_id(); if ($lastId) { - $sql = "UPDATE $table_group SET id = $lastId WHERE iid = $lastId"; + $sql = "UPDATE $table_group SET id = iid WHERE iid = $lastId"; Database::query($sql); $desired_dir_name= '/'.replace_dangerous_char($name,'strict').'_groupdocs'; @@ -812,7 +812,7 @@ class GroupManager $categoryId = $categoryId +1; } - $sql = "UPDATE $table_group_category SET id = $categoryId WHERE iid = $categoryId"; + $sql = "UPDATE $table_group_category SET id = iid WHERE iid = $categoryId"; Database::query($sql); return $categoryId; diff --git a/main/inc/lib/link.lib.php b/main/inc/lib/link.lib.php index d857756204..234be58af0 100755 --- a/main/inc/lib/link.lib.php +++ b/main/inc/lib/link.lib.php @@ -193,7 +193,7 @@ class Link extends Model Database:: query($sql); $link_id = Database:: insert_id(); // iid - $sql = "UPDATE $tbl_link SET id = $link_id WHERE iid = $link_id"; + $sql = "UPDATE $tbl_link SET id = iid WHERE iid = $link_id"; Database:: query($sql); if ($link_id) { @@ -350,7 +350,7 @@ class Link extends Model Database:: query($sql); $linkId = Database:: insert_id(); // iid - $sql = "UPDATE $tbl_categories SET id = $linkId WHERE iid = $linkId"; + $sql = "UPDATE $tbl_categories SET id = iid WHERE iid = $linkId"; Database:: query($sql); if ($linkId) { diff --git a/main/inc/lib/thematic.lib.php b/main/inc/lib/thematic.lib.php index 66b29b03b2..0dee5d71ef 100755 --- a/main/inc/lib/thematic.lib.php +++ b/main/inc/lib/thematic.lib.php @@ -297,7 +297,7 @@ class Thematic $result = Database::query($sql); $last_id = Database::insert_id(); if ($last_id) { - $sql = "UPDATE $tbl_thematic SET id = $last_id WHERE iid = $last_id"; + $sql = "UPDATE $tbl_thematic SET id = iid WHERE iid = $last_id"; Database::query($sql); api_item_property_update($_course, 'thematic', $last_id,"ThematicAdded", $user_id); } @@ -644,7 +644,7 @@ class Thematic } } } - + return $data; } @@ -678,7 +678,7 @@ class Thematic $last_id = Database::insert_id(); if ($last_id) { - $sql = "UPDATE $tbl_thematic_advance SET id = $last_id WHERE iid = $last_id"; + $sql = "UPDATE $tbl_thematic_advance SET id = iid WHERE iid = $last_id"; Database::query($sql); api_item_property_update($_course, 'thematic_advance', $last_id,"ThematicAdvanceAdded", $user_id); @@ -873,7 +873,7 @@ class Thematic $result = Database::query($ins); $last_id = Database::insert_id(); if ($last_id) { - $sql = "UPDATE $tbl_thematic_plan SET id = $last_id WHERE iid = $last_id"; + $sql = "UPDATE $tbl_thematic_plan SET id = iid WHERE iid = $last_id"; Database::query($sql); api_item_property_update($_course, 'thematic_plan', $last_id,"ThematicPlanAdded", $user_id); } @@ -885,7 +885,7 @@ class Thematic $result = Database::query($ins); $last_id = Database::insert_id(); if ($last_id) { - $sql = "UPDATE $tbl_thematic_plan SET id = $last_id WHERE iid = $last_id"; + $sql = "UPDATE $tbl_thematic_plan SET id = iid WHERE iid = $last_id"; Database::query($sql); api_item_property_update($_course, 'thematic_plan', $last_id,"ThematicPlanAdded", $user_id); } diff --git a/main/newscorm/learnpath.class.php b/main/newscorm/learnpath.class.php index be734c529c..ddba330791 100755 --- a/main/newscorm/learnpath.class.php +++ b/main/newscorm/learnpath.class.php @@ -216,7 +216,7 @@ class learnpath Database::query($sql); $this->lp_view_id = Database::insert_id(); - $sql = "UPDATE $lp_table SET id = ".$this->lp_view_id." WHERE iid = ".$this->lp_view_id; + $sql = "UPDATE $lp_table SET id = iid WHERE iid = ".$this->lp_view_id; Database::query($sql); @@ -388,7 +388,7 @@ class learnpath Database::query($sql); $insertId = Database::insert_id(); - $sql = "UPDATE $lp_item_view_table SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $lp_item_view_table SET id = iid WHERE iid = $insertId"; Database::query($sql); } } @@ -587,7 +587,7 @@ class learnpath $new_item_id = Database::insert($tbl_lp_item, $params); - $sql = "UPDATE $tbl_lp_item SET id = $new_item_id WHERE iid = $new_item_id"; + $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id"; Database::query($sql); if ($this->debug > 2) { @@ -787,7 +787,7 @@ class learnpath Database::query($sql); $id = Database :: insert_id(); if ($id > 0) { - $sql = "UPDATE $tbl_lp SET id = $id WHERE iid = $id"; + $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id"; Database::query($sql); $course_info = api_get_course_info(); @@ -3670,7 +3670,7 @@ class learnpath $id = Database :: insert_id(); $this->lp_view_id = $id; - $sql = "UPDATE $lp_view_table SET id = $id WHERE iid = $id"; + $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id"; Database::query($sql); } @@ -4215,7 +4215,7 @@ class learnpath Database::query($sql); $insertId = Database::insert_id(); - $sql = "UPDATE $tbl_tool SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId"; Database::query($sql); } elseif (($set_visibility == 'v') && ($num > 0)) { @@ -4267,7 +4267,7 @@ class learnpath $res = Database::query($sql); $view_id = Database::insert_id(); - $sql = "UPDATE $lp_view_table SET id = $view_id WHERE iid = $view_id"; + $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id"; Database::query($sql); if ($view_id) { diff --git a/main/newscorm/learnpathItem.class.php b/main/newscorm/learnpathItem.class.php index d8bb6201ef..4c8c6e8ef3 100755 --- a/main/newscorm/learnpathItem.class.php +++ b/main/newscorm/learnpathItem.class.php @@ -3746,7 +3746,7 @@ class learnpathItem $insertId = Database::insert($iva_table, $params); - $sql = "UPDATE $iva_table SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $iva_table SET id = iid WHERE iid = $insertId"; Database::query($sql); } } @@ -3846,7 +3846,7 @@ class learnpathItem } $this->db_item_view_id = Database::insert($item_view_table, $params); - $sql = "UPDATE $item_view_table SET id = ".$this->db_item_view_id." WHERE iid = ".$this->db_item_view_id; + $sql = "UPDATE $item_view_table SET id = iid WHERE iid = ".$this->db_item_view_id; Database::query($sql); $inserted = true; @@ -3893,7 +3893,7 @@ class learnpathItem $this->db_item_view_id = Database::insert($item_view_table, $params); - $sql = "UPDATE $item_view_table SET id = ".$this->db_item_view_id." WHERE iid = ".$this->db_item_view_id; + $sql = "UPDATE $item_view_table SET id = iid WHERE iid = ".$this->db_item_view_id; Database::query($sql); } else { @@ -4172,7 +4172,7 @@ class learnpathItem $insertId = Database::insert($iva_table, $params); - $sql = "UPDATE $iva_table SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $iva_table SET id = iid WHERE iid = $insertId"; Database::query($sql); } } diff --git a/main/survey/survey.lib.php b/main/survey/survey.lib.php index 68ccf03a89..3e97230976 100755 --- a/main/survey/survey.lib.php +++ b/main/survey/survey.lib.php @@ -609,7 +609,7 @@ class SurveyManager ); $insertId = Database::insert($table_survey_question_group, $params); - $sql = "UPDATE $table_survey_question_group SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $table_survey_question_group SET id = iid WHERE iid = $insertId"; Database::query($sql); $group_id[$row['id']] = $insertId; @@ -636,7 +636,7 @@ class SurveyManager ); $insertId = Database::insert($table_survey_question, $params); - $sql = "UPDATE $table_survey_question SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $table_survey_question SET id = iid WHERE iid = $insertId"; Database::query($sql); $question_id[$row['question_id']] = $insertId; diff --git a/main/wiki/wiki.inc.php b/main/wiki/wiki.inc.php index 1dd38b0fb4..9d7a79f925 100755 --- a/main/wiki/wiki.inc.php +++ b/main/wiki/wiki.inc.php @@ -331,7 +331,7 @@ class Wiki $id = Database::insert_id(); if ($id > 0) { - $sql = "UPDATE $tbl_wiki SET id = $insertId WHERE iid = $insertId"; + $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $insertId"; Database::query($sql); //insert into item_property @@ -429,7 +429,7 @@ class Wiki $id = Database::insert_id(); if ($id) { - $sql = "UPDATE $tbl_wiki SET id = $id WHERE iid = $id"; + $sql = "UPDATE $tbl_wiki SET id = iid WHERE iid = $id"; Database::query($sql); api_item_property_update( diff --git a/main/work/work.lib.php b/main/work/work.lib.php index c31ef37625..ce1ee7e481 100755 --- a/main/work/work.lib.php +++ b/main/work/work.lib.php @@ -3936,7 +3936,7 @@ function processWorkForm($workInfo, $values, $courseInfo, $sessionId, $groupId, Database::query($sql); $workId = Database::insert_id(); - $sql = "UPDATE $work_table SET id = $workId WHERE iid = $workId "; + $sql = "UPDATE $work_table SET id = iid WHERE iid = $workId "; Database::query($sql); if ($workId) { @@ -4034,7 +4034,7 @@ function addDir($params, $user_id, $courseInfo, $group_id, $session_id) // Add the directory $id = Database::insert_id(); - $sql = "UPDATE $work_table SET id = $id WHERE iid = $id"; + $sql = "UPDATE $work_table SET id = iid WHERE iid = $id"; Database::query($sql); if ($id) { From ae5594d30b1ded39a27d5e8ecd53d4a80fd948f0 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 13 Apr 2015 13:29:28 +0200 Subject: [PATCH 102/159] Fix query see #7474 --- main/inc/lib/agenda.lib.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/main/inc/lib/agenda.lib.php b/main/inc/lib/agenda.lib.php index 8230fd0e8c..9cda96fb19 100644 --- a/main/inc/lib/agenda.lib.php +++ b/main/inc/lib/agenda.lib.php @@ -1341,14 +1341,16 @@ class Agenda } $dateCondition = null; - if (!empty($start) && !empty($end)) { + + if (!empty($start) && !empty($end)) { $dateCondition .= "AND ( - (agenda.start_date >= '".$start."' OR agenda.start_date IS NULL) AND - (agenda.end_date <= '".$end."' OR agenda.end_date IS NULL) + agenda.start_date BETWEEN '".$start."' AND '".$end."' OR + agenda.end_date BETWEEN '".$start."' AND '".$end."' )"; } $sql .= $dateCondition; + //echo $sql; $allowComments = api_get_configuration_value('allow_agenda_event_comment'); $result = Database::query($sql); @@ -1543,7 +1545,7 @@ class Agenda */ private function formatEventDate($utcTime) { - return date('c', api_strtotime(api_get_local_time($utcTime))); + return date(DateTime::ISO8601, api_strtotime(api_get_local_time($utcTime))); } /** From 42d122a4510f374c64f8179f02c2dd4723d82f2f Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Mon, 13 Apr 2015 13:42:51 +0200 Subject: [PATCH 103/159] Fix PHP warnings. --- main/inc/lib/message.lib.php | 8 ++++-- main/inc/lib/template.lib.php | 9 ++++--- main/inc/lib/tracking.lib.php | 16 +++++++++--- main/messages/new_message.php | 10 +++----- main/messages/outbox.php | 35 +++++++++++--------------- main/tracking/course_log_resources.php | 2 +- 6 files changed, 42 insertions(+), 38 deletions(-) diff --git a/main/inc/lib/message.lib.php b/main/inc/lib/message.lib.php index abf209dbca..983752834d 100755 --- a/main/inc/lib/message.lib.php +++ b/main/inc/lib/message.lib.php @@ -224,12 +224,16 @@ class MessageManager // Validating fields if (empty($subject) && empty($group_id)) { - return get_lang('YouShouldWriteASubject'); + Display::addFlash(Display::return_message(get_lang('YouShouldWriteASubject'), 'warning')); + return false; } else if ($total_filesize > intval(api_get_setting('message_max_upload_filesize'))) { - return sprintf( + $warning = sprintf( get_lang("FilesSizeExceedsX"), format_file_size(api_get_setting('message_max_upload_filesize')) ); + + Display::addFlash(Display::return_message($warning , 'warning')); + return false; } $inbox_last_id = null; diff --git a/main/inc/lib/template.lib.php b/main/inc/lib/template.lib.php index 8514719ed0..df0d14f72a 100755 --- a/main/inc/lib/template.lib.php +++ b/main/inc/lib/template.lib.php @@ -451,11 +451,12 @@ class Template //Here we can add system parameters that can be use in any template $_s = array( - 'software_name' => $_configuration['software_name'], + 'software_name' => $_configuration['software_name'], 'system_version' => $_configuration['system_version'], - 'site_name' => api_get_setting('siteName'), - 'institution' => api_get_setting('Institution'), - 'date' => api_format_date('now', DATE_FORMAT_LONG), + 'site_name' => api_get_setting('siteName'), + 'institution' => api_get_setting('Institution'), + 'date' => api_format_date('now', DATE_FORMAT_LONG), + 'timezone' => _api_get_timezone() ); $this->assign('_s', $_s); } diff --git a/main/inc/lib/tracking.lib.php b/main/inc/lib/tracking.lib.php index 9209657888..816f774c78 100755 --- a/main/inc/lib/tracking.lib.php +++ b/main/inc/lib/tracking.lib.php @@ -5670,14 +5670,18 @@ class TrackingCourseLog WHERE c_id = $course_id AND id = $ref"; $rs_document = Database::query($sql); $obj_document = Database::fetch_object($rs_document); - $row[5] = $obj_document->title; + if ($obj_document) { + $row[5] = $obj_document->title; + } break; case 'glossary': $sql = "SELECT name FROM $table_tool WHERE c_id = $course_id AND glossary_id = $ref"; $rs_document = Database::query($sql); $obj_document = Database::fetch_object($rs_document); - $row[5] = $obj_document->name; + if ($obj_document) { + $row[5] = $obj_document->name; + } break; case 'lp': $sql = "SELECT name @@ -5691,14 +5695,18 @@ class TrackingCourseLog WHERE c_id = $course_id AND id = $ref"; $rs_document = Database::query($sql); $obj_document = Database::fetch_object($rs_document); - $row[5] = $obj_document->title; + if ($obj_document) { + $row[5] = $obj_document->title; + } break; case 'course_description': $sql = "SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref"; $rs_document = Database::query($sql); $obj_document = Database::fetch_object($rs_document); - $row[5] = $obj_document->title; + if ($obj_document) { + $row[5] = $obj_document->title; + } break; case 'thematic': $rs = Database::query("SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref"); diff --git a/main/messages/new_message.php b/main/messages/new_message.php index 995f4af2fc..9669b904a7 100755 --- a/main/messages/new_message.php +++ b/main/messages/new_message.php @@ -254,11 +254,7 @@ function manage_form($default, $select_from_user_list = null, $sent_to = null) $parent_id ); if ($res) { - if (is_string($res)) { - $html .= Display::return_message($res, 'error'); - } else { - $html .= MessageManager::display_success_message($user); - } + $html .= MessageManager::display_success_message($user); } } } else { @@ -384,8 +380,8 @@ if (api_get_setting('allow_social_tool') == 'true') { $tpl->display($social_layout); } else { $content = $social_right_content; - $tpl->assign('actions', $actions); - $tpl->assign('message', $show_message); + //$tpl->assign('actions', $actions); + //$tpl->assign('message', $show_message); $tpl->assign('content', $content); $tpl->display_one_col_template(); } diff --git a/main/messages/outbox.php b/main/messages/outbox.php index 7166aba7b4..c8eae17aac 100755 --- a/main/messages/outbox.php +++ b/main/messages/outbox.php @@ -27,9 +27,7 @@ if (api_get_setting('allow_message_tool')!='true'){ //jquery thickbox already called from main/inc/header.inc.php $htmlHeadXtra[]=''; function get_courses_list_by_user_id_based_in_exercises($user_id) { - $TABLETRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES); + $TABLETRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES); $user_id = intval($user_id); $sql = "SELECT DISTINCT exe_user_id, c_id, session_id - FROM $TABLETRACK_EXERCICES WHERE exe_user_id = $user_id + FROM $TABLETRACK_EXERCICES + WHERE exe_user_id = $user_id ORDER by exe_user_id, c_id ASC"; $res = Database::query($sql); $course_list = array(); - while($row = Database::fetch_array($res,'ASSOC')) { + while ($row = Database::fetch_array($res,'ASSOC')) { $course_list []= $row; } return $course_list; @@ -641,7 +643,7 @@ foreach ($session_list as $session_data) { $combinations = array(); if (!empty($user_list)) { - foreach ($user_list as $user) { + foreach ($user_list as $user) { $user_id = $user['user_id']; $name = $user['firstname'].' '.$user['lastname']; $course_list_registered = CourseManager::get_courses_list_by_user_id( @@ -658,7 +660,7 @@ if (!empty($user_list)) { // Recover the code for historical reasons. If it can be proven // that the code can be safely replaced by c_id in the following // PHP code, feel free to do so - $courseInfo = api_get_course_info_by_id($course_reg['c_id']); + $courseInfo = api_get_course_info_by_id($course_reg['real_id']); $course_reg['code'] = $courseInfo['code']; $new_course_list[] = $course_reg['code'].'_'.$course_reg['session_id']; } diff --git a/main/inc/lib/login.lib.php b/main/inc/lib/login.lib.php index c1c5a6b809..4300a96c01 100755 --- a/main/inc/lib/login.lib.php +++ b/main/inc/lib/login.lib.php @@ -28,10 +28,9 @@ class Login */ public static function get_user_account_list($user, $reset = false, $by_username = false) { - global $_configuration; $portal_url = api_get_path(WEB_PATH); - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { $url = api_get_access_url($access_url_id); @@ -82,8 +81,9 @@ class Login * @param int $user * @author Olivier Cauberghe , Ghent University */ - public static function send_password_to_user($user, $by_username = false) { - global $_configuration; + public static function send_password_to_user($user, $by_username = false) + { + $email_subject = "[" . api_get_setting('siteName') . "] " . get_lang('LoginRequest'); // SUBJECT if ($by_username) { // Show only for lost password @@ -95,7 +95,7 @@ class Login } $portal_url = api_get_path(WEB_PATH); - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { $url = api_get_access_url($access_url_id); diff --git a/main/inc/lib/system_announcements.lib.php b/main/inc/lib/system_announcements.lib.php index 2b34fa408f..3ff0e234b6 100755 --- a/main/inc/lib/system_announcements.lib.php +++ b/main/inc/lib/system_announcements.lib.php @@ -57,7 +57,7 @@ class SystemAnnouncementManager } global $_configuration; $current_access_url_id = 1; - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $current_access_url_id = api_get_current_access_url_id(); } $sql .= " AND access_url_id = '$current_access_url_id' "; @@ -251,7 +251,7 @@ class SystemAnnouncementManager global $_configuration; $current_access_url_id = 1; - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $current_access_url_id = api_get_current_access_url_id(); } $sql .= " AND access_url_id = '$current_access_url_id' "; @@ -277,9 +277,8 @@ class SystemAnnouncementManager $now = api_get_utc_datetime(); $sql = "SELECT *, IF( '$now' >= date_start AND '$now' <= date_end, '1', '0') AS visible FROM $db_table"; - global $_configuration; $current_access_url_id = 1; - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $current_access_url_id = api_get_current_access_url_id(); } $sql .= " WHERE access_url_id = '$current_access_url_id' "; @@ -357,9 +356,8 @@ class SystemAnnouncementManager $langsql = is_null($lang) ? 'NULL' : "'".Database::escape_string($lang)."'"; - global $_configuration; $current_access_url_id = 1; - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $current_access_url_id = api_get_current_access_url_id(); } diff --git a/main/inc/lib/template.lib.php b/main/inc/lib/template.lib.php index df0d14f72a..30c493ba44 100755 --- a/main/inc/lib/template.lib.php +++ b/main/inc/lib/template.lib.php @@ -760,7 +760,7 @@ class Template $favico = ''; - if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { $url_info = api_get_access_url($access_url_id); diff --git a/main/inc/lib/userportal.lib.php b/main/inc/lib/userportal.lib.php index ced1db24c8..46a4e58512 100755 --- a/main/inc/lib/userportal.lib.php +++ b/main/inc/lib/userportal.lib.php @@ -1,8 +1,6 @@ validate()) { //$emailto = '"'.api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS).'" <'.$email.'>'; $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName'); $portal_url = $_configuration['root_web']; - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { $access_url_id = api_get_current_access_url_id(); if ($access_url_id != -1) { $url = api_get_access_url($access_url_id); diff --git a/main/webservices/registration.soap.php b/main/webservices/registration.soap.php index 664ca21518..62abc1f2b5 100755 --- a/main/webservices/registration.soap.php +++ b/main/webservices/registration.soap.php @@ -331,7 +331,7 @@ function WSCreateUsers($params) { if ($result) { //echo "id returned"; $return = Database::insert_id(); - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { if (api_get_current_access_url_id() != -1) { UrlManager::add_user_to_url($return, api_get_current_access_url_id()); } else { @@ -536,7 +536,7 @@ function WSCreateUser($params) { if ($result) { //echo "id returned"; $return = Database::insert_id(); - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { if (api_get_current_access_url_id() != -1) { UrlManager::add_user_to_url($return, api_get_current_access_url_id()); } else { @@ -827,7 +827,7 @@ function WSCreateUsersPasswordCrypted($params) { if ($result) { //echo "id returned"; $return = Database::insert_id(); - if ($_configuration['multiple_access_urls']) { + if (api_is_multiple_url_enabled()) { if (api_get_current_access_url_id() != -1) { UrlManager::add_user_to_url($return, api_get_current_access_url_id()); } else { From dfd572d0a08d6ee2ca365ca9168062b3ef3fd560 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 15 Apr 2015 14:57:32 +0200 Subject: [PATCH 142/159] Replace function name. --- main/admin/configure_inscription.php | 14 +++++++------- .../lib/search_course_widget.class.php | 4 ++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/main/admin/configure_inscription.php b/main/admin/configure_inscription.php index 16f48c5c20..e09c0fdc4f 100755 --- a/main/admin/configure_inscription.php +++ b/main/admin/configure_inscription.php @@ -11,7 +11,7 @@ require_once '../inc/global.inc.php'; api_protect_admin_script(); // Load terms & conditions from the current lang -if (get_setting('allow_terms_conditions') == 'true') { +if (api_get_setting('allow_terms_conditions') == 'true') { $get = array_keys($_GET); if (isset($get)) { if ($get[0] == 'legal') { @@ -159,12 +159,12 @@ echo Display::page_header($tool_name); // The following security condition has been removed, because it makes no sense here. See Bug #1846. //// Forbidden to self-register -//if (get_setting('allow_registration') == 'false') { +//if (api_get_setting('allow_registration') == 'false') { // api_not_allowed(); //} //api_display_tool_title($tool_name); -if (get_setting('allow_registration') == 'approval') { +if (api_get_setting('allow_registration') == 'approval') { Display::display_normal_message(get_lang('YourAccountHasToBeApproved')); } //if openid was not found @@ -173,7 +173,7 @@ if (!empty($_GET['openid_msg']) && $_GET['openid_msg'] == 'idnotfound') { } $form = new FormValidator('registration'); -if (get_setting('allow_terms_conditions') == 'true') { +if (api_get_setting('allow_terms_conditions') == 'true') { $display_all_form = !isset($_SESSION['update_term_and_condition']['user_id']); } else { $display_all_form = true; @@ -229,12 +229,12 @@ if ($display_all_form) { } // LANGUAGE - if (get_setting('registration', 'language') == 'true') { + if (api_get_setting('registration', 'language') == 'true') { $form->addElement('select_language', 'language', get_lang('Language'), '', array('disabled' => 'disabled')); } // STUDENT/TEACHER - if (get_setting('allow_registration_as_teacher') != 'false') { + if (api_get_setting('allow_registration_as_teacher') != 'false') { $form->addElement('radio', 'status', get_lang('Status'), get_lang('RegStudent'), STUDENT, array('disabled' => 'disabled')); $form->addElement('radio', 'status', null, get_lang('RegAdmin'), COURSEMANAGER, array('disabled' => 'disabled')); } @@ -271,7 +271,7 @@ if ($display_all_form) { } // Terms and conditions -if (get_setting('allow_terms_conditions') == 'true') { +if (api_get_setting('allow_terms_conditions') == 'true') { $language = api_get_interface_language(); $language = api_get_language_id($language); $term_preview = LegalManager::get_last_condition($language); diff --git a/plugin/search_course/lib/search_course_widget.class.php b/plugin/search_course/lib/search_course_widget.class.php index 806ece533b..3792758a7e 100755 --- a/plugin/search_course/lib/search_course_widget.class.php +++ b/plugin/search_course/lib/search_course_widget.class.php @@ -227,8 +227,8 @@ EOT; $user_courses = $this->retrieve_user_courses(); - $display_coursecode = (get_setting('display_coursecode_in_courselist') == 'true'); - $display_teacher = (get_setting('display_teacher_in_courselist') == 'true'); + $display_coursecode = (api_get_setting('display_coursecode_in_courselist') == 'true'); + $display_teacher = (api_get_setting('display_teacher_in_courselist') == 'true'); echo '
      '; foreach ($courses as $key => $course) From 1382059625bf7cb6087debd86b40cd5a15223319 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 15 Apr 2015 15:06:50 +0200 Subject: [PATCH 143/159] Fix fatal error due recent changes. --- main/admin/configure_inscription.php | 2 +- main/inc/lib/statistics.lib.php | 33 +++++++++++++------- main/inc/lib/zombie/zombie_manager.class.php | 24 ++++++++------ main/inc/lib/zombie/zombie_report.class.php | 17 +++++----- 4 files changed, 46 insertions(+), 30 deletions(-) diff --git a/main/admin/configure_inscription.php b/main/admin/configure_inscription.php index e09c0fdc4f..8bac4e087e 100755 --- a/main/admin/configure_inscription.php +++ b/main/admin/configure_inscription.php @@ -109,7 +109,7 @@ if (!empty($homep_new)) { } if (!empty($action)) { - if ($_POST['formSent']) { + if (isset($_POST['formSent'])) { switch ($action) { case 'edit_top': // Filter diff --git a/main/inc/lib/statistics.lib.php b/main/inc/lib/statistics.lib.php index 0532c42c5e..6e6b356874 100644 --- a/main/inc/lib/statistics.lib.php +++ b/main/inc/lib/statistics.lib.php @@ -96,9 +96,9 @@ class Statistics public static function countUsers($status = null, $categoryCode = null, $countInvisibleCourses = true, $onlyActive = false) { // Database table definitions - $course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER); - $course_table = Database :: get_main_table(TABLE_MAIN_COURSE); - $user_table = Database :: get_main_table(TABLE_MAIN_USER); + $course_user_table = Database:: get_main_table(TABLE_MAIN_COURSE_USER); + $course_table = Database:: get_main_table(TABLE_MAIN_COURSE); + $user_table = Database:: get_main_table(TABLE_MAIN_USER); $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); $current_url_id = api_get_current_access_url_id(); $active_filter = $onlyActive?' AND active=1':''; @@ -107,22 +107,33 @@ class Statistics if (api_is_multiple_url_enabled()) { $sql = "SELECT COUNT(DISTINCT(u.user_id)) AS number FROM $user_table as u, $access_url_rel_user_table as url - WHERE u.user_id=url.user_id - AND access_url_id='".$current_url_id."' + WHERE + u.user_id = url.user_id AND + access_url_id = '".$current_url_id."' $status_filter $active_filter"; if (isset ($categoryCode)) { $sql = "SELECT COUNT(DISTINCT(cu.user_id)) AS number FROM $course_user_table cu, $course_table c, $access_url_rel_user_table as url - WHERE c.id = cu.c_id - AND c.category_code = '".Database::escape_string($categoryCode)."' - AND cu.user_id=url.user_id AND access_url_id='".$current_url_id."' - $status_filter $active_filter"; + WHERE + c.id = cu.c_id AND + c.category_code = '".Database::escape_string($categoryCode)."' AND + cu.user_id = url.user_id AND + access_url_id='".$current_url_id."' + $status_filter $active_filter"; } } else { - $sql = "SELECT COUNT(DISTINCT(user_id)) AS number FROM $user_table WHERE 1=1 $status_filter $active_filter"; + $sql = "SELECT COUNT(DISTINCT(user_id)) AS number + FROM $user_table WHERE 1=1 $status_filter $active_filter"; if (isset ($categoryCode)) { $status_filter = isset($status)?' AND status = '.intval($status):''; - $sql = "SELECT COUNT(DISTINCT(cu.user_id)) AS number FROM $course_user_table cu, $course_table c WHERE c.code = cu.course_code AND c.category_code = '".Database::escape_string($categoryCode)."' $status_filter $active_filter"; + $sql = "SELECT COUNT(DISTINCT(cu.user_id)) AS number + FROM $course_user_table cu, $course_table c + WHERE + c.id = cu.c_id AND + c.category_code = '".Database::escape_string($categoryCode)."' + $status_filter + $active_filter + "; } } diff --git a/main/inc/lib/zombie/zombie_manager.class.php b/main/inc/lib/zombie/zombie_manager.class.php index 0f57e6d094..68a4029abb 100755 --- a/main/inc/lib/zombie/zombie_manager.class.php +++ b/main/inc/lib/zombie/zombie_manager.class.php @@ -26,7 +26,7 @@ class ZombieManager * @param bool $active_only if true returns only active users. Otherwise returns all users. * @return ResultSet */ - static function list_zombies($ceiling, $active_only = true) + static function listZombies($ceiling, $active_only = true, $count = 0, $from = 10, $column = 'user.firstname', $direction = 'desc') { $ceiling = is_numeric($ceiling) ? (int) $ceiling : strtotime($ceiling); $ceiling = date('Y-m-d H:i:s', $ceiling); @@ -46,7 +46,6 @@ class ZombieManager user.active, access.login_date'; - global $_configuration; if (api_is_multiple_url_enabled()) { $access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); $current_url_id = api_get_current_access_url_id(); @@ -70,24 +69,31 @@ class ZombieManager access.login_date <= '$ceiling' AND user.user_id = access.login_user_id"; } - if($active_only) - { + if ($active_only) { $sql .= ' AND user.active = 1'; } - return ResultSet::create($sql); + $count = intval($count); + $from = intval($from); + + $sql .= " ORDER BY $column $direction"; + $sql .= " LIMIT $count, $from "; + + $result = Database::query($sql); + + return Database::store_result($result, 'ASSOC'); } + /** + * @param $ceiling + */ static function deactivate_zombies($ceiling) { $zombies = self::list_zombies($ceiling); $ids = array(); - foreach($zombies as $zombie) - { + foreach($zombies as $zombie) { $ids[] = $zombie['user_id']; } UserManager::deactivate_users($ids); } - - } diff --git a/main/inc/lib/zombie/zombie_report.class.php b/main/inc/lib/zombie/zombie_report.class.php index 24510ceca8..cc73b7d47c 100755 --- a/main/inc/lib/zombie/zombie_report.class.php +++ b/main/inc/lib/zombie/zombie_report.class.php @@ -31,7 +31,7 @@ class ZombieReport implements Countable function get_parameters() { - + $result = array( 'name' => 'zombie_report_parameters', 'method' => 'GET', @@ -149,7 +149,7 @@ class ZombieReport implements Countable { /** - * todo check token + * todo check token */ $check = Security::check_token('post'); Security::clear_token(); @@ -197,7 +197,7 @@ class ZombieReport implements Countable $ceiling = $this->get_ceiling(); $active_only = $this->get_active_only(); - $items = ZombieManager::list_zombies($ceiling, $active_only); + $items = ZombieManager::listZombies($ceiling, $active_only); return count($items); } @@ -209,7 +209,7 @@ class ZombieReport implements Countable $ceiling = $this->get_ceiling(); $active_only = $this->get_active_only(); - $items = ZombieManager::list_zombies($ceiling, $active_only)->limit($count, $from)->orderby($column, $direction); + $items = ZombieManager::listZombies($ceiling, $active_only, $count, $from, $column, $direction); $result = array(); foreach ($items as $item) { $row = array(); @@ -231,7 +231,6 @@ class ZombieReport implements Countable function display_data($return = false) { - $count = array($this, 'count'); $data = array($this, 'get_data'); @@ -277,9 +276,9 @@ class ZombieReport implements Countable /** * Table formatter for the active column. - * - * @param string $active - * @return string + * + * @param string $active + * @return string */ function format_active($active) { @@ -323,4 +322,4 @@ class ZombieReport implements Countable } } -} \ No newline at end of file +} From d39bd6ef17e4d8fd7aa9ecb6eff6ff5674946678 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 15 Apr 2015 15:45:35 +0200 Subject: [PATCH 144/159] Fix query, format code. --- main/admin/special_exports.php | 16 ++++++++----- .../classes/CourseBuilder.class.php | 9 ++++---- .../classes/CourseSelectForm.class.php | 4 ++-- .../classes/CourseSession.class.php | 2 +- main/inc/lib/course.lib.php | 2 +- main/webservices/cm_webservice_inbox.php | 23 ++++++++----------- 6 files changed, 29 insertions(+), 27 deletions(-) diff --git a/main/admin/special_exports.php b/main/admin/special_exports.php index 912060a588..c053bd34f8 100755 --- a/main/admin/special_exports.php +++ b/main/admin/special_exports.php @@ -1,5 +1,6 @@ * @package chamilo.include.export */ + // including the global file $cidReset = true; require_once '../inc/global.inc.php'; @@ -204,7 +206,7 @@ function fullexportspecial(){ $code_course = ''; $list_course = array(); $zip_folder = new PclZip($FileZip['TEMP_FILE_ZIP']); - $list_course = Database::get_course_list(); + $list_course = CourseManager::get_course_list(); $tbl_document = Database::get_course_table(TABLE_DOCUMENT); $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY); @@ -217,7 +219,7 @@ function fullexportspecial(){ } else { $querypath = $FileZip['PATH']; } - $course_id = $_course['real_id']; + $course_id = $_course['real_id']; //Add tem to the zip file course $sql = "SELECT path FROM $tbl_document AS docs, $tbl_property AS props @@ -238,10 +240,12 @@ function fullexportspecial(){ } //Add tem to the zip file session course $code_course = $_course['code']; - $sql_session = "SELECT id, name, c_id - FROM $tbl_session_course - INNER JOIN $tbl_session ON session_id = id - WHERE course_code = '$code_course' "; + $sql_session = "SELECT s.id, name, c_id + FROM $tbl_session_course sc + INNER JOIN $tbl_session s + ON sc.session_id = s.id + WHERE c_id = '$course_id' "; + $query_session = Database::query($sql_session); while ($rows_session = Database::fetch_assoc($query_session)) { $session_id = $rows_session['id']; diff --git a/main/coursecopy/classes/CourseBuilder.class.php b/main/coursecopy/classes/CourseBuilder.class.php index ec323bd271..b882953aa7 100755 --- a/main/coursecopy/classes/CourseBuilder.class.php +++ b/main/coursecopy/classes/CourseBuilder.class.php @@ -1317,10 +1317,11 @@ class CourseBuilder ); //current platform encoding $code_course = $_course['code']; $courseId = $_course['real_id']; - $sql_session = "SELECT id, name, c_id - FROM $tbl_session_course - INNER JOIN $tbl_session ON session_id = id - WHERE c_id = '$courseId' "; + $sql_session = "SELECT s.id, name, c_id + FROM $tbl_session_course sc + INNER JOIN $tbl_session s + ON sc.session_id = s.id + WHERE sc.c_id = '$courseId' "; $query_session = Database::query($sql_session); while ($rows_session = Database::fetch_assoc($query_session)) { $session = new CourseSession( diff --git a/main/coursecopy/classes/CourseSelectForm.class.php b/main/coursecopy/classes/CourseSelectForm.class.php index 60c9230851..dfcc6445b4 100755 --- a/main/coursecopy/classes/CourseSelectForm.class.php +++ b/main/coursecopy/classes/CourseSelectForm.class.php @@ -561,9 +561,9 @@ class CourseSelectForm * @param array $hidden_fiels Hidden fields to add to the form. * @param boolean the document array will be serialize. This is used in the course_copy.php file */ - function display_form_session_export($list_course, $hidden_fields = null, $avoid_serialize = false) + public static function display_form_session_export($list_course, $hidden_fields = null, $avoid_serialize = false) { -?> + ?>