Browse Source

Merge with 1.10

Julio Montoya 11 năm trước cách đây
mục cha
commit
06b8f7e9e8
99 tập tin đã thay đổi với 1091 bổ sung11460 xóa
  1. 0 4
      .gitignore
  2. 51 2
      README.md
  3. 0 46
      config/configuration.dist.yml.php
  4. 5 0
      config/routing.yml
  5. 3 2
      main/admin/access_url_edit.php
  6. 8 22
      main/admin/access_url_edit_users_to_url.php
  7. 3 26
      main/admin/user_add.php
  8. 39 80
      main/admin/user_edit.php
  9. 12 119
      main/admin/user_list.php
  10. 50 43
      main/auth/inscription.php
  11. 11 3
      main/cron/import_csv.php
  12. 15 24
      main/inc/Entity/Repository/UserRepository.php
  13. 18 16
      main/inc/Entity/User.php
  14. 6 16
      main/inc/global.inc.php
  15. 2 1
      main/inc/lib/api.lib.php
  16. 0 8
      main/inc/lib/database.constants.inc.php
  17. 34 54
      main/inc/lib/events.lib.inc.php
  18. 5 0
      main/inc/lib/sessionmanager.lib.php
  19. 0 593
      main/inc/lib/stats.lib.inc.php
  20. 2 2
      main/inc/lib/urlmanager.lib.php
  21. 36 7
      main/inc/lib/usermanager.lib.php
  22. 0 1
      main/inc/routes.php
  23. 16 36
      main/inc/services.php
  24. 0 264
      main/install/country_data.csv
  25. 2 5
      main/install/index.php
  26. 0 66
      main/install/install.lib.php
  27. 0 135
      main/install/install_db.inc.php
  28. 0 36
      main/install/install_files.inc.php
  29. 0 65
      main/install/migrate-db-1.6.x-1.8.0-post.sql
  30. 0 315
      main/install/migrate-db-1.6.x-1.8.0-pre.sql
  31. 0 78
      main/install/migrate-db-1.8.0-1.8.2-pre.sql
  32. 0 25
      main/install/migrate-db-1.8.2-1.8.3-pre.sql
  33. 0 37
      main/install/migrate-db-1.8.3-1.8.4-pre.sql
  34. 0 159
      main/install/migrate-db-1.8.4-1.8.5-pre.sql
  35. 0 231
      main/install/migrate-db-1.8.5-1.8.6-pre.sql
  36. 0 65
      main/install/migrate-db-1.8.6-1.8.6.1-pre.sql
  37. 0 21
      main/install/migrate-db-1.8.6.1-1.8.6.2-post.sql
  38. 0 149
      main/install/migrate-db-1.8.6.1-1.8.6.2-pre.sql
  39. 0 38
      main/install/migrate-db-1.8.6.2-1.8.7-post.sql
  40. 0 154
      main/install/migrate-db-1.8.6.2-1.8.7-pre.sql
  41. 0 231
      main/install/migrate-db-1.8.7-1.8.8-pre.sql
  42. 0 344
      main/install/migrate-db-1.8.8-1.9.0-pre.sql
  43. 0 140
      main/install/migrate-db-1.8.8-1.9.0-pre.sql.optimized
  44. 0 71
      main/install/update-configuration.inc.php
  45. 0 536
      main/install/update-db-1.6.x-1.8.0.inc.php
  46. 0 211
      main/install/update-db-1.8.0-1.8.2.inc.php
  47. 0 210
      main/install/update-db-1.8.2-1.8.3.inc.php
  48. 0 263
      main/install/update-db-1.8.3-1.8.4.inc.php
  49. 0 281
      main/install/update-db-1.8.4-1.8.5.inc.php
  50. 0 1147
      main/install/update-db-1.8.5-1.8.6.inc.php
  51. 0 263
      main/install/update-db-1.8.6-1.8.6.1.inc.php
  52. 0 347
      main/install/update-db-1.8.6.1-1.8.6.2.inc.php
  53. 0 567
      main/install/update-db-1.8.6.2-1.8.7.inc.php
  54. 0 407
      main/install/update-db-1.8.7-1.8.8.inc.php
  55. 0 680
      main/install/update-db-1.8.8-1.9.0.inc.php
  56. 0 383
      main/install/update-db-1.9.0-1.10.0.inc.php
  57. 0 1282
      main/install/update-db-scorm-1.6.x-1.8.0.inc.php
  58. 0 150
      main/install/update-files-1.6.x-1.8.0.inc.php
  59. 0 56
      main/install/update-files-1.8.3-1.8.4.inc.php
  60. 0 52
      main/install/update-files-1.8.4-1.8.5.inc.php
  61. 0 118
      main/install/update-files-1.8.5-1.8.6.inc.php
  62. 0 64
      main/install/update-files-1.8.6-1.8.6.1.inc.php
  63. 0 95
      main/install/update-files-1.8.6.1-1.8.6.2.inc.php
  64. 0 75
      main/install/update-files-1.8.6.2-1.8.7.inc.php
  65. 0 75
      main/install/update-files-1.8.7-1.8.8.inc.php
  66. 0 85
      main/install/update-files-1.8.8-1.9.0.inc.php
  67. 7 3
      main/newscorm/learnpath.class.php
  68. 0 12
      main/newscorm/learnpath_functions.inc.php
  69. 2 2
      main/newscorm/lp_view.php
  70. 0 2
      main/newscorm/resourcelinker.inc.php
  71. 36 45
      main/session/session_list.php
  72. 11 2
      main/template/default/admin/index.tpl
  73. 113 0
      main/template/default/admin/session_manager/role_index.tpl
  74. 6 5
      main/template/default/layout/main_header.tpl
  75. 7 0
      main/template/default/layout/page_body.tpl
  76. 8 8
      main/template/default/layout/show_header.tpl
  77. 1 0
      main/template/default/layout/topbar.tpl
  78. 129 0
      main/work/add_document.php
  79. 104 0
      main/work/add_user.php
  80. 20 15
      main/work/download.php
  81. 6 0
      main/work/downloadfolder.inc.php
  82. 4 3
      main/work/edit.php
  83. 16 15
      main/work/file.php
  84. 29 2
      main/work/upload.php
  85. 13 9
      main/work/view.php
  86. 160 30
      main/work/work.lib.php
  87. 12 52
      main/work/work.php
  88. 16 0
      main/work/work_list.php
  89. 10 2
      main/work/work_list_all.php
  90. 2 1
      main/work/work_list_others.php
  91. 7 5
      src/ChamiloLMS/Command/Template/AsseticDumpCommand.php
  92. 24 0
      src/ChamiloLMS/Component/Auth/LoginListener.php
  93. 13 5
      src/ChamiloLMS/Component/Auth/LoginSuccessHandler.php
  94. 15 3
      src/ChamiloLMS/Component/Auth/Role.php
  95. 0 1
      src/ChamiloLMS/Controller/Admin/AdminController.php
  96. 0 67
      src/ChamiloLMS/Controller/IndexController.php
  97. 0 4
      src/ChamiloLMS/Controller/LegacyController.php
  98. 0 84
      src/ChamiloLMS/Controller/UserPortalController.php
  99. 2 2
      src/ChamiloLMS/Resources/config/route_example.yml

+ 0 - 4
.gitignore

@@ -22,11 +22,7 @@ logs/*
 *.log
 
 # IDE settings
-
 .idea
-.idea/*
-.idea/dictionaries/*
-.idea/cssxfire.xml
 
 *.orig
 nbproject/*

+ 51 - 2
README.md

@@ -1,20 +1,69 @@
 Chamilo LMS
 =============
 
-A next generation Learning Content Management system focused on ease of use, collaboration and sharing.
+A next generation Learning Management system focused on ease of use, collaboration and sharing.
 See documentation/index.html for a complete overview of Chamilo.
 
+Versions differentiation
+------------------------
+
+Beware that the Chamilo Association hosts *two completely different applications*: Chamilo LMS (this software here) and Chamilo LCMS (a more experimental application focused on sharing learning objects, mostly, hosted on Bitbucket, not here).
+https://campus.chamilo.org, https://stable.chamilo.org and the vast majority of Chamilo installations around the world (98%) use Chamilo LMS.
+
+Inside this Chamilo LMS project itself, there are two main "branches":
+* Chamilo LMS 1.9.x offers a stable version of Chamilo that is made more stable with each new version
+* Chamilo LMS HEAD (the default if you download it from Github) is in active development and will soon spawn the new 1.10 version (or v10) of Chamilo LMS. It is NOT to be used in production right now.
+
+If you are in search of the latest patches to your production installation, you should choose 1.9.x. If you are adventurous and look forward to contribute to something that *mostly* works but is still under heavy development, you should stick with the default HEAD branch.
+
+Chamilo LMS v10 should be out around January 2014, so not too far away, and comes with an improved files structure and a lot of new dependencies/packages coming from Symfony and Composer. If you have time on your hands and are looking for long term contributions, that's where we'd like you to help.
+
 Installation
 ------------
 
 You need a working web server + PHP + MySQL setup.
-Refer to documentation/installation_guide.html for instructions.
+
+To install from Git (which means installing an unstable, development version of this application), do the following:
+
+* Create a directory where you will store the Chamilo LMS files (beware, the Git repo is about 600MB in size now)
+* Install git (if that's not already the case)
+* Clone the Chamilo LMS repo from Github:
+```
+git clone https://github.com/chamilo/chamilo-lms.git the-directory-you-created
+```
+
+Once you have downloaded it, you will need to follow the installation instructions. You can get the latest version inside the documentation/ folder of your recently-downloaded Chamilo, or you can see them online for the latest *stable* version at https://stable.chamilo.org/documentation/installation_guide.html
+
+Before you start the installation procedure, if you want to work on Chamilo LMS 1.9.x, you'll need to do this:
+```
+cd the-directory-you-created
+git checkout --track origin/1.9.x
+git config --global push.default current
+```
+
+This way, you'll stick to the 1.9.x branch only in this directory (your installation will be 1.9.x only), and when sending commits, they will automatically be sent to the 1.9.x branch.
+
+Finally, if you are really looking into contributing back to Chamilo, you should (really) create yourself a Github account and "fork this project". You would then download Chamilo from your own Github repository first, then send changes to your repository and finally (once you're sure they're matching our coding conventions), submit a "Pull request" to Chamilo. This is the cleanest, more time-saving way to do it!
 
 Reporting bugs
 --------------
 
 Please submit any bugs, feature requests and non-trivial patches to
 http://support.chamilo.org/
+Always make sure you look for the Chamilo LMS subproject when submittingbug reports, contributing, asking on the forum, IRC, etc.
+
+Contributing
+------------
+
+When contributing patches (which we always welcome, as long as you agree to do that under the GNU/GPLv3 license), please ensure you respect our coding conventions: https://support.chamilo.org/projects/1/wiki/Coding_conventions (mostly PSR-2 with a few additional rules and hints).
+
+Manual testing
+--------------
+
+You can always check the impact of your changes and confirm with other users on the following portals, which are automatically updated every 15 minutes:
+* https://stable.chamilo.org for versions 1.9.x
+* https://unstable.chamilo.org for development version (currently 1.10) - this one doesn't automatically apply database changes, so it is more likely to break often
+These are *NOT* production portals. Your content *WILL* be deleted once every now and then. It is completely public and anyone can enter and delete your content if they want to. DO NOT put important content there.
 
 Learn more
 ----------

+ 0 - 46
config/configuration.dist.yml.php

@@ -1,46 +0,0 @@
-<?php
-/** This script is only use when using the console.php chamilo:install command */
-/**
- * Database settings
- */
-// Your MySQL server
-$_configuration['db_host']     = 'localhost';
-// Your MySQL username
-$_configuration['db_user']     = 'root';
-// Your MySQL password
-$_configuration['db_password'] = 'root';
-
-// Prefix for course tables (IF NOT EMPTY, can be replaced by another prefix, else leave empty)
-/*$_configuration['table_prefix']          = '';
-// prefix all created bases (for courses) with this string
-$_configuration['db_prefix']             = '';*/
-// main Chamilo database
-$_configuration['main_database']         = 'chamilo';
-
-/**
- * Directory settings
- */
-// URL to the root of your Chamilo installation, e.g.: http://www.mychamilo.com/
-// Comment this line if you want to enable multiple URLs
-$_configuration['root_web']       = 'http://localhost/chamilo';
-$_configuration['root_sys']       = '/var/www/chamilo';
-
-/**
- * Misc. settings
- */
-// Security word for password recovery
-$_configuration['security_key']      = md5(uniqid(rand().time()));
-// Hash function method
-$_configuration['password_encryption']      = 'sha1';
-// You may have to restart your web server if you change this
-$_configuration['session_stored_in_db']     = false;
-// Session lifetime
-$_configuration['session_lifetime']         = 3600;
-// Activation for multi-url access
-//$_configuration['multiple_access_urls']   = true;
-//Deny the elimination of users
-$_configuration['deny_delete_users']        = false;
-//Prevent all admins from using the "login_as" feature
-$_configuration['login_as_forbidden_globally'] = false;
-// Version settings
-$_configuration['system_version']           = '1.10.0';

+ 5 - 0
config/routing.yml

@@ -1,5 +1,6 @@
 admin_login_check:
     pattern:   /admin/login_check
+
 admin_logout:
     pattern:   /admin/logout
 
@@ -7,6 +8,10 @@ home:
     path:      /home
     defaults:  { _controller: index.controller:indexAction, culture: en }
 
+homepage:
+    path:      /homepage
+    defaults:  { _controller: index.controller:indexAction, culture: en }
+
 example:
     resource: "src/ChamiloLMS/Resources/config/route_example.yml"
     prefix:   /example-route

+ 3 - 2
main/admin/access_url_edit.php

@@ -119,7 +119,7 @@ $form->addElement('textarea','description',get_lang('Description'));
 
 //the first url with id = 1 will be always active
 if (isset($_GET['url_id']) && $_GET['url_id'] != 1) {
-    $form->addElement('checkbox','active',get_lang('Active'));
+    $form->addElement('checkbox','active', null, get_lang('Active'));
 }
 
 //$form->addRule('checkbox', get_lang('ThisFieldIsRequired'), 'required');
@@ -141,8 +141,9 @@ if (isset($_GET['url_id'])) {
     $submit_name = get_lang('AddUrl');
 }
 
-if (!$_configuration['multiple_access_urls']) {
+if (!api_is_multiple_url_enabled()) {
     header('Location: index.php');
+    exit;
 }
 
 $tool_name = get_lang('AddUrl');

+ 8 - 22
main/admin/access_url_edit_users_to_url.php

@@ -5,14 +5,6 @@
 *	@author Julio Montoya <gugli100@gmail.com>
 */
 
-
-// name of the language file that needs to be included
-$language_file='admin';
-
-// resetting the course id
-$cidReset = true;
-
-require_once '../inc/global.inc.php';
 require_once __DIR__.'/../inc/lib/xajax/xajax.inc.php';
 $xajax = new xajax();
 
@@ -29,7 +21,6 @@ if (!api_get_multiple_access_url()) {
 	exit;
 }
 
-
 // Database Table Definitions
 $tbl_user				 = Database::get_main_table(TABLE_MAIN_USER);
 $tbl_access_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
@@ -41,12 +32,12 @@ $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAd
 $interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
 
 $add_type = 'multiple';
-if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
+if (isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
 	$add_type = Security::remove_XSS($_REQUEST['add_type']);
 }
 
 $access_url_id=1;
-if(isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
+if (isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
 	$access_url_id = Security::remove_XSS($_REQUEST['access_url_id']);
 }
 
@@ -97,9 +88,11 @@ if (isset($_POST['form_sent']) && $_POST['form_sent']) {
 	if (!is_array($UserList)) {
 		$UserList=array();
 	}
+
 	if ($form_sent == 1) {
-		if ($access_url_id==0) {
+		if ($access_url_id == 0) {
 			header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
+            exit;
 		} elseif (is_array($UserList)) {
 			$result     = UrlManager::update_urls_rel_user($UserList, $access_url_id);
             $url_info   = UrlManager::get_url_data_from_id($access_url_id);
@@ -111,7 +104,7 @@ if (isset($_POST['form_sent']) && $_POST['form_sent']) {
                 $message .=  '<h4>'.get_lang('UsersAdded').':</h4>';
                 $i = 1;
                 $user_added_list = array();
-                foreach($result['users_added'] as $user) {
+                foreach ($result['users_added'] as $user) {
                     $user_info = api_get_user_info($user);
                     if (!empty($user_info)) {
                         $user_added_list[] = $i.'. '.api_get_person_name($user_info['firstname'], $user_info['lastname']);
@@ -186,7 +179,6 @@ if ($ajax_search) {
 	}
 }
 
-
 if ($add_type == 'multiple') {
 	$link_add_type_unique = '<a href="'.api_get_self().'?add_type=unique&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeUnique').'</a>';
 	$link_add_type_multiple = get_lang('SessionAddTypeMultiple');
@@ -241,8 +233,8 @@ if (!empty($errorMsg)) {
     <td>
     <h3>
     <?php
-            $total_users = count($nosessionUsersList) +  count($sessionUsersList);
-            echo get_lang('TotalAvailableUsers').' '.$total_users;
+        $total_users = count($nosessionUsersList) +  count($sessionUsersList);
+        echo get_lang('TotalAvailableUsers').' '.$total_users;
     ?>
     </h3>
     </td>
@@ -304,7 +296,6 @@ if (!empty($errorMsg)) {
 foreach ($sessionUsersList as $enreg) {
 ?>
 	<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
-
 <?php
 }
 unset($sessionUsersList);
@@ -331,11 +322,6 @@ function valide(){
 	var options = document.getElementById('destination_users').options;
 	for (i = 0 ; i<options.length ; i++)
 		options[i].selected = true;
-	/*
-	var options = document.getElementById('destination_classes').options;
-	for (i = 0 ; i<options.length ; i++)
-		options[i].selected = true;
-		*/
 	document.forms.formulaire.submit();
 }
 

+ 3 - 26
main/admin/user_add.php

@@ -4,20 +4,9 @@
 *	@package chamilo.admin
 */
 
-// Language files that should be included
-$language_file = array('admin', 'registration');
-$cidReset = true;
-// Including necessary libraries.
-require_once '../inc/global.inc.php';
-
-// Section for the tabs
-$this_section = SECTION_PLATFORM_ADMIN;
-
 // User permissions
 api_protect_admin_script(true);
 
-$is_platform_admin = api_is_platform_admin() ? 1 : 0;
-
 $message = null;
 
 $htmlHeadXtra[] = api_get_password_checker_js('#username', '#password');
@@ -161,7 +150,7 @@ $auth_sources = 0; //make available wider as we need it in case of form reset (s
 $nb_ext_auth_source_added = 0;
 if (isset($extAuthSource) && count($extAuthSource) > 0) {
 	$auth_sources = array();
-	foreach($extAuthSource as $key => $info) {
+	foreach ($extAuthSource as $key => $info) {
 	    // @todo : make uniform external authentification configuration (ex : cas and external_login ldap)
 	    // Special case for CAS. CAS is activated from Chamilo > Administration > Configuration > CAS
 	    // extAuthSource always on for CAS even if not activated
@@ -185,8 +174,10 @@ $form->addGroup($group, 'password', get_lang('Password'), '');
 if (isset($_configuration['allow_strength_pass_checker']) && $_configuration['allow_strength_pass_checker']) {
     $form->addElement('label', null, '<div id="password_progress" style="display:none"></div>');
 }
+
 // Status
 $status = api_get_user_roles();
+unset($status[ANONYMOUS]);
 
 $form->addElement(
     'select',
@@ -209,18 +200,6 @@ if (isset($drh_list) && is_array($drh_list)) {
 }
 $form->addElement('html', '</div>');
 
-/*
-if (api_is_platform_admin()) {
-    // Platform admin
-    $group = array();
-    $group[] = $form->createElement('radio', 'platform_admin', 'id="id_platform_admin"', get_lang('Yes'), 1);
-    $group[] = $form->createElement('radio', 'platform_admin', 'id="id_platform_admin"', get_lang('No'), 0);
-    //$display = ($_POST['status'] == STUDENT || !isset($_POST['status'])) ? 'none' : 'block';
-    $form->addElement('html', '<div id="id_platform_admin" style="display:'.$display.';">');
-    $form->addGroup($group, 'admin', get_lang('PlatformAdmin'), '&nbsp;');
-    $form->addElement('html', '</div>');
-}*/
-
 $form->addElement('select_language', 'language', get_lang('Language'), null);
 
 // Send email
@@ -257,7 +236,6 @@ $(document).ready(function(){
 </script>';
 
 // Set default values
-$defaults['admin']['platform_admin'] = 0;
 $defaults['mail']['send_mail'] = 0;
 $defaults['password']['password_auto'] = 1;
 $defaults['active'] = 1;
@@ -291,7 +269,6 @@ if( $form->validate()) {
 		$status         = intval($user['status']);
 		$language       = $user['language'];
 		$picture        = $_FILES['picture'];
-		$platform_admin = intval($user['admin']['platform_admin']);
 		$send_mail      = intval($user['mail']['send_mail']);
 		$hr_dept_id     = intval($user['hr_dept_id']);
 

+ 39 - 80
main/admin/user_edit.php

@@ -4,17 +4,6 @@
  * @package chamilo.admin
  */
 
-// Language files that should be included
-$language_file = array('admin', 'registration');
-
-$cidReset = true;
-
-require_once '../inc/global.inc.php';
-
-$this_section = SECTION_PLATFORM_ADMIN;
-
-api_protect_admin_script(true);
-
 $user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : intval($_POST['user_id']);
 
 api_protect_super_admin($user_id, null, true);
@@ -79,7 +68,6 @@ if (Database::num_rows($res) != 1) {
 }
 
 $user_data = Database::fetch_array($res, 'ASSOC');
-$user_data['platform_admin'] = is_null($user_data['is_admin']) ? 0 : 1;
 $user_data['send_mail'] = 0;
 $user_data['old_password'] = $user_data['password'];
 //Convert the registration date of the user
@@ -216,13 +204,18 @@ if (api_is_global_platform_admin() or api_get_setting('admins_can_set_users_pass
 
 // Status.
 $status = api_get_user_roles();
+unset($status[ANONYMOUS]);
 
 $form->addElement(
     'select',
     'status',
     get_lang('Profile'),
     $status,
-    array('id' => 'status_select', 'onchange' => 'javascript: display_drh_list();', 'class' => 'chzn-select')
+    array(
+        'id' => 'status_select',
+        'onchange' => 'javascript: display_drh_list();',
+        'class' => 'chzn-select'
+    )
 );
 
 $display = isset($user_data['status']) && ($user_data['status'] == STUDENT || (isset($_POST['status']) && $_POST['status'] == STUDENT)) ? 'block' : 'none';
@@ -244,19 +237,6 @@ foreach($drh_list as $drh) {
 $form->addElement('html', '</div>');
 */
 
-// Platform admin
-if (api_is_platform_admin()) {
-    $group = array();
-    $group[] = $form->createElement('radio', 'platform_admin', null, get_lang('Yes'), 1);
-    $group[] = $form->createElement('radio', 'platform_admin', null, get_lang('No'), 0);
-
-    $user_data['status'] == 1 ? $display = 'block' : $display = 'none';
-
-    $form->addElement('html', '<div id="id_platform_admin" style="display:'.$display.'">');
-    $form->addGroup($group, 'admin', get_lang('PlatformAdmin'), null, false);
-    $form->addElement('html', '</div>');
-}
-
 //Language
 $form->addElement('select_language', 'language', get_lang('Language'));
 
@@ -269,24 +249,21 @@ $form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;', false);
 // Registration Date
 $form->addElement('static', 'registration_date', get_lang('RegistrationDate'), $user_data['registration_date']);
 
-if (!$user_data['platform_admin']) {
-    // Expiration Date
-    $form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
-    $group = array();
-    $group[] = $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
-    $group[] = $form->createElement(
-        'datepicker',
-        'expiration_date',
-        null,
-        array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();')
-    );
-    $form->addGroup($group, 'max_member_group', null, '', false);
-
-    // Active account or inactive account
-    $form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);
-    $form->addElement('radio', 'active', '', get_lang('Inactive'), 0);
-}
+// Expiration Date
+$form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
+$group = array();
+$group[] = $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
+$group[] = $form->createElement(
+    'datepicker',
+    'expiration_date',
+    null,
+    array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();')
+);
+$form->addGroup($group, 'max_member_group', null, '', false);
 
+// Active account or inactive account
+$form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);
+$form->addElement('radio', 'active', '', get_lang('Inactive'), 0);
 
 // EXTRA FIELDS
 $extraField = new ExtraField('user');
@@ -325,6 +302,18 @@ if ($expiration_date == '0000-00-00 00:00:00') {
     $user_data['expiration_date']['H'] = substr($expiration_date, 11, 2);
     $user_data['expiration_date']['i'] = substr($expiration_date, 14, 2);
 }
+
+$user = $app['orm.em']->getRepository('Entity\User')->find($user_data['user_id']);
+
+$roles = $user->getRoles();
+
+$role  = array();
+if (!empty($roles)) {
+    $role = current($roles);
+    $role = $role->getId();
+}
+
+$user_data['status'] = $role;
 $form->setDefaults($user_data);
 
 $error_drh = false;
@@ -355,33 +344,28 @@ if ($form->validate()) {
         $firstname = $user['firstname'];
         $password = $user['password'];
         $auth_source = $user['auth_source'];
-
         $official_code = $user['official_code'];
         $email = $user['email'];
         $phone = $user['phone'];
         $username = $user['username'];
         $status = intval($user['status']);
-        $platform_admin = intval($user['platform_admin']);
         $send_mail = intval($user['send_mail']);
         $reset_password = intval($user['reset_password']);
         $hr_dept_id = intval($user['hr_dept_id']);
         $language = $user['language'];
-        if ($user['radio_expiration_date'] == '1' && !$user_data['platform_admin']) {
+
+        if ($user['radio_expiration_date'] == '1') {
             $expiration_date = Text::return_datetime_from_array($user['expiration_date']);
         } else {
-            $expiration_date = '0000-00-00 00:00:00';
+            $expiration_date = null;
         }
 
-        $active = $user_data['platform_admin'] ? 1 : intval($user['active']);
-
-        //If the user is set to admin the status will be overwrite by COURSEMANAGER = 1
-        if ($platform_admin == 1) {
-            $status = COURSEMANAGER;
-        }
+        $active = intval($user['active']);
 
         if (api_get_setting('login_is_email') == 'true') {
             $username = $email;
         }
+
         UserManager::update_user(
             $user_id,
             $firstname,
@@ -408,38 +392,13 @@ if ($form->validate()) {
         if (api_get_setting('openid_authentication') == 'true' && !empty($user['openid'])) {
             $up = UserManager::update_openid($user_id, $user['openid']);
         }
-        if ($user_id != $_SESSION['_uid']) {
-            if ($platform_admin == 1) {
-                UserManager::add_user_as_admin($user_id);
-            } else {
-                UserManager::remove_user_admin($user_id);
-            }
-        }
 
-        // Using the extrafieldvalue obj
+        // Using the extra field value obj
         $extraFieldValues = new ExtraFieldValue('user');
         $extraFieldValues->save_field_values($user);
 
-        /*
-        foreach ($user as $key => $value) {
-            if (substr($key, 0, 6) == 'extra_') {
-                //an extra field
-                if (is_array($value) && isset($value['Y']) && isset($value['F']) && isset($value['d'])) {
-                    if (isset($value['H']) && isset($value['i'])) {
-                        // extra field date time
-                        $time = mktime($value['H'], $value['i'], 0, $value['F'], $value['d'], $value['Y']);
-                        $value = date('Y-m-d H:i:s', $time);
-                    } else {
-                        // extra field date
-                        $time = mktime(0, 0, 0, $value['F'], $value['d'], $value['Y']);
-                        $value = date('Y-m-d', $time);
-                    }
-                }
-                UserManager::update_extra_field_value($user_id, substr($key, 6), $value);
-            }
-        }*/
-
         $tok = Security::get_token();
+
         header(
             'Location: user_list.php?action=show_message&message='.urlencode(get_lang('UserUpdated')).'&sec_token='.$tok
         );

+ 12 - 119
main/admin/user_list.php

@@ -12,6 +12,7 @@ $cidReset = true;
 
 global $_configuration;
 
+
 $current_access_url_id = api_get_current_access_url_id();
 
 // Blocks the possibility to delete a user
@@ -156,120 +157,6 @@ $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script(true);
 
-/**
-*	Make sure this function is protected because it does NOT check password!
-*
-*	This function defines globals.
-*   @param  int     User ID
-*   @return bool    False on failure, redirection on success
-*	@author Evie Embrechts
-*   @author Yannick Warnier <yannick.warnier@dokeos.com>
-*/
-function login_user($user_id) {
-    $user_id = intval($user_id);
-
-    if (empty($user_id)) {
-        return false;
-    }
-    if ($user_id != strval(intval($user_id))) {
-    	return false;
-    }
-
-    //Only superadmins can login to admin accounts
-    if (!api_global_admin_can_edit_admin($user_id)) {
-        return false;
-    }
-
-    //Load $_user to be sure we clean it before logging in
-	global $uidReset, $loginFailed, $_user;
-
-	$main_user_table      = Database::get_main_table(TABLE_MAIN_USER);
-	$main_admin_table     = Database::get_main_table(TABLE_MAIN_ADMIN);
-	$track_e_login_table  = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-
-	unset($_user['user_id']); // uid not in session ? prevent any hacking
-
-    $user_info = api_get_user_info($user_id);
-
-    // check if the user is allowed to 'login_as'
-    $can_login_as = empty($_configuration['login_as_forbidden_globally']) && (api_is_global_platform_admin() || (api_get_setting('login_as_allowed') === 'true' && (api_is_platform_admin() OR (api_is_session_admin() && $user_info['status'] == 5 ))));
-    if (!$can_login_as) { return false; }
-
-	$firstname  = $user_info['firstname'];
-	$lastname   = $user_info['lastname'];
-	$user_id    = $user_info['user_id'];
-
-	//$message = "Attempting to login as ".api_get_person_name($firstname, $lastname)." (id ".$user_id.")";
-	if (api_is_western_name_order()) {
-		$message = sprintf(get_lang('AttemptingToLoginAs'),$firstname,$lastname,$user_id);
-	} else {
-		$message = sprintf(get_lang('AttemptingToLoginAs'), $lastname, $firstname, $user_id);
-	}
-
-	$loginFailed = false;
-	$uidReset = false;
-
-	if ($user_id) { // a uid is given (log in succeeded)
-
-		$sql_query = "SELECT user.*, a.user_id is_admin,
-			UNIX_TIMESTAMP(login.login_date) login_date
-			FROM $main_user_table
-			LEFT JOIN $main_admin_table a
-			ON user.user_id = a.user_id
-			LEFT JOIN $track_e_login_table login
-			ON user.user_id = login.login_user_id
-			WHERE user.user_id = '".$user_id."'
-			ORDER BY login.login_date DESC LIMIT 1";
-
-		$sql_result = Database::query($sql_query);
-
-		if (Database::num_rows($sql_result) > 0) {
-			// Extracting the user data
-
-			$user_data = Database::fetch_array($sql_result);
-
-            //Delog the current user
-
-            Online::loginDelete($_SESSION["_user"]["user_id"]);
-
-			// Cleaning session variables
-			unset($_SESSION['_user']);
-			unset($_SESSION['is_platformAdmin']);
-			unset($_SESSION['is_allowedCreateCourse']);
-			unset($_SESSION['_uid']);
-
-
-			$_user['firstName'] 	= $user_data['firstname'];
-			$_user['lastName'] 		= $user_data['lastname'];
-			$_user['mail'] 			= $user_data['email'];
-			$_user['lastLogin'] 	= $user_data['login_date'];
-			$_user['official_code'] = $user_data['official_code'];
-			$_user['picture_uri'] 	= $user_data['picture_uri'];
-			$_user['user_id']		= $user_data['user_id'];
-            $_user['status']        = $user_data['status'];
-
-			$is_platformAdmin = (bool) (!is_null($user_data['is_admin']));
-			$is_allowedCreateCourse = (bool) ($user_data['status'] == 1);
-
-			// Filling session variables with new data
-			$_SESSION['_uid']                   = $user_id;
-			$_SESSION['_user']                  = $_user;
-			$_SESSION['is_platformAdmin']       = $is_platformAdmin;
-			$_SESSION['is_allowedCreateCourse'] = $is_allowedCreateCourse;
-			$_SESSION['login_as']               = true; // will be useful later to know if the user is actually an admin or not (example reporting)s
-
-			$target_url = api_get_path(WEB_PATH)."user_portal.php";
-			$message .= '<br />'.sprintf(get_lang('LoginSuccessfulGoToX'),'<a href="'.$target_url.'">'.$target_url.'</a>');
-			Display :: display_header(get_lang('UserList'));
-			Display :: display_normal_message($message,false);
-			Display :: display_footer();
-			exit;
-		} else {
-			exit ("<br />WARNING UNDEFINED UID !! ");
-		}
-	}
-}
-
 /**
  * Get the total number of users on the platform
  * @see SortableTable#get_total_number_of_items()
@@ -289,8 +176,6 @@ function get_number_of_users() {
  */
 function get_user_data($from, $number_of_items, $column, $direction, $get_count = false)
 {
-    $roles = api_get_user_roles();
-
 	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
 	$admin_table = Database :: get_main_table(TABLE_MAIN_ADMIN);
 
@@ -480,8 +365,11 @@ function user_filter($name, $params, $row) {
  * @return string Some HTML-code with modify-buttons
  */
 function modify_filter($user_id, $url_params, $row) {
-	global $charset, $_admins_list, $delete_user_available;
+	global $_admins_list, $delete_user_available, $app;
     $is_admin = false;
+
+    $userId = api_get_user_id();
+
     if (is_array($_admins_list)) {
 	    $is_admin   = in_array($user_id,$_admins_list);
     }
@@ -524,6 +412,7 @@ function modify_filter($user_id, $url_params, $row) {
     // $_configuration['login_as_forbidden_globally'], defined in
     // configuration.php, is the master key to these conditions
     global $_configuration;
+
     if (empty($_configuration['login_as_forbidden_globally']) &&
         (api_is_global_platform_admin() ||
             (api_get_setting('login_as_allowed') === 'true' &&
@@ -536,9 +425,13 @@ function modify_filter($user_id, $url_params, $row) {
         )
     ) {
         if (!$user_is_anonymous) {
-            if (api_global_admin_can_edit_admin($user_id)) {
+            if ($app['security']->isGranted('ROLE_GLOBAL_ADMIN')) {
                 // everything looks good, show "login as" link
-                $result .= '<a href="user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>&nbsp;&nbsp;';
+                if ($user_id != $userId) {
+                    $result .= '<a href="'.api_get_path(WEB_PUBLIC_PATH).'?_switch_user='.$row[5].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>&nbsp;&nbsp;';
+                } else {
+                    $result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
+                }
             } else {
                 // if this user in particular can't be edited, show disabled
                 $result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';

+ 50 - 43
main/auth/inscription.php

@@ -7,13 +7,15 @@
  */
 
 use \ChamiloSession as Session;
+use Symfony\Component\EventDispatcher\EventDispatcher,
+    Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken,
+    Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
 
 $language_file = array('registration', 'admin');
 
 if (!empty($_POST['language'])) { //quick hack to adapt the registration form result to the selected registration language
     $_GET['language'] = $_POST['language'];
 }
-require_once '../inc/global.inc.php';
 
 if (api_get_setting('allow_registration') === 'false') {
     api_not_allowed(true);
@@ -79,14 +81,12 @@ if ($user_already_registered_show_terms == false) {
     if (api_get_setting('openid_authentication') == 'true') {
         $form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => 40));
     }
-    // Enabled by Ivan Tcholakov, 06-APR-2009. CONFVAL_ASK_FOR_OFFICIAL_CODE = false by default.
-    //	OFFICIAL CODE
-    //if (CONFVAL_ASK_FOR_OFFICIAL_CODE) {
-        $form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => 40));
-        if (api_get_setting('registration', 'officialcode') == 'true') {
-            $form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
-        }
-    //}
+
+    $form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => 40));
+    if (api_get_setting('registration', 'officialcode') == 'true') {
+        $form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
+    }
+
 
     //	USERNAME
     if (api_get_setting('login_is_email') != 'true') {
@@ -120,13 +120,6 @@ if ($user_already_registered_show_terms == false) {
         $form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
     }
 
-    // PICTURE
-    /*if (api_get_setting('profile', 'picture') == 'true') {
-        $form->addElement('file', 'picture', get_lang('AddPicture'));
-        $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
-        $form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
-    }*/
-
     //	LANGUAGE
     if (api_get_setting('registration', 'language') == 'true') {
         $form->addElement('select_language', 'language', get_lang('Language'));
@@ -228,7 +221,7 @@ if (!CustomPages::enabled()) {
         }
     }
 
-    $tool_name = get_lang('Registration', null, (!empty($_POST['language'])?$_POST['language']:$_user['language']));
+    $tool_name = get_lang('Registration');
 
     if (api_get_setting('allow_terms_conditions') == 'true' && $user_already_registered_show_terms) {
         $tool_name = get_lang('TermsAndConditions');
@@ -329,13 +322,31 @@ if ($form->validate()) {
         Session::write('is_platformAdmin', $is_admin);
     } else {
         // Creates a new user
-        $user_id = UserManager::create_user($values['firstname'], $values['lastname'], $values['status'], $values['email'], $values['username'], $values['pass1'], $values['official_code'], $values['language'], $values['phone'], $picture_uri, PLATFORM_AUTH_SOURCE, null, 1, 0, null, null, true);
+        $user_id = UserManager::create_user(
+            $values['firstname'],
+            $values['lastname'],
+            $values['status'],
+            $values['email'],
+            $values['username'],
+            $values['pass1'],
+            $values['official_code'],
+            $values['language'],
+            $values['phone'],
+            null,
+            PLATFORM_AUTH_SOURCE,
+            null,
+            1,
+            0,
+            null,
+            null,
+            true
+        );
 
         // Register extra fields
         $extras = array();
         foreach ($values as $key => $value) {
             if (substr($key, 0, 6) == 'extra_') { //an extra field
-                $extras[substr($key,6)] = $value;
+                $extras[substr($key, 6)] = $value;
             }
         }
 
@@ -390,19 +401,19 @@ if ($form->validate()) {
 
                 $emailsubject	 = get_lang('ApprovalForNewAccount',null,$values['language']).': '.$values['username'];
                 $emailbody		 = get_lang('ApprovalForNewAccount',null,$values['language'])."\n";
-                $emailbody		.= get_lang('UserName',null,$values['language']).': '.$values['username']."\n";
+                $emailbody		.= get_lang('UserName',null, $values['language']).': '.$values['username']."\n";
 
                 if (api_is_western_name_order()) {
-                    $emailbody	.= get_lang('FirstName',null,$values['language']).': '.$values['firstname']."\n";
-                    $emailbody	.= get_lang('LastName',null,$values['language']).': '.$values['lastname']."\n";
+                    $emailbody	.= get_lang('FirstName',null, $values['language']).': '.$values['firstname']."\n";
+                    $emailbody	.= get_lang('LastName',null, $values['language']).': '.$values['lastname']."\n";
                 } else {
-                    $emailbody	.= get_lang('LastName',null,$values['language']).': '.$values['lastname']."\n";
-                    $emailbody	.= get_lang('FirstName',null,$values['language']).': '.$values['firstname']."\n";
+                    $emailbody	.= get_lang('LastName',null, $values['language']).': '.$values['lastname']."\n";
+                    $emailbody	.= get_lang('FirstName',null, $values['language']).': '.$values['firstname']."\n";
                 }
-                $emailbody		.= get_lang('Email',null,$values['language']).': '.$values['email']."\n";
-                $emailbody		.= get_lang('Status',null,$values['language']).': '.$values['status']."\n\n";
+                $emailbody		.= get_lang('Email',null, $values['language']).': '.$values['email']."\n";
+                $emailbody		.= get_lang('Status',null, $values['language']).': '.$values['status']."\n\n";
                 $url_edit        = Display::url(api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user_id, api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user_id);
-                $emailbody		.= get_lang('ManageUser',null,$values['language']).": $url_edit";
+                $emailbody		.= get_lang('ManageUser',null, $values['language']).": $url_edit";
 
                 $admins = UserManager::get_all_administrators();
                 foreach ($admins as $admin_info) {
@@ -436,24 +447,20 @@ if ($form->validate()) {
         $values = api_get_user_info($user_id);
     }
 
-    /* SESSION REGISTERING */
-    /* @todo move this in a function */
-    $_user['firstName'] = stripslashes($values['firstname']);
-    $_user['lastName'] 	= stripslashes($values['lastname']);
-    $_user['mail'] 		= $values['email'];
-    $_user['language'] 	= $values['language'];
-    $_user['user_id']	= $user_id;
-    $is_allowedCreateCourse = $values['status'] == 1;
+    // Symfony way to login as a user
+    $user = $app['orm.em']->getRepository('Entity\User')->find($user_id);
+
+    // Here, "secured" is the name of the firewall in your security.yml
+    $token = new UsernamePasswordToken($user, $user->getPassword(), 'secured', $user->getRoles());
+    $app['security']->setToken($token);
+    $request = $app['request'];
 
-    Session::write('_user', $_user);
-    Session::write('is_allowedCreateCourse', $is_allowedCreateCourse);
+    // Fire the login event
+    // Logging the user in above the way we do it doesn't do this automatically
+    $event = new InteractiveLoginEvent($request, $token);
+    $app['dispatcher']->dispatch("security.interactive_login", $event);
 
-    //stats
-    event_login();
 
-    // last user login date is now
-    $user_last_login_datetime = 0; // used as a unix timestamp it will correspond to : 1 1 1970
-    Session::write('user_last_login_datetime', $user_last_login_datetime);
     $recipient_name = api_get_person_name($values['firstname'], $values['lastname']);
 
     $text_after_registration = '<p>'.get_lang('Dear', null, $_user['language']).' '.stripslashes(Security::remove_XSS($recipient_name)).',<br /><br />'.get_lang('PersonalSettings',null,$_user['language']).".</p>";
@@ -470,7 +477,7 @@ if ($form->validate()) {
             $text_after_registration.= '<p>'.get_lang('MailHasBeenSent',null,$_user['language']).'.</p>';
         }
 
-        if ($is_allowedCreateCourse) {
+        if (api_is_allowed_to_create_course()) {
             $form_data['message'] = '<p>'. get_lang('NowGoCreateYourCourse',null,$_user['language']). "</p>";
             $form_data['action']  = '../create_course/add_course.php';
 

+ 11 - 3
main/cron/import_csv.php

@@ -349,7 +349,7 @@ class ImportCsv
         /*
          * Another users import.
         Unique identifier: official code and username . ok
-        Username and password should never get updated. ok
+        Password should never get updated. ok
         If an update should need to occur (because it changed in the .csv), we’ll want that logged. We will handle this manually in that case.
         All other fields should be updateable, though passwords should of course not get updated. ok
         If a user gets deleted (not there anymore),
@@ -440,7 +440,7 @@ class ImportCsv
                         $userInfo['user_id'],
                         $row['firstname'], // <<-- changed
                         $row['lastname'],  // <<-- changed
-                        $userInfo['username'],
+                        $row['username'],  // <<-- changed
                         null, //$password = null,
                         $auth_source = null,
                         $userInfo['email'],
@@ -460,6 +460,9 @@ class ImportCsv
                     );
 
                     if ($result) {
+                        if ($row['username'] != $userInfo['username']) {
+                            $this->logger->addInfo("Students - Username was changes from '".$userInfo['username']."' to '".$row['username']."' ");
+                        }
                         foreach ($row as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') { //an extra field
                                 UserManager::update_extra_field_value($userInfo['user_id'], substr($key, 6), $value);
@@ -538,6 +541,10 @@ class ImportCsv
      */
     private function importSessions($file)
     {
+        $avoid =  null;
+        if (isset($this->conditions['importSessions']) && isset($this->conditions['importSessions']['update'])) {
+            $avoid = $this->conditions['importSessions']['update'];
+        }
         $result = SessionManager::importCSV(
             $file,
             true,
@@ -547,7 +554,8 @@ class ImportCsv
             $this->extraFieldIdNameList['session'],
             $this->daysCoachAccessBeforeBeginning,
             $this->daysCoachAccessAfterBeginning,
-            $this->defaultSessionVisibility
+            $this->defaultSessionVisibility,
+            $avoid
         );
 
         if (!empty($result['error_message'])) {

+ 15 - 24
main/inc/Entity/Repository/UserRepository.php

@@ -16,9 +16,9 @@ use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
 class UserRepository extends EntityRepository implements UserProviderInterface
 {
     /**
-     * @param string $keyword
-     * @return mixed
-     */
+    * @param string $keyword
+    * @return mixed
+    */
     public function searchUserByKeyword($keyword)
     {
         $qb = $this->createQueryBuilder('a');
@@ -77,7 +77,7 @@ class UserRepository extends EntityRepository implements UserProviderInterface
 
     /**
      * @param string $username
-     * @return mixed
+     * @return \Entity\User
      * @throws UsernameNotFoundException
      */
     public function loadUserByUsername($username)
@@ -102,14 +102,22 @@ class UserRepository extends EntityRepository implements UserProviderInterface
     }
 
     /**
+     * Refreshes the user for the account interface.
+     *
+     * It is up to the implementation if it decides to reload the user data
+     * from the database, or if it simply merges the passed User into the
+     * identity map of an entity manager.
+     *
+     * @throws UnsupportedUserException if the account is not supported
      * @param UserInterface $user
-     * @return \Entity\User
-     * @throws UnsupportedUserException
+     *
+     * @return UserInterface
      */
     public function refreshUser(UserInterface $user)
     {
         return $user;
-        /*$class = get_class($user);
+        /*
+        $class = get_class($user);
         if (!$this->supportsClass($class)) {
             throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $class));
         }
@@ -124,21 +132,4 @@ class UserRepository extends EntityRepository implements UserProviderInterface
     {
         return $this->getEntityName() === $class || is_subclass_of($class, $this->getEntityName());
     }
-
-    public function getUsers($limit = null)
-    {
-        $qb = $this->createQueryBuilder('u')
-                   ->select('u')
-                   ->addOrderBy('u.username', 'DESC');
-
-        return $qb;
-    }
-
-    public function getSubscribedUsers($limit = null)
-    {
-        $qb = $this->createQueryBuilder('u')
-            ->select('u')
-            ->addOrderBy('u.username', 'DESC');
-        return $qb;
-    }
 }

+ 18 - 16
main/inc/Entity/User.php

@@ -12,7 +12,7 @@ use Symfony\Component\Validator\Mapping\ClassMetadata;
 
 use Symfony\Component\Validator\Constraints as Assert;
 use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
-
+use Symfony\Component\Validator\Constraints\DateTime;
 use ChamiloLMS\Component\Auth;
 
 /**
@@ -77,7 +77,7 @@ class User implements AdvancedUserInterface, \Serializable , EquatableInterface
     /**
      * @var boolean
      *
-     * @ORM\Column(name="status", type="boolean", precision=0, scale=0, nullable=false, unique=false)
+     * @ORM\Column(name="status", type="integer", precision=0, scale=0, nullable=false, unique=false)
      */
     private $status;
 
@@ -253,7 +253,7 @@ class User implements AdvancedUserInterface, \Serializable , EquatableInterface
      */
     private $curriculumItems;
 
-     /**
+    /**
      *
      */
     public function __construct()
@@ -335,11 +335,13 @@ class User implements AdvancedUserInterface, \Serializable , EquatableInterface
     }
 
     /**
-    * @inheritDoc
-    */
+     * @inheritDoc
+     */
     public function isAccountNonExpired()
     {
         return true;
+        /*$now = new \DateTime();
+        return $this->getExpirationDate() < $now;*/
     }
 
     /**
@@ -371,10 +373,10 @@ class User implements AdvancedUserInterface, \Serializable , EquatableInterface
      */
     public function eraseCredentials()
     {
-        $this->password = null;
     }
 
     /**
+     * This function is needed in order to pass roles to the security component
      * @inheritDoc
      */
     public function getRoles()
@@ -400,14 +402,16 @@ class User implements AdvancedUserInterface, \Serializable , EquatableInterface
         /*
          * ! Don't serialize $roles field !
          */
-        return \serialize(array(
-            $this->userId,
-            $this->username,
-            $this->email,
-            $this->salt,
-            $this->password,
-            $this->isActive
-        ));
+        return \serialize(
+            array(
+                $this->userId,
+                $this->username,
+                $this->email,
+                $this->salt,
+                $this->password,
+                $this->isActive
+            )
+        );
     }
 
     /**
@@ -490,7 +494,6 @@ class User implements AdvancedUserInterface, \Serializable , EquatableInterface
      */
     public function getCompleteName()
     {
-        //return $this->lastname .', '. $this->firstname .' ('. $this->email .')';
         return $this->lastname .', '. $this->firstname;
     }
 
@@ -521,7 +524,6 @@ class User implements AdvancedUserInterface, \Serializable , EquatableInterface
         return $this->userId;
     }
 
-
     /**
      * Set lastname
      *

+ 6 - 16
main/inc/global.inc.php

@@ -4,7 +4,7 @@
 /**
  * This is a bootstrap file that loads all Chamilo dependencies including:
  *
- * - Chamilo settings in main/inc/conf/configuration.php or config/configuration.yml or config/configuration.php (in this order, using what if finds first)
+ * - Chamilo settings config/configuration.yml or config/configuration.php (in this order, using what if finds first)
  * - Database (Using Doctrine DBAL/ORM)
  * - Templates (Using Twig)
  * - Loading language files (Using Symfony component)
@@ -176,7 +176,10 @@ $app['debug'] = isset($_configuration['debug']) ? $_configuration['debug'] : fal
 $app['show_profiler'] = isset($_configuration['show_profiler']) ? $_configuration['show_profiler'] : false;
 
 // Enables assetic in order to load 1 compressed stylesheet or split files
+//$app['assetic.enabled'] = $app['debug'];
+// Harcoded to false by default. Implementation is not finished yet.
 $app['assetic.enabled'] = false;
+
 // Dumps assets
 $app['assetic.auto_dump_assets'] = false;
 
@@ -217,13 +220,12 @@ $app['template.show_footer'] = true;
 $app['template.show_learnpath'] = false;
 $app['template.hide_global_chat'] = true;
 $app['template.load_plugins'] = true;
-
 $app['configuration'] = $_configuration;
 
-
 $_plugins = array();
 if ($alreadyInstalled) {
 
+
     /** Including service providers */
     require_once 'services.php';
 
@@ -244,12 +246,7 @@ if ($alreadyInstalled) {
                 $_configuration['access_url'] = $details['id'];
             }
         }
-        //Session::write('url_id', $_configuration['access_url']);
-        //Session::write('url_info', api_get_current_access_url_info($_configuration['access_url']));
-    } else {
-        //Session::write('url_id', 1);
     }
-
 }
 
 $charset = 'UTF-8';
@@ -290,9 +287,7 @@ $app->error(
 
         // Default layout.
         $app['default_layout'] = $app['template_style'].'/layout/layout_1_col.tpl';
-
         $app['template']->assign('error', array('code' => $code, 'message' => $message));
-
         $response = $app['template']->render_layout('error.tpl');
 
         return new Response($response);
@@ -302,7 +297,7 @@ $app->error(
 // Preserving the value of the global variable $charset.
 $charset_initial_value = $charset;
 
-// Section (tabs in the main chamilo menu)
+// Section (tabs in the main Chamilo menu)
 $app['this_section'] = SECTION_GLOBAL;
 
 // Inclusion of internationalization libraries
@@ -773,8 +768,6 @@ $charset = $charset_initial_value;
 // For determing text direction correspondent to the current language we use now information from the internationalization library.
 $text_dir = api_get_text_direction();
 
-// Update of the logout_date field in the table track_e_login (needed for the calculation of the total connection time)
-
 /** "Login as user" custom script */
 // @todo move this code in a controller
 if (!isset($_SESSION['login_as']) && isset($_user)) {
@@ -803,9 +796,6 @@ if (!isset($_SESSION['login_as']) && isset($_user)) {
         $now = api_get_utc_datetime();
         $s_sql_update_logout_date = "UPDATE $tbl_track_login SET logout_date = '$now' WHERE login_id = $i_id_last_connection";
         Database::query($s_sql_update_logout_date);
-    } else {
-        // it isn't, we should create a fresh entry
-        event_login();
     }
 }
 

+ 2 - 1
main/inc/lib/api.lib.php

@@ -6895,7 +6895,7 @@ function api_get_user_roles()
 {
     global $app;
     $em = $app['orm.ems']['db_read'];
-    $roles = $em->getRepository('Entity\Role')->findAll();
+    $roles = $em->getRepository('Entity\Role')->findBy(array(), array('name'=>'asc'));
     $userRoles = array();
     foreach ($roles as $role) {
         $userRoles[$role->getId()] = $role->getName();
@@ -6911,6 +6911,7 @@ function api_get_user_roles()
     $status[QUESTION_MANAGER] = get_lang('QuestionManager');
     return $status;
 }
+
 /**
  * Finds all the information about a user from username instead of user id
  * @param $username (string): the username

+ 0 - 8
main/inc/lib/database.constants.inc.php

@@ -135,20 +135,12 @@ 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');
 define('TABLE_MAIN_USER_REL_COURSE_VOTE',           'user_rel_course_vote');
 
-
 // SCORM database tables this is used only during the migration from 1.6 to 1.8 see update-db-scorm-1.6.x-1.8.0.inc
 define('TABLE_SCORM_MAIN', 'scorm_main');
 define('TABLE_SCORM_SCO_DATA', 'scorm_sco_data');

+ 34 - 54
main/inc/lib/events.lib.inc.php

@@ -13,74 +13,54 @@
  */
 
 /**
- * @author Sebastien Piraux <piraux_seb@hotmail.com>
- * @desc Record information for open event (when homepage is opened)
+ * @author Sebastien Piraux <piraux_seb@hotmail.com> old code
+ * @author Julio Montoya 2013
+ * @desc Record information for login event when an user identifies himself with username & password
  */
-function event_open()
+function event_login(\Entity\User $user)
 {
-    global $_configuration;
-    $TABLETRACK_OPEN = Database::get_main_table(TABLE_STATISTIC_TRACK_E_OPEN);
-
-    // @getHostByAddr($_SERVER['REMOTE_ADDR']) : will provide host and country information
-    // $_SERVER['HTTP_USER_AGENT'] :  will provide browser and os information
-    // $_SERVER['HTTP_REFERER'] : provide information about refering url
-    if (isset($_SERVER['HTTP_REFERER'])) {
-        $referer = Database::escape_string($_SERVER['HTTP_REFERER']);
-    } else {
-        $referer = '';
-    }
-    // record informations only if user comes from another site
-    //if(!eregi($_configuration['root_web'],$referer))
-    $pos = strpos($referer, $_configuration['root_web']);
-    if ($pos === false && $referer != '') {
-        $ip = api_get_real_ip();
-        $remhost = @ getHostByAddr($ip);
-        if ($remhost == $ip) {
-            $remhost = "Unknown"; // don't change this
-        }
-        $reallyNow = api_get_utc_datetime();
-        $sql = "INSERT INTO ".$TABLETRACK_OPEN."
-        		(open_remote_host,
-        		 open_agent,
-        		 open_referer,
-        		 open_date)
-        		VALUES
-        		('".$remhost."',
-        		 '".Database::escape_string($_SERVER['HTTP_USER_AGENT'])."', '".Database::escape_string($referer)."', '$reallyNow')";
-        Database::query($sql);
-    }
-    return 1;
-}
+    $userId =  $user->getUserId();
 
-/**
- * @author Sebastien Piraux <piraux_seb@hotmail.com>
- * @desc Record information for login event
- * (when an user identifies himself with username & password)
- */
-function event_login()
-{
     $TABLETRACK_LOGIN = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-    $_user = api_get_user_info();
 
     $reallyNow = api_get_utc_datetime();
+
     $sql = "INSERT INTO ".$TABLETRACK_LOGIN." (login_user_id, login_ip, login_date, logout_date) VALUES
-                ('".api_get_user_id()."',
+                ('".$userId."',
         		'".Database::escape_string(api_get_real_ip())."',
         		'".$reallyNow."',
         		'".$reallyNow."'
         		)";
     Database::query($sql);
 
+    $roles = $user->getRolesObj();
+
     // auto subscribe
-    $user_status = $_user['status'] == SESSIONADMIN ? 'sessionadmin' :
-    $_user['status'] == COURSEMANAGER ? 'teacher' :
-    $_user['status'] == DRH ? 'DRH' : 'student';
-    $autoSubscribe = api_get_setting($user_status.'_autosubscribe');
-    if ($autoSubscribe) {
-        $autoSubscribe = explode('|', $autoSubscribe);
-        foreach ($autoSubscribe as $code) {
-            if (CourseManager::course_exists($code)) {
-                CourseManager::subscribe_user($_user['user_id'], $code);
+
+    /** @var \Entity\Role $role  */
+    foreach ($roles as $role) {
+        $role = $role->getRole();
+        $userStatusParsed = 'student';
+
+        switch ($role) {
+            case 'ROLE_SESSION_MANAGER':
+                $userStatusParsed = 'sessionadmin';
+                break;
+            case 'ROLE_TEACHER':
+                $userStatusParsed = 'teacher';
+                break;
+            case 'ROLE_RRHH':
+                $userStatusParsed = 'DRH';
+                break;
+        }
+
+        $autoSubscribe = api_get_setting($userStatusParsed.'_autosubscribe');
+        if ($autoSubscribe) {
+            $autoSubscribe = explode('|', $autoSubscribe);
+            foreach ($autoSubscribe as $code) {
+                if (CourseManager::course_exists($code)) {
+                    CourseManager::subscribe_user($userId, $code);
+                }
             }
         }
     }

+ 5 - 0
main/inc/lib/sessionmanager.lib.php

@@ -2076,6 +2076,10 @@ class SessionManager
             return false;
         }
 
+        if (api_is_session_admin()) {
+            return false;
+        }
+
         $blockTeachers = !api_is_teacher() || (api_is_teacher() && api_get_setting('allow_teachers_to_create_sessions') == 'false');
 
         if ($blockTeachers) {
@@ -2085,6 +2089,7 @@ class SessionManager
         if (!empty($id)) {
             $session_info = self::fetch($id);
 
+
             if (empty($session_info)) {
                 api_not_allowed(true);
             }

+ 0 - 593
main/inc/lib/stats.lib.inc.php

@@ -1,593 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
-*	This is the statistics library for Dokeos.
-*	Include/require it in your code to use its functionality.
-*
-*	@author Sebastien Piraux
-*	@package chamilo.library
-*
-*/
-
-/*
-	List of functions :
-	-------------------
-
-	addBrowser			--		OK
-	addCountry 			--		OK
-	addOs				--		OK
-	addProvider 			-- 		OK
-	addReferer			--		OK
-	cleanProcessedRecords 	        --		OK
-	decodeOpenInfos 		--		OK
-	extractAgent			--		OK	MUST BE IMPROVED
-	extractCountry 			--		OK 	MUST BE IMPROVED
-	extractProvider 		--		OK	MUST BE IMPROVED
-	fillCountriesTable 		--		OK
-	fillBrowsersTable		--		OK
-	fillOsTable			--		OK
-	fillProvidersTable 		-- 		OK
-	fillReferersTable 		--		OK
-	loadCountries 			--		OK
-	loadOs 				-- 		OK
-	loadBrowsers 			-- 		OK
-                                                    ----------
-							OK BUT MAY BE OPTIMIZED
-
-*/
-
-/*
-	   Variables
-*/
-
-// regroup table names for maintenance purpose
-//we can use the database class: this file is only called in the /index.php file before the global.inc.php
-
-$TABLETRACK_OPEN            = Database::get_main_table(TABLE_STATISTIC_TRACK_E_OPEN);
-$TABLESTATS_PROVIDERS       = Database::get_main_table(TABLE_STATISTIC_TRACK_C_PROVIDERS);
-$TABLESTATS_COUNTRIES       = Database::get_main_table(TABLE_STATISTIC_TRACK_C_COUNTRIES);
-$TABLESTATS_BROWSERS        = Database::get_main_table(TABLE_STATISTIC_TRACK_C_BROWSERS);
-$TABLESTATS_OS              = Database::get_main_table(TABLE_STATISTIC_TRACK_C_OS);
-$TABLESTATS_REFERERS        = Database::get_main_table(TABLE_STATISTIC_TRACK_C_REFERERS);
-/*
-
-	   Main : decodeOpenInfos launch all processes
-*/
-
-
-/**
- * @author Sebastien Piraux <piraux_seb@hotmail.com>
- * @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
-
-    $sql = "SELECT open_id
-                FROM $TABLETRACK_OPEN
-                WHERE open_date <= NOW()
-                ORDER BY open_id DESC
-                LIMIT 1";
-    //$processBegin = 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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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 <piraux_seb@hotmail.com>
- * @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);
-        }
-    }
-}

+ 2 - 2
main/inc/lib/urlmanager.lib.php

@@ -650,12 +650,12 @@ class UrlManager
         $result             = Database::query($sql);
         $existing_users     = array();
 
-        //Getting all users
+        // Getting all users
         while ($row = Database::fetch_array($result)) {
             $existing_users[] = $row['user_id'];
         }
 
-        //Adding users
+        // Adding users
         $users_added = array();
         foreach ($user_list as $user_id_to_add) {
             if (!in_array($user_id_to_add, $existing_users)) {

+ 36 - 7
main/inc/lib/usermanager.lib.php

@@ -167,7 +167,8 @@ class UserManager
                 UrlManager::add_user_to_url($user_id, 1);
             }
 
-            /* global $app;
+            global $app;
+            /*
             $em = $app['orm.ems']['db_write'];
             // @var Entity\User $user
             $user = $em->getRepository('Entity\User')->findOneById($user_id);
@@ -371,10 +372,6 @@ class UserManager
             $user = $em->getRepository('Entity\User')->find($return);
             $role = $em->getRepository('Entity\Role')->find($status);
 
-            if ($role->getRole() == 'ROLE_ADMIN') {
-                UserManager::add_user_as_admin($return);
-            }
-
             $user->getRolesObj()->add($role);
             $em->persist($user);
             $t2 = microtime() - $t0;
@@ -724,7 +721,28 @@ class UserManager
      * @return boolean true if the user information was updated
      * @assert (false) === false
      */
-    public static function update_user($user_id, $firstname, $lastname, $username, $password = null, $auth_source = null, $email = null, $status = STUDENT, $official_code = null, $phone = null , $picture_uri = null, $expiration_date = null, $active = 1, $creator_id = null, $hr_dept_id = 0, $extra = null, $language = 'english', $encrypt_method = '', $send_email = false, $reset_password = 0) {
+    public static function update_user(
+        $user_id,
+        $firstname,
+        $lastname,
+        $username,
+        $password = null,
+        $auth_source = null,
+        $email = null,
+        $status = STUDENT,
+        $official_code = null,
+        $phone = null,
+        $picture_uri = null,
+        $expiration_date = null,
+        $active = 1,
+        $creator_id = null,
+        $hr_dept_id = 0,
+        $extra = null,
+        $language = 'english',
+        $encrypt_method = '',
+        $send_email = false,
+        $reset_password = 0
+    ) {
         global $_configuration;
         $original_password = $password;
 
@@ -804,7 +822,18 @@ class UserManager
         if ($user_info['active'] != $active) {
             self::change_active_state($user_id, $active);
         }
-        //active='".Database::escape_string($active)."',
+
+        global $app;
+        // Adding user
+        /** @var Entity\User $user */
+        $em = $app['orm.ems']['db_write'];
+        $user = $em->getRepository('Entity\User')->find($user_id);
+        $role = $em->getRepository('Entity\Role')->find($status);
+
+        $user->getRolesObj()->remove(0);
+        $user->getRolesObj()->add($role);
+        $em->persist($user);
+        $em->flush();
 
         if (!empty($email) && $send_email) {
             $recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);

+ 0 - 1
main/inc/routes.php

@@ -434,7 +434,6 @@ $app->match('/main/{file}', 'legacy.controller:classicAction', 'GET|POST')
     ->assert('file', '.+')
     ->assert('type', '.+');
 
-
 /** Login form */
 $app->match('/login', 'index.controller:loginAction', 'GET|POST')
     ->bind('login');

+ 16 - 36
main/inc/services.php

@@ -13,6 +13,7 @@ use FranMoreno\Silex\Provider\PagerfantaServiceProvider;
 use Silex\Application;
 use Silex\ServiceProviderInterface;
 use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
+use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
 
 // Flint
 $app->register(new Flint\Provider\ConfigServiceProvider());
@@ -32,6 +33,7 @@ $app->register(new ConsoleServiceProvider(), array(
     'console.version'           => '1.0.0',
     'console.project_directory' => __DIR__.'/..'
 ));
+
 // Monolog.
 if (is_writable($app['sys_temp_path'])) {
 
@@ -75,8 +77,7 @@ $app->register(new SecurityServiceProvider, array(
             'pattern' => '^/login$',
             'anonymous' => true
         ),
-        'admin' => array(
-            //'http' => true,
+        'secured' => array(
             'pattern' => '^/.*$',
             'form'    => array(
                 'login_path' => '/login',
@@ -92,6 +93,7 @@ $app->register(new SecurityServiceProvider, array(
             'users' => $app->share(function() use ($app) {
                 return $app['orm.em']->getRepository('Entity\User');
             }),
+            'switch_user' => true,
             'anonymous' => true
         )
     )
@@ -115,8 +117,16 @@ $app['security.authentication.logout_handler.admin'] = $app->share(function($app
     return new ChamiloLMS\Component\Auth\LogoutSuccessHandler($app['url_generator'], $app['security']);
 });
 
+// What to do when switch user?
+$app['security.authentication_listener.switch_user.secured'] = $app->share(function($app) {
+    return new ChamiloLMS\Component\Auth\LoginListener();
+});
+
 // Role hierarchy
 $app['security.role_hierarchy'] = array(
+    // the admin that belongs to the portal #1 can affect all portals
+    'ROLE_GLOBAL_ADMIN' => array('ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'),
+    // the default admin
     'ROLE_ADMIN' => array(
         'ROLE_QUESTION_MANAGER',
         'ROLE_SESSION_MANAGER',
@@ -128,7 +138,7 @@ $app['security.role_hierarchy'] = array(
     'ROLE_RRHH' => array('ROLE_TEACHER'),
     'ROLE_TEACHER' => array('ROLE_STUDENT'),
     'ROLE_QUESTION_MANAGER' => array('ROLE_STUDENT', 'ROLE_QUESTION_MANAGER'),
-    'ROLE_SESSION_MANAGER' => array('ROLE_STUDENT', 'ROLE_SESSION_MANAGER'),
+    'ROLE_SESSION_MANAGER' => array('ROLE_STUDENT', 'ROLE_SESSION_MANAGER', 'ROLE_ALLOWED_TO_SWITCH'),
     'ROLE_STUDENT' => array('ROLE_STUDENT'),
     'ROLE_ANONYMOUS' => array('ROLE_ANONYMOUS'),
 
@@ -168,13 +178,14 @@ $app['security.access_rules'] = array(
 $app['allow_admin_toolbar'] = array(
     'ROLE_ADMIN',
     'ROLE_QUESTION_MANAGER',
+	'ROLE_SESSION_MANAGER',
     'ROLE_DIRECTOR',
     'ROLE_JURY_PRESIDENT',
     'ROLE_JURY_SUBSTITUTE',
     'ROLE_JURY_MEMBER'
 );
 
-/**
+/*
 $app['security.access_manager'] = $app->share(function($app) {
     return new AccessDecisionManager($app['security.voters'], 'unanimous');
 });*/
@@ -249,6 +260,7 @@ if (isset($app['configuration']['main_database'])) {
         $dbPort = $hostParts[1];
         $host = str_replace(':'.$dbPort, '', $app['configuration']['db_host']);
     }
+
     $defaultDatabaseOptions = array(
         'db_read' => array(
             'driver' => $dbDriver,
@@ -722,35 +734,3 @@ $app['upgrade.controller'] = $app->share(
     }
 );
 
-
-// Ministerio
-
-$app['branch.controller'] = $app->share(
-    function () use ($app) {
-        return new ChamiloLMS\Controller\Admin\Administrator\BranchController($app);
-    }
-);
-
-$app['branch_director.controller'] = $app->share(
-    function () use ($app) {
-        return new ChamiloLMS\Controller\Admin\Director\BranchDirectorController($app);
-    }
-);
-
-$app['jury.controller'] = $app->share(
-    function () use ($app) {
-        return new ChamiloLMS\Controller\Admin\Administrator\JuryController($app);
-    }
-);
-
-$app['jury_president.controller'] = $app->share(
-    function () use ($app) {
-        return new ChamiloLMS\Controller\Admin\JuryPresident\JuryPresidentController($app);
-    }
-);
-
-$app['jury_member.controller'] = $app->share(
-    function () use ($app) {
-        return new ChamiloLMS\Controller\Admin\JuryMember\JuryMemberController($app);
-    }
-);

+ 0 - 264
main/install/country_data.csv

@@ -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,

+ 2 - 5
main/install/index.php

@@ -32,9 +32,7 @@ $app['sys_course_path'] = isset($_configuration['sys_course_path']) ? $_configur
 $app['sys_log_path'] = isset($_configuration['sys_log_path']) ? $_configuration['sys_log_path'] : $app['root_sys'].'logs/';
 $app['sys_temp_path'] = isset($_configuration['sys_temp_path']) ? $_configuration['sys_temp_path'] : $app['sys_data_path'].'temp/';
 
-
 // Registering services
-
 $app['debug'] = false;
 $app->register(new Silex\Provider\UrlGeneratorServiceProvider());
 $app->register(new Silex\Provider\FormServiceProvider());
@@ -47,7 +45,6 @@ $app['translator'] = $app->share($app->extend('translator', function($translator
     $file = 'main/locale/'.$locale.'.po';
     $translator->addResource('pofile', $file, $locale);*/
 
-
     /*$translator->addLoader('yaml', new Symfony\Component\Translation\Loader\YamlFileLoader());
     $translator->addResource('yaml', __DIR__.'/lang/fr.yml', 'fr');
     $translator->addResource('yaml', __DIR__.'/lang/en.yml', 'en');
@@ -55,8 +52,6 @@ $app['translator'] = $app->share($app->extend('translator', function($translator
     return $translator;
 }));
 
-//$app->register(new Whoops\Provider\Silex\WhoopsServiceProvider);
-
 $app->register(
     new Silex\Provider\TwigServiceProvider(),
     array(
@@ -136,6 +131,8 @@ $blockInstallation = function() use($app) {
 // Controllers
 
 $app->match('/', function() use($app) {
+    // in order to get a list of countries
+    //var_dump(Symfony\Component\Intl\Intl::getRegionBundle()->getCountryNames());
     $languages = array(
         'english' => 'english',
         'spanish' =>  'spanish',

+ 0 - 66
main/install/install.lib.php

@@ -11,46 +11,9 @@
  */
 
 /* CONSTANTS */
-
-//define('SYSTEM_MAIN_DATABASE_FILE', $new_version.'/db_main.sql');
-define('COUNTRY_DATA_FILENAME', 'country_data.csv');
 define('COURSES_HTACCESS_FILENAME', 'htaccess.dist');
 define('SYSTEM_CONFIG_FILENAME', 'configuration.dist.php');
 
-/*      COMMON PURPOSE FUNCTIONS    */
-
-/**
- * This function detects whether the system has been already installed.
- * It should be used for prevention from second running the installation
- * script and as a result - destroying a production system.
- * @return bool     The detected result;
- * @author Ivan Tcholakov, 2010;
- */
-function is_already_installed_system()
-{
-    global $new_version, $_configuration;
-
-    if (empty($new_version)) {
-        return true; // Must be initialized.
-    }
-
-    if (empty($_configuration)) {
-        return false;
-    }
-
-    $current_version = null;
-
-    if (isset($_configuration['dokeos_version'])) {
-        $current_version = trim($_configuration['dokeos_version']);
-    }
-    if (empty($current_version)) {
-        $current_version = trim($_configuration['system_version']);
-    }
-
-    // If the current version is old, upgrading is assumed, the installer goes ahead.
-    return empty($current_version) ? false : version_compare($current_version, $new_version, '>=');
-}
-
 /**
  * This function checks if a php extension exists or not and returns an HTML status string.
  *
@@ -272,16 +235,6 @@ function file_to_array($filename)
     return explode('<br />', nl2br($buffer));
 }
 
-/**
- * We assume this function is called from install scripts that reside inside the install folder.
- */
-function set_file_folder_permissions()
-{
-    @chmod('.', 0755); //set permissions on install dir
-    @chmod('..', 0755); //set permissions on parent dir of install dir
-    @chmod('country_data.csv.csv', 0755);
-}
-
 /**
  * Add's a .htaccess file to the courses directory
  * @param string $url_append The path from your webroot to your chamilo root
@@ -567,25 +520,6 @@ function testDatabaseConnect($dbHostForm, $dbUsernameForm, $dbPassForm, $singleD
 
 }
 
-/**
- * Fills the countries table with a list of countries.
- */
-function fill_track_countries_table($track_countries_table)
-{
-    $file_path = dirname(__FILE__).'/'.COUNTRY_DATA_FILENAME;
-    $countries = file($file_path);
-    $add_country_sql = "INSERT INTO $track_countries_table (id, code, country, counter) VALUES ";
-    foreach ($countries as $line) {
-        $elems = explode(',', $line);
-        $add_country_sql .= '('.intval($elems[0]).',\''.Database::escape_string(
-            $elems[1]
-        ).'\',\''.Database::escape_string($elems[2]).'\','.intval($elems[3]).'),';
-    }
-    $add_country_sql = substr($add_country_sql, 0, -1);
-    //$add_country_sql = "LOAD DATA INFILE '".Database::escape_string($file_path)."' INTO TABLE $track_countries_table FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\'';";
-    @ Database::query($add_country_sql);
-}
-
 /**
  * Creates the structure of the main database and fills it
  * with data. Placeholder symbols in the main database file

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

@@ -1,135 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-/**
- *	Install the Chamilo database
- *	Notice : This script has to be included by index.php
- *
- *	@package chamilo.install
- */
-
-/* This page is called only during a NEW chamilo installation */
-/* This page can only be access through including from the install script.  */
-/**
- * Init checks
- */
-if (!defined('SYSTEM_INSTALLATION')) {
-	echo 'You are not allowed here!';
-	exit;
-}
-
-$urlForm = api_add_trailing_slash($urlForm);
-
-switch ($encryptPassForm) {
-    case 'md5':
-        $passToStore = md5($passForm);
-		break;
-    case 'sha1':
-        $passToStore = sha1($passForm);
-        break;
-    case 'none':
-        $passToStore = $passForm;
-        break;
-}
-
-$dbPrefixForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbPrefixForm);
-
-$dbNameForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbNameForm);
-if (!empty($dbPrefixForm) && strpos($dbNameForm, $dbPrefixForm) !== 0) {
-	$dbNameForm = $dbPrefixForm.$dbNameForm;
-}
-
-$dbStatsForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbStatsForm);
-if (!empty($dbPrefixForm) && strpos($dbStatsForm, $dbPrefixForm) !== 0) {
-	$dbStatsForm = $dbPrefixForm.$dbStatsForm;
-}
-
-$dbUserForm = preg_replace('/[^a-zA-Z0-9_\-]/', '', $dbUserForm);
-if (!empty($dbPrefixForm) && strpos($dbUserForm, $dbPrefixForm) !== 0) {
-	$dbUserForm = $dbPrefixForm.$dbUserForm;
-}
-
-$mysqlMainDb = $dbNameForm;
-if (empty($mysqlMainDb) || $mysqlMainDb == 'mysql' || $mysqlMainDb == $dbPrefixForm) {
-	$mysqlMainDb = $dbPrefixForm.'main';
-}
-
-$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')) {
-
-	$result = Database::query("SHOW VARIABLES LIKE 'datadir'") or die(Database::error());
-
-	$mysqlRepositorySys = Database::fetch_array($result);
-	$mysqlRepositorySys = $mysqlRepositorySys['Value'];
-
-	$create_database = true;
-
-	if (database_exists($mysqlMainDb)) {
-        $create_database = false;
-    }
-	// Create database.
-	if ($create_database) {
-        $charset_clause = ' DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci';
-		$sql = "CREATE DATABASE IF NOT EXISTS `$mysqlMainDb` $charset_clause";
-		Database::query($sql) or die(Database::error());
-	}
-}
-
-$mysqlStatsDb = $mysqlMainDb;
-$mysqlUserDb = $mysqlMainDb;
-
-// This parameter is needed to run a command line install of Chamilo (needed for Phing)
-if (!defined('CLI_INSTALLATION')) {
-	include api_get_path(SYS_LANG_PATH).'english/create_course.inc.php';
-
-	if ($languageForm != 'english') {
-		include api_get_path(SYS_LANG_PATH).$languageForm.'/create_course.inc.php';
-	}
-}
-
-iDatabase::select_db($mysqlMainDb) or die(Database::error());
-
-$installation_settings = array();
-$installation_settings['{ORGANISATIONNAME}']                = $institutionForm;
-$installation_settings['{ORGANISATIONURL}']                 = $institutionUrlForm;
-$installation_settings['{CAMPUSNAME}']                      = $campusForm;
-$installation_settings['{PLATFORMLANGUAGE}']                = $languageForm;
-$installation_settings['{ALLOWSELFREGISTRATION}']           = true_false($allowSelfReg);
-$installation_settings['{ALLOWTEACHERSELFREGISTRATION}']    = true_false($allowSelfRegProf);
-$installation_settings['{ADMINLASTNAME}']                   = $adminLastName;
-$installation_settings['{ADMINFIRSTNAME}']                  = $adminFirstName;
-$installation_settings['{ADMINLOGIN}']                      = $loginForm;
-$installation_settings['{ADMINPASSWORD}']                   = $passToStore;
-$installation_settings['{ADMINEMAIL}']                      = $emailForm;
-$installation_settings['{ADMINPHONE}']                      = $adminPhoneForm;
-$installation_settings['{PLATFORM_AUTH_SOURCE}']            = PLATFORM_AUTH_SOURCE;
-$installation_settings['{ADMINLANGUAGE}']                   = $languageForm;
-$installation_settings['{HASHFUNCTIONMODE}']                = $encryptPassForm;
-
-load_main_database($installation_settings);
-
-$app['monolog']->addInfo("drop_course_tables");
-drop_course_tables();
-
-$app['monolog']->addInfo("create_course_tables");
-load_database_script($new_version.'/db_course.sql');
-
-$track_countries_table = "track_c_countries";
-
-$app['monolog']->addInfo("fill_track_countries_table");
-fill_track_countries_table($track_countries_table);
-
-$app['monolog']->addInfo("locking_settings");
-
-locking_settings();
-
-update_dir_and_files_permissions();

+ 0 - 36
main/install/install_files.inc.php

@@ -1,36 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Install the Chamilo files
- * Notice : This script has to be included by install/index.php
- *
- * The script creates two files:
- * - configuration.php, the file that contains very important info for Chamilo
- *   such as the database names.
- * - .htaccess file (in the courses directory) that is optional but improves
- *   security
- *
- * @package chamilo.install
- */
-
-if (defined('SYSTEM_INSTALLATION')) {
-
-	// Write the system config file
-	// write_system_config_file(api_get_path(CONFIGURATION_PATH).'configuration.php');
-
-    write_system_config_file(api_get_path(SYS_CONFIG_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 distribution files with renaming for being the actual system configuration files.
-	copy(api_get_path(SYS_CONFIG_PATH).'mail.conf.dist.php', api_get_path(SYS_CONFIG_PATH).'mail.conf.php');
-	copy(api_get_path(SYS_CONFIG_PATH).'profile.conf.dist.php', api_get_path(SYS_CONFIG_PATH).'profile.conf.php');
-    copy(api_get_path(SYS_CONFIG_PATH).'events.conf.dist.php', api_get_path(SYS_CONFIG_PATH).'events.conf.php');
-    copy(api_get_path(SYS_CONFIG_PATH).'auth.conf.dist.php', api_get_path(SYS_CONFIG_PATH).'auth.conf.php');
-	copy(api_get_path(SYS_CONFIG_PATH).'portfolio.conf.dist.php', api_get_path(SYS_CONFIG_PATH).'portfolio.conf.php');
-}

+ 0 - 65
main/install/migrate-db-1.6.x-1.8.0-post.sql

@@ -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;

+ 0 - 315
main/install/migrate-db-1.6.x-1.8.0-pre.sql

@@ -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 datetitme 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 DEFAULT '',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');

+ 0 - 78
main/install/migrate-db-1.8.0-1.8.2-pre.sql

@@ -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';

+ 0 - 25
main/install/migrate-db-1.8.2-1.8.3-pre.sql

@@ -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

+ 0 - 37
main/install/migrate-db-1.8.3-1.8.4-pre.sql

@@ -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 '';

+ 0 - 159
main/install/migrate-db-1.8.4-1.8.5-pre.sql

@@ -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 '';

+ 0 - 231
main/install/migrate-db-1.8.5-1.8.6-pre.sql

@@ -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;

+ 0 - 65
main/install/migrate-db-1.8.6-1.8.6.1-pre.sql

@@ -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';

+ 0 - 21
main/install/migrate-db-1.8.6.1-1.8.6.2-post.sql

@@ -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

+ 0 - 149
main/install/migrate-db-1.8.6.1-1.8.6.2-pre.sql

@@ -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;

+ 0 - 38
main/install/migrate-db-1.8.6.2-1.8.7-post.sql

@@ -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 '';

+ 0 - 154
main/install/migrate-db-1.8.6.2-1.8.7-pre.sql

@@ -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;

+ 0 - 231
main/install/migrate-db-1.8.7-1.8.8-pre.sql

@@ -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 ('&#2361;&#2367;&#2344;&#2381;&#2342;&#2368;', '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));
-

+ 0 - 344
main/install/migrate-db-1.8.8-1.9.0-pre.sql

@@ -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 ('&#2476;&#2494;&#2434;&#2482;&#2494;','bengali','bn','bengali',0), ('&#1575;&#1604;&#1589;&#1608;&#1605;&#1575;&#1604;&#1610;&#1577;','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 '';

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 0 - 140
main/install/migrate-db-1.8.8-1.9.0-pre.sql.optimized


+ 0 - 71
main/install/update-configuration.inc.php

@@ -1,71 +0,0 @@
-<?php
-
-/* For licensing terms, see /license.txt */
-/**
- *
- * Chamilo LMS
- *
- * Only updates the  main/inc/conf/configuration.php  file with the new version use only from 1.8.8.1 to 1.8.8.2 (with no DB changes)
- * @package chamilo.install
- */
-
-use Symfony\Component\Yaml\Dumper;
-
-if (defined('SYSTEM_INSTALLATION')) {
-
-    $app['monolog']->addInfo("Starting " . basename(__FILE__));
-
-    //Creating app/config/configuration.yml
-    global $_configuration;
-
-    $_configuration['system_version'] = $new_version;
-    $_configuration['system_stable'] = $new_version_stable ? 'true' : 'false';
-    $_configuration['software_name'] = isset($software_name) ? $software_name : 'chamilo';
-    $_configuration['software_url'] = isset($software_url) ? $software_url : 'chamilo';
-    $_configuration['password_encryption'] = isset($userPasswordCrypted) ? $userPasswordCrypted : $_configuration['password_encryption'];
-
-    $dumper = new Dumper();
-
-    //removing useless indexes before saving in the configuration file
-
-    unset($_configuration['dokeos_version']);
-    unset($_configuration['dokeos_stable']);
-    unset($_configuration['code_append']);
-    unset($_configuration['course_folder']);
-
-    $yaml = $dumper->dump($_configuration, 2); //inline
-    $newConfigurationFile = api_get_path(SYS_CONFIG_PATH).'configuration.yml';
-    file_put_contents($newConfigurationFile, $yaml);
-
-    //Moving files in app/config
-
-    if (file_exists(api_get_path(CONFIGURATION_PATH).'mail.conf.php')) {
-        copy(api_get_path(CONFIGURATION_PATH).'mail.conf.php', api_get_path(SYS_CONFIG_PATH).'mail.conf.php');
-        unlink(api_get_path(CONFIGURATION_PATH).'mail.conf.php');
-    }
-
-    if (file_exists(api_get_path(CONFIGURATION_PATH).'auth.conf.php')) {
-        copy(api_get_path(CONFIGURATION_PATH).'auth.conf.php', api_get_path(SYS_CONFIG_PATH).'auth.conf.php');
-        unlink(api_get_path(CONFIGURATION_PATH).'auth.conf.php');
-    }
-
-    if (file_exists(api_get_path(CONFIGURATION_PATH).'events.conf.php')) {
-        copy(api_get_path(CONFIGURATION_PATH).'events.conf.php', api_get_path(SYS_CONFIG_PATH).'events.conf.php');
-        unlink(api_get_path(CONFIGURATION_PATH).'events.conf.php');
-    }
-
-    if (file_exists(api_get_path(CONFIGURATION_PATH).'mail.conf.php')) {
-        copy(api_get_path(CONFIGURATION_PATH).'mail.conf.php', api_get_path(SYS_CONFIG_PATH).'mail.conf.php');
-        unlink(api_get_path(CONFIGURATION_PATH).'mail.conf.php');
-    }
-
-    if (file_exists(api_get_path(CONFIGURATION_PATH).'portfolio.conf.php')) {
-        copy(api_get_path(CONFIGURATION_PATH).'portfolio.conf.php', api_get_path(SYS_CONFIG_PATH).'portfolio.conf.php');
-        unlink(api_get_path(CONFIGURATION_PATH).'portfolio.conf.php');
-    }
-
-    if (file_exists(api_get_path(CONFIGURATION_PATH).'profile.conf.php')) {
-        copy(api_get_path(CONFIGURATION_PATH).'profile.conf.php', api_get_path(SYS_CONFIG_PATH).'profile.conf.php');
-        unlink(api_get_path(CONFIGURATION_PATH).'profile.conf.php');
-    }
-}

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

@@ -1,536 +0,0 @@
-<?php
-
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Dokeos version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE `$dbNameForm`.`cours`
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-
-// Check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-    // Check if the current Dokeos install is eligible for update
-    if (empty($updateFromConfigFile) || !file_exists($_POST['updatePath'] . $updateFromConfigFile) || !in_array(get_config_param('clarolineVersion'), $update_from_version_6)) {
-
-        echo '<strong>' . get_lang('Error') . ' !</strong> Dokeos ' . implode('|', $updateFromVersion) . ' ' . get_lang('HasNotBeenFound') . '.<br /><br />
-								' . get_lang('PleasGoBackToStep1') . '.
-							    <p><button type="submit" class="back" name="step1" value="&lt; ' . get_lang('Back') . '">' . get_lang('Back') . '</button></p>
-							    </td></tr></table></form></body></html>';
-        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 '../lang/english/create_course.inc.php';
-
-        if ($languageForm != 'english') {
-            // languageForm has been escaped in index.php
-            include '../lang/' . $languageForm . '/create_course.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__;
-}

+ 0 - 211
main/install/update-db-1.8.0-1.8.2.inc.php

@@ -1,211 +0,0 @@
-<?php
-
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Dokeos version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE `$dbNameForm`.`cours`
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-
-// Check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-    // Check if the current Dokeos install is eligible for update
-    if (!file_exists('../inc/conf/configuration.php')) {
-        echo '<strong>' . get_lang('Error') . ' !</strong> Dokeos ' . implode('|', $updateFromVersion) . ' ' . get_lang('HasNotBeenFound') . '.<br /><br />
-								' . get_lang('PleasGoBackToStep1') . '.
-							    <p><button type="submit" class="back" name="step1" value="&lt; ' . get_lang('Back') . '">' . get_lang('Back') . '</button></p>
-							    </td></tr></table></form></body></html>';
-        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 '../lang/english/create_course.inc.php';
-
-        if ($languageForm != 'english') {
-            //languageForm has been escaped in index.php
-            include '../lang/' . $languageForm . '/create_course.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']);
-                    }
-                    $app['monolog']->addInfo('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__;
-}

+ 0 - 210
main/install/update-db-1.8.2-1.8.3.inc.php

@@ -1,210 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Dokeos version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE `$dbNameForm`.`cours`
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-
-// Check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-	// Check if the current Dokeos install is eligible for update
-	if (!file_exists('../inc/conf/configuration.php')) {
-		echo '<strong>'.get_lang('Error').' !</strong> Dokeos '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.<br /><br />
-								'.get_lang('PleasGoBackToStep1').'.
-							    <p><button type="submit" class="back" name="step1" value="&lt; '.get_lang('Back').'">'.get_lang('Back').'</button></p>
-							    </td></tr></table></form></body></html>';
-		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 '../lang/english/create_course.inc.php';
-
-		if ($languageForm != 'english') {
-			// languageForm has been escaped in index.php
-			include '../lang/'.$languageForm.'/create_course.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']);
-					}
-                    
-					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__;
-
-}

+ 0 - 263
main/install/update-db-1.8.3-1.8.4.inc.php

@@ -1,263 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Dokeos version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE `$dbNameForm`.`cours`
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-
-// Check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-	// Check if the current Dokeos install is eligible for update
-	if (!file_exists('../inc/conf/configuration.php')) {
-		echo '<strong>'.get_lang('Error').' !</strong> Dokeos '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.<br /><br />
-								'.get_lang('PleasGoBackToStep1').'.
-							    <p><button type="submit" class="back" name="step1" value="&lt; '.get_lang('Back').'">'.get_lang('Back').'</button></p>
-							    </td></tr></table></form></body></html>';
-		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 '../lang/english/create_course.inc.php';
-
-		if ($languageForm != 'english') {
-			// languageForm has been escaped in index.php
-			include '../lang/'.$languageForm.'/create_course.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']);
-					}
-                    
-					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__;
-
-}

+ 0 - 281
main/install/update-db-1.8.4-1.8.5.inc.php

@@ -1,281 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Dokeos version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE `$dbNameForm`.`cours`
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-$old_file_version = '1.8.4';
-$new_file_version = '1.8.5';
-
-// Check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-	// Check if the current Dokeos install is eligible for update
-	if (!file_exists('../inc/conf/configuration.php')) {
-		echo '<strong>'.get_lang('Error').' !</strong> Dokeos '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.<br /><br />
-								'.get_lang('PleasGoBackToStep1').'.
-							    <p><button type="submit" class="back" name="step1" value="&lt; '.get_lang('Back').'">'.get_lang('Back').'</button></p>
-							    </td></tr></table></form></body></html>';
-		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 '../lang/english/create_course.inc.php';
-
-		if ($languageForm != 'english') {
-			// languageForm has been escaped in index.php
-			include '../lang/'.$languageForm.'/create_course.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']);
-					}
-                    $app['monolog']->addInfo('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."<br />";
-								if ($myres2 !== false) {
-									$mysql3 = "UPDATE $mytable SET min_score = 0 WHERE id = '".$myrow['id']."'";
-									$myres3 = Database::query($mysql3);
-									//echo $mysql3."<br />";
-								}
-							}
-						}
-					}
-
-					// 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__;
-
-}

+ 0 - 1147
main/install/update-db-1.8.5-1.8.6.inc.php

@@ -1,1147 +0,0 @@
-<?php
-
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Dokeos version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE `$dbNameForm`.`cours`
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-$app['monolog']->addInfo('Entering file');
-
-$old_file_version = '1.8.5';
-$new_file_version = '1.8.6';
-
-// Check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-    // Check if the current Dokeos install is eligible for update
-    if (!file_exists('../inc/conf/configuration.php')) {
-        echo '<strong>' . get_lang('Error') . ' !</strong> Dokeos ' . implode('|', $updateFromVersion) . ' ' . get_lang('HasNotBeenFound') . '.<br /><br />
-								' . get_lang('PleasGoBackToStep1') . '.
-							    <p><button type="submit" class="back" name="step1" value="&lt; ' . get_lang('Back') . '">' . get_lang('Back') . '</button></p>
-							    </td></tr></table></form></body></html>';
-        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 '../lang/english/create_course.inc.php';
-
-        if ($languageForm != 'english') {
-            // languageForm has been escaped in index.php
-            include '../lang/' . $languageForm . '/create_course.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) {
-                $app['monolog']->addError('Database name ' . $dbNameForm . ' is too long, skipping');
-            } elseif (!in_array($dbNameForm, $dblist)) {
-                $app['monolog']->addError('Database ' . $dbNameForm . ' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbNameForm);
-                foreach ($m_q_list as $query) {
-                    if ($only_test) {
-                        $app['monolog']->addInfo("iDatabase::query($dbNameForm,$query)");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($log) {
-                            $app['monolog']->addInfo("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\', \'
-		<head>
-		            	{CSS}
-		            	<style type="text/css">
-		            	.gris_title         	{
-		            		color: silver;
-		            	}
-		            	h1
-		            	{
-		            		text-align: right;
-		            	}
-						</style>
-
-		            </head>
-		            <body>
-					<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-					<tbody>
-					<tr>
-					<td style="vertical-align: middle; width: 50%;" colspan="1" rowspan="1">
-						<h1>TITULUS 1<br />
-						<span class="gris_title">TITULUS 2</span><br />
-						</h1>
-					</td>
-					<td style="width: 50%;">
-						<img alt="Chamilo logo" src="{COURSE_DIR}images/logo_chamilo.png"></td>
-					</tr>
-					</tbody>
-					</table>
-					<p><br />
-					<br />
-					</p>
-					</body>
-		\');';
-        $res = iDatabase::query($sql);
-
-        /*
-          $sql = 'INSERT INTO '.$dbNameForm.'.system_template (title, comment, image, content) VALUES
-          (\'TemplateTitleCheckList\', \'TemplateTitleCheckListDescription\', \'checklist.gif\', \'
-          <head>
-          {CSS}
-          </head>
-          <body>
-          <table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-          <tbody>
-          <tr>
-          <td style="vertical-align: top; width: 66%;">
-          <h3>Lorem ipsum dolor sit amet</h3>
-          <ul>
-          <li>consectetur adipisicing elit</li>
-          <li>sed do eiusmod tempor incididunt</li>
-          <li>ut labore et dolore magna aliqua</li>
-          </ul>
-
-          <h3>Ut enim ad minim veniam</h3>
-          <ul>
-          <li>quis nostrud exercitation ullamco</li>
-          <li>laboris nisi ut aliquip ex ea commodo consequat</li>
-          <li>Excepteur sint occaecat cupidatat non proident</li>
-          </ul>
-
-          <h3>Sed ut perspiciatis unde omnis</h3>
-          <ul>
-          <li>iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam</li>
-          <li>eaque ipsa quae ab illo inventore veritatis</li>
-          <li>et quasi architecto beatae vitae dicta sunt explicabo.&nbsp;</li>
-          </ul>
-
-          </td>
-          <td style="background: transparent url({IMG_DIR}postit.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; width: 33%; text-align: center; vertical-align: bottom;">
-          <h3>Ut enim ad minima</h3>
-          Veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur.<br />
-          <h3>
-          <img style="width: 180px; height: 144px;" alt="trainer" src="{COURSE_DIR}images/trainer/trainer_smile.png "><br /></h3>
-          </td>
-          </tr>
-          </tbody>
-          </table>
-          <p><br />
-          <br />
-          </p>
-          </body>
-          \');';
-
-          $res = iDatabase::query($sql);
-         */
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleTeacher\', \'TemplateTitleTeacherDescription\', \'yourinstructor.gif\', \'
-		<head>
-		                   {CSS}
-		                   <style type="text/css">
-			            	.text
-			            	{
-			            		font-weight: normal;
-			            	}
-							</style>
-		                </head>
-		                <body>
-							<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-							<tbody>
-							<tr>
-							<td></td>
-							<td style="height: 33%;"></td>
-							<td></td>
-							</tr>
-							<tr>
-							<td style="width: 25%;"></td>
-							<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 33%; text-align: right; font-weight: bold;" colspan="1" rowspan="1">
-							<span class="text">
-							<br />
-							Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis pellentesque.</span>
-							</td>
-							<td style="width: 25%; font-weight: bold;">
-							<img style="width: 180px; height: 241px;" alt="trainer" src="{COURSE_DIR}images/trainer/trainer_case.png "></td>
-							</tr>
-							</tbody>
-							</table>
-							<p><br />
-							<br />
-							</p>
-						</body>
-		\');
-		';
-        $res = iDatabase::query($sql);
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleLeftList\', \'TemplateTitleListLeftListDescription\', \'leftlist.gif\', \'
-		<head>
-			           {CSS}
-			       </head>
-				    <body>
-						<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-						<tbody>
-						<tr>
-						<td style="width: 66%;"></td>
-						<td style="vertical-align: bottom; width: 33%;" colspan="1" rowspan="4">&nbsp;<img style="width: 180px; height: 248px;" alt="trainer" src="{COURSE_DIR}images/trainer/trainer_reads.png "><br />
-						</td>
-						</tr>
-						<tr align="right">
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 66%;">Lorem
-						ipsum dolor sit amet.
-						</td>
-						</tr>
-						<tr align="right">
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 66%;">
-						Vivamus
-						a quam.&nbsp;<br />
-						</td>
-						</tr>
-						<tr align="right">
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 66%;">
-						Proin
-						a est stibulum ante ipsum.</td>
-						</tr>
-						</tbody>
-						</table>
-					<p><br />
-					<br />
-					</p>
-					</body>
-		\');';
-        $res = iDatabase::query($sql);
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleLeftRightList\', \'TemplateTitleLeftRightListDescription\', \'leftrightlist.gif\', \'
-
-		<head>
-			           {CSS}
-				    </head>
-					<body>
-						<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; height: 400px; width: 720px;" border="0" cellpadding="15" cellspacing="6">
-						<tbody>
-						<tr>
-						<td></td>
-						<td style="vertical-align: top;" colspan="1" rowspan="4">&nbsp;<img style="width: 180px; height: 294px;" alt="Trainer" src="{COURSE_DIR}images/trainer/trainer_join_hands.png "><br />
-						</td>
-						<td></td>
-						</tr>
-						<tr>
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 33%; text-align: right;">Lorem
-						ipsum dolor sit amet.
-						</td>
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 33%; text-align: left;">
-						Convallis
-						ut.&nbsp;Cras dui magna.</td>
-						</tr>
-						<tr>
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 33%; text-align: right;">
-						Vivamus
-						a quam.&nbsp;<br />
-						</td>
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 33%; text-align: left;">
-						Etiam
-						lacinia stibulum ante.<br />
-						</td>
-						</tr>
-						<tr>
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 33%; text-align: right;">
-						Proin
-						a est stibulum ante ipsum.</td>
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 33%; text-align: left;">
-						Consectetuer
-						adipiscing elit. <br />
-						</td>
-						</tr>
-						</tbody>
-						</table>
-					<p><br />
-					<br />
-					</p>
-					</body>
-
-		\');';
-        $res = iDatabase::query($sql);
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleRightList\', \'TemplateTitleRightListDescription\', \'rightlist.gif\', \'
-			<head>
-			           {CSS}
-				    </head>
-				    <body style="direction: ltr;">
-						<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-						<tbody>
-						<tr>
-						<td style="vertical-align: bottom; width: 50%;" colspan="1" rowspan="4"><img style="width: 300px; height: 199px;" alt="trainer" src="{COURSE_DIR}images/trainer/trainer_points_right.png"><br />
-						</td>
-						<td style="width: 50%;"></td>
-						</tr>
-						<tr>
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; text-align: left; width: 50%;">
-						Convallis
-						ut.&nbsp;Cras dui magna.</td>
-						</tr>
-						<tr>
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; text-align: left; width: 50%;">
-						Etiam
-						lacinia.<br />
-						</td>
-						</tr>
-						<tr>
-						<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; text-align: left; width: 50%;">
-						Consectetuer
-						adipiscing elit. <br />
-						</td>
-						</tr>
-						</tbody>
-						</table>
-					<p><br />
-					<br />
-					</p>
-					</body>
-		\');';
-        $res = iDatabase::query($sql);
-
-        /*
-          $sql = 'INSERT INTO '.$dbNameForm.'.system_template (title, comment, image, content) VALUES
-          (\'TemplateTitleComparison\', \'TemplateTitleComparisonDescription\', \'compare.gif\', \'
-          <head>
-          {CSS}
-          </head>
-
-          <body>
-          <table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-          <tr>
-          <td style="height: 10%; width: 33%;"></td>
-          <td style="vertical-align: top; width: 33%;" colspan="1" rowspan="2">&nbsp;<img style="width: 180px; height: 271px;" alt="trainer" src="{COURSE_DIR}images/trainer/trainer_standing.png "><br />
-          </td>
-          <td style="height: 10%; width: 33%;"></td>
-          </tr>
-          <tr>
-          <td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 33%; text-align: right;">
-          Lorem ipsum dolor sit amet.
-          </td>
-          <td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; text-align: left; width: 33%;">
-          Convallis
-          ut.&nbsp;Cras dui magna.</td>
-          </tr>
-          </body>
-          \');';
-          $res = iDatabase::query($sql);
-         */
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleDiagram\', \'TemplateTitleDiagramDescription\', \'diagram.gif\', \'
-			<head>
-			                   {CSS}
-						    </head>
-
-							<body>
-							<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-							<tbody>
-							<tr>
-							<td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; text-align: left; height: 33%; width: 33%;">
-							<br />
-							Etiam
-							lacinia stibulum ante.
-							Convallis
-							ut.&nbsp;Cras dui magna.</td>
-							<td colspan="1" rowspan="3">
-								<img style="width: 350px; height: 267px;" alt="Alaska chart" src="{COURSE_DIR}images/diagrams/alaska_chart.png "></td>
-							</tr>
-							<tr>
-							<td colspan="1" rowspan="1">
-							<img style="width: 300px; height: 199px;" alt="trainer" src="{COURSE_DIR}images/trainer/trainer_points_right.png "></td>
-							</tr>
-							<tr>
-							</tr>
-							</tbody>
-							</table>
-							<p><br />
-							<br />
-							</p>
-							</body>
-		\');
-		';
-        $res = iDatabase::query($sql);
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleDesc\', \'TemplateTitleCheckListDescription\', \'description.gif\', \'
-		<head>
-			                   {CSS}
-						    </head>
-							<body>
-								<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-								<tbody>
-								<tr>
-								<td style="width: 50%; vertical-align: top;">
-									<img style="width: 48px; height: 49px; float: left;" alt="01" src="{COURSE_DIR}images/small/01.png " hspace="5"><br />Lorem ipsum dolor sit amet<br /><br /><br />
-									<img style="width: 48px; height: 49px; float: left;" alt="02" src="{COURSE_DIR}images/small/02.png " hspace="5">
-									<br />Ut enim ad minim veniam<br /><br /><br />
-									<img style="width: 48px; height: 49px; float: left;" alt="03" src="{COURSE_DIR}images/small/03.png " hspace="5">Duis aute irure dolor in reprehenderit<br /><br /><br />
-									<img style="width: 48px; height: 49px; float: left;" alt="04" src="{COURSE_DIR}images/small/04.png " hspace="5">Neque porro quisquam est</td>
-
-								<td style="vertical-align: top; width: 50%; text-align: right;" colspan="1" rowspan="1">
-									<img style="width: 300px; height: 291px;" alt="Gearbox" src="{COURSE_DIR}images/diagrams/gearbox.jpg "><br /></td>
-								</tr><tr></tr>
-								</tbody>
-								</table>
-								<p><br />
-								<br />
-								</p>
-							</body>
-		\');
-		';
-        $res = iDatabase::query($sql);
-
-        /*
-          $sql = 'INSERT INTO '.$dbNameForm.'.system_template (title, comment, image, content) VALUES
-          (\'TemplateTitleObjectives\', \'TemplateTitleObjectivesDescription\', \'courseobjectives.gif\', \'
-          <head>
-          {CSS}
-          </head>
-
-          <body>
-          <table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-          <tbody>
-          <tr>
-          <td style="vertical-align: bottom; width: 33%;" colspan="1" rowspan="2">
-          <img style="width: 180px; height: 271px;" alt="trainer" src="{COURSE_DIR}images/trainer/trainer_chair.png "><br />
-          </td>
-          <td style="height: 10%; width: 66%;"></td>
-          </tr>
-          <tr>
-          <td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; text-align: left; width: 66%;">
-          <h3>Lorem ipsum dolor sit amet</h3>
-          <ul>
-          <li>consectetur adipisicing elit</li>
-          <li>sed do eiusmod tempor incididunt</li>
-          <li>ut labore et dolore magna aliqua</li>
-          </ul>
-          <h3>Ut enim ad minim veniam</h3>
-          <ul>
-          <li>quis nostrud exercitation ullamco</li>
-          <li>laboris nisi ut aliquip ex ea commodo consequat</li>
-          <li>Excepteur sint occaecat cupidatat non proident</li>
-          </ul>
-          </td>
-          </tr>
-          </tbody>
-          </table>
-          <p><br />
-          <br />
-          </p>
-          </body>
-          \');';
-          $res = iDatabase::query($sql);
-         */
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleCycle\', \'TemplateTitleCycleDescription\', \'cyclechart.gif\', \'
-		<head>
-			               {CSS}
-			               <style>
-			               .title
-			               {
-			               	color: white; font-weight: bold;
-			               }
-			               </style>
-					    </head>
-
-
-					    <body>
-						<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="8" cellspacing="6">
-						<tbody>
-						<tr>
-							<td style="text-align: center; vertical-align: bottom; height: 10%;" colspan="3" rowspan="1">
-								<img style="width: 250px; height: 76px;" alt="arrow" src="{COURSE_DIR}images/diagrams/top_arrow.png ">
-							</td>
-						</tr>
-						<tr>
-							<td style="height: 5%; width: 45%; vertical-align: top; background-color: rgb(153, 153, 153); text-align: center;">
-								<span class="title">Lorem ipsum</span>
-							</td>
-
-							<td style="height: 5%; width: 10%;"></td>
-							<td style="height: 5%; vertical-align: top; background-color: rgb(153, 153, 153); text-align: center;">
-								<span class="title">Sed ut perspiciatis</span>
-							</td>
-						</tr>
-							<tr>
-								<td style="background-color: rgb(204, 204, 255); width: 45%; vertical-align: top;">
-									<ul>
-										<li>dolor sit amet</li>
-										<li>consectetur adipisicing elit</li>
-										<li>sed do eiusmod tempor&nbsp;</li>
-										<li>adipisci velit, sed quia non numquam</li>
-										<li>eius modi tempora incidunt ut labore et dolore magnam</li>
-									</ul>
-						</td>
-						<td style="width: 10%;"></td>
-						<td style="background-color: rgb(204, 204, 255); width: 45%; vertical-align: top;">
-							<ul>
-							<li>ut enim ad minim veniam</li>
-							<li>quis nostrud exercitation</li><li>ullamco laboris nisi ut</li>
-							<li> Quis autem vel eum iure reprehenderit qui in ea</li>
-							<li>voluptate velit esse quam nihil molestiae consequatur,</li>
-							</ul>
-							</td>
-							</tr>
-							<tr align="center">
-							<td style="height: 10%; vertical-align: top;" colspan="3" rowspan="1">
-							<img style="width: 250px; height: 76px;" alt="arrow" src="{COURSE_DIR}images/diagrams/bottom_arrow.png ">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;
-						</td>
-						</tr>
-						</tbody>
-						</table>
-						<p><br />
-						<br />
-						</p>
-						</body>
-		\');';
-        $res = iDatabase::query($sql);
-
-        /*
-          $sql = 'INSERT INTO '.$dbNameForm.'.system_template (title, comment, image, content) VALUES
-          (\'TemplateTitleLearnerWonder\', \'TemplateTitleLearnerWonderDescription\', \'learnerwonder.gif\', \'
-          <head>
-          {CSS}
-          </head>
-
-          <body>
-          <table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-          <tbody>
-          <tr>
-          <td style="width: 33%;" colspan="1" rowspan="4">
-          <img style="width: 120px; height: 348px;" alt="learner wonders" src="{COURSE_DIR}images/silhouette.png "><br />
-          </td>
-          <td style="width: 66%;"></td>
-          </tr>
-          <tr align="center">
-          <td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 66%;">
-          Convallis
-          ut.&nbsp;Cras dui magna.</td>
-          </tr>
-          <tr align="center">
-          <td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 66%;">
-          Etiam
-          lacinia stibulum ante.<br />
-          </td>
-          </tr>
-          <tr align="center">
-          <td style="background: transparent url({IMG_DIR}faded_grey.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 66%;">
-          Consectetuer
-          adipiscing elit. <br />
-          </td>
-          </tr>
-          </tbody>
-          </table>
-          <p><br />
-          <br />
-          </p>
-          </body>
-          \');
-          ';
-          $res = iDatabase::query($sql);
-         */
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleTimeline\', \'TemplateTitleTimelineDescription\', \'phasetimeline.gif\', \'
-		<head>
-		               {CSS}
-						<style>
-						.title
-						{
-							font-weight: bold; text-align: center;
-						}
-						</style>
-				    </head>
-
-				    <body>
-						<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="8" cellspacing="5">
-						<tbody>
-						<tr class="title">
-							<td style="vertical-align: top; height: 3%; background-color: rgb(224, 224, 224);">Lorem ipsum</td>
-							<td style="height: 3%;"></td>
-							<td style="vertical-align: top; height: 3%; background-color: rgb(237, 237, 237);">Perspiciatis</td>
-							<td style="height: 3%;"></td>
-							<td style="vertical-align: top; height: 3%; background-color: rgb(245, 245, 245);">Nemo enim</td>
-						</tr>
-
-						<tr>
-							<td style="vertical-align: top; width: 30%; background-color: rgb(224, 224, 224);">
-								<ul>
-								<li>dolor sit amet</li>
-								<li>consectetur</li>
-								<li>adipisicing elit</li>
-							</ul>
-							<br />
-							</td>
-							<td>
-								<img style="width: 32px; height: 32px;" alt="arrow" src="{COURSE_DIR}images/small/arrow.png ">
-							</td>
-
-							<td style="vertical-align: top; width: 30%; background-color: rgb(237, 237, 237);">
-								<ul>
-									<li>ut labore</li>
-									<li>et dolore</li>
-									<li>magni dolores</li>
-								</ul>
-							</td>
-							<td>
-								<img style="width: 32px; height: 32px;" alt="arrow" src="{COURSE_DIR}images/small/arrow.png ">
-							</td>
-
-							<td style="vertical-align: top; background-color: rgb(245, 245, 245); width: 30%;">
-								<ul>
-									<li>neque porro</li>
-									<li>quisquam est</li>
-									<li>qui dolorem&nbsp;&nbsp;</li>
-								</ul>
-								<br /><br />
-							</td>
-						</tr>
-						</tbody>
-						</table>
-					<p><br />
-					<br />
-					</p>
-					</body>
-		\');
-		';
-        $res = iDatabase::query($sql);
-
-        /*
-          $sql = 'INSERT INTO '.$dbNameForm.'.system_template (title, comment, image, content) VALUES
-          (\'TemplateTitleStopAndThink\', \'TemplateTitleStopAndThinkDescription\', \'stopthink.gif\', \'
-          <head>
-          {CSS}
-          </head>
-          <body>
-          <table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-          <tbody>
-          <tr>
-          <td style="vertical-align: bottom; width: 33%;" colspan="1" rowspan="2">
-          <img style="width: 180px; height: 169px;" alt="trainer" src="{COURSE_DIR}images/trainer/trainer_staring.png ">
-          <br />
-          </td>
-          <td style="height: 10%; width: 66%;"></td>
-          </tr>
-          <tr>
-          <td style="background: transparent url({IMG_DIR}postit.png ) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; width: 66%; vertical-align: middle; text-align: center;">
-          <h3>Attentio sectetur adipisicing elit</h3>
-          <ul>
-          <li>sed do eiusmod tempor incididunt</li>
-          <li>ut labore et dolore magna aliqua</li>
-          <li>quis nostrud exercitation ullamco</li>
-          </ul><br /></td>
-          </tr>
-          </tbody>
-          </table>
-          <p><br />
-          <br />
-          </p>
-          </body>
-          \');';
-          $res = iDatabase::query($sql);
-         */
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleTable\', \'TemplateTitleCheckListDescription\', \'table.gif\', \'
-		<head>
-		                   {CSS}
-		                   <style type="text/css">
-						.title
-						{
-							font-weight: bold; text-align: center;
-						}
-
-						.items
-						{
-							text-align: right;
-						}
-
-
-							</style>
-
-					    </head>
-					    <body>
-					    <br />
-					   <h2>A table</h2>
-						<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px;" border="1" cellpadding="5" cellspacing="0">
-						<tbody>
-						<tr class="title">
-							<td>City</td>
-							<td>2005</td>
-							<td>2006</td>
-							<td>2007</td>
-							<td>2008</td>
-						</tr>
-						<tr class="items">
-							<td>Lima</td>
-							<td>10,40</td>
-							<td>8,95</td>
-							<td>9,19</td>
-							<td>9,76</td>
-						</tr>
-						<tr class="items">
-						<td>New York</td>
-							<td>18,39</td>
-							<td>17,52</td>
-							<td>16,57</td>
-							<td>16,60</td>
-						</tr>
-						<tr class="items">
-						<td>Barcelona</td>
-							<td>0,10</td>
-							<td>0,10</td>
-							<td>0,05</td>
-							<td>0,05</td>
-						</tr>
-						<tr class="items">
-						<td>Paris</td>
-							<td>3,38</td>
-							<td >3,63</td>
-							<td>3,63</td>
-							<td>3,54</td>
-						</tr>
-						</tbody>
-						</table>
-						<br />
-						</body>
-		\');';
-        $res = iDatabase::query($sql);
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleAudio\', \'TemplateTitleAudioDescription\', \'audiocomment.gif\', \'
-		<head>
-		               {CSS}
-				    </head>
-		                   <body>
-							<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-							<tbody>
-							<tr>
-							<td>
-							<div align="center">
-							<span style="text-align: center;">
-								<embed  type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" width="300" height="20" bgcolor="#FFFFFF" src="{REL_PATH}main/inc/lib/mediaplayer/player.swf" allowfullscreen="false" allowscriptaccess="always" flashvars="file={COURSE_DIR}audio/ListeningComprehension.mp3&amp;autostart=true"></embed>
-		                    </span></div>
-
-							<br />
-							</td>
-							<td colspan="1" rowspan="3"><br />
-								<img style="width: 300px; height: 341px; float: right;" alt="image" src="{COURSE_DIR}images/diagrams/head_olfactory_nerve.png "><br /></td>
-							</tr>
-							<tr>
-							<td colspan="1" rowspan="1">
-								<img style="width: 180px; height: 271px;" alt="trainer" src="{COURSE_DIR}images/trainer/trainer_glasses.png"><br /></td>
-							</tr>
-							<tr>
-							</tr>
-							</tbody>
-							</table>
-							<p><br />
-							<br />
-							</p>
-							</body>
-		\');';
-        $res = iDatabase::query($sql);
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleVideo\', \'TemplateTitleVideoDescription\', \'video.gif\', \'
-		<head>
-		            	{CSS}
-					</head>
-
-					<body>
-					<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 720px; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-					<tbody>
-					<tr>
-					<td style="width: 50%; vertical-align: top;">
-
-					<div style="text-align: center;" id="player810625-parent">
-					<div style="border-style: none; overflow: hidden; width: 320px; height: 240px; background-color: rgb(220, 220, 220);">
-
-						<div id="player810625">
-							<div id="player810625-config" style="overflow: hidden; display: none; visibility: hidden; width: 0px; height: 0px;">url={REL_PATH}main/default_course_document/video/flv/example.flv width=320 height=240 loop=false play=false downloadable=false fullscreen=true displayNavigation=true displayDigits=true align=left dispPlaylist=none playlistThumbs=false</div>
-						</div>
-
-						<embed
-							type="application/x-shockwave-flash"
-							src="{REL_PATH}main/inc/lib/mediaplayer/player.swf"
-							width="320"
-							height="240"
-							id="single"
-							name="single"
-							quality="high"
-							allowfullscreen="true"
-							flashvars="width=320&height=240&autostart=false&file={REL_PATH}main/default_course_document/video/flv/example.flv&repeat=false&image=&showdownload=false&link={REL_PATH}main/default_course_document/video/flv/example.flv&showdigits=true&shownavigation=true&logo="
-						/>
-
-					</div>
-					</div>
-
-					</td>
-					<td style="background: transparent url({IMG_DIR}faded_grey.png) repeat scroll center top; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; vertical-align: top; width: 50%;">
-					<h3><br />
-					</h3>
-					<h3>Lorem ipsum dolor sit amet</h3>
-						<ul>
-						<li>consectetur adipisicing elit</li>
-						<li>sed do eiusmod tempor incididunt</li>
-						<li>ut labore et dolore magna aliqua</li>
-						</ul>
-					<h3>Ut enim ad minim veniam</h3>
-						<ul>
-						<li>quis nostrud exercitation ullamco</li>
-						<li>laboris nisi ut aliquip ex ea commodo consequat</li>
-						<li>Excepteur sint occaecat cupidatat non proident</li>
-						</ul>
-					</td>
-					</tr>
-					</tbody>
-					</table>
-					<p><br />
-					<br />
-					</p>
-					 <style type="text/css">body{}</style><!-- to fix a strange bug appearing with firefox when editing this template -->
-					</body>
-		\'); ';
-        $res = iDatabase::query($sql);
-
-        $sql = 'INSERT INTO ' . $dbNameForm . '.system_template (title, comment, image, content) VALUES
-		(\'TemplateTitleFlash\', \'TemplateTitleFlashDescription\', \'flash.gif\', \'
-		<head>
-		               {CSS}
-				    </head>
-				    <body>
-				    <center>
-						<table style="background: transparent url({IMG_DIR}faded_blue_horizontal.png ) repeat scroll 0% 50%; -moz-background-clip: initial; -moz-background-origin: initial; -moz-background-inline-policy: initial; text-align: left; width: 100%; height: 400px;" border="0" cellpadding="15" cellspacing="6">
-						<tbody>
-							<tr>
-							<td align="center">
-							<embed width="700" height="300" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" src="{COURSE_DIR}flash/SpinEchoSequence.swf" play="true" loop="true" menu="true"></embed></span><br />
-							</td>
-							</tr>
-						</tbody>
-						</table>
-						<p><br />
-						<br />
-						</p>
-					</center>
-					</body>
-		\'); ';
-        $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) {
-                $app['monolog']->addError('Database name ' . $dbStatsForm . ' is too long, skipping');
-            } elseif (!in_array($dbStatsForm, $dblist)) {
-                $app['monolog']->addError('Database ' . $dbStatsForm . ' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbStatsForm);
-                foreach ($s_q_list as $query) {
-                    if ($only_test) {
-                        $app['monolog']->addInfo("iDatabase::query($dbStatsForm,$query)");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($log) {
-                            $app['monolog']->addInfo("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) {
-                $app['monolog']->addError('Database name ' . $dbUserForm . ' is too long, skipping');
-            } elseif (!in_array($dbUserForm, $dblist)) {
-                $app['monolog']->addError('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']);
-                    }
-                    $app['monolog']->addInfo('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) {
-                            $app['monolog']->addInfo("iDatabase::query(" . $row_course['db_name'] . ",$query)");
-                        } else {
-                            $res = iDatabase::query($query);
-                            if ($log) {
-                                $app['monolog']->addInfo("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__;
-}

+ 0 - 263
main/install/update-db-1.8.6-1.8.6.1.inc.php

@@ -1,263 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Dokeos version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE `$dbNameForm`.`cours`
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-
-$old_file_version = '1.8.6';
-$new_file_version = '1.8.6.1';
-
-//check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-	// Check if the current Dokeos install is eligible for update
-	if (!file_exists('../inc/conf/configuration.php')) {
-		echo '<strong>'.get_lang('Error').' !</strong> Dokeos '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.<br /><br />
-								'.get_lang('PleasGoBackToStep1').'.
-							    <p><button type="submit" class="back" name="step1" value="&lt; '.get_lang('Back').'">'.get_lang('Back').'</button></p>
-							    </td></tr></table></form></body></html>';
-		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 '../lang/english/create_course.inc.php';
-
-		if ($languageForm != 'english') {
-			//languageForm has been escaped in index.php
-			include '../lang/'.$languageForm.'/create_course.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) {
-				 $app['monolog']->addError('Database name '.$dbNameForm.' is too long, skipping');
-			} elseif (!in_array($dbNameForm,$dblist)) {
-				 $app['monolog']->addError('Database '.$dbNameForm.' was not found, skipping');
-			} else {
-				iDatabase::select_db($dbNameForm);
-				foreach($m_q_list as $query) {
-					if ($only_test){
-						 $app['monolog']->addInfo("iDatabase::query($dbNameForm,$query)");
-					} else {
-						$res = iDatabase::query($query);
-						if ($log) {
-							 $app['monolog']->addInfo("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) {
-				 $app['monolog']->addError('Database name '.$dbStatsForm.' is too long, skipping');
-			} elseif (!in_array($dbStatsForm,$dblist)) {
-				 $app['monolog']->addError('Database '.$dbStatsForm.' was not found, skipping');
-			} else {
-				iDatabase::select_db($dbStatsForm);
-				foreach ($s_q_list as $query) {
-					if ($only_test) {
-						 $app['monolog']->addInfo("iDatabase::query($dbStatsForm,$query)");
-					} else {
-						$res = iDatabase::query($query);
-						if ($log) {
-							 $app['monolog']->addInfo("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) {
-				 $app['monolog']->addError('Database name '.$dbUserForm.' is too long, skipping');
-			} elseif (!in_array($dbUserForm, $dblist)) {
-				 $app['monolog']->addError('Database '.$dbUserForm.' was not found, skipping');
-			} else {
-				iDatabase::select_db($dbUserForm);
-				foreach ($u_q_list as $query) {
-					if ($only_test) {
-						 $app['monolog']->addInfo("iDatabase::query($dbUserForm,$query)");
-						 $app['monolog']->addInfo("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) {
-			 $app['monolog']->addError('Database name '.$dbNameForm.' is too long, skipping');
-		} elseif (!in_array($dbNameForm, $dblist)) {
-			 $app['monolog']->addError('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']);
-					}
-                    $app['monolog']->addInfo('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) {
-							 $app['monolog']->addInfo("iDatabase::query(".$row_course['db_name'].",$query)");
-						} else {
-							$res = iDatabase::query($query);
-							if ($log) {
-								 $app['monolog']->addInfo("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__;
-
-}

+ 0 - 347
main/install/update-db-1.8.6.1-1.8.6.2.inc.php

@@ -1,347 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Dokeos version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE `$dbNameForm`.`cours`
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-$old_file_version = '1.8.6.1';
-$new_file_version = '1.8.6.2';
-
-// Check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-	// Check if the current Dokeos install is eligible for update
-	if (!file_exists('../inc/conf/configuration.php')) {
-		echo '<strong>'.get_lang('Error').' !</strong> Dokeos '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.<br /><br />
-								'.get_lang('PleasGoBackToStep1').'.
-							    <p><button type="submit" class="back" name="step1" value="&lt; '.get_lang('Back').'">'.get_lang('Back').'</button></p>
-							    </td></tr></table></form></body></html>';
-		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 '../lang/english/create_course.inc.php';
-
-		if ($languageForm != 'english') {
-			// languageForm has been escaped in index.php
-			include '../lang/'.$languageForm.'/create_course.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) {
-				 $app['monolog']->addError('Database name '.$dbNameForm.' is too long, skipping');
-			} elseif (!in_array($dbNameForm,$dblist)) {
-				 $app['monolog']->addError('Database '.$dbNameForm.' was not found, skipping');
-			} else {
-				iDatabase::select_db($dbNameForm);
-				foreach ($m_q_list as $query) {
-					if ($only_test) {
-						 $app['monolog']->addInfo("iDatabase::query($dbNameForm,$query)");
-					} else {
-						$res = iDatabase::query($query);
-						if ($log) {
-							 $app['monolog']->addInfo("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) {
-				     $app['monolog']->addError('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) {
-							 $app['monolog']->addError('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) {
-				     $app['monolog']->addError('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) {
-				     $app['monolog']->addError('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) {
-                 $app['monolog']->addError('Database name '.$dbNameForm.' is too long, skipping');
-            } elseif (!in_array($dbNameForm,$dblist)) {
-                 $app['monolog']->addError('Database '.$dbNameForm.' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbNameForm);
-                foreach ($m_q_list as $query) {
-                    if ($only_test) {
-                         $app['monolog']->addInfo("iDatabase::query($dbNameForm,$query)");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($log) {
-                             $app['monolog']->addInfo("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) {
-				 $app['monolog']->addError('Database name '.$dbStatsForm.' is too long, skipping');
-			} elseif (!in_array($dbStatsForm, $dblist)) {
-				 $app['monolog']->addError('Database '.$dbStatsForm.' was not found, skipping');
-			} else {
-				iDatabase::select_db($dbStatsForm);
-				foreach ($s_q_list as $query) {
-					if ($only_test) {
-						 $app['monolog']->addInfo("iDatabase::query($dbStatsForm,$query)");
-					} else {
-						$res = iDatabase::query($query);
-						if ($log) {
-							 $app['monolog']->addInfo("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) {
-				 $app['monolog']->addError('Database name '.$dbUserForm.' is too long, skipping');
-			} elseif (!in_array($dbUserForm,$dblist)) {
-				 $app['monolog']->addError('Database '.$dbUserForm.' was not found, skipping');
-			} else {
-				iDatabase::select_db($dbUserForm);
-				foreach ($u_q_list as $query) {
-					if ($only_test){
-						 $app['monolog']->addInfo("iDatabase::query($dbUserForm,$query)");
-						 $app['monolog']->addInfo("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) {
-			 $app['monolog']->addError('Database name '.$dbNameForm.' is too long, skipping');
-		} elseif (!in_array($dbNameForm, $dblist)) {
-			 $app['monolog']->addError('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']);
-					}
-                    $app['monolog']->addInfo('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) {
-							 $app['monolog']->addError("iDatabase::query(".$row_course['db_name'].",$query)");
-						} else {
-							$res = iDatabase::query($query);
-							if ($log) {
-								 $app['monolog']->addError("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) {
-				    	 $app['monolog']->addError('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__;
-
-}

+ 0 - 567
main/install/update-db-1.8.6.2-1.8.7.inc.php

@@ -1,567 +0,0 @@
-<?php
-
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Chamilo version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE $dbNameForm.cours
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-
-$old_file_version = '1.8.6.2';
-$new_file_version = '1.8.7';
-
-// Check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-    // Check if the current Chamilo install is eligible for update
-    if (!file_exists('../inc/conf/configuration.php')) {
-        echo '<strong>' . get_lang('Error') . ' !</strong> Chamilo ' . implode('|', $updateFromVersion) . ' ' . get_lang('HasNotBeenFound') . '.<br /><br />
-                                ' . get_lang('PleasGoBackToStep1') . '.
-                                <p><button type="submit" class="back" name="step1" value="&lt; ' . get_lang('Back') . '">' . get_lang('Back') . '</button></p>
-                                </td></tr></table></form></body></html>';
-        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 '../lang/english/create_course.inc.php';
-
-        if ($languageForm != 'english') {
-            // languageForm has been escaped in index.php
-            include '../lang/' . $languageForm . '/create_course.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) {
-                $app['monolog']->addError('Database name ' . $dbNameForm . ' is too long, skipping');
-            } elseif (!in_array($dbNameForm, $dblist)) {
-                $app['monolog']->addError('Database ' . $dbNameForm . ' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbNameForm);
-                foreach ($m_q_list as $query) {
-                    if ($only_test) {
-                        $app['monolog']->addInfo("Database::query($dbNameForm,$query)");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($log) {
-                            $app['monolog']->addInfo("In $dbNameForm, executed: $query");
-                        }
-                        if ($res === false) {
-                            $app['monolog']->addError('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) {
-                        $app['monolog']->addError('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) {
-                    $app['monolog']->addError('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) {
-                $app['monolog']->addError('Database name ' . $dbNameForm . ' is too long, skipping');
-            } elseif (!in_array($dbNameForm, $dblist)) {
-                $app['monolog']->addError('Database ' . $dbNameForm . ' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbNameForm);
-                foreach ($m_q_list as $query) {
-                    if ($only_test) {
-                        $app['monolog']->addInfo("Database::query($dbNameForm,$query)");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($log) {
-                            $app['monolog']->addInfo("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) {
-                $app['monolog']->addError('Database name ' . $dbStatsForm . ' is too long, skipping');
-            } elseif (!in_array($dbStatsForm, $dblist)) {
-                $app['monolog']->addError('Database ' . $dbStatsForm . ' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbStatsForm);
-
-                foreach ($s_q_list as $query) {
-                    if ($only_test) {
-                        $app['monolog']->addInfo("Database::query($dbStatsForm,$query)");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($log) {
-                            $app['monolog']->addInfo("In $dbStatsForm, executed: $query");
-                        }
-                        if ($res === false) {
-                            $app['monolog']->addError('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) {
-                        $app['monolog']->addError('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) {
-                    $app['monolog']->addError('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) {
-                $app['monolog']->addError('Database name ' . $dbUserForm . ' is too long, skipping');
-            } elseif (!in_array($dbUserForm, $dblist)) {
-                $app['monolog']->addError('Database ' . $dbUserForm . ' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbUserForm);
-                foreach ($u_q_list as $query) {
-                    if ($only_test) {
-                        $app['monolog']->addInfo("Database::query($dbUserForm,$query)");
-                        $app['monolog']->addInfo("In $dbUserForm, executed: $query");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($res === false) {
-                            $app['monolog']->addError('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) {
-                        $app['monolog']->addError('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) {
-                    $app['monolog']->addError('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) {
-            $app['monolog']->addError('Database name ' . $dbNameForm . ' is too long, skipping');
-        } elseif (!in_array($dbNameForm, $dblist)) {
-            $app['monolog']->addError('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) {
-                            $app['monolog']->addInfo("Database::query(" . $row_course['db_name'] . ",$query)");
-                        } else {
-                            $res = iDatabase::query($query);
-                            if ($log) {
-                                $app['monolog']->addInfo("In " . $row_course['db_name'] . ", executed: $query");
-                            }
-                            if ($res === false) {
-                                $app['monolog']->addError('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) {
-                                $app['monolog']->addError('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) {
-                            $app['monolog']->addError('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) {
-                        $app['monolog']->addError('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) {
-            $app['monolog']->addError('Database name ' . $dbNameForm . ' is too long, skipping');
-        } elseif (!in_array($dbNameForm, $dblist)) {
-            $app['monolog']->addError('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) {
-                            $app['monolog']->addInfo("Database::query(" . $row['db_name'] . ",$query)");
-                        } else {
-                            $res = iDatabase::query($query);
-                            if ($log) {
-                                $app['monolog']->addInfo("In " . $row['db_name'] . ", executed: $query");
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-} else {
-
-    echo 'You are not allowed here !' . __FILE__;
-}

+ 0 - 407
main/install/update-db-1.8.7-1.8.8.inc.php

@@ -1,407 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Chamilo version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE $dbNameForm.cours
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-$old_file_version = '1.8.7';
-$new_file_version = '1.8.8';
-
-// Check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-    // Check if the current Chamilo install is eligible for update
-    if (!file_exists('../inc/conf/configuration.php')) {
-        echo '<strong>'.get_lang('Error').' !</strong> Chamilo '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.<br /><br />
-                                '.get_lang('PleasGoBackToStep1').'.
-                                <p><button type="submit" class="back" name="step1" value="&lt; '.get_lang('Back').'">'.get_lang('Back').'</button></p>
-                                </td></tr></table></form></body></html>';
-        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 '../lang/english/create_course.inc.php';
-
-        if ($languageForm != 'english') {
-            // languageForm has been escaped in index.php
-            include '../lang/'.$languageForm.'/create_course.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) {
-                $app['monolog']->addError('Database name '.$dbNameForm.' is too long, skipping');
-            } elseif (!in_array($dbNameForm, $dblist)) {
-                $app['monolog']->addError('Database '.$dbNameForm.' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbNameForm);
-                foreach ($m_q_list as $query){
-                    if ($only_test) {
-                        $app['monolog']->addInfo("iDatabase::query($dbNameForm,$query)");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($log) {
-                             $app['monolog']->addInfo("In $dbNameForm, executed: $query");
-                        }
-                        if ($res === false) {
-                        	 $app['monolog']->addError('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) {
-                 $app['monolog']->addError('Database name '.$dbStatsForm.' is too long, skipping');
-            } elseif (!in_array($dbStatsForm, $dblist)){
-                 $app['monolog']->addError('Database '.$dbStatsForm.' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbStatsForm);
-
-                foreach ($s_q_list as $query) {
-                    if ($only_test) {
-                         $app['monolog']->addInfo("iDatabase::query($dbStatsForm,$query)");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($log) {
-                             $app['monolog']->addInfo("In $dbStatsForm, executed: $query");
-                        }
-                        if ($res === false) {
-                             $app['monolog']->addError('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) {
-                 $app['monolog']->addError('Database name '.$dbUserForm.' is too long, skipping');
-            } elseif (!in_array($dbUserForm,$dblist)) {
-                 $app['monolog']->addError('Database '.$dbUserForm.' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbUserForm);
-                foreach ($u_q_list as $query) {
-                    if ($only_test) {
-                         $app['monolog']->addInfo("iDatabase::query($dbUserForm,$query)");
-                         $app['monolog']->addInfo("In $dbUserForm, executed: $query");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($res === false) {
-                             $app['monolog']->addError('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) {
-             $app['monolog']->addError('Database name '.$dbNameForm.' is too long, skipping');
-        } elseif(!in_array($dbNameForm, $dblist)) {
-             $app['monolog']->addError('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']);
-                    }
-                    $app['monolog']->addInfo('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) {
-                             $app['monolog']->addInfo("iDatabase::query(".$row_course['db_name'].",$query)");
-                        } else {
-                            $res = iDatabase::query($query);
-                            if ($log) {
-                                 $app['monolog']->addInfo("In ".$row_course['db_name'].", executed: $query");
-                            }
-                            if ($res === false) {
-                                 $app['monolog']->addError('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 $dbNameForm.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) {
-             $app['monolog']->addError('Database name '.$dbNameForm.' is too long, skipping');
-        } elseif (!in_array($dbNameForm, $dblist)) {
-             $app['monolog']->addError('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) {
-                             $app['monolog']->addInfo("iDatabase::query(".$row['db_name'].",$query)");
-                        } else {
-                            $res = iDatabase::query($query);
-                            if ($log) {
-                                 $app['monolog']->addInfo("In ".$row['db_name'].", executed: $query");
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-    */
-} else {
-    echo 'You are not allowed here !' . __FILE__;
-}

+ 0 - 680
main/install/update-db-1.8.8-1.9.0.inc.php

@@ -1,680 +0,0 @@
-fv<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Chamilo version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE $dbNameForm.cours
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-
-$old_file_version = '1.8.8';
-$new_file_version = '1.9.0';
-
-// Check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-    // Check if the current Chamilo install is eligible for update
-    if (!file_exists('../inc/conf/configuration.php')) {
-        echo '<strong>'.get_lang('Error').' !</strong> Chamilo '.implode('|', $updateFromVersion).' '.get_lang('HasNotBeenFound').'.<br /><br />
-                                '.get_lang('PleasGoBackToStep1').'.
-                                <p><button type="submit" class="back" name="step1" value="&lt; '.get_lang('Back').'">'.get_lang('Back').'</button></p>
-                                </td></tr></table></form></body></html>';
-        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 '../lang/english/create_course.inc.php';
-
-        if ($languageForm != 'english') {
-            // languageForm has been escaped in index.php
-            include '../lang/'.$languageForm.'/create_course.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) {
-                $app['monolog']->addError('Database name '.$dbNameForm.' is too long, skipping');
-            } elseif (!in_array($dbNameForm, $dblist)) {
-                $app['monolog']->addError('Database '.$dbNameForm.' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbNameForm);
-                foreach ($m_q_list as $query){
-                    if ($only_test) {
-                        $app['monolog']->addInfo("iDatabase::query($dbNameForm,$query)");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($res === false) {
-                        	$app['monolog']->addError('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);
-                    }
-                }
-
-                $app['monolog']->addInfo("#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) {
-                $app['monolog']->addError('Database name '.$dbStatsForm.' is too long, skipping');
-            } elseif (!in_array($dbStatsForm, $dblist)){
-                $app['monolog']->addError('Database '.$dbStatsForm.' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbStatsForm);
-
-                foreach ($s_q_list as $query) {
-                    if ($only_test) {
-                        $app['monolog']->addInfo("iDatabase::query($dbStatsForm,$query)");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($res === false) {
-                            $app['monolog']->addError('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) {
-                $app['monolog']->addError('Database name '.$dbUserForm.' is too long, skipping');
-            } elseif (!in_array($dbUserForm,$dblist)) {
-                $app['monolog']->addError('Database '.$dbUserForm.' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbUserForm);
-                foreach ($u_q_list as $query) {
-                    if ($only_test) {
-                        $app['monolog']->addInfo("iDatabase::query($dbUserForm,$query)");
-                        $app['monolog']->addInfo("In $dbUserForm, executed: $query");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($res === false) {
-                            $app['monolog']->addError('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);
-    }
-
-    //Adds the c_XXX courses tables see #3910
-    global $_configuration;
-
-    drop_course_tables();
-    create_course_tables();
-
-    $prefix = '';
-    if ($singleDbForm) {
-        $prefix =  get_config_param('table_prefix');
-    }
-
-    $app['monolog']->addInfo("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');
-    $app['monolog']->addInfo('Starting migration: '.$old_file_version.' - '.$new_file_version);
-
-    if (count($c_q_list) > 0) {
-        // Get the courses list
-        if (strlen($dbNameForm) > 40) {
-            $app['monolog']->addError('Database name '.$dbNameForm.' is too long, skipping');
-        } elseif(!in_array($dbNameForm, $dblist)) {
-            $app['monolog']->addError('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']);
-                    }
-                    $app['monolog']->addInfo('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) {
-                            $app['monolog']->addInfo("iDatabase::query(".$row_course['db_name'].",$query)");
-                        } else {
-                            $res = iDatabase::query($query);
-                            if ($res === false) {
-                                $app['monolog']->addError('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'
-                    );
-
-                    $app['monolog']->addInfo('<<<------- 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 {
-                                $app['monolog']->addError("Count(*) in table $old_table failed");
-                            }
-
-                            $app['monolog']->addInfo("# 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;
-                                }
-                            }
-                            $app['monolog']->addInfo("#rows inserted in $new_table: $count");
-
-                            if ($old_count != $count) {
-                                $app['monolog']->addError("ERROR count of new and old table doesn't match: $old_count - $new_table");
-                                $app['monolog']->addError("Check the results: ");
-                                $app['monolog']->addError(print_r($errors, 1));
-                                error_log(print_r($errors, 1));
-                            }
-                        } else {
-                            $app['monolog']->addError("Seems that the table $old_table doesn't exists ");
-                        }
-                    }
-                    $app['monolog']->addInfo('<<<------- 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);
-            }
-        }
-    }
-}

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

@@ -1,383 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Update the Chamilo database from an older Chamilo version
- * Notice : This script has to be included by index.php
- * or update_courses.php (deprecated).
- *
- * @package chamilo.install
- * @todo
- * - conditional changing of tables. Currently we execute for example
- * ALTER TABLE $dbNameForm.cours
- * instructions without checking wether this is necessary.
- * - reorganise code into functions
- * @todo use database library
- */
-$old_file_version = '1.9.0';
-$new_file_version = '1.10.0';
-
-// Check if we come from index.php or update_courses.php - otherwise display error msg
-if (defined('SYSTEM_INSTALLATION')) {
-
-    // Check if the current Chamilo install is eligible for update
-    if (empty($_configuration)) {
-        echo '<strong>'.get_lang('Error').' !</strong> Chamilo '.get_lang('HasNotBeenFound').'.<br /><br />
-                                '.get_lang('PleasGoBackToStep1').'.
-                                <p><button type="submit" class="back" name="step1" value="&lt; '.get_lang('Back').'">'.get_lang('Back').'</button></p>
-                                </td></tr></table></form></body></html>';
-        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 '../lang/english/create_course.inc.php';
-
-        if ($languageForm != 'english') {
-            // languageForm has been escaped in index.php
-            include '../lang/'.$languageForm.'/create_course.inc.php';
-        }
-
-        // Get the main queries list (m_q_list)
-        $m_q_list = get_sql_file_contents($new_file_version.'/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) {
-                $app['monolog']->addError('Database name '.$dbNameForm.' is too long, skipping');
-            } elseif (!in_array($dbNameForm, $dblist)) {
-                $app['monolog']->addError('Database '.$dbNameForm.' was not found, skipping');
-            } else {
-                iDatabase::select_db($dbNameForm);
-                foreach ($m_q_list as $query) {
-                    if ($only_test) {
-                        $app['monolog']->addInfo("iDatabase::query($dbNameForm,$query)");
-                    } else {
-                        $res = iDatabase::query($query);
-                        if ($res === false) {
-                            $app['monolog']->addError('Error in '.$query.': '.iDatabase::error());
-                        }
-                    }
-                }
-            }
-        }
-
-        if (INSTALL_TYPE_UPDATE == 'update') {
-            $session_table = "$dbNameForm.session";
-            $session_rel_course_table = "$dbNameForm.session_rel_course";
-            $session_rel_course_rel_user_table = "$dbNameForm.session_rel_course_rel_user";
-            $course_table = "$dbNameForm.course";
-
-            //Fixes new changes in sessions
-            $sql = "SELECT id, date_start, date_end, nb_days_access_before_beginning, nb_days_access_after_end FROM $session_table ";
-            $result = iDatabase::query($sql);
-            while ($session = Database::fetch_array($result)) {
-                $session_id = $session['id'];
-
-                //Fixing date_start
-                if (isset($session['date_start']) && !empty($session['date_start']) && $session['date_start'] != '0000-00-00') {
-                    $datetime = $session['date_start'].' 00:00:00';
-                    $update_sql = "UPDATE $session_table SET display_start_date = '$datetime' , access_start_date = '$datetime' WHERE id = $session_id";
-                    iDatabase::query($update_sql);
-
-                    //Fixing nb_days_access_before_beginning
-                    if (!empty($session['nb_days_access_before_beginning'])) {
-                        $datetime = api_strtotime($datetime, 'UTC') - (86400 * $session['nb_days_access_before_beginning']);
-                        $datetime = api_get_utc_datetime($datetime);
-                        $update_sql = "UPDATE $session_table SET coach_access_start_date = '$datetime' WHERE id = $session_id";
-                        iDatabase::query($update_sql);
-                    }
-                }
-
-                //Fixing end_date
-                if (isset($session['date_end']) && !empty($session['date_end']) && $session['date_end'] != '0000-00-00') {
-                    $datetime = $session['date_end'].' 00:00:00';
-                    $update_sql = "UPDATE $session_table SET display_end_date = '$datetime', access_end_date = '$datetime' WHERE id = $session_id";
-                    iDatabase::query($update_sql);
-
-                    //Fixing nb_days_access_before_beginning
-                    if (!empty($session['nb_days_access_after_end'])) {
-                        $datetime = api_strtotime($datetime, 'UTC') + (86400 * $session['nb_days_access_after_end']);
-                        $datetime = api_get_utc_datetime($datetime);
-                        $update_sql = "UPDATE $session_table SET coach_access_end_date = '$datetime' WHERE id = $session_id";
-                        iDatabase::query($update_sql);
-                    }
-                }
-            }
-
-            // Fixes new changes session_rel_course
-            $sql = "SELECT id_session, sc.course_code, c.id FROM $course_table c INNER JOIN $session_rel_course_table sc ON sc.course_code = c.code";
-            $result = iDatabase::query($sql);
-            while ($row = Database::fetch_array($result)) {
-                $sql = "UPDATE $session_rel_course_table SET c_id = {$row['id']}
-                        WHERE course_code = '{$row['course_code']}' AND id_session = {$row['id_session']} ";
-                iDatabase::query($sql);
-            }
-
-            // Fixes new changes in session_rel_course_rel_user
-            $sql = "SELECT id_session, sc.course_code, c.id FROM $course_table c INNER JOIN $session_rel_course_rel_user_table sc ON sc.course_code = c.code";
-            $result = iDatabase::query($sql);
-            while ($row = Database::fetch_array($result)) {
-                $sql = "UPDATE $session_rel_course_rel_user_table SET c_id = {$row['id']}
-                        WHERE course_code = '{$row['course_code']}' AND id_session = {$row['id_session']} ";
-                iDatabase::query($sql);
-            }
-
-            //Updating c_quiz_order
-            $teq = "$dbNameForm.c_quiz";
-            $seq = "SELECT c_id, session_id, id FROM $teq ORDER BY c_id, session_id, id";
-            $req = iDatabase::query($seq);
-            $to = "$dbNameForm.c_quiz_order";
-            $do = "DELETE FROM $to";
-            Database::query($do);
-            $cid = 0;
-            $temp_session_id = 0;
-            $order = 1;
-            while ($row = Database::fetch_assoc($req)) {
-                if ($row['c_id'] != $cid) {
-                    $cid = $row['c_id'];
-                    $temp_session_id = $row['session_id'];
-                    $order = 1;
-                } elseif ($row['session_id'] != $temp_session_id) {
-                    $temp_session_id = $row['session_id'];
-                    $order = 1;
-                }
-                $ins = "INSERT INTO $to (c_id, session_id, exercise_id, exercise_order)".
-                       " VALUES ($cid, $temp_session_id, {$row['id']}, $order)";
-                $rins = iDatabase::query($ins);
-
-                $order++;
-            }
-
-            $sql = "SELECT id FROM $dbNameForm.course_field WHERE field_variable = 'special_course'";
-            $result = Database::query($sql);
-            $fieldData = Database::fetch_array($result, 'ASSOC');
-            $id = $fieldData['id'];
-
-            $sql = "INSERT INTO $dbNameForm.course_field_options (field_id, option_value, option_display_text, option_order)
-                    VALUES ('$id', '1', '".get_lang('Yes')."', '1')";
-            $result = Database::query($sql);
-
-            $sql = "INSERT INTO $dbNameForm.course_field_options (field_id, option_value, option_display_text, option_order)
-                    VALUES ('$id', '0', '".get_lang('No')."', '2')";
-            Database::query($sql);
-
-
-            // Moving social group to class
-            $output->writeln('Fixing social groups');
-
-            $sql = "SELECT * FROM $dbNameForm.groups";
-            $result = Database::query($sql);
-            $oldGroups = array();
-            if (Database::num_rows($result)) {
-                while ($group = Database::fetch_array($result, 'ASSOC')) {
-
-                    $group['name'] = Database::escape_string($group['name']);
-                    $group['description'] = Database::escape_string($group['description']);
-                    $group['picture'] = Database::escape_string($group['picture_uri']);
-                    $group['url'] = Database::escape_string($group['url']);
-                    $group['visibility'] = Database::escape_string($group['visibility']);
-                    $group['updated_on'] = Database::escape_string($group['updated_on']);
-                    $group['created_on'] = Database::escape_string($group['created_on']);
-
-                    $sql = "INSERT INTO $dbNameForm.usergroup (name, group_type, description, picture, url, visibility, updated_on, created_on)
-                    VALUES ('{$group['name']}', '1', '{$group['description']}', '{$group['picture_uri']}', '{$group['url']}', '{$group['visibility']}', '{$group['updated_on']}', '{$group['created_on']}')";
-                    Database::query($sql);
-                    $id = Database::insert_id();
-                    $oldGroups[$group['id']] = $id;
-                }
-            }
-
-            if (!empty($oldGroups)) {
-                $output->writeln('Moving group files');
-                foreach ($oldGroups as $oldId => $newId) {
-                    $path = GroupPortalManager::get_group_picture_path_by_id($oldId, 'system');
-                    if (!empty($path)) {
-                        var_dump($path['dir']);
-                        $newPath = str_replace("groups/$oldId/", "groups/$newId/", $path['dir']);
-                        $command = "mv {$path['dir']} $newPath ";
-                        system($command);
-                        $output->writeln("Moving files: $command");
-                    }
-                }
-                $sql = "SELECT * FROM $dbNameForm.group_rel_user";
-                $result = Database::query($sql);
-
-                if (Database::num_rows($result)) {
-                    while ($data = Database::fetch_array($result, 'ASSOC')) {
-                        if (isset($oldGroups[$data['group_id']])) {
-                            $data['group_id'] = $oldGroups[$data['group_id']];
-                            $sql = "INSERT INTO $dbNameForm.usergroup_rel_user (usergroup_id, user_id, relation_type)
-                            VALUES ('{$data['group_id']}', '{$data['user_id']}', '{$data['relation_type']}')";
-                            Database::query($sql);
-                        }
-                    }
-                }
-
-                $sql = "SELECT * FROM $dbNameForm.group_rel_group";
-                $result = Database::query($sql);
-
-                if (Database::num_rows($result)) {
-                    while ($data = Database::fetch_array($result, 'ASSOC')) {
-                        if (isset($oldGroups[$data['group_id']]) && isset($oldGroups[$data['subgroup_id']])) {
-                            $data['group_id'] = $oldGroups[$data['group_id']];
-                            $data['subgroup_id'] = $oldGroups[$data['subgroup_id']];
-                            $sql = "INSERT INTO $dbNameForm.usergroup_rel_usergroup (group_id, subgroup_id, relation_type)
-                                    VALUES ('{$data['group_id']}', '{$data['subgroup_id']}', '{$data['relation_type']}')";
-                            Database::query($sql);
-                        }
-                    }
-                }
-
-                $sql = "SELECT * FROM $dbNameForm.announcement_rel_group";
-                $result = Database::query($sql);
-
-                if (Database::num_rows($result)) {
-                    while ($data = Database::fetch_array($result, 'ASSOC')) {
-                        if (isset($oldGroups[$data['group_id']])) {
-                            //Deleting relation
-                            $sql = "DELETE FROM announcement_rel_group WHERE id = {$data['id']}";
-                            Database::query($sql);
-
-                            //Add new relation
-                            $data['group_id'] = $oldGroups[$data['group_id']];
-                            $sql = "INSERT INTO $dbNameForm.announcement_rel_group(group_id, announcement_id)
-                            VALUES ('{$data['group_id']}', '{$data['announcement_id']}')";
-                            Database::query($sql);
-                        }
-                    }
-                }
-
-                $sql = "SELECT * FROM $dbNameForm.group_rel_tag";
-                $result = Database::query($sql);
-                if (Database::num_rows($result)) {
-                    while ($data = Database::fetch_array($result, 'ASSOC')) {
-                        if (isset($oldGroups[$data['group_id']])) {
-                            $data['group_id'] = $oldGroups[$data['group_id']];
-                            $sql = "INSERT INTO $dbNameForm.usergroup_rel_tag (tag_id, usergroup_id)
-                            VALUES ('{$data['tag_id']}', '{$data['group_id']}')";
-                            Database::query($sql);
-                        }
-                    }
-                }
-
-                $course = "$dbNameForm.course";
-                $sql = "SELECT id FROM $course";
-                $result = Database::query($sql);
-                $test = false;
-                // Getting courses
-                while ($data = Database::fetch_array($result, 'ASSOC')) {
-                    $courseId = $data['id'];
-                    $sql = "SELECT id, iid FROM $dbNameForm.c_quiz WHERE c_id = $courseId";
-                    $resultQuiz = Database::query($sql);
-                    // getting quiz
-                    while ($quiz = Database::fetch_array($resultQuiz, 'ASSOC')) {
-                        $quizId = $quiz['id'];
-                        $newQuizId = $quiz['iid'];
-
-                        //item properties
-                        $sql = "UPDATE $dbNameForm.c_item_property SET ref= $newQuizId WHERE c_id = $courseId AND ref = $quizId AND tool = 'quiz' ";
-                        if ($test) {
-                            var_dump($sql);
-                        } else {
-                            Database::query($sql);
-                        }
-
-                        //item c_lp_item
-                        $sql = "UPDATE $dbNameForm.c_lp_item SET ref= $newQuizId WHERE c_id = $courseId AND ref = $quizId AND item_type = 'quiz' ";
-                        if ($test) {
-                            var_dump($sql);
-                        } else {
-                            Database::query($sql);
-                        }
-                        // getting questions
-                        $sql = "SELECT r.question_id, q.iid FROM $dbNameForm.c_quiz_rel_question r INNER JOIN $dbNameForm.c_quiz_question q
-                                ON (r.c_id = q.c_id AND r.question_id = q.id)
-                                WHERE r.c_id = $courseId AND exercice_id = $quizId";
-                        $resultQuestion = Database::query($sql);
-                        while ($question = Database::fetch_array($resultQuestion, 'ASSOC')) {
-
-                            $oldQuestionId = $question['question_id'];
-                            $newQuestionId = $question['iid'];
-
-                            // moving answers
-                            $sql = "SELECT id, iid FROM $dbNameForm.c_quiz_answer WHERE c_id = $courseId AND question_id = $oldQuestionId";
-                            $resultAnswer = Database::query($sql);
-                            while ($answer = Database::fetch_array($resultAnswer, 'ASSOC')) {
-                                $sql = "UPDATE $dbNameForm.c_quiz_answer SET question_id = $newQuestionId
-                                        WHERE c_id = $courseId AND question_id = $oldQuestionId";
-
-                                if ($test) {
-                                    var_dump($sql);
-                                } else {
-                                    Database::query($sql);
-                                }
-                            }
-
-                            $sql = "UPDATE $dbNameForm.c_quiz_rel_question SET exercice_id = $newQuizId, question_id = $newQuestionId
-                                    WHERE c_id = $courseId AND question_id = $oldQuestionId";
-                            if ($test ) {
-                                var_dump($sql);
-                            } else {
-                                Database::query($sql);
-                            }
-                        }
-
-                        // Categories
-                        $sql = "SELECT iid, id FROM $dbNameForm.c_quiz_category WHERE c_id = $courseId";
-                        $resultCat = Database::query($sql);
-                        while ($category = Database::fetch_array($resultCat, 'ASSOC')) {
-                            $oldId = $category['id'];
-                            $newId = $category['iid'];
-
-                            $sql = "UPDATE $dbNameForm.c_quiz_rel_category SET exercice_id = $newQuizId, category_id = $newId
-                                    WHERE c_id = $courseId AND category_id = $oldId";
-                            if ($test ) {
-                                var_dump($sql);
-                            } else {
-                                Database::query($sql);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-}

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

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

+ 0 - 150
main/install/update-files-1.6.x-1.8.0.inc.php

@@ -1,150 +0,0 @@
-<?php
-
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Updates the Dokeos files from version 1.6.x to version 1.8.0
- * IMPORTANT: This script has to be included by install/index.php or
- * update_courses.php (deprecated)
- *
- * SYSTEM_INSTALLATION is defined in the install/index.php (means that we are in
- * the regular upgrade process)
- *
- * When SYSTEM_INSTALLATION is defined, do for every course:
- * - create a new set of directories that reflect the new tools offered by 1.8
- * - record an item_property for each directory added
- *
- * @package chamilo.install
- */
-
-function insert_db($db_name, $folder_name, $text)
-{
-    // TODO: The (global?) variable $_course has not been declared/initialized.
-    $_course['dbName'] = $db_name;
-
-    $doc_id = FileManager::add_document_180($_course, '/'.$folder_name, 'folder', 0, api_ucfirst($text));
-    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', 1);
-}
-
-if (defined('SYSTEM_INSTALLATION')) {
-
-    $sys_course_path = $pathForm.'courses/';
-    //$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
-    Database::select_db($dbNameForm);
-    $db_name = $dbNameForm;
-    $sql = "SELECT * FROM course";
-    $app['monolog']->addInfo('Getting courses for files updates: '.$sql);
-    $result = Database::query($sql);
-
-    while ($courses_directories = Database::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)) {
-            $app['monolog']->addError('Directory '.$origCRS.' does not exist. Skipping.');
-            continue;
-        }
-        // Move everything to the new hierarchy (from old path to new path)
-        $app['monolog']->addInfo('Renaming '.$origCRS.' to '.$sys_course_path.$courses_directories["directory"]);
-        rename($origCRS, $sys_course_path.$courses_directories["directory"]);
-        $app['monolog']->addInfo('Creating dirs in '.$currentCourseRepositorySys);
-
-        // FOLDER DOCUMENT
-        // document > 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 = '<?php'."\n".
-            '$cidReq="'.$courses_directories['code'].'";'."\n".
-            '$dbname="'.$courses_directories['db_name'].'";'."\n".
-            'include("../../main/course_home/course_home.php");'."\n".
-            '?>';
-        unlink($currentCourseRepositorySys.'index.php');
-        $fp = @ fopen($currentCourseRepositorySys.'index.php', 'w');
-        if ($fp) {
-            $app['monolog']->addError('Writing redirection file in '.$currentCourseRepositorySys.'index.php');
-            fwrite($fp, $content);
-            fclose($fp);
-        } else {
-            $app['monolog']->addError('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');
-
-    $app['monolog']->addInfo('Renaming '.$updatePath.'claroline/upload/users to '.$pathForm.'main/upload/users');
-    rename($updatePath.'claroline/upload/users', $pathForm.'main/upload/users');
-    $app['monolog']->addInfo('Renaming '.$updatePath.'claroline/upload/audio to '.$pathForm.'main/upload/audio');
-    rename($updatePath.'claroline/upload/audio', $pathForm.'main/upload/audio');
-    $app['monolog']->addInfo('Renaming '.$updatePath.'claroline/upload/images to '.$pathForm.'main/upload/images');
-    rename($updatePath.'claroline/upload/images', $pathForm.'main/upload/images');
-    $app['monolog']->addInfo(
-        'Renaming '.$updatePath.'claroline/upload/linked_files to '.$pathForm.'main/upload/linked_files'
-    );
-    rename($updatePath.'claroline/upload/linked_files', $pathForm.'main/upload/linked_files');
-    $app['monolog']->addInfo('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__;
-}

+ 0 - 56
main/install/update-files-1.8.3-1.8.4.inc.php

@@ -1,56 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Updates the Dokeos files from version 1.8.3 to version 1.8.4
- * This script operates only in the case of an update, and only to change the
- * active version number (and other things that might need a change) in the
- * current configuration file.
- * As of 1.8.4, the Dokeos version has been added to configuration.php to
- * allow for edition (inc/conf is one of the directories that needs write
- * permissions on upgrade).
- * Being in configuration.php, it benefits from the configuration.dist.php
- * advantages that a new version doesn't overwrite it, thus letting the old
- * version be available until the end of the installation.
- * @package chamilo.install
- */
-
-if (defined('SYSTEM_INSTALLATION')) {
-
-	// Edit the configuration file
-	$file = file(api_get_path(CONFIGURATION_PATH).'configuration.php');
-	$fh = fopen(api_get_path(CONFIGURATION_PATH).'configuration.php', 'w');
-	$found_version = false;
-	$found_stable = false;
-	foreach ($file as $line) {
-		$ignore = false;
-		if (stripos($line, '$_configuration[\'dokeos_version\']') !== false) {
-			$found_version = true;
-			$line = '$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n";
-		} elseif (stripos($line, '$_configuration[\'dokeos_stable\']') !== false) {
-			$found_stable = true;
-			$line = '$_configuration[\'dokeos_stable\'] = '.($new_version_stable ? 'true' : 'false').';'."\r\n";
-		} elseif (stripos($line, '?>') !== 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__;
-
-}

+ 0 - 52
main/install/update-files-1.8.4-1.8.5.inc.php

@@ -1,52 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Updates the Dokeos files from version 1.8.4 to version 1.8.5
- * This script operates only in the case of an update, and only to change the
- * active version number (and other things that might need a change) in the
- * current configuration file.
- * As of 1.8.5, the Dokeos version has been added to configuration.php to
- * allow for edition (inc/conf is one of the directories that needs write
- * permissions on upgrade).
- * Being in configuration.php, it benefits from the configuration.dist.php
- * advantages that a new version doesn't overwrite it, thus letting the old
- * version be available until the end of the installation.
- * @package chamilo.install
- */
-if (defined('SYSTEM_INSTALLATION')) {
-
-    // Edit the configuration file
-    $file = file(api_get_path(CONFIGURATION_PATH).'configuration.php');
-    $fh = fopen(api_get_path(CONFIGURATION_PATH).'configuration.php', 'w');
-    $found_version = false;
-    $found_stable = false;
-    foreach ($file as $line) {
-        $ignore = false;
-        if (stripos($line, '$_configuration[\'dokeos_version\']') !== false) {
-            $found_version = true;
-            $line = '$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n";
-        } elseif (stripos($line, '$_configuration[\'dokeos_stable\']') !== false) {
-            $found_stable = true;
-            $line = '$_configuration[\'dokeos_stable\'] = '.($new_version_stable ? 'true' : 'false').';'."\r\n";
-        } elseif (stripos($line, '?>') !== 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__;
-}

+ 0 - 118
main/install/update-files-1.8.5-1.8.6.inc.php

@@ -1,118 +0,0 @@
-<?php
-
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Updates the Dokeos files from version 1.8.5 to version 1.8.6
- * This script operates only in the case of an update, and only to change the
- * active version number (and other things that might need a change) in the
- * current configuration file.
- * As of 1.8.6, the Dokeos version has been added to configuration.php to
- * allow for edition (inc/conf is one of the directories that needs write
- * permissions on upgrade).
- * Being in configuration.php, it benefits from the configuration.dist.php
- * advantages that a new version doesn't overwrite it, thus letting the old
- * version be available until the end of the installation.
- * @package chamilo.install
- */
-
-if (defined('SYSTEM_INSTALLATION')) {
-
-    // Edit the configuration file
-    $file = file(api_get_path(CONFIGURATION_PATH) . 'configuration.php');
-    $fh = fopen(api_get_path(CONFIGURATION_PATH) . 'configuration.php', 'w');
-    $found_version = false;
-    $found_stable = false;
-    foreach ($file as $line) {
-        $ignore = false;
-        if (stripos($line, '$_configuration[\'dokeos_version\']') !== false) {
-            $found_version = true;
-            $line = '$_configuration[\'dokeos_version\'] = \'' . $new_version . '\';' . "\r\n";
-        } elseif (stripos($line, '$_configuration[\'dokeos_stable\']') !== false) {
-            $found_stable = true;
-            $line = '$_configuration[\'dokeos_stable\'] = ' . ($new_version_stable ? 'true' : 'false') . ';' . "\r\n";
-        } elseif (stripos($line, '$userPasswordCrypted') !== false) {
-            $line = '$userPasswordCrypted 									= \'' . ($userPasswordCrypted) . '\';' . "\r\n";
-        } elseif (stripos($line, '?>') !== 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";
-    $app['monolog']->addInfo('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)) {
-            $app['monolog']->addError('Directory ' . $origCRS . ' does not exist. Skipping.');
-            continue;
-        }
-        // Move everything to the new hierarchy (from old path to new path)
-        $app['monolog']->addInfo('Renaming ' . $origCRS . ' to ' . $sys_course_path . $courses_directories['directory']);
-        rename($origCRS, $sys_course_path . $courses_directories['directory']);
-        $app['monolog']->addInfo('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__;
-}

+ 0 - 64
main/install/update-files-1.8.6-1.8.6.1.inc.php

@@ -1,64 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Updates the Dokeos files from version 1.8.6 to version 1.8.6.1
- * This script operates only in the case of an update, and only to change the
- * active version number (and other things that might need a change) in the
- * current configuration file.
- * As of 1.8.6, the Dokeos version has been added to configuration.php to
- * allow for edition (inc/conf is one of the directories that needs write
- * permissions on upgrade).
- * Being in configuration.php, it benefits from the configuration.dist.php
- * advantages that a new version doesn't overwrite it, thus letting the old
- * version be available until the end of the installation.
- * @package chamilo.install
- */
-
-if (defined('SYSTEM_INSTALLATION')) {
-
-	// Edit the configuration file
-	$file = file(api_get_path(CONFIGURATION_PATH).'configuration.php');
-	$fh = fopen(api_get_path(CONFIGURATION_PATH).'configuration.php', 'w');
-	$found_version = false;
-	$found_stable = false;
-	foreach ($file as $line) {
-		$ignore = false;
-		if (stripos($line, '$_configuration[\'dokeos_version\']') !== false) {
-			$found_version = true;
-			$line = '$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n";
-		} elseif (stripos($line, '$_configuration[\'dokeos_stable\']') !== false) {
-			$found_stable = true;
-			$line = '$_configuration[\'dokeos_stable\'] = '.($new_version_stable ? 'true' : 'false').';'."\r\n";
-		} elseif (stripos($line, '$userPasswordCrypted') !== false) {
-			$line = '$userPasswordCrypted 									= \''.($userPasswordCrypted).'\';'."\r\n";
-		} elseif (stripos($line, '?>') !== 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__;
-
-}

+ 0 - 95
main/install/update-files-1.8.6.1-1.8.6.2.inc.php

@@ -1,95 +0,0 @@
-<?php
-
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Updates the Dokeos files from version 1.8.6.1 to Chamilo version 1.8.6.2
- * This script operates only in the case of an update, and only to change the
- * active version number (and other things that might need a change) in the
- * current configuration file.
- * @package chamilo.install
- */
-
-if (defined('SYSTEM_INSTALLATION')) {
-
-    // Edit the configuration file
-    $file = file(api_get_path(CONFIGURATION_PATH) . 'configuration.php');
-    $fh = fopen(api_get_path(CONFIGURATION_PATH) . 'configuration.php', 'w');
-    $found_version = false;
-    $found_stable = false;
-    foreach ($file as $line) {
-        $ignore = false;
-        if (stripos($line, '$_configuration[\'dokeos_version\']') !== false) {
-            $found_version = true;
-            $line = '$_configuration[\'dokeos_version\'] = \'' . $new_version . '\';' . "\r\n";
-        } elseif (stripos($line, '$_configuration[\'dokeos_stable\']') !== false) {
-            $found_stable = true;
-            $line = '$_configuration[\'dokeos_stable\'] = ' . ($new_version_stable ? 'true' : 'false') . ';' . "\r\n";
-        } elseif (stripos($line, '$userPasswordCrypted') !== false) {
-            $line = '$userPasswordCrypted 									= \'' . ($userPasswordCrypted) . '\';' . "\r\n";
-        } elseif (stripos($line, '?>') !== 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";
-    $app['monolog']->addInfo('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'];
-                    $app['monolog']->addError("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'];
-                    $app['monolog']->addError("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__;
-}

+ 0 - 75
main/install/update-files-1.8.6.2-1.8.7.inc.php

@@ -1,75 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Updates the Chamilo files from version 1.8.6.2 to version 1.8.7
- * This script operates only in the case of an update, and only to change the
- * active version number (and other things that might need a change) in the
- * current configuration file.
- * @package chamilo.install
- */
-
-if (defined('SYSTEM_INSTALLATION')) {
-
-	// Edit the configuration file
-	$file = file(api_get_path(CONFIGURATION_PATH).'configuration.php');
-	$fh = fopen(api_get_path(CONFIGURATION_PATH).'configuration.php', 'w');
-	$found_version_old = false;
-	$found_stable_old = false;
-	$found_version = false;
-	$found_stable = false;
-	$found_software_name = false;
-	$found_software_url = false;
-	foreach ($file as $line) {
-		$ignore = false;
-		if (stripos($line, '$_configuration[\'dokeos_version\']') !== false) {
-			$found_version_old = true;
-			$line = '$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n";
-			$ignore = true;
-		} elseif (stripos($line, '$_configuration[\'system_version\']') !== false) {
-			$found_version = true;
-			$line = '$_configuration[\'system_version\'] = \''.$new_version.'\';'."\r\n";
-		} elseif (stripos($line, '$_configuration[\'dokeos_stable\']') !== false) {
-			$found_stable_old = true;
-			$line = '$_configuration[\'dokeos_stable\'] = '.($new_version_stable ? 'true' : 'false').';'."\r\n";
-			$ignore = true;
-		} elseif (stripos($line, '$_configuration[\'system_stable\']') !== false) {
-			$found_stable = true;
-			$line = '$_configuration[\'system_stable\'] = '.($new_version_stable ? 'true' : 'false').';'."\r\n";
-		} elseif (stripos($line, '$_configuration[\'software_name\']') !== false) {
-			$found_software_name = true;
-			$line = '$_configuration[\'software_name\'] = \''.$software_name.'\';'."\r\n";
-		} elseif (stripos($line, '$_configuration[\'software_url\']') !== false) {
-			$found_software_url = true;
-			$line = '$_configuration[\'software_url\'] = \''.$software_url.'\';'."\r\n";
-		} elseif (stripos($line,'$userPasswordCrypted') !== false) {
-			$line = '$userPasswordCrypted = \''.($userPasswordCrypted).'\';'."\r\n";
-		} elseif (stripos($line, '?>') !== 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__;
-
-}

+ 0 - 75
main/install/update-files-1.8.7-1.8.8.inc.php

@@ -1,75 +0,0 @@
-<?php
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Updates the Chamilo files from version 1.8.7 to version 1.8.8
- * This script operates only in the case of an update, and only to change the
- * active version number (and other things that might need a change) in the
- * current configuration file.
- * @package chamilo.install
- */
-
-if (defined('SYSTEM_INSTALLATION')) {
-
-	// Edit the configuration file
-	$file = file(api_get_path(CONFIGURATION_PATH).'configuration.php');
-	$fh = fopen(api_get_path(CONFIGURATION_PATH).'configuration.php', 'w');
-	$found_version_old = false;
-	$found_stable_old = false;
-	$found_version = false;
-	$found_stable = false;
-	$found_software_name = false;
-	$found_software_url = false;
-	foreach ($file as $line) {
-		$ignore = false;
-		if (stripos($line, '$_configuration[\'dokeos_version\']') !== false) {
-			$found_version_old = true;
-			$line = '$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n";
-			$ignore = true;
-		} elseif (stripos($line, '$_configuration[\'system_version\']') !== false) {
-			$found_version = true;
-			$line = '$_configuration[\'system_version\'] = \''.$new_version.'\';'."\r\n";
-		} elseif (stripos($line, '$_configuration[\'dokeos_stable\']') !== false) {
-			$found_stable_old = true;
-			$line = '$_configuration[\'dokeos_stable\'] = '.($new_version_stable ? 'true' : 'false').';'."\r\n";
-			$ignore = true;
-		} elseif (stripos($line, '$_configuration[\'system_stable\']') !== false) {
-			$found_stable = true;
-			$line = '$_configuration[\'system_stable\'] = '.($new_version_stable ? 'true' : 'false').';'."\r\n";
-		} elseif (stripos($line, '$_configuration[\'software_name\']') !== false) {
-			$found_software_name = true;
-			$line = '$_configuration[\'software_name\'] = \''.$software_name.'\';'."\r\n";
-		} elseif (stripos($line, '$_configuration[\'software_url\']') !== false) {
-			$found_software_url = true;
-			$line = '$_configuration[\'software_url\'] = \''.$software_url.'\';'."\r\n";
-		} elseif (stripos($line,'$userPasswordCrypted') !== false) {
-			$line = '$userPasswordCrypted = \''.($userPasswordCrypted).'\';'."\r\n";
-		} elseif (stripos($line, '?>') !== 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__;
-
-}

+ 0 - 85
main/install/update-files-1.8.8-1.9.0.inc.php

@@ -1,85 +0,0 @@
-<?php
-
-/* For licensing terms, see /license.txt */
-
-/**
- * Chamilo LMS
- *
- * Updates the Chamilo files from version 1.8.8 to version 1.9.0
- * This script operates only in the case of an update, and only to change the
- * active version number (and other things that might need a change) in the
- * current configuration file.
- * @package chamilo.install
- */
-if (defined('SYSTEM_INSTALLATION')) {
-
-    $conf_dir = api_get_path(CONFIGURATION_PATH);
-    $portfolio_conf_dist = $conf_dir . 'portfolio.conf.dist.php';
-    $portfolio_conf = $conf_dir . 'portfolio.conf.dist.php';
-
-    if (!file_exists($portfolio_conf)) {
-        copy($portfolio_conf_dist, $portfolio_conf);
-    }
-
-    // Edit the configuration file
-    $file = file(api_get_path(CONFIGURATION_PATH) . 'configuration.php');
-    $fh = fopen(api_get_path(CONFIGURATION_PATH) . 'configuration.php', 'w');
-    $found_version_old = false;
-    $found_stable_old = false;
-    $found_version = false;
-    $found_stable = false;
-    $found_software_name = false;
-    $found_software_url = false;
-    foreach ($file as $line) {
-        $ignore = false;
-        if (stripos($line, '$userPasswordCrypted') !== false) {
-            $line = '$_configuration[\'password_encryption\'] = \'' . ($userPasswordCrypted) . '\';' . "\r\n";
-        } elseif (stripos($line, '?>') !== 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__;
-}

+ 7 - 3
main/newscorm/learnpath.class.php

@@ -4074,15 +4074,19 @@ class learnpath
      * @param    integer    Learnpath ID
      * @param    string    New visibility
      */
-    public function toggle_visibility($lp_id, $set_visibility = 1)
+    public function toggle_visibility($lp_id, $set_visibility = 1, $course_id = null)
     {
         //if ($this->debug > 0) { error_log('New LP - In learnpath::toggle_visibility()', 0); }
         $action = 'visible';
         if ($set_visibility != 1) {
             $action = 'invisible';
         }
-
-        return api_item_property_update(api_get_course_info(), TOOL_LEARNPATH, $lp_id, $action, api_get_user_id());
+        if (!empty($course_id)) {
+            $course = api_get_course_info_by_id($course_id);
+        } else {
+            $course = api_get_course_info();
+        }
+        return api_item_property_update($course, TOOL_LEARNPATH, $lp_id, $action, api_get_user_id());
     }
 
     /**

+ 0 - 12
main/newscorm/learnpath_functions.inc.php

@@ -1454,18 +1454,6 @@ function exportitem($id, $item_id, $item_type, $add_scorm_communications = false
     include_once $libp.'answer.class.php';
 
     $langLasting = ''; //avoid code parser warning
-    include_once $libp.'lang/english/announcements.inc.php'; //this line is here only for $langPubl in announcements
-    include_once $libp.'lang/'.$language_interface.'/announcements.inc.php'; //this line is here only for $langPubl in announcements
-    include_once $libp.'lang/english/agenda.inc.php'; //this line is here only for $langLasting
-    include_once $libp.'lang/'.$language_interface.'/agenda.inc.php'; //this line is here only for $langLasting
-    include_once $libp.'lang/english/course_description.inc.php'; //this line is here only for $langThisCourseDescriptionIsEmpty
-    include_once $libp.'lang/'.$language_interface.'/course_description.inc.php'; //				 -||-
-    include_once $libp.'lang/english/resourcelinker.inc.php';
-    include_once $libp.'lang/'.$language_interface.'/resourcelinker.inc.php';
-    include_once $libp.'lang/english/learnpath.inc.php';
-    include_once $libp.'lang/'.$language_interface.'/learnpath.inc.php';
-    include_once $libp.'lang/english/exercice.inc.php';
-    include_once $libp.'lang/'.$language_interface.'/exercice.inc.php';
 
     include_once '../resourcelinker/resourcelinker.inc.php';
 

+ 2 - 2
main/newscorm/lp_view.php

@@ -444,9 +444,9 @@ if ($show_audioplayer) {
     // hub 26-05-2010 Fullscreen or not fullscreen
     $height = '100%';
     if ($_SESSION['oLP']->mode == 'fullscreen') {
-        echo '<iframe id="content_id_blank" name="content_name_blank" src="blank.php" border="0" frameborder="0" style="width:100%;height:'.$height.'" ></iframe>';
+        echo '<iframe id="content_id_blank" name="content_name_blank" src="blank.php" border="0" frameborder="0" style="width:100%;height:'.$height.'" allowFullScreen></iframe>';
     } else {
-        echo '<iframe id="content_id" name="content_name" src="'.$src.'" border="0" frameborder="0" style="display: block; width:100%;height:'.$height.'"></iframe>';
+        echo '<iframe id="content_id" name="content_name" src="'.$src.'" border="0" frameborder="0" style="display: block; width:100%;height:'.$height.'" allowFullScreen></iframe>';
     }
     ?>
 </div>

+ 0 - 2
main/newscorm/resourcelinker.inc.php

@@ -23,9 +23,7 @@ use \ChamiloSession as Session;
 $use_anonymous = true;
 
 require_once '../inc/global.inc.php';
-require_once api_get_path(SYS_CODE_PATH).'lang/english/resourcelinker.inc.php';
 if (!empty($_course['language'])) {
-    $resource_linker_file = api_get_path(SYS_CODE_PATH).'lang/'.$_course['language'].'/resourcelinker.inc.php';
     if (file_exists($resource_linker_file)) {
         require_once $resource_linker_file;
     }

+ 36 - 45
main/session/session_list.php

@@ -7,15 +7,8 @@
 /**
  * Code
  */
-$language_file = 'admin';
-$cidReset = true;
-
-require_once '../inc/global.inc.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 
-//api_protect_admin_script(true);
-//@todo use filters
-//$app['controllers_factory']->before($app['index.controller']->security());
 SessionManager::protect_session_edit();
 
 //Add the JS needed to use the jqgrid
@@ -101,7 +94,6 @@ $url_select = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?1=1';
 
 function setSearchSelect(columnName) {
     $("#sessions").jqGrid('setColProp', columnName, {
-
        /*searchoptions:{
             dataInit:function(el){
                 $("option[value='1']",el).attr("selected", "selected");
@@ -185,42 +177,42 @@ $(function() {
     setSearchSelect("status");
 
     var grid = $("#sessions"),
-    prmSearch = {
-        multipleSearch : true,
-        overlay : false,
-        width: 'auto',
-        caption: '<?php echo addslashes(get_lang('Search')); ?>',
-        formclass:'data_table',
-        onSearch : function() {
-            var postdata = grid.jqGrid('getGridParam', 'postData');
-
-            if (postdata && postdata.filters) {
-                filters = jQuery.parseJSON(postdata.filters);
+        prmSearch = {
+            multipleSearch : true,
+            overlay : false,
+            width: 'auto',
+            caption: '<?php echo addslashes(get_lang('Search')); ?>',
+            formclass:'data_table',
+            onSearch : function() {
+                var postdata = grid.jqGrid('getGridParam', 'postData');
+
+                if (postdata && postdata.filters) {
+                    filters = jQuery.parseJSON(postdata.filters);
+                    clean_cols(grid, added_cols);
+                    added_cols = [];
+                    $.each(filters, function(key, value){
+                        //console.log('key: ' + key );
+
+                        if (key == 'rules') {
+                            $.each(value, function(subkey, subvalue) {
+
+                                if (subvalue.data == undefined) {
+                                }
+
+                                //if (added_cols[value.field] == undefined) {
+                                    added_cols[subvalue.field] = subvalue.field;
+                                //}
+                                //grid.showCol(value.field);
+                            });
+                        }
+                    });
+                    show_cols(grid, added_cols);
+                }
+           },
+           onReset: function() {
                 clean_cols(grid, added_cols);
-                added_cols = [];
-                $.each(filters, function(key, value){
-                    //console.log('key: ' + key );
-
-                    if (key == 'rules') {
-                        $.each(value, function(subkey, subvalue) {
-
-                            if (subvalue.data == undefined) {
-                            }
-
-                            //if (added_cols[value.field] == undefined) {
-                                added_cols[subvalue.field] = subvalue.field;
-                            //}
-                            //grid.showCol(value.field);
-                        });
-                    }
-                });
-                show_cols(grid, added_cols);
-            }
-       },
-       onReset: function() {
-            clean_cols(grid, added_cols);
-       }
-    };
+           }
+        };
 
     original_cols = grid.jqGrid('getGridParam', 'colModel');
 
@@ -268,6 +260,7 @@ $(function() {
 });
 </script>
 <?php
+
 echo '<div class="actions">';
 echo '<a href="'.api_get_path(WEB_CODE_PATH).'session/session_add.php">'.Display::return_icon('new_session.png',get_lang('AddSession'),'',ICON_SIZE_MEDIUM).'</a>';
 echo '<a href="'.api_get_path(WEB_CODE_PATH).'admin/add_many_session_to_category.php">'.Display::return_icon('session_to_category.png',get_lang('AddSessionsInCategories'),'',ICON_SIZE_MEDIUM).'</a>';
@@ -278,6 +271,4 @@ if ($list_type == 'complete') {
     echo '<a href="'.api_get_self().'?list_type=complete">'.Display::return_icon('view_text.png',get_lang('Complete'),'',ICON_SIZE_MEDIUM).'</a>';
 }
 echo '</div>';
-
 echo Display::grid_html('sessions');
-Display::display_footer();

+ 11 - 2
main/template/default/admin/index.tpl

@@ -3,12 +3,21 @@
     <div id="settings">
         <div class="row">
             {% for role in app.admin_toolbar_roles %}
-                {% include app.template_style ~ "/admin/" ~ role ~ "/role_index.tpl" %}
+                {% if is_granted('ROLE_ADMIN') %}
+                    {# Skip session admin #}
+                    {% if (role != 'session_manager') %}
+                        {% include app.template_style ~ "/admin/" ~ role ~ "/role_index.tpl" %}
+                    {% endif %}
+                {% else %}
+                    {% include app.template_style ~ "/admin/" ~ role ~ "/role_index.tpl" %}
+                {% endif %}
+
+
             {% endfor %}
         </div>
     </div>
 
-    {% if is_granted('ROLE_ADMIN')%}
+    {% if is_granted('ROLE_ADMIN') %}
         <script>
         $(function() {
             //$("#settings").tabs();

+ 113 - 0
main/template/default/admin/session_manager/role_index.tpl

@@ -0,0 +1,113 @@
+<div class="span6">    
+    <div class="well_border">
+        <h4>
+            <img src="{{ _p.web_main }}img/icons/22/user.png" alt="{{ 'Users' | get_lang }}">
+            {{ 'Users' | get_lang }}
+        </h4>
+        <div style="list-style-type:none">
+            <form method="get" class="form-search" action="{{ _p.web_main }}admin/user_list.php">
+                <input class="span3" type="text" name="keyword" value="">
+                <button class="btn" type="submit">Search</button>
+            </form>
+        </div>
+        <ul>
+            <li>
+                <a href="{{ _p.web_main }}admin/user_list.php">
+                    User list
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}admin/user_add.php">
+                    Add a user
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}admin/user_export.php">
+                    Export users list
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}admin/user_import.php">
+                    Import users list
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}admin/extra_fields.php?type=user">
+                    Profiling
+                </a>
+            </li>
+        </ul>
+    </div>
+</div>
+
+<div class="span6">
+    <div class="well_border ">
+        <h4>
+            <img src="{{ _p.web_main }}img/icons/22/session.png" alt="{{ 'Sessions' | trans }}">{{ 'Sessions' | trans }}
+        </h4>
+        <div style="list-style-type:none">
+            <form method="GET" class="form-search" action="{{ _p.web_main }}session/session_list.php">
+                <input class="span3" type="text" name="keyword" value="">
+                <button class="btn" type="submit">Search</button>
+            </form>
+        </div>
+        <ul>
+            <li>
+                <a href="{{ _p.web_main }}session/session_list.php">
+                    Training sessions list
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}session/session_add.php">
+                    Add a training session
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}session_category_list.php">
+                    ListSessionCategory
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}session/session_import.php">
+                    Import sessions list
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}session/session_export.php">
+                    Export sessions list
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}admin/../coursecopy/copy_course_session.php">
+                    CopyFromCourseInSessionToAnotherSession
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}admin/user_move_stats.php">
+                    MoveUserStats
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}admin/career_dashboard.php">
+                    CareersAndPromotions
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}admin/usergroups.php">
+                    Classes
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}admin/exercise_report.php">
+                    ExerciseReport
+                </a>
+            </li>
+            <li>
+                <a href="{{ _p.web_main }}admin/extra_fields.php?type=session">
+                    ManageSessionFields
+                </a>
+            </li>
+        </ul>
+
+    </div>
+</div>

+ 6 - 5
main/template/default/layout/main_header.tpl

@@ -43,11 +43,11 @@
         {% include app.template_style ~ "/layout/topbar.tpl" %}
 
         {% block main_div_container %}
-        {% if app.full_width == 1 %}
-            <div id="main" class="container-fluid">
-        {% else %}
-            <div id="main" class="container">
-        {% endif %}
+            {% if app.full_width == 1 %}
+                <div id="main" class="container-fluid">
+            {% else %}
+                <div id="main" class="container">
+            {% endif %}
         {% endblock main_div_container %}
             <header>
                 <div class="row">
@@ -117,6 +117,7 @@
             {% else %}
                 <div id="top_main_content" class="row">
             {% endif %}
+
             {# course navigation links/shortcuts need to be activated by the admin #}
             {% include app.template_style ~ "/layout/course_navigation.tpl" %}
 {% endif %}

+ 7 - 0
main/template/default/layout/page_body.tpl

@@ -16,6 +16,13 @@
     </div>
 {% endif %}
 
+
+{% if is_granted('ROLE_PREVIOUS_ADMIN') %}
+    <div class="alert">
+        <a href="{{ path('index', {'_switch_user': '_exit'}) }}">{{ 'Exit impersonation' | trans }}</a>
+    </div>
+{% endif %}
+
 {#  Show messages #}
 {% if message != '' %}
     <section id="messages">

+ 8 - 8
main/template/default/layout/show_header.tpl

@@ -5,12 +5,12 @@
 #}
 
 {% if app.template.show_header == true %}
-        {% if plugin_content_top is not null %}
-            <div id="plugin_content_top" class="span12">
-                {{ plugin_content_top }}
-            </div>
-        {% endif %}
-        <div class="span12">
-            {% include app.template_style ~ "/layout/page_body.tpl" %}
-            {% block main_content_section_block %}<section id="main_content">{% endblock main_content_section_block %}
+    {% if plugin_content_top is not null %}
+        <div id="plugin_content_top" class="span12">
+            {{ plugin_content_top }}
+        </div>
+    {% endif %}
+    <div class="span12">
+        {% include app.template_style ~ "/layout/page_body.tpl" %}
+        {% block main_content_section_block %}<section id="main_content">{% endblock main_content_section_block %}
 {% endif %}

+ 1 - 0
main/template/default/layout/topbar.tpl

@@ -7,6 +7,7 @@
             {% else %}
                 <div id="main" class="container">
             {% endif %}
+
                 <a class="brand" href="{{ _p.web }}">
                     {{ "siteName" | get_setting }}
                 </a>

+ 129 - 0
main/work/add_document.php

@@ -0,0 +1,129 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+use ChamiloSession as Session;
+
+$language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
+
+require_once '../inc/global.inc.php';
+// Including necessary files
+require_once 'work.lib.php';
+
+if (ADD_DOCUMENT_TO_WORK == false) {
+    exit;
+}
+
+$current_course_tool  = TOOL_STUDENTPUBLICATION;
+
+$workId = isset($_GET['id']) ? intval($_GET['id']) : null;
+$docId = isset($_GET['document_id']) ? intval($_GET['document_id']) : null;
+$action = isset($_GET['action']) ? $_GET['action'] : null;
+
+if (empty($workId)) {
+    api_not_allowed(true);
+}
+
+$my_folder_data = get_work_data_by_id($workId);
+if (empty($my_folder_data)) {
+    api_not_allowed(true);
+}
+
+$work_data = get_work_assignment_by_id($workId);
+
+if (!api_is_allowed_to_edit()) {
+    api_not_allowed(true);
+}
+
+$courseInfo = api_get_course_info();
+
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq(), 'name' => get_lang('StudentPublications'));
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$workId, 'name' => $my_folder_data['title']);
+$interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AddDocument'));
+
+$error_message = null;
+
+switch ($action) {
+    case 'delete':
+        if (!empty($workId) && !empty($docId)) {
+            deleteDocumentToWork($docId, $workId, api_get_course_int_id());
+            $url = api_get_path(WEB_CODE_PATH).'work/add_document.php?id='.$workId;
+            header('Location: '.$url);
+            exit;
+        }
+        break;
+}
+
+Display :: display_header(null);
+
+if (empty($docId)) {
+    echo Display::page_subheader(get_lang('DocumentsAdded'));
+
+    $documents = getAllDocumentToWork($workId, api_get_course_int_id());
+    if (!empty($documents)) {
+        echo '<div class="well">';
+        foreach ($documents as $doc) {
+            $documentId = $doc['document_id'];
+            $docData = DocumentManager::get_document_data_by_id($documentId, $courseInfo['code']);
+            if ($docData) {
+                $url = api_get_path(WEB_CODE_PATH).'work/add_document.php?action=delete&id='.$workId.'&document_id='.$documentId;
+                $link = Display::url(get_lang('Delete'), $url);
+                echo $docData['title'].' '.$link.'<br />';
+            }
+
+        }
+        echo '</div>';
+    }
+
+    $document_tree = DocumentManager::get_document_preview($courseInfo, null, null, 0, false, '/', api_get_path(WEB_CODE_PATH).'work/add_document.php?id='.$workId);
+    echo Display::page_subheader(get_lang('DocumentToAdd'));
+    echo $document_tree;
+    echo '<hr /><div class="clear"></div>';
+
+} else {
+
+    $documentInfo = DocumentManager::get_document_data_by_id($docId, $courseInfo['code']);
+    $form = new FormValidator('add_doc', 'post', api_get_path(WEB_CODE_PATH).'work/add_document.php?id='.$workId.'&document_id='.$docId);
+    $form->addElement('header', get_lang('AddDocument'));
+    $form->addElement('hidden', 'add_doc', '1');
+    $form->addElement('hidden', 'id', $workId);
+    $form->addElement('hidden', 'document_id', $docId);
+    $form->addElement('label', get_lang('File'), $documentInfo['title']);
+    $form->addElement('style_submit_button', 'submit', get_lang('Add'));
+    $form->display();
+
+    if ($form->validate()) {
+        $values = $form->exportValues();
+        $workId = $values['id'];
+        $docId = $values['document_id'];
+        $data = getDocumentToWork($docId, $workId, api_get_course_int_id());
+
+        if (empty($data)) {
+            addDocumentToWork($docId, $workId, api_get_course_int_id());
+            Display::display_confirmation_message(get_lang('Added'));
+        } else {
+            Display::display_warning_message(get_lang('DocumentAlreadyAdded'));
+        }
+    }
+}
+
+/*
+ *
+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
+);
+
+CREATE TABLE IF NOT EXISTS c_student_publication_rel_user (
+    id  INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
+    work_id INT NOT NULL,
+    user_id INT NOT NULL,
+    c_id INT NOT NULL
+);
+
+
+
+*/
+
+

+ 104 - 0
main/work/add_user.php

@@ -0,0 +1,104 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+use ChamiloSession as Session;
+
+$language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
+
+require_once '../inc/global.inc.php';
+// Including necessary files
+require_once 'work.lib.php';
+
+if (ADD_DOCUMENT_TO_WORK == false) {
+    exit;
+}
+
+$current_course_tool  = TOOL_STUDENTPUBLICATION;
+
+$workId = isset($_GET['id']) ? intval($_GET['id']) : null;
+$userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : null;
+$action = isset($_GET['action']) ? $_GET['action'] : null;
+
+if (empty($workId)) {
+    api_not_allowed(true);
+}
+
+$my_folder_data = get_work_data_by_id($workId);
+if (empty($my_folder_data)) {
+    api_not_allowed(true);
+}
+
+$work_data = get_work_assignment_by_id($workId);
+
+if (!api_is_allowed_to_edit()) {
+    api_not_allowed(true);
+}
+
+$courseInfo = api_get_course_info();
+
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq(), 'name' => get_lang('StudentPublications'));
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$workId, 'name' => $my_folder_data['title']);
+$interbreadcrumb[] = array('url' => '#', 'name' => get_lang('AddUser'));
+
+$error_message = null;
+
+switch ($action) {
+    case 'add':
+
+        $data = getUserToWork($userId, $workId, api_get_course_int_id());
+        if (empty($data)) {
+            addUserToWork($userId, $workId, api_get_course_int_id());
+        }
+        $url = api_get_path(WEB_CODE_PATH).'work/add_user.php?id='.$workId;
+        header('Location: '.$url);
+        exit;
+
+        break;
+    case 'delete':
+        if (!empty($workId) && !empty($userId)) {
+            deleteUserToWork($userId, $workId, api_get_course_int_id());
+            $url = api_get_path(WEB_CODE_PATH).'work/add_user.php?id='.$workId;
+            header('Location: '.$url);
+            exit;
+        }
+        break;
+}
+
+Display :: display_header(null);
+
+echo Display::page_subheader(get_lang('UsersAdded'));
+
+$items = getAllUserToWork($workId, api_get_course_int_id());
+$usersAdded = array();
+if (!empty($items)) {
+    echo '<div class="well">';
+    foreach ($items as $data) {
+        $myUserId = $data['user_id'];
+        $usersAdded[] = $myUserId;
+        $userInfo = api_get_user_info($myUserId);
+        $url = api_get_path(WEB_CODE_PATH).'work/add_user.php?action=delete&id='.$workId.'&user_id='.$myUserId;
+        $link = Display::url(get_lang('Delete'), $url);
+        echo $userInfo['complete_name'].' '.$link.'<br />';
+    }
+    echo '</div>';
+}
+
+$userList = CourseManager::get_user_list_from_course_code($courseInfo['code'], api_get_session_id(), null, null, STUDENT);
+
+echo Display::page_subheader(get_lang('UserToAdd'));
+if (!empty($userList)) {
+    echo '<div class="well">';
+    foreach ($userList as $user) {
+        if (in_array($user['user_id'], $usersAdded)) {
+            continue;
+        }
+        $userName = api_get_person_name($user['firstname'], $user['lastname']);
+        $url = api_get_path(WEB_CODE_PATH).'work/add_user.php?action=add&id='.$workId.'&user_id='.$user['user_id'];
+        $link = Display::url(get_lang('Add'), $url);
+        echo $userName.' '.$link.'<br />';
+    }
+    echo '</div>';
+}
+
+
+echo '<hr /><div class="clear"></div>';

+ 20 - 15
main/work/download.php

@@ -12,6 +12,8 @@
 
 session_cache_limiter('public');
 require_once '../inc/global.inc.php';
+require_once 'work.lib.php';
+
 $current_course_tool  = TOOL_STUDENTPUBLICATION;
 
 $this_section = SECTION_COURSES;
@@ -29,26 +31,29 @@ $id = intval($_GET['id']);
 $course_info = api_get_course_info();
 
 if (empty($course_info)) {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
 
 $tbl_student_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
 
-if (!empty($course_info['real_id'])) {    
+if (!empty($course_info['real_id'])) {
 	$sql = 'SELECT * FROM '.$tbl_student_publication.' WHERE c_id = '.$course_info['real_id'].' AND id = "'.$id.'"';
 	$result = Database::query($sql);
-	if ($result && Database::num_rows($result)) {
-	    $row = Database::fetch_array($result, 'ASSOC');        
+    if ($result && Database::num_rows($result)) {
+        $row = Database::fetch_array($result, 'ASSOC');
         $full_file_name = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.$row['url'];
-           
-        $item_info = api_get_item_property_info(api_get_course_int_id(), 'work', $row['id']);           
+
+        $item_info = api_get_item_property_info(api_get_course_int_id(), 'work', $row['id']);
+
+        allowOnlySubscribedUser(api_get_user_id(), $row['parent_id'], $course_info['real_id']);
+
         if (empty($item_info)) {
             exit;
         }
-        
+
         /*
         field show_score in table course :  0 => 	New documents are visible for all users
-                                            1 =>    New documents are only visible for the teacher(s) 
+                                            1 =>    New documents are only visible for the teacher(s)
         field visibility in table item_property :   0 => eye closed, invisible for all students
                                                     1 => eye open
         field accepted in table c_student_publication : 0 => eye closed, invisible for all students
@@ -56,24 +61,24 @@ if (!empty($course_info['real_id'])) {
         (we should have visibility == accepted , otherwise there is an inconsistency in the Database)
         field value in table c_course_setting :     0 => Allow learners to delete their own publications = NO
                                                     1 => Allow learners to delete their own publications = YES
-                                                    
+
         +------------------+------------------------------+----------------------------+
         |Can download work?|      doc visible for all = 0 |     doc visible for all = 1|
         +------------------+------------------------------+----------------------------+
         |  visibility = 0  | editor only                  | editor only                |
         |                  |                              |                            |
-        +------------------+------------------------------+----------------------------+                  
+        +------------------+------------------------------+----------------------------+
         |  visibility = 1  | editor                       | editor                     |
         |                  | + owner of the work          | + any student              |
-        +------------------+------------------------------+----------------------------+                  
+        +------------------+------------------------------+----------------------------+
         (editor = teacher + admin + anybody with right api_is_allowed_to_edit)
         */
-        
+
         $work_is_visible = ($item_info['visibility'] == 1 && $row['accepted'] == 1);
         $doc_visible_for_all = ($course_info['show_score'] == 1);
         $is_editor = api_is_allowed_to_edit(true,true,true);
         $student_is_owner_of_work = ($row['user_id'] == api_get_user_id());
-        
+
 	    if ($is_editor
 	        || (!$doc_visible_for_all && $work_is_visible && $student_is_owner_of_work)
 	        || ($doc_visible_for_all && $work_is_visible)) {
@@ -84,7 +89,7 @@ if (!empty($course_info['real_id'])) {
 		    }
 	    } else {
             api_not_allowed();
-        }	    
+        }
 	}
 }
-exit;
+exit;

+ 6 - 0
main/work/downloadfolder.inc.php

@@ -33,6 +33,9 @@ if (empty($_course) || empty($_course['path'])) {
 
 $sys_course_path = api_get_path(SYS_COURSE_PATH);
 
+//zip library for creation of the zipfile
+require_once api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php';
+
 //Creating a ZIP file
 $temp_zip_file = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
 
@@ -68,6 +71,9 @@ if (api_is_allowed_to_edit()) {
 
 } else {
     $courseInfo = api_get_course_info();
+
+    allowOnlySubscribedUser(api_get_user_id(), $work_id, $courseInfo['real_id']);
+
     $userCondition = null;
 
     // All users

+ 4 - 3
main/work/edit.php

@@ -147,7 +147,7 @@ if ($is_allowed_to_edit && !empty($item_id)) {
     }
 }
 
-$form->addElement('hidden', 'active',   1);
+$form->addElement('hidden', 'active', 1);
 $form->addElement('hidden', 'accepted', 1);
 $form->addElement('hidden', 'item_to_edit', $item_id);
 $form->addElement('hidden', 'sec_token', $token);
@@ -178,9 +178,10 @@ if ($form->validate()) {
             if ($is_author) {
                 $work_data = get_work_data_by_id($item_to_edit_id);
 
-                if (!empty($_POST['title']))
+                if (!empty($_POST['title'])) {
                     $title 		 = isset($_POST['title']) ? $_POST['title'] : $work_data['title'];
-                    $description = isset($_POST['description']) ? $_POST['description'] : $work_data['description'];
+                }
+                $description = isset($_POST['description']) ? $_POST['description'] : $work_data['description'];
 
                 if ($is_allowed_to_edit && ($_POST['qualification'] !='' )) {
                     $add_to_update = ', qualificator_id ='."'".api_get_user_id()."',";

+ 16 - 15
main/work/file.php

@@ -4,24 +4,25 @@ Use Model\StudentPublication;
 Use Model\Course;
 
 /**
- * 	Return either
- *
+ * 	Return either 
+ * 
  *      - one work item (file)
  *      - several work items (files) zipped together
- *
+ * 
  * Used to transfer files to another application through http.
- *
+ * 
  * Script parameters:
- *
- *      - id        id(s) of the work item id=1 or id=1,2,4
+ * 
+ *      - id        id(s) of the work item id=1 or id=1,2,4  
  *      - cidReq    course code
- *
+ * 
  * Note this script enables key authentication so access with a key token is possible.
- *
+ * 
  * @package chamilo.document
  * @license see /license.txt
  * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
  */
+require_once __DIR__ . '/../inc/autoload.inc.php';
 KeyAuth::enable();
 
 require_once __DIR__ . '/../inc/global.inc.php';
@@ -40,7 +41,7 @@ $course = Course::current();
 
 /**
  * No files requested. We make sure we return 404 error to tell the client
- * that the call failed.
+ * that the call failed. 
  */
 if (count($ids) == 0 || empty($course)) {
     Response::not_found();
@@ -68,7 +69,7 @@ if (count($ids) == 1) {
     }
 
     /**
-     * one folder requested
+     * one folder requested 
      */
     $items = array();
     $children = $pub->get_children();
@@ -92,7 +93,7 @@ if (count($ids) == 1) {
 }
 
 /**
- * Several files requested. In this case we zip them together.
+ * Several files requested. In this case we zip them together. 
  */
 $items = array();
 foreach ($ids as $id) {
@@ -104,19 +105,19 @@ foreach ($ids as $id) {
         $items[] = $pub;
     }
     /**
-     * We ignore folders
+     * We ignore folders 
      */
 }
 
 /**
- * Requested files may not be accessible.
+ * Requested files may not be accessible. 
  */
 if (count($items) == 0) {
     Response::not_found();
 }
 
 /**
- * Zip files together.
+ * Zip files together. 
  */
 $zip = Chamilo::temp_zip();
 foreach ($items as $item) {
@@ -126,7 +127,7 @@ foreach ($items as $item) {
 }
 
 /**
- * Send file for download
+ * Send file for download 
  */
 event_download(Uri::here());
 DocumentManager::file_send_for_download($zip->get_path(), false, get_lang('StudentPublications') . '.zip');

+ 29 - 2
main/work/upload.php

@@ -26,6 +26,7 @@ $work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
 $is_allowed_to_edit = api_is_allowed_to_edit();
 $course_id = api_get_course_int_id();
 $user_id = api_get_user_id();
+$userInfo = api_get_user_info();
 $session_id = api_get_session_id();
 $course_code = api_get_course_id();
 $course_info = api_get_course_info();
@@ -35,6 +36,8 @@ if (empty($work_id)) {
     api_not_allowed(true);
 }
 
+allowOnlySubscribedUser($user_id, $work_id, $course_id);
+
 $parent_data = $my_folder_data = get_work_data_by_id($work_id);
 
 if (empty($parent_data)) {
@@ -74,11 +77,15 @@ if (!empty($parent_data) && !empty($parent_data['qualification'])) {
     }
 }*/
 
+$has_expired = false;
+$has_ended   = false;
+$message = null;
+
 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') {
-        $time_now		= time();
+        $time_now = time();
 
         if (!empty($homework['expires_on']) && $homework['expires_on'] != '0000-00-00 00:00:00') {
             $time_expires 	= api_strtotime($homework['expires_on'], 'UTC');
@@ -103,6 +110,16 @@ if (!empty($my_folder_data)) {
         $ends_on 	= api_convert_and_format_date($homework['ends_on']);
         $expires_on = api_convert_and_format_date($homework['expires_on']);
     }
+
+    if ($has_ended) {
+        $message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
+    } elseif ($has_expired) {
+        $message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
+    } else {
+        if ($has_expired) {
+            $message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
+        }
+    }
 }
 
 $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq(), 'name' => get_lang('StudentPublications'));
@@ -119,7 +136,7 @@ $form->addElement('header', $form_title);
 $show_progress_bar = false;
 
 if ($submitGroupWorkUrl) {
-    // For user comming from group space to publish his work
+    // For user coming from group space to publish his work
     $realUrl = str_replace($_configuration['root_sys'], api_get_path(WEB_PATH), str_replace("\\", '/', realpath($submitGroupWorkUrl)));
     $form->addElement('hidden', 'newWorkUrl', $submitGroupWorkUrl);
     $text_document = $form->addElement('text', 'document', get_lang('Document'));
@@ -160,6 +177,12 @@ if ($show_progress_bar) {
     $form->add_real_progress_bar('uploadWork', 'file');
 }
 
+$documentTemplateData = getDocumentTemplateFromWork($work_id, $course_info);
+if (!empty($documentTemplateData)) {
+    $defaults['title'] = $userInfo['complete_name'].'_'.$documentTemplateData['title'].'_'.substr(api_get_utc_datetime(), 0, 10);
+    $defaults['description'] = $documentTemplateData['file_content'];
+}
+
 $form->setDefaults($defaults);
 $error_message = null;
 $_course = api_get_course_info();
@@ -309,6 +332,9 @@ $htmlHeadXtra[] = to_javascript_work();
 Display :: display_header(null);
 
 if (!empty($work_id)) {
+
+    echo $message;
+
     if ($is_allowed_to_edit) {
         if (api_resource_is_locked_by_gradebook($work_id, LINK_STUDENTPUBLICATION)) {
             echo Display::display_warning_message(get_lang('ResourceLockedByGradebook'));
@@ -322,6 +348,7 @@ if (!empty($work_id)) {
             Display::display_error_message(get_lang('ActionNotAllowed'));
         }
     } elseif ($student_can_edit_in_session && $has_ended == false) {
+
         $form->display();
     } else {
         Display::display_error_message(get_lang('ActionNotAllowed'));

+ 13 - 9
main/work/view.php

@@ -1,5 +1,7 @@
 <?php
 
+/* For licensing terms, see /license.txt */
+
 $language_file = array('exercice', 'work', 'document', 'admin');
 
 require_once '../inc/global.inc.php';
@@ -7,30 +9,32 @@ $current_course_tool  = TOOL_STUDENTPUBLICATION;
 
 require_once 'work.lib.php';
 
-$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : null;
+$id = isset($_GET['id']) ? intval($_GET['id']) : null;
 $work = get_work_data_by_id($id);
 
 if (empty($id) || empty($work)) {
-	api_not_allowed();
+    api_not_allowed();
 }
 $interbreadcrumb[] = array ('url' => 'work.php', 'name' => get_lang('StudentPublications'));
 
 $my_folder_data = get_work_data_by_id($work['parent_id']);
 $course_info = api_get_course_info();
 
+allowOnlySubscribedUser(api_get_user_id(), $work['parent_id'], $course_info['real_id']);
+
 if (user_is_author($id) || $course_info['show_score'] == 0 && $work['active'] == 1 && $work['accepted'] == 1) {
     $url_dir = 'work.php?&id=' . $my_folder_data['id'];
-    $interbreadcrumb[] = array ('url' => $url_dir,'name' =>  $my_folder_data['title']);	
-    $interbreadcrumb[] = array ('url' => '#','name' =>  $work['title']);	
+    $interbreadcrumb[] = array ('url' => $url_dir,'name' =>  $my_folder_data['title']);
+    $interbreadcrumb[] = array ('url' => '#','name' =>  $work['title']);
 
     if (($course_info['show_score'] == 0 && $work['active'] == 1 && $work['accepted'] == 1) || api_is_allowed_to_edit() || ($work['user_id'] == api_get_user_id() && $work['active'] == 1 && $work['accepted'] == 1)) {
-        $tpl = $app['template'];
+        $tpl = new Template();
         $tpl->assign('work', $work);
-        $template = $tpl->get_template('work/view.tpl');	
+        $template = $tpl->get_template('work/view.tpl');
         $content  = $tpl->fetch($template);
         $tpl->assign('content', $content);
-        $tpl->display_one_col_template();	
+        $tpl->display_one_col_template();
     } else {
-        api_not_allowed();	
+        api_not_allowed();
     }
-}
+}

+ 160 - 30
main/work/work.lib.php

@@ -17,6 +17,8 @@ require_once api_get_path(SYS_CODE_PATH).'document/document.inc.php';
 require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php';
 require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
 
+define('ADD_DOCUMENT_TO_WORK', false);
+
 /**
  * Displays action links (for admins, authorized groups members and authorized students)
  * @param	string	Current dir
@@ -491,6 +493,7 @@ function display_student_publications_list($id, $my_folder_data, $work_parents,
 
     $group_id = api_get_group_id();
 
+
 	if (is_array($work_parents)) {
 		foreach ($work_parents as $work_parent) {
 			$sql_select_directory = "SELECT
@@ -574,7 +577,7 @@ function display_student_publications_list($id, $my_folder_data, $work_parents,
 					list($d_year, $d_month, $d_day) = explode('-', $parts[0]);
 					list($d_hour, $d_minute) = explode(':', $parts[1]);
 
-                    $qualification_input[] = FormValidator :: createElement('text', 'qualification');
+                    $qualification_input[] = $form_folder->createElement('text', 'qualification');
                     $form_folder -> addGroup($qualification_input, 'qualification', get_lang('QualificationNumeric'));
 
                     if (Gradebook::is_active()) {
@@ -590,7 +593,7 @@ function display_student_publications_list($id, $my_folder_data, $work_parents,
                         //Loading gradebook select
                         load_gradebook_select_in_tool($form_folder);
 
-                        $weight_input2[] = FormValidator :: createElement('text', 'weight');
+                        $weight_input2[] = $form_folder->createElement('text', 'weight');
                         $form_folder -> addGroup($weight_input2, 'weight', get_lang('WeightInTheGradebook'), 'size="10"');
 
                         $form_folder -> addElement('html', '</div>');
@@ -805,36 +808,14 @@ function display_student_publications_list($id, $my_folder_data, $work_parents,
 
 			if (api_is_allowed_to_edit()) {
                 $cant_files = get_count_work($work_data['id']);
-
-                /*$sql_document = "SELECT count(*)
-                                 FROM $work_table w INNER JOIN $user_table u ON w.user_id = u.user_id
-                                 WHERE w.c_id = $course_id AND w.parent_id = ".$work_data['id']." AND w.active IN (0, 1)";*/
 			} else {
-                $cant_files = get_count_work($work_data['id'], api_get_user_id());
-                /*
-                $user_filter = "user_id = ".api_get_user_id()." AND ";
-                if ($course_info['show_score'] == 0) {
-                    $user_filter  = null;
+                $isSubscribed = userIsSubscribedToWork(api_get_user_id(), $work_data['id'], $course_id);
+                if ($isSubscribed == false) {
+                    continue;
                 }
-
-                $sql_document = "SELECT count(*) FROM $work_table s, $iprop_table p
-                                  WHERE s.c_id = $course_id  AND
-                                        p.c_id = $course_id AND
-                                        s.id = p.ref AND
-                                        p.tool='work' AND
-                                        s.accepted='1' AND
-                                        $user_filter
-                                        parent_id = ".$work_data['id']." AND
-                                        active = 1 AND
-                                        parent_id = ".$work_parent->id."";*/
+                $cant_files = get_count_work($work_data['id'], api_get_user_id());
 			}
 
-
-			//count documents
-			/*$res_document   = Database::query($sql_document);
-			$count_document = Database::fetch_row($res_document);
-			$cant_files     = $count_document[0];*/
-
 			$text_file = get_lang('FilesUpload');
 
 			if ($cant_files == 1) {
@@ -1793,7 +1774,8 @@ function get_work_user_list($start, $limit, $column, $direction, $work_id, $wher
                 if ($work['contains_file']) {
                     $link_to_download = '<a href="download.php?id='.$item_id.'">'.Display::return_icon('save.png', get_lang('Save'),array(), ICON_SIZE_SMALL).'</a> ';
                 } else {
-                    $link_to_download = '<a href="view.php?id='.$item_id.'">'.Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a> ';
+                    //api_get_cidreq()
+                   //$link_to_download = '<a href="view.php?id='.$item_id.'">'.Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a> ';
                 }
 
                 $send_to = Portfolio::share('work', $work['id'],  array('style' => 'white-space:nowrap;'));
@@ -1849,7 +1831,7 @@ function get_work_user_list($start, $limit, $column, $direction, $work_id, $wher
                         $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL);
                     }
                     if (api_get_course_setting('student_delete_own_publication') == 1) {
-                        $action .= '<a href="'.$url.'work.php?'.api_get_cidreq().'&action=delete&amp;item_id='.$item_id.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'"  >'.Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
+                        $action .= ' <a href="'.$url.'work.php?'.api_get_cidreq().'&action=delete&amp;item_id='.$item_id.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'"  >'.Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
                     }
                 } else {
                     $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL);
@@ -2140,3 +2122,151 @@ function display_list_users_without_publication($task_id, $studentId = null)
 	$column_show[] = 1;
 	Display::display_sortable_config_table('work', $table_header, $data, $sorting_options, $paging_options, $my_params, $column_show);
 }
+
+// Document to work
+
+function addDocumentToWork($documentId, $workId, $courseId)
+{
+    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
+    $params = array(
+        'document_id' => $documentId,
+        'work_id' => $workId,
+        'c_id' => $courseId
+    );
+    Database::insert($table, $params);
+}
+
+function getDocumentToWork($documentId, $workId, $courseId)
+{
+    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
+    $params = array(
+        'document_id = ? and work_id = ? and c_id = ?' => array($documentId, $workId, $courseId)
+    );
+    return Database::select('*', $table, array('where' => $params));
+}
+
+function getAllDocumentToWork($workId, $courseId)
+{
+    if (ADD_DOCUMENT_TO_WORK == false) {
+        return array();
+    }
+    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
+    $params = array(
+        'work_id = ? and c_id = ?' => array($workId, $courseId)
+    );
+    return Database::select('*', $table, array('where' => $params));
+}
+
+
+function deleteDocumentToWork($documentId, $workId, $courseId)
+{
+    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_DOCUMENT);
+    $params = array(
+        'document_id = ? and work_id = ? and c_id = ?' => array($documentId, $workId, $courseId)
+    );
+    Database::delete($table, $params);
+}
+
+// User to work
+
+
+function addUserToWork($userId, $workId, $courseId)
+{
+    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
+    $params = array(
+        'user_id' => $userId,
+        'work_id' => $workId,
+        'c_id' => $courseId
+    );
+    Database::insert($table, $params);
+}
+
+function getUserToWork($userId, $workId, $courseId)
+{
+    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
+    $params = array(
+        'user_id = ? and work_id = ? and c_id = ?' => array($userId, $workId, $courseId)
+    );
+    return Database::select('*', $table, array('where' => $params));
+}
+
+function getAllUserToWork($workId, $courseId)
+{
+    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
+    $params = array(
+        'work_id = ? and c_id = ?' => array($workId, $courseId)
+    );
+    return Database::select('*', $table, array('where' => $params));
+}
+
+function userAddedToWork($userId, $workId, $courseId)
+{
+    /*$table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
+    $params = array(
+        'user_id = ? and work_id = ? and c_id = ?' => array($userId, $workId, $courseId)
+    );
+    $result = Database::select('count(*)', $table, array('where' => $params));*/
+}
+
+
+function deleteUserToWork($userId, $workId, $courseId)
+{
+    $table = Database::get_course_table(TABLE_STUDENT_PUBLICATION_REL_USER);
+    $params = array(
+        'user_id = ? and work_id = ? and c_id = ?' => array($userId, $workId, $courseId)
+    );
+    Database::delete($table, $params);
+}
+
+function userIsSubscribedToWork($userId, $workId, $courseId)
+{
+    if (ADD_DOCUMENT_TO_WORK == false) {
+        return true;
+    }
+    $subscribedUsers = getAllUserToWork($workId, $courseId);
+
+    if (empty($subscribedUsers)) {
+        return true;
+    } else {
+        $subscribedUsersIdList = array();
+        foreach ($subscribedUsers as $item) {
+            $subscribedUsersIdList[] = $item['user_id'];
+        }
+        if (in_array($userId, $subscribedUsersIdList)) {
+            return true;
+        }
+    }
+    return false;
+}
+
+function allowOnlySubscribedUser($userId, $workId, $courseId)
+{
+    if (ADD_DOCUMENT_TO_WORK == false) {
+        return true;
+    }
+    if (api_is_platform_admin() || api_is_allowed_to_edit()) {
+        return true;
+    }
+    if (userIsSubscribedToWork($userId, $workId, $courseId) == false) {
+        api_not_allowed(true);
+    }
+
+}
+
+function getDocumentTemplateFromWork($workId, $courseInfo)
+{
+    $documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
+    if (!empty($documents)) {
+        foreach ($documents as $doc) {
+            $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
+            $fileInfo = pathinfo($docData['path']);
+            if ($fileInfo['extension'] == 'html') {
+                if (file_exists($docData['absolute_path']) && is_file($docData['absolute_path'])) {
+                    $docData['file_content'] = file_get_contents($docData['absolute_path']);
+                    return $docData;
+                }
+            }
+        }
+    }
+    return array();
+}

+ 12 - 52
main/work/work.php

@@ -41,7 +41,7 @@ use ChamiloSession as Session;
  *
  */
 
-/*		INIT SECTION */
+/* INIT SECTION */
 
 $language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
 
@@ -55,6 +55,11 @@ api_protect_course_script(true);
 // Including necessary files
 require_once 'work.lib.php';
 
+require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
+require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php';
+
 $course_id      = api_get_course_int_id();
 $course_info    = api_get_course_info();
 $user_id 	    = api_get_user_id();
@@ -109,10 +114,6 @@ $title 			        = isset($_REQUEST['title']) ? $_REQUEST['title'] : '';
 $description 	        = isset($_REQUEST['description']) ? $_REQUEST['description'] : '';
 $uploadvisibledisabled  = isset($_REQUEST['uploadvisibledisabled']) ? Database::escape_string($_REQUEST['uploadvisibledisabled']) : $course_info['show_score'];
 
-// get data for publication assignment
-$has_expired = false;
-$has_ended   = false;
-
 //directories management
 $sys_course_path 	= api_get_path(SYS_COURSE_PATH);
 $course_dir 		= $sys_course_path . $_course['path'];
@@ -142,10 +143,10 @@ if (isset ($_POST['cancelForm']) && !empty ($_POST['cancelForm'])) {
 if ($_SERVER['REQUEST_METHOD'] == 'POST' && !sizeof($_POST)) {
     if (strstr($_SERVER['REQUEST_URI'], '?')) {
         header('Location: ' . $_SERVER['REQUEST_URI'] . '&submitWork=1');
-        exit ();
+        exit();
     } else {
         header('Location: ' . $_SERVER['REQUEST_URI'] . '?submitWork=1');
-        exit ();
+        exit();
     }
 }
 
@@ -252,59 +253,16 @@ if (!in_array($action, array('add','create_dir'))) {
     $token = Security::get_token();
 }
 
-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') {
-        $time_now		= time();
-
-        if (!empty($homework['expires_on']) && $homework['expires_on'] != '0000-00-00 00:00:00') {
-            $time_expires 	= api_strtotime($homework['expires_on'], 'UTC');
-            $difference 	= $time_expires - $time_now;
-            if ($difference < 0) {
-                $has_expired = true;
-            }
-        }
-
-        if (empty($homework['expires_on']) || $homework['expires_on'] == '0000-00-00 00:00:00') {
-            $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 ($difference2 < 0) {
-                $has_ended = true;
-            }
-        }
-
-        $ends_on 	= api_convert_and_format_date($homework['ends_on']);
-        $expires_on = api_convert_and_format_date($homework['expires_on']);
-
-        if ($has_ended) {
-            $message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
-        } elseif ($has_expired) {
-            $message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
-        } else {
-            if ($has_expired) {
-                $message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
-            }
-        }
-    }
-}
-
 display_action_links($work_id, $curdirpath, $action);
 
-echo $message;
-
-//for teachers
+// for teachers
 
 switch ($action) {
     case 'settings':
         //if posts
         if ($is_allowed_to_edit && !empty($_POST['changeProperties'])) {
             // Changing the tool setting: default visibility of an uploaded document
-            // @todo i
+            // @todo
             $query = "UPDATE ".$main_course_table." SET show_score='" . $uploadvisibledisabled . "' WHERE code='" . api_get_course_id() . "'";
             $res = Database::query($query);
 
@@ -783,6 +741,8 @@ switch ($action) {
             echo $table->toHtml();
             echo '</div>';
         } else {
+
+
             display_student_publications_list($work_id, $my_folder_data, $work_parents, $origin, $add_query, null);
         }
 

+ 16 - 0
main/work/work_list.php

@@ -35,6 +35,7 @@ $courseInfo = api_get_course_info();
 $htmlHeadXtra[] = api_get_jqgrid_js();
 $url_dir = api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq();
 
+allowOnlySubscribedUser(api_get_user_id(), $workId, $courseInfo['real_id']);
 
 if (!empty($group_id)) {
     $group_properties  = GroupManager :: get_group_properties($group_id);
@@ -77,6 +78,21 @@ if (!empty($my_folder_data['description'])) {
     echo '<p><div><strong>'.get_lang('Description').':</strong><p>'.Security::remove_XSS($my_folder_data['description']).'</p></div></p>';
 }
 
+$documents = getAllDocumentToWork($workId, $courseInfo['real_id']);
+if (!empty($documents)) {
+    $docContent = '<ul class="nav nav-list well">';
+    $docContent .= '<li class="nav-header">'.get_lang('Documents').'</li>';
+    foreach ($documents as $doc) {
+        $docData = DocumentManager::get_document_data_by_id($doc['document_id'], $courseInfo['code']);
+        if ($docData) {
+            $docContent .= '<li><a target="_blank" href="'.$docData['url'].'">'.$docData['title'].'</a></li>';
+        }
+
+    }
+    $docContent .= '</ul><br />';
+    echo $docContent;
+}
+
 $check_qualification = intval($my_folder_data['qualification']);
 
 if (!empty($work_data['enable_qualification']) && !empty($check_qualification)) {

+ 10 - 2
main/work/work_list_all.php

@@ -66,10 +66,18 @@ echo '<div class="actions">';
 echo '<a href="'.api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq().'&origin='.$origin.'&gradebook='.$gradebook.'">'.Display::return_icon('back.png', get_lang('BackToWorksList'),'',ICON_SIZE_MEDIUM).'</a>';
 if (api_is_allowed_to_session_edit(false, true) && !empty($workId)) {
     echo '<a href="'.api_get_path(WEB_CODE_PATH).'work/upload.php?'.api_get_cidreq().'&id='.$workId.'&origin='.$origin.'&gradebook='.$gradebook.'">';
-    echo Display::return_icon('upload_file.png', get_lang('UploadADocument'),'',ICON_SIZE_MEDIUM).'</a>';
+    echo Display::return_icon('upload_file.png', get_lang('UploadADocument'), '', ICON_SIZE_MEDIUM).'</a>';
+
+    if (ADD_DOCUMENT_TO_WORK) {
+        echo '<a href="'.api_get_path(WEB_CODE_PATH).'work/add_document.php?'.api_get_cidreq().'&id='.$workId.'">';
+        echo Display::return_icon('new_document.png', get_lang('AddDocument'), '', ICON_SIZE_MEDIUM).'</a>';
+
+        echo '<a href="'.api_get_path(WEB_CODE_PATH).'work/add_user.php?'.api_get_cidreq().'&id='.$workId.'">';
+        echo Display::return_icon('user.png', get_lang('AddUser'), '', ICON_SIZE_MEDIUM).'</a>';
+    }
 
     $display_output .= '<a href="'.api_get_path(WEB_CODE_PATH).'work/work_missing.php?'.api_get_cidreq().'&amp;id='.$workId.'&amp;curdirpath='.$cur_dir_path.'&amp;origin='.$origin.'&amp;gradebook='.$gradebook.'&amp;list=without">'.
-    Display::return_icon('exercice_uncheck.png', get_lang('ViewUsersWithoutTask'),'',ICON_SIZE_MEDIUM)."</a>\n";
+    Display::return_icon('exercice_uncheck.png', get_lang('ViewUsersWithoutTask'), '', ICON_SIZE_MEDIUM)."</a>";
     $count = get_count_work($workId);
     if ($count > 0) {
         $display_output .= '<a href="downloadfolder.inc.php?id='.$workId.'">'.Display::return_icon('save_pack.png', get_lang('Save'), array('style' => 'float:right;'), ICON_SIZE_MEDIUM).'</a>';

+ 2 - 1
main/work/work_list_others.php

@@ -38,8 +38,9 @@ if ($courseInfo['show_score'] == 1) {
     api_not_allowed(true);
 }
 
-$htmlHeadXtra[] = api_get_jqgrid_js();
+allowOnlySubscribedUser(api_get_user_id(), $workId, $courseInfo['real_id']);
 
+$htmlHeadXtra[] = api_get_jqgrid_js();
 
 if (!empty($group_id)) {
     $group_properties  = GroupManager :: get_group_properties($group_id);

+ 7 - 5
src/ChamiloLMS/Command/Template/AsseticDumpCommand.php

@@ -28,7 +28,7 @@ class AsseticDumpCommand extends Command
     /**
      * @param Console\Input\InputInterface $input
      * @param Console\Output\OutputInterface $output
-     * @return int|null|void
+     * @return integer|null|boolean|void
      */
     protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
     {
@@ -49,10 +49,10 @@ class AsseticDumpCommand extends Command
         if (empty($theme)) {
             $dialog = $this->getHelperSet()->get('dialog');
             if (!$dialog->askConfirmation(
-                $output,
-                '<question>Are you sure you want to dump css/js of all themes?</question>(y/N)',
-                false
-            )
+                    $output,
+                    '<question>Are you sure you want to dump css/js of all themes?</question>(y/N)',
+                    false
+                )
             ) {
                 return;
             }
@@ -89,5 +89,7 @@ class AsseticDumpCommand extends Command
             }
         }
         $output->writeln('<info>Dump finished</info>');
+
+        return true;
     }
 }

+ 24 - 0
src/ChamiloLMS/Component/Auth/LoginListener.php

@@ -0,0 +1,24 @@
+<?php
+namespace ChamiloLMS\Component\Auth;
+
+use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
+use Symfony\Component\Security\Http\Event\SwitchUserEvent;
+
+class LoginListener
+{
+    /**
+     * Fired on switch user, you can remove attributes or whatever you want here.
+     * @param SwitchUserEvent $event
+     */
+    public function onSecuritySwitchUser(SwitchUserEvent $event)
+    {
+        /** @var \Entity\User $user */
+        $user = $event->getTargetUser();
+        /*var_dump($user );
+        var_dump($event->getRequest()->getUser());
+        */
+
+        $session = $event->getRequest()->getSession();
+        //$session->remove('partThatShouldNotCarryOver');
+    }
+}

+ 13 - 5
src/ChamiloLMS/Component/Auth/LoginSuccessHandler.php

@@ -35,17 +35,24 @@ class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface
      */
     public function onAuthenticationSuccess(Request $request, TokenInterface $token)
     {
+        /** @var \Entity\User $user */
+        $user = $token->getUser();
+        $userId = $user->getUserId();
+
+        event_login($user);
+
+        $session = $request->getSession();
+
+        // Setting last login datetime
+        $session->set('user_last_login_datetime', api_get_utc_datetime());
+
         $response = null;
-        //$session = $request->getSession();
         /* Possible values: index.php, user_portal.php, main/auth/courses.php */
         $pageAfterLogin = api_get_setting('page_after_login');
 
-        $user = $token->getUser();
-        $userId = $user->getUserId();
-
         $url = null;
         if ($this->security->isGranted('ROLE_STUDENT') && !empty($pageAfterLogin)) {
-            switch($pageAfterLogin) {
+            switch ($pageAfterLogin) {
                 case 'index.php':
                     $url = $this->router->generate('index');
                     break;
@@ -57,6 +64,7 @@ class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface
                     break;
             }
         }
+
         // Redirecting to a course or a session
 
         if (api_get_setting('go_to_course_after_login') == 'true') {

+ 15 - 3
src/ChamiloLMS/Component/Auth/Role.php

@@ -6,17 +6,29 @@ namespace ChamiloLMS\Component\Auth;
  */
 
 use Symfony\Component\Security\Core\Role\RoleInterface;
-use Symfony\Component\Security\Core\User\UserInterface;
+use Symfony\Component\Security\Core\User\AdvancedUserInterface;
 
 class Role implements RoleInterface
 {
-    public function __construct(UserInterface $user)
+    private $user;
+
+    /**
+     * @param AdvancedUserInterface $user
+     */
+    public function __construct(AdvancedUserInterface $user)
     {
         $this->user = $user;
     }
 
+    /**
+     * @return string
+     */
     public function getRole()
     {
-        //return 'ROLE_' . strtoupper($this->user->getUsername());
+        /*$globalPlatform = api_is_global_platform_admin($this->user->getUserId());
+        if ($globalPlatform) {
+            //return 'ROLE_GLOBAL_ADMIN';
+        }*/
+
     }
 }

+ 0 - 1
src/ChamiloLMS/Controller/Admin/AdminController.php

@@ -216,7 +216,6 @@ class AdminController extends CommonController
         $blocks['sessions']['items'] = $items;
         $blocks['sessions']['extra'] = null;
 
-
         /* Settings */
         if (api_is_platform_admin()) {
 

+ 0 - 67
src/ChamiloLMS/Controller/IndexController.php

@@ -28,7 +28,6 @@ class IndexController extends CommonController
         /** @var \Template $template */
         $template = $app['template'];
 
-
         /*
         $token = $app['security']->getToken();
         if (null !== $token) {
@@ -101,31 +100,6 @@ class IndexController extends CommonController
         $app['this_section'] = SECTION_CAMPUS;
         $request = $app['request'];
 
-        /*
-        $sql = 'SELECT * from user WHERE user_id = 1';
-        var_dump($sql);
-        $result = \Database::query($sql);
-        var_dump(\Database::fetch_object($result));*/
-
-        // Testing translation using translator
-        //echo $app['translator']->trans('Wiki Search Results');
-        //echo $app['translator']->trans('Profile');
-
-        //$token = $app['security']->getToken();
-
-        //$article = $app['orm.em']->getRepository('Entity\Course');
-        //$courses_query = $app['orm.em']->createQuery('SELECT a FROM Entity\Course a');
-        //$a = new Course();
-        //$article = $app['orm.em']->getRepository('Course');
-        //var_dump($article);
-        //$courses_query = $app['orm.em']->createQuery('SELECT a FROM Entity\Course a');
-        /*
-          $paginator = new Doctrine\ORM\Tools\Pagination\Paginator($courses_query, $fetchJoinCollection = true);
-          $c = count($paginator);
-          foreach ($paginator as $course) {
-          echo $course->getCode() . "\n";
-          }
-          exit; */
         if (api_get_setting('allow_terms_conditions') == 'true') {
             unset($_SESSION['term_and_condition']);
         }
@@ -216,46 +190,6 @@ class IndexController extends CommonController
         return new Response($response, 200, array('Cache-Control' => 's-maxage=3600, public'));
     }
 
-    /**
-     *
-     * @todo This piece of code should probably move to local.inc.php where the actual login procedure is handled.
-     * @todo Check if this code is used. I think this code is never executed because after clicking the submit button
-     *       the code does the stuff in local.inc.php and then redirects to index.php or user_portal.php depending
-     *       on api_get_setting('page_after_login').
-     * @deprecated seems not to be used
-     */
-    function check_last_login()
-    {
-        if (!empty($_POST['submitAuth'])) {
-            // The user has been already authenticated, we are now to find the last login of the user.
-            if (!empty($this->user_id)) {
-                $track_login_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-                $sql_last_login = "SELECT login_date
-                                    FROM $track_login_table
-                                    WHERE login_user_id = '".$this->user_id."'
-                                    ORDER BY login_date DESC LIMIT 1";
-                $result_last_login = Database::query($sql_last_login);
-                if (!$result_last_login) {
-                    if (Database::num_rows($result_last_login) > 0) {
-                        $user_last_login_datetime = Database::fetch_array($result_last_login);
-                        $user_last_login_datetime = $user_last_login_datetime[0];
-                        Session::write('user_last_login_datetime', $user_last_login_datetime);
-                    }
-                }
-                Database::free_result($result_last_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();
-                }
-            }
-        } else {
-            // Only if login form was not sent because if the form is sent the user was already on the page.
-            event_open();
-        }
-    }
-
     /**
      * @param \Silex\Application $app
      */
@@ -465,7 +399,6 @@ class IndexController extends CommonController
         }
     }
 
-
     /**
      * Reacts on a failed login.
      * Displays an explanation with a link to the registration form.

+ 0 - 4
src/ChamiloLMS/Controller/LegacyController.php

@@ -70,9 +70,6 @@ class LegacyController extends CommonController
             $app['template']->setFooter($app['template.show_footer']);
             $app['template']->setHeader($app['template.show_header']);
 
-            $token = $app['security']->getToken();
-            //var_dump($app['template.show_header']);
-
             if (isset($htmlHeadXtra)) {
                 $app['template']->addJsFiles($htmlHeadXtra);
             }
@@ -91,7 +88,6 @@ class LegacyController extends CommonController
         } else {
             return $app->abort(404, 'File not found');
         }
-
         return new Response($response, 200, $responseHeaders);
     }
 }

+ 0 - 84
src/ChamiloLMS/Controller/UserPortalController.php

@@ -87,90 +87,6 @@ class UserPortalController extends CommonController
 
         $response = $app['template']->render_template('userportal/index.tpl');
 
-        //return new Response($response, 200, array('Cache-Control' => 's-maxage=3600, private'));
         return new Response($response, 200, array());
     }
-
-    /**
-     * Redirects after login
-     */
-    public function redirectAfterLogin()
-    {
-        // Get the courses list
-        $personal_course_list = \UserManager::get_personal_session_course_list(api_get_user_id());
-
-        $my_session_list = array();
-        $count_of_courses_no_sessions = 0;
-        $count_of_courses_with_sessions = 0;
-
-        foreach ($personal_course_list as $course) {
-            if (!empty($course['id_session'])) {
-                $my_session_list[$course['id_session']] = true;
-                $count_of_courses_with_sessions++;
-            } else {
-                $count_of_courses_no_sessions++;
-            }
-        }
-        $count_of_sessions = count($my_session_list);
-
-        if ($count_of_sessions == 1 && $count_of_courses_no_sessions == 0) {
-            $key = array_keys($personal_course_list);
-            $course_info = $personal_course_list[$key[0]];
-            $id_session = isset($course_info['id_session']) ? $course_info['id_session'] : 0;
-
-            $url = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$id_session;
-            header('location:'.$url);
-            exit;
-        }
-
-        if (!isset($_SESSION['coursesAlreadyVisited']) && $count_of_sessions == 0 && $count_of_courses_no_sessions == 1) {
-            $key = array_keys($personal_course_list);
-            $course_info = $personal_course_list[$key[0]];
-            $course_directory = $course_info['course_info']['path'];
-            $id_session = isset($course_info['id_session']) ? $course_info['id_session'] : 0;
-
-            $url = api_get_path(WEB_COURSE_PATH).$course_directory.'/index.php?id_session='.$id_session;
-            header('location:'.$url);
-            exit;
-        }
-    }
-
-    public function check_last_login()
-    {
-        /**
-         * @todo This piece of code should probably move to local.inc.php where the actual login procedure is handled.
-         * @todo Check if this code is used. I think this code is never executed because after clicking the submit button
-         *       the code does the stuff in local.inc.php and then redirects to index.php or user_portal.php depending
-         *       on api_get_setting('page_after_login').
-         */
-        if (!empty($_POST['submitAuth'])) {
-            // The user has been already authenticated, we are now to find the last login of the user.
-            if (!empty($this->user_id)) {
-                $track_login_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
-                $sql_last_login = "SELECT login_date
-                                    FROM $track_login_table
-                                    WHERE login_user_id = '".$this->user_id."'
-                                    ORDER BY login_date DESC LIMIT 1";
-                $result_last_login = Database::query($sql_last_login);
-                if (!$result_last_login) {
-                    if (Database::num_rows($result_last_login) > 0) {
-                        $user_last_login_datetime = Database::fetch_array($result_last_login);
-                        $user_last_login_datetime = $user_last_login_datetime[0];
-                        Session::write('user_last_login_datetime', $user_last_login_datetime);
-                    }
-                }
-                Database::free_result($result_last_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 {
-            // Only if login form was not sent because if the form is sent the user was already on the page.
-            event_open();
-        }
-    }
 }

+ 2 - 2
src/ChamiloLMS/Resources/config/route_example.yml

@@ -1,3 +1,3 @@
-homepage:
-    path:      /homepage
+example:
+    path:      /example
     defaults:  { _controller: index.controller:indexAction, culture: en }

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác