From 22190bc46a439abaea1b27eb51ac557262fe2a43 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Fri, 25 Jan 2013 16:49:43 +0100 Subject: [PATCH] Using $app obj to handle installation process --- composer.lock | 40 +- main/inc/global.inc.php | 74 ++- main/inc/lib/chamilo_session.class.php | 59 +- main/inc/lib/database.lib.php | 819 +++++++++++++++---------- main/install/index.php | 3 +- main/install/install.lib.php | 14 +- resources/config/prod.php | 4 +- 7 files changed, 595 insertions(+), 418 deletions(-) diff --git a/composer.lock b/composer.lock index fff117cdb1..6a59a2a60c 100755 --- a/composer.lock +++ b/composer.lock @@ -261,12 +261,12 @@ "source": { "type": "git", "url": "https://github.com/doctrine/common", - "reference": "f44d98d5fdd102959e2bf71b36392dbacf0e568d" + "reference": "db84fc111652774f22b72a916aef40ce3f584e45" }, "dist": { "type": "zip", - "url": "https://github.com/doctrine/common/archive/f44d98d5fdd102959e2bf71b36392dbacf0e568d.zip", - "reference": "f44d98d5fdd102959e2bf71b36392dbacf0e568d", + "url": "https://github.com/doctrine/common/archive/db84fc111652774f22b72a916aef40ce3f584e45.zip", + "reference": "db84fc111652774f22b72a916aef40ce3f584e45", "shasum": "" }, "require": { @@ -277,7 +277,7 @@ "doctrine/lexer": "1.*", "doctrine/annotations": "1.*" }, - "time": "2013-01-20 19:00:57", + "time": "2013-01-25 05:59:24", "type": "library", "extra": { "branch-alias": { @@ -335,12 +335,12 @@ "source": { "type": "git", "url": "https://github.com/doctrine/dbal", - "reference": "f444b115d162e50aeeabaaef1edd0b65b61a7438" + "reference": "19269218ee387bd96b4fc8f31b1f492f298c5917" }, "dist": { "type": "zip", - "url": "https://github.com/doctrine/dbal/archive/f444b115d162e50aeeabaaef1edd0b65b61a7438.zip", - "reference": "f444b115d162e50aeeabaaef1edd0b65b61a7438", + "url": "https://github.com/doctrine/dbal/archive/19269218ee387bd96b4fc8f31b1f492f298c5917.zip", + "reference": "19269218ee387bd96b4fc8f31b1f492f298c5917", "shasum": "" }, "require": { @@ -353,7 +353,7 @@ "suggest": { "symfony/console": "For helpful console commands such as SQL execution and import of files." }, - "time": "2013-01-23 23:16:30", + "time": "2013-01-25 06:00:32", "type": "library", "extra": { "branch-alias": { @@ -643,12 +643,12 @@ "source": { "type": "git", "url": "git://github.com/l3pp4rd/DoctrineExtensions.git", - "reference": "baa42fda5607978d70040b9f38b6b3a13823c903" + "reference": "93349ad3ab200c7aa69237355c4ee811d359d160" }, "dist": { "type": "zip", - "url": "https://github.com/l3pp4rd/DoctrineExtensions/archive/baa42fda5607978d70040b9f38b6b3a13823c903.zip", - "reference": "baa42fda5607978d70040b9f38b6b3a13823c903", + "url": "https://github.com/l3pp4rd/DoctrineExtensions/archive/93349ad3ab200c7aa69237355c4ee811d359d160.zip", + "reference": "93349ad3ab200c7aa69237355c4ee811d359d160", "shasum": "" }, "require": { @@ -668,7 +668,7 @@ "doctrine/mongodb": ">=1.0.0", "doctrine/mongodb-odm": ">=1.0.0-BETA7" }, - "time": "2013-01-18 18:21:44", + "time": "2013-01-24 18:57:40", "type": "library", "extra": { "branch-alias": { @@ -968,12 +968,12 @@ "source": { "type": "git", "url": "git://github.com/fabpot/Silex.git", - "reference": "f7a8956f96e991f86a5fc4811876bef76e3a4e25" + "reference": "a23c221e609a17dfc2923066e1680149b7678cf9" }, "dist": { "type": "zip", - "url": "https://github.com/fabpot/Silex/archive/f7a8956f96e991f86a5fc4811876bef76e3a4e25.zip", - "reference": "f7a8956f96e991f86a5fc4811876bef76e3a4e25", + "url": "https://github.com/fabpot/Silex/archive/a23c221e609a17dfc2923066e1680149b7678cf9.zip", + "reference": "a23c221e609a17dfc2923066e1680149b7678cf9", "shasum": "" }, "require": { @@ -1009,7 +1009,7 @@ "symfony/css-selector": ">=2.1,<2.3-dev", "symfony/dom-crawler": ">=2.1,<2.3-dev" }, - "time": "2013-01-24 12:18:41", + "time": "2013-01-25 06:59:19", "type": "library", "extra": { "branch-alias": { @@ -1145,18 +1145,18 @@ "source": { "type": "git", "url": "https://github.com/symfony/Console", - "reference": "v2.2.0-BETA2" + "reference": "fdb2d9320106926266a0f7a5a97aab7213e11ad6" }, "dist": { "type": "zip", - "url": "https://github.com/symfony/Console/archive/v2.2.0-BETA2.zip", - "reference": "v2.2.0-BETA2", + "url": "https://github.com/symfony/Console/archive/fdb2d9320106926266a0f7a5a97aab7213e11ad6.zip", + "reference": "fdb2d9320106926266a0f7a5a97aab7213e11ad6", "shasum": "" }, "require": { "php": ">=5.3.3" }, - "time": "2013-01-18 08:14:58", + "time": "2013-01-24 15:55:08", "type": "library", "extra": { "branch-alias": { diff --git a/main/inc/global.inc.php b/main/inc/global.inc.php index c9ddf6f5ac..2ceaad58ff 100755 --- a/main/inc/global.inc.php +++ b/main/inc/global.inc.php @@ -147,13 +147,15 @@ $app->register( $app->register(new Silex\Provider\FormServiceProvider()); //Monolog -$app->register( - new Silex\Provider\MonologServiceProvider(), - array( - 'monolog.logfile' => api_get_path(SYS_ARCHIVE_PATH).'chamilo_development.log', - 'monolog.name' => 'chamilo', - ) -); +if (is_writable(api_get_path(SYS_ARCHIVE_PATH))) { + $app->register( + new Silex\Provider\MonologServiceProvider(), + array( + 'monolog.logfile' => api_get_path(SYS_ARCHIVE_PATH).'chamilo_development.log', + 'monolog.name' => 'chamilo', + ) + ); +} /* //Monolog examples @@ -239,7 +241,6 @@ if (isset($_configuration['main_database'])) { ) ); - //Setting Doctrine2 extensions $timestampableListener = new \Gedmo\Timestampable\TimestampableListener(); @@ -317,20 +318,24 @@ $app->error( /* use Symfony\Component\HttpKernel\Debug\ErrorHandler; ErrorHandler::register(); - */ +*/ use Symfony\Component\HttpFoundation\RedirectResponse; //Filters $app->before( function () use ($app) { - //Check the PHP version - if (api_check_php_version() == false) { - $app->abort(500, "Incorrect PHP version"); //error 1 - } if (!file_exists($app['configuration_file'])) { return new RedirectResponse(api_get_path(WEB_CODE_PATH).'install'); } + + //Check the PHP version + if (api_check_php_version() == false) { + $app->abort(500, "Incorrect PHP version"); + } + if (!is_writable(api_get_path(SYS_ARCHIVE_PATH))) { + $app->abort(500, "archive folder must be writeable"); + } //$app['request']->getSession()->start(); } ); @@ -345,14 +350,14 @@ $app->finish( //@todo will be removed before a stable release $mtime = microtime(); $mtime = explode(" ", $mtime); - $mtime = $mtime[1] + $mtime[0]; + $mtime = $mtime[1] + $mtime[0]; /* $message = "Page loaded in:".($mtime - START); $app['monolog']->addInfo($message); $message = "memory_get_usage: ".format_file_size(memory_get_usage(true)); $app['monolog']->addInfo($message); $message = "memory_get_peak_usage: ".format_file_size(memory_get_peak_usage(true)); - $app['monolog']->addInfo($message); + $app['monolog']->addInfo($message);*/ } ); @@ -392,9 +397,10 @@ if (!($conn_return = @Database::connect( //$app->abort(500, "Database is unavailable"); //error 3 } +/* if (!$_configuration['db_host']) { //$app->abort(500, "Database is unavailable"); //error 3 -} +}*/ /* RETRIEVING ALL THE CHAMILO CONFIG SETTINGS FOR MULTIPLE URLs FEATURE*/ @@ -418,7 +424,11 @@ if (!empty($_configuration['multiple_access_urls'])) { // 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)) { +if (isset($_configuration['main_database']) && !Database::select_db( + $_configuration['main_database'], + $database_connection +) +) { //$app->abort(500, "Database is unavailable"); //error 3 } @@ -459,19 +469,21 @@ Database::query("SET NAMES 'utf8';"); //@todo user silex session provider instead of a custom class Chamilo::session()->start($already_installed); -$settings_refresh_info = api_get_settings_params_simple(array('variable = ?' => 'settings_latest_update')); -$settings_latest_update = $settings_refresh_info ? $settings_refresh_info['selected_value'] : null; +if ($already_installed) { + $settings_refresh_info = api_get_settings_params_simple(array('variable = ?' => 'settings_latest_update')); + $settings_latest_update = $settings_refresh_info ? $settings_refresh_info['selected_value'] : null; -$_setting = isset($_SESSION['_setting']) ? $_SESSION['_setting'] : null; -$_plugins = isset($_SESSION['_plugins']) ? $_SESSION['_plugins'] : null; + $_setting = isset($_SESSION['_setting']) ? $_SESSION['_setting'] : null; + $_plugins = isset($_SESSION['_plugins']) ? $_SESSION['_plugins'] : null; -if (!isset($_setting)) { - api_set_settings_and_plugins(); -} else { - if (isset($_setting['settings_latest_update']) && $_setting['settings_latest_update'] != $settings_latest_update) { + if (!isset($_setting)) { api_set_settings_and_plugins(); - $_setting = isset($_SESSION['_setting']) ? $_SESSION['_setting'] : null; - $_plugins = isset($_SESSION['_plugins']) ? $_SESSION['_plugins'] : null; + } else { + if (isset($_setting['settings_latest_update']) && $_setting['settings_latest_update'] != $settings_latest_update) { + api_set_settings_and_plugins(); + $_setting = isset($_SESSION['_setting']) ? $_SESSION['_setting'] : null; + $_plugins = isset($_SESSION['_plugins']) ? $_SESSION['_plugins'] : null; + } } } @@ -505,10 +517,10 @@ $app->register( new Silex\Provider\SwiftmailerServiceProvider(), array( 'swiftmailer.options' => array( - 'host' => $platform_email['SMTP_HOST'], - 'port' => $platform_email['SMTP_PORT'], - 'username' => $platform_email['SMTP_USER'], - 'password' => $platform_email['SMTP_PASS'], + 'host' => isset($platform_email['SMTP_HOST']) ? $platform_email['SMTP_HOST'] : null, + 'port' => isset($platform_email['SMTP_PORT']) ? $platform_email['SMTP_PORT'] : null, + 'username' => isset($platform_email['SMTP_USER']) ? $platform_email['SMTP_USER'] : null, + 'password' => isset($platform_email['SMTP_PASS']) ? $platform_email['SMTP_PASS'] : null, 'encryption' => null, 'auth_mode' => null ) diff --git a/main/inc/lib/chamilo_session.class.php b/main/inc/lib/chamilo_session.class.php index 72abc8e5ae..b1cce16f8b 100644 --- a/main/inc/lib/chamilo_session.class.php +++ b/main/inc/lib/chamilo_session.class.php @@ -2,16 +2,16 @@ /** * Chamilo session. - * + * * Usage: - * - * + * + * * use ChamiloSession as Session; - * + * * Session::read('name'); - * + * * Or - * + * * Chamilo::session()->... * session()->... * @@ -25,7 +25,7 @@ class ChamiloSession extends System\Session /** * - * @return ChamiloSession + * @return ChamiloSession */ static function instance() { @@ -33,13 +33,15 @@ class ChamiloSession extends System\Session if (empty($result)) { $result = new ChamiloSession(); } + return $result; } static function session_lifetime() { global $_configuration; - return $_configuration['session_lifetime']; + + return isset($_configuration['session_lifetime']) ? $_configuration['session_lifetime'] : 3600; } static function session_stored_in_db() @@ -74,11 +76,18 @@ class ChamiloSession extends System\Session if (self::session_stored_in_db() && function_exists('session_set_save_handler')) { $handler = new SessionHandler(); - @session_set_save_handler(array(& $handler, 'open'), array(& $handler, 'close'), array(& $handler, 'read'), array(& $handler, 'write'), array(& $handler, 'destroy'), array(& $handler, 'garbage')); + @session_set_save_handler( + array(& $handler, 'open'), + array(& $handler, 'close'), + array(& $handler, 'read'), + array(& $handler, 'write'), + array(& $handler, 'destroy'), + array(& $handler, 'garbage') + ); } /* - * 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 @@ -88,12 +97,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 identifiers. @@ -107,8 +116,10 @@ class ChamiloSession extends System\Session if ($already_installed) { if (!isset($session['checkChamiloURL'])) { $session['checkChamiloURL'] = api_get_path(WEB_PATH); - } else if ($session['checkChamiloURL'] != api_get_path(WEB_PATH)) { - self::clear(); + } else { + if ($session['checkChamiloURL'] != api_get_path(WEB_PATH)) { + self::clear(); + } } } @@ -119,7 +130,7 @@ class ChamiloSession extends System\Session /** * Session start time: that is the last time the user accesseed the application. - * + * * @return int timestamp */ function start_time() @@ -129,20 +140,21 @@ class ChamiloSession extends System\Session /** * Session end time: when the session expires. - * + * * @return int timestamp */ function end_time() { $start_time = $this->start_time(); $lifetime = self::session_lifetime(); + return $start_time + $lifetime; } /** * Returns true if the session is stalled. I.e. if session end time is * greater than now. Returns false otherwise. - * + * * @return bool */ function is_stalled() @@ -161,7 +173,7 @@ class ChamiloSession extends System\Session /** * The current (logged in) user. - * + * * @return CurrentUser */ public function user() @@ -170,9 +182,10 @@ class ChamiloSession extends System\Session if (empty($result)) { $result = CurrentUser::instance(); } + return $result; } - + /** * * @return CurrentCourse @@ -183,14 +196,14 @@ class ChamiloSession extends System\Session if (empty($result)) { $result = CurrentCourse::instance(); } + return $result; } - - + /** * The current group for the current (logged in) user. - * + * * @return int */ public function group_id() diff --git a/main/inc/lib/database.lib.php b/main/inc/lib/database.lib.php index 70680f159d..e4e612a0f6 100644 --- a/main/inc/lib/database.lib.php +++ b/main/inc/lib/database.lib.php @@ -11,14 +11,15 @@ * If trying to replicate the database layer, don't forget to look for "sql" * named functions in main_api.lib.php * - * @package chamilo.library + * @package chamilo.library */ /** * Database class definition * @package chamilo.database */ -class Database { +class Database +{ /* Variable use only in the installation process to log errors. See the Database::query function */ static $log_queries = false; @@ -30,87 +31,103 @@ class Database { */ /** - * Returns the name of the main database. + * Returns the name of the main database. */ - public static function get_main_database() { + public static function get_main_database() + { global $_configuration; - return $_configuration['main_database']; + + return isset($_configuration['main_database']) ? $_configuration['main_database'] : null; } /** - * Returns the name of the statistics database. - * @todo use main_database + * Returns the name of the statistics database. + * @todo use main_database */ - public static function get_statistic_database() { + public static function get_statistic_database() + { global $_configuration; - return $_configuration['main_database']; + + return isset($_configuration['main_database']) ? $_configuration['main_database'] : null; } /** - * Returns the name of the database where all the personal stuff of the user is stored - * @todo use main_database + * Returns the name of the database where all the personal stuff of the user is stored + * @todo use main_database */ - public static function get_user_personal_database() { + public static function get_user_personal_database() + { global $_configuration; + return $_configuration['main_database']; } /** - * Returns the name of the current course database. - * @return mixed Glued database name of false if undefined + * Returns the name of the current course database. + * @return mixed Glued database name of false if undefined */ - public static function get_current_course_database() { + public static function get_current_course_database() + { $course_info = api_get_course_info(); if (empty($course_info['dbName'])) { return false; } + return $course_info['dbName']; } /** - * Returns the glued name of the current course database. - * @return mixed Glued database name of false if undefined + * 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() { + 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. + * 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() { + 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. + * 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. + * TIP: This can be convenient if you have multiple system installations + * on the same physical server. */ - public static function get_database_name_prefix() { + 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. + * 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() { + public static function get_course_table_prefix() + { global $_configuration; + return $_configuration['table_prefix']; } @@ -139,14 +156,15 @@ 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($short_table_name) + { return self::format_table_name( - self::get_main_database(), - $short_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. @@ -157,7 +175,8 @@ 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($short_table_name, $extra = null) + { //forces fatal errors so we can debug more easily if (!empty($extra)) { var_dump($extra); @@ -165,7 +184,8 @@ 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); //return self::format_glued_course_table_name(self::fix_database_parameter($database_name), $short_table_name); } @@ -177,7 +197,8 @@ class Database { * * @param string $short_table_name, the name of the table */ - public static function get_statistic_table($short_table_name) { + public static function get_statistic_table($short_table_name) + { return self::format_table_name(self::get_statistic_database(), $short_table_name); } @@ -189,11 +210,13 @@ class Database { * * @param string $short_table_name, the name of the table */ - public static function get_user_personal_table($short_table_name) { + public static function get_user_personal_table($short_table_name) + { return self::format_table_name(self::get_user_personal_database(), $short_table_name); } - public static function get_course_chat_connected_table($database_name = '') { + public static function get_course_chat_connected_table($database_name = '') + { return self::format_glued_course_table_name(self::fix_database_parameter($database_name), TABLE_CHAT_CONNECTED); } @@ -203,25 +226,30 @@ class Database { */ /** - * @return a list (array) of all courses. - * @todo shouldn't this be in the course.lib.php script? + * @return a list (array) of all courses. + * @todo shouldn't this be in the course.lib.php script? */ - public static function get_course_list() { + public static function get_course_list() + { $table = self::get_main_table(TABLE_MAIN_COURSE); + return self::store_result(self::query("SELECT *, id as real_id FROM $table")); } /** - * Returns an array with all database fields for the specified course. + * Returns an array with all database fields for the specified course. * - * @param string The real (system) course code (main course table ID) - * @todo shouldn't this be in the course.lib.php script? + * @param string The real (system) course code (main course table ID) + * @todo shouldn't this be in the course.lib.php script? */ - public static function get_course_info($course_code) { + public static function get_course_info($course_code) + { $course_code = self::escape_string($course_code); $table = self::get_main_table(TABLE_MAIN_COURSE); $result = self::generate_abstract_course_field_names( - self::fetch_array(self::query("SELECT *, id as real_id FROM $table WHERE code = '$course_code'"))); + self::fetch_array(self::query("SELECT *, id as real_id FROM $table WHERE code = '$course_code'")) + ); + return $result === false ? array('db_name' => '') : $result; } @@ -235,14 +263,17 @@ class Database { * @desc find all the information about a specified user. Without parameter this is the current user. * @todo shouldn't this be in the user.lib.php script? */ - public static function get_user_info_from_id($user_id = '') { + public static function get_user_info_from_id($user_id = '') + { if (empty($user_id)) { return $GLOBALS['_user']; } $table = self::get_main_table(TABLE_MAIN_USER); $user_id = self::escape_string($user_id); + return self::generate_abstract_user_field_names( - self::fetch_array(self::query("SELECT * FROM $table WHERE user_id = '$user_id'"))); + self::fetch_array(self::query("SELECT * FROM $table WHERE user_id = '$user_id'")) + ); } /** @@ -251,41 +282,50 @@ class Database { * @return string Course code * @todo move this function in a gradebook-related library */ - public static function get_course_by_category($category_id) { + public static function get_course_by_category($category_id) + { $category_id = intval($category_id); - $info = self::fetch_array(self::query('SELECT course_code FROM '.self::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).' WHERE id='.$category_id), 'ASSOC'); + $info = self::fetch_array( + self::query( + 'SELECT course_code FROM '.self::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY).' WHERE id='.$category_id + ), + 'ASSOC' + ); + return $info ? $info['course_code'] : false; } /** - * This method creates an abstraction layer between database field names - * and field names expected in code. + * This method creates an abstraction layer between database field names + * and field names expected in code. * - * This approach helps when changing database names. - * It's also useful now to get rid of the 'franglais'. + * This approach helps when changing database names. + * It's also useful now to get rid of the 'franglais'. * - * @todo add more array entries to abstract course info from field names - * @author Roan Embrechts + * @todo add more array entries to abstract course info from field names + * @author Roan Embrechts * - * @todo What's the use of this method. I think this is better removed. - * There should be consistency in the variable names and the + * @todo What's the use of this method. I think this is better removed. + * There should be consistency in the variable names and the * use throughout the scripts - * for the database name we should consistently use or db_name + * for the database name we should consistently use or db_name * or database (db_name probably being the better one) */ - public static function generate_abstract_course_field_names($result_array) { + public static function generate_abstract_course_field_names($result_array) + { $visual_code = isset($result_array['visual_code']) ? $result_array['visual_code'] : null; - $code = isset($result_array['code']) ? $result_array['code'] : null; - $title = isset($result_array['title']) ? $result_array['title'] : null; - $db_name = isset($result_array['db_name']) ? $result_array['db_name'] : null; + $code = isset($result_array['code']) ? $result_array['code'] : null; + $title = isset($result_array['title']) ? $result_array['title'] : null; + $db_name = isset($result_array['db_name']) ? $result_array['db_name'] : null; $category_code = isset($result_array['category_code']) ? $result_array['category_code'] : null; $result_array['official_code'] = $visual_code; - $result_array['visual_code'] = $visual_code; - $result_array['real_code'] = $code; - $result_array['system_code'] = $code; - $result_array['title'] = $title; - $result_array['database'] = $db_name; - $result_array['faculty'] = $category_code; + $result_array['visual_code'] = $visual_code; + $result_array['real_code'] = $code; + $result_array['system_code'] = $code; + $result_array['title'] = $title; + $result_array['database'] = $db_name; + $result_array['faculty'] = $category_code; + //$result_array['directory'] = $result_array['directory']; /* still to do: (info taken from local.inc.php) @@ -307,27 +347,30 @@ class Database { $_course['visibility' ] = (bool) ($cData['visibility'] == 2 || $cData['visibility'] == 3); $_course['registrationAllowed'] = (bool) ($cData['visibility'] == 1 || $cData['visibility'] == 2); */ + return $result_array; } /** - * This method creates an abstraction layer between database field names - * and field names expected in code. + * This method creates an abstraction layer between database field names + * and field names expected in code. * - * This helps when changing database names. - * It's also useful now to get rid of the 'franglais'. + * This helps when changing database names. + * It's also useful now to get rid of the 'franglais'. * - * @todo add more array entries to abstract user info from field names - * @author Roan Embrechts - * @author Patrick Cool + * @todo add more array entries to abstract user info from field names + * @author Roan Embrechts + * @author Patrick Cool * - * @todo what's the use of this function. I think this is better removed. - * There should be consistency in the variable names and the use throughout the scripts + * @todo what's the use of this function. I think this is better removed. + * There should be consistency in the variable names and the use throughout the scripts */ - public static function generate_abstract_user_field_names($result_array) { - $result_array['firstName'] = $result_array['firstname']; - $result_array['lastName'] = $result_array['lastname']; - $result_array['mail'] = $result_array['email']; + public static function generate_abstract_user_field_names($result_array) + { + $result_array['firstName'] = $result_array['firstname']; + $result_array['lastName'] = $result_array['lastname']; + $result_array['mail'] = $result_array['email']; + #$result_array['picture_uri'] = $result_array['picture_uri']; #$result_array ['user_id'] = $result_array['user_id']; return $result_array; @@ -338,8 +381,9 @@ class Database { * @param string $table The table of which the rows should be counted * @return int The number of rows in the given table. */ - public static function count_rows($table) { - $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table")); // + public static function count_rows($table) + { + $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table")); // return $obj->n; } @@ -349,26 +393,28 @@ 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 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) { + public static function affected_rows($connection = null) + { 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. + * @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) { + 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. + * @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']. @@ -376,7 +422,8 @@ class Database { * @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()) { + public static function connect($parameters = array()) + { // A MySQL-specific implementation. if (!isset($parameters['server'])) { $parameters['server'] = @ini_get('mysql.default_host'); @@ -404,6 +451,7 @@ class Database { $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); @@ -411,32 +459,35 @@ class Database { /** * Returns error number from the last operation done on the database server. - * @param resource $connection (optional) The database server connection, + * @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) { + 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(). + * @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) { + public static function error($connection = null) + { return self::use_default_connection($connection) ? mysql_error() : mysql_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 + * @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) { + public static function escape_string($string, $connection = null) + { return get_magic_quotes_gpc() ? (self::use_default_connection($connection) ? mysql_real_escape_string(stripslashes($string)) @@ -448,93 +499,122 @@ class Database { /** * 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 + * @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($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)); + public static function fetch_array($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)); } /** * 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. + * @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) { + public static function fetch_assoc($result) + { 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 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) { - 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) + { + 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 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) { + public static function fetch_row($result) + { 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. + * @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) { + public static function free_result($result) + { return mysql_free_result($result); } /** * Returns the database client library version. - * @return strung Returns a string that represents the client library version. + * @return strung Returns a string that represents the client library version. */ - public static function get_client_info() { + 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. + * @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) { + 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); + $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 a list of the fields that a given table contains. The list may contain all of the available field names or filtered field names by using a pattern. * By using a special option, this method is able to return an indexed list of fields' properties, where field names are keys. - * @param string $table This is the examined table. - * @param string $pattern (optional) A pattern for filtering field names as if it was needed for the SQL's LIKE clause, for example 'column_%'. - * @param string $database (optional) The name of the targeted database. If it is omited, the current database is assumed, see Database::select_db(). - * @param bool $including_properties (optional) When this option is true, the returned result has the followong format: - * array(field_name_1 => array(0 => property_1, 1 => property_2, ...), fieald_name_2 => array(0 => property_1, ...), ...) - * @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 field names. + * @param string $table This is the examined table. + * @param string $pattern (optional) A pattern for filtering field names as if it was needed for the SQL's LIKE clause, for example 'column_%'. + * @param string $database (optional) The name of the targeted database. If it is omited, the current database is assumed, see Database::select_db(). + * @param bool $including_properties (optional) When this option is true, the returned result has the followong format: + * array(field_name_1 => array(0 => property_1, 1 => property_2, ...), fieald_name_2 => array(0 => property_1, ...), ...) + * @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 field names. */ - public static function get_fields($table, $pattern = '', $database = '', $including_properties = false, $connection = null) { + public static function get_fields( + $table, + $pattern = '', + $database = '', + $including_properties = false, + $connection = null + ) { $result = array(); $query = "SHOW COLUMNS FROM `".self::escape_string($table, $connection)."`"; if (!empty($database)) { @@ -555,45 +635,50 @@ class Database { $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. + * @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) { + 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. + * @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) { + 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. + * @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) { + 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. + * @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) { + public static function get_tables($database = '', $pattern = '', $connection = null) + { $result = array(); $query = "SHOW TABLES"; if (!empty($database)) { @@ -606,39 +691,46 @@ class Database { 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 + * @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) { + public static function insert_id($connection = null) + { 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 + * @param resource The result + * @return integer The number of rows contained in this result * @author Yannick Warnier **/ - public static function num_rows($result) { + public static function num_rows($result) + { 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 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($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($resource, $row, $field = '') + { + return self::num_rows($resource) > 0 ? (!empty($field) ? mysql_result($resource, $row, $field) : mysql_result( + $resource, + $row + )) : null; } /** @@ -646,14 +738,14 @@ class Database { * 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 resource The returned result from the query + * @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 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); @@ -665,7 +757,8 @@ class Database { * Database::query($query, $connection, __FILE__, __LINE__); * $result = Database::query($query, $connection, __FILE__, __LINE__); */ - public static function query($query, $connection = null, $file = null, $line = null) { + public static function query($query, $connection = null, $file = null, $line = null) + { $use_default_connection = self::use_default_connection($connection); if ($use_default_connection) { // Let us do parameter shifting, thus the method would be similar @@ -677,9 +770,9 @@ class Database { //@todo remove this before the stable release //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 ( + 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 && @@ -704,20 +797,20 @@ class Database { strpos($query, 'chamilo_electric_blue') === false && strpos($query, 'wcag_anysurfer_public_pages') === 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 - ) { + 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

'; @@ -725,7 +818,7 @@ class Database { echo $message; echo '
'; //error_log($message); - } + } } if (!($result = $use_default_connection ? @mysql_query($query) : @mysql_query($query, $connection))) { @@ -751,23 +844,23 @@ class Database { $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) . '
'; + $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; + $info .= 'FUNCTION :
'.$function; } } else { if (!empty($class) && !empty($function)) { - $info .= 'CLASS :
' . $class . '
'; - $info .= 'METHOD :
' . $function; + $info .= 'CLASS :
'.$class.'
'; + $info .= 'METHOD :
'.$function; } } $info .= '
'; @@ -781,35 +874,40 @@ class Database { error_log('error #'.self::errno($connection)); error_log('error: '.self::error($connection)); - $info = 'FILE: ' .(empty($file) ? ' unknown ' : $file); + $info = 'FILE: '.(empty($file) ? ' unknown ' : $file); $info .= ' +'.(empty($line) ? ' unknown ' : $line); error_log($info); if (empty($type)) { if (!empty($function)) { - $info = 'FUNCTION: ' . $function; + $info = 'FUNCTION: '.$function; error_log($info); } } else { if (!empty($class) && !empty($function)) { - $info = 'CLASS: ' . $class.' METHOD: '.$function; + $info = 'CLASS: '.$class.' 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. + * @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); + 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 + ); } /** @@ -820,13 +918,15 @@ 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($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; } @@ -836,20 +936,25 @@ class Database { /** * 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. + * @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) { + 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) { + if (self::num_rows( + self::query("SHOW CHARACTER SET WHERE Charset = '".self::escape_string($db_encoding)."';") + ) > 0 + ) { $supported[$encoding] = true; } } } + return $supported[$encoding]; } @@ -857,12 +962,13 @@ class Database { * 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. + * @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) { + public static function make_charset_clause($encoding = null, $language = null) + { if (empty($encoding)) { $encoding = api_get_system_encoding(); } @@ -878,17 +984,19 @@ class Database { $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. + * @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) { + public static function to_db_encoding($encoding) + { static $result = array(); if (!isset($result[$encoding])) { $result[$encoding] = null; @@ -900,17 +1008,19 @@ class Database { } } } + 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. + * @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) { + public static function from_db_encoding($db_encoding) + { static $result = array(); if (!isset($result[$db_encoding])) { $result[$db_encoding] = null; @@ -922,17 +1032,19 @@ class Database { } } } + 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. + * @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) { + public static function to_db_collation($encoding, $language = null) + { static $result = array(); if (!isset($result[$encoding][$language])) { $result[$encoding][$language] = null; @@ -956,6 +1068,7 @@ class Database { } } } + return $result[$encoding][$language]; } @@ -966,47 +1079,55 @@ class Database { */ /** - * Glues a course database. - * glue format from local.inc.php. + * Glues a course database. + * glue format from local.inc.php. */ - private static function glue_course_database_name($database_name) { + 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 + * @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. + * @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) { + 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`.` + * 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) { + 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 + * 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) { + private static function format_table_name($database, $table) + { global $_configuration; + $glue = isset($_configuration['db_glue']) ? $_configuration['db_glue'] : null; /*if ($_configuration['single_database']) { $table_name = '`'.$database.'`.`'.$table.'`'; } else {*/ - $table_name = '`'.$database.$_configuration['db_glue'].$table.'`'; + $table_name = '`'.$database.$glue.$table.'`'; + //} return $table_name; } @@ -1016,22 +1137,28 @@ class Database { * 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. + * @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) { + 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. + * @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()); + private static function remove_XSS(& $var) + { + return class_exists('Security') ? Security::remove_XSS($var) : @htmlspecialchars( + $var, + ENT_QUOTES, + api_get_system_encoding() + ); } /** @@ -1039,35 +1166,37 @@ class Database { * conventional and MuSQL-specific encoding identificators. * @author Ivan Tcholakov */ - private static function & get_db_encoding_map() { + 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', + '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; } @@ -1075,29 +1204,38 @@ class Database { * A helper language id translation table for choosing some collations. * @author Ivan Tcholakov */ - private static function & get_db_collation_map() { + 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. + * @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) { + 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'); + $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'; @@ -1107,6 +1245,7 @@ class Database { return $collation; } } + return null; } @@ -1118,7 +1257,8 @@ class Database { * Experimental useful database insert * @todo lot of stuff to do here */ - public static function insert($table_name, $attributes, $show_query = false) { + public static function insert($table_name, $attributes, $show_query = false) + { if (empty($attributes) || empty($table_name)) { return false; } @@ -1126,21 +1266,25 @@ class Database { 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 + $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).')'; + $sql = 'INSERT INTO '.$table_name.' ('.implode(', ', $params).') VALUES ('.implode(', ', $values).')'; $result = self::query($sql); //error_log($sql); if ($show_query) { - //var_dump($sql); + //var_dump($sql); error_log($sql); } if (!$result) { error_log("Error in query: $sql"); } + return self::get_last_insert_id(); } + return false; } @@ -1151,8 +1295,9 @@ class Database { * @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') { + */ + 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 ... @@ -1183,6 +1328,7 @@ class Database { } else { $array = self::fetch_array($result, $option); } + return $array; } @@ -1191,8 +1337,9 @@ class Database { * @todo known issues, it doesn't work when using LIKE conditions example: array('where'=>array('course_code LIKE "?%"')) * @param array * @todo lot of stuff to do here - */ - static function parse_conditions($conditions) { + */ + static function parse_conditions($conditions) + { if (empty($conditions)) { return ''; } @@ -1207,9 +1354,9 @@ class Database { foreach ($condition_data as $condition => $value_array) { if (is_array($value_array)) { $clean_values = array(); - foreach($value_array as $item) { + foreach ($value_array as $item) { $item = Database::escape_string($item); - $clean_values[]= $item; + $clean_values[] = $item; } } else { $value_array = Database::escape_string($value_array); @@ -1217,24 +1364,24 @@ class Database { } if (!empty($condition) && $clean_values != '') { - $condition = str_replace('%',"'@percentage@'", $condition); //replace "%" - $condition = str_replace("'?'","%s", $condition); - $condition = str_replace("?","%s", $condition); + $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); + $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 "%" + $condition = str_replace('@percentage@', '%', $condition); //replace "%" $where_return .= $condition; } } if (!empty($where_return)) { - $return_value = " WHERE $where_return" ; + $return_value = " WHERE $where_return"; } break; case 'order': @@ -1246,7 +1393,7 @@ class Database { $new_order_array = explode(',', $order_array); $temp_value = array(); - foreach($new_order_array as $element) { + foreach ($new_order_array as $element) { $element = explode(' ', $element); $element = array_filter($element); $element = array_values($element); @@ -1257,10 +1404,10 @@ class Database { if (in_array($element[1], array('desc', 'asc'))) { $order = $element[1]; } - $temp_value[]= $element[0].' '.$order.' '; + $temp_value[] = $element[0].' '.$order.' '; } else { //by default DESC - $temp_value[]= $element[0].' DESC '; + $temp_value[] = $element[0].' DESC '; } } if (!empty($temp_value)) { @@ -1276,31 +1423,38 @@ class Database { if (!empty($limit_array)) { if (count($limit_array) > 1) { $return_value .= ' LIMIT '.intval($limit_array[0]).' , '.intval($limit_array[1]); - } else { + } 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)); + 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, $show_query = false) { + public static function delete($table_name, $where_conditions, $show_query = false) + { $result = false; $where_return = self::parse_where_conditions($where_conditions); - $sql = "DELETE FROM $table_name $where_return "; - if ($show_query) { echo $sql; echo '
'; } + $sql = "DELETE FROM $table_name $where_return "; + if ($show_query) { + echo $sql; + echo '
'; + } $result = self::query($sql); $affected_rows = self::affected_rows(); + //@todo should return affected_rows for return $affected_rows; } @@ -1308,56 +1462,63 @@ class Database { /** * Experimental useful database update - * @param string table name use Database::get_main_table - * @param array array with values to updates, keys are the fields in the database: Example: $params['name'] = 'Julio'; $params['lastname'] = 'Montoya'; - * @param array where conditions i.e array('id = ?' =>'4') + * @param string table name use Database::get_main_table + * @param array array with values to updates, keys are the fields in the database: Example: $params['name'] = 'Julio'; $params['lastname'] = 'Montoya'; + * @param array where conditions i.e array('id = ?' =>'4') * @todo lot of stuff to do here */ - public static function update($table_name, $attributes, $where_conditions = array(), $show_query = false) { + 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)) + foreach ($attributes as $key => $value) { - $value = self::escape_string($value); + if (!is_array($value)) { + $value = self::escape_string($value); + } $update_sql .= "$key = '$value' "; if ($count < count($attributes)) { - $update_sql.=', '; + $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); } + $sql = "UPDATE $table_name SET $update_sql $where_return "; + if ($show_query) { + var_dump($sql); + } $result = self::query($sql); $affected_rows = self::affected_rows(); + return $affected_rows; } } + return false; } - /* - DEPRECATED METHODS - */ + /* + DEPRECATED METHODS + */ /** * @deprecated Use api_get_language_isocode($language) instead. */ - public static function get_language_isocode($language) { + 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() { + public static function get_last_insert_id() + { return mysql_insert_id(); } } diff --git a/main/install/index.php b/main/install/index.php index d98fb1be52..eda4901364 100644 --- a/main/install/index.php +++ b/main/install/index.php @@ -27,6 +27,8 @@ define('MAX_FORM_FIELD_LENGTH', 80); require_once '../inc/global.inc.php'; +require_once __DIR__.'../../../vendor/autoload.php'; + require_once 'install.lib.php'; require_once 'i_database.class.php'; @@ -130,7 +132,6 @@ if (!empty($_POST['old_version'])) { require_once __DIR__.'/version.php'; - // A protection measure for already installed systems. if (is_already_installed_system()) { diff --git a/main/install/install.lib.php b/main/install/install.lib.php index 4f3ba0e02c..9b10bb1885 100755 --- a/main/install/install.lib.php +++ b/main/install/install.lib.php @@ -981,7 +981,8 @@ function get_sql_file_contents($file, $section, $print_errors = true) * @param string $title * @return id if inserted document */ -function FileManager::add_document_180($_course, $path, $filetype, $filesize, $title, $comment = null){ +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`) @@ -1029,17 +1030,6 @@ function display_language_selection_box($name = 'language_list', $default_langua // Reading language list. $language_list = get_language_folder_list(); - /* - // Reduction of the number of languages shown. Enable this fragment of code for customization purposes. - // Modify the language list according to your preference. Don't exclude the 'english' item. - $language_to_display = array('asturian', 'bulgarian', 'english', 'italian', 'french', 'slovenian', 'slovenian_unicode', 'spanish'); - foreach ($language_list as $key => & $value) { - if (!in_array($key, $language_to_display)) { - unset($language_list[$key]); - } - } - */ - // Sanity checks due to the possibility for customizations. if (!is_array($language_list) || empty($language_list)) { $language_list = array('english' => 'English'); diff --git a/resources/config/prod.php b/resources/config/prod.php index 5f25f1d3c6..27056137b0 100644 --- a/resources/config/prod.php +++ b/resources/config/prod.php @@ -70,9 +70,9 @@ if (!is_dir($app['assetic.path_to_web'].'/js')) { * */ if (!is_dir($app['db.orm.proxies_dir'])) { - mkdir($app['db.orm.proxies_dir'], api_get_permissions_for_new_directories()); + @mkdir($app['db.orm.proxies_dir'], api_get_permissions_for_new_directories()); } if (!is_dir($app['cache.path'].'twig')) { - mkdir($app['cache.path'].'twig', api_get_permissions_for_new_directories()); + @mkdir($app['cache.path'].'twig', api_get_permissions_for_new_directories()); } \ No newline at end of file