Browse Source

Changing lot of queries in order to use one real course database see #3910

Julio Montoya 13 years ago
parent
commit
b020f1dc61
100 changed files with 2761 additions and 2780 deletions
  1. 0 7
      main/admin/calendar_ical_export.php
  2. 5 4
      main/admin/course_edit.php
  3. 20 24
      main/admin/course_information.php
  4. 1 1
      main/admin/session_course_user.php
  5. 18 11
      main/admin/special_exports.php
  6. 56 49
      main/admin/user_move_stats.php
  7. 53 37
      main/announcements/announcements.inc.php
  8. 61 78
      main/announcements/announcements.php
  9. 4 2
      main/announcements/download.php
  10. 2 5
      main/blog/blog.php
  11. 2 4
      main/blog/blog_admin.php
  12. 1 0
      main/calendar/agenda.lib.php
  13. 0 2
      main/calendar/agenda_js.php
  14. 5 3
      main/chat/chat_chat.php
  15. 1 1
      main/chat/chat_hidden.php
  16. 3 2
      main/chat/chat_message.php
  17. 12 3
      main/chat/chat_whoisonline.php
  18. 1 5
      main/course_description/add.php
  19. 1 1
      main/course_description/course_description_controller.php
  20. 3 2
      main/course_home/course_home.php
  21. 2 5
      main/course_info/infocours.php
  22. 213 170
      main/coursecopy/classes/CourseBuilder.class.php
  23. 95 102
      main/coursecopy/classes/CourseRecycler.class.php
  24. 262 221
      main/coursecopy/classes/CourseRestorer.class.php
  25. 15 10
      main/coursecopy/classes/CourseSelectForm.class.php
  26. 12 12
      main/create_course/add_course.php
  27. 2 1
      main/document/create_document.php
  28. 3 2
      main/document/document.php
  29. 13 9
      main/document/downloadfolder.inc.php
  30. 41 30
      main/dropbox/dropbox_class.inc.php
  31. 12 9
      main/dropbox/dropbox_functions.inc.php
  32. 1 1
      main/exercice/addlimits.php
  33. 5 8
      main/exercice/admin.php
  34. 10 12
      main/exercice/answer.class.php
  35. 1 1
      main/exercice/answer_admin.inc.php
  36. 1 1
      main/exercice/exercice.php
  37. 20 19
      main/exercice/exercise.class.php
  38. 1 1
      main/exercice/exercise_show.php
  39. 1 1
      main/exercice/mark_free_answer.php
  40. 1 1
      main/exercice/overview.php
  41. 37 31
      main/exercice/question.class.php
  42. 2 2
      main/exercice/result.php
  43. 122 90
      main/forum/forumfunction.inc.php
  44. 5 7
      main/forum/viewforum.php
  45. 2 8
      main/glossary/index.php
  46. 5 6
      main/gradebook/gradebook.php
  47. 7 7
      main/gradebook/gradebook_add_link.php
  48. 17 35
      main/gradebook/gradebook_edit_all.php
  49. 12 11
      main/gradebook/gradebook_edit_link.php
  50. 19 15
      main/gradebook/gradebook_result.class.php
  51. 6 2
      main/gradebook/index.php
  52. 6 3
      main/gradebook/lib/be/attendancelink.class.php
  53. 16 8
      main/gradebook/lib/be/forumthreadlink.class.php
  54. 6 7
      main/gradebook/lib/be/learnpathlink.class.php
  55. 11 4
      main/gradebook/lib/be/studentpublicationlink.class.php
  56. 9 5
      main/gradebook/lib/be/surveylink.class.php
  57. 20 4
      main/gradebook/lib/gradebook_functions.inc.php
  58. 1 1
      main/gradebook/lib/scoredisplay.class.php
  59. 3 12
      main/inc/ajax/exercise.ajax.php
  60. 9 16
      main/inc/ajax/social.ajax.php
  61. 2 1
      main/inc/introductionSection.inc.php
  62. 180 124
      main/inc/lib/add_course.lib.inc.php
  63. 43 17
      main/inc/lib/attendance.lib.php
  64. 235 258
      main/inc/lib/blog.lib.php
  65. 35 50
      main/inc/lib/course.lib.php
  66. 38 32
      main/inc/lib/course_description.lib.php
  67. 39 14
      main/inc/lib/course_home.lib.php
  68. 1 0
      main/inc/lib/database.constants.inc.php
  69. 48 3
      main/inc/lib/database.lib.php
  70. 21 15
      main/inc/lib/display.lib.php
  71. 116 120
      main/inc/lib/document.lib.php
  72. 50 36
      main/inc/lib/events.lib.inc.php
  73. 1 1
      main/inc/lib/fckeditor/myconfig.php
  74. 15 20
      main/inc/lib/fileDisplay.lib.php
  75. 22 15
      main/inc/lib/fileUpload.lib.php
  76. 30 16
      main/inc/lib/glossary.lib.php
  77. 161 139
      main/inc/lib/groupmanager.lib.php
  78. 25 17
      main/inc/lib/link.lib.php
  79. 79 44
      main/inc/lib/main_api.lib.php
  80. 6 3
      main/inc/lib/notebook.lib.php
  81. 4 2
      main/inc/lib/sessionmanager.lib.php
  82. 7 8
      main/inc/lib/social.lib.php
  83. 11 481
      main/inc/lib/surveymanager.lib.php
  84. 12 5
      main/inc/lib/thematic.lib.php
  85. 112 65
      main/inc/lib/tracking.lib.php
  86. 5 6
      main/inc/tool_navigation_menu.inc.php
  87. 6 17
      main/install/install.lib.php
  88. 5 0
      main/install/install_db.inc.php
  89. 1 5
      main/link/link.php
  90. 0 2
      main/mySpace/access_details.php
  91. 1 1
      main/mySpace/lp_tracking.php
  92. 8 7
      main/mySpace/myStudents.php
  93. 5 13
      main/newscorm/aicc.class.php
  94. 94 60
      main/newscorm/learnpath.class.php
  95. 9 9
      main/newscorm/learnpathItem.class.php
  96. 19 23
      main/newscorm/learnpath_functions.inc.php
  97. 1 0
      main/newscorm/lp_content.php
  98. 26 11
      main/newscorm/lp_stats.php
  99. 4 2
      main/newscorm/resourcelinker.inc.php
  100. 9 7
      main/newscorm/resourcelinker.php

+ 0 - 7
main/admin/calendar_ical_export.php

@@ -21,13 +21,6 @@ require_once (api_get_path(LIBRARY_PATH).'icalcreator/iCalcreator.class.php');
 // setting the name of the tool
 $nameTools = get_lang('MyAgenda');
 
-// setting the database variables
-//$TABLECOURS = Database :: get_main_table(TABLE_MAIN_COURSE);
-//$TABLECOURSUSER = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-//$TABLEAGENDA 			=Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-//$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-//$tbl_personal_agenda = Database :: get_user_personal_table(TABLE_PERSONAL_AGENDA);
-
 // the variables for the days and the months
 // Defining the shorts for the days
 $DaysShort = api_get_week_days_short();

+ 5 - 4
main/admin/course_edit.php

@@ -13,7 +13,6 @@ $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
 require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-require_once api_get_path(LIBRARY_PATH).'course.lib.php';
 
 $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
 $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
@@ -296,9 +295,11 @@ if ($form->validate()) {
 				sort='0',
 				user_course_cat='0'";
 	Database::query($sql);
-
-	$forum_config_table = Database::get_course_table(TOOL_FORUM_CONFIG_TABLE,$course_db_name);
-	$sql = "UPDATE ".$forum_config_table." SET default_lang='".Database::escape_string($course_language)."'";
+	
+	$course_info = api_get_course_info($course_code);
+	$course_id = $course_info['real_id'];
+	$forum_config_table = Database::get_course_table(TOOL_FORUM_CONFIG_TABLE);
+	$sql = "UPDATE ".$forum_config_table." SET default_lang='".Database::escape_string($course_language)."' WHERE c_id = $course_id ";
 	if ($visual_code_is_used) {
 	    header('Location: course_list.php?action=show_msg&warn='.urlencode($warn));
 	} else {

+ 20 - 24
main/admin/course_information.php

@@ -20,42 +20,39 @@ api_protect_admin_script();
 /**
  *
  */
-function get_course_usage($course_code, $session_id = 0)
-{
+function get_course_usage($course_code, $session_id = 0) {
 	$table = Database::get_main_table(TABLE_MAIN_COURSE);
     $course_code = Database::escape_string($course_code);
 	$sql = "SELECT * FROM $table WHERE code='".$course_code."'";
 	$res = Database::query($sql);
 	$course = Database::fetch_object($res);
 	// Learnpaths
-	$table = Database :: get_course_table(TABLE_LP_MAIN, $course->db_name);
-	$usage[] = array (get_lang(ucfirst(TOOL_LEARNPATH)), CourseManager::count_rows_course_table($table,$session_id));
+	$table = Database :: get_course_table(TABLE_LP_MAIN);
+	$usage[] = array (get_lang(ucfirst(TOOL_LEARNPATH)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
 	// Forums
-	$table = Database :: get_course_table(TABLE_FORUM, $course->db_name);
-	$usage[] = array (get_lang('Forums'), CourseManager::count_rows_course_table($table,$session_id));
+	$table = Database :: get_course_table(TABLE_FORUM);
+	$usage[] = array (get_lang('Forums'), CourseManager::count_rows_course_table($table,$session_id, $course->id));
 	// Quizzes
-	$table = Database :: get_course_table(TABLE_QUIZ_TEST, $course->db_name);
-	$usage[] = array (get_lang(ucfirst(TOOL_QUIZ)), CourseManager::count_rows_course_table($table,$session_id));
+	$table = Database :: get_course_table(TABLE_QUIZ_TEST);
+	$usage[] = array (get_lang(ucfirst(TOOL_QUIZ)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
 	// Documents
-	$table = Database :: get_course_table(TABLE_DOCUMENT, $course->db_name);
-	$usage[] = array (get_lang(ucfirst(TOOL_DOCUMENT)), CourseManager::count_rows_course_table($table,$session_id));
+	$table = Database :: get_course_table(TABLE_DOCUMENT);
+	$usage[] = array (get_lang(ucfirst(TOOL_DOCUMENT)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
 	// Groups
-	$table = Database :: get_course_table(TABLE_GROUP, $course->db_name);
-	$usage[] = array (get_lang(ucfirst(TOOL_GROUP)), CourseManager::count_rows_course_table($table,$session_id));
+	$table = Database :: get_course_table(TABLE_GROUP);
+	$usage[] = array (get_lang(ucfirst(TOOL_GROUP)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
 	// Calendar
-	$table = Database :: get_course_table(TABLE_AGENDA, $course->db_name);
-	$usage[] = array (get_lang(ucfirst(TOOL_CALENDAR_EVENT)), CourseManager::count_rows_course_table($table,$session_id));
+	$table = Database :: get_course_table(TABLE_AGENDA);
+	$usage[] = array (get_lang(ucfirst(TOOL_CALENDAR_EVENT)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
 	// Link
-	$table = Database::get_course_table(TABLE_LINK, $course->db_name);
-	$usage[] = array(get_lang(ucfirst(TOOL_LINK)), CourseManager::count_rows_course_table($table,$session_id));
+	$table = Database::get_course_table(TABLE_LINK);
+	$usage[] = array(get_lang(ucfirst(TOOL_LINK)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
 	// Announcements
-	$table = Database::get_course_table(TABLE_ANNOUNCEMENT, $course->db_name);
-	$usage[] = array(get_lang(ucfirst(TOOL_ANNOUNCEMENT)), CourseManager::count_rows_course_table($table,$session_id));
+	$table = Database::get_course_table(TABLE_ANNOUNCEMENT);
+	$usage[] = array(get_lang(ucfirst(TOOL_ANNOUNCEMENT)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
 	return $usage;
 }
-/*****************************************************************/
-if (!isset ($_GET['code']))
-{
+if (!isset ($_GET['code'])) {
 	api_not_allowed();
 }
 $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
@@ -154,7 +151,7 @@ echo '</blockquote>';
  * Show all classes subscribed in this course
  */
 $table_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
-$table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
+$table_class 		= Database :: get_main_table(TABLE_MAIN_CLASS);
 $sql = "SELECT * FROM $table_course_class cc, $table_class c WHERE cc.class_id = c.id AND cc.course_code = '".$code."'";
 $res = Database::query($sql);
 if (Database::num_rows($res) > 0)
@@ -180,5 +177,4 @@ if (Database::num_rows($res) > 0)
 	echo '<p>'.get_lang('NoClassesForThisCourse').'</p>';
 }
 /*	FOOTER	*/
-Display::display_footer();
-?>
+Display::display_footer();

+ 1 - 1
main/admin/session_course_user.php

@@ -136,7 +136,7 @@ WHERE id_user = $id_user and session_rel_course.id_session = $id_session";
 // actual user
 $sql="SELECT code, title, visual_code, srcru.id_session " .
 			"FROM $tbl_course course inner JOIN $tbl_session_rel_course_rel_user   as srcru  " .
-			"ON course.code = srcru.course_code  where srcru.id_user = $id_user AND id_session = $id_session";
+			"ON course.code = srcru.course_code  WHERE srcru.id_user = $id_user AND id_session = $id_session";
 
 //all
 $sql_all="SELECT code, title, visual_code, src.id_session " .

+ 18 - 11
main/admin/special_exports.php

@@ -68,9 +68,11 @@ if ((isset ($_POST['action']) && $_POST['action'] == 'course_select_form') || (i
 		} else {
 			$Resource = $_POST['resource'];
 			foreach($Resource as $Code_course => $Sessions) {
-				$_course = Database::get_course_info(Security::remove_XSS($Code_course));
-				$tbl_document = Database::get_course_table(TABLE_DOCUMENT, $_course['db_name']);
-				$tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['db_name']);
+				$_course 		= Database::get_course_info($Code_course);
+				$tbl_document 	= Database::get_course_table(TABLE_DOCUMENT);
+				$tbl_property 	= Database::get_course_table(TABLE_ITEM_PROPERTY);
+				$course_id 		= $_course['real_id'];
+				
 				//Add tem to the zip file course
 				$sql = "SELECT path FROM $tbl_document AS docs, $tbl_property AS props
 					WHERE props.tool='".TOOL_DOCUMENT."'
@@ -79,7 +81,7 @@ if ((isset ($_POST['action']) && $_POST['action'] == 'course_select_form') || (i
 						AND docs.filetype='file'
 						AND docs.session_id = '0'
 						AND props.visibility<>'2'
-						AND props.to_group_id=".$to_group_id."";
+						AND props.to_group_id=".$to_group_id." AND docs.c_id = $course_id AND props.c_id = $course_id";
 				$query = Database::query($sql );
 				while ($rows_course_file = Database::fetch_assoc($query)) {
 					$zip_folder->add($FileZip['PATH_COURSE'].$_course['directory']."/document".$rows_course_file['path'],
@@ -210,15 +212,20 @@ function fullexportspecial(){
     $list_course = array();
     $zip_folder = new PclZip($FileZip['TEMP_FILE_ZIP']);
     $list_course = Database::get_course_list();
-    if(count($list_course) >0 ) {
+    
+    $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
+    $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
+    
+    
+    if (count($list_course) >0 ) {
         foreach($list_course as $_course) {
             if($FileZip['PATH'] == '/') {
                 $querypath=''; // to prevent ...path LIKE '//%'... in query
             } else {
                 $querypath = $FileZip['PATH'];
             }
-            $tbl_document = Database::get_course_table(TABLE_DOCUMENT, $_course['db_name']);
-            $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['db_name']);
+            $course_id 		= $_course['real_id'];            
+            
             //Add tem to the zip file course
             $sql = "SELECT path FROM $tbl_document AS docs, $tbl_property AS props
                 WHERE props.tool='".TOOL_DOCUMENT."'
@@ -227,7 +234,7 @@ function fullexportspecial(){
                     AND docs.filetype='file'
                     AND docs.session_id = '0'
                     AND props.visibility<>'2'
-                    AND props.to_group_id=".$to_group_id."";
+                    AND props.to_group_id=".$to_group_id." AND docs.c_id = $course_id AND props.c_id = $course_id";
             $query = Database::query($sql );
             while ($rows_course_file = Database::fetch_assoc($query)) {
                 $rows_course_file['path'];
@@ -238,20 +245,20 @@ function fullexportspecial(){
             }
             //Add tem to the zip file session course
             $code_course = $_course['code'];
-            $sql_session = "SELECT id, name, course_code  FROM $tbl_session_course
+            $sql_session = "SELECT id, name, course_code FROM $tbl_session_course
                 INNER JOIN  $tbl_session ON id_session = id
                 WHERE course_code = '$code_course' ";
             $query_session = Database::query($sql_session);
             while ($rows_session = Database::fetch_assoc($query_session)) {
                 $session_id = $rows_session['id'];
-                $sql_session_doc = "SELECT path FROM $tbl_document AS docs,$tbl_property AS props
+                $sql_session_doc = "SELECT path FROM $tbl_document AS docs, $tbl_property AS props
                     WHERE props.tool='".TOOL_DOCUMENT."'
                         AND docs.id=props.ref
                         AND docs.path LIKE '".$querypath."/%'
                         AND docs.filetype='file'
                         AND docs.session_id = '$session_id'
                         AND props.visibility<>'2'
-                        AND props.to_group_id=".$to_group_id."";
+                        AND props.to_group_id=".$to_group_id." AND docs.c_id = $course_id AND props.c_id = $course_id ";
                 $query_session_doc = Database::query($sql_session_doc);
                 while ($rows_course_session_file = Database::fetch_assoc($query_session_doc)) {
                     $zip_folder->add($FileZip['PATH_COURSE'].$_course['directory'].'/document'.$rows_course_session_file['path'],

+ 56 - 49
main/admin/user_move_stats.php

@@ -102,20 +102,22 @@ if (isset($_REQUEST['load_ajax'])) {
                            
                 //Begin with the import process
                 $course_info                = api_get_course_info($origin_course_code);
+                $course_id 					= $course_info['real_id'];
+                
                 $TABLETRACK_EXERCICES       = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
                 $TBL_TRACK_ATTEMPT          = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
                 $TBL_TRACK_E_COURSE_ACCESS  = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
                 $TBL_TRACK_E_LAST_ACCESS    = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
                                 
-                $TBL_LP_VIEW                = Database::get_course_table(TABLE_LP_VIEW, $course_info['dbName']);
-                $TBL_NOTEBOOK               = Database::get_course_table(TABLE_NOTEBOOK, $course_info['dbName']);
-                $TBL_STUDENT_PUBLICATION    = Database::get_course_table(TABLE_STUDENT_PUBLICATION, $course_info['dbName']);
-                $TBL_STUDENT_PUBLICATION_ASSIGNMENT    = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT, $course_info['dbName']);
-                $TBL_ITEM_PROPERTY          = Database::get_course_table(TABLE_ITEM_PROPERTY, $course_info['dbName']);
+                $TBL_LP_VIEW                = Database::get_course_table(TABLE_LP_VIEW);
+                $TBL_NOTEBOOK               = Database::get_course_table(TABLE_NOTEBOOK);
+                $TBL_STUDENT_PUBLICATION    = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
+                $TBL_STUDENT_PUBLICATION_ASSIGNMENT    = Database::get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
+                $TBL_ITEM_PROPERTY          = Database::get_course_table(TABLE_ITEM_PROPERTY);
                 
-                $TBL_DROPBOX_FILE           = Database::get_course_table(TABLE_DROPBOX_FILE, $course_info['dbName']);
-                $TBL_DROPBOX_POST           = Database::get_course_table(TABLE_DROPBOX_POST, $course_info['dbName']);
-                $TBL_AGENDA                 = Database::get_course_table(TABLE_AGENDA, $course_info['dbName']);
+                $TBL_DROPBOX_FILE           = Database::get_course_table(TABLE_DROPBOX_FILE);
+                $TBL_DROPBOX_POST           = Database::get_course_table(TABLE_DROPBOX_POST);
+                $TBL_AGENDA                 = Database::get_course_table(TABLE_AGENDA);
                 
                 //$TBL_DROPBOX_CATEGORY       = Database::get_course_table(TABLE_DROPBOX_CATEGORY, $course_info['dbName']);
               
@@ -223,7 +225,7 @@ if (isset($_REQUEST['load_ajax'])) {
                  
                //CHECK ORIGIN
                
-                $sql = "SELECT * FROM $TBL_LP_VIEW WHERE user_id = $user_id AND session_id = $origin_session_id ";
+                $sql = "SELECT * FROM $TBL_LP_VIEW WHERE user_id = $user_id AND session_id = $origin_session_id AND c_id = $course_id ";
                 $res = Database::query($sql);
                 
                 //Getting the list of LPs in the new session 
@@ -241,7 +243,7 @@ if (isset($_REQUEST['load_ajax'])) {
                 if (!empty($list))
                 foreach ($list as $id=>$data) {
                     if ($update_database) {
-                        $sql = "UPDATE $TBL_LP_VIEW SET session_id = '$new_session_id' WHERE id = $id";
+                        $sql = "UPDATE $TBL_LP_VIEW SET session_id = '$new_session_id' WHERE id = $id ";
                         if ($debug) var_dump($sql); 
                         $res = Database::query($sql);          
                         if ($debug) var_dump($res);   
@@ -257,7 +259,7 @@ if (isset($_REQUEST['load_ajax'])) {
                 
                 //CHECk DESTINY
                 if (!$update_database) {
-                         $sql = "SELECT * FROM $TBL_LP_VIEW WHERE user_id = $user_id AND session_id = $new_session_id ";
+                         $sql = "SELECT * FROM $TBL_LP_VIEW WHERE user_id = $user_id AND session_id = $new_session_id AND c_id = $course_id";
                         $res = Database::query($sql);
                         
                         //Getting the list of LPs in the new session 
@@ -285,7 +287,7 @@ if (isset($_REQUEST['load_ajax'])) {
                 //6. Agenda
                 
                 //calendar_event_attachment no problems no session_id
-                $sql = "SELECT ref FROM $TBL_ITEM_PROPERTY WHERE tool = 'calendar_event' AND insert_user_id = $user_id";
+                $sql = "SELECT ref FROM $TBL_ITEM_PROPERTY WHERE tool = 'calendar_event' AND insert_user_id = $user_id AND c_id = $course_id ";
                 $res = Database::query($sql);
                 while($row = Database::fetch_array($res,'ASSOC')) {
                      $id = $row['ref'];
@@ -304,12 +306,12 @@ if (isset($_REQUEST['load_ajax'])) {
                 
                 //echo '<h1>Student publication</h1>';
                 
-                $sql = "SELECT ref FROM $TBL_ITEM_PROPERTY WHERE tool = 'work' AND insert_user_id = $user_id";
+                $sql = "SELECT ref FROM $TBL_ITEM_PROPERTY WHERE tool = 'work' AND insert_user_id = $user_id AND c_id = $course_id";
                 if ($debug) echo $sql;
                 $res = Database::query($sql);
                 while($row = Database::fetch_array($res,'ASSOC')) {
                     $id = $row['ref'];
-                    $sql = "SELECT * FROM $TBL_STUDENT_PUBLICATION WHERE id = $id AND session_id = $origin_session_id ";
+                    $sql = "SELECT * FROM $TBL_STUDENT_PUBLICATION WHERE id = $id AND session_id = $origin_session_id AND c_id = $course_id";
                     if ($debug) var_dump($sql); 
                     $sub_res = Database::query($sql);
                     if (Database::num_rows($sub_res) > 0 ) {
@@ -317,7 +319,7 @@ if (isset($_REQUEST['load_ajax'])) {
                         if ($debug) var_dump($data);                  
                         $parent_id = $data['parent_id'];
                         if (isset($data['parent_id']) && !empty($data['parent_id'])) {
-                            $sql = "SELECT * FROM $TBL_STUDENT_PUBLICATION WHERE id = $parent_id";
+                            $sql = "SELECT * FROM $TBL_STUDENT_PUBLICATION WHERE id = $parent_id AND c_id = $course_id";
                             $select_res     = Database::query($sql);
                             $parent_data    = Database::fetch_array($select_res,'ASSOC');
                             if ($debug)     var_dump($parent_data);
@@ -332,7 +334,9 @@ if (isset($_REQUEST['load_ajax'])) {
                             //@todo ugly fix
                             $search_this = "folder_moved_from_session_id_$origin_session_id";
                             $search_this2 = $parent_data['url'];
-                            $sql = "SELECT * FROM $TBL_STUDENT_PUBLICATION WHERE description like '%$search_this%' AND url LIKE '%$search_this2%' AND session_id = $new_session_id ORDER BY id desc  LIMIT 1";
+                            $sql = "SELECT * FROM $TBL_STUDENT_PUBLICATION 
+                            		WHERE description like '%$search_this%' AND url LIKE '%$search_this2%' AND session_id = $new_session_id AND c_id = $course_id 
+                            		ORDER BY id desc  LIMIT 1";
                             if ($debug) echo $sql;
                             $sub_res = Database::query($sql);
                             $num_rows = Database::num_rows($sub_res);
@@ -345,46 +349,48 @@ if (isset($_REQUEST['load_ajax'])) {
                                 
                                 if ($update_database) {
                                     
-                                $dir_name = substr($parent_data['url'], 1);
-                                $created_dir = create_unexisting_work_directory($base_work_dir, $dir_name);
-                                $created_dir = '/'.$created_dir;                                
-                                $now = api_get_utc_datetime();
-                                //Creating directory                                
-                                $sql_add_publication = "INSERT INTO " . $TBL_STUDENT_PUBLICATION . " SET " .         
-                                       "url         = '".$created_dir."',
-                                       title        = '".$parent_data['title']."',
-                                       description  = '".$parent_data['description']." folder_moved_from_session_id_$origin_session_id ',
-                                       author       = '',
-                                       active       = '0',
-                                       accepted     = '1',
-                                       filetype     = 'folder',                                   
-                                       sent_date    = '".$now."',
-                                       qualification    = '".$parent_data['qualification'] ."',
-                                       parent_id    = '',
-                                       qualificator_id  = '',
-                                       date_of_qualification    = '0000-00-00 00:00:00',
-                                       session_id   = ".$new_session_id;                                       
-                                $rest_insert     = Database::query($sql_add_publication);
-                                if ($debug) echo ($sql_add_publication);
-                                // add the directory
-                                $id = Database::insert_id();
-                                 //Folder created
-                                api_item_property_update($course_info, 'work', $id, 'DirectoryCreated', api_get_user_id());      
-                                if ($debug) var_dump($rest_insert);
-                                $new_parent_id = $id;                                
-                                $result_message[$TBL_STUDENT_PUBLICATION.' - new folder created called: '.$created_dir]++;
+	                                $dir_name = substr($parent_data['url'], 1);
+	                                $created_dir = create_unexisting_work_directory($base_work_dir, $dir_name);
+	                                $created_dir = '/'.$created_dir;                                
+	                                $now = api_get_utc_datetime();
+	                                //Creating directory                                
+	                                $sql_add_publication = "INSERT INTO " . $TBL_STUDENT_PUBLICATION . " SET " .         
+	                                       "url         = '".$created_dir."',
+	                                       c_id        = '".$course_id."',
+	                                       title        = '".$parent_data['title']."',
+	                                       description  = '".$parent_data['description']." folder_moved_from_session_id_$origin_session_id ',
+	                                       author       = '',
+	                                       active       = '0',
+	                                       accepted     = '1',
+	                                       filetype     = 'folder',                                   
+	                                       sent_date    = '".$now."',
+	                                       qualification    = '".$parent_data['qualification'] ."',
+	                                       parent_id    = '',
+	                                       qualificator_id  = '',
+	                                       date_of_qualification    = '0000-00-00 00:00:00',
+	                                       session_id   = ".$new_session_id;                                       
+	                                $rest_insert     = Database::query($sql_add_publication);
+	                                if ($debug) echo ($sql_add_publication);
+	                                // add the directory
+	                                $id = Database::insert_id();
+	                                 //Folder created
+	                                api_item_property_update($course_info, 'work', $id, 'DirectoryCreated', api_get_user_id());      
+	                                if ($debug) var_dump($rest_insert);
+	                                $new_parent_id = $id;                                
+	                                $result_message[$TBL_STUDENT_PUBLICATION.' - new folder created called: '.$created_dir]++;
                                 }                                                        
                             }                            
                                    
                             //Creating student_publication_assignment if exists
-                            $sql = "SELECT * FROM $TBL_STUDENT_PUBLICATION_ASSIGNMENT WHERE publication_id = $parent_id";
+                            $sql = "SELECT * FROM $TBL_STUDENT_PUBLICATION_ASSIGNMENT WHERE publication_id = $parent_id AND c_id = $course_id";
                             if ($debug) var_dump($sql);
                             $rest_select     = Database::query($sql);
                             if (Database::num_rows($rest_select) > 0 ) {
                                 if ($update_database) {
                                     $assignment_data = Database::fetch_array($rest_select,'ASSOC');
-                                    $sql_add_publication = "INSERT INTO " . $TBL_STUDENT_PUBLICATION_ASSIGNMENT . " SET " .         
-                                       "expires_on          = '".$assignment_data['expires_on']."',
+                                    $sql_add_publication = "INSERT INTO " . $TBL_STUDENT_PUBLICATION_ASSIGNMENT . " SET 
+                                    	c_id = '$course_id',          
+                                       expires_on          = '".$assignment_data['expires_on']."',
                                        ends_on              = '".$assignment_data['ends_on']."',
                                        add_to_calendar      = '".$assignment_data['add_to_calendar']."',
                                        enable_qualification = '".$assignment_data['enable_qualification']."',
@@ -413,6 +419,7 @@ if (isset($_REQUEST['load_ajax'])) {
                                 //Creating a new work                                  
                                 $sql_add_publication = "INSERT INTO " . $TBL_STUDENT_PUBLICATION . " SET " .
                                                "url         = '" . $new_url . "',
+                                               c_id        = '".$course_id."',
                                                title       = '" . $data['title']. "',
                                                description = '" . $data['description'] . " file moved',
                                                author      = '" . $data['author'] . "',
@@ -454,7 +461,7 @@ if (isset($_REQUEST['load_ajax'])) {
                 
                 //10. Dropbox - not neccesary to move categories (no presence of session_id)
                
-                $sql = "SELECT id FROM $TBL_DROPBOX_FILE WHERE uploader_id = $user_id AND session_id = $origin_session_id ";
+                $sql = "SELECT id FROM $TBL_DROPBOX_FILE WHERE uploader_id = $user_id AND session_id = $origin_session_id AND c_id = $course_id";
                 if ($debug) var_dump($sql); 
                 $res = Database::query($sql);
                 while($row = Database::fetch_array($res,'ASSOC')) {
@@ -475,7 +482,7 @@ if (isset($_REQUEST['load_ajax'])) {
                 
                 //11. Notebook
                 
-                $sql = "SELECT notebook_id FROM $TBL_NOTEBOOK WHERE user_id = $user_id AND session_id = $origin_session_id AND course =  '$origin_course_code' ";
+                $sql = "SELECT notebook_id FROM $TBL_NOTEBOOK WHERE user_id = $user_id AND session_id = $origin_session_id AND course = '$origin_course_code' AND c_id = $course_id";
                 if ($debug) var_dump($sql); 
                 $res = Database::query($sql);
                 while($row = Database::fetch_array($res,'ASSOC')) {

+ 53 - 37
main/announcements/announcements.inc.php

@@ -51,28 +51,22 @@ class AnnouncementManager  {
 	 * @param	int session id
 	 * @return	array html with the content and count of announcements or false otherwise
 	 */
-	public static function get_all_annoucement_by_course($course_db, $session_id = 0) {
+	public static function get_all_annoucement_by_course($course_info, $session_id = 0) {
 		if (empty($course_db)) {
 			return false;
 		}
 		$session_id = intval($session_id);
+		$course_id = $course_info['real_id'];
 		
-		$tbl_announcement	= Database::get_course_table(TABLE_ANNOUNCEMENT, $course_db['db_name']);
-		$tbl_item_property  = Database::get_course_table(TABLE_ITEM_PROPERTY, $course_db['db_name']);
-		/*
-		if (empty($group_id)) {
-			$group_condition = "AND (toolitemproperties.to_group_id='0' OR toolitemproperties.to_group_id is null)";
-		} else {
-			$group_condition = "AND (toolitemproperties.to_group_id='$group_id')";
-		}
-		$group_condition
-		*/
+		$tbl_announcement	= Database::get_course_table(TABLE_ANNOUNCEMENT);
+		$tbl_item_property  = Database::get_course_table(TABLE_ITEM_PROPERTY);
 			
 		$sql="SELECT DISTINCT announcement.id, announcement.title, announcement.content
 				FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
 				WHERE announcement.id = toolitemproperties.ref
 				AND toolitemproperties.tool='announcement'				
-				AND announcement.session_id  = '$session_id'
+				AND announcement.session_id  = '$session_id' AND
+				c_id = $course_id
 				ORDER BY display_order DESC";
 		$rs = Database::query($sql);
 		$num_rows = Database::num_rows($rs);
@@ -135,13 +129,16 @@ class AnnouncementManager  {
         global $charset;
 		$tbl_announcement 	= Database::get_course_table(TABLE_ANNOUNCEMENT);
 		$tbl_item_property	= Database::get_course_table(TABLE_ITEM_PROPERTY);
+		$course_id 			= api_get_course_int_id();
 	    
 		if (api_is_allowed_to_edit(false,true) || (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
             $sql_query = "  SELECT announcement.*, toolitemproperties.*
                             FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
                             WHERE announcement.id = toolitemproperties.ref
                             AND announcement.id = '$announcement_id'
-                            AND toolitemproperties.tool='announcement'                                                        
+                            AND toolitemproperties.tool='announcement' AND
+                            announcement.c_id = $course_id AND
+							toolitemproperties.c_id = $course_id                                       
                             ORDER BY display_order DESC";   
 		} else {
     		if (api_get_user_id() != 0) {
@@ -151,7 +148,9 @@ class AnnouncementManager  {
     							AND announcement.id = '$announcement_id'
     							AND toolitemproperties.tool='announcement'
     							AND (toolitemproperties.to_user_id='".api_get_user_id()."' OR toolitemproperties.to_group_id='0')
-    							AND toolitemproperties.visibility='1'
+    							AND toolitemproperties.visibility='1' AND
+    							announcement.c_id = $course_id AND
+								toolitemproperties.c_id = $course_id
     							ORDER BY display_order DESC";
     	
     		} else {
@@ -161,19 +160,19 @@ class AnnouncementManager  {
     							AND announcement.id = '$announcement_id'
     							AND toolitemproperties.tool='announcement'
     							AND toolitemproperties.to_group_id='0'
-    							AND toolitemproperties.visibility='1'";
+    							AND toolitemproperties.visibility='1' AND
+    							announcement.c_id = $course_id AND
+								toolitemproperties.c_id = $course_id
+    							";
     		}
 		}		
 		$sql_result = Database::query($sql_query);
 		if (Database::num_rows($sql_result) > 0 ) {
-    		$result		= Database::fetch_array($sql_result, 'ASSOC');    		
-    	
+    		$result		= Database::fetch_array($sql_result, 'ASSOC');    		    	
 			$title		 = $result['title'];
-			$content	 = $result['content'];
-				
+			$content	 = $result['content'];				
     		echo "<table height=\"100\" width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" class=\"data_table\">";
-    		echo "<tr><td><h2>".$title."</h2></td></tr>";   		
-    		
+    		echo "<tr><td><h2>".$title."</h2></td></tr>";   	
     		
     		if (api_is_allowed_to_edit(false,true) || (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
     		    $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=modify&id=".$announcement_id."\">".Display::return_icon('edit.png', get_lang('Edit'),'',22)."</a>";
@@ -253,8 +252,15 @@ class AnnouncementManager  {
 		$newContent = Database::escape_string($newContent);
 		$order = intval($order);
 	    $now = api_get_utc_datetime();
+	    $course_id = api_get_course_int_id();
+	    
 		// store in the table announcement
-		$sql = "INSERT INTO $tbl_announcement SET content = '$newContent', title = '$emailTitle', end_date = '$now', display_order ='$order', session_id=".api_get_session_id();
+		$sql = "INSERT INTO $tbl_announcement SET 
+				c_id = '$course_id',  
+				content = '$newContent', 
+				title = '$emailTitle', end_date = '$now', 
+				display_order ='$order', 
+				session_id=".api_get_session_id();
 		$result = Database::query($sql);
 		if ($result === false) {
 			return false;
@@ -306,9 +312,10 @@ class AnnouncementManager  {
 		$order = intval($order);
 		
 		$now = api_get_utc_datetime();
+		$course_id = api_get_course_int_id();
 	
 		// store in the table announcement
-		$sql = "INSERT INTO $tbl_announcement SET content = '$newContent', title = '$emailTitle', end_date = '$now', display_order ='$order', session_id=".api_get_session_id();
+		$sql = "INSERT INTO $tbl_announcement SET c_id = '$course_id', content = '$newContent', title = '$emailTitle', end_date = '$now', display_order ='$order', session_id=".api_get_session_id();
 		$result = Database::query($sql);
 		if ($result === false) {
 			return false;
@@ -440,8 +447,9 @@ class AnnouncementManager  {
 		$tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
 		if ($insert_id != strval(intval($insert_id))) { return false; }
 		$insert_id = Database::escape_string($insert_id);
+		$course_id = api_get_course_int_id();
 		// store the modifications in the table tbl_annoucement
-		$sql = "UPDATE $tbl_announcement SET email_sent='1' WHERE id='$insert_id'";
+		$sql = "UPDATE $tbl_announcement SET email_sent='1' WHERE c_id = $course_id AND id='$insert_id'";
 		Database::query($sql);
 	}
 	
@@ -451,22 +459,29 @@ class AnnouncementManager  {
 	 * @param	int user id
 	 * @return	array html with the content and count of announcements or false otherwise
 	 */
-	public static function get_all_annoucement_by_user_course($course_db, $user_id) {
-		if (empty($course_db) || empty($user_id)) {
+	public static function get_all_annoucement_by_user_course($course_code, $user_id) {
+		
+		$course_info = api_get_course_info($course_code);
+		$course_id	 = $course_info['real_id'];
+		
+		if (empty($user_id)) {
 			return false;
 		}
-		$tbl_announcement		= Database::get_course_table(TABLE_ANNOUNCEMENT, $course_db);
-		$tbl_item_property  	= Database::get_course_table(TABLE_ITEM_PROPERTY, $course_db);
+		$tbl_announcement		= Database::get_course_table(TABLE_ANNOUNCEMENT);
+		$tbl_item_property  	= Database::get_course_table(TABLE_ITEM_PROPERTY);
 		if (!empty($user_id) && is_numeric($user_id)) {
 			$user_id = intval($user_id);
 			$sql="SELECT DISTINCT announcement.title, announcement.content
-							FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
-							WHERE announcement.id = toolitemproperties.ref
-							AND toolitemproperties.tool='announcement'
-							AND (toolitemproperties.insert_user_id='$user_id' AND (toolitemproperties.to_group_id='0' OR toolitemproperties.to_group_id is null))
-							AND toolitemproperties.visibility='1'
-							AND announcement.session_id  = 0
-							ORDER BY display_order DESC";
+					FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties
+					WHERE
+						announcement.c_id = $course_id AND 
+						toolitemproperties.c_id = $course_id AND												 
+						announcement.id = toolitemproperties.ref AND 
+						toolitemproperties.tool='announcement' AND 
+						(toolitemproperties.insert_user_id='$user_id' AND (toolitemproperties.to_group_id='0' OR toolitemproperties.to_group_id is null))
+						AND toolitemproperties.visibility='1'
+						AND announcement.session_id  = 0
+					ORDER BY display_order DESC";
 			$rs = Database::query($sql);
 			$num_rows = Database::num_rows($rs);
 			$content = '';
@@ -1097,6 +1112,7 @@ class AnnouncementManager  {
 		$tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
 		$return = 0;
 		$announcement_id = intval($announcement_id);
+		$course_id = api_get_course_int_id();
 	
 		if (is_array($file) && $file['error'] == 0 ) {
 			$courseDir   = $_course['path'].'/upload/announcements'; // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
@@ -1119,8 +1135,8 @@ class AnnouncementManager  {
 				$safe_file_name     = Database::escape_string($file_name);
 				$safe_new_file_name = Database::escape_string($new_file_name);
 				// Storing the attachments if any
-				$sql = 'INSERT INTO '.$tbl_announcement_attachment.'(filename, comment, path, announcement_id, size) '.
-					   "VALUES ( '$safe_file_name', '$file_comment', '$safe_new_file_name' , '$announcement_id', '".intval($file['size'])."' )";
+				$sql = 'INSERT INTO '.$tbl_announcement_attachment.' (c_id, filename, comment, path, announcement_id, size) '.
+					   "VALUES ($course_id, '$safe_file_name', '$file_comment', '$safe_new_file_name' , '$announcement_id', '".intval($file['size'])."' )";
 				$result = Database::query($sql);
 	            $return = 1;
 			}

+ 61 - 78
main/announcements/announcements.php

@@ -69,40 +69,11 @@ require_once $lib.'fckeditor/fckeditor.php';
 require_once $lib.'fileUpload.lib.php';
 require_once 'announcements.inc.php';
 
-/*
- 	Resource linker
-$_SESSION['source_type']="Ad_Valvas";
-require_once '../resourcelinker/resourcelinker.inc.php';
-if (!empty($_POST['addresources'])) {
-	// When the "Add Resource" button is clicked we store all the form data into a session
-    $form_elements= array ('emailTitle'=>Security::remove_XSS($emailTitle), 'newContent'=>Security::remove_XSS($newContent), 'id'=>$id, 'to'=>$selectedform, 'emailoption'=>$email_ann);
-    $_SESSION['formelements']=$form_elements;
-    if($id) {
-    	// this is to correctly handle edits
-		$action="edit";
-    } else {
-		$action="add";
-    }
-
-	// ============== //
-	// 7 = Ad_Valvas	//
-	// ============== //
-	if($surveyid) {
-		header("Location: ../resourcelinker/resourcelinker.php?source_id=7&action=$action&id=$id&originalresource=no&publish_survey=$surveyid&db_name=$db_name&cidReq=$cidReq");
-		exit;
-	} else {
-		header("Location: ../resourcelinker/resourcelinker.php?source_id=7&action=$action&id=$id&originalresource=no");
-		exit;
-	}
-	exit;
-}
-*/
 /*	Tracking	*/
 event_access_tool(TOOL_ANNOUNCEMENT);
 
 
 /*	POST TO	*/
-
 $safe_emailTitle = $_POST['emailTitle'];
 $safe_newContent = $_POST['newContent'];
 
@@ -500,7 +471,7 @@ if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_ed
                             	$data_file = array('path' => $path_attach,'filename' => $filename_attach);
                             }
                             @api_mail_html($recipient_name, $mailid, stripslashes($emailSubject), $mail_body, $sender_name, $sender_email, null, $data_file, true);
-                            
+                            //@todo who uses the $table_reminder??
 							if ($_REQUEST['reminder']=="1") {
 								$time=getdate();
 								$time = $time['yday'];
@@ -888,6 +859,9 @@ if ($display_form) {
 /*
 		DISPLAY ANNOUNCEMENT LIST
 */
+
+$course_id = api_get_course_int_id();
+
 //if ($display_announcement_list && !$surveyid) {
 if ($display_announcement_list) {
 	// by default we use the id of the current user. The course administrator can see the announcement of other users by using the user / group filter
@@ -911,19 +885,24 @@ if ($display_announcement_list) {
 			if (is_array($group_memberships) && count($group_memberships)>0) {
 				$sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date
 					FROM $tbl_announcement announcement, $tbl_item_property ip
-					WHERE announcement.id = ip.ref
-					AND ip.tool='announcement'
-					AND	(ip.to_user_id=$user_id OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") )
-					$condition_session
+					WHERE 	announcement.c_id = $course_id AND
+							ip.c_id = $course_id AND							
+							announcement.id = ip.ref AND 
+							ip.tool			= 'announcement' AND	
+							(ip.to_user_id=$user_id OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") )
+							$condition_session
+							
 					ORDER BY display_order DESC";
 
 			} else {
 				$sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date
 					FROM $tbl_announcement announcement, $tbl_item_property ip
-					WHERE announcement.id = ip.ref
-					AND ip.tool='announcement'
-					AND (ip.to_user_id=$user_id OR ip.to_group_id='0')
-					AND ip.visibility='1'
+					WHERE	announcement.c_id 	= $course_id AND
+							ip.c_id 			= $course_id AND 
+							announcement.id 	= ip.ref AND 
+							ip.tool				='announcement' AND 
+							(ip.to_user_id		= $user_id OR ip.to_group_id='0') AND 
+							ip.visibility='1'
 					$condition_session
 					ORDER BY display_order DESC";
 
@@ -931,14 +910,15 @@ if ($display_announcement_list) {
 		} elseif (api_get_group_id() !=0 ) {
 			// A.2. you are a course admin with a GROUP filter
 			// => see only the messages of this specific group
-			$sql="SELECT
-				announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date
+			$sql="SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date
 				FROM $tbl_announcement announcement, $tbl_item_property ip
-				WHERE announcement.id = ip.ref
-				AND ip.tool='announcement'
-				AND ip.visibility<>'2'
-				AND (ip.to_group_id=$group_id OR ip.to_group_id='0')
-				$condition_session
+				WHERE	announcement.c_id = $course_id AND
+						ip.c_id = $course_id AND	 
+						announcement.id = ip.ref
+						AND ip.tool='announcement'
+						AND ip.visibility<>'2'
+						AND (ip.to_group_id=$group_id OR ip.to_group_id='0')
+						$condition_session
 				GROUP BY ip.ref
 				ORDER BY display_order DESC";
 		} else {
@@ -950,22 +930,25 @@ if ($display_announcement_list) {
 				$sql="SELECT
 					announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date
 					FROM $tbl_announcement announcement, $tbl_item_property ip
-					WHERE announcement.id = ip.ref
-					AND ip.tool='announcement'
-					AND ip.visibility='1'
-					$condition_session
+					WHERE	announcement.c_id = $course_id AND
+							ip.c_id = $course_id AND	 
+							announcement.id = ip.ref
+							AND ip.tool='announcement'
+							AND ip.visibility='1'
+							$condition_session
 					GROUP BY ip.ref
 					ORDER BY display_order DESC";
 			} else {
 				// A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
 				// => see all the messages of all the users and groups with editing possibilities
-				$sql="SELECT
-					announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date
+				$sql="SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date
 					FROM $tbl_announcement announcement, $tbl_item_property ip
-					WHERE announcement.id = ip.ref
-					AND ip.tool='announcement'
-					AND (ip.visibility='0' or ip.visibility='1')
-					$condition_session
+					WHERE 	announcement.c_id = $course_id AND
+							ip.c_id = $course_id AND	
+							announcement.id = ip.ref
+							AND ip.tool='announcement'
+							AND (ip.visibility='0' or ip.visibility='1')
+							$condition_session
 					GROUP BY ip.ref
 					ORDER BY display_order DESC";
 			}
@@ -994,11 +977,13 @@ if ($display_announcement_list) {
 
 				$sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date
         				FROM $tbl_announcement announcement, $tbl_item_property ip
-        				WHERE announcement.id = ip.ref
-        				AND ip.tool='announcement'
-        				$cond_user_id
-        				$condition_session
-        				AND ip.visibility='1'
+        				WHERE	announcement.c_id = $course_id AND
+								ip.c_id = $course_id AND	 
+		        				announcement.id = ip.ref
+		        				AND ip.tool='announcement'
+		        				$cond_user_id
+		        				$condition_session
+		        				AND ip.visibility='1'
         				ORDER BY display_order DESC";
 			} else {
 				if ($_user['user_id']) {
@@ -1010,12 +995,15 @@ if ($display_announcement_list) {
 
 					$sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date
 							FROM $tbl_announcement announcement, $tbl_item_property ip
-    						WHERE announcement.id = ip.ref
-    						AND ip.tool='announcement'
-    						$cond_user_id
-    						$condition_session
-    						AND ip.visibility='1'
-    						AND announcement.session_id IN(0,".api_get_session_id().")
+    						WHERE
+	    						announcement.c_id = $course_id AND
+								ip.c_id = $course_id AND	 
+	    						announcement.id = ip.ref AND 
+	    						ip.tool='announcement'
+	    						$cond_user_id
+	    						$condition_session
+	    						AND ip.visibility='1'
+	    						AND announcement.session_id IN(0,".api_get_session_id().")
     						ORDER BY display_order DESC";
 				} else {
 
@@ -1027,7 +1015,10 @@ if ($display_announcement_list) {
 
 					$sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date
     						FROM $tbl_announcement announcement, $tbl_item_property ip
-    						WHERE announcement.id = ip.ref
+    						WHERE
+    						announcement.c_id = $course_id AND
+							ip.c_id = $course_id AND	 
+    						announcement.id = ip.ref
     						AND ip.tool='announcement'
     						$cond_user_id
     						$condition_session
@@ -1049,16 +1040,12 @@ if ($display_announcement_list) {
     	$iterator = 1;
     	$bottomAnnouncement = $announcement_number;
     
-    	echo '<table width="100%" class="data_table">';
-    	
+    	echo '<table width="100%" class="data_table">';    	
         $ths = Display::tag('th', get_lang('Title'));
-        //$ths .= Display::tag('th', get_lang('Content'));        
-        $ths .= Display::tag('th', get_lang('By') );
-        //$ths .= Display::tag('th', get_lang('AnnouncementPublishedOn') );    
+        $ths .= Display::tag('th', get_lang('By') );   
         $ths .= Display::tag('th', get_lang('LastUpdateDate') );
         if (api_is_allowed_to_edit(false,true) OR (api_is_course_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT,$myrow['id']))         
                  OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
-            //$ths .= Display::tag('th', get_lang('SentTo'));
             $ths .= Display::tag('th', get_lang('Modify'));
         }
         
@@ -1074,8 +1061,6 @@ if ($display_announcement_list) {
                 }
                 
     			$title		 = $myrow['title'].$sent_to_icon;
-    			//$content	 = $myrow['content'];
-    
     
     			/* DATE */    
     			$last_post_datetime = $myrow['end_date'];    
@@ -1091,8 +1076,7 @@ if ($display_announcement_list) {
     			
     		    // show attachment list
                 $attachment_list = array();
-                $attachment_list = AnnouncementManager::get_attachment($myrow['id']);
-                
+                $attachment_list = AnnouncementManager::get_attachment($myrow['id']);                
                 
                 $attachment = '';
                 $attachment_icon = '';
@@ -1103,7 +1087,6 @@ if ($display_announcement_list) {
                 /* TITLE */
     		    $title = Display::url($title.$attachment_icon, '?action=view&id='.$myrow['id']);
                 echo Display::tag('td', Security::remove_XSS($title), array('class' => $style));                
-                //echo Display::tag('td', Security::remove_XSS($content).$attachment);    		
                 	
                 $user_info		= api_get_user_info($myrow['insert_user_id']);    						
     			echo Display::tag('td', api_get_person_name($user_info['firstName'], $user_info['lastName']));

+ 4 - 2
main/announcements/download.php

@@ -60,8 +60,10 @@ $tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATT
 // launch event
 event_download($doc_url);
 
-$sql='SELECT filename FROM '.$tbl_announcement_attachment.'
-  	  WHERE path LIKE BINARY "'.$doc_url.'"';
+$course_id = api_get_course_int_id();
+
+$sql = "SELECT filename FROM $tbl_announcement_attachment
+  	  	WHERE c_id = $course_id AND path LIKE BINARY $doc_url";
 
 $result= Database::query($sql);
 if (Database::num_rows($result) > 0) {

+ 2 - 5
main/blog/blog.php

@@ -373,8 +373,7 @@ if (isset ($_GET['task_id']) && is_numeric($_GET['task_id'])) {
 		$user_task = true;
 }
 
-switch ($current_page)
-{
+switch ($current_page) {
 	case 'new_post' :
 		if (api_is_allowed('BLOG_'.$blog_id, 'article_add', $user_task ? $task_id : 0))
 		{
@@ -512,8 +511,6 @@ switch ($current_page)
 	</td>
 </tr>
 </table>
-
 <?php
 // Display the footer
-Display::display_footer();
-?>
+Display::display_footer();

+ 2 - 4
main/blog/blog_admin.php

@@ -22,8 +22,7 @@ $blog_table_attachment 	= Database::get_course_table(TABLE_BLOGS_ATTACHMENT);
 api_protect_course_script(true);
 
 //	 ONLY USERS REGISTERED IN THE COURSE
-if((!$is_allowed_in_course || !$is_courseMember) && !api_is_allowed_to_edit())
-{
+if((!$is_allowed_in_course || !$is_courseMember) && !api_is_allowed_to_edit()) {
 	api_not_allowed(true);//print headers/footers
 }
 
@@ -125,5 +124,4 @@ if (api_is_allowed_to_edit()) {
 }
 
 // Display the footer
-Display::display_footer();
-?>
+Display::display_footer();

+ 1 - 0
main/calendar/agenda.lib.php

@@ -62,6 +62,7 @@ class Agenda {
 				$attributes['end_date'] 	= $end;
 				$attributes['all_day'] 		= $all_day;
 				$attributes['session_id'] 	= api_get_session_id();
+				$attributes['c_id'] 		= $this->course['real_id'];
 				
 				//simple course event
 				$id = Database::insert($this->tbl_course_agenda, $attributes);				

+ 0 - 2
main/calendar/agenda_js.php

@@ -62,9 +62,7 @@ $tpl->assign('type', $type);
 $tpl->assign('can_add_events', $can_add_events);
  
 $agenda_ajax_url = api_get_path(WEB_AJAX_PATH).'agenda.ajax.php?type='.$type.'&';
-
 $tpl->assign('web_agenda_ajax_url', $agenda_ajax_url);
-
 $content = $tpl->fetch('default/agenda/month.tpl');
 $tpl->assign('content', $content);
 $template_file = $tpl->get_template('layout/layout_1_col.tpl');

+ 5 - 3
main/chat/chat_chat.php

@@ -47,6 +47,8 @@ if (!empty($course)) {
 	$chat_path = $document_path.$basepath_chat.'/';
 
 	$TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+	
+	$course_id = api_get_course_int_id();
 
 	if (!is_dir($chat_path)) {
 		if (is_file($chat_path)) {
@@ -58,8 +60,8 @@ if (!empty($course)) {
 			// Save chat files document for group into item property
 			if (!empty($group_id)) {
 				$doc_id = add_document($_course, $basepath_chat, 'folder', 0, 'chat_files');
-				$sql = "INSERT INTO $TABLEITEMPROPERTY (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,'FolderCreated',1,$group_id,NULL,0)";
+				$sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
+						VALUES ($course_id, 'document',1,NOW(),NOW(),$doc_id,'FolderCreated',1,$group_id,NULL,0)";
 				Database::query($sql);
 			}
 		}
@@ -135,7 +137,7 @@ if (!empty($course)) {
 	}
 	if ($_GET['origin'] == 'whoisonlinejoin') {   //the joiner (we have to delete the chat request to him when he joins the chat)
 		$track_user_table = Database::get_main_table(TABLE_MAIN_USER);
-		$sql = "UPDATE $track_user_table set chatcall_user_id = '', chatcall_date = '', chatcall_text='' where (user_id = ".$_user['user_id'].")";
+		$sql = "UPDATE $track_user_table set chatcall_user_id = '', chatcall_date = '', chatcall_text='' WHERE (user_id = ".$_user['user_id'].")";
 		$result = Database::query($sql);
 	}
 

+ 1 - 1
main/chat/chat_hidden.php

@@ -128,7 +128,7 @@ if ($_SESSION["origin"] == 'whoisonline') {  //check if our target has denied ou
 	$row = Database::fetch_array($result);
 	if ($row['chatcall_text'] == 'DENIED') {
 		echo "<script language=\"javascript\" type=\"text/javascript\"> alert('".get_lang('ChatDenied')."'); </script>";
-		$sql = "update $track_user_table set chatcall_user_id = '', chatcall_date = '', chatcall_text='' where (user_id = $talk_to)";
+		$sql = "update $track_user_table set chatcall_user_id = '', chatcall_date = '', chatcall_text='' WHERE (user_id = $talk_to)";
 		$result = Database::query($sql);
 	}
 }

+ 3 - 2
main/chat/chat_message.php

@@ -97,6 +97,7 @@ if (!empty($course) && !empty($_user['user_id'])) {
 	$chat_path = $document_path.$basepath_chat.'/';
 
 	$TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+	$course_id = api_get_course_int_id();
 
 	if (!is_dir($chat_path)) {
 		if (is_file($chat_path)) {
@@ -107,8 +108,8 @@ if (!empty($course) && !empty($_user['user_id'])) {
 			// save chat files document for group into item property
 			if (!empty($group_id)) {
 				$doc_id = add_document($_course,$basepath_chat, 'folder', 0, 'chat_files');
-				$sql = "INSERT INTO $TABLEITEMPROPERTY (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,'FolderCreated',1,$group_id,NULL,0)";
+				$sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
+						VALUES ($course_id, 'document',1,NOW(),NOW(),$doc_id,'FolderCreated',1,$group_id,NULL,0)";
 				Database::query($sql);
 			}
 		}

+ 12 - 3
main/chat/chat_whoisonline.php

@@ -36,7 +36,7 @@ if (!empty($course)) {
 	$tbl_session				= Database::get_main_table(TABLE_MAIN_SESSION);
 	$tbl_session_course			= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
 	$tbl_user					= Database::get_main_table(TABLE_MAIN_USER);
-	$tbl_chat_connected			= Database::get_course_table(CHAT_CONNECTED_TABLE, $_course['dbName']);
+	$tbl_chat_connected			= Database::get_course_table(CHAT_CONNECTED_TABLE);
 
 	$query = "SELECT username FROM $tbl_user WHERE user_id='".$_user['user_id']."'";
 	$result = Database::query($query);
@@ -49,9 +49,18 @@ if (!empty($course)) {
 	$date_inter = date('Y-m-d H:i:s', time() - 120);
 
 	$users = array();
-
+	$course_id = api_get_course_int_id();
+	
 	if (empty($session_id)) {
-		$query = "SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri,t3.status FROM $tbl_user t1,$tbl_chat_connected t2,$tbl_course_user t3 WHERE t1.user_id=t2.user_id AND t3.user_id=t2.user_id AND t3.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND t3.course_code = '".$_course['sysCode']."' AND t2.last_connection>'".$date_inter."' $extra_condition ORDER BY username";
+		$query = "SELECT DISTINCT t1.user_id,username,firstname,lastname,picture_uri,t3.status 
+				  FROM $tbl_user t1,$tbl_chat_connected t2,$tbl_course_user t3 
+				  WHERE t2.c_id = $course_id, 
+				  		t1.user_id=t2.user_id AND 
+				  		t3.user_id=t2.user_id AND 
+						t3.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND 
+						t3.course_code = '".$_course['sysCode']."' AND 
+						t2.last_connection>'".$date_inter."' $extra_condition 
+						ORDER BY username";
 		$result = Database::query($query);
 		$users = Database::store_result($result);
 	} else {

+ 1 - 5
main/course_description/add.php

@@ -70,14 +70,10 @@ if (isset ($question[$description_type])) {
 	$message .= $question[$description_type];
 	Display::display_normal_message($message, false);
 }
-
 if (api_get_setting('wcag_anysurfer_public_pages')=='true') {
 	echo (WCAG_Rendering::editor_header());
 }
-
 $form->display();
-
 if (api_get_setting('wcag_anysurfer_public_pages')=='true') {
 	echo (WCAG_Rendering::editor_footer());
-}
-?>
+}

+ 1 - 1
main/course_description/course_description_controller.php

@@ -187,7 +187,7 @@ class CourseDescriptionController { // extends Controller {
 		        		$course_description->set_description_type($description_type);
 		        		$course_description->set_title($title);
 		        		$course_description->set_content($content);
-						$affected_rows = $course_description->insert();
+						$affected_rows = $course_description->insert(api_get_course_int_id());
 		        	}
 		        	Security::clear_token();	
         		} 

+ 3 - 2
main/course_home/course_home.php

@@ -202,11 +202,12 @@ if (!empty($auto_lunch)) {
             }
         }        
     } else {
-        $lp_table = Database::get_course_table(TABLE_LP_MAIN);        
+        $lp_table = Database::get_course_table(TABLE_LP_MAIN);   
+        $course_id = api_get_course_int_id();
         $condition = '';        
         if (!empty($session_id)) {
             $condition =  api_get_session_condition($session_id);
-            $sql = "SELECT id FROM $lp_table WHERE autolunch = 1 $condition LIMIT 1";
+            $sql = "SELECT id FROM $lp_table WHERE c_id = $course_id AND autolunch = 1 $condition LIMIT 1";
             $result = Database::query($sql);
             //If we found nothing in the session we just called the session_id =  0 autolunch
             if (Database::num_rows($result) ==  0) {

+ 2 - 5
main/course_info/infocours.php

@@ -34,16 +34,13 @@ define('COURSE_CHANGE_PROPERTIES', 'COURSE_CHANGE_PROPERTIES');
 
 $TABLECOURSE 				= Database :: get_main_table(TABLE_MAIN_COURSE);
 $TABLEFACULTY 				= Database :: get_main_table(TABLE_MAIN_CATEGORY);
-$TABLECOURSEHOME 			= Database :: get_course_table(TABLE_TOOL_LIST);
 $TABLELANGUAGES 			= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-$TABLEBBCONFIG 				= Database :: get_course_table(TOOL_FORUM_CONFIG_TABLE);
 $currentCourseID 			= $_course['sysCode'];
 $currentCourseRepository    = $_course['path'];
 $is_allowedToEdit 			= $is_courseAdmin || $is_platformAdmin;
-$course_setting_table 		= Database::get_course_table(TABLE_COURSE_SETTING);
 
-$course_code = $_course['sysCode'];
-$course_access_settings = CourseManager :: get_access_settings($course_code);
+$course_code 				= $_course['sysCode'];
+$course_access_settings 	= CourseManager :: get_access_settings($course_code);
 
 //LOGIC FUNCTIONS
 function is_settings_editable() {

+ 213 - 170
main/coursecopy/classes/CourseBuilder.class.php

@@ -70,12 +70,15 @@ class CourseBuilder {
 	 *                 in the session, (session_id = 0 or session_id = X) 
 	 */
 	function build($session_id = 0, $course_code = '', $with_base_content = false) {
+		$course_info	= api_get_course_info($course_code);
+		
+		$course_id 		= $course_info['real_id'];
+		
+		$table_link       = Database :: get_course_table(TABLE_LINKED_RESOURCES);
+		$table_properties = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 		
 		if (!empty($session_id) && !empty($course_code)) {
-			$course_info      = api_get_course_info($course_code);
-			$table_link       = Database :: get_course_table(TABLE_LINKED_RESOURCES,$course_info['dbName']);
-			$table_properties = Database :: get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-
+			
 			$this->build_documents($session_id, $course_code, $with_base_content);
 			$this->build_quizzes($session_id, $course_code,   $with_base_content);
 			$this->build_glossary($session_id, $course_code,  $with_base_content);
@@ -86,9 +89,7 @@ class CourseBuilder {
 			//$this->build_thematic($session_id, $course_code, $with_base_content);
 			$this->build_thematic();			
 			$this->build_attendance();
-		} else {
-			$table_link = Database :: get_course_table(TABLE_LINKED_RESOURCES);
-			$table_properties = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+		} else {			
 
 			$this->build_events();
 			$this->build_announcements();
@@ -109,7 +110,7 @@ class CourseBuilder {
 
 		foreach ($this->course->resources as $type => $resources) {
 			foreach ($resources as $id => $resource) {
-				$sql = "SELECT * FROM ".$table_link." WHERE source_type = '".$resource->get_type()."' AND source_id = '".$resource->get_id()."'";
+				$sql = "SELECT * FROM ".$table_link." WHERE c_id = $course_id AND source_type = '".$resource->get_type()."' AND source_id = '".$resource->get_id()."'";
 				$res = Database::query($sql);
 				while ($link = Database::fetch_object($res)) {
 					$this->course->resources[$type][$id]->add_linked_resource($link->resource_type, $link->resource_id);
@@ -122,7 +123,7 @@ class CourseBuilder {
 			{
 				$tool = $resource->get_tool();
 				if ($tool != null) {
-					$sql = "SELECT * FROM $table_properties WHERE TOOL = '".$tool."' AND ref='".$resource->get_id()."'";
+					$sql = "SELECT * FROM $table_properties WHERE c_id = $course_id AND TOOL = '".$tool."' AND ref='".$resource->get_id()."'";
 					$res = Database::query($sql);
 					$all_properties = array ();
 					while ($item_property = Database::fetch_array($res))
@@ -141,10 +142,13 @@ class CourseBuilder {
 	 */
 	function build_documents($session_id = 0, $course_code = '', $with_base_content = false) {
 
-		if (!empty($course_code) && !empty($session_id)) {
-			$course_info = api_get_course_info($course_code);
-			$table_doc   = Database::get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
-			$table_prop  = Database::get_course_table(TABLE_ITEM_PROPERTY, $course_info['dbName']);
+		$course_info 	= api_get_course_info($course_code);
+		$course_id 		= $course_info['real_id'];
+		
+		$table_doc   = Database::get_course_table(TABLE_DOCUMENT);
+		$table_prop  = Database::get_course_table(TABLE_ITEM_PROPERTY);
+		
+		if (!empty($course_code) && !empty($session_id)) {			
 
 			$session_id  = intval($session_id);
             if ($with_base_content) {
@@ -153,11 +157,22 @@ class CourseBuilder {
                 $session_condition = api_get_session_condition($session_id, true);
             }
 			if (!empty($this->course->type) && $this->course->type=='partial') {
-			    $sql = 'SELECT d.id, d.path, d.comment, d.title, d.filetype, d.size FROM '.$table_doc.' d, '.$table_prop.' p 
-			            WHERE tool = \''.TOOL_DOCUMENT.'\' AND p.ref = d.id AND p.visibility != 2 AND path NOT LIKE \'/images/gallery%\' '.$session_condition.' ORDER BY path';
+			    $sql = "SELECT d.id, d.path, d.comment, d.title, d.filetype, d.size FROM $table_doc d, $table_prop p 
+			            WHERE 	d.c_id = $course_id AND 
+			            		p.c_id = $course_id AND
+			            		tool = '".TOOL_DOCUMENT."' AND 
+			            		p.ref = d.id AND 
+			            		p.visibility != 2 AND 
+			            		path NOT LIKE '/images/gallery%' 
+			            		$session_condition 
+			    		ORDER BY path";
 			} else {
-	        	$sql = 'SELECT d.id, d.path, d.comment, d.title, d.filetype, d.size FROM '.$table_doc.' d, '.$table_prop.' p 
-	        	        WHERE tool = \''.TOOL_DOCUMENT.'\' AND p.ref = d.id AND p.visibility != 2 '.$session_condition.' ORDER BY path';
+	        	$sql = "SELECT d.id, d.path, d.comment, d.title, d.filetype, d.size FROM $table_doc d, $table_prop p 
+	        	        WHERE 	d.c_id = $course_id AND 
+			            		p.c_id = $course_id AND
+	        					tool = '".TOOL_DOCUMENT."' AND 
+	        					p.ref = d.id AND p.visibility != 2 $session_condition 
+	        			ORDER BY path";
 			}
  
 			$db_result = Database::query($sql);
@@ -166,13 +181,18 @@ class CourseBuilder {
 				$this->course->add_resource($doc);
 			}
 		} else {
-			$table_doc = Database :: get_course_table(TABLE_DOCUMENT);
-			$table_prop = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-
+			
 			if (!empty($this->course->type) && $this->course->type=='partial')
-        		$sql = 'SELECT d.id, d.path, d.comment, d.title, d.filetype, d.size FROM '.$table_doc.' d, '.$table_prop.' p WHERE tool = \''.TOOL_DOCUMENT.'\' AND p.ref = d.id AND p.visibility != 2 AND path  NOT LIKE \'/images/gallery%\' AND d.session_id = 0 ORDER BY path';
+        		$sql = 'SELECT d.id, d.path, d.comment, d.title, d.filetype, d.size FROM '.$table_doc.' d, '.$table_prop.' p 
+						WHERE 	d.c_id = '.$course_id.' AND 
+			            		p.c_id = '.$course_id.' AND
+								tool = \''.TOOL_DOCUMENT.'\' AND p.ref = d.id AND p.visibility != 2 AND path  NOT LIKE \'/images/gallery%\' AND d.session_id = 0 ORDER BY path';
 	        else
-	        	$sql = 'SELECT d.id, d.path, d.comment, d.title, d.filetype, d.size  FROM '.$table_doc.' d, '.$table_prop.' p WHERE tool = \''.TOOL_DOCUMENT.'\' AND p.ref = d.id AND p.visibility != 2 AND d.session_id = 0 ORDER BY path';
+	        	$sql = 'SELECT d.id, d.path, d.comment, d.title, d.filetype, d.size  
+	        			FROM '.$table_doc.' d, '.$table_prop.' p
+	        			WHERE 	d.c_id = '.$course_id.' AND 
+			            		p.c_id = '.$course_id.' AND 
+	        					tool = \''.TOOL_DOCUMENT.'\' AND p.ref = d.id AND p.visibility != 2 AND d.session_id = 0 ORDER BY path';
  
 			$db_result = Database::query($sql);
 			while ($obj = Database::fetch_object($db_result)) {
@@ -186,7 +206,8 @@ class CourseBuilder {
 	 */
 	function build_forums() {
 		$table = Database :: get_course_table(TABLE_FORUM);
-		$sql = 'SELECT * FROM '.$table;
+		$course_id = api_get_course_int_id();		
+		$sql = "SELECT * FROM $table WHERE c_id = $course_id ";
 		$db_result = Database::query($sql);
 		while ($obj = Database::fetch_object($db_result)) {
 			$forum = new Forum($obj->forum_id, $obj->forum_title, $obj->forum_comment, $obj->forum_category, $obj->forum_last_post, $obj->forum_threads, $obj->forum_posts, $obj->allow_anonymous, $obj->allow_edit, $obj->approval_direct_post, $obj->allow_attachements, $obj->allow_new_threads, $obj->default_view, $obj->forum_of_group, $obj->forum_group_public_private, $obj->forum_order, $obj->locked, $obj->session_id, $obj->forum_image);
@@ -201,7 +222,8 @@ class CourseBuilder {
 	 */
 	function build_forum_category($id) {
 		$table = Database :: get_course_table(TABLE_FORUM_CATEGORY);
-		$sql = 'SELECT * FROM '.$table.' WHERE cat_id = '.$id;
+		$course_id = api_get_course_int_id();
+		$sql = "SELECT * FROM $table WHERE c_id = $course_id AND cat_id = $id";
 		$db_result = Database::query($sql);
 		while ($obj = Database::fetch_object($db_result)) {
 			$forum_category = new ForumCategory($obj->cat_id, $obj->cat_title, $obj->cat_comment, $obj->cat_order, $obj->locked, $obj->session_id);
@@ -214,7 +236,8 @@ class CourseBuilder {
 	 */
 	function build_forum_topics() {
 		$table = Database :: get_course_table(TABLE_FORUM_THREAD);
-		$sql = 'SELECT * FROM '.$table;
+		$course_id = api_get_course_int_id();		
+		$sql = "SELECT * FROM $table WHERE c_id = $course_id ";
 		$db_result = Database::query($sql);
 		while ($obj = Database::fetch_object($db_result))
 		{
@@ -229,40 +252,47 @@ class CourseBuilder {
 	 */
 	function build_forum_posts()
 	{
-		$table_post = Database :: get_course_table(TABLE_FORUM_POST);
-		$sql = 'SELECT * FROM '.$table_post;
+		$table = Database :: get_course_table(TABLE_FORUM_POST);
+		$course_id = api_get_course_int_id();		
+		$sql = "SELECT * FROM $table WHERE c_id = $course_id ";
 		$db_result = Database::query($sql);
-		while ($obj = Database::fetch_object($db_result))
-		{
+		while ($obj = Database::fetch_object($db_result)) {
 			$forum_post = new ForumPost($obj->post_id, $obj->post_title, $obj->post_text, $obj->post_date, $obj->poster_id, $obj->poster_name, $obj->post_notification, $obj->post_parent_id, $obj->thread_id, $obj->forum_id, $obj->visible);
 			$this->course->add_resource($forum_post);
 		}
 	}
+	
 	/**
 	 * Build the links
 	 */
-	function build_links($session_id = 0, $course_code = '', $with_base_content = false)
-	{
-		if (!empty($session_id) && !empty($course_code)) {
-			$course_info = api_get_course_info($course_code);
-			$table = Database :: get_course_table(TABLE_LINK,$course_info['dbName']);
-			$table_prop = Database :: get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+	function build_links($session_id = 0, $course_code = '', $with_base_content = false) {
+		$course_info = api_get_course_info($course_code);
+		$course_id 		= $course_info['real_id'];
+		
+		
+		$table = Database :: get_course_table(TABLE_LINK);
+		$table_prop = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+		
+		if (!empty($session_id) && !empty($course_code)) {			
 			$session_id = intval($session_id);
             if ($with_base_content) {
                 $session_condition = api_get_session_condition($session_id, true, true);                
             } else {
                 $session_condition = api_get_session_condition($session_id, true);
             }  
-			$sql = "SELECT  l.id, l.title, l.url, l.description, l.category_id, l.on_homepage  FROM $table l, $table_prop p WHERE p.ref=l.id AND p.tool = '".TOOL_LINK."' AND p.visibility != 2 $session_condition  ORDER BY l.display_order";
-		} else {
-			$table = Database :: get_course_table(TABLE_LINK);
-			$table_prop = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-			$sql = "SELECT l.id, l.title, l.url, l.description, l.category_id, l.on_homepage  FROM $table l, $table_prop p WHERE p.ref=l.id AND p.tool = '".TOOL_LINK."' AND p.visibility != 2 AND l.session_id = 0 ORDER BY l.display_order";
+			$sql = "SELECT  l.id, l.title, l.url, l.description, l.category_id, l.on_homepage 
+					FROM $table l, $table_prop p
+					WHERE l.c_id = $course_id AND p.c_id = $course_id AND p.ref=l.id AND p.tool = '".TOOL_LINK."' AND p.visibility != 2 $session_condition  
+					ORDER BY l.display_order";
+		} else {		
+			$sql = "SELECT l.id, l.title, l.url, l.description, l.category_id, l.on_homepage  
+					FROM $table l, $table_prop p 
+					WHERE l.c_id = $course_id AND p.c_id = $course_id AND p.ref=l.id AND p.tool = '".TOOL_LINK."' AND p.visibility != 2 AND l.session_id = 0 
+					ORDER BY l.display_order";
 		}
 
 		$db_result = Database::query($sql);
-		while ($obj = Database::fetch_object($db_result))
-		{
+		while ($obj = Database::fetch_object($db_result)) {
 			$link = new Link($obj->id, $obj->title, $obj->url, $obj->description, $obj->category_id, $obj->on_homepage);
 			$this->course->add_resource($link);
 
@@ -272,8 +302,7 @@ class CourseBuilder {
 				$res = $this->build_link_category($obj->category_id);
 			}
 
-			if($res > 0)
-			{
+			if($res > 0) {
 				$this->course->resources[RESOURCE_LINK][$obj->id]->add_linked_resource(RESOURCE_LINKCATEGORY, $obj->category_id);
 			}
 		}
@@ -284,10 +313,10 @@ class CourseBuilder {
 	function build_tool_intro()
 	{
 		$table = Database :: get_course_table(TABLE_TOOL_INTRO);
-		$sql = 'SELECT * FROM '.$table;
+		$course_id = api_get_course_int_id();		
+		$sql = "SELECT * FROM $table WHERE c_id = $course_id ";
 		$db_result = Database::query($sql);
-		while ($obj = Database::fetch_object($db_result))
-		{
+		while ($obj = Database::fetch_object($db_result)) {
 			$tool_intro = new ToolIntro($obj->id, $obj->intro_text);
 			$this->course->add_resource($tool_intro);
 		}
@@ -295,19 +324,15 @@ class CourseBuilder {
 	/**
 	 * Build a link category
 	 */
-	function build_link_category($id, $course_code = '')
-	{
-		if (!empty($course_code)) {
-			$course_info = api_get_course_info($course_code);
-			$link_cat_table = Database :: get_course_table(TABLE_LINK_CATEGORY, $course_info['dbName']);
-		} else {
-			$link_cat_table = Database :: get_course_table(TABLE_LINK_CATEGORY);
-		}
+	function build_link_category($id, $course_code = '') {
+		$course_info = api_get_course_info($course_code);
+		$course_id 		= $course_info['real_id'];
+		
+		$link_cat_table = Database :: get_course_table(TABLE_LINK_CATEGORY);
 
-		$sql = 'SELECT * FROM '.$link_cat_table.' WHERE id = '.$id;
+		$sql = "SELECT * FROM $link_cat_table WHERE c_id = $course_id AND id = $id";
 		$db_result = Database::query($sql);
-		while ($obj = Database::fetch_object($db_result))
-		{
+		while ($obj = Database::fetch_object($db_result)) {
 			$link_category = new LinkCategory($obj->id, $obj->category_title, $obj->description, $obj->display_order);
 			$this->course->add_resource($link_category);
 			return $id;
@@ -317,37 +342,36 @@ class CourseBuilder {
 	/**
 	 * Build the Quizzes
 	 */
-	function build_quizzes($session_id = 0, $course_code = '', $with_base_content = false)
-	{	    
+	function build_quizzes($session_id = 0, $course_code = '', $with_base_content = false) {
+		$course_info = api_get_course_info($course_code);
+		$table_qui = Database :: get_course_table(TABLE_QUIZ_TEST);
+		$table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
+		$table_doc = Database :: get_course_table(TABLE_DOCUMENT);
+		
+		$course_id 		= $course_info['real_id'];		
+		
 		if (!empty($course_code) && !empty($session_id)) {		    
 		    $session_id  = intval($session_id);
             if ($with_base_content) {
                 $session_condition = api_get_session_condition($session_id, true, true);                
             } else {
                 $session_condition = api_get_session_condition($session_id, true);
-            }            
-			$course_info = api_get_course_info($course_code);
-			$table_qui = Database :: get_course_table(TABLE_QUIZ_TEST, $course_info['dbName']);
-			$table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION, $course_info['dbName']);
-			$table_doc = Database :: get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
+            }
 			$session_id = intval($session_id);
-			$sql = 'SELECT * FROM '.$table_qui.' WHERE active >=0 '.$session_condition; //select only quizzes with active = 0 or 1 (not -1 which is for deleted quizzes)
-		} else {
-			$table_qui = Database :: get_course_table(TABLE_QUIZ_TEST);
-			$table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
-			$table_doc = Database :: get_course_table(TABLE_DOCUMENT);
-			$sql = 'SELECT * FROM '.$table_qui.' WHERE active >=0 AND session_id = 0'; //select only quizzes with active = 0 or 1 (not -1 which is for deleted quizzes)
+			$sql = "SELECT * FROM $table_qui WHERE c_id = $course_id AND active >=0 $session_condition"; //select only quizzes with active = 0 or 1 (not -1 which is for deleted quizzes)
+		} else {			
+			$sql = "SELECT * FROM $table_qui WHERE c_id = $course_id AND active >=0 AND session_id = 0"; //select only quizzes with active = 0 or 1 (not -1 which is for deleted quizzes)
 		}
 
 		$db_result = Database::query($sql);
 		while ($obj = Database::fetch_object($db_result)) {
 			if (strlen($obj->sound) > 0) {
-				$doc = Database::fetch_object(Database::query("SELECT id FROM ".$table_doc." WHERE path = '/audio/".$obj->sound."'"));
+				$doc = Database::fetch_object(Database::query("SELECT id FROM ".$table_doc." WHERE c_id = $course_id AND path = '/audio/".$obj->sound."'"));
 				$obj->sound = $doc->id;
 			}
 			$quiz = new Quiz($obj->id, $obj->title, $obj->description, $obj->random, $obj->type, $obj->active, $obj->sound, $obj->max_attempt, 
 			                 $obj->results_disabled, $obj->access_condition, $obj->start_time, $obj->end_time, $obj->feedback_type, $obj->random_answers, $obj->expired_time, $obj->session_id);
-			$sql = 'SELECT * FROM '.$table_rel.' WHERE exercice_id = '.$obj->id;
+			$sql = 'SELECT * FROM '.$table_rel.' WHERE c_id = '.$course_id.' AND exercice_id = '.$obj->id;
 			$db_result2 = Database::query($sql);
 			while ($obj2 = Database::fetch_object($db_result2)) {
 				$quiz->add_question($obj2->question_id, $obj2->question_order);
@@ -365,24 +389,18 @@ class CourseBuilder {
 	/**
 	 * Build the Quiz-Questions
 	 */
-	function build_quiz_questions($course_code = '')
-	{
-
-		if (!empty($course_code)) {
-			$course_info = api_get_course_info($course_code);
-			$table_qui = Database :: get_course_table(TABLE_QUIZ_TEST,$course_info['dbName']);
-			$table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION,$course_info['dbName']);
-			$table_que = Database :: get_course_table(TABLE_QUIZ_QUESTION,$course_info['dbName']);
-			$table_ans = Database :: get_course_table(TABLE_QUIZ_ANSWER,$course_info['dbName']);
-		} else {
-			$table_qui = Database :: get_course_table(TABLE_QUIZ_TEST);
-			$table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
-			$table_que = Database :: get_course_table(TABLE_QUIZ_QUESTION);
-			$table_ans = Database :: get_course_table(TABLE_QUIZ_ANSWER);
-		}
+	function build_quiz_questions($course_code = '') {
+		$course_info = api_get_course_info($course_code);
+		$course_id 		= $course_info['real_id'];
+				
+		$table_qui = Database :: get_course_table(TABLE_QUIZ_TEST);
+		$table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
+		$table_que = Database :: get_course_table(TABLE_QUIZ_QUESTION);
+		$table_ans = Database :: get_course_table(TABLE_QUIZ_ANSWER);
 
 		// Building normal tests.
-		$sql = 'SELECT * FROM '.$table_que;
+		$sql = "SELECT * FROM $table_que WHERE c_id = $course_id ";
+		
 		$db_result = Database::query($sql);
 		while ($obj = Database::fetch_object($db_result)) {
 			$question = new QuizQuestion($obj->id, $obj->question, $obj->description, $obj->ponderation, $obj->type, $obj->position, $obj->picture,$obj->level, $obj->extra);
@@ -396,15 +414,20 @@ class CourseBuilder {
 
 		// Building a fictional test for collecting orphan questions.
 		$build_orphan_questions = !empty($_POST['recycle_option']); // When a course is emptied this option should be activated (true).
-		$sql = 'SELECT * FROM '.$table_que.
-			' as questions LEFT JOIN '.$table_rel.' as quizz_questions ON questions.id=quizz_questions.question_id LEFT JOIN '.$table_qui.
-			' as exercices ON exercice_id=exercices.id WHERE quizz_questions.exercice_id IS NULL OR exercices.active = -1'; // active = -1 means "deleted" test.
+		$sql = "SELECT * FROM $table_que as questions LEFT JOIN $table_rel as quizz_questions 
+				ON questions.id=quizz_questions.question_id LEFT JOIN $table_qui as exercices 
+				ON exercice_id=exercices.id 
+				WHERE	questions.c_id = $course_id  AND 
+						quizz_questions.c_id = $course_id  AND
+						exercices.c_id = $course_id  AND
+						quizz_questions.exercice_id IS NULL OR 
+						exercices.active = -1"; // active = -1 means "deleted" test.
 		$db_result = Database::query($sql);
 		if (Database::num_rows($db_result) > 0) {
 			$build_orphan_questions = true;
 			while ($obj = Database::fetch_object($db_result)) {
 				$question = new QuizQuestion($obj->id, $obj->question, $obj->description, $obj->ponderation, $obj->type, $obj->position, $obj->picture,$obj->level, $obj->extra);
-				$sql = 'SELECT * FROM '.$table_ans.' WHERE question_id = '.(int)$obj->id;
+				$sql = "SELECT * FROM $table_ans WHERE c_id = $course_id AND question_id = ".$obj->id;
 				$db_result2 = Database::query($sql);
 				while ($obj2 = Database::fetch_object($db_result2)) {
 					$question->add_answer($obj2->id, $obj2->answer, $obj2->correct, $obj2->comment, $obj2->ponderation, $obj2->position, $obj2->hotspot_coordinates, $obj2->hotspot_type);
@@ -425,13 +448,20 @@ class CourseBuilder {
 		$table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
 		$table_que = Database :: get_course_table(TABLE_QUIZ_QUESTION);
 		$table_ans = Database :: get_course_table(TABLE_QUIZ_ANSWER);
+		
+		$course_id = api_get_course_int_id();
+		
 
-		$sql = 'SELECT * FROM '.$table_que.
-			' as questions LEFT JOIN '.$table_rel.' as quizz_questions ON questions.id=quizz_questions.question_id LEFT JOIN '.$table_qui.
-			' as exercices ON exercice_id=exercices.id WHERE quizz_questions.exercice_id IS NULL OR exercices.active = -1';
+		$sql = 'SELECT * FROM '.$table_que.' as questions LEFT JOIN '.$table_rel.' as quizz_questions 
+				ON questions.id=quizz_questions.question_id LEFT JOIN '.$table_qui.' as exercices 
+				ON exercice_id=exercices.id 
+				WHERE 	questions.c_id = '.$course_id.'  AND 
+						quizz_questions.c_id = '.$course_id.' AND
+						exercices.c_id = '.$course_id.' AND
+						quizz_questions.exercice_id IS NULL OR 
+						exercices.active = -1';
 		$db_result = Database::query($sql);
-		if (Database::num_rows($db_result) > 0)
-		{
+		if (Database::num_rows($db_result) > 0) {
 			$orphan_questions = new Quiz(-1, get_lang('OrphanQuestions', ''), '', 0, 0, 1, '', 0); // Tjis is the fictional test for collecting orphan questions.
 			$this->course->add_resource($orphan_questions);
 			while ($obj = Database::fetch_object($db_result))
@@ -450,11 +480,12 @@ class CourseBuilder {
 	/**
 	 * Build the Surveys
 	 */
-	function build_surveys()
-	{
+	function build_surveys() {
 		$table_survey = Database :: get_course_table(TABLE_SURVEY);
 		$table_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
-		$sql = 'SELECT * FROM '.$table_survey.' WHERE session_id = 0 ';
+		$course_id = api_get_course_int_id();
+		
+		$sql = 'SELECT * FROM '.$table_survey.' WHERE c_id = '.$course_id.' AND session_id = 0 ';
 		$db_result = Database::query($sql);
 		while ($obj = Database::fetch_object($db_result))
 		{
@@ -481,7 +512,10 @@ class CourseBuilder {
 	{
 		$table_que = Database :: get_course_table(TABLE_SURVEY_QUESTION);
 		$table_opt = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
-		$sql = 'SELECT * FROM '.$table_que;
+		
+		$course_id = api_get_course_int_id();
+		
+		$sql = 'SELECT * FROM '.$table_que.' WHERE c_id = '.$course_id.'  ';
 		$db_result = Database::query($sql);
 		while ($obj = Database::fetch_object($db_result))
 		{
@@ -489,7 +523,7 @@ class CourseBuilder {
 											$obj->survey_question, $obj->survey_question_comment,
 											$obj->type, $obj->display, $obj->sort,
 											$obj->shared_question_id, $obj->max_value);
-			$sql = 'SELECT * FROM '.$table_opt.' WHERE question_id = '."'".$obj->question_id."'";
+			$sql = 'SELECT * FROM '.$table_opt.' WHERE c_id = '.$course_id.' AND question_id = '."'".$obj->question_id."'";
 			$db_result2 = Database::query($sql);
 			while ($obj2 = Database::fetch_object($db_result2))
 			{
@@ -503,11 +537,13 @@ class CourseBuilder {
 	 */
 	function build_announcements() {
 		$table = Database :: get_course_table(TABLE_ANNOUNCEMENT);
-		$sql = 'SELECT * FROM '.$table.' WHERE session_id = 0';
+		$course_id = api_get_course_int_id();
+		
+		$sql = 'SELECT * FROM '.$table.' WHERE c_id = '.$course_id.' AND session_id = 0';
 		$db_result = Database::query($sql);
 		$table_attachment = Database :: get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
 		while ($obj = Database::fetch_object($db_result)) {			
-			$sql = 'SELECT path, comment, filename, size  FROM '.$table_attachment.' WHERE announcement_id = '.$obj->id.'';
+			$sql = 'SELECT path, comment, filename, size  FROM '.$table_attachment.' WHERE c_id = '.$course_id.' AND announcement_id = '.$obj->id.'';
 			$result = Database::query($sql);
 			$attachment_obj = Database::fetch_object($result);
 			$att_path = $att_filename = $att_size = $atth_comment = '';
@@ -527,12 +563,14 @@ class CourseBuilder {
 	 */
 	function build_events()
 	{
-		$table = Database :: get_course_table(TABLE_AGENDA, $this->course->db_name);
-		$sql = 'SELECT * FROM '.$table.' WHERE session_id = 0';
+		$table = Database :: get_course_table(TABLE_AGENDA);
+		$course_id = api_get_course_int_id();
+		
+		$sql = 'SELECT * FROM '.$table.' WHERE c_id = '.$course_id.' AND session_id = 0';
 		$db_result = Database::query($sql);
 		while ($obj = Database::fetch_object($db_result)) {
-			$table_attachment = Database :: get_course_table(TABLE_AGENDA_ATTACHMENT, $this->course->db_name);
-			$sql = 'SELECT path, comment, filename, size  FROM '.$table_attachment.' WHERE agenda_id = '.$obj->id.'';
+			$table_attachment = Database :: get_course_table(TABLE_AGENDA_ATTACHMENT);
+			$sql = 'SELECT path, comment, filename, size  FROM '.$table_attachment.' WHERE c_id = '.$course_id.' AND agenda_id = '.$obj->id.'';
 			$result = Database::query($sql);
 			
 			$attachment_obj = Database::fetch_object($result);			
@@ -552,27 +590,29 @@ class CourseBuilder {
 	/**
 	 * Build the course-descriptions
 	 */
-	function build_course_descriptions($session_id = 0,$course_code = '', $with_base_content = false)
-	{
+	function build_course_descriptions($session_id = 0,$course_code = '', $with_base_content = false) {
+		$course_info = api_get_course_info($course_code);
+		$course_id 		= $course_info['real_id'];
+		
+		$table = Database :: get_course_table(TABLE_COURSE_DESCRIPTION);
+		
 		if (!empty($session_id) && !empty($course_code)) {
-			$course_info = api_get_course_info($course_code);
-			$table = Database :: get_course_table(TABLE_COURSE_DESCRIPTION,$course_info['dbName']);
+			
 			$session_id = intval($session_id);
             if ($with_base_content) {
-                $session_condition = api_get_session_condition($session_id, false, true);                
+                $session_condition = api_get_session_condition($session_id, true, true);                
             } else {
-                $session_condition = api_get_session_condition($session_id, false);
+                $session_condition = api_get_session_condition($session_id, true);
             }  
            
-			$sql = 'SELECT * FROM '.$table. ' '.$session_condition;
+			$sql = 'SELECT * FROM '.$table. ' WHERE c_id = '.$course_id.' '.$session_condition;
 		} else {
 			$table = Database :: get_course_table(TABLE_COURSE_DESCRIPTION);
-			$sql = 'SELECT * FROM '.$table. ' WHERE session_id = 0';
+			$sql = 'SELECT * FROM '.$table. ' WHERE c_id = '.$course_id.'  AND session_id = 0';
 		}
 
 		$db_result = Database::query($sql);
-		while ($obj = Database::fetch_object($db_result))
-		{
+		while ($obj = Database::fetch_object($db_result)) {
 			$cd = new CourseDescription($obj->id, $obj->title, $obj->content, $obj->description_type);
 			$this->course->add_resource($cd);
 		}
@@ -581,31 +621,29 @@ class CourseBuilder {
 	 * Build the learnpaths
 	 */
 	function build_learnpaths($session_id = 0,$course_code = '', $with_base_content = false) {
-
+		
+		$course_info 	= api_get_course_info($course_code);
+		$course_id 		= $course_info['real_id'];
+		$table_main 	= Database::get_course_table(TABLE_LP_MAIN);
+		$table_item 	= Database::get_course_table(TABLE_LP_ITEM);
+		$table_tool 	= Database::get_course_table(TABLE_TOOL_LIST);
+		
 		if (!empty($session_id) && !empty($course_code)) {
-			$course_info 	= api_get_course_info($course_code);
-			$table_main 	= Database :: get_course_table(TABLE_LP_MAIN,$course_info['dbName']);
-			$table_item 	= Database :: get_course_table(TABLE_LP_ITEM,$course_info['dbName']);
-			$table_tool 	= Database::get_course_table(TABLE_TOOL_LIST,$course_info['dbName']);
-			
 			$session_id = intval($session_id);
             if ($with_base_content) {
-                $session_condition = api_get_session_condition($session_id, false, true);                
+                $session_condition = api_get_session_condition($session_id, true, true);                
             } else {
-                $session_condition = api_get_session_condition($session_id, false);
+                $session_condition = api_get_session_condition($session_id, true);
             }            
-			$sql = 'SELECT * FROM '.$table_main.' '.$session_condition;
-		} else {
-			$table_main 	= Database::get_course_table(TABLE_LP_MAIN);
-			$table_item 	= Database::get_course_table(TABLE_LP_ITEM);
-			$table_tool 	= Database::get_course_table(TABLE_TOOL_LIST);
-			$sql = 'SELECT * FROM '.$table_main.' WHERE session_id = 0';
-		}        
+			$sql = 'SELECT * FROM '.$table_main.' WHERE c_id = '.$course_id.'  '.$session_condition;
+		} else {			
+			$sql = 'SELECT * FROM '.$table_main.' WHERE c_id = '.$course_id.' AND session_id = 0';
+		}		 
 		$db_result = Database::query($sql);
 
 		while ($obj = Database::fetch_object($db_result)) {
 			$items = array();
-			$sql_items = "SELECT * FROM ".$table_item." WHERE lp_id = ".$obj->id."";
+			$sql_items = "SELECT * FROM ".$table_item." WHERE c_id = '$course_id' AND lp_id = ".$obj->id."";
 			$db_items = Database::query($sql_items);
 			while ($obj_item = Database::fetch_object($db_items)) {
 				$item['id']				   = $obj_item->id;
@@ -628,7 +666,7 @@ class CourseBuilder {
 				$items[] = $item;
 			}
 
-			$sql_tool = "SELECT id FROM ".$table_tool." WHERE (link LIKE '%lp_controller.php%lp_id=".$obj->id."%' and image='scormbuilder.gif') AND visibility='1'";
+			$sql_tool = "SELECT id FROM ".$table_tool." WHERE c_id = $course_id AND  (link LIKE '%lp_controller.php%lp_id=".$obj->id."%' and image='scormbuilder.gif') AND visibility='1'";
 			$db_tool = Database::query($sql_tool);
 
 			if(Database::num_rows($db_tool)) {
@@ -669,7 +707,7 @@ class CourseBuilder {
 
 		//save scorm directory (previously build_scorm_documents())
 		$i = 1;
-		if($dir=@opendir($this->course->backup_path.'/scorm')) {
+		if ($dir=@opendir($this->course->backup_path.'/scorm')) {
 			while($file=readdir($dir)) {
 				if(is_dir($this->course->backup_path.'/scorm/'.$file) && !in_array($file,array('.','..'))) {
 					$doc = new ScormDocument($i++, '/'.$file, $file);
@@ -684,29 +722,30 @@ class CourseBuilder {
 	 * Build the glossarys
 	 */
 	function build_glossary($session_id = 0, $course_code = '', $with_base_content = false) {
-
-		if (!empty($session_id) && !empty($course_code)) {
-			$course_info = api_get_course_info($course_code);
-			$table_glossary = Database :: get_course_table(TABLE_GLOSSARY,$course_info['dbName']);
+		$course_info 	= api_get_course_info($course_code);
+		$table_glossary = Database :: get_course_table(TABLE_GLOSSARY);
+		$course_id 		= $course_info['real_id'];		
+		
+		if (!empty($session_id) && !empty($course_code)) {			
 			$session_id = intval($session_id);
 		    if ($with_base_content) {
-                $session_condition = api_get_session_condition($session_id, false, true);                
+                $session_condition = api_get_session_condition($session_id, true, true);                
             } else {
-                $session_condition = api_get_session_condition($session_id, false);
+                $session_condition = api_get_session_condition($session_id, true);
             }
             //@todo check this queries are the same ... 
 	        if (!empty($this->course->type) && $this->course->type=='partial') {
-	        	$sql = 'SELECT * FROM '.$table_glossary.' g '.$session_condition;
+	        	$sql = 'SELECT * FROM '.$table_glossary.' g WHERE g.c_id = '.$course_id.' '.$session_condition;
 	        } else {
-	        	$sql = 'SELECT * FROM '.$table_glossary.' g '.$session_condition;
+	        	$sql = 'SELECT * FROM '.$table_glossary.' g WHERE g.c_id = '.$course_id.' '.$session_condition;
 	        }
 		} else {
 			$table_glossary = Database :: get_course_table(TABLE_GLOSSARY);
 			//@todo check this queries are the same ... ayayay 
 	        if (!empty($this->course->type) && $this->course->type=='partial') {
-	        	$sql = 'SELECT * FROM '.$table_glossary.' g WHERE session_id = 0';
+	        	$sql = 'SELECT * FROM '.$table_glossary.' g WHERE g.c_id = '.$course_id.' AND session_id = 0';
 	        } else {
-	        	$sql = 'SELECT * FROM '.$table_glossary.' g WHERE session_id = 0';
+	        	$sql = 'SELECT * FROM '.$table_glossary.' g WHERE g.c_id = '.$course_id.' AND session_id = 0';
 	        }
 		}
 		$db_result = Database::query($sql);
@@ -745,26 +784,26 @@ class CourseBuilder {
 		return $list;
 	}
 
-	function build_wiki($session_id = 0, $course_code = 0, $with_base_content = false)
-	{
-		if (!empty($session_id) && !empty($course_code)) {
-			$course_info = api_get_course_info($course_code);
-			$tbl_wiki = Database::get_course_table(TABLE_WIKI,$course_info['dbName']);
+	function build_wiki($session_id = 0, $course_code = 0, $with_base_content = false) {
+		$course_info 	= api_get_course_info($course_code);
+		$tbl_wiki 		= Database::get_course_table(TABLE_WIKI);
+		
+		$course_id 		= $course_info['real_id'];
+				
+		if (!empty($session_id) && !empty($course_code)) {			
 			 $session_id = intval($session_id);
             if ($with_base_content) {
-                $session_condition = api_get_session_condition($session_id, false, true);                
+                $session_condition = api_get_session_condition($session_id, true, true);                
             } else {
-                $session_condition = api_get_session_condition($session_id, false);
-            }  
-            
-	        $sql = 'SELECT * FROM ' . $tbl_wiki . ' '.$session_condition;
+                $session_condition = api_get_session_condition($session_id, true);
+            }            
+	        $sql = 'SELECT * FROM ' . $tbl_wiki . ' WHERE c_id = '.$course_id.' '.$session_condition;
 		} else {
 			$tbl_wiki = Database::get_course_table(TABLE_WIKI);
-	        $sql = 'SELECT * FROM ' . $tbl_wiki . ' WHERE session_id = 0';
+	        $sql = 'SELECT * FROM ' . $tbl_wiki . ' WHERE c_id = '.$course_id.' AND session_id = 0';
 		}
 		$db_result = Database::query($sql);
-		while ($obj = Database::fetch_object($db_result))
-		{
+		while ($obj = Database::fetch_object($db_result)) {
 			$wiki = new Wiki($obj->id, $obj->page_id, $obj->reflink, $obj->title, $obj->content, $obj->user_id, $obj->group_id, $obj->dtime, $obj->progress, $obj->version);
 			$this->course->add_resource($wiki);
 		}
@@ -774,28 +813,29 @@ class CourseBuilder {
 	* Build the Surveys
 	*/
 	function build_thematic() {
-		$table_thematic	= Database :: get_course_table(TABLE_THEMATIC);
+		$table_thematic			= Database :: get_course_table(TABLE_THEMATIC);
 		$table_thematic_advance = Database :: get_course_table(TABLE_THEMATIC_ADVANCE);
 		$table_thematic_plan    = Database :: get_course_table(TABLE_THEMATIC_PLAN);
 		
-		$sql = 'SELECT * FROM '.$table_thematic.' WHERE session_id = 0 ';
+		$course_id = api_get_course_int_id();
+		
+		
+		$sql = 'SELECT * FROM '.$table_thematic.' WHERE c_id = '.$course_id.' AND session_id = 0 ';
 		$db_result = Database::query($sql);
 		while ($row = Database::fetch_array($db_result,'ASSOC')) {
 			$thematic = new Thematic($row);
-			$sql = 'SELECT * FROM '.$table_thematic_advance.' WHERE thematic_id = '.$row['id'];
+			$sql = 'SELECT * FROM '.$table_thematic_advance.' WHERE c_id = '.$course_id.' AND thematic_id = '.$row['id'];
 			
 			$result = Database::query($sql);
 			while ($sub_row = Database::fetch_array($result,'ASSOC')) {				
 				$thematic->add_thematic_advance($sub_row);
-			}
-			
-			$sql = 'SELECT * FROM '.$table_thematic_plan.' WHERE thematic_id = '.$row['id'];
+			}			
+			$sql = 'SELECT * FROM '.$table_thematic_plan.' WHERE c_id = '.$course_id.' AND thematic_id = '.$row['id'];
 				
 			$result = Database::query($sql);
 			while ($sub_row = Database::fetch_array($result,'ASSOC')) {
 				$thematic->add_thematic_plan($sub_row);
-			}
-			
+			}			
 			$this->course->add_resource($thematic);			
 		}		
 	}	
@@ -807,11 +847,14 @@ class CourseBuilder {
 		$table_attendance			= Database :: get_course_table(TABLE_ATTENDANCE);
 		$table_attendance_calendar  = Database :: get_course_table(TABLE_ATTENDANCE_CALENDAR);
 		
-		$sql = 'SELECT * FROM '.$table_attendance.' WHERE session_id = 0 ';
+		$course_id = api_get_course_int_id();
+		
+		
+		$sql = 'SELECT * FROM '.$table_attendance.' WHERE c_id = '.$course_id.' AND session_id = 0 ';
 		$db_result = Database::query($sql);
 		while ($row = Database::fetch_array($db_result,'ASSOC')) {
 			$obj = new Attendance($row);
-			$sql = 'SELECT * FROM '.$table_attendance_calendar.' WHERE attendance_id = '.$row['id'];
+			$sql = 'SELECT * FROM '.$table_attendance_calendar.' WHERE c_id = '.$course_id.' AND attendance_id = '.$row['id'];
 				
 			$result = Database::query($sql);
 			while ($sub_row = Database::fetch_array($result,'ASSOC')) {

+ 95 - 102
main/coursecopy/classes/CourseRecycler.class.php

@@ -19,20 +19,21 @@ class CourseRecycler
      * @param course $course The course-object which contains the items to
      * delete
      */
-    function CourseRecycler($course)
-    {
-        $this->course = $course;
+    function CourseRecycler($course) {
+        $this->course = $course;        
+        $this->course_info = api_get_course_info($this->course->code); 
+        $this->course_id = $course->info['real_id'];
     }
     /**
      * Delete all items from the course.
      * This deletes all items in the course-object from the current Chamilo-
      * course
      */
-    function recycle()
-    {
-        $table_tool_intro = Database::get_course_table(TABLE_TOOL_INTRO);
-        $table_linked_resources = Database :: get_course_table(TABLE_LINKED_RESOURCES);
-        $table_item_properties = Database::get_course_table(TABLE_ITEM_PROPERTY);
+    function recycle() {
+    	
+        $table_tool_intro 		= Database::get_course_table(TABLE_TOOL_INTRO);
+        $table_linked_resources = Database::get_course_table(TABLE_LINKED_RESOURCES);
+        $table_item_properties 	= Database::get_course_table(TABLE_ITEM_PROPERTY);
 
         $this->recycle_links();
         $this->recycle_link_categories();
@@ -53,13 +54,13 @@ class CourseRecycler
 
         foreach ($this->course->resources as $type => $resources) {
             foreach ($resources as $id => $resource) {
-                $sql = "DELETE FROM ".$table_linked_resources." WHERE (source_type = '".$type."' AND source_id = '".$id."') OR (resource_type = '".$type."' AND resource_id = '".$id."')  ";
+                $sql = "DELETE FROM ".$table_linked_resources." WHERE c_id = ".$this->course_id." AND  (source_type = '".$type."' AND source_id = '".$id."') OR (resource_type = '".$type."' AND resource_id = '".$id."')  ";
                 Database::query($sql);
                 if(is_numeric($id)) {
-                    $sql = "DELETE FROM ".$table_item_properties." WHERE tool ='".$resource->get_tool()."' AND ref=".$id;
+                    $sql = "DELETE FROM ".$table_item_properties." WHERE c_id = ".$this->course_id." AND  tool ='".$resource->get_tool()."' AND ref=".$id;
                     Database::query($sql);
                 } elseif ($type == RESOURCE_TOOL_INTRO) {
-                    $sql = "DELETE FROM $table_tool_intro WHERE id='$id'";
+                    $sql = "DELETE FROM $table_tool_intro WHERE c_id = ".$this->course_id." AND  id='$id'";
                     Database::query($sql);
                 }
             }
@@ -74,8 +75,7 @@ class CourseRecycler
         if ($this->course->has_resources(RESOURCE_DOCUMENT))
         {
             $table = Database :: get_course_table(TABLE_DOCUMENT);
-            foreach ($this->course->resources[RESOURCE_DOCUMENT] as $id => $document)
-            {
+            foreach ($this->course->resources[RESOURCE_DOCUMENT] as $id => $document) {            	
                 rmdirr($this->course->backup_path.'/'.$document->path);
             }
             $ids = implode(',', (array_keys($this->course->resources[RESOURCE_DOCUMENT])));
@@ -123,13 +123,11 @@ class CourseRecycler
     /**
      * Delete links
      */
-    function recycle_links()
-    {
-        if ($this->course->has_resources(RESOURCE_LINK))
-        {
+    function recycle_links() {
+        if ($this->course->has_resources(RESOURCE_LINK)) {
             $table = Database :: get_course_table(TABLE_LINK);
             $ids = implode(',', (array_keys($this->course->resources[RESOURCE_LINK])));
-            $sql = "DELETE FROM ".$table." WHERE id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table." WHERE c_id = ".$this->course_id." AND id IN(".$ids.")";
             Database::query($sql);
         }
     }
@@ -138,8 +136,7 @@ class CourseRecycler
      */
     function recycle_forums()
     {
-        if ($this->course->has_resources(RESOURCE_FORUM))
-        {
+        if ($this->course->has_resources(RESOURCE_FORUM)) {
             $table_category = Database :: get_course_table(TABLE_FORUM_CATEGORY);
             $table_forum = Database :: get_course_table(TABLE_FORUM);
             $table_thread = Database :: get_course_table(TABLE_FORUM_THREAD);
@@ -154,45 +151,45 @@ class CourseRecycler
 
             $sql = "DELETE FROM ".$table_attachment.
                 " USING ".$table_attachment." INNER JOIN ".$table_post.
-                " WHERE ".$table_attachment.".post_id = ".$table_post.".post_id".
+                " WHERE c_id = ".$this->course_id." AND  ".$table_attachment.".post_id = ".$table_post.".post_id".
                 " AND ".$table_post.".forum_id IN(".$forum_ids.");";
             Database::query($sql);
 
             $sql = "DELETE FROM ".$table_mail_queue.
                 " USING ".$table_mail_queue." INNER JOIN ".$table_post.
-                " WHERE ".$table_mail_queue.".post_id = ".$table_post.".post_id".
+                " WHERE c_id = ".$this->course_id." AND  ".$table_mail_queue.".post_id = ".$table_post.".post_id".
                 " AND ".$table_post.".forum_id IN(".$forum_ids.");";
             Database::query($sql);
 
             // Just in case, deleting in the same table using thread_id as record-linker.
             $sql = "DELETE FROM ".$table_mail_queue.
                 " USING ".$table_mail_queue." INNER JOIN ".$table_thread.
-                " WHERE ".$table_mail_queue.".thread_id = ".$table_thread.".thread_id".
+                " WHERE c_id = ".$this->course_id." AND ".$table_mail_queue.".thread_id = ".$table_thread.".thread_id".
                 " AND ".$table_thread.".forum_id IN(".$forum_ids.");";
             Database::query($sql);
 
             $sql = "DELETE FROM ".$table_thread_qualify.
                 " USING ".$table_thread_qualify." INNER JOIN ".$table_thread.
-                " WHERE ".$table_thread_qualify.".thread_id = ".$table_thread.".thread_id".
+                " WHERE c_id = ".$this->course_id." AND ".$table_thread_qualify.".thread_id = ".$table_thread.".thread_id".
                 " AND ".$table_thread.".forum_id IN(".$forum_ids.");";
             Database::query($sql);
 
             $sql = "DELETE FROM ".$table_thread_qualify_log.
                 " USING ".$table_thread_qualify_log." INNER JOIN ".$table_thread.
-                " WHERE ".$table_thread_qualify_log.".thread_id = ".$table_thread.".thread_id".
+                " WHERE c_id = ".$this->course_id." AND ".$table_thread_qualify_log.".thread_id = ".$table_thread.".thread_id".
                 " AND ".$table_thread.".forum_id IN(".$forum_ids.");";
             Database::query($sql);
 
-            $sql = "DELETE FROM ".$table_notification." WHERE forum_id IN(".$forum_ids.")";
+            $sql = "DELETE FROM ".$table_notification." WHERE c_id = ".$this->course_id." AND forum_id IN(".$forum_ids.")";
             Database::query($sql);
 
-            $sql = "DELETE FROM ".$table_post." WHERE forum_id IN(".$forum_ids.")";
+            $sql = "DELETE FROM ".$table_post." WHERE c_id = ".$this->course_id." AND forum_id IN(".$forum_ids.")";
             Database::query($sql);
 
-            $sql = "DELETE FROM ".$table_thread." WHERE forum_id IN(".$forum_ids.")";
+            $sql = "DELETE FROM ".$table_thread." WHERE c_id = ".$this->course_id." AND forum_id IN(".$forum_ids.")";
             Database::query($sql);
 
-            $sql = "DELETE FROM ".$table_forum." WHERE forum_id IN(".$forum_ids.")";
+            $sql = "DELETE FROM ".$table_forum." WHERE c_id = ".$this->course_id." AND forum_id IN(".$forum_ids.")";
             Database::query($sql);
         }
     }
@@ -204,11 +201,11 @@ class CourseRecycler
     {
         $table_forum = Database :: get_course_table(TABLE_FORUM);
         $table_forumcat = Database :: get_course_table(TABLE_FORUM_CATEGORY);
-        $sql = "SELECT fc.cat_id FROM ".$table_forumcat." fc LEFT JOIN ".$table_forum." f ON fc.cat_id=f.forum_category WHERE f.forum_id IS NULL";
+        $sql = "SELECT fc.cat_id FROM ".$table_forumcat." fc LEFT JOIN ".$table_forum." f ON fc.cat_id=f.forum_category 
+        		WHERE fc.c_id = ".$this->course_id." AND f.c_id = ".$this->course_id." AND f.forum_id IS NULL";
         $res = Database::query($sql);
-        while ($obj = Database::fetch_object($res))
-        {
-            $sql = "DELETE FROM ".$table_forumcat." WHERE cat_id = ".$obj->cat_id;
+        while ($obj = Database::fetch_object($res)) {
+            $sql = "DELETE FROM ".$table_forumcat." WHERE c_id = ".$this->course_id." AND cat_id = ".$obj->cat_id;
             Database::query($sql);
         }
     }
@@ -220,11 +217,12 @@ class CourseRecycler
     {
         $link_cat_table = Database :: get_course_table(TABLE_LINK_CATEGORY);
         $link_table = Database :: get_course_table(TABLE_LINK);
-        $sql = "SELECT lc.id FROM ".$link_cat_table." lc LEFT JOIN ".$link_table." l ON lc.id=l.category_id WHERE l.id IS NULL";
+        $sql = "SELECT lc.id FROM ".$link_cat_table." lc LEFT JOIN ".$link_table." l ON lc.id=l.category_id 
+        		WHERE l.id IS NULL";
         $res = Database::query($sql);
         while ($obj = Database::fetch_object($res))
         {
-            $sql = "DELETE FROM ".$link_cat_table." WHERE id = ".$obj->id;
+            $sql = "DELETE FROM ".$link_cat_table." WHERE c_id = ".$this->course_id." AND id = ".$obj->id;
             Database::query($sql);
         }
     }
@@ -237,10 +235,10 @@ class CourseRecycler
             $table_attachment = Database :: get_course_table(TABLE_AGENDA_ATTACHMENT);
 
             $ids = implode(',', (array_keys($this->course->resources[RESOURCE_EVENT])));
-            $sql = "DELETE FROM ".$table." WHERE id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table." WHERE c_id = ".$this->course_id." AND id IN(".$ids.")";
             Database::query($sql);
 
-            $sql = "DELETE FROM ".$table_attachment." WHERE agenda_id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table_attachment." WHERE c_id = ".$this->course_id." AND agenda_id IN(".$ids.")";
             Database::query($sql);
         }
     }
@@ -253,62 +251,63 @@ class CourseRecycler
             $table_attachment = Database :: get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
 
             $ids = implode(',', (array_keys($this->course->resources[RESOURCE_ANNOUNCEMENT])));
-            $sql = "DELETE FROM ".$table." WHERE id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table." WHERE c_id = ".$this->course_id." AND id IN(".$ids.")";
             Database::query($sql);
 
-            $sql = "DELETE FROM ".$table_attachment." WHERE announcement_id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table_attachment." WHERE c_id = ".$this->course_id." AND announcement_id IN(".$ids.")";
             Database::query($sql);
         }
     }
     /**
      * Recycle quizzes - doesn't remove the questions and their answers, as they might still be used later
      */
-    function recycle_quizzes()
-    {
-        if ($this->course->has_resources(RESOURCE_QUIZ))
-        {
-            $table_qui_que = Database :: get_course_table(TABLE_QUIZ_QUESTION);
-            $table_qui_ans = Database :: get_course_table(TABLE_QUIZ_ANSWER);
-            $table_qui = Database :: get_course_table(TABLE_QUIZ_TEST);
-            $table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
+    function recycle_quizzes() {
+    	
+        if ($this->course->has_resources(RESOURCE_QUIZ)) {
+            $table_qui_que 	= Database :: get_course_table(TABLE_QUIZ_QUESTION);
+            $table_qui_ans 	= Database :: get_course_table(TABLE_QUIZ_ANSWER);
+            $table_qui 		= Database :: get_course_table(TABLE_QUIZ_TEST);
+            $table_rel 		= Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
 
             $ids = array_keys($this->course->resources[RESOURCE_QUIZ]);
             $delete_orphan_questions = in_array(-1, $ids);
             $ids = implode(',', $ids);
 
             // Deletion of the normal tests, questions in them are not deleted, they become orphan at this moment.
-            $sql = "DELETE FROM ".$table_qui." WHERE id <> -1 AND id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table_qui." WHERE c_id = ".$this->course_id." AND id <> -1 AND id IN(".$ids.")";
             Database::query($sql);
-            $sql = "DELETE FROM ".$table_rel." WHERE exercice_id <> -1 AND exercice_id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table_rel." WHERE c_id = ".$this->course_id." AND exercice_id <> -1 AND exercice_id IN(".$ids.")";
             Database::query($sql);
 
             // Identifying again and deletion of the orphan questions, if it was desired.
-            if ($delete_orphan_questions)
-            {
-                $sql = 'SELECT questions.id FROM '.$table_qui_que.
-                    ' as questions LEFT JOIN '.$table_rel.' as quizz_questions ON questions.id=quizz_questions.question_id LEFT JOIN '.$table_qui.
-                    ' as exercices ON exercice_id=exercices.id WHERE quizz_questions.exercice_id IS NULL OR exercices.active = -1'; // active = -1 means "deleted" test.
+            if ($delete_orphan_questions) {
+                $sql = 'SELECT questions.id FROM '.$table_qui_que.' as questions LEFT JOIN '.$table_rel.' as quizz_questions 
+                		ON questions.id=quizz_questions.question_id LEFT JOIN '.$table_qui.' as exercices 
+                		ON exercice_id=exercices.id 
+                		WHERE 
+                			questions.c_id = '.$this->course_id.' AND
+                			quizz_questions.c_id = '.$this->course_id.' AND
+                			exercices.c_id = '.$this->course_id.' AND 
+                			quizz_questions.exercice_id IS NULL OR exercices.active = -1'; // active = -1 means "deleted" test.
                 $db_result = Database::query($sql);
-                if (Database::num_rows($db_result) > 0)
-                {
+                if (Database::num_rows($db_result) > 0) {
                     $orphan_ids = array();
-                    while ($obj = Database::fetch_object($db_result))
-                    {
+                    while ($obj = Database::fetch_object($db_result)) {
                         $orphan_ids[] = $obj->id;
                     }
                     $orphan_ids = implode(',', $orphan_ids);
-                    $sql = "DELETE FROM ".$table_rel." WHERE question_id IN(".$orphan_ids.")";
+                    $sql = "DELETE FROM ".$table_rel." WHERE c_id = ".$this->course_id." AND question_id IN(".$orphan_ids.")";
                     Database::query($sql);
-                    $sql = "DELETE FROM ".$table_qui_ans." WHERE question_id IN(".$orphan_ids.")";
+                    $sql = "DELETE FROM ".$table_qui_ans." WHERE c_id = ".$this->course_id." AND question_id IN(".$orphan_ids.")";
                     Database::query($sql);
-                    $sql = "DELETE FROM ".$table_qui_que." WHERE id IN(".$orphan_ids.")";
+                    $sql = "DELETE FROM ".$table_qui_que." WHERE c_id = ".$this->course_id." AND id IN(".$orphan_ids.")";
                     Database::query($sql);
                 }
             }
         }
 
         // Purge "deleted" tests (active = -1).
-        $sql = "DELETE FROM ".$table_qui." WHERE active = -1";
+        $sql = "DELETE FROM ".$table_qui." WHERE c_id = ".$this->course_id." AND active = -1";
         Database::query($sql);
     }
     /**
@@ -324,15 +323,15 @@ class CourseRecycler
             $table_survey_a = Database :: get_course_Table(TABLE_SURVEY_ANSWER);
             $table_survey_i = Database :: get_course_table(TABLE_SURVEY_INVITATION);
             $ids = implode(',', (array_keys($this->course->resources[RESOURCE_SURVEY])));
-            $sql = "DELETE FROM ".$table_survey_i." ";
+            $sql = "DELETE FROM ".$table_survey_i." WHERE c_id = ".$this->course_id." ";
             Database::query($sql);
-            $sql = "DELETE FROM ".$table_survey_a." WHERE survey_id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table_survey_a." WHERE c_id = ".$this->course_id."  AND survey_id IN(".$ids.")";
             Database::query($sql);
-            $sql = "DELETE FROM ".$table_survey_q_o." WHERE survey_id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table_survey_q_o." WHERE c_id = ".$this->course_id."  AND survey_id IN(".$ids.")";
             Database::query($sql);
-            $sql = "DELETE FROM ".$table_survey_q." WHERE survey_id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table_survey_q." WHERE c_id = ".$this->course_id."  AND survey_id IN(".$ids.")";
             Database::query($sql);
-            $sql = "DELETE FROM ".$table_survey." WHERE survey_id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table_survey." WHERE c_id = ".$this->course_id."  AND survey_id IN(".$ids.")";
             Database::query($sql);
         }
     }
@@ -341,19 +340,17 @@ class CourseRecycler
      */
     function recycle_learnpaths()
     {
-        if ($this->course->has_resources(RESOURCE_LEARNPATH))
-        {
+        if ($this->course->has_resources(RESOURCE_LEARNPATH)) {
             $table_main = Database :: get_course_table(TABLE_LP_MAIN);
             $table_item = Database :: get_course_table(TABLE_LP_ITEM);
             $table_view = Database :: get_course_table(TABLE_LP_VIEW);
             $table_iv   = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
-            $table_iv_int = Database :: get_course_table(TABLE_LP_IV_INTERACTION);
+            $table_iv_int = Database::get_course_table(TABLE_LP_IV_INTERACTION);
             $table_tool = Database::get_course_table(TABLE_TOOL_LIST);
-            foreach($this->course->resources[RESOURCE_LEARNPATH] as $id => $learnpath)
-            {
+            
+            foreach($this->course->resources[RESOURCE_LEARNPATH] as $id => $learnpath) {
                 // See task #875.
-                if ($learnpath->lp_type == 2)
-                {
+                if ($learnpath->lp_type == 2) {
                     // This is a learning path of SCORM type.
                     if (trim($learnpath->path) != '')   // A sanity check for avoiding removal of the parent folder scorm/
                                                         // when $learnpath->path value is incorrect for some reason.
@@ -365,34 +362,32 @@ class CourseRecycler
                 }
 
                 //remove links from course homepage
-                $sql = "DELETE FROM $table_tool WHERE link LIKE '%lp_controller.php%lp_id=$id%' AND image='scormbuilder.gif'";
+                $sql = "DELETE FROM $table_tool WHERE c_id = ".$this->course_id."  AND link LIKE '%lp_controller.php%lp_id=$id%' AND image='scormbuilder.gif'";
                 Database::query($sql);
                 //remove elements from lp_* tables (from bottom-up) by removing interactions, then item_view, then views and items, then paths
-                $sql_items = "SELECT id FROM $table_item WHERE lp_id=$id";
+                $sql_items = "SELECT id FROM $table_item WHERE  c_id = ".$this->course_id."  AND lp_id=$id";
                 $res_items = Database::query($sql_items);
-                while ($row_item = Database::fetch_array($res_items))
-                {
+                while ($row_item = Database::fetch_array($res_items)) {
                     //get item views
-                    $sql_iv = "SELECT id FROM $table_iv WHERE lp_item_id=".$row_item['id'];
+                    $sql_iv = "SELECT id FROM $table_iv WHERE  c_id = ".$this->course_id."  AND lp_item_id=".$row_item['id'];
                     $res_iv = Database::query($sql_iv);
-                    while ($row_iv = Database::fetch_array($res_iv))
-                    {
+                    while ($row_iv = Database::fetch_array($res_iv)) {
                         //delete interactions
-                        $sql_iv_int_del = "DELETE FROM $table_iv_int WHERE lp_iv_id = ".$row_iv['id'];
+                        $sql_iv_int_del = "DELETE FROM $table_iv_int WHERE  c_id = ".$this->course_id."  AND lp_iv_id = ".$row_iv['id'];
                         $res_iv_int_del = Database::query($sql_iv_int_del);
                     }
                     //delete item views
-                    $sql_iv_del = "DELETE FROM $table_iv WHERE lp_item_id=".$row_item['id'];
+                    $sql_iv_del = "DELETE FROM $table_iv WHERE c_id = ".$this->course_id."  AND lp_item_id=".$row_item['id'];
                     $res_iv_del = Database::query($sql_iv_del);
                 }
                 //delete items
-                $sql_items_del = "DELETE FROM $table_item WHERE lp_id=$id";
+                $sql_items_del = "DELETE FROM $table_item WHERE c_id = ".$this->course_id."  AND lp_id=$id";
                 $res_items_del = Database::query($sql_items_del);
                 //delete views
-                $sql_views_del = "DELETE FROM $table_view WHERE lp_id=$id";
+                $sql_views_del = "DELETE FROM $table_view WHERE c_id = ".$this->course_id."  AND lp_id=$id";
                 $res_views_del = Database::query($sql_views_del);
                 //delete lps
-                $sql_del = "DELETE FROM $table_main WHERE id = $id";
+                $sql_del = "DELETE FROM $table_main WHERE c_id = ".$this->course_id."  AND id = $id";
                 $res_del = Database::query($sql_del);
             }
         }
@@ -400,13 +395,11 @@ class CourseRecycler
     /**
      * Delete course description
      */
-    function recycle_cours_description()
-    {
-        if ($this->course->has_resources(RESOURCE_COURSEDESCRIPTION))
-        {
+    function recycle_cours_description() {
+        if ($this->course->has_resources(RESOURCE_COURSEDESCRIPTION)) {
             $table = Database :: get_course_table(TABLE_COURSE_DESCRIPTION);
             $ids = implode(',', (array_keys($this->course->resources[RESOURCE_COURSEDESCRIPTION])));
-            $sql = "DELETE FROM ".$table." WHERE id IN(".$ids.")";
+            $sql = "DELETE FROM ".$table." WHERE  c_id = ".$this->course_id."  AND id IN(".$ids.")";
             Database::query($sql);
         }
     }
@@ -415,30 +408,30 @@ class CourseRecycler
     */
     function recycle_thematic($session_id = 0) {
         if ($this->course->has_resources(RESOURCE_THEMATIC)) {
-            $table_thematic         = Database :: get_course_table(TABLE_THEMATIC, $this->course->destination_db);
-            $table_thematic_advance = Database :: get_course_table(TABLE_THEMATIC_ADVANCE, $this->course->destination_db);
-            $table_thematic_plan    = Database :: get_course_table(TABLE_THEMATIC_PLAN, $this->course->destination_db);
-        
+            $table_thematic         = Database :: get_course_table(TABLE_THEMATIC);
+            $table_thematic_advance = Database :: get_course_table(TABLE_THEMATIC_ADVANCE);
+            $table_thematic_plan    = Database :: get_course_table(TABLE_THEMATIC_PLAN);
+        	
             $resources = $this->course->resources;
             foreach ($resources[RESOURCE_THEMATIC] as $last_id => $thematic) {
                 if (is_numeric($last_id)) {
                     
                     foreach($thematic->thematic_advance_list as $thematic_advance) {
-                        $cond = array('id = ?'=>$thematic_advance['id']);
-                        api_item_property_update($this->destination_course_info, 'thematic_advance', $thematic_advance['id'],'ThematicAdvanceDeleted', api_get_user_id());
+                        $cond = array('id = ? AND  c_id = ?'=>array($thematic_advance['id'], $this->course_id));
+                        api_item_property_update($this->course_info, 'thematic_advance', $thematic_advance['id'],'ThematicAdvanceDeleted', api_get_user_id());
                         Database::delete($table_thematic_advance, $cond);
                     }
                     
                     foreach($thematic->thematic_plan_list as $thematic_plan) {
-                        $cond = array('id = ?'=>$thematic_plan['id']);
-                        api_item_property_update($this->destination_course_info, 'thematic_plan', $thematic_advance['id'], 'ThematicPlanDeleted', api_get_user_id());
+                        $cond = array('id = ? AND  c_id = ?'=>array($thematic_plan['id'], $this->course_id));
+                        api_item_property_update($this->course_info, 'thematic_plan', $thematic_advance['id'], 'ThematicPlanDeleted', api_get_user_id());
                         Database::delete($table_thematic_plan, $cond);
                     }
-                    $cond = array('id = ?'=>$last_id);
-                    api_item_property_update($this->destination_course_info, 'thematic', $last_id,'ThematicDeleted', api_get_user_id());
+                    $cond = array('id = ? AND  c_id = ?'=>array($last_id, $this->course_id));
+                    api_item_property_update($this->course_info, 'thematic', $last_id,'ThematicDeleted', api_get_user_id());
                     Database::delete($table_thematic,$cond);
                 }
-            }
+            }            
         }
     }
     

File diff suppressed because it is too large
+ 262 - 221
main/coursecopy/classes/CourseRestorer.class.php


+ 15 - 10
main/coursecopy/classes/CourseSelectForm.class.php

@@ -225,14 +225,12 @@ class CourseSelectForm
 		//Loading the results from the checkboxes of the javascript
 		$resource = $_POST['resource'][RESOURCE_DOCUMENT];
 
-		if (!empty($course_code)) {
-			$course_info = api_get_course_info($course_code);
-			$table_doc = Database :: get_course_table(TABLE_DOCUMENT,$course_info['dbName']);
-			$table_prop = Database :: get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-		} else {
-			$table_doc = Database :: get_course_table(TABLE_DOCUMENT);
-			$table_prop = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-		}
+		$course_info 	= api_get_course_info($course_code);
+		$table_doc 		= Database::get_course_table(TABLE_DOCUMENT);
+		$table_prop 	= Database::get_course_table(TABLE_ITEM_PROPERTY);
+		
+		$course_id 		= $course_info['real_id'];
+		
 
 		// Searching the documents resource that have been set to null because $avoid_serialize is true in the display_form() function
 
@@ -247,13 +245,20 @@ class CourseSelectForm
 						$condition_session = ' AND d.session_id ='.$session_id;
 					}
 
-					$sql = 'SELECT d.id, d.path, d.comment, d.title, d.filetype, d.size  FROM '.$table_doc.' d, '.$table_prop.' p WHERE tool = \''.TOOL_DOCUMENT.'\' AND p.ref = d.id AND p.visibility != 2 AND d.id = '.$resource_item.$condition_session.' ORDER BY path';
+					$sql = 'SELECT d.id, d.path, d.comment, d.title, d.filetype, d.size 
+							FROM '.$table_doc.' d, '.$table_prop.' p 
+							WHERE 	d.c_id = '.$course_id.' AND
+									p.c_id = '.$course_id.' AND
+									tool 	= \''.TOOL_DOCUMENT.'\' AND 
+									p.ref 	= d.id AND p.visibility != 2 AND 
+									d.id 	= '.$resource_item.$condition_session.' 
+							ORDER BY path';
 					$db_result = Database::query($sql);
 					while ($obj = Database::fetch_object($db_result)) {
 						$doc = new Document($obj->id, $obj->path, $obj->comment, $obj->title, $obj->filetype, $obj->size);
 						$course->add_resource($doc);
 						// adding item property
-						$sql = "SELECT * FROM $table_prop WHERE TOOL = '".RESOURCE_DOCUMENT."' AND ref='".$resource_item."'";
+						$sql = "SELECT * FROM $table_prop WHERE c_id = '.$course_id.'  AND TOOL = '".RESOURCE_DOCUMENT."' AND ref='".$resource_item."'";
 						$res = Database::query($sql);
 						$all_properties = array ();
 						while ($item_property = Database::fetch_array($res,'ASSOC')) {

+ 12 - 12
main/create_course/add_course.php

@@ -205,6 +205,7 @@ if (isset($_user['language']) && $_user['language'] != '') {
 $values['tutor_name'] = api_get_person_name($_user['firstName'], $_user['lastName'], null, null, $values['course_language']);
 $form->setDefaults($values);
 
+
 // Validate the form.
 if ($form->validate()) {
     $course_values = $form->exportValues();
@@ -241,20 +242,21 @@ if ($form->validate()) {
             // Create the course immediately.
 
             $keys = define_course_keys($wanted_code, '', $_configuration['db_prefix']);
-
             if (count($keys)) {
-
-                $visual_code = $keys['currentCourseCode'];
-                $code = $keys['currentCourseId'];
-                $db_name = $keys['currentCourseDbName'];
-                $directory = $keys['currentCourseRepository'];
-
+                $visual_code 	= $keys['currentCourseCode'];
+                $code 			= $keys['currentCourseId'];
+                $db_name 		= $keys['currentCourseDbName'];
+                $directory 		= $keys['currentCourseRepository'];
                 $expiration_date = time() + $firstExpirationDelay;
+                
                 prepare_course_repository($directory, $code);
-                update_Db_course($db_name);
+                //update_Db_course($db_name);
                 $pictures_array = fill_course_repository($directory,  $exemplary_content);
-                fill_Db_course($db_name, $directory, $course_language, $pictures_array, $exemplary_content);
-                register_course($code, $visual_code, $directory, $db_name, $tutor_name, $category_code, $title, $course_language, api_get_user_id(), $expiration_date);
+                
+                $course_id = register_course($code, $visual_code, $directory, '', $tutor_name, $category_code, $title, $course_language, api_get_user_id(), $expiration_date);
+                                
+                fill_Db_course($course_id, $directory, $course_language, $pictures_array, $exemplary_content);
+                
 
                 // Preparing a confirmation message.
                 $link = api_get_path(WEB_COURSE_PATH).$directory.'/';
@@ -265,9 +267,7 @@ if ($form->validate()) {
                 echo '<div style="float: right; margin:0px; padding: 0px;">' .
                     '<a class="bottom-link" href="'.api_get_path(WEB_PATH).'user_portal.php">'.get_lang('Enter').'</a>' .
                     '</div>';
-
             } else {
-
                 Display :: display_error_message(get_lang('CourseCreationFailed'), false);
                 // Display the form.
                 $form->display();

+ 2 - 1
main/document/create_document.php

@@ -393,6 +393,7 @@ $folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is
 
 if (!$is_certificate_mode && !is_my_shared_folder($_user['user_id'], $dir, $current_session_id)) {
 	$folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is_allowed_to_edit);
+	
 	//$parent_select -> addOption(get_lang('HomeDirectory'), '/');
 	$parent_select = $form->addElement('select', 'curdirpath', get_lang('DestinationDirectory'));
 	
@@ -501,7 +502,7 @@ $form->setDefaults($default);
 if ($form->validate()) {
 	$values = $form->exportValues();
 	$readonly = isset($values['readonly']) ? 1 : 0;
-
+	
 	$values['title'] = trim($values['title']);	
 	
 	if (!empty($values['curdirpath'])) {

+ 3 - 2
main/document/document.php

@@ -701,8 +701,7 @@ if($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folde
 if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folder(api_get_user_id(), $curdirpath, $session_id)) {
     // Create directory with $_POST data
     if (isset($_POST['create_dir']) && $_POST['dirname'] != '') {
-        // Needed for directory creation
-        require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
+        // Needed for directory creation        
         $post_dir_name = $_POST['dirname'];
 
         if ($post_dir_name == '../' || $post_dir_name == '.' || $post_dir_name == '..') {
@@ -716,9 +715,11 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
             $dir_name = $curdirpath.$added_slash.replace_dangerous_char($post_dir_name);
             $dir_name = disable_dangerous_file($dir_name);
             $dir_check = $base_work_dir.$dir_name;
+        
             
             if (!is_dir($dir_check)) {
                 $created_dir = create_unexisting_directory($_course, api_get_user_id(), api_get_session_id(), $to_group_id, $to_user_id, $base_work_dir, $dir_name, $post_dir_name);
+                
                 if ($created_dir) {
                     Display::display_confirmation_message('<span title="'.$created_dir.'">'.get_lang('DirCr').'</span>', false);
                     // Uncomment if you want to enter the created dir

+ 13 - 9
main/document/downloadfolder.inc.php

@@ -9,16 +9,15 @@
  * Code
  */
 set_time_limit(0);
-
 $document_data = DocumentManager::get_document_data_by_id($_GET['id'], api_get_course_id());
-$path          = $document_data['path']; 
-
+$path          = $document_data['path'];
+ 
+if (empty($path)) {
+	$path = '/';
+}
 if (empty($document_data)) {
-    api_not_allowed();
+    //api_not_allowed();
 }
-if (empty($path)) {
-    $path = '/';
-} 
 
 //a student should not be able to download a root shared directory
 if (($path == '/shared_folder' || $path=='/shared_folder_session_'.api_get_session_id()) && (!api_is_allowed_to_edit() || !api_is_platform_admin())){		
@@ -59,8 +58,13 @@ if (api_is_allowed_to_edit()) {
 	}
 	$querypath = Database::escape_string($querypath);
 	// Search for all files that are not deleted => visibility != 2
-	$sql = "SELECT path FROM $doc_table AS docs,$prop_table AS props  
-			WHERE props.tool='".TOOL_DOCUMENT."' AND docs.id=props.ref AND docs.path LIKE '".$querypath."/%' AND docs.filetype='file' AND props.visibility<>'2' AND props.to_group_id=".$to_group_id."";
+	$sql = "SELECT path FROM $doc_table AS docs, $prop_table AS props  
+			WHERE 	props.tool='".TOOL_DOCUMENT."' AND 
+					docs.id				= props.ref 	AND 
+					docs.path 			LIKE '".$querypath."/%' AND 
+					docs.filetype		= 'file' AND props.visibility<>'2' AND 
+					props.to_group_id	= ".$to_group_id." AND 
+					docs.c_id 			= ".api_get_course_int_id()." ";
 	$query = Database::query($sql);
 	// Add tem to the zip file
 	while ($not_deleted_file = Database::fetch_assoc($query)) {

+ 41 - 30
main/dropbox/dropbox_class.inc.php

@@ -104,12 +104,13 @@ class Dropbox_Work {
 		$this->description = $description;
 		$this->author = api_get_person_name($_user['firstName'], $_user['lastName']);
 		$this->last_upload_date = api_get_utc_datetime();
+		
+		$course_id = api_get_course_int_id();
 
 		// Check if object exists already. If it does, the old object is used
 		// with updated information (authors, descriptio, upload_date)
 		$this->isOldWork = false;
-		$sql = "SELECT id, upload_date
-				FROM ".$dropbox_cnf['tbl_file']."
+		$sql = "SELECT id, upload_date FROM ".$dropbox_cnf['tbl_file']."
 				WHERE filename = '".Database::escape_string($this->filename)."'";
         $result = Database::query($sql);
 		$res = Database::fetch_array($result);
@@ -120,19 +121,19 @@ class Dropbox_Work {
 		if ($this->isOldWork) {
 			$this->id = $res['id'];
 			$this->upload_date = $res['upload_date'];
-		    $sql = "UPDATE ".$dropbox_cnf["tbl_file"]."
-					SET filesize = '".Database::escape_string($this->filesize)."'
-					, title = '".Database::escape_string($this->title)."'
-					, description = '".Database::escape_string($this->description)."'
-					, author = '".Database::escape_string($this->author)."'
-					, last_upload_date = '".Database::escape_string($this->last_upload_date)."'
+		    $sql = "UPDATE ".$dropbox_cnf["tbl_file"]." SET 
+					filesize			= '".Database::escape_string($this->filesize)."' , 
+					title 				= '".Database::escape_string($this->title)."', 
+					description 		= '".Database::escape_string($this->description)."', 
+					author 				= '".Database::escape_string($this->author)."',
+					last_upload_date 	= '".Database::escape_string($this->last_upload_date)."'
 					WHERE id='".Database::escape_string($this->id)."'";
 			$result = Database::query($sql);
 		} else {
 			$this->upload_date = $this->last_upload_date;
-			$sql = "INSERT INTO ".$dropbox_cnf['tbl_file']."
-				(uploader_id, filename, filesize, title, description, author, upload_date, last_upload_date, session_id)
-				VALUES ('".Database::escape_string($this->uploader_id)."'
+			$sql = "INSERT INTO ".$dropbox_cnf['tbl_file']." (c_id, uploader_id, filename, filesize, title, description, author, upload_date, last_upload_date, session_id)
+				VALUES ( $course_id, 
+						'".Database::escape_string($this->uploader_id)."'
 						, '".Database::escape_string($this->filename)."'
 						, '".Database::escape_string($this->filesize)."'
 						, '".Database::escape_string($this->title)."'
@@ -148,9 +149,9 @@ class Dropbox_Work {
 		}
 
 		// Insert entries into person table
-		$sql = "INSERT INTO ".$dropbox_cnf['tbl_person']."
-				(file_id, user_id)
-				VALUES ('".Database::escape_string($this->id)."'
+		$sql = "INSERT INTO ".$dropbox_cnf['tbl_person']." (c_id, file_id, user_id)
+				VALUES ($course_id, 
+						'".Database::escape_string($this->id)."'
 						, '".Database::escape_string($this->uploader_id)."'
 						)";
         $result = Database::query($sql);	//if work already exists no error is generated
@@ -261,6 +262,8 @@ class Dropbox_SentWork extends Dropbox_Work
 		global $dropbox_cnf;
 		// Call constructor of Dropbox_Work object
 		$this->Dropbox_Work($uploader_id, $title, $description, $author, $filename, $filesize);
+		
+		$course_id = api_get_course_int_id();
 
 		// Do sanity checks on recipient_ids array & property fillin
 		// The sanity check for ex-coursemembers is already done in base constructor
@@ -286,13 +289,13 @@ class Dropbox_SentWork extends Dropbox_Work
 
 		// Insert data in dropbox_post and dropbox_person table for each recipient
 		foreach ($this->recipients as $rec) {
-			$sql = "INSERT INTO ".$dropbox_cnf['tbl_post']." (file_id, dest_user_id, session_id)
-				VALUES ('".Database::escape_string($this->id)."', '".Database::escape_string($rec['id'])."', ".intval($_SESSION['id_session']).")";
+			$sql = "INSERT INTO ".$dropbox_cnf['tbl_post']." (c_id, file_id, dest_user_id, session_id) VALUES 
+					($course_id, '".Database::escape_string($this->id)."', '".Database::escape_string($rec['id'])."', ".intval($_SESSION['id_session']).")";
 	        $result = Database::query($sql);	// If work already exists no error is generated
 
 			// Insert entries into person table
-			$sql = "INSERT INTO ".$dropbox_cnf['tbl_person']." (file_id, user_id)
-				    VALUES ('".Database::escape_string($this->id)."', '".Database::escape_string($rec['id'])."')";
+			$sql = "INSERT INTO ".$dropbox_cnf['tbl_person']." (c_id, file_id, user_id)
+				    VALUES ($course_id, '".Database::escape_string($this->id)."', '".Database::escape_string($rec['id'])."')";
 
         	// Do not add recipient in person table if mailing zip or just upload.
 			if (!$justSubmit) {
@@ -377,16 +380,20 @@ class Dropbox_Person
 
 		$session_id = api_get_session_id();
 		$condition_session = api_get_session_condition($session_id);
-
+		$course_id = api_get_course_int_id();
+		
 		$post_tbl = Database::get_course_table(TABLE_DROPBOX_POST);
 		$person_tbl = Database::get_course_table(TABLE_DROPBOX_PERSON);
 		$file_tbl = Database::get_course_table(TABLE_DROPBOX_FILE);
 		// Find all entries where this person is the recipient
-		$sql = "SELECT r.file_id, r.cat_id
-				FROM $post_tbl r, $person_tbl p
-				WHERE r.dest_user_id = '".Database::escape_string($this->userId)."'
-					AND r.dest_user_id = p.user_id
-					AND r.file_id = p.file_id $condition_session";
+		 $sql = "SELECT r.file_id, r.cat_id FROM $post_tbl r, $person_tbl p
+				WHERE 
+					r.dest_user_id 	= '".Database::escape_string($this->userId)."' AND 
+					r.dest_user_id 	= p.user_id AND 
+		 			r.file_id 		= p.file_id $condition_session AND
+		 			r.c_id = $course_id AND
+		 			p.c_id = $course_id
+		 			";
 
 		//if (intval($_SESSION['id_session']>0)) { $sql .= " AND r.session_id = ".intval($_SESSION['id_session']); }
 
@@ -400,9 +407,13 @@ class Dropbox_Person
 		// Find all entries where this person is the sender/uploader
 		$sql = "SELECT f.id
 				FROM $file_tbl f, $person_tbl p
-				WHERE f.uploader_id = '".Database::escape_string($this->userId)."'
-				AND f.uploader_id = p.user_id
-				AND f.id = p.file_id $condition_session";
+				WHERE 
+				f.uploader_id 	= '".Database::escape_string($this->userId)."' AND 
+				f.uploader_id 	= p.user_id AND 
+				f.id 			= p.file_id $condition_session AND
+				f.c_id 			= $course_id AND
+		 		p.c_id 			= $course_id				 
+		";
 
 		//if(intval($_SESSION['id_session']>0)) { $sql .= " AND f.session_id = ".intval($_SESSION['id_session']); }
 
@@ -522,11 +533,11 @@ class Dropbox_Person
 	function deleteReceivedWorkFolder($id) {
 		global $dropbox_cnf;
 		$id = intval($id);
-		$sql = "DELETE FROM ".$dropbox_cnf['tbl_file']." where cat_id = '".$id."' ";
+		$sql = "DELETE FROM ".$dropbox_cnf['tbl_file']." WHERE cat_id = '".$id."' ";
 		if (!Database::query($sql)) return false;
-		$sql = "DELETE FROM ".$dropbox_cnf['tbl_category']." where cat_id = '".$id."' ";
+		$sql = "DELETE FROM ".$dropbox_cnf['tbl_category']." WHERE cat_id = '".$id."' ";
 		if (!Database::query($sql)) return false;
-		$sql = "DELETE FROM ".$dropbox_cnf['tbl_post']." where cat_id = '".$id."' ";
+		$sql = "DELETE FROM ".$dropbox_cnf['tbl_post']." WHERE cat_id = '".$id."' ";
 		if (!Database::query($sql)) return false;
 		return true;
 	}

+ 12 - 9
main/dropbox/dropbox_functions.inc.php

@@ -331,6 +331,8 @@ function store_addcategory() {
 	if ($_POST['category_name'] == '') {
 		return array('type' => 'error', 'message' => get_lang('ErrorPleaseGiveCategoryName'));
 	}
+	
+	$course_id = api_get_course_int_id();
 
 	if (!$_POST['edit_id']) {
 		$session_id = api_get_session_id();
@@ -340,8 +342,8 @@ function store_addcategory() {
 
 		// step 3b, we add the category if it does not exist yet.
 		if (Database::num_rows($result) == 0) {
-			$sql = "INSERT INTO ".$dropbox_cnf['tbl_category']." (cat_name, received, sent, user_id, session_id)
-					VALUES ('".Database::escape_string($_POST['category_name'])."', '".Database::escape_string($received)."', '".Database::escape_string($sent)."', '".Database::escape_string($_user['user_id'])."',$session_id)";
+			$sql = "INSERT INTO ".$dropbox_cnf['tbl_category']." (c_id, cat_name, received, sent, user_id, session_id)
+					VALUES ($course_id, '".Database::escape_string($_POST['category_name'])."', '".Database::escape_string($received)."', '".Database::escape_string($sent)."', '".Database::escape_string($_user['user_id'])."',$session_id)";
 			Database::query($sql);
 			return array('type' => 'confirmation', 'message' => get_lang('CategoryStored'));
 		} else {
@@ -997,17 +999,16 @@ function feedback_form() {
 * @version march 2006
 */
 function store_feedback() {
-	global $dropbox_cnf;	
-
+	global $dropbox_cnf;
 	if (!is_numeric($_GET['id'])) {
 		return get_lang('FeedbackError');
 	}
-
+	$course_id = api_get_course_int_id();
 	if (empty($_POST['feedback'])) {
 		return get_lang('PleaseTypeText');
 	} else {
-		$sql="INSERT INTO ".$dropbox_cnf['tbl_feedback']." (file_id, author_user_id, feedback, feedback_date) VALUES
-				('".intval($_GET['id'])."','".api_get_user_id()."','".Database::escape_string($_POST['feedback'])."', '".api_get_utc_datetime()."')";
+		$sql="INSERT INTO ".$dropbox_cnf['tbl_feedback']." (c_id, file_id, author_user_id, feedback, feedback_date) VALUES
+			  ($course_id, '".intval($_GET['id'])."','".api_get_user_id()."','".Database::escape_string($_POST['feedback'])."', '".api_get_utc_datetime()."')";
 		Database::query($sql);
 		return get_lang('DropboxFeedbackStored');
 	}
@@ -1158,8 +1159,10 @@ function generate_html_overview($files, $dont_show_columns = array(), $make_link
 */
 function get_total_number_feedback($file_id = '') {
 	global $dropbox_cnf;
-	$sql = "SELECT COUNT(feedback_id) AS total, file_id FROM ".$dropbox_cnf['tbl_feedback']." GROUP BY file_id";
-	$result=Database::query($sql);
+	$course_id = api_get_course_int_id();
+	$sql = "SELECT COUNT(feedback_id) AS total, file_id FROM ".$dropbox_cnf['tbl_feedback']." 
+			WHERE c_id = $course_id GROUP BY file_id";
+	$result = Database::query($sql);
 	while ($row=Database::fetch_array($result)) {
 		$return[$row['file_id']] = $row['total'];
 	}

+ 1 - 1
main/exercice/addlimits.php

@@ -183,7 +183,7 @@ if (isset($_POST['ok'])) {
 	$exercise_id = Database::escape_string($_POST['exe_id']);
 	if ($_POST['limit']==1) {
 		$minutes = Database::escape_string($_POST['minutes']);
-		$query = "UPDATE ".$TBL_EXERCICES." SET ques_time_limit= $minutes where id= $exercise_id";
+		$query = "UPDATE ".$TBL_EXERCICES." SET ques_time_limit= $minutes WHERE id= $exercise_id";
 		Database::query($query);
 	} else {
 		$query = "UPDATE ".$TBL_EXERCICES." SET ques_time_limit= 0 WHERE id= $exercise_id";

+ 5 - 8
main/exercice/admin.php

@@ -475,22 +475,19 @@ if (isset($_GET['message'])) {
 
 if ($newQuestion || $editQuestion) {
 	// statement management
-	$type = $_REQUEST['answerType'];    
-	?><input type="hidden" name="Type" value="<?php echo $type; ?>" />
-	<?php	
-   require 'question_admin.inc.php';
+	$type = Security::remove_XSS($_REQUEST['answerType']);
+	echo '<input type="hidden" name="Type" value="'.$type.'" />';	
+	require 'question_admin.inc.php';
 }
  
-if (isset($_GET['hotspotadmin'])) {
-    
+if (isset($_GET['hotspotadmin'])) {    
     if (!is_object($objQuestion)) {
         $objQuestion = Question :: read($_GET['hotspotadmin']);
     }
     if (!$objQuestion) {
         api_not_allowed();
     }    
-	require 'hotspot_admin.inc.php';
-}
+	require 'hotspot_admin.inc.php';}
 if (!$newQuestion && !$modifyQuestion && !$editQuestion && !isset($_GET['hotspotadmin'])) {
 	// question list management
 	require 'question_list_admin.inc.php';

+ 10 - 12
main/exercice/answer.class.php

@@ -151,7 +151,7 @@ class Answer {
 		$TBL_QUIZ= Database::get_course_table(TABLE_QUIZ_QUESTION, $this->course['db_name']);
 		$questionId=intval($this->questionId);
 		
-		$sql = "SELECT type FROM $TBL_QUIZ where id = $questionId";
+		$sql = "SELECT type FROM $TBL_QUIZ WHERE id = $questionId";
 		$result_question=Database::query($sql);
 		$question_type=Database::fetch_array($result_question);
 		$remove_doubt_answer = ''; //
@@ -484,15 +484,12 @@ class Answer {
 		$questionId=$this->questionId;
 
 		// removes old answers before inserting of new ones
-		$sql="DELETE FROM $TBL_REPONSES WHERE question_id='".Database::escape_string($questionId)."'";
+		$sql = "DELETE FROM $TBL_REPONSES WHERE question_id='".Database::escape_string($questionId)."'";
 		Database::query($sql);
-
+		$c_id = $this->course['real_id'];
 		// inserts new answers into data base
-		$sql="INSERT INTO $TBL_REPONSES" .
-				"(id,question_id,answer,correct,comment," .
-				"ponderation,position,hotspot_coordinates,hotspot_type,destination) VALUES";
-
-		for($i=1;$i <= $this->new_nbrAnswers;$i++) {
+		$sql = "INSERT INTO $TBL_REPONSES (c_id, id, question_id, answer,correct,comment, ponderation,position,hotspot_coordinates,hotspot_type,destination) VALUES ";
+		for ($i=1;$i <= $this->new_nbrAnswers;$i++) {
 			$answer					= Database::escape_string($this->new_answer[$i]);
 			$correct				= Database::escape_string($this->new_correct[$i]);
 			$comment				= Database::escape_string($this->new_comment[$i]);
@@ -502,8 +499,7 @@ class Answer {
 			$hotspot_type			= Database::escape_string($this->new_hotspot_type[$i]);
 			$destination			= Database::escape_string($this->new_destination[$i]);
 
-			$sql.="('$i','$questionId','$answer','$correct','$comment',
-					'$weighting','$position','$hotspot_coordinates','$hotspot_type','$destination'),";
+			$sql.="($c_id, '$i','$questionId','$answer','$correct','$comment','$weighting','$position','$hotspot_coordinates','$hotspot_type','$destination'),";
 		}
 		$sql = api_substr($sql,0,-1);
 		Database::query($sql);
@@ -567,7 +563,9 @@ class Answer {
 		// if at least one answer
 		if ($this->nbrAnswers) {
 			// inserts new answers into data base
-			$sql="INSERT INTO $TBL_REPONSES (id,question_id,answer,correct,comment, ponderation,position,hotspot_coordinates,hotspot_type,destination) VALUES";
+			$sql="INSERT INTO $TBL_REPONSES (c_id, id,question_id,answer,correct,comment, ponderation,position,hotspot_coordinates,hotspot_type,destination) VALUES";
+			$c_id = $course_info['real_id'];
+			
 			for($i=1;$i <= $this->nbrAnswers;$i++) {
                 if ($course_info['db_name'] != $this->course['db_name']) {                    
                 	$this->answer[$i]  = DocumentManager::replace_urls_inside_content_html_from_copy_course($this->answer[$i],$this->course['id'], $course_info['id']) ;
@@ -587,7 +585,7 @@ class Answer {
 				$hotspot_coordinates	= Database::escape_string($this->hotspot_coordinates[$i]);
 				$hotspot_type			= Database::escape_string($this->hotspot_type[$i]);
 				$destination			= Database::escape_string($this->destination[$i]);
-				$sql.="('$i','$newQuestionId','$answer','$correct','$comment'," .
+				$sql.="($c_id, '$i','$newQuestionId','$answer','$correct','$comment'," .
 						"'$weighting','$position','$hotspot_coordinates','$hotspot_type','$destination'),";
 			}
 

+ 1 - 1
main/exercice/answer_admin.inc.php

@@ -1128,7 +1128,7 @@ if($modifyAnswers)
 			?>
 			<h3>
 			<?php echo $questionName;?></h3><?php
-			$sql = "select description from ".$TBL_QUESTIONS." where id = '".Database::escape_string($questionId)."'";
+			$sql = "select description from ".$TBL_QUESTIONS." WHERE id = '".Database::escape_string($questionId)."'";
 			$res = Database::query($sql,_FILE_,_LINE_);
 			?>
 			&nbsp; &nbsp; &nbsp;

+ 1 - 1
main/exercice/exercice.php

@@ -202,7 +202,7 @@ if ($show == 'result' && $_REQUEST['comments'] == 'update' && ($is_allowedToEdit
 		Database::query($recording_changes);
 	}
 	
-	$qry = 'SELECT DISTINCT question_id, marks FROM ' . $TBL_TRACK_ATTEMPT . ' where exe_id = '.$id .' GROUP BY question_id';
+	$qry = 'SELECT DISTINCT question_id, marks FROM ' . $TBL_TRACK_ATTEMPT . ' WHERE exe_id = '.$id .' GROUP BY question_id';
 	$res = Database::query($qry);
 	$tot = 0;
 	while ($row = Database :: fetch_array($res, 'ASSOC')) {

+ 20 - 19
main/exercice/exercise.class.php

@@ -121,7 +121,12 @@ class Exercise {
 			}
 			$this->expired_time 	= $object->expired_time; //control time
 
-			$sql="SELECT question_id, question_order FROM $TBL_EXERCICE_QUESTION, $TBL_QUESTIONS WHERE question_id=id AND exercice_id='".Database::escape_string($id)."' ORDER BY question_order";
+			$sql = "SELECT e.question_id, e.question_order FROM $TBL_EXERCICE_QUESTION e, $TBL_QUESTIONS  q
+					WHERE 	e.question_id	= q.id AND 
+							e.exercice_id	= '".Database::escape_string($id)."' AND
+							e.c_id = ".api_get_course_int_id()." AND
+							q.c_id = ".api_get_course_int_id()." 														 
+					ORDER BY question_order";
 				
 			$result = Database::query($sql);
 
@@ -288,7 +293,12 @@ class Exercise {
 			$TBL_EXERCICE_QUESTION  = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION, $this->course['db_name']);
 			$TBL_QUESTIONS          = Database::get_course_table(TABLE_QUIZ_QUESTION, $this->course['db_name']);
 
-			$sql="SELECT question_id, question_order FROM $TBL_EXERCICE_QUESTION, $TBL_QUESTIONS WHERE question_id = id AND exercice_id='".$this->id."' ORDER BY question_order";
+			$sql = "SELECT question_id, question_order FROM $TBL_EXERCICE_QUESTION eq , $TBL_QUESTIONS q 
+					WHERE 	eq.question_id = q.id AND 
+							exercice_id='".$this->id."' AND
+							eq.c_id = {$this->course['real_id']} AND
+							q.c_id = {$this->course['real_id']}
+					ORDER BY question_order";			
 			$result = Database::query($sql);
 			$question_list = array();
 			while ($new_object = Database::fetch_object($result)) {
@@ -438,16 +448,6 @@ class Exercise {
 					 ." ('".str_replace($documentPath,'',$audioPath).'/'.$this->sound."','file')";
 					Database::query($query);*/
 					$id = add_document($this->course,str_replace($documentPath,'',$audioPath).'/'.$this->sound,'file',$sound['size'],$sound['name']);
-						
-					//$id = Database::insert_id();
-					//$time = time();
-					//$time = date("Y-m-d H:i:s", $time);
-					// insert into the item_property table, using default visibility of "visible"
-					/*$query = "INSERT INTO $TBL_ITEM_PROPERTY "
-					 ."(tool, ref, insert_user_id,to_group_id, insert_date, lastedit_date, lastedit_type) "
-					." VALUES "
-					."('".TOOL_DOCUMENT."', $id, $_user['user_id'], 0, '$time', '$time', 'DocumentAdded' )";
-					Database::query($query);*/
 					api_item_property_update($this->course, TOOL_DOCUMENT, $id, 'DocumentAdded',api_get_user_id());
 					item_property_update_on_folder($this->course,str_replace($documentPath,'',$audioPath),api_get_user_id());
 				}
@@ -588,8 +588,9 @@ class Exercise {
 			}
 		} else {
 			// creates a new exercise
-			$sql="INSERT INTO $TBL_EXERCICES (start_time, end_time, title, description, sound, type, random, random_answers,active, results_disabled, max_attempt, feedback_type, expired_time, session_id)
+			$sql="INSERT INTO $TBL_EXERCICES (c_id, start_time, end_time, title, description, sound, type, random, random_answers,active, results_disabled, max_attempt, feedback_type, expired_time, session_id)
 					VALUES(
+						".api_get_course_int_id().",
 						'$start_time','$end_time',
 						'".Database::escape_string($exercise)."',
 						'".Database::escape_string($description)."',
@@ -1803,8 +1804,8 @@ class Exercise {
 		$table_ans              = Database::get_course_table(TABLE_QUIZ_ANSWER);
 
 		// Creates a temporary Question object
-		$objQuestionTmp         = Question::read($questionId);
-
+		$objQuestionTmp         = Question::read($questionId, api_get_course_int_id());
+		
 		$questionName 			= $objQuestionTmp->selectTitle();
 		$questionDescription 	= $objQuestionTmp->selectDescription();
 		$questionWeighting 		= $objQuestionTmp->selectWeighting();
@@ -1874,7 +1875,7 @@ class Exercise {
 				case UNIQUE_ANSWER :
 				case UNIQUE_ANSWER_NO_OPTION :
 					if ($from_database) {
-						$queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".$exeId."' and question_id= '".$questionId."'";
+						$queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' and question_id= '".$questionId."'";
 						$resultans = Database::query($queryans);
 						$choice = Database::result($resultans,0,"answer");
 
@@ -2259,7 +2260,7 @@ class Exercise {
 						
 						if ($show_result) {
 							$TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
-							$query = "SELECT hotspot_correct FROM ".$TBL_TRACK_HOTSPOT." where hotspot_exe_id = '".$exeId."' and hotspot_question_id= '".$questionId."' AND hotspot_answer_id='".Database::escape_string($answerId)."'";
+							$query = "SELECT hotspot_correct FROM ".$TBL_TRACK_HOTSPOT." WHERE hotspot_exe_id = '".$exeId."' and hotspot_question_id= '".$questionId."' AND hotspot_answer_id='".Database::escape_string($answerId)."'";
 							$resq = Database::query($query);
 							$studentChoice = Database::result($resq,0,"hotspot_correct");							
 						}
@@ -2731,7 +2732,7 @@ class Exercise {
 		// destruction of Answer
 
 		if (!$saved_results && $answerType == HOT_SPOT) {
-			$queryfree      = "SELECT marks FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($exeId)."' and question_id= '".Database::escape_string($questionId)."'";
+			$queryfree      = "SELECT marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".Database::escape_string($exeId)."' and question_id= '".Database::escape_string($questionId)."'";
 			$resfree        = Database::query($queryfree);
 			$questionScore  = Database::result($resfree,0,"marks");
 		}
@@ -3298,7 +3299,7 @@ class Exercise {
 		// 4. We check if the student have attempts
 		if ($is_visible) {
 			if ($this->selectAttempts()) {
-				$attempt_count = get_attempt_count(api_get_user_id(), $this->id, $lp_id, $lp_item_id, $lp_item_view_id);
+				$attempt_count = get_attempt_count_not_finished(api_get_user_id(), $this->id, $lp_id, $lp_item_id, $lp_item_view_id);
 				if ($attempt_count >= $this->selectAttempts()) {
 					//Display :: display_warning_message(sprintf(get_lang('ReachedMaxAttempts'), $exerciseTitle, $objExercise->selectAttempts()), false);
 					$is_visible = false;

+ 1 - 1
main/exercice/exercise_show.php

@@ -448,7 +448,7 @@ foreach ($questionList as $questionId) {
         		}
         		
         		//showing the score	
-         		$queryfree = "select marks from ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
+         		$queryfree = "select marks from ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".Database::escape_string($id)."' and question_id= '".Database::escape_string($questionId)."'";
         		$resfree = Database::query($queryfree);
         		$questionScore= Database::result($resfree,0,"marks");
         		$totalScore+=$questionScore;        		

+ 1 - 1
main/exercice/mark_free_answer.php

@@ -147,7 +147,7 @@ if ($action == 'mark') {
 			#	{
 			#		$user_id = '0';
 			#	}
-			#	$sql2 = "update $tbl_learnpath_user set score='$score' where (user_id=$user_id and learnpath_id='$learnpath_id' and learnpath_item_id='$learnpath_item_id')";
+			#	$sql2 = "update $tbl_learnpath_user set score='$score' WHERE (user_id=$user_id and learnpath_id='$learnpath_id' and learnpath_item_id='$learnpath_item_id')";
 			#	$res2 = Database::query($sql2);
 			#}
 			$res = Database::query($sql);

+ 1 - 1
main/exercice/overview.php

@@ -91,7 +91,7 @@ if (!empty($attempt_list)) {
 $html .= $message;
 $exercise_url_button = Display::url($label, $exercise_url, array('class'=>'a_button blue bigger round'));
 
-if (!$objExercise->is_visible()) {
+if (!$objExercise->is_visible($learnpath_id, $learnpath_item_id)) {
 	$exercise_url = api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidreq().'&show=result&exerciseId='.$objExercise->id;
 	$exercise_url_button = Display::url(get_lang('SeeResults'), $exercise_url, array('class'=>'a_button white bigger round no_link'));
 }

+ 37 - 31
main/exercice/question.class.php

@@ -71,7 +71,7 @@ abstract class Question
 	 *
 	 * @author - Olivier Brouckaert
 	 */
-	function Question() {
+	public function Question() {
 		$this->id=0;
 		$this->question='';
 		$this->description='';
@@ -81,6 +81,7 @@ abstract class Question
 		$this->level = 1;
         $this->extra='';
 		$this->exerciseList=array();
+		$this->course = api_get_course_info();
 	}
 
 	public function getIsContent() {
@@ -573,16 +574,17 @@ abstract class Question
 		$TBL_EXERCICE_QUESTION	= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION, $this->course['db_name']);
 		$TBL_QUESTIONS			= Database::get_course_table(TABLE_QUIZ_QUESTION, $this->course['db_name']);
 
-		$id=$this->id;
-		$question=$this->question;
-		$description=$this->description;
-		$weighting=$this->weighting;
-		$position=$this->position;
-		$type=$this->type;
-		$picture=$this->picture;
-		$level=$this->level;
-        $extra=$this->extra;
-
+		$id				= $this->id;
+		$question		= $this->question;
+		$description	= $this->description;
+		$weighting		= $this->weighting;
+		$position		= $this->position;
+		$type			= $this->type;
+		$picture		= $this->picture;
+		$level			= $this->level;
+        $extra			= $this->extra;
+        $c_id 			= $this->course['real_id'];
+        
 		// question already exists
 		if(!empty($id)) {
 			$sql="UPDATE $TBL_QUESTIONS SET
@@ -596,8 +598,8 @@ abstract class Question
 					level		='".Database::escape_string($level)."'
 				WHERE id='".Database::escape_string($id)."'";
 			Database::query($sql);
-			if(!empty($exerciseId)) {
-			api_item_property_update($this->course, TOOL_QUIZ, $id,'QuizQuestionUpdated',api_get_user_id);
+			if (!empty($exerciseId)) {
+				api_item_property_update($this->course, TOOL_QUIZ, $id,'QuizQuestionUpdated',api_get_user_id);
 			}
             if (api_get_setting('search_enabled')=='true') {
                 if ($exerciseId != 0) {
@@ -612,13 +614,19 @@ abstract class Question
 
 		} else {
 			// creates a new question
-			$sql="SELECT max(position) FROM $TBL_QUESTIONS as question, $TBL_EXERCICE_QUESTION as test_question WHERE question.id=test_question.question_id AND test_question.exercice_id='".Database::escape_string($exerciseId)."'";
-			$result=Database::query($sql);
-			$current_position=Database::result($result,0,0);
-			$this -> updatePosition($current_position+1);
-			$position = $this -> position;
-
-			$sql="INSERT INTO $TBL_QUESTIONS(question,description,ponderation,position,type,picture,extra, level) VALUES(
+			$sql	= "SELECT max(position) FROM $TBL_QUESTIONS as question, $TBL_EXERCICE_QUESTION as test_question 
+					   WHERE 	question.id					= test_question.question_id AND 
+								test_question.exercice_id	= '".Database::escape_string($exerciseId)."' AND
+								question.c_id 				= $c_id AND
+								test_question.c_id 			= $c_id
+								
+						";
+			$result	= Database::query($sql);
+			$current_position = Database::result($result,0,0);
+			$this->updatePosition($current_position+1);
+			$position = $this->position;
+			$sql = "INSERT INTO $TBL_QUESTIONS (c_id, question, description, ponderation, position, type, picture, extra, level) VALUES ( 
+					$c_id,
 					'".Database::escape_string($question)."',
 					'".Database::escape_string($description)."',
 					'".Database::escape_string($weighting)."',
@@ -627,29 +635,26 @@ abstract class Question
 					'".Database::escape_string($picture)."',
 					'".Database::escape_string($extra)."',
                     '".Database::escape_string($level)."'
-					)";
+					)";			
 			Database::query($sql);
 
-			$this->id=Database::insert_id();
+			$this->id = Database::insert_id();
 
 			api_item_property_update($this->course, TOOL_QUIZ, $this->id,'QuizQuestionAdded',api_get_user_id());
 
 			// If hotspot, create first answer
 			if ($type == HOT_SPOT || $type == HOT_SPOT_ORDER) {
 				$TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER);
-				$sql="INSERT INTO $TBL_ANSWERS (id , question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type ) VALUES ('1', '".Database::escape_string($this->id)."', '', NULL , '', '10' , '1', '0;0|0|0', 'square')";
+				$sql = "INSERT INTO $TBL_ANSWERS (c_id, id, question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type ) 
+					    VALUES (".$c_id.", '1', '".Database::escape_string($this->id)."', '', NULL , '', '10' , '1', '0;0|0|0', 'square')";
 				Database::query($sql);
             }
             
 			if ($type == HOT_SPOT_DELINEATION ) {
 				$TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER);
-				$sql="INSERT INTO $TBL_ANSWERS (id , question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type ) VALUES ('1', '".Database::escape_string($this->id)."', '', NULL , '', '10' , '1', '0;0|0|0', 'delineation')";
-				api_sql_query($sql,__FILE__,__LINE__);
-				
-				//$TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER);
-				//$sql="INSERT INTO $TBL_ANSWERS (`id` , `question_id` , `answer` , `correct` , `comment` , `ponderation` , `position` , `hotspot_coordinates` , `hotspot_type` ) VALUES ('2', '".Database::escape_string($this->id)."', '', NULL , '', NULL , '1', '0;0|0|0', 'noerror')";
-				//api_sql_query($sql,__FILE__,__LINE__);		
-				
+				$sql="INSERT INTO $TBL_ANSWERS (c_id, id, question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type ) 
+					  VALUES (".$c_id.", '1', '".Database::escape_string($this->id)."', '', NULL , '', '10' , '1', '0;0|0|0', 'delineation')";
+				Database::query($sql);
 			}
 			
 
@@ -802,7 +807,8 @@ abstract class Question
             $new_exercise->read($exerciseId);
             $count = $new_exercise->selectNbrQuestions();
             $count++;
-			$sql="INSERT INTO $TBL_EXERCICE_QUESTION (question_id, exercice_id, question_order) VALUES ('".Database::escape_string($id)."','".Database::escape_string($exerciseId)."', '$count' )";
+			$sql="INSERT INTO $TBL_EXERCICE_QUESTION (c_id, question_id, exercice_id, question_order) VALUES 
+				 ({$this->course['real_id']}, '".Database::escape_string($id)."','".Database::escape_string($exerciseId)."', '$count' )";
 			Database::query($sql);
             
             // we do not want to reindex if we had just saved adnd indexed the question

+ 2 - 2
main/exercice/result.php

@@ -114,7 +114,7 @@ $counter = 1;
 if (!empty($question_list)) {
 
 	foreach ($question_list as $question_item) {
-    	$objQuestionTmp     = Question::read($question_item['question_id']);
+    	$objQuestionTmp     = Question::read($question_item['question_id'], api_get_course_int_id());
     	$total_weighting   += $objQuestionTmp->selectWeighting();        
 	}
 
@@ -124,7 +124,7 @@ if (!empty($question_list)) {
 			
 		// creates a temporary Question object
 		$questionId 		= $question_item['question_id'];
-		$objQuestionTmp 	= Question::read($questionId);
+		$objQuestionTmp 	= Question::read($questionId, api_get_course_int_id());		
 		
 		$questionName		= $objQuestionTmp->selectTitle();
 		$questionDescription= $objQuestionTmp->selectDescription();

+ 122 - 90
main/forum/forumfunction.inc.php

@@ -487,7 +487,8 @@ function store_forumcategory($values) {
         api_item_property_update(api_get_course_info(), TOOL_FORUM_CATEGORY, $values['forum_category_id'], 'ForumCategoryUpdated', api_get_user_id());
         $return_message = get_lang('ForumCategoryEdited');
     } else {
-        $sql = "INSERT INTO ".$table_categories." (cat_title, cat_comment, cat_order, session_id) VALUES ('".$clean_cat_title."','".Database::escape_string($values['forum_category_comment'])."','".Database::escape_string($new_max)."','".Database::escape_string($session_id)."')";
+        $sql = "INSERT INTO ".$table_categories." (c_id, cat_title, cat_comment, cat_order, session_id) 
+        		VALUES (".api_get_course_int_id().", '".$clean_cat_title."','".Database::escape_string($values['forum_category_comment'])."','".Database::escape_string($new_max)."','".Database::escape_string($session_id)."')";
         Database::query($sql);
         $last_id = Database::insert_id();
         if ($last_id > 0) {
@@ -605,9 +606,10 @@ function store_forum($values) {
         }
         $b = $values['forum_comment'];
 
-        $sql = "INSERT INTO ".$table_forums."
-            (forum_title, forum_image, forum_comment, forum_category, allow_anonymous, allow_edit, approval_direct_post, allow_attachments, allow_new_threads, default_view, forum_of_group, forum_group_public_private, forum_order, session_id)
-            VALUES ('".$clean_title."',
+        $sql = "INSERT INTO ".$table_forums." (c_id, forum_title, forum_image, forum_comment, forum_category, allow_anonymous, allow_edit, approval_direct_post, allow_attachments, allow_new_threads, default_view, forum_of_group, forum_group_public_private, forum_order, session_id)
+            VALUES (
+            	".api_get_course_int_id().",
+            	'".$clean_title."',
                 ".$sql_image."
                 '".Database::escape_string(stripslashes(isset($values['forum_comment'])?$values['forum_comment']:null))."',
                 '".Database::escape_string(stripslashes(isset($values['forum_category'])?$values['forum_category']:null))."',
@@ -1079,6 +1081,8 @@ function get_forum_categories($id = '') {
     // Condition for the session
     $session_id = api_get_session_id();
     $condition_session = api_get_session_condition($session_id);
+    $course_id = api_get_course_int_id();
+    $condition_session .= "AND forum_categories.c_id = $course_id ";
 
     if ($id == '') {
         $sql = "SELECT * FROM".$table_categories." forum_categories, ".$table_item_property." item_properties
@@ -1100,6 +1104,7 @@ function get_forum_categories($id = '') {
                 AND forum_categories.cat_id='".Database::escape_string($id)."' $condition_session
                 ORDER BY forum_categories.cat_order ASC";
     }
+    
     $result = Database::query($sql);
     while ($row = Database::fetch_array($result)) {
         if ($id == '') {
@@ -1125,18 +1130,22 @@ function get_forums_in_category($cat_id) {
     $table_item_property 	= Database :: get_course_table(TABLE_ITEM_PROPERTY);
 
     $forum_list = array();
+    $course_id = api_get_course_int_id();
+    
     $sql = "SELECT * FROM ".$table_forums." forum , ".$table_item_property." item_properties
-                WHERE forum.forum_category='".Database::escape_string($cat_id)."'
+            WHERE forum.forum_category='".Database::escape_string($cat_id)."'
                 AND forum.forum_id=item_properties.ref
                 AND item_properties.visibility=1
-                AND item_properties.tool='".TOOL_FORUM."'
+                AND item_properties.tool='".TOOL_FORUM."' AND
+                forum.c_id = $course_id
                 ORDER BY forum.forum_order ASC";
     if (is_allowed_to_edit()) {
         $sql = "SELECT * FROM ".$table_forums." forum , ".$table_item_property." item_properties
-                WHERE forum.forum_category='".Database::escape_string($cat_id)."'
-                AND forum.forum_id=item_properties.ref
-                AND item_properties.visibility<>2
-                AND item_properties.tool='".TOOL_FORUM."'
+                WHERE 	forum.forum_category		= '".Database::escape_string($cat_id)."' AND 
+                		forum.forum_id				= item_properties.ref AND 
+                		item_properties.visibility<>2 AND 
+                		item_properties.tool		= '".TOOL_FORUM."' AND 
+                		forum.c_id 					= $course_id
                 ORDER BY forum_order ASC";
     }
     $result = Database::query($sql);
@@ -1157,39 +1166,41 @@ function get_forums_in_category($cat_id) {
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  * @version february 2006, dokeos 1.8
  */
-function get_forums($id='', $course_db_name = '') {
-    if (!isset($course_db_name)) {
-        $course_db_name = '';
-    }
+function get_forums($id='', $course_code = '') {
+    $course_info = api_get_course_info($course_code);
+    
     $table_users 			= Database :: get_main_table(TABLE_MAIN_USER);
-    $table_forums 			= Database :: get_course_table(TABLE_FORUM, $course_db_name);
-    $table_threads 			= Database :: get_course_table(TABLE_FORUM_THREAD, $course_db_name);
-    $table_posts 			= Database :: get_course_table(TABLE_FORUM_POST, $course_db_name);
-    $table_item_property 	= Database :: get_course_table(TABLE_ITEM_PROPERTY, $course_db_name);
+    $table_forums 			= Database :: get_course_table(TABLE_FORUM);
+    $table_threads 			= Database :: get_course_table(TABLE_FORUM_THREAD);
+    $table_posts 			= Database :: get_course_table(TABLE_FORUM_POST);
+    $table_item_property 	= Database :: get_course_table(TABLE_ITEM_PROPERTY);
 
 
-    // **************** GETTING ALL THE FORUMS ************************* //
+    // GETTING ALL THE FORUMS //
 
     // Condition for the session
     $session_id = api_get_session_id();
     $condition_session = api_get_session_condition($session_id);
+    $course_id = $course_info['real_id'];
+    
+    $condition_course .= " AND forum.c_id = $course_id";
 
     $forum_list = array();
     if ($id == '') {
-        //-------------- Student -----------------//
+        // Student 
         // Select all the forum information of all forums (that are visible to students).
         $sql = "SELECT * FROM $table_forums forum , ".$table_item_property." item_properties
                         WHERE forum.forum_id=item_properties.ref
                         AND item_properties.visibility=1
                         AND item_properties.tool='".TOOL_FORUM."'
-                        $condition_session
+                        $condition_session AND forum.c_id = $course_id
                         ORDER BY forum.forum_order ASC";
 
         // Select the number of threads of the forums (only the threads that are visible).
         $sql2 = "SELECT count(*) AS number_of_threads, threads.forum_id FROM $table_threads threads, ".$table_item_property." item_properties
                         WHERE threads.thread_id=item_properties.ref
                         AND item_properties.visibility=1
-                        AND item_properties.tool='".TOOL_FORUM_THREAD."'
+                        AND item_properties.tool='".TOOL_FORUM_THREAD."' AND threads.c_id = $course_id
                         GROUP BY threads.forum_id";
 
         // Select the number of posts of the forum (post that are visible and that are in a thread that is visible).
@@ -1198,7 +1209,7 @@ function get_forums($id='', $course_db_name = '') {
                         AND posts.thread_id=threads.thread_id
                         AND threads.thread_id=item_properties.ref
                         AND item_properties.visibility=1
-                        AND item_properties.tool='".TOOL_FORUM_THREAD."'
+                        AND item_properties.tool='".TOOL_FORUM_THREAD."' AND posts.c_id = $course_id
                         GROUP BY threads.forum_id";
 
         //-------------- Course Admin  -----------------//
@@ -1208,14 +1219,14 @@ function get_forums($id='', $course_db_name = '') {
                             WHERE forum.forum_id=item_properties.ref
                             AND item_properties.visibility<>2
                             AND item_properties.tool='".TOOL_FORUM."'
-                            $condition_session
+                            $condition_session AND forum.c_id = $course_id
                             ORDER BY forum_order ASC";
             //echo $sql.'<hr />';
             // Select the number of threads of the forums (only the threads that are not deleted).
             $sql2 = "SELECT count(*) AS number_of_threads, threads.forum_id FROM $table_threads threads, ".$table_item_property." item_properties
                             WHERE threads.thread_id=item_properties.ref
                             AND item_properties.visibility<>2
-                            AND item_properties.tool='".TOOL_FORUM_THREAD."'
+                            AND item_properties.tool='".TOOL_FORUM_THREAD."' AND threads.c_id = $course_id
                             GROUP BY threads.forum_id";
             //echo $sql2.'<hr />';
             // Select the number of posts of the forum.
@@ -1223,14 +1234,14 @@ function get_forums($id='', $course_db_name = '') {
                             WHERE posts.thread_id=threads.thread_id
                             AND threads.thread_id=item_properties.ref
                             AND item_properties.visibility=1
-                            AND item_properties.tool='".TOOL_FORUM_THREAD."'
+                            AND item_properties.tool='".TOOL_FORUM_THREAD."' AND posts.c_id = $course_id
                             GROUP BY threads.forum_id";
             //echo $sql3.'<hr />';
         }
-
-
     }
-    // **************** GETTING ONE SPECIFIC FORUM ************************* //
+    
+    // GETTING ONE SPECIFIC FORUM 
+    
     // We could do the splitup into student and course admin also but we want to have as much as information about a certain forum as possible
     // so we do not take too much information into account. This function (or this section of the function) is namely used to fill the forms
     // when editing a forum (and for the moment it is the only place where we use this part of the function)
@@ -1241,24 +1252,24 @@ function get_forums($id='', $course_db_name = '') {
                                 AND forum_id='".Database::escape_string($id)."'
                                 AND item_properties.visibility<>2
                                 AND item_properties.tool='".TOOL_FORUM."'
-                                $condition_session
+                                $condition_session  AND forum.c_id = $course_id
                                 ORDER BY forum_order ASC";
 
             // Select the number of threads of the forum.
             $sql2 = "SELECT count(*) AS number_of_threads, forum_id FROM $table_threads
-                                WHERE forum_id=".Database::escape_string($id)."
-                                GROUP BY forum_id";
+						WHERE forum_id=".Database::escape_string($id)." AND c_id = $course_id
+                    	GROUP BY forum_id";
 
             // Select the number of posts of the forum.
             $sql3 = "SELECT count(*) AS number_of_posts, forum_id FROM $table_posts
-                                WHERE forum_id=".Database::escape_string($id)."
+                                WHERE forum_id=".Database::escape_string($id)."  AND c_id = $course_id
                                 GROUP BY forum_id";
 
             // Select the last post and the poster (note: this is probably no longer needed).
             $sql4 = "SELECT  post.post_id, post.forum_id, post.poster_id, post.poster_name, post.post_date, users.lastname, users.firstname
                                 FROM $table_posts post, $table_users users
                                 WHERE forum_id=".Database::escape_string($id)."
-                                AND post.poster_id=users.user_id
+                                AND post.poster_id=users.user_id  AND post.c_id = $course_id
                                 GROUP BY post.forum_id
                                 ORDER BY post.post_id ASC";
         }
@@ -1390,16 +1401,15 @@ function get_last_post_information($forum_id, $show_invisibles = false, $course_
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  * @version february 2006, dokeos 1.8
  */
-function get_threads($forum_id, $course_db = '') {
-
-    if (!isset($course_db)) {
-        $course_db  = '';
-    }
+function get_threads($forum_id, $course_code = '') {
 
-    $table_item_property 	= Database :: get_course_table(TABLE_ITEM_PROPERTY,$course_db);
-    $table_threads 			= Database :: get_course_table(TABLE_FORUM_THREAD, $course_db);
-    $table_posts 			= Database :: get_course_table(TABLE_FORUM_POST,$course_db);
-    $table_users 			= Database :: get_main_table(TABLE_MAIN_USER, $course_db);
+	$course_info = api_get_course_info($course_code);
+	$course_id = $course_info['real_id'];
+	
+    $table_item_property 	= Database :: get_course_table(TABLE_ITEM_PROPERTY);
+    $table_threads 			= Database :: get_course_table(TABLE_FORUM_THREAD);
+    $table_posts 			= Database :: get_course_table(TABLE_FORUM_POST);
+    $table_users 			= Database :: get_main_table(TABLE_MAIN_USER);
 
     $thread_list = array();
     // important note: 	it might seem a little bit awkward that we have 'thread.locked as locked' in the sql statement
@@ -1420,7 +1430,11 @@ function get_threads($forum_id, $course_db = '') {
                 ON thread.thread_last_post = post.post_id
             LEFT JOIN $table_users last_poster_users
                 ON post.poster_id= last_poster_users.user_id
-            WHERE thread.forum_id='".Database::escape_string($forum_id)."'
+            WHERE
+            post.c_id = $course_id AND
+            item_properties.c_id = $course_id AND
+            thread.c_id = $course_id AND             
+            thread.forum_id='".Database::escape_string($forum_id)."'
             ORDER BY thread.thread_sticky DESC, thread.thread_date DESC";
     if (is_allowed_to_edit()) {
         // important note: 	it might seem a little bit awkward that we have 'thread.locked as locked' in the sql statement
@@ -1440,7 +1454,11 @@ function get_threads($forum_id, $course_db = '') {
                     ON thread.thread_last_post = post.post_id
                 LEFT JOIN $table_users last_poster_users
                     ON post.poster_id= last_poster_users.user_id
-                WHERE thread.forum_id='".Database::escape_string($forum_id)."'
+                WHERE
+                post.c_id = $course_id AND
+            	item_properties.c_id = $course_id AND
+            	thread.c_id = $course_id AND 
+                thread.forum_id='".Database::escape_string($forum_id)."'
                 ORDER BY thread.thread_sticky DESC, thread.thread_date DESC";
     }
     $result = Database::query($sql);
@@ -1518,11 +1536,14 @@ function get_post_information($post_id) {
 function get_thread_information($thread_id) {
     $table_item_property 	= Database :: get_course_table(TABLE_ITEM_PROPERTY);
     $table_threads 			= Database :: get_course_table(TABLE_FORUM_THREAD);
+    $course_id = api_get_course_int_id();
 
     $sql = "SELECT * FROM ".$table_threads." threads, ".$table_item_property." item_properties
-            WHERE item_properties.tool='".TOOL_FORUM_THREAD."'
-            AND item_properties.ref='".Database::escape_string($thread_id)."'
-            AND threads.thread_id='".Database::escape_string($thread_id)."'";
+            WHERE 	item_properties.tool= '".TOOL_FORUM_THREAD."' AND 
+            		item_properties.ref	= '".Database::escape_string($thread_id)."' AND 
+    				threads.thread_id	= '".Database::escape_string($thread_id)."' AND
+    				threads.c_id = $course_id 
+   			";
     $result = Database::query($sql);
     $row = Database::fetch_array($result);
     return $row;
@@ -1719,11 +1740,15 @@ function get_forum_information($forum_id) {
     $table_item_property 	= Database :: get_course_table(TABLE_ITEM_PROPERTY);
 
     $sql = "SELECT * FROM ".$table_forums." forums, ".$table_item_property." item_properties
-            WHERE item_properties.tool='".TOOL_FORUM."'
-            AND item_properties.ref='".Database::escape_string($forum_id)."'
-            AND forums.forum_id='".Database::escape_string($forum_id)."'";
+            WHERE 	item_properties.tool	= '".TOOL_FORUM."' AND 
+            		item_properties.ref		= '".Database::escape_string($forum_id)."' AND 
+    				forums.forum_id			= '".Database::escape_string($forum_id)."' AND
+    				forums.c_id = ".api_get_course_int_id()."
+    				
+   			";
+    
     $result = Database::query($sql);
-    $row = Database::fetch_array($result);
+    $row 	= Database::fetch_array($result);
     $row['approval_direct_post'] = 0; // We can't anymore change this option, so it should always be activated.
     return $row;
 }
@@ -1739,11 +1764,13 @@ function get_forum_information($forum_id) {
 function get_forumcategory_information($cat_id) {
     $table_categories 		= Database :: get_course_table(TABLE_FORUM_CATEGORY);
     $table_item_property 	= Database :: get_course_table(TABLE_ITEM_PROPERTY);
-
+	$course_id = api_get_course_int_id();
     $sql = "SELECT * FROM ".$table_categories." forumcategories, ".$table_item_property." item_properties
-            WHERE item_properties.tool='".TOOL_FORUM_CATEGORY."'
-            AND item_properties.ref='".Database::escape_string($cat_id)."'
-            AND forumcategories.cat_id='".Database::escape_string($cat_id)."'";
+            WHERE 	forumcategories.c_id = $course_id AND
+            		item_properties.c_id = $course_id AND
+            		item_properties.tool='".TOOL_FORUM_CATEGORY."' AND 
+            		item_properties.ref='".Database::escape_string($cat_id)."' AND 
+    				forumcategories.cat_id='".Database::escape_string($cat_id)."'";
     $result = Database::query($sql);
     $row = Database::fetch_array($result);
     return $row;
@@ -1809,8 +1836,10 @@ function store_thread($values) {
         $clean_post_title = Database::escape_string(stripslashes($values['post_title']));
 
         // We first store an entry in the forum_thread table because the thread_id is used in the forum_post table.
-        $sql = "INSERT INTO $table_threads (thread_title, forum_id, thread_poster_id, thread_poster_name, thread_date, thread_sticky,thread_title_qualify,thread_qualify_max,thread_weight,session_id)
-                VALUES ('".$clean_post_title."',
+        $sql = "INSERT INTO $table_threads (c_id, thread_title, forum_id, thread_poster_id, thread_poster_name, thread_date, thread_sticky,thread_title_qualify,thread_qualify_max,thread_weight,session_id)
+                VALUES (
+                		".api_get_course_int_id().",
+                		'".$clean_post_title."',
                         '".Database::escape_string($values['forum_id'])."',
                         '".Database::escape_string($_user['user_id'])."',
                         '".Database::escape_string(stripslashes(isset($values['poster_name'])?$values['poster_name']:null))."',
@@ -1850,8 +1879,10 @@ function store_thread($values) {
             $visible = 1;
         }
         // We now store the content in the table_post table.
-        $sql = "INSERT INTO $table_posts (post_title, post_text, thread_id, forum_id, poster_id, poster_name, post_date, post_notification, post_parent_id, visible)
-                VALUES ('".$clean_post_title."',
+        $sql = "INSERT INTO $table_posts (c_id, post_title, post_text, thread_id, forum_id, poster_id, poster_name, post_date, post_notification, post_parent_id, visible)
+                VALUES (
+                ".api_get_course_int_id().",
+                '".$clean_post_title."',
                 '".Database::escape_string(stripslashes($values['post_text']))."',
                 '".Database::escape_string($last_thread_id)."',
                 '".Database::escape_string($values['forum_id'])."',
@@ -2117,15 +2148,11 @@ function store_theme_qualify($user_id, $thread_id, $thread_qualify = 0, $qualify
             $row = Database::fetch_array($res1);
 
             if ($row[0] == 0) {
-                $sql = "INSERT INTO $table_threads_qualify (user_id," .
-                    "thread_id,qualify,qualify_user_id,qualify_time,session_id)" .
-                    "VALUES('".$user_id."','".$thread_id."',".(float)$thread_qualify."," .
-                    "'".$qualify_user_id."','".$qualify_time."','".$session_id."')";
+                $sql = "INSERT INTO $table_threads_qualify (c_id, user_id, thread_id,qualify,qualify_user_id,qualify_time,session_id) 
+				VALUES (".api_get_course_int_id().", '".$user_id."','".$thread_id."',".(float)$thread_qualify.", '".$qualify_user_id."','".$qualify_time."','".$session_id."')";
                 $res = Database::query($sql);
-
                 return $res;
             } else {
-
                 $sql1 = "SELECT qualify FROM ".$table_threads_qualify." WHERE user_id=".$user_id." and thread_id=".$thread_id.";";
                 $rs = Database::query($sql1);
                 $row = Database::fetch_array($rs);
@@ -2227,10 +2254,8 @@ function store_qualify_historical($option, $couser_id, $forum_id, $user_id, $thr
         $row = Database::fetch_array($rs);
 
         // Insert thread_historical.
-        $sql1 = "INSERT INTO $table_threads_qualify_log (user_id," .
-                "thread_id,qualify,qualify_user_id,qualify_time,session_id)" .
-                "VALUES('".$user_id."','".$thread_id."',".(float)$row[0]."," .
-                "'".$qualify_user_id."','".$row[1]."','')";
+        $sql1 = "INSERT INTO $table_threads_qualify_log (c_id, user_id, thread_id,qualify,qualify_user_id,qualify_time,session_id) 
+ 				 VALUES(".api_get_course_int_id().", '".$user_id."','".$thread_id."',".(float)$row[0].", '".$qualify_user_id."','".$row[1]."','')";
         Database::query($sql1);
 
         // Update
@@ -2290,8 +2315,10 @@ function store_reply($values) {
     
     if ($upload_ok) {
         // We first store an entry in the forum_post table.
-        $sql = "INSERT INTO $table_posts (post_title, post_text, thread_id, forum_id, poster_id, post_date, post_notification, post_parent_id, visible)
-                VALUES ('".Database::escape_string($values['post_title'])."',
+        $sql = "INSERT INTO $table_posts (c_id, post_title, post_text, thread_id, forum_id, poster_id, post_date, post_notification, post_parent_id, visible)
+                VALUES (
+                		".api_get_course_int_id().",
+                		'".Database::escape_string($values['post_title'])."',
                         '".Database::escape_string(isset($values['post_text']) ? (api_html_entity_decode($values['post_text'])) : null)."',
                         '".Database::escape_string($values['thread_id'])."',
                         '".Database::escape_string($values['forum_id'])."',
@@ -2327,12 +2354,11 @@ function store_reply($values) {
 
                 // Storing the attachments if any.
                 if ($result) {
-                    $sql = 'INSERT INTO '.$forum_table_attachment.'(filename,comment, path, post_id,size) '.
-                         "VALUES ( '".Database::escape_string($file_name)."', '".Database::escape_string($comment)."', '".Database::escape_string($new_file_name)."' , '".$new_post_id."', '".intval($_FILES['user_upload']['size'])."' )";
+                    $sql = 'INSERT INTO '.$forum_table_attachment.'(c_id, filename,comment, path, post_id,size) '.
+                         	"VALUES (".api_get_course_int_id().", '".Database::escape_string($file_name)."', '".Database::escape_string($comment)."', '".Database::escape_string($new_file_name)."' , '".$new_post_id."', '".intval($_FILES['user_upload']['size'])."' )";
                     $result = Database::query($sql);
                     $message .= ' / '.get_lang('FileUploadSucces');
                     $last_id = Database::insert_id();
-
                     api_item_property_update($_course, TOOL_FORUM_ATTACH, $last_id ,'ForumAttachmentAdded', api_get_user_id());
                 }
             }
@@ -2874,7 +2900,7 @@ function send_notification_mails($thread_id, $reply_info) {
         $sql = "SELECT * FROM $table_notification WHERE forum_id = '".Database::escape_string($current_forum['forum_id'])."' OR thread_id = '".Database::escape_string($thread_id)."'";
         $result = Database::query($sql);
         while ($row = Database::fetch_array($result)) {
-            $sql_mailcue = "INSERT INTO $table_mailcue (thread_id, post_id) VALUES ('".Database::escape_string($thread_id)."', '".Database::escape_string($reply_info['new_post_id'])."')";
+            $sql_mailcue = "INSERT INTO $table_mailcue (c_id, thread_id, post_id) VALUES (".api_get_course_int_id().", '".Database::escape_string($thread_id)."', '".Database::escape_string($reply_info['new_post_id'])."')";
             $result_mailcue = Database::query($sql_mailcue);
         }
     }
@@ -3107,8 +3133,9 @@ function store_move_post($values) {
         $current_post = get_post_information($values['post_id']);
 
         // Storing a new thread.
-        $sql = "INSERT INTO $table_threads (thread_title, forum_id, thread_poster_id, thread_poster_name, thread_last_post, thread_date)
+        $sql = "INSERT INTO $table_threads (c_id, thread_title, forum_id, thread_poster_id, thread_poster_name, thread_last_post, thread_date)
             VALUES (
+            	".api_get_course_int_id().",
                 '".Database::escape_string($current_post['post_title'])."',
                 '".Database::escape_string($current_post['forum_id'])."',
                 '".Database::escape_string($current_post['poster_id'])."',
@@ -3446,8 +3473,8 @@ function add_forum_attachment_file($file_comment,$last_id) {
             $last_id = intval($last_id);
             // Storing the attachments if any.
             if ($result) {
-                $sql = "INSERT INTO $agenda_forum_attachment(filename, comment, path, post_id, size)
-                      VALUES ( '$safe_file_name', '$safe_file_comment', '$safe_new_file_name' , '$last_id', '".intval($_FILES['user_upload']['size'])."' )";
+                $sql = "INSERT INTO $agenda_forum_attachment (c_id, filename, comment, path, post_id, size)
+                      	VALUES (".api_get_course_int_id().", '$safe_file_name', '$safe_file_comment', '$safe_new_file_name' , '$last_id', '".intval($_FILES['user_upload']['size'])."' )";
                 $result = Database::query($sql);
                 $message .= ' / '.get_lang('FileUploadSucces').'<br />';
 
@@ -3701,7 +3728,7 @@ function set_notification($content,$id, $add_only = false) {
 
     // If the user did not indicate that (s)he wanted to be notified already then we store the notification request (to prevent double notification requests).
     if ($total <= 0) {
-        $sql = "INSERT INTO $table_notification ($database_field, user_id) VALUES ('".Database::escape_string($id)."','".Database::escape_string($_user['user_id'])."')";
+        $sql = "INSERT INTO $table_notification (c_id, $database_field, user_id) VALUES (".api_get_course_int_id().", '".Database::escape_string($id)."','".Database::escape_string($_user['user_id'])."')";
         $result = Database::query($sql);
         api_session_unregister('forum_notification');
         get_notifications_of_user(0, true);
@@ -3927,8 +3954,8 @@ function get_statistical_information($thread_id, $user_id, $course_id) {
  * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,
  * @version octubre 2008, dokeos 1.8
  */
-function get_thread_user_post($course_db, $thread_id, $user_id ) {
-    $table_posts =  Database::get_course_table(TABLE_FORUM_POST, $course_db);
+function get_thread_user_post($course_code, $thread_id, $user_id ) {
+    $table_posts =  Database::get_course_table(TABLE_FORUM_POST);
     $table_users =  Database::get_main_table(TABLE_MAIN_USER);
     $thread_id = intval($thread_id);
     $user_id = intval($user_id);
@@ -3997,24 +4024,24 @@ function get_name_thread_by_id($thread_id) {
  * @return string
  */
 
-function get_all_post_from_user($user_id, $course_db) {
+function get_all_post_from_user($user_id, $course_code) {
     $j = 0;
-    $forums = get_forums('', $course_db);
+    $forums = get_forums('', $course_code);
     krsort($forums);
     $forum_results = '';
 
      foreach ($forums as $forum) {
         if ($j <= 4) {
-             $threads = get_threads($forum['forum_id'], $course_db);
+             $threads = get_threads($forum['forum_id'], $course_code);
 
              if (is_array($threads)) {
-                 $my_course_code = CourseManager::get_course_id_by_database_name($course_db);
+                 $my_course_code = CourseManager::get_course_id_by_database_name($course_code);
                  $i = 0;
                  $hand_forums = '';
                  $post_counter = 0;
                  foreach($threads as $thread) {
                      if ($i <= 4) {
-                         $post_list = get_thread_user_post_limit($course_db, $thread['thread_id'], $user_id, 1);
+                         $post_list = get_thread_user_post_limit($course_code, $thread['thread_id'], $user_id, 1);
                          $post_counter = count($post_list);
                          if (is_array($post_list) && count($post_list) > 0) {
                              $hand_forums.= '<div id="social-thread">';
@@ -4058,14 +4085,19 @@ function get_all_post_from_user($user_id, $course_db) {
  * @param int
  * @return void
  */
-function get_thread_user_post_limit($course_db, $thread_id, $user_id, $limit = 10) {
-    $table_posts =  Database::get_course_table(TABLE_FORUM_POST, $course_db);
+function get_thread_user_post_limit($course_code, $thread_id, $user_id, $limit = 10) {
+    $table_posts =  Database::get_course_table(TABLE_FORUM_POST);
     $table_users =  Database::get_main_table(TABLE_MAIN_USER);
+    
+    $course_info = api_get_course_info($course_code);
+    $course_id = $course_info['real_id'];
 
     $sql = "SELECT * FROM $table_posts posts
             LEFT JOIN  $table_users users
                 ON posts.poster_id=users.user_id
-            WHERE posts.thread_id='".Database::escape_string($thread_id)."'
+            WHERE
+            	posts.c_id = $course_id AND 
+            	posts.thread_id='".Database::escape_string($thread_id)."'
                 AND posts.poster_id='".Database::escape_string($user_id)."'
             ORDER BY posts.post_id DESC LIMIT $limit ";
     $result = Database::query($sql);

+ 5 - 7
main/forum/viewforum.php

@@ -73,10 +73,11 @@ if (!empty($my_forum_group)) {
         $current_forum_category = get_forumcategory_information($current_forum['forum_category']);
     }
 } else {
-    $result = get_forum_information($my_forum);
+    $result = get_forum_information($my_forum);    
     if ($result['forum_of_group'] == 0) {
-        $current_forum = get_forum_information($my_forum); // Note: This has to be validated that it is an existing forum.
+        $current_forum = get_forum_information($my_forum); // Note: This has to be validated that it is an existing forum.        
         $current_forum_category = get_forumcategory_information($current_forum['forum_category']);
+        
     }
 }
 
@@ -242,11 +243,8 @@ if ($my_action == 'liststd' AND isset($_GET['content']) AND isset($_GET['id']) A
 
 // If the user is not a course administrator and the forum is hidden
 // then the user is not allowed here.
-if (!api_is_allowed_to_edit(false, true) AND ($current_forum_category['visibility'] == 0 OR $current_forum['visibility'] == 0)) {
-    $forum_allow = forum_not_allowed_here();
-    if ($forum_allow === false) {
-        exit;
-    }
+if (!api_is_allowed_to_edit(false, true) AND ($current_forum_category['visibility'] == 0 OR $current_forum['visibility'] == 0)) {	
+ 	api_not_allowed();
 }
 
 if ($origin == 'learnpath') {

+ 2 - 8
main/glossary/index.php

@@ -94,18 +94,12 @@ if (api_is_allowed_to_edit(null, true)) {
         $form->addElement('hidden', 'glossary_id');
         $form->addElement('text', 'glossary_title', get_lang('TermName'),array('size'=>'80'));
         //$form->applyFilter('glossary_title', 'html_filter');
-        $form->addElement('html_editor', 'glossary_comment', get_lang('TermDefinition'), null, array('ToolbarSet' => 'Glossary', 'Width' => '90%', 'Height' => '300'));
-        
-        
-        
+        $form->addElement('html_editor', 'glossary_comment', get_lang('TermDefinition'), null, array('ToolbarSet' => 'Glossary', 'Width' => '90%', 'Height' => '300'));        
         $element = $form->addElement('text', 'insert_date', get_lang('CreationDate'),array('size'=>'100'));
         $element ->freeze();        
         $element = $form->addElement('text', 'update_date', get_lang('UpdateDate'),array('size'=>'100'));
-        $element ->freeze();
-       
+        $element ->freeze();       
         $form->addElement('style_submit_button', 'SubmitGlossary', get_lang('TermUpdateButton'), 'class="save"');
-        
-        
 
         // setting the defaults
         $glossary_data = GlossaryManager::get_glossary_information($_GET['glossary_id']);

+ 5 - 6
main/gradebook/gradebook.php

@@ -56,14 +56,12 @@ function confirmation ()
 </script>';
 $filter_confirm_msg = true;
 $filter_warning_msg = true;
-// --------------------------------------------------------------------------------
-// -                                  ACTIONS                                     -
-// --------------------------------------------------------------------------------
+// ACTIONS
 
 $my_selectcat =isset($_GET['selectcat']) ? Security::remove_XSS($_GET['selectcat']) : '';
 if ($my_selectcat!='') {
-	$my_db_name       = get_database_name_by_link_id($my_selectcat);
-	$tbl_forum_thread = Database :: get_course_table(TABLE_FORUM_THREAD,$my_db_name);
+	$course_id        = get_course_id_by_link_id($my_selectcat);
+	$tbl_forum_thread = Database :: get_course_table(TABLE_FORUM_THREAD);
 	$tbl_grade_links  = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 }
 
@@ -264,7 +262,8 @@ if (isset ($_GET['deletelink'])) {
 	if (!empty($_GET['deletelink'])) {	
 		$link= LinkFactory :: load($_GET['deletelink']);
 		if ($link[0] != null) {
-			$sql='UPDATE '.$tbl_forum_thread.' SET thread_qualify_max=0,thread_weight=0,thread_title_qualify="" WHERE thread_id=(SELECT ref_id FROM '.$tbl_grade_links.' where id='.intval($_GET['deletelink']).');';
+			$sql = 'UPDATE '.$tbl_forum_thread.' SET thread_qualify_max=0,thread_weight=0,thread_title_qualify="" 
+					WHERE c_id = '.$course_id.' AND thread_id=(SELECT ref_id FROM '.$tbl_grade_links.' WHERE c_id = '.$course_id.' AND id='.intval($_GET['deletelink']).');';
 			Database::query($sql);
 			$link[0]->delete();
 		}

+ 7 - 7
main/gradebook/gradebook_add_link.php

@@ -18,7 +18,7 @@ require_once '../forum/forumfunction.inc.php';
 api_block_anonymous_users();
 block_students();
 
-$course_info =isset($_GET['course_code'])? api_get_course_info($_GET['course_code']) : '';
+$course_info =isset($_GET['course_code'])? api_get_course_info($_GET['course_code']) : api_get_course_info();
 $my_db_course=isset($_GET['course_code'])?$course_info['dbName']:'';
 
 $tbl_forum_thread = Database :: get_course_table(TABLE_FORUM_THREAD,$my_db_course);
@@ -59,7 +59,6 @@ if (isset($_GET['typeselected']) && $_GET['typeselected'] != '0') {
 		$link->set_user_id(api_get_user_id());
 		if($category[0]->get_course_code() == '' && !empty($_GET['course_code'])) {
 			$link->set_course_code($_GET['course_code']);
-
 		} else {
 			$link->set_course_code($category[0]->get_course_code());
 		}
@@ -81,21 +80,22 @@ if (isset($_GET['typeselected']) && $_GET['typeselected'] != '0') {
 		}
 		$link->set_visible(empty ($addvalues['visible']) ? 0 : 1);
 
-		//update view_properties
-		$work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
+		//update view_properties		
 		if ( isset($_GET['typeselected']) && 5==$_GET['typeselected'] && (isset($addvalues['select_link']) && $addvalues['select_link']<>"")) {
 
-			$sql1='SELECT thread_title from '.$tbl_forum_thread.' where thread_id='.$addvalues['select_link'].';';
+			$sql1 = 'SELECT thread_title from '.$tbl_forum_thread.' 
+					 WHERE c_id = '.$course_info['real_id'].' AND thread_id='.$addvalues['select_link'];
 			$res1=Database::query($sql1);
 			$rowtit=Database::fetch_row($res1);
 			$course_id=api_get_course_id();
-			$sql_l='SELECT count(*) FROM '.$tbl_link.' WHERE ref_id='.$addvalues['select_link'].' and course_code="'.$course_id.'" and type=5;';
+			$sql_l='SELECT count(*) FROM '.$tbl_link.' WHERE c_id = '.$course_info['real_id'].' AND ref_id='.$addvalues['select_link'].' and course_code="'.$course_id.'" and type=5;';
 			$res_l=Database::query($sql_l);
 			$row=Database::fetch_row($res_l);
 
 			if ( $row[0]==0 ) {
 				$link->add();
-				$sql='UPDATE '.$tbl_forum_thread.' set thread_qualify_max='.$addvalues['weight'].',thread_weight='.$addvalues['weight'].',thread_title_qualify="'.$rowtit[0].'" WHERE thread_id='.$addvalues['select_link'].';';
+				$sql = 'UPDATE '.$tbl_forum_thread.' SET thread_qualify_max='.$addvalues['weight'].',thread_weight='.$addvalues['weight'].',thread_title_qualify="'.$rowtit[0].'" 
+						WHERE thread_id='.$addvalues['select_link'].' AND c_id = '.$course_info['real_id'].' ';
 				Database::query($sql);
 				//$sql_l='UPDATE '.$tbl_link.' SET weight='.$addvalues['weight'].' WHERE ref_id='.$addvalues['select_link'].' AND type=5;';
 				//Database::query($sql_l);

+ 17 - 35
main/gradebook/gradebook_edit_all.php

@@ -30,7 +30,7 @@ if (!api_is_allowed_to_create_course()) {
 	exit;
 }
 
-$my_selectcat=isset($_GET['selectcat']) ? Security::remove_XSS($_GET['selectcat']) : '';
+$my_selectcat = isset($_GET['selectcat']) ? Security::remove_XSS($_GET['selectcat']) : '';
 
 if (empty($my_selectcat)) {
 	api_not_allowed();
@@ -54,31 +54,14 @@ if (!isset($_GET['exportpdf']) and !isset($_GET['export_certificate'])) {
 
 
 
+$course_id			  =	get_course_id_by_link_id($my_selectcat);
+
 $table_link           = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 $table_evaluation     = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
-//$table_forum_thread=Database::get_course_table(TABLE_FORUM_THREAD);
-
-$my_db_name=get_database_name_by_link_id($my_selectcat);
-$tbl_forum_thread     = Database :: get_course_table(TABLE_FORUM_THREAD,$my_db_name);
-$tbl_work             = Database :: get_course_table(TABLE_STUDENT_PUBLICATION,$my_db_name);
-$tbl_attendance       = Database :: get_course_table(TABLE_ATTENDANCE,$my_db_name);
-/*
-if($_SERVER['REQUEST_METHOD']=='POST'):
-	foreach($_POST['link'] as $key => $value){
-		Database::query('UPDATE '.$table_link.' SET weight = '."'".$value."'".' WHERE id = '.$key);
-	}
-	foreach($_POST['evaluation'] as $key => $value){
-		Database::query('UPDATE '.$table_evaluation.' SET weight = '."'".$value."'".' WHERE id = '.$key);
-	}
-	Display :: display_normal_message(get_lang('GradebookWeightUpdated')) . '<br /><br />';
-endif;*/
-/*
-define('LINK_EXERCISE',1);
-define('LINK_DROPBOX',2);
-define('LINK_STUDENTPUBLICATION',3);
-define('LINK_LEARNPATH',4);
-define('LINK_FORUM_THREAD',5);
-*/
+$tbl_forum_thread     = Database :: get_course_table(TABLE_FORUM_THREAD);
+$tbl_work             = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
+$tbl_attendance       = Database :: get_course_table(TABLE_ATTENDANCE);
+
 $table_evaluated[LINK_EXERCISE]           = array(TABLE_QUIZ_TEST, 'title', 'id', get_lang('Exercise'));
 $table_evaluated[LINK_DROPBOX]            = array(TABLE_DROPBOX_FILE, 'name','id', get_lang('Dropbox'));
 $table_evaluated[LINK_STUDENTPUBLICATION] = array(TABLE_STUDENT_PUBLICATION, 'url','id', get_lang('Student_publication'));
@@ -94,12 +77,10 @@ if($submitted==1) {
 		require_once 'lib/be/evaluation.class.php';
 		$eval_log = new Evaluation();
 	}
-
 	if(isset($_POST['link'])){
 		require_once 'lib/be/abstractlink.class.php';
 		//$eval_link_log = new AbstractLink();
 	}
-
 }
 
 $category_id = (int)$_GET['selectcat'];
@@ -111,26 +92,29 @@ $result = Database::query($sql);
 		if(isset($_POST['link'][$row['id']]) && $_POST['link'][$row['id']] != $row['weight']) {
 
 			AbstractLink::add_link_log($row['id']);
-			Database::query('UPDATE '.$table_link.' SET weight = '."'".Database::escape_string(trim($_POST['link'][$row['id']]))."'".' WHERE id = '.$row['id']);
+			Database::query('UPDATE '.$table_link.' SET weight = '."'".Database::escape_string(trim($_POST['link'][$row['id']]))."'".' WHERE c_id = '.$course_id.' AND  id = '.$row['id']);
 			$row['weight'] = trim($_POST['link'][$row['id']]);
 
 			//Update weight for attendance
-			$sql = 'SELECT ref_id FROM '.$table_link.' WHERE id = '.intval($row['id']).' AND type='.LINK_ATTENDANCE;
+			$sql = 'SELECT ref_id FROM '.$table_link.' WHERE c_id = '.$course_id.' AND id = '.intval($row['id']).' AND type='.LINK_ATTENDANCE;
 			$rs_attendance  = Database::query($sql);
 			if (Database::num_rows($rs_attendance) > 0) {
 				$row_attendance = Database::fetch_array($rs_attendance);
-				$upd_attendance = 'UPDATE '.$tbl_attendance.' SET attendance_weight ='.floatval($_POST['link'][$row['id']]).' WHERE id = '.intval($row_attendance['ref_id']);
+				$upd_attendance = 'UPDATE '.$tbl_attendance.' SET attendance_weight ='.floatval($_POST['link'][$row['id']]).' 
+								 WHERE c_id = '.$course_id.' AND  id = '.intval($row_attendance['ref_id']);
 				Database::query($upd_attendance);
 			}
 			//Update weight into forum thread
-			$sql_t='UPDATE '.$tbl_forum_thread.' SET thread_weight='.floatval($_POST['link'][$row['id']]).' WHERE thread_id= (SELECT ref_id FROM '.$table_link.' WHERE id='.intval($row['id']).' AND type='.LINK_FORUM_THREAD.');';
+			$sql_t = 'UPDATE '.$tbl_forum_thread.' SET thread_weight='.floatval($_POST['link'][$row['id']]).' 
+					  WHERE c_id = '.$course_id.' AND thread_id = (SELECT ref_id FROM '.$table_link.' WHERE id='.intval($row['id']).' AND type='.LINK_FORUM_THREAD.' AND c_id = '.$course_id.') ';
 			Database::query($sql_t);
 			//Update weight into student publication(work)
-			$sql_t='UPDATE '.$tbl_work.' SET weight='.floatval($_POST['link'][$row['id']]).' WHERE id = (SELECT ref_id FROM '.$table_link.' WHERE id='.intval($row['id']).' AND type = '.LINK_STUDENTPUBLICATION.');';
+			$sql_t='UPDATE '.$tbl_work.' SET weight='.floatval($_POST['link'][$row['id']]).' 
+					WHERE  c_id = '.$course_id.' AND id = (SELECT ref_id FROM '.$table_link.' WHERE id='.intval($row['id']).' AND type = '.LINK_STUDENTPUBLICATION.' AND c_id = '.$course_id.' ) ';
 			Database::query($sql_t);
 		}
 
-		$tempsql = Database::query('SELECT * FROM '.get_table_type_course($row['type'],$row['course_code']).' WHERE '.$table_evaluated[$row['type']][2].' = '.$row['ref_id']);
+		$tempsql = Database::query('SELECT * FROM '.get_table_type_course($row['type'],$row['course_code']).' WHERE c_id = '.$course_id.' AND  '.$table_evaluated[$row['type']][2].' = '.$row['ref_id']);
 		$resource_name = Database ::fetch_array($tempsql);
 		//var_dump($resource_name['lp_type']);
 		if (isset($resource_name['lp_type'])) {
@@ -143,7 +127,6 @@ $result = Database::query($sql);
 
 	$sql = Database::query('SELECT * FROM '.$table_evaluation.' WHERE category_id = '.$category_id);
 	while($row = Database ::fetch_array($sql)) {
-
 		//update only if value changed
 		if(isset($_POST['evaluation'][$row['id']]) && $_POST['evaluation'][$row['id']] != $row['weight']) {
 			Evaluation::add_evaluation_log($row['id']);
@@ -183,5 +166,4 @@ Display::display_normal_message($warning_message,false);
  <button class="save" type="submit" name="name" value="<?php echo get_lang('Save') ?>"><?php echo get_lang('SaveScoringRules') ?></button>
 </form>
 <?php
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 12 - 11
main/gradebook/gradebook_edit_link.php

@@ -16,14 +16,13 @@ require_once 'lib/fe/linkform.class.php';
 require_once 'lib/fe/linkaddeditform.class.php';
 api_block_anonymous_users();
 block_students();
-$course_table = Database::get_main_table(TABLE_MAIN_COURSE);
 $tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 //selected name of database
-$my_db_name=get_database_name_by_link_id(Security::remove_XSS($_GET['editlink']));
-$tbl_forum_thread = Database :: get_course_table(TABLE_FORUM_THREAD,$my_db_name);
-$tbl_work = Database :: get_course_table(TABLE_STUDENT_PUBLICATION,$my_db_name);
-$tbl_attendance = Database :: get_course_table(TABLE_ATTENDANCE,$my_db_name);
-$linkarray = LinkFactory :: load(Security::remove_XSS($_GET['editlink']));
+$course_id 		= get_course_id_by_link_id(Security::remove_XSS($_GET['editlink']));
+$tbl_forum_thread 		= Database :: get_course_table(TABLE_FORUM_THREAD);
+$tbl_work 				= Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
+$tbl_attendance 		= Database :: get_course_table(TABLE_ATTENDANCE);
+$linkarray 				= LinkFactory :: load(Security::remove_XSS($_GET['editlink']));
 $link = $linkarray[0];
 $linkcat  = isset($_GET['selectcat']) ? Security::remove_XSS($_GET['selectcat']):'';
 $linkedit = isset($_GET['editlink']) ? Security::remove_XSS($_GET['editlink']):'';
@@ -43,20 +42,22 @@ if ($form->validate()) {
 	$link->save();
 
 	//Update weight for attendance
-	$sql = 'SELECT ref_id FROM '.$tbl_grade_links.' WHERE id = '.intval($_GET['editlink']).' AND type='.LINK_ATTENDANCE;
+	$sql = 'SELECT ref_id FROM '.$tbl_grade_links.' WHERE c_id = '.$course_id.' AND  id = '.intval($_GET['editlink']).' AND type='.LINK_ATTENDANCE;
 	$rs_attendance  = Database::query($sql);
 	if (Database::num_rows($rs_attendance) > 0) {
 		$row_attendance = Database::fetch_array($rs_attendance);
 		$attendance_id  = $row_attendance['ref_id'];
-		$upd_attendance = 'UPDATE '.$tbl_attendance.' SET attendance_weight ='.floatval($values['weight']).' WHERE id = '.intval($attendance_id);
+		$upd_attendance = 'UPDATE '.$tbl_attendance.' SET attendance_weight ='.floatval($values['weight']).' WHERE c_id = '.$course_id.' AND  id = '.intval($attendance_id);
 		Database::query($upd_attendance);
 	}
 
 	//Update weight into forum thread
-	$sql_t='UPDATE '.$tbl_forum_thread.' SET thread_weight='.$values['weight'].' WHERE thread_id=(SELECT ref_id FROM '.$tbl_grade_links.' where id='.intval($_GET['editlink']).' and type=5);';
+	$sql_t = 'UPDATE '.$tbl_forum_thread.' SET thread_weight='.$values['weight'].' 
+			  WHERE c_id = '.$course_id.' AND thread_id=(SELECT ref_id FROM '.$tbl_grade_links.' WHERE id='.intval($_GET['editlink']).' and type=5 AND c_id = '.$course_id.'  ) ';
 	Database::query($sql_t);
 	//Update weight into student publication(work)
-	$sql_t='UPDATE '.$tbl_work.' SET weight='.$values['weight'].' WHERE id=(SELECT ref_id FROM '.$tbl_grade_links.' where id='.intval($_GET['editlink']).' and type=3);';
+	$sql_t = 'UPDATE '.$tbl_work.' SET weight='.$values['weight'].' 
+			  WHERE c_id = '.$course_id.' AND id = (SELECT ref_id FROM '.$tbl_grade_links.' WHERE c_id = '.$course_id.' AND id='.intval($_GET['editlink'] ).' AND  type=3 )';
 	Database::query($sql_t);
 	header('Location: '.$_SESSION['gradebook_dest'].'?linkedited=&selectcat=' . $link->get_category_id());
 	exit;
@@ -66,4 +67,4 @@ $interbreadcrumb[] = array ('url' => Security::remove_XSS($_SESSION['gradebook_d
 
 Display :: display_header(get_lang('EditLink'));
 $form->display();
-Display :: display_footer();
+Display :: display_footer();

+ 19 - 15
main/gradebook/gradebook_result.class.php

@@ -68,11 +68,15 @@ class GradeBookResult
 		$return = array();
     	$TBL_EXERCISE_QUESTION  = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
     	$TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
+    	$course_id = api_get_course_int_id();
 		$sql="SELECT q.id, q.question, q.ponderation, q.position, q.type, q.picture " .
 			" FROM $TBL_EXERCISE_QUESTION eq, $TBL_QUESTIONS q " .
-			" WHERE eq.question_id=q.id AND eq.exercice_id='$e_id' " .
+			" WHERE eq.c_di = $course_id AND
+					q.c_di = $course_id AND					
+					eq.question_id=q.id AND 
+					eq.exercice_id='$e_id' " .
 			" ORDER BY q.position";
-		$result=Database::query($sql);
+		$result = Database::query($sql);
 
 		// fills the array with the question ID for this exercise
 		// the key of the array is the question position
@@ -89,23 +93,21 @@ class GradeBookResult
 	function _getGradeBookReporting($document_path,$user_id=null) {
 		$return = array();
     	$TBL_EXERCISES          = Database::get_course_table(TABLE_QUIZ_TEST);
-    	$TBL_EXERCISE_QUESTION  = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
-    	$TBL_QUESTIONS 			= Database::get_course_table(TABLE_QUIZ_QUESTION);
-		$TBL_USER          	    = Database::get_main_table(TABLE_MAIN_USER);
-		$TBL_DOCUMENT          	= Database::get_course_table(TABLE_DOCUMENT);
-		$TBL_ITEM_PROPERTY      = Database::get_course_table(TABLE_ITEM_PROPERTY);
+    	$TBL_USER          	    = Database::get_main_table(TABLE_MAIN_USER);		
 		$TBL_TRACK_EXERCISES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
 		$TBL_TRACK_HOTPOTATOES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
-		$TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-
+		
     	$cid = api_get_course_id();
+    	$course_id = api_get_course_int_id();
 		if (empty($user_id)) {
 			//get all results (ourself and the others) as an admin should see them
 			//AND exe_user_id <> $_user['user_id']  clause has been removed
 			$sql="SELECT ".(api_is_western_name_order() ? "CONCAT(firstname,' ',lastname)" : "CONCAT(lastname,' ',firstname)").", ce.title, te.exe_result ,
 						te.exe_weighting, te.exe_date,te.exe_id, user.email, user.user_id
 				  FROM $TBL_EXERCISES ce , $TBL_TRACK_EXERCISES te, $TBL_USER user
-				  WHERE te.exe_exo_id = ce.id AND user_id=te.exe_user_id AND te.exe_cours_id='$cid'
+				  WHERE ce.c_id = $course_id AND
+				  		te.exe_exo_id = ce.id AND 
+				  		user_id=te.exe_user_id AND te.exe_cours_id='$cid'
 				  ORDER BY te.exe_cours_id ASC, ce.title ASC, te.exe_date ASC";
 
 			$hpsql="SELECT ".(api_is_western_name_order() ? "CONCAT(tu.firstname,' ',tu.lastname)" : "CONCAT(tu.lastname,' ',tu.firstname)").", tth.exe_name,
@@ -115,11 +117,13 @@ class GradeBookResult
 					ORDER BY tth.exe_cours_id ASC, tth.exe_date ASC";
 
 		} else { // get only this user's results
-			  $sql="SELECT '',ce.title, te.exe_result , te.exe_weighting, " .
-			  		"te.exe_date,te.exe_id
-				  FROM $TBL_EXERCISES ce , $TBL_TRACK_EXERCISES te
-				  WHERE te.exe_exo_id = ce.id AND te.exe_user_id='".$user_id."' AND te.exe_cours_id='$cid'
-				  ORDER BY te.exe_cours_id ASC, ce.title ASC, te.exe_date ASC";
+			  $sql = "SELECT '',ce.title, te.exe_result , te.exe_weighting, te.exe_date,te.exe_id
+						FROM $TBL_EXERCISES ce , $TBL_TRACK_EXERCISES te
+				  		WHERE 	ce.c_id 		= $course_id AND
+				  				te.exe_exo_id 	= ce.id AND 
+				  				te.exe_user_id 	= '".$user_id."' AND 
+				  				te.exe_cours_id = '$cid'
+				  		ORDER BY te.exe_cours_id ASC, ce.title ASC, te.exe_date ASC";
 
 			$hpsql="SELECT '',exe_name, exe_result , exe_weighting, exe_date
 					FROM $TBL_TRACK_HOTPOTATOES

+ 6 - 2
main/gradebook/index.php

@@ -324,6 +324,8 @@ if (isset ($_GET['visiblelink'])) {
 	}
 }
 
+$course_id = api_get_course_int_id();
+
 if (isset ($_GET['deletelink'])) {
 	block_students();
 	$get_delete_link=Security::remove_XSS($_GET['deletelink']);
@@ -332,10 +334,12 @@ if (isset ($_GET['deletelink'])) {
 		$link= LinkFactory :: load($get_delete_link);
 		if ($link[0] != null) {
 			// clean forum qualify
-			$sql='UPDATE '.$tbl_forum_thread.' SET thread_qualify_max=0,thread_weight=0,thread_title_qualify="" WHERE thread_id=(SELECT ref_id FROM '.$tbl_grade_links.' WHERE id='.$get_delete_link.' AND type = '.LINK_FORUM_THREAD.');';
+			$sql = 'UPDATE '.$tbl_forum_thread.' SET thread_qualify_max=0,thread_weight=0,thread_title_qualify="" 
+					WHERE c_id = '.$course_id.' AND thread_id = (SELECT ref_id FROM '.$tbl_grade_links.' WHERE id='.$get_delete_link.' AND type = '.LINK_FORUM_THREAD.');';
 			Database::query($sql);
 			// clean attendance
-			$sql='UPDATE '.$tbl_attendance.' SET attendance_qualify_max=0, attendance_weight = 0, attendance_qualify_title="" WHERE id=(SELECT ref_id FROM '.$tbl_grade_links.' WHERE id='.$get_delete_link.' AND type = '.LINK_ATTENDANCE.');';
+			$sql = 'UPDATE '.$tbl_attendance.' SET attendance_qualify_max=0, attendance_weight = 0, attendance_qualify_title="" 
+				 	WHERE c_id = '.$course_id.' AND id = (SELECT ref_id FROM '.$tbl_grade_links.' WHERE id='.$get_delete_link.' AND type = '.LINK_ATTENDANCE.');';
 			Database::query($sql);
 			$link[0]->delete();
 		}

+ 6 - 3
main/gradebook/lib/be/attendancelink.class.php

@@ -93,7 +93,8 @@ class AttendanceLink extends AbstractLink
     public function has_results() {
     	$course_info = api_get_course_info($this->course_code);
     	$tbl_attendance_result = Database :: get_course_table(TABLE_ATTENDANCE_RESULT,$course_info['dbName']);
-		$sql = 'SELECT count(*) AS number FROM '.$tbl_attendance_result." WHERE attendance_id = '".intval($this->get_ref_id())."'";
+		$sql = 'SELECT count(*) AS number FROM '.$tbl_attendance_result." 
+				WHERE c_id = {$course_info['real_id']} AND attendance_id = '".intval($this->get_ref_id())."'";
     	$result = Database::query($sql);
 		$number = Database::fetch_row($result);
 		return ($number[0] != 0);
@@ -108,12 +109,14 @@ class AttendanceLink extends AbstractLink
 			$session_id = api_get_session_id();
 
 			// get attendance qualify max
-	  		$sql = 'SELECT att.attendance_qualify_max FROM '.$this->get_attendance_table().' att WHERE att.id = '.intval($this->get_ref_id()).' AND att.session_id='.intval($session_id).'';
+	  		$sql = 'SELECT att.attendance_qualify_max FROM '.$this->get_attendance_table().' att 
+	  				WHERE att.c_id = '.$course_info['real_id'].' AND att.id = '.intval($this->get_ref_id()).' AND att.session_id='.intval($session_id).'';
 			$query = Database::query($sql);
 			$attendance = Database::fetch_array($query);
 
 			// get results
-	  	    $sql = 'SELECT * FROM '.$tbl_attendance_result.' WHERE attendance_id = '.intval($this->get_ref_id());
+	  	    $sql = 'SELECT * FROM '.$tbl_attendance_result.' 
+	  	    		WHERE c_id = '.$course_info['real_id'].' AND attendance_id = '.intval($this->get_ref_id());
 	    	if (isset($stud_id)) {
 	    		$sql .= ' AND user_id = '.intval($stud_id);
 	    	}

+ 16 - 8
main/gradebook/lib/be/forumthreadlink.class.php

@@ -73,10 +73,17 @@ class ForumThreadLink extends AbstractLink
     	if (empty($this->course_code)) {
     		die('Error in get_not_created_links() : course code not set');
     	}
-    	$course_info = api_get_course_info($this->course_code);
-    	$tbl_grade_links = Database :: get_course_table(TABLE_FORUM_THREAD,$course_info['dbName']);
-    	$tbl_item_property=Database :: get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-		$sql = 'SELECT tl.thread_id,tl.thread_title,tl.thread_title_qualify FROM '.$tbl_grade_links.' tl ,'.$tbl_item_property.' ip WHERE tl.thread_id=ip.ref AND ip.tool="forum_thread" AND ip.visibility<>2 AND tl.session_id='.api_get_session_id().' GROUP BY ip.ref ';
+    	$course_info 		= api_get_course_info($this->course_code);
+    	$tbl_grade_links 	= Database :: get_course_table(TABLE_FORUM_THREAD,$course_info['dbName']);
+    	$tbl_item_property	= Database :: get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+    	
+		$sql = 'SELECT tl.thread_id, tl.thread_title, tl.thread_title_qualify 
+				FROM '.$tbl_grade_links.' tl ,'.$tbl_item_property.' ip 
+				WHERE 	tl.c_id 		= '.$course_info['real_id'].' AND
+						ip.c_id 		= '.$course_info['real_id'].' AND 
+						tl.thread_id	= ip.ref AND 
+						ip.tool			= "forum_thread" AND 
+						ip.visibility<>2 AND tl.session_id='.api_get_session_id().' GROUP BY ip.ref ';
 		$result = Database::query($sql);
 
 		while ($data=Database::fetch_array($result)) {
@@ -97,7 +104,8 @@ class ForumThreadLink extends AbstractLink
     public function has_results() {
     	$course_info = api_get_course_info($this->course_code);
     	$tbl_grade_links = Database :: get_course_table(TABLE_FORUM_POST,$course_info['dbName']);
-		$sql = 'SELECT count(*) AS number FROM '.$tbl_grade_links." WHERE thread_id = '".$this->get_ref_id()."'";
+		$sql = 'SELECT count(*) AS number FROM '.$tbl_grade_links." 
+				WHERE c_id = ".$course_info['real_id']." AND thread_id = '".$this->get_ref_id()."'";
     	$result = Database::query($sql);
 		$number=Database::fetch_row($result);
 		return ($number[0] != 0);
@@ -110,12 +118,12 @@ class ForumThreadLink extends AbstractLink
 		if (!empty($database_name)) {
 			$thread_qualify = Database :: get_course_table(TABLE_FORUM_THREAD_QUALIFY, $database_name);
 
-	  		$sql = 'SELECT thread_qualify_max FROM '.Database :: get_course_table(TABLE_FORUM_THREAD, $database_name)." WHERE thread_id = '".$this->get_ref_id()."'";
+	  		$sql = 'SELECT thread_qualify_max FROM '.Database :: get_course_table(TABLE_FORUM_THREAD, $database_name)." 
+	  				WHERE c_id = ".$course_info['real_id']." AND thread_id = '".$this->get_ref_id()."'";
 			$query = Database::query($sql);
 			$assignment = Database::fetch_array($query);
 
-	  	    $sql = 'SELECT * FROM '.$thread_qualify.' WHERE thread_id = '.$this->get_ref_id();
-
+	  	    $sql = "SELECT * FROM $thread_qualify WHERE c_id = ".$course_info['real_id']." AND thread_id = ".$this->get_ref_id();
 	    	if (isset($stud_id)) {
 	    		$sql .= ' AND user_id = '."'".intval($stud_id)."'";
 	    	}

+ 6 - 7
main/gradebook/lib/be/learnpathlink.class.php

@@ -83,12 +83,12 @@ class LearnpathLink extends AbstractLink
     /**
      * Has anyone used this learnpath yet ?
      */
-    public function has_results()
-    {
+    public function has_results() {
+    	
     	$course_info = api_get_course_info($this->get_course_code());
     	$tbl_stats = Database::get_course_table(TABLE_LP_VIEW,$course_info['dbName']);
-		$sql = 'SELECT count(id) AS number FROM '.$tbl_stats
-				." WHERE lp_id = '".$this->get_ref_id()."'";
+		$sql = "SELECT count(id) AS number FROM $tbl_stats
+				WHERE c_id = {$course_info['real_id']} AND lp_id = ".$this->get_ref_id();
     	$result = Database::query($sql);
 		$number=Database::fetch_array($result,'NUM');
 		return ($number[0] != 0);
@@ -104,12 +104,11 @@ class LearnpathLink extends AbstractLink
     public function calc_score($stud_id = null)
     {
     	$course_info = api_get_course_info($this->get_course_code());
-    	$tbl_stats = Database::get_course_table(TABLE_LP_VIEW,$course_info['dbName']);
+    	$tbl_stats = Database::get_course_table(TABLE_LP_VIEW);
     	if (is_null($course_info['dbName'])===true) {
 			return false;
 		}
-    	$sql = 'SELECT * FROM '.$tbl_stats
-    			." WHERE lp_id = ".$this->get_ref_id();
+    	$sql = "SELECT * FROM $tbl_stats WHERE c_id = {$course_info['real_id']} AND lp_id = ".$this->get_ref_id();
 
     	if (isset($stud_id))
     		$sql .= ' AND user_id = '.intval($stud_id);

+ 11 - 4
main/gradebook/lib/be/studentpublicationlink.class.php

@@ -101,9 +101,10 @@ class StudentPublicationLink extends AbstractLink
      		die('Error in get_not_created_links() : course code not set');
     	}
     	$course_info = api_get_course_info($this->course_code);
-    	$tbl_grade_links = Database :: get_course_table(TABLE_STUDENT_PUBLICATION,$course_info['dbName']);
+    	$tbl_grade_links = Database :: get_course_table(TABLE_STUDENT_PUBLICATION, $course_info['dbName']);
 
-		$sql = "SELECT id,url FROM $tbl_grade_links WHERE has_properties != '' AND filetype='folder' AND session_id = ".api_get_session_id()."";
+		$sql = "SELECT id, url FROM $tbl_grade_links 
+				WHERE c_id = {$course_info['real_id']} AND has_properties != '' AND filetype='folder' AND session_id = ".api_get_session_id()."";
 		$result = Database::query($sql);
 		while ($data=Database::fetch_array($result)) {
 			$cats[] = array ($data['id'], basename($data['url']));
@@ -118,7 +119,10 @@ class StudentPublicationLink extends AbstractLink
     public function has_results() {
     	$course_info = api_get_course_info($this->course_code);
     	$tbl_grade_links = Database :: get_course_table(TABLE_STUDENT_PUBLICATION,$course_info['dbName']);
-		$sql = 'SELECT count(*) AS number FROM '.$tbl_grade_links." WHERE parent_id = '".intval($this->get_ref_id())."' AND session_id=".api_get_session_id()."";
+		$sql = 'SELECT count(*) AS number FROM '.$tbl_grade_links." 
+				WHERE 	c_id 		= {$course_info['real_id']} AND 
+						parent_id 	= '".intval($this->get_ref_id())."' AND 
+						session_id	=".api_get_session_id()."";
     	$result = Database::query($sql);
 		$number=Database::fetch_row($result);
 		return ($number[0] != 0);
@@ -132,7 +136,10 @@ class StudentPublicationLink extends AbstractLink
 		if (is_null($database_name)===true) {
 			return false;
 		}
-    	$sql = 'SELECT * FROM '.$tbl_stats." WHERE id = '".intval($this->get_ref_id())."' AND session_id=".api_get_session_id()."";
+    	$sql = 'SELECT * FROM '.$tbl_stats." 
+    			WHERE 	c_id 		= {$course_info['real_id']} AND  
+    					id 			= '".intval($this->get_ref_id())."' AND 
+    					session_id	= ".api_get_session_id()."";
 		$query = Database::query($sql);
 		$assignment = Database::fetch_array($query);
 

+ 9 - 5
main/gradebook/lib/be/surveylink.class.php

@@ -107,9 +107,11 @@ class SurveyLink extends AbstractLink
 
 			$get_individual_score = !is_null($stud_id);
 
-			$sql = 'SELECT COUNT(i.answered) FROM '.$tbl_survey.' AS s JOIN '.$tbl_survey_invitation.' AS i
-				ON s.code = i.survey_code
-				WHERE s.survey_id = '.$ref_id.' AND i.session_id = '.$session_id;
+			$sql = "SELECT COUNT(i.answered) FROM $tbl_survey AS s JOIN $tbl_survey_invitation AS i ON s.code = i.survey_code
+					WHERE 	s.c_id = {$course_info['real_id']} AND
+							i.c_id = {$course_info['real_id']} AND 
+							s.survey_id = $ref_id AND 
+							i.session_id = $session_id";
 
 			$sql_result = Database::query($sql);
 			$data = Database::fetch_array($sql_result);
@@ -136,9 +138,11 @@ class SurveyLink extends AbstractLink
 
 			$get_individual_score = !is_null($stud_id);
 
-			$sql = 'SELECT i.answered FROM '.$tbl_survey.' AS s JOIN '.$tbl_survey_invitation.' AS i
+			$sql = "SELECT i.answered FROM $tbl_survey AS s JOIN $tbl_survey_invitation AS i
 				ON s.code = i.survey_code
-				WHERE s.survey_id = '.$ref_id.' AND i.session_id = '.$session_id;
+				WHERE 	s.c_id = {$course_info['real_id']} AND
+						i.c_id = {$course_info['real_id']} AND 
+						s.survey_id = $ref_id AND i.session_id = $session_id";
 
 			if ($get_individual_score) {
 	    		$sql .= ' AND i.user = '.intval($stud_id);

+ 20 - 4
main/gradebook/lib/gradebook_functions.inc.php

@@ -359,14 +359,30 @@ function remove_resource_from_course_gradebook($link_id) {
  * @return   String
  */
 function get_database_name_by_link_id($id_link) {
-	$course_table = Database::get_main_table(TABLE_MAIN_COURSE);
-	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
-	$res=Database::query('SELECT db_name FROM '.$course_table.' c INNER JOIN '.$tbl_grade_links.' l
-			ON c.code=l.course_code WHERE l.id='.intval($id_link).' OR l.category_id='.intval($id_link));
+	$course_table 		= Database::get_main_table(TABLE_MAIN_COURSE);
+	$tbl_grade_links 	= Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+	$sql = 'SELECT db_name FROM '.$course_table.' c INNER JOIN '.$tbl_grade_links.' l
+			ON c.code=l.course_code WHERE l.id='.intval($id_link).' OR l.category_id='.intval($id_link);	
+	$res=Database::query($sql);
 	$my_db_name=Database::fetch_array($res,'ASSOC');
 	return $my_db_name['db_name'];
 }
 
+/**
+* Return the course id
+* @param    int
+* @return   String
+*/
+function get_course_id_by_link_id($id_link) {
+	$course_table 		= Database::get_main_table(TABLE_MAIN_COURSE);
+	$tbl_grade_links 	= Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+	$sql = 'SELECT c.id FROM '.$course_table.' c INNER JOIN '.$tbl_grade_links.' l
+			ON c.code = l.course_code WHERE l.id='.intval($id_link).' OR l.category_id='.intval($id_link);	
+	$res = Database::query($sql);
+	$array = Database::fetch_array($res,'ASSOC');
+	return $array['id'];
+}
+
 function get_table_type_course($type,$course) {
 	global $_configuration;
 	global $table_evaluated;

+ 1 - 1
main/gradebook/lib/scoredisplay.class.php

@@ -364,7 +364,7 @@ class ScoreDisplay
 	}
 
 	private function load_int_setting ($property, $default = 0) {
-    	$tbl_setting = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
+    	$tbl_setting = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
         $property    = Database::escape_string($property);
         $default     = Database::escape_string($default);
 		$sql = "SELECT selected_value FROM $tbl_setting WHERE category = 'Gradebook' AND variable = '".$property."'";

+ 3 - 12
main/inc/ajax/exercise.ajax.php

@@ -50,12 +50,7 @@ switch ($action) {
             
             //There is a reminder?
             $remind_list             = isset($_REQUEST['remind_list']) && !empty($_REQUEST['remind_list'])? array_keys($_REQUEST['remind_list']) : null;
-            /*
-            //Lp ids
-            $safe_lp_id              = $_REQUEST['learnpath_id'];  
-            $safe_lp_item_id         = $_REQUEST['learnpath_item_id'];
-            $safe_lp_item_view_id    = $_REQUEST['learnpath_item_view_id'];*/
-            
+               
             $exe_id = $_REQUEST['exe_id'];
             
             //Exercise information            
@@ -66,13 +61,9 @@ switch ($action) {
             if (empty($question_list) || empty($objExercise)) {
                 echo 0;
                 exit;
-            }          
-                 
-            
+            }            
             //Getting information of the current exercise    
-            //$exercise_stat_info = $objExercise->get_stat_track_exercise_info($safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id);
-            $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id($exe_id);
-            
+            $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id($exe_id);           
             
             $attempt_list = array();
               

+ 9 - 16
main/inc/ajax/social.ajax.php

@@ -134,20 +134,13 @@ switch ($action) {
 		
 		switch ($action) {
 			case 'load_course' :
-				$course_db =  $_POST['course_code'];				
-				$course_id = CourseManager::get_course_id_by_database_name($course_db);
-	
-				if (api_is_user_of_course($course_id, api_get_user_id())) {
-	
-					$table_forums 			= Database :: get_course_table(TABLE_FORUM,$course_db);
-					$table_threads 			= Database :: get_course_table(TABLE_FORUM_THREAD,$course_db);
-					$table_posts 			= Database :: get_course_table(TABLE_FORUM_POST,$course_db);
-					$table_item_property 	= Database :: get_course_table(TABLE_ITEM_PROPERTY,$course_db);
-					$table_users 			= Database :: get_main_table(TABLE_MAIN_USER);
-	
-					//------Forum messages
-	
-					$forum_result = get_all_post_from_user($user_id, $course_db);
+				$course_id =  intval($_POST['course_code']); // the int course id
+				$course_info = api_get_course_info_by_id($course_id);				
+				$course_code = $course_info['code'];
+					
+				if (api_is_user_of_course($course_code, api_get_user_id())) {	
+					//------Forum messages	
+					$forum_result = get_all_post_from_user($user_id, $course_code);
 					$all_result_data = 0;
 					if ($forum_result !='') {
 						echo '<div id="social-forum-main-title">';
@@ -162,7 +155,7 @@ switch ($action) {
 					}
 	
 					//------Blog posts
-					$result = get_blog_post_from_user($course_db, $user_id);
+					$result = get_blog_post_from_user($course_code, $user_id);
 					if (!empty($result)) {
 						api_display_tool_title(api_xml_http_response_encode(get_lang('Blog')));
 						echo '<div style="background:#FAF9F6; padding:0px;">';
@@ -173,7 +166,7 @@ switch ($action) {
 					}
 	
 					//------Blog comments
-					$result = get_blog_comment_from_user($course_db, $user_id);
+					$result = get_blog_comment_from_user($course_code, $user_id);
 					if (!empty($result)) {
 						echo '<div  style="background:#FAF9F6; padding-left:10px;">';
 						api_display_tool_title(api_xml_http_response_encode(get_lang('BlogComments')));

+ 2 - 1
main/inc/introductionSection.inc.php

@@ -81,6 +81,7 @@ $form->add_html_editor('intro_content', null, null, false, $editor_config);
 $form->addElement('style_submit_button', 'intro_cmdUpdate', get_lang('SaveIntroText'), 'class="save"');
 
 /*	INTRODUCTION MICRO MODULE - COMMANDS SECTION (IF ALLOWED) */
+$course_id = api_get_course_int_id();
 
 if ($intro_editAllowed) {
 	$moduleId = Database::escape_string($moduleId);
@@ -91,7 +92,7 @@ if ($intro_editAllowed) {
 			$form_values = $form->exportValues();
 			$intro_content = Security::remove_XSS(stripslashes(api_html_entity_decode($form_values['intro_content'])), COURSEMANAGERLOWSECURITY);			
 			if (!empty($intro_content)) {
-				$sql = "REPLACE $TBL_INTRODUCTION SET id='$moduleId',intro_text='".Database::escape_string($intro_content)."', session_id='".intval($session_id)."'";				
+				$sql = "REPLACE $TBL_INTRODUCTION SET c_id = $course_id, id='$moduleId',intro_text='".Database::escape_string($intro_content)."', session_id='".intval($session_id)."'";				
 				Database::query($sql);
 				Display::display_confirmation_message(get_lang('IntroductionTextUpdated'), false);
 			} else {

File diff suppressed because it is too large
+ 180 - 124
main/inc/lib/add_course.lib.inc.php


+ 43 - 17
main/inc/lib/attendance.lib.php

@@ -19,13 +19,16 @@ class Attendance
 	private $description;
 	private $attendance_qualify_title;
 	private $attendance_weight;
+	private $course_int_id;
 
     // constants
 	const DONE_ATTENDANCE_LOG_TYPE = 'done_attendance_sheet';
     const UPDATED_ATTENDANCE_LOG_TYPE = 'updated_attendance_sheet';
     const LOCKED_ATTENDANCE_LOG_TYPE = 'locked_attendance_sheet';
 
-	public function __construct() {}
+	public function __construct() {
+		$this->course_int_id = api_get_course_int_id();
+	}
 
 	/**
 	 * Get the total number of attendance inside current course and current session
@@ -58,8 +61,8 @@ class Attendance
 			$tbl_attendance = Database :: get_course_table(TABLE_ATTENDANCE, $course_db_name);
 		}
 
-                $session_id = isset($session_id)?intval($session_id):api_get_session_id();
-                $condition_session = api_get_session_condition($session_id);
+        $session_id = isset($session_id)?intval($session_id):api_get_session_id();
+        $condition_session = api_get_session_condition($session_id);
 
 		// Get attendance data
 		$sql = "SELECT id, name, attendance_qualify_max FROM $tbl_attendance WHERE active = 1 $condition_session ";
@@ -201,12 +204,13 @@ class Attendance
 		$table_link 	= Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 		$session_id 	= api_get_session_id();
 		$user_id 		= api_get_user_id();
-		$course_code	= api_get_course_id();
+		$course_code	= api_get_course_id();		
 		$title_gradebook= Database::escape_string($this->attendance_qualify_title);
 		$value_calification  = 0;
 		$weight_calification =	floatval($this->attendance_weight);
-		$sql = "INSERT INTO $tbl_attendance
-				SET name ='".Database::escape_string($this->name)."',
+		$sql = "INSERT INTO $tbl_attendance SET
+					c_id =  $this->course_int_id, 
+					name ='".Database::escape_string($this->name)."',
 					description = '".Database::escape_string($this->description)."',
 					attendance_qualify_title = '$title_gradebook',
 					attendance_weight = '$weight_calification',
@@ -249,8 +253,7 @@ class Attendance
 		$title_gradebook	 = Database::escape_string($this->attendance_qualify_title);
 		$value_calification  = 0;
 		$weight_calification =	floatval($this->attendance_weight);
-
-
+		
 		$sql = "UPDATE $tbl_attendance
 				SET name ='".Database::escape_string($this->name)."',
 					description = '".Database::escape_string($this->description)."',
@@ -427,9 +430,13 @@ class Attendance
 			$uid = intval($user_present);
 			// check if user already was registered with the $calendar_id
 			$sql = "SELECT user_id FROM $tbl_attendance_sheet WHERE user_id='$uid' AND attendance_calendar_id = '$calendar_id'";
-			$rs  = Database::query($sql);
+			$rs  = Database::query($sql);			
 			if (Database::num_rows($rs) == 0) {
-				$sql = "INSERT INTO $tbl_attendance_sheet SET user_id ='$uid', attendance_calendar_id = '$calendar_id', presence = 1";
+				$sql = "INSERT INTO $tbl_attendance_sheet SET 
+						c_id					= $this->course_int_id, 
+						user_id 				= '$uid', 
+						attendance_calendar_id 	= '$calendar_id', 
+						presence 				= 1";
 				Database::query($sql);
 				$affected_rows += Database::affected_rows();
 			} else {
@@ -446,7 +453,11 @@ class Attendance
 			$sql = "SELECT user_id FROM $tbl_attendance_sheet WHERE user_id='$uid' AND attendance_calendar_id = '$calendar_id'";
 			$rs  = Database::query($sql);
 			if (Database::num_rows($rs) == 0) {
-				$sql = "INSERT INTO $tbl_attendance_sheet SET user_id ='$uid', attendance_calendar_id = '$calendar_id', presence = 0";
+				$sql = "INSERT INTO $tbl_attendance_sheet SET
+						c_id = $this->course_int_id, 
+						user_id ='$uid', 
+						attendance_calendar_id = '$calendar_id', 
+						presence = 0";
 				Database::query($sql);
 				$affected_rows += Database::affected_rows();
 			} else {
@@ -509,11 +520,17 @@ class Attendance
 				$rs_check_result = Database::query($sql);
 				if (Database::num_rows($rs_check_result) > 0) {
 					// update result
-					$sql = "UPDATE $tbl_attendance_result SET score='$count_presences' WHERE user_id='$uid' AND attendance_id='$attendance_id'";
+					$sql = "UPDATE $tbl_attendance_result SET 
+							score='$count_presences' 
+							WHERE user_id='$uid' AND attendance_id='$attendance_id'";
 					Database::query($sql);
 				} else {
 					// insert new result
-					$sql = "INSERT INTO $tbl_attendance_result SET user_id='$uid', attendance_id = '$attendance_id', score='$count_presences'";
+					$sql = "INSERT INTO $tbl_attendance_result SET
+								c_id = $this->course_int_id , 
+								user_id			= '$uid', 
+								attendance_id 	= '$attendance_id', 
+								score			= '$count_presences'";
 					Database::query($sql);
 				}
 			}
@@ -552,8 +569,8 @@ class Attendance
             }
 
             // save data
-            $ins = "INSERT INTO $tbl_attendance_sheet_log(attendance_id, lastedit_date, lastedit_type, lastedit_user_id, calendar_date_value)
-                    VALUES($attendance_id, '$lastedit_date', '$lastedit_type', $lastedit_user_id, '$calendar_date_value')";
+            $ins = "INSERT INTO $tbl_attendance_sheet_log(c_id, attendance_id, lastedit_date, lastedit_type, lastedit_user_id, calendar_date_value)
+                    VALUES($this->course_int_id, $attendance_id, '$lastedit_date', '$lastedit_type', $lastedit_user_id, '$calendar_date_value')";
 
             Database::query($ins);
 
@@ -725,6 +742,8 @@ class Attendance
 		foreach ($attendance_calendar as $cal) {
 			$calendar_ids[] = $cal['id'];
 		}
+		
+		$course_id = api_get_course_int_id();
 
 		$data = array();
 		if (empty($user_id)) {
@@ -746,7 +765,11 @@ class Attendance
 			// get attendance for current user
 			$user_id = intval($user_id);
 			if (count($calendar_ids) > 0) {
-				$sql = "SELECT cal.date_time, att.presence FROM $tbl_attendance_sheet att INNER JOIN  $tbl_attendance_calendar cal ON cal.id = att.attendance_calendar_id WHERE att.user_id = '$user_id' AND att.attendance_calendar_id IN(".implode(',',$calendar_ids).") ";
+				$sql = "SELECT cal.date_time, att.presence FROM $tbl_attendance_sheet att INNER JOIN  $tbl_attendance_calendar cal ON cal.id = att.attendance_calendar_id 
+						WHERE 	att.c_id = $course_id AND
+								cal.c_id =  $course_id AND
+								att.user_id = '$user_id' AND 
+								att.attendance_calendar_id IN(".implode(',',$calendar_ids).") ";
 				$res = Database::query($sql);
 				if (Database::num_rows($res) > 0) {
 					while ($row = Database::fetch_array($res)) {
@@ -982,7 +1005,10 @@ class Attendance
 		$sql = "SELECT id FROM $tbl_attendance_calendar WHERE date_time='".Database::escape_string($this->date_time)."' AND attendance_id = '$attendance_id'";
 		$rs = Database::query($sql);
 		if (Database::num_rows($rs) == 0) {
-			$sql = "INSERT INTO $tbl_attendance_calendar SET date_time='".Database::escape_string($this->date_time)."', attendance_id = '$attendance_id'";
+			$sql = "INSERT INTO $tbl_attendance_calendar SET
+					c_id			= $this->course_int_id,  
+					date_time		= '".Database::escape_string($this->date_time)."', 
+					attendance_id 	= '$attendance_id'";
 			Database::query($sql);
 			$affected_rows = Database::affected_rows();
 		}

+ 235 - 258
main/inc/lib/blog.lib.php

@@ -68,18 +68,16 @@ class Blog {
 	 */
 	public static function get_blog_users ($blog_id) {
 		// Database table definitions
-		$tbl_users = Database::get_main_table(TABLE_MAIN_USER);
-		$tbl_blogs = Database::get_course_table(TABLE_BLOGS);
+		$tbl_users = Database::get_main_table(TABLE_MAIN_USER);		
 		$tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
+		
+		$course_id = api_get_course_int_id();
 
 		// Get blog members
-		$sql = "SELECT
-				user.user_id,
-				user.firstname,
-				user.lastname
-			FROM " . $tbl_blogs_rel_user . " blogs_rel_user
-			INNER JOIN " . $tbl_users . " user ON blogs_rel_user.user_id = user.user_id
-			WHERE blogs_rel_user.blog_id = '" . Database::escape_string((int)$blog_id)."'";
+		$sql = "SELECT user.user_id, user.firstname, user.lastname 
+				FROM " . $tbl_blogs_rel_user . " blogs_rel_user INNER JOIN " . $tbl_users . " user ON blogs_rel_user.user_id = user.user_id
+				WHERE	blogs_rel_user.c_id = $course_id AND						
+						blogs_rel_user.blog_id = '" . (int)$blog_id."'";
 		$result = Database::query($sql);
 		$blog_members = array ();
 		while($user = Database::fetch_array($result)) {
@@ -110,10 +108,12 @@ class Blog {
 		$sql='SELECT COUNT(*) as count FROM '.$tbl_blogs.'  WHERE blog_name="'.Database::escape_string($title).'" AND blog_subtitle="'.Database::escape_string($subtitle).'";';
 		$res=Database::query($sql);
 		$info_count=Database::result($res,0,0);
+		$course_id = api_get_course_int_id();
+		
 		if ($info_count==0) {
 			// Create the blog
-			$sql = "INSERT INTO $tbl_blogs (blog_name, blog_subtitle, date_creation, visibility, session_id )
-						VALUES ('".Database::escape_string($title)."', '".Database::escape_string($subtitle)."', '".$current_date."', '1', '$session_id');";
+			$sql = "INSERT INTO $tbl_blogs (c_id, blog_name, blog_subtitle, date_creation, visibility, session_id )
+					VALUES ($course_id, '".Database::escape_string($title)."', '".Database::escape_string($subtitle)."', '".$current_date."', '1', '$session_id');";
 			Database::query($sql);
 			$this_blog_id = Database::insert_id();
 
@@ -123,13 +123,13 @@ class Blog {
 			}
 
 			// Make first post. :)
-			$sql = "INSERT INTO $tbl_blogs_posts (title, full_text, date_creation, blog_id, author_id )
-						VALUES ('".get_lang("Welcome")."', '" . get_lang('FirstPostText')."','".$current_date."', '".Database::escape_string((int)$this_blog_id)."', '".Database::escape_string((int)$_user['user_id'])."');";
+			$sql = "INSERT INTO $tbl_blogs_posts (c_id, title, full_text, date_creation, blog_id, author_id )
+						VALUES ($course_id, '".get_lang("Welcome")."', '" . get_lang('FirstPostText')."','".$current_date."', '".Database::escape_string((int)$this_blog_id)."', '".Database::escape_string((int)$_user['user_id'])."');";
 			Database::query($sql);
 
 			// Put it on course homepage
-			$sql = "INSERT INTO $tbl_tool (name, link, image, visibility, admin, address, added_tool, session_id)
-						VALUES ('".Database::escape_string($title)."','blog/blog.php?blog_id=".(int)$this_blog_id."','blog.gif','1','0','pastillegris.gif',0,'$session_id')";
+			$sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, session_id)
+						VALUES ($course_id, '".Database::escape_string($title)."','blog/blog.php?blog_id=".(int)$this_blog_id."','blog.gif','1','0','pastillegris.gif',0,'$session_id')";
 			Database::query($sql);
 
 			// Subscribe the teacher to this blog
@@ -225,6 +225,9 @@ class Blog {
 		$upload_ok=true;
 		$has_attachment=false;
 		$current_date=date('Y-m-d H:i:s',time());
+		
+		$course_id = api_get_course_int_id();
+		
 
 		if(!empty($_FILES['user_upload']['name'])) {
 			require_once('fileUpload.lib.php');
@@ -237,8 +240,8 @@ class Blog {
 			$tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
 
 			// Create the post
-			$sql = "INSERT INTO " . $tbl_blogs_posts." (title, full_text, date_creation, blog_id, author_id )
-					VALUES ('".Database::escape_string($title)."', '".Database::escape_string($full_text)."','".$current_date."', '".(int)$blog_id."', '".(int)$_user['user_id']."');";
+			$sql = "INSERT INTO $tbl_blogs_posts (c_id, title, full_text, date_creation, blog_id, author_id )
+					VALUES ($course_id, '".Database::escape_string($title)."', '".Database::escape_string($full_text)."','".$current_date."', '".(int)$blog_id."', '".(int)$_user['user_id']."');";
 
 			Database::query($sql);
 			$last_post_id=Database::insert_id();
@@ -267,16 +270,15 @@ class Blog {
 
 					// Storing the attachments if any
 					if ($result) {
-						$sql='INSERT INTO '.$blog_table_attachment.'(filename,comment, path, post_id,size, blog_id,comment_id) '.
-							 "VALUES ( '".Database::escape_string($file_name)."', '".Database::escape_string($comment)."', '".Database::escape_string($new_file_name)."' , '".$last_post_id."', '".intval($_FILES['user_upload']['size'])."',  '".$blog_id."', '0' )";
+						$sql='INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size, blog_id,comment_id) '.
+							 "VALUES ($course_id, '".Database::escape_string($file_name)."', '".Database::escape_string($comment)."', '".Database::escape_string($new_file_name)."' , '".$last_post_id."', '".intval($_FILES['user_upload']['size'])."',  '".$blog_id."', '0' )";
 						$result=Database::query($sql);
 						$message.=' / '.get_lang('AttachmentUpload');
+						exit;
 					}
 				}
 			}
-		}
-		else
-		{
+		} else {
 			Display::display_error_message(get_lang('UplNoFileUploaded'));
 		}
 	}
@@ -340,9 +342,10 @@ class Blog {
 		global $_course;
 		global $blog_table_attachment;
 
-		$upload_ok=true;
-		$has_attachment=false;
-		$current_date=date('Y-m-d H:i:s',time());
+		$upload_ok			= true;
+		$has_attachment		= false;
+		$current_date		= date('Y-m-d H:i:s',time());
+		$course_id 			= api_get_course_int_id();
 
 		if(!empty($_FILES['user_upload']['name']))
 		{
@@ -351,14 +354,13 @@ class Blog {
 			$has_attachment=true;
 		}
 
-		if($upload_ok)
-		{
+		if ($upload_ok) {
 			// Table Definition
 			$tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
 
 			// Create the comment
-			$sql = "INSERT INTO $tbl_blogs_comments (title, comment, author_id, date_creation, blog_id, post_id, parent_comment_id, task_id )
-						VALUES ('".Database::escape_string($title)."', '".Database::escape_string($full_text)."', '".(int)$_user['user_id']."','".$current_date."', '".(int)$blog_id."', '".(int)$post_id."', '".(int)$parent_id."', '".(int)$task_id."')";
+			$sql = "INSERT INTO $tbl_blogs_comments (c_id, title, comment, author_id, date_creation, blog_id, post_id, parent_comment_id, task_id )
+					VALUES ($course_id, '".Database::escape_string($title)."', '".Database::escape_string($full_text)."', '".(int)$_user['user_id']."','".$current_date."', '".(int)$blog_id."', '".(int)$post_id."', '".(int)$parent_id."', '".(int)$task_id."')";
 			Database::query($sql);
 
 			// Empty post values, or they are shown on the page again
@@ -393,8 +395,8 @@ class Blog {
 					// Storing the attachments if any
 					if ($result)
 					{
-						$sql='INSERT INTO '.$blog_table_attachment.'(filename,comment, path, post_id,size,blog_id,comment_id) '.
-							 "VALUES ( '".Database::escape_string($file_name)."', '".Database::escape_string($comment)."', '".Database::escape_string($new_file_name)."' , '".$post_id."', '".$_FILES['user_upload']['size']."',  '".$blog_id."', '".$last_id."'  )";
+						$sql='INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size,blog_id,comment_id) '.
+							 "VALUES ($course_id, '".Database::escape_string($file_name)."', '".Database::escape_string($comment)."', '".Database::escape_string($new_file_name)."' , '".$post_id."', '".$_FILES['user_upload']['size']."',  '".$blog_id."', '".$last_id."'  )";
 						$result=Database::query($sql);
 						$message.=' / '.get_lang('AttachmentUpload');
 					}
@@ -450,55 +452,42 @@ class Blog {
 		// Init
 		$tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
 		$tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS);
+		
+		$course_id = api_get_course_int_id();
 
 		// Create the task
-		$sql = "INSERT INTO $tbl_blogs_tasks (blog_id, title, description, color, system_task )
-					VALUES ('".(int)$blog_id."', '" . Database::escape_string($title)."', '" . Database::escape_string($description)."', '" . Database::escape_string($color)."', '0');";
+		$sql = "INSERT INTO $tbl_blogs_tasks (c_id, blog_id, title, description, color, system_task )
+				VALUES ($course_id , '".(int)$blog_id."', '" . Database::escape_string($title)."', '" . Database::escape_string($description)."', '" . Database::escape_string($color)."', '0');";
 		Database::query($sql);
 
 		$task_id = Database::insert_id();
 		$tool = 'BLOG_' . $blog_id;
 
-		if($articleDelete == 'on')
-		{
-			$sql = "
-				INSERT INTO " . $tbl_tasks_permissions . " (
-					task_id,
-					tool,
-					action
-				) VALUES (
+		if ($articleDelete == 'on') {
+			$sql = " INSERT INTO " . $tbl_tasks_permissions . " ( c_id,  task_id, tool, action) VALUES (
+					'" . (int)$course_id . "',
 					'" . (int)$task_id . "',
 					'" . Database::escape_string($tool) . "',
 					'article_delete'
 				)";
-
 			Database::query($sql);
 		}
 
-		if($articleEdit == 'on')
-		{
+		if($articleEdit == 'on') {
 			$sql = "
-				INSERT INTO " . $tbl_tasks_permissions . " (
-					task_id,
-					tool,
-					action
-				) VALUES (
+				INSERT INTO " . $tbl_tasks_permissions . " (c_id, task_id, tool, action ) VALUES (
+					'" . (int)$course_id . "',
 					'" . (int)$task_id . "',
 					'" . Database::escape_string($tool) . "',
 					'article_edit'
 				)";
-
 			Database::query($sql);
 		}
 
-		if($commentsDelete == 'on')
-		{
+		if($commentsDelete == 'on') {
 			$sql = "
-				INSERT INTO " . $tbl_tasks_permissions . " (
-					task_id,
-					tool,
-					action
-				) VALUES (
+				INSERT INTO " . $tbl_tasks_permissions . " (c_id, task_id, tool, action ) VALUES (
+					'" . (int)$course_id . "',
 					'" . (int)$task_id . "',
 					'" . Database::escape_string($tool) . "',
 					'article_comments_delete'
@@ -531,20 +520,14 @@ class Blog {
 
 		$tool = 'BLOG_' . $blog_id;
 
-		$sql = "
-			DELETE FROM " . $tbl_tasks_permissions . "
-			WHERE task_id = '" . (int)$task_id."'";
-
+		$sql = "DELETE FROM " . $tbl_tasks_permissions . " WHERE task_id = '" . (int)$task_id."'";
 		Database::query($sql);
+		
+		$course_id = api_get_course_int_id();
 
-		if($articleDelete == 'on')
-		{
-			$sql = "
-				INSERT INTO " . $tbl_tasks_permissions . " (
-					task_id,
-					tool,
-					action
-				) VALUES (
+		if($articleDelete == 'on') {
+			$sql = "INSERT INTO " . $tbl_tasks_permissions . " ( c_id, task_id, tool, action) VALUES (
+					'" . (int)$course_id . "',
 					'" . (int)$task_id . "',
 					'" . Database::escape_string($tool) . "',
 					'article_delete'
@@ -553,35 +536,23 @@ class Blog {
 			Database::query($sql);
 		}
 
-		if($articleEdit == 'on')
-		{
-			$sql = "
-				INSERT INTO " . $tbl_tasks_permissions . " (
-					task_id,
-					tool,
-					action
-				) VALUES (
+		if($articleEdit == 'on') {
+			$sql = "INSERT INTO " . $tbl_tasks_permissions . " (c_id, task_id, tool, action) VALUES (
+					'" . (int)$course_id . "',
 					'" . (int)$task_id . "',
 					'" . Database::escape_string($tool) . "',
 					'article_edit'
 				)";
-
 			Database::query($sql);
 		}
 
-		if($commentsDelete == 'on')
-		{
-			$sql = "
-				INSERT INTO " . $tbl_tasks_permissions . " (
-					task_id,
-					tool,
-					action
-				) VALUES (
+		if($commentsDelete == 'on') {
+			$sql = " INSERT INTO " . $tbl_tasks_permissions . " (c_id, task_id, tool, action) VALUES (
+					'" . (int)$course_id . "',
 					'" . (int)$task_id . "',
 					'" . Database::escape_string($tool) . "',
 					'article_comments_delete'
 				)";
-
 			Database::query($sql);
 		}
 	}
@@ -622,24 +593,29 @@ class Blog {
 		global $_user;
 
 		// Init
-		$tbl_blogs = Database::get_course_table(TABLE_BLOGS);
-		$tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
-		$tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
+		$tbl_blogs 					= Database::get_course_table(TABLE_BLOGS);
+		$tbl_blogs_tasks_rel_user 	= Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
+		$tbl_blogs_tasks 			= Database::get_course_table(TABLE_BLOGS_TASKS);
+		
+		$course_id = api_get_course_int_id();
 
-		if($_user['user_id'])
-		{
+		if($_user['user_id']) {
 			$sql = "SELECT task_rel_user.*, task.title, blog.blog_name FROM $tbl_blogs_tasks_rel_user task_rel_user
 			INNER JOIN $tbl_blogs_tasks task ON task_rel_user.task_id = task.task_id
 			INNER JOIN $tbl_blogs blog ON task_rel_user.blog_id = blog.blog_id
 			AND blog.blog_id = ".intval($_GET['blog_id'])."
-			WHERE task_rel_user.user_id = ".(int)$_user['user_id']." ORDER BY target_date ASC";
+			WHERE
+				task.c_id = $course_id AND
+				blog.c_id = $course_id AND
+				task_rel_user.c_id = $course_id AND				 
+				task_rel_user.user_id = ".(int)$_user['user_id']."				 
+			ORDER BY target_date ASC";
+			
 			$result = Database::query($sql);
 
-			if (Database::num_rows($result) > 0)
-			{
+			if (Database::num_rows($result) > 0) {
 				echo '<ul>';
-				while($mytask = Database::fetch_array($result))
-				{
+				while($mytask = Database::fetch_array($result)) {
 					echo '<li><a href="blog.php?action=execute_task&amp;blog_id=' . $mytask['blog_id'] . '&amp;task_id='.stripslashes($mytask['task_id']) . '" title="[Blog: '.stripslashes($mytask['blog_name']) . '] ' . get_lang('ExecuteThisTask') . '">'.stripslashes($mytask['title']) . '</a></li>';
 				}
 				echo '<ul>';
@@ -665,6 +641,7 @@ class Blog {
 		// Init
 		$tbl_blogs = Database::get_course_table(TABLE_BLOGS);
 		$tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
+		$course_id = api_get_course_int_id();
 
 		// Get blog properties
 		$sql = "SELECT blog_name, visibility FROM $tbl_blogs WHERE blog_id='".(int)$blog_id."'";
@@ -688,8 +665,8 @@ class Blog {
 			$sql = "UPDATE $tbl_blogs SET visibility = '1' WHERE blog_id ='".(int)$blog_id."' LIMIT 1";
 			$result = Database::query($sql);
 
-			$sql = "INSERT INTO $tbl_tool (name, link, image, visibility, admin, address, added_tool, target )
-					VALUES ('".Database::escape_string($title)."', 'blog/blog.php?blog_id=".(int)$blog_id."', 'blog.gif', '1', '0', 'pastillegris.gif', '0', '_self')";
+			$sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, target )
+					VALUES ($course_id, '".Database::escape_string($title)."', 'blog/blog.php?blog_id=".(int)$blog_id."', 'blog.gif', '1', '0', 'pastillegris.gif', '0', '_self')";
 			$result = Database::query($sql);
 		}
 	}
@@ -707,13 +684,16 @@ class Blog {
 		$tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
 		$tbl_users = Database::get_main_table(TABLE_MAIN_USER);
 		global $dateFormatLong;
+		
+		$course_id = api_get_course_int_id();
 
 		// Get posts and authors
 		$sql = "SELECT post.*, user.lastname, user.firstname FROM $tbl_blogs_posts post
 					INNER JOIN $tbl_users user ON post.author_id = user.user_id
-					WHERE post.blog_id = '".(int)$blog_id."'
-					AND $filter
-					ORDER BY post_id DESC LIMIT 0,".(int)$max_number_of_posts;
+				WHERE 	post.blog_id = '".(int)$blog_id."' AND
+						post.c_id = $course_id AND
+						$filter
+				ORDER BY post_id DESC LIMIT 0,".(int)$max_number_of_posts;
 		$result = Database::query($sql);
 
 		// Display
@@ -833,12 +813,17 @@ class Blog {
 		$tbl_users = Database::get_main_table(TABLE_MAIN_USER);
 
 		global $charset,$dateFormatLong;
+		
+		$course_id = api_get_course_int_id();
+		
 
 		// Get posts and author
 		$sql = "SELECT post.*, user.lastname, user.firstname FROM $tbl_blogs_posts post
 					INNER JOIN $tbl_users user ON post.author_id = user.user_id
-					WHERE post.blog_id = '".(int)$blog_id."'
-					AND post.post_id = '".(int)$post_id."'
+					WHERE
+						post.c_id = $course_id AND 
+						post.blog_id = '".(int)$blog_id."' AND 
+						post.post_id = '".(int)$post_id."'
 					ORDER BY post_id DESC";
 		$result = Database::query($sql);
 		$blog_post = Database::fetch_array($result);
@@ -924,6 +909,7 @@ class Blog {
 
 		// Init
 		$tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING);
+		$course_id = api_get_course_int_id();
 
 		// Check if the user has already rated this post/comment
 		$sql = "SELECT rating_id FROM $tbl_blogs_rating
@@ -935,8 +921,8 @@ class Blog {
 
 		if(Database::num_rows($result) == 0) // Add rating
 		{
-			$sql = "INSERT INTO $tbl_blogs_rating ( blog_id, rating_type, item_id, user_id, rating )
-						VALUES ('".(int)$blog_id."', '".Database::escape_string($type)."', '".(int)$item_id."', '".(int)$_user['user_id']."', '".Database::escape_string($rating)."')";
+			$sql = "INSERT INTO $tbl_blogs_rating (c_id, blog_id, rating_type, item_id, user_id, rating )
+					VALUES ($course_id, '".(int)$blog_id."', '".Database::escape_string($type)."', '".(int)$item_id."', '".(int)$_user['user_id']."', '".Database::escape_string($rating)."')";
 			$result = Database::query($sql);
 			return true;
 		}
@@ -1031,10 +1017,12 @@ class Blog {
 	 */
 	public static function get_threaded_comments ($current = 0, $current_level = 0, $blog_id, $post_id, $task_id = 0) {
 		// Init
-		$tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS);
-		$tbl_users = Database::get_main_table(TABLE_MAIN_USER);
-		$tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
+		$tbl_blogs_comments 	= Database::get_course_table(TABLE_BLOGS_COMMENTS);
+		$tbl_users 				= Database::get_main_table(TABLE_MAIN_USER);
+		$tbl_blogs_tasks 		= Database::get_course_table(TABLE_BLOGS_TASKS);
 		global $charset,$dateFormatLong;
+		
+		$course_id = api_get_course_int_id();		
 
 		// Select top level comments
 		$next_level = $current_level + 1;
@@ -1042,19 +1030,22 @@ class Blog {
 					FROM $tbl_blogs_comments comments
 						INNER JOIN $tbl_users user ON comments.author_id = user.user_id
 						LEFT JOIN $tbl_blogs_tasks task ON comments.task_id = task.task_id
-					WHERE parent_comment_id = $current
-						AND comments.blog_id = '".(int)$blog_id."'
-						AND comments.post_id = '".(int)$post_id."'";
+					WHERE 	comments.c_id = $course_id AND
+							task.c_id = $course_id AND					
+							parent_comment_id = $current AND 
+							comments.blog_id = '".(int)$blog_id."' AND 
+							comments.post_id = '".(int)$post_id."'";
 		$result = Database::query($sql);
 
-		while($comment = Database::fetch_array($result))
-		{
+		while($comment = Database::fetch_array($result)) {
 			// Select the children recursivly
 			$tmp = "SELECT comments.*, user.lastname, user.firstname FROM $tbl_blogs_comments comments
 					INNER JOIN $tbl_users user ON comments.author_id = user.user_id
-					WHERE comment_id = $current
-					AND blog_id = '".(int)$blog_id."'
-					AND post_id = '".(int)$post_id."'";
+					WHERE
+						comments.c_id = $course_id AND 
+						comment_id = $current
+						AND blog_id = '".(int)$blog_id."'
+						AND post_id = '".(int)$post_id."'";
 			$tmp = Database::query($tmp);
 			$tmp = Database::fetch_array($tmp);
 			$parent_cat = $tmp['parent_comment_id'];
@@ -1067,8 +1058,7 @@ class Blog {
 			if(api_is_allowed('BLOG_' . $blog_id, 'article_comments_delete', $task_id)) { $blog_comment_actions .= '<a href="blog.php?action=view_post&amp;blog_id=' . $blog_id . '&amp;post_id=' . $post_id . '&amp;do=delete_comment&amp;comment_id=' . $comment['comment_id'] . '&amp;task_id=' . $task_id . '" title="' . get_lang('DeleteThisComment') . '" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)). '\')) return false;"><img src="../img/delete.gif" border="0" /></a>'; }
 			if(api_is_allowed('BLOG_' . $blog_id, 'article_comments_rate')) { $rating_select = Blog::display_rating_form('comment', $blog_id, $post_id, $comment['comment_id']); }
 
-			if(!is_null($comment['task_id']))
-			{
+			if(!is_null($comment['task_id'])) {
 				$border_color = ' border-left: 3px solid #' . $comment['color'];
 			}
 
@@ -1265,12 +1255,16 @@ class Blog {
 		// Init
 		$tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
 		$tbl_users = Database::get_main_table(TABLE_MAIN_USER);
-
+		
+		$course_id = api_get_course_int_id();
+		
 		// Get posts and author
 		$sql = "SELECT post.*, user.lastname, user.firstname FROM $tbl_blogs_posts post
 				INNER JOIN $tbl_users user ON post.author_id = user.user_id
-				WHERE post.blog_id = '".(int)$blog_id ."'
-				AND post.post_id = '".(int)$post_id."'
+				WHERE
+				post.c_id 			= $course_id AND 
+				post.blog_id 		= '".(int)$blog_id ."'
+				AND post.post_id	= '".(int)$post_id."'
 				ORDER BY post_id DESC";
 		$result = Database::query($sql);
 		$blog_post = Database::fetch_array($result);
@@ -1287,25 +1281,21 @@ class Blog {
 		echo '<div><span class="form_required">*</span>' . get_lang('Title') . ': <input name="post_title" id="post_title" type="text" size="60" value="'.stripslashes($blog_post['title']) . '" /><br /></div>';
 
 		// article text
-								$oFCKeditor = new FCKeditor('post_full_text') ;
+		$oFCKeditor = new FCKeditor('post_full_text') ;
 
-								$oFCKeditor->Width		= '100%';
-								$oFCKeditor->Height		= '200';
+		$oFCKeditor->Width		= '100%';
+		$oFCKeditor->Height		= '200';
 
-								if(!api_is_allowed_to_edit())
-								{
-									$oFCKeditor->ToolbarSet = 'ProjectStudent';
-								}
-								else
-								{
-									$oFCKeditor->ToolbarSet = 'Project';
-								}
-								$oFCKeditor->Value		= isset($_POST['post_full_text'])?stripslashes($_POST['post_full_text']):$blog_post_text;
+		if(!api_is_allowed_to_edit()) {
+			$oFCKeditor->ToolbarSet = 'ProjectStudent';
+		} else {
+			$oFCKeditor->ToolbarSet = 'Project';
+		}
+		$oFCKeditor->Value		= isset($_POST['post_full_text'])?stripslashes($_POST['post_full_text']):$blog_post_text;
 		echo '<div class="formw">';
 		echo $oFCKeditor->Create();
 		echo '</div>';
-
-
+		
 		// submit
 		echo '	<div class="row">
 					<div class="label">
@@ -1422,18 +1412,21 @@ class Blog {
 				 "<th><b>",get_lang('Description'),"</b></th>\n",
 				 "<th><b>",get_lang('TargetDate'),"</b></th>\n",
 				 "<th width='50'><b>",get_lang('Modify'),"</b></th>\n",
-			"</tr>\n";
-
+			"</tr>";
+		
+		$course_id = api_get_course_int_id();
 
-		$sql = "SELECT task_rel_user.*, task.title, user.firstname, user.lastname, task.description, task.system_task, task.blog_id, task.task_id FROM $tbl_blogs_tasks_rel_user task_rel_user
-		INNER JOIN $tbl_blogs_tasks task ON task_rel_user.task_id = task.task_id
-		INNER JOIN $tbl_users user ON task_rel_user.user_id = user.user_id
-		WHERE task_rel_user.blog_id = '".(int)$blog_id."' ORDER BY target_date ASC";
+		$sql = "SELECT task_rel_user.*, task.title, user.firstname, user.lastname, task.description, task.system_task, task.blog_id, task.task_id 
+				FROM $tbl_blogs_tasks_rel_user task_rel_user
+				INNER JOIN $tbl_blogs_tasks task ON task_rel_user.task_id = task.task_id
+				INNER JOIN $tbl_users user ON task_rel_user.user_id = user.user_id
+				WHERE task_rel_user.c_id = $course_id AND
+						task.c_id = $course_id AND						
+						task_rel_user.blog_id = '".(int)$blog_id."' 
+				ORDER BY target_date ASC";
 		$result = Database::query($sql);
 
-
-		while($assignment = Database::fetch_array($result))
-		{
+		while($assignment = Database::fetch_array($result)) {
 			$counter++;
 			$css_class = (($counter % 2)==0) ? "row_odd" : "row_even";
 			$delete_icon = ($assignment['system_task'] == '1') ? "delete_na.gif" : "delete.gif";
@@ -1659,12 +1652,15 @@ class Blog {
 		$month	= date("m");
 		$year	= date("Y");
 		global $MonthsLong;
+		
+		$course_id = api_get_course_int_id();
+		
 
 		// Get users in this blog / make select list of it
 		$sql = "SELECT user.user_id, user.firstname, user.lastname FROM $tbl_users user
 				INNER JOIN $tbl_blogs_rel_user blogs_rel_user
 				ON user.user_id = blogs_rel_user.user_id
-				WHERE blogs_rel_user.blog_id = '".(int)$blog_id."'";
+				WHERE blogs_rel_user.c_id = $course_id AND blogs_rel_user.blog_id = '".(int)$blog_id."'";
 		$result = Database::query($sql);
 		$select_user_list = '<select name="task_user_id">';
 		while($user = Database::fetch_array($result))
@@ -1793,38 +1789,16 @@ class Blog {
 	 *
 	 */
 	public static function display_edit_assigned_task_form ($blog_id, $task_id, $user_id) {
-		//$parameters = explode('_', $assignment_id);
-		//$task_id = $parameters[0];
-		//$user_id = $parameters[1];
-
-		/* ------------- */
-		// Init
 		$tbl_users 					= Database::get_main_table(TABLE_MAIN_USER);
 		$tbl_blogs_rel_user 		= Database::get_course_table(TABLE_BLOGS_REL_USER);
 		$tbl_blogs_tasks 			= Database::get_course_table(TABLE_BLOGS_TASKS);
 		$tbl_blogs_tasks_rel_user 	= Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
-
+		
+		$course_id = api_get_course_int_id();
+		
 		$year	= date("Y");
 		global $MonthsLong;
 
-		/*// Get assignd tasks of user
-		$sql = "
-			SELECT task_id
-			FROM $tbl_blogs_tasks_rel_user
-			WHERE
-				user_id = $user_id AND
-				blog_id = $blog_id";
-
-		$result = Database::query($sql);
-
-		$arrUserTasks = array();
-
-        while ($row = Database::fetch_assoc($result))
-        {
-            $arrUserTasks[] = $row['task_id'];
-        }
-        */
-
 		// Get assignd date;
 		$sql = "
 			SELECT target_date
@@ -1842,17 +1816,15 @@ class Blog {
 		$sql = "
 			SELECT user.user_id, user.firstname, user.lastname
 			FROM $tbl_users user
-			INNER JOIN $tbl_blogs_rel_user blogs_rel_user on user.user_id = blogs_rel_user.user_id
-			WHERE blogs_rel_user.blog_id = '".(int)$blog_id."'";
+			INNER JOIN $tbl_blogs_rel_user blogs_rel_user O user.user_id = blogs_rel_user.user_id
+			WHERE blogs_rel_user.c_id = $course_id AND blogs_rel_user.blog_id = '".(int)$blog_id."'";
 		$result = Database::query($sql);
 
 		$select_user_list = '<select name="task_user_id">';
-
-		while($user = Database::fetch_array($result))
-		{
+		while($user = Database::fetch_array($result)) {
 			$select_user_list .= '<option ' . (($user_id == $user['user_id']) ? 'selected="selected "' : ' ') . 'value="' . $user['user_id'] . '">' . api_get_person_name($user['firstname'], $user['lastname']) . '</option>';
 		}
-
+		
 		$select_user_list .= '</select>';
 
 		// Get tasks in this blog / make select list of it
@@ -1866,15 +1838,12 @@ class Blog {
 				system_task
 			FROM " . $tbl_blogs_tasks . "
 			WHERE blog_id = " . (int)$blog_id . "
-			ORDER BY
-				system_task,
-				title";
+			ORDER BY system_task, title";
 		$result = Database::query($sql);
 
 		$select_task_list = '<select name="task_task_id">';
 
-		while($task = Database::fetch_array($result))
-		{
+		while($task = Database::fetch_array($result)) {
 			//if(!in_array($task['task_id'], $arrUserTasks) || $task_id == $task['task_id'])
 				$select_task_list .= '<option ' . (($task_id == $task['task_id']) ? 'selected="selected "' : ' ') . 'value="' . $task['task_id'] . '">'.stripslashes($task['title']) . '</option>';
 		}
@@ -1962,6 +1931,7 @@ class Blog {
 	public static function assign_task ($blog_id, $user_id, $task_id, $target_date) {
 		// Init
 		$tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
+		$course_id = api_get_course_int_id();
 
 		$sql = "
 			SELECT COUNT(*) as 'number'
@@ -1974,15 +1944,16 @@ class Blog {
 		$result = @Database::query($sql);
 		$row = Database::fetch_assoc($result);
 
-		if($row['number'] == 0)
-		{
+		if($row['number'] == 0) {
 			$sql = "
 				INSERT INTO " . $tbl_blogs_tasks_rel_user . " (
+					c_id, 
 					blog_id,
 					user_id,
 					task_id,
 					target_date
 				) VALUES (
+					'" . (int)$course_id . "',
 					'" . (int)$blog_id . "',
 					'" . (int)$user_id . "',
 					'" . (int)$task_id . "',
@@ -1996,9 +1967,10 @@ class Blog {
 	public static function edit_assigned_task ($blog_id, $user_id, $task_id, $target_date, $old_user_id, $old_task_id, $old_target_date) {
 		// Init
 		$tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
+		
+		$course_id = api_get_course_int_id();		
 
-		$sql = "
-			SELECT COUNT(*) as 'number'
+		$sql = "SELECT COUNT(*) as 'number'
 			FROM " . $tbl_blogs_tasks_rel_user . "
 			WHERE
 				blog_id = " . (int)$blog_id . " AND
@@ -2009,8 +1981,7 @@ class Blog {
 		$result = @Database::query($sql);
 		$row = Database::fetch_assoc($result);
 
-		if($row['number'] == 0 || ($row['number'] != 0 && $task_id == $old_task_id && $user_id == $old_user_id))
-		{
+		if($row['number'] == 0 || ($row['number'] != 0 && $task_id == $old_task_id && $user_id == $old_user_id)) {
 			$sql = "
 				UPDATE " . $tbl_blogs_tasks_rel_user . "
 				SET
@@ -2018,6 +1989,7 @@ class Blog {
 					task_id = " . (int)$task_id . ",
 					target_date = '" . Database::escape_string($target_date) . "'
 				WHERE
+					c_id = $course_id AND
 					blog_id = " . (int)$blog_id . " AND
 					user_id = " . (int)$old_user_id . " AND
 					task_id = " . (int)$old_task_id . " AND
@@ -2039,39 +2011,31 @@ class Blog {
 		$tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
 		$tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS);
 		$tbl_users = Database::get_main_table(TABLE_MAIN_USER);
-
-		$sql = "
-			SELECT title, description
-			FROM $tbl_blogs_tasks
-			WHERE task_id = '".(int)$task_id."'";
+		$course_id = api_get_course_int_id();
+		
+				
+		$sql = "SELECT title, description FROM $tbl_blogs_tasks
+				WHERE task_id = '".(int)$task_id."'";
 		$result = Database::query($sql);
 		$row = Database::fetch_assoc($result);
 		// Get posts and authors
-		$sql = "
-			SELECT
-				post.*,
-				user.lastname,
-				user.firstname
-			FROM $tbl_blogs_posts post
-			INNER JOIN $tbl_users user ON post.author_id = user.user_id
-			WHERE post.blog_id = '".(int)$blog_id."'
-			ORDER BY post_id DESC
-			LIMIT 0, 100";
+		$sql = "SELECT post.*, user.lastname, user.firstname
+				FROM $tbl_blogs_posts post
+				INNER JOIN $tbl_users user ON post.author_id = user.user_id
+				WHERE post.blog_id = '".(int)$blog_id."' AND post.c_id = $course_id
+				ORDER BY post_id DESC
+				LIMIT 0, 100";
 		$result = Database::query($sql);
 
 		// Display
 		echo '<span class="blogpost_title">' . get_lang('SelectTaskArticle') . ' "' . stripslashes($row['title']) . '"</span>';
 		echo '<span style="font-style: italic;"">'.stripslashes($row['description']) . '</span><br><br>';
 
-
-		if(Database::num_rows($result) > 0)
-		{
-			while($blog_post = Database::fetch_array($result))
-			{
+		if(Database::num_rows($result) > 0) {
+			while($blog_post = Database::fetch_array($result)) {
 				echo '<a href="blog.php?action=execute_task&amp;blog_id=' . $blog_id . '&amp;task_id=' . $task_id . '&amp;post_id=' . $blog_post['post_id'] . '#add_comment">'.stripslashes($blog_post['title']) . '</a>, ' . get_lang('WrittenBy') . ' ' . stripslashes(api_get_person_name($blog_post['firstname'], $blog_post['lastname'])) . '<br />';
 			}
-		}
-		else
+		} else 
 			echo get_lang('NoArticles');
 	}
 
@@ -2086,15 +2050,17 @@ class Blog {
 		// Init
 		$tbl_blogs_rel_user 	= Database::get_course_table(TABLE_BLOGS_REL_USER);
 		$tbl_user_permissions 	= Database::get_course_table(TABLE_PERMISSION_USER);
+		
+		$course_id = api_get_course_int_id();
 
 		// Subscribe the user
-		$sql = "INSERT INTO $tbl_blogs_rel_user ( blog_id, user_id ) VALUES ('".(int)$blog_id."', '".(int)$user_id."');";
+		$sql = "INSERT INTO $tbl_blogs_rel_user (c_id, blog_id, user_id ) VALUES ($course_id, '".(int)$blog_id."', '".(int)$user_id."');";
 		$result = Database::query($sql);
 
 		// Give this user basic rights
-		$sql="INSERT INTO $tbl_user_permissions (user_id,tool,action) VALUES ('".(int)$user_id."','BLOG_" . (int)$blog_id."','article_add')";
+		$sql="INSERT INTO $tbl_user_permissions (c_id, user_id,tool,action) VALUES ($course_id, '".(int)$user_id."','BLOG_" . (int)$blog_id."','article_add')";
 		$result = Database::query($sql);
-		$sql="INSERT INTO $tbl_user_permissions (user_id,tool,action) VALUES ('".(int)$user_id."','BLOG_" . (int)$blog_id."','article_comments_add')";
+		$sql="INSERT INTO $tbl_user_permissions (c_id, user_id,tool,action) VALUES ($course_id, '".(int)$user_id."','BLOG_" . (int)$blog_id."','article_comments_add')";
 		$result = Database::query($sql);
 	}
 
@@ -2138,17 +2104,17 @@ class Blog {
 		$table_course_user 	= Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
 		echo '<div class="row"><div class="form_header">'.get_lang('SubscribeMembers').'</div></div>';
-
+		$course_id = api_get_course_int_id();
 		$properties["width"] = "100%";
 
 		// Get blog members' id.
 		$sql = "SELECT user.user_id FROM $tbl_users user
 				INNER JOIN $tbl_blogs_rel_user blogs_rel_user
 				ON user.user_id = blogs_rel_user.user_id
-				WHERE blogs_rel_user.blog_id = '".intval($blog_id)."'";
+				WHERE blogs_rel_user.c_id = $course_id AND blogs_rel_user.blog_id = '".intval($blog_id)."'";
 		$result = Database::query($sql);
 
-		$blog_member_ids = array ();
+		$blog_member_ids = array();
 		while($user = Database::fetch_array($result))
 		{
 			$blog_member_ids[] = $user['user_id'];
@@ -2259,12 +2225,13 @@ class Blog {
 		$column_header[] = array (get_lang('Email'), true, '');
 		$column_header[] = array (get_lang('TaskManager'), true, '');
 		$column_header[] = array (get_lang('UnRegister'), false, '');
-
+		
+		$course_id = api_get_course_int_id();
+		
 		$sql_query = "SELECT user.user_id, user.lastname, user.firstname, user.email
-			FROM $tbl_users user
-			INNER JOIN $tbl_blogs_rel_user blogs_rel_user
+			FROM $tbl_users user INNER JOIN $tbl_blogs_rel_user blogs_rel_user
 			ON user.user_id = blogs_rel_user.user_id
-			WHERE blogs_rel_user.blog_id = '".(int)$blog_id."'";
+			WHERE blogs_rel_user.c_id = $course_id AND  blogs_rel_user.blog_id = '".(int)$blog_id."'";
 
 		if (!($sql_result = Database::query($sql_query))) {
 			return false;
@@ -2272,8 +2239,7 @@ class Blog {
 
 		$user_data = array ();
 
-		while($myrow = Database::fetch_array($sql_result))
-		{
+		while($myrow = Database::fetch_array($sql_result)) {
 			$row = array ();
 			$row[] = '<input type="checkbox" name="user[]" value="' . $myrow['user_id'] . '" '.(($_GET['selectall'] == "unsubscribe") ? ' checked="checked" ' : '') . '/>';
 			if ($is_western_name_order) {
@@ -2288,7 +2254,10 @@ class Blog {
 			$sql = "SELECT bt.title task
 			FROM " . Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER) . " btu
 			INNER JOIN " . Database::get_course_table(TABLE_BLOGS_TASKS) . " bt ON btu.task_id = bt.task_id
-			WHERE btu.blog_id = $blog_id AND btu.user_id = " . $myrow['user_id'] . "";
+			WHERE 	btu.c_id 	= $course_id  AND 
+					bt.c_id 	= $course_id  AND 
+					btu.blog_id = $blog_id AND 
+					btu.user_id = " . $myrow['user_id'];
 
 			if (!($sql_res = Database::query($sql))) {
 				die(Database::error());
@@ -2454,6 +2423,8 @@ class Blog {
 		$tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
 		$tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER);
 		$tbl_blogs = Database::get_course_table(TABLE_BLOGS);
+		
+		$course_id = api_get_course_int_id();
 
 		//Handle leap year
 		$numberofdays = array (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
@@ -2474,17 +2445,16 @@ class Blog {
 		$sql = "SELECT post.*, DAYOFMONTH(date_creation) as post_day, user.lastname, user.firstname FROM $tbl_blogs_posts post
 				INNER JOIN $tbl_users user
 				ON post.author_id = user.user_id
-				WHERE post.blog_id = '".(int)$blog_id."'
-				AND MONTH(date_creation) = '".(int)$month."'
-				AND YEAR(date_creation) = '".(int)$year."'
+				WHERE 	post.c_id = $course_id AND
+						post.blog_id = '".(int)$blog_id."' AND 
+						MONTH(date_creation) = '".(int)$month."' AND 
+						YEAR(date_creation) = '".(int)$year."' 
 				ORDER BY date_creation";
 		$result = Database::query($sql);
 
 		// We will create an array of days on which there are posts.
-		if( Database::num_rows($result) > 0)
-		{
-			while($blog_post = Database::fetch_array($result))
-			{
+		if( Database::num_rows($result) > 0) {
+			while($blog_post = Database::fetch_array($result)) {
 				// If the day of this post is not yet in the array, add it.
 				if(!in_array($blog_post['post_day'], $posts))
 					$posts[] = $blog_post['post_day'];
@@ -2492,18 +2462,16 @@ class Blog {
 		}
 
 		// Get tasks for this month
-		if($_user['user_id'])
-		{
-			$sql = "
-				SELECT
-					task_rel_user.*,
-					DAYOFMONTH(target_date) as task_day,
-					task.title,
-					blog.blog_name
+		if($_user['user_id']) {
+			$sql = " SELECT task_rel_user.*,  DAYOFMONTH(target_date) as task_day, task.title, blog.blog_name 
 				FROM $tbl_blogs_tasks_rel_user task_rel_user
 				INNER JOIN $tbl_blogs_tasks task ON task_rel_user.task_id = task.task_id
 				INNER JOIN $tbl_blogs blog ON task_rel_user.blog_id = blog.blog_id
-				WHERE task_rel_user.user_id = '".(int)$_user['user_id']."'
+				WHERE 
+				task_rel_user.c_id = $course_id AND
+				task.c_id = $course_id AND
+				blog.c_id = $course_id AND
+				task_rel_user.user_id = '".(int)$_user['user_id']."'
 				AND	MONTH(target_date) = '".(int)$month."'
 				AND	YEAR(target_date) = '".(int)$year."'
 				ORDER BY target_date ASC";
@@ -2713,10 +2681,12 @@ class Blog {
 
 		$sql = 'SELECT blog_name,blog_subtitle,visibility,blog_id FROM '.$tbl_blogs.' ORDER BY date_creation DESC ';
 		$result = Database::query($sql);
-
-		while ($row_project=Database::fetch_row($result)) {
-			$list_info[]=$row_project;
+		if (Database::num_rows($result)) {
+			while ($row_project=Database::fetch_row($result)) {
+				$list_info[]=$row_project;
+			}
 		}
+		
 
 		$list_content_blog = array();
 		$list_body_blog = array();
@@ -2901,25 +2871,28 @@ function delete_all_blog_attachment($blog_id,$post_id=null,$comment_id=null)
  * @param string db course name
  * @param int user id
  */
-function get_blog_post_from_user($course_db_name, $user_id) {
-
-		$tbl_blogs = Database::get_course_table(TABLE_BLOGS,$course_db_name);
-		$tbl_blog_post = Database::get_course_table(TABLE_BLOGS_POSTS,$course_db_name);
+function get_blog_post_from_user($course_code, $user_id) {
+		$tbl_blogs 		= Database::get_course_table(TABLE_BLOGS);
+		$tbl_blog_post 	= Database::get_course_table(TABLE_BLOGS_POSTS);
+		$course_info 	= api_get_course_info($course_code);
+		$course_id 		= $course_info['real_id'];
+		
 		$sql = "SELECT DISTINCT blog.blog_id, post_id, title, full_text, post.date_creation
 				FROM $tbl_blogs blog INNER JOIN  $tbl_blog_post post
 				ON (blog.blog_id = post.blog_id)
-				WHERE author_id =  $user_id AND visibility = 1
+				WHERE
+					blog.c_id = $course_id AND
+					post.c_id = $course_id AND 
+					author_id =  $user_id AND visibility = 1
 				ORDER BY post.date_creation DESC ";
 		$result = Database::query($sql);
 		$return_data = '';
-		//$my_course_info=explode('_',$course_db_name);
-		$my_course_id=CourseManager::get_course_id_by_database_name($course_db_name);
+		
 		if (Database::num_rows($result)!=0) {
 			while ($row=Database::fetch_array($result)) {
 				$return_data.=  '<div class="clear"></div><br />';
 	 			$return_data.=  '<div class="actions" style="margin-left:5px;margin-right:5px;">'.Display::return_icon('blog_article.png',get_lang('BlogPosts')).' '.$row['title'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="float:right;margin-top:-18px"><a href="../blog/blog.php?blog_id='.$row['blog_id'].'&gidReq=&cidReq='.$my_course_id.' " >'.get_lang('SeeBlog').'</a></div></div>';
 	 			$return_data.=  '<br / >';
-				//$return_data.= '<strong>'.$row['title'].'</strong>'; echo '<br>';
 				$return_data.= $row['full_text'];
 				$return_data.= '<br /><br />';
 			}
@@ -2932,24 +2905,28 @@ function get_blog_post_from_user($course_db_name, $user_id) {
  * @param string db course name
  * @param int user id
  */
-function get_blog_comment_from_user($course_db_name, $user_id) {
-
-		$tbl_blogs = Database::get_course_table(TABLE_BLOGS,$course_db_name);
-		$tbl_blog_comment = Database::get_course_table(TABLE_BLOGS_COMMENTS,$course_db_name);
-		$user_id = Database::escape_string($user_id);
+function get_blog_comment_from_user($course_code, $user_id) {
+		$tbl_blogs 			= Database::get_course_table(TABLE_BLOGS);
+		$tbl_blog_comment 	= Database::get_course_table(TABLE_BLOGS_COMMENTS);
+		$user_id 			= Database::escape_string($user_id);
+		
+		$course_info 		= api_get_course_info($course_code);
+		$course_id 			= $course_info['real_id'];
 
 		$sql = "SELECT DISTINCT blog.blog_id, comment_id, title, comment, comment.date_creation
 				FROM $tbl_blogs blog INNER JOIN  $tbl_blog_comment comment
 				ON (blog.blog_id = comment.blog_id)
-				WHERE author_id =  $user_id AND visibility = 1
+				WHERE 	blog.c_id = $course_id AND
+						comment.c_id = $course_id AND
+						author_id =  $user_id AND 
+						visibility = 1
 				ORDER BY blog_name";
 		$result = Database::query($sql);
 		$return_data = '';
-		$my_course_info=explode('_',$course_db_name);
 		if (Database::num_rows($result)!=0) {
 			while ($row=Database::fetch_array($result)) {
 				$return_data.=  '<div class="clear"></div><br />';
-	 			$return_data.=  '<div class="actions" style="margin-left:5px;margin-right:5px;">'.$row['title'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="float:right;margin-top:-18px"><a href="../blog/blog.php?blog_id='.$row['blog_id'].'&gidReq=&cidReq='.$my_course_info[1].' " >'.get_lang('SeeBlog').'</a></div></div>';
+	 			$return_data.=  '<div class="actions" style="margin-left:5px;margin-right:5px;">'.$row['title'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="float:right;margin-top:-18px"><a href="../blog/blog.php?blog_id='.$row['blog_id'].'&gidReq=&cidReq='.Security::remove_XSS($course_code).' " >'.get_lang('SeeBlog').'</a></div></div>';
 	 			$return_data.=  '<br / >';
 				//$return_data.=  '<strong>'.$row['title'].'</strong>'; echo '<br>';*/
 				$return_data.=  $row['comment'];

+ 35 - 50
main/inc/lib/course.lib.php

@@ -122,9 +122,9 @@ class CourseManager {
      * @return an array with all the fields of the course table
      * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
      */
-    public static function get_course_information($course_code) {
+    public static function get_course_information($course_code) {    	
         return Database::fetch_array(Database::query(
-            "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
+            "SELECT *, id as real_id FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
             WHERE code='".Database::escape_string($course_code)."'"),'ASSOC'
         );
     }
@@ -257,43 +257,38 @@ class CourseManager {
             $user_ids = intval($user_id);
         }
 
-        $course_code = Database::escape_string($course_code);
-
-        $course = Database::fetch_object(Database::query("SELECT db_name FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
-                WHERE code = '".$course_code."'"));
+        
+        $course_info = api_get_course_info($course_code);
+        $course_id = $course_info['real_id'];
 
         // Unsubscribe user from all groups in the course.
-        Database::query("DELETE FROM ".Database::get_course_table(TABLE_GROUP_USER, $course->db_name)."
-                WHERE user_id IN (".$user_ids.")");
-        Database::query("DELETE FROM ".Database::get_course_table(TABLE_GROUP_TUTOR, $course->db_name)."
-                WHERE user_id IN (".$user_ids.")");
+        Database::query("DELETE FROM ".Database::get_course_table(TABLE_GROUP_USER)."  WHERE c_id = $course_id AND user_id IN (".$user_ids.")");
+        Database::query("DELETE FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)." WHERE c_id = $course_id AND user_id IN (".$user_ids.")");
 
         // Erase user student publications (works) in the course - by André Boivin
         //@todo field student_publication.author should be the user id
-
-        $table_course_user_publication 	= Database :: get_course_table(TABLE_STUDENT_PUBLICATION, $course->db_name);
+        
         $sqlu = "SELECT * FROM $table_user WHERE user_id IN (".$user_ids.")";
         $resu = Database::query($sqlu);
         $username = Database::fetch_array($resu,'ASSOC');
-          $userfirstname = $username['firstname'];
+        $userfirstname = $username['firstname'];
         $userlastname = $username['lastname'];
-         $publication_name = $userfirstname.' '.$userlastname ;
-
-        $sql = "DELETE FROM $table_course_user_publication WHERE author = '".Database::escape_string($publication_name)."'";
+	    $publication_name = $userfirstname.' '.$userlastname ;
+	    
+	    $table_course_user_publication 	= Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
+        $sql = "DELETE FROM $table_course_user_publication WHERE c_id = $course_id AND author = '".Database::escape_string($publication_name)."'";
         Database::query($sql);
 
 
         // Unsubscribe user from all blogs in the course.
-        Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_REL_USER, $course->db_name)."
-                WHERE user_id IN (".$user_ids.")");
-        Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER, $course->db_name)."
-                WHERE user_id IN (".$user_ids.")");
+        Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_REL_USER)." WHERE c_id = $course_id AND  user_id IN (".$user_ids.")");
+        Database::query("DELETE FROM ".Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER)."WHERE c_id = $course_id AND  user_id IN (".$user_ids.")");
 
         //Deleting users in forum_notification and mailqueue course tables
-        $sql_delete_forum_notification = "DELETE FROM  ".Database::get_course_table(TABLE_FORUM_NOTIFICATION, $course->db_name)." WHERE user_id IN (".$user_ids.")";
+        $sql_delete_forum_notification = "DELETE FROM  ".Database::get_course_table(TABLE_FORUM_NOTIFICATION)." WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
         Database::query($sql_delete_forum_notification);
 
-        $sql_delete_mail_queue = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_MAIL_QUEUE, $course->db_name)." WHERE user_id IN (".$user_ids.")";
+        $sql_delete_mail_queue = "DELETE FROM ".Database::get_course_table(TABLE_FORUM_MAIL_QUEUE)." WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
         Database::query($sql_delete_mail_queue);
 
 
@@ -1359,16 +1354,17 @@ class CourseManager {
      * @return  array   List of groups info
      */
     public static function get_group_list_of_course($course_code, $session_id = 0) {
-        $course_info = Database::get_course_info($course_code);
-        $database_name = $course_info['db_name'];
-
+        $course_info = Database::get_course_info($course_code);        
+        $course_id = $course_info['real_id'];
         $group_list = array();
         $session_id != 0 ? $session_condition = ' WHERE g.session_id IN(1,'.intval($session_id).')' : $session_condition = ' WHERE g.session_id = 0';
         $sql="SELECT g.id, g.name, COUNT(gu.id) userNb
-                FROM ".Database::get_course_table(TABLE_GROUP, $database_name)." AS g
-                LEFT JOIN ".Database::get_course_table(TABLE_GROUP_USER, $database_name)." gu
+                FROM ".Database::get_course_table(TABLE_GROUP)." AS g
+                LEFT JOIN ".Database::get_course_table(TABLE_GROUP_USER)." gu
                 ON g.id = gu.group_id
-                $session_condition
+                $session_condition AND
+                g.c_id = $course_id AND
+                gu.c_id = $course_id AND
                 GROUP BY g.id
                 ORDER BY g.name";
         $result = Database::query($sql);
@@ -2446,13 +2442,18 @@ class CourseManager {
      *  @param  int		optionally count rows by session id
      *  @return int 	The number of rows in the given table.
      */
-    public static function count_rows_course_table($table, $session_id = '') {
+    public static function count_rows_course_table($table, $session_id = '', $course_id = null) {
         $condition_session = '';
         if ($session_id !== '') {
             $session_id = intval($session_id);
-            $condition_session = " WHERE session_id = '$session_id' ";
+            $condition_session = " AND session_id = '$session_id' ";
         }
-        $sql	= "SELECT COUNT(*) AS n FROM $table $condition_session ";
+        if (!empty($course_id)) {
+        	$course_id = intval($course_id);
+        	$condition_session .= " AND c_id = '$course_id' ";
+        }
+        
+        $sql	= "SELECT COUNT(*) AS n FROM $table WHERE 1=1 $condition_session ";
         $rs 	= Database::query($sql);
         $row 	= Database::fetch_row($rs);
         return $row[0];
@@ -2986,15 +2987,10 @@ class CourseManager {
         $result = '';
     
         // Table definitions
-        //$statistic_database = Database::get_statistic_database();
         $main_user_table            = Database :: get_main_table(TABLE_MAIN_USER);
         $tbl_session                = Database :: get_main_table(TABLE_MAIN_SESSION);
         $tbl_session_category       = Database :: get_main_table(TABLE_MAIN_SESSION_CATEGORY);
-        $course_database            = $my_course['db'];
-        $course_tool_table          = Database :: get_course_table(TABLE_TOOL_LIST, $course_database);
-        $tool_edit_table            = Database :: get_course_table(TABLE_ITEM_PROPERTY, $course_database);
-        $course_group_user_table    = Database :: get_course_table(TOOL_USER, $course_database);
-    
+            
         $user_id                = api_get_user_id();
         $course_system_code     = $my_course['k'];
         $course_visual_code     = $my_course['c'];
@@ -3002,7 +2998,7 @@ class CourseManager {
         $course_directory       = $my_course['d'];
         $course_teacher         = $my_course['t'];
         $course_teacher_email   = isset($my_course['email']) ? $my_course['email'] : '';
-        $course_info = Database :: get_course_info($course_system_code);
+        $course_info 			= Database :: get_course_info($course_system_code);
         $course_access_settings = CourseManager :: get_access_settings($course_system_code);
         $course_id = isset($course_info['course_id']) ? $course_info['course_id'] : null;
         $course_visibility = $course_access_settings['visibility'];
@@ -3035,19 +3031,8 @@ class CourseManager {
         $is_coach = api_is_coach($my_course['id_session'], $course['code']);
             
         $s_htlm_status_icon = Display::return_icon('blackboard_blue.png', get_lang('Course'), array('width' => '48px'));
-        /*
-        if ($s_course_status == 1) {
-            $s_htlm_status_icon = Display::return_icon('course.gif', get_lang('Course')).' '.Display::return_icon('teachers.gif', get_lang('Status').': '.get_lang('Teacher'), array('style' => 'width: 11px; height: 11px;'));
-        }
-        if ($s_course_status == 2 || ($is_coach && $s_course_status != 1)) {
-            $s_htlm_status_icon = Display::return_icon('course.gif', get_lang('Course')).' '.Display::return_icon('coachs.gif', get_lang('Status').': '.get_lang('GeneralCoach'), array('style' => 'width: 11px; height: 11px;'));
-        }
-        if (($s_course_status == 5 && !$is_coach) || empty($s_course_status)) {
-            $s_htlm_status_icon = Display::return_icon('course.gif', get_lang('Course')).' '.Display::return_icon('students.gif', get_lang('Status').': '.get_lang('Student'), array('style' => 'width: 11px; height: 11px;'));
-        }
-        */
-        // Display course entry.
         
+        // Display course entry.        
         // Show a hyperlink to the course, unless the course is closed and user is not course admin.
         $session_url = '';
         $session_title = '';

+ 38 - 32
main/inc/lib/course_description.lib.php

@@ -91,14 +91,17 @@ class CourseDescription
 	public function get_description_history($description_type) {
 		$tbl_stats_item_property = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
 		$tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
-		$course_id = api_get_real_course_id();
-
+		
 		$description_id = $this->get_id_by_description_type($description_type);
 		$item_property_id = api_get_item_property_id($course_id, TOOL_COURSE_DESCRIPTION, $description_id);
+		
+		$course_id = api_get_course_int_id();
 
-		$sql = "SELECT tip.id, tip.course_id, tip.item_property_id, tip.title, tip.content, tip.progress, tip.lastedit_date, tip.session_id FROM $tbl_stats_item_property tip
-				INNER JOIN $tbl_item_property ip ON ip.tool = '".TOOL_COURSE_DESCRIPTION."' AND ip.id = tip.item_property_id
-				WHERE tip.course_id = '$course_id' AND tip.session_id = '".intval($this->session_id)."' ORDER BY tip.lastedit_date DESC";
+		$sql = "SELECT tip.id, tip.course_id, tip.item_property_id, tip.title, tip.content, tip.progress, tip.lastedit_date, tip.session_id 
+				FROM $tbl_stats_item_property tip INNER JOIN $tbl_item_property ip 
+				ON ip.tool = '".TOOL_COURSE_DESCRIPTION."' AND ip.id = tip.item_property_id
+				WHERE ip.c_id = $course_id AND tip.course_id = '$course_id' AND tip.session_id = '".intval($this->session_id)."' 
+				ORDER BY tip.lastedit_date DESC";
 
 		$rs = Database::query($sql);
 		$data = array();
@@ -161,13 +164,16 @@ class CourseDescription
      * first you must set description_type, title, content, progress and session_id properties with the object CourseDescription
      * @return  int  affected rows
      */
-	public function insert($course_db = null) {
-		if($course_db === null) {
-			$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
-		} else {
-			$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION, $course_db);
-		}
-		$sql = "INSERT IGNORE INTO $tbl_course_description SET description_type='".intval($this->description_type)."', title = '".Database::escape_string($this->title)."', content = '".Database::escape_string($this->content)."', progress = '".intval($this->progress)."', session_id = '".intval($this->session_id)."' ";
+	public function insert() {		
+		$course_id = api_get_course_int_id();
+		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);		
+		$sql = "INSERT IGNORE INTO $tbl_course_description SET
+				c_id 				=  $course_id, 
+				description_type	= '".intval($this->description_type)."', 
+				title 				= '".Database::escape_string($this->title)."', 
+				content 			= '".Database::escape_string($this->content)."', 
+				progress 			= '".intval($this->progress)."', 
+				session_id = '".intval($this->session_id)."' ";
 		Database::query($sql);
 		$last_id = Database::insert_id();
 		$affected_rows = Database::affected_rows();
@@ -192,14 +198,15 @@ class CourseDescription
 		$course_code = api_get_course_id();
 		$item_property_id = api_get_item_property_id($course_code, TOOL_COURSE_DESCRIPTION, $description_id);
 		$sql = "INSERT IGNORE INTO $tbl_stats_item_property SET
-				course_id = '$course_id',
-			 	item_property_id = '$item_property_id',
-			 	title = '".Database::escape_string($this->title)."',
-			 	content = '".Database::escape_string($this->content)."',
-			 	progress = '".intval($this->progress)."',
-			 	lastedit_date = '".date('Y-m-d H:i:s')."',
-			 	lastedit_user_id = '".api_get_user_id()."',
-			 	session_id	= '".intval($this->session_id)."'";
+				c_id				= ".api_get_course_int_id().",
+				course_id 			= '$course_id',
+			 	item_property_id 	= '$item_property_id',
+			 	title 				= '".Database::escape_string($this->title)."',
+			 	content 			= '".Database::escape_string($this->content)."',
+			 	progress 			= '".intval($this->progress)."',
+			 	lastedit_date 		= '".date('Y-m-d H:i:s')."',
+			 	lastedit_user_id 	= '".api_get_user_id()."',
+			 	session_id			= '".intval($this->session_id)."'";
 		Database::query($sql);
 		$affected_rows = Database::affected_rows();
 		return $affected_rows;
@@ -210,13 +217,16 @@ class CourseDescription
      * and session_id properties with the object CourseDescription
      * @return int	affected rows
      */
-	public function update($course_db = null) {
-		if($course_db === null) {
-			$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
-		} else {
-			$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION, $course_db);
-		}
-		$sql = "UPDATE $tbl_course_description SET  title = '".Database::escape_string($this->title)."', content = '".Database::escape_string($this->content)."', progress = '".$this->progress."' WHERE description_type='".intval($this->description_type)."' AND session_id = '".$this->session_id."'";
+	public function update($course_db = null) {		
+		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);		
+		$sql = "UPDATE $tbl_course_description SET  
+						title = '".Database::escape_string($this->title)."', 
+						content = '".Database::escape_string($this->content)."', 
+						progress = '".$this->progress."' 
+				WHERE 	description_type='".intval($this->description_type)."' AND 
+						session_id = '".$this->session_id."' AND
+						c_id = ".api_get_course_int_id()."
+						";
 		Database::query($sql);
 		$affected_rows = Database::affected_rows();
 		$description_id = $this->get_id_by_description_type($this->description_type);
@@ -232,11 +242,7 @@ class CourseDescription
      * @return int	affected rows
      */
 	public function delete($course_db = null) {
-		if($course_db === null) {
-			$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
-		} else {
-			$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION, $course_db);
-		}
+		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);		
 		$description_id = $this->get_id_by_description_type($this->description_type);
 		$sql = "DELETE FROM $tbl_course_description WHERE description_type = '".intval($this->description_type)."' AND session_id = '".intval($this->session_id)."'";
 		Database::query($sql);

+ 39 - 14
main/inc/lib/course_home.lib.php

@@ -55,6 +55,9 @@ class CourseHome {
         while ($tool = Database::fetch_array($result)) {
             $all_tools[] = $tool;
         }
+        
+        $course_id = api_get_course_int_id();
+        
 
         // Grabbing all the links that have the property on_homepage set to 1
         if ($cat == 'External') {
@@ -62,14 +65,20 @@ class CourseHome {
             $tbl_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
             if (api_is_allowed_to_edit(null, true)) {
                 $sql_links = "SELECT tl.*, tip.visibility
-                                    FROM $tbl_link tl
-                                    LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
-                                    WHERE tl.on_homepage='1' AND tip.visibility != 2";
+								FROM $tbl_link tl
+                                LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
+                                WHERE 	tl.c_id = $course_id AND
+                                		tip.c_id = $course_id AND
+                						tl.on_homepage='1' AND 
+                						tip.visibility != 2";
             } else {
                 $sql_links = "SELECT tl.*, tip.visibility
                                     FROM $tbl_link tl
                                     LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
-                                    WHERE tl.on_homepage='1' AND tip.visibility = 1";
+                                    WHERE 	tl.c_id = $course_id AND
+                                			tip.c_id = $course_id AND
+                							tl.on_homepage='1' AND 
+                							tip.visibility = 1";
             }
             $result_links = Database::query($sql_links);
             while ($links_row = Database::fetch_array($result_links)) { 
@@ -244,22 +253,29 @@ class CourseHome {
             }
             $all_tools_list[] = $temp_row;
         }
+        
+        $course_id = api_get_course_int_id();
 
         // Grabbing all the links that have the property on_homepage set to 1
-        $course_link_table = Database::get_course_table(TABLE_LINK);
+        $course_link_table 			= Database::get_course_table(TABLE_LINK);
         $course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
+        
         switch ($course_tool_category)  {
             case TOOL_PUBLIC:
                 $sql_links="SELECT tl.*, tip.visibility
                         FROM $course_link_table tl
                         LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
-                        WHERE tl.on_homepage='1' AND tip.visibility = 1";
+                        WHERE 	tl.c_id = $course_id AND 
+                        		tip.c_id = $course_id AND
+                        		tl.on_homepage='1' AND tip.visibility = 1";
                 break;
             case TOOL_PUBLIC_BUT_HIDDEN:
                 $sql_links="SELECT tl.*, tip.visibility
                     FROM $course_link_table tl
                     LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
-                    WHERE tl.on_homepage='1' AND tip.visibility = 0";
+                    WHERE 	tl.c_id = $course_id AND 
+                        	tip.c_id = $course_id AND
+                        	tl.on_homepage='1' AND tip.visibility = 0";
                 break;
             default:
                 $sql_links = null;
@@ -416,9 +432,10 @@ class CourseHome {
         $all_tools_list = array();
 
         // Condition for the session
-        $session_id = api_get_session_id();
-        $condition_session = api_get_session_condition($session_id, true, true);
-
+        $session_id 			= api_get_session_id();
+        $condition_session 		= api_get_session_condition($session_id, true, true);
+        $course_id_condition 	= api_get_course_table_condition();
+        
         switch ($course_tool_category) {
             case TOOL_STUDENT_VIEW:
                     $condition_display_tools = ' WHERE visibility = 1 AND (category = "authoring" OR category = "interaction" OR category = "plugin") ';
@@ -487,15 +504,19 @@ class CourseHome {
 
         $i = 0;
         // Grabbing all the links that have the property on_homepage set to 1
-        $course_link_table = Database::get_course_table(TABLE_LINK);
+        $course_link_table 			= Database::get_course_table(TABLE_LINK);
         $course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
+        
+        $course_id = api_get_course_int_id();
 
         switch ($course_tool_category) {
                 case TOOL_AUTHORING:
                     $sql_links = "SELECT tl.*, tip.visibility
                         FROM $course_link_table tl
                         LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
-                            WHERE tl.on_homepage='1' $condition_session";
+                        WHERE 	tl.c_id = $course_id AND 
+                        		tip.c_id = $course_id AND
+                        		tl.on_homepage='1' $condition_session";
                     break;
 
                 case TOOL_INTERACTION:
@@ -512,14 +533,18 @@ class CourseHome {
                     $sql_links = "SELECT tl.*, tip.visibility
                         FROM $course_link_table tl
                         LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
-                            WHERE tl.on_homepage='1' $condition_session";
+                            WHERE 	tl.c_id 		= $course_id AND 
+                        			tip.c_id 		= $course_id AND
+                        			tl.on_homepage	='1' $condition_session";
                     break;
 
                 case TOOL_ADMIN:
                     $sql_links = "SELECT tl.*, tip.visibility
                         FROM $course_link_table tl
                         LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
-                            WHERE tl.on_homepage='1' $condition_session";
+                        WHERE 	tl.c_id = $course_id AND 
+                        		tip.c_id = $course_id AND
+                        		tl.on_homepage='1' $condition_session";
                     break;
 
                 default:

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

@@ -192,6 +192,7 @@ define('TABLE_QUIZ_TEST_QUESTION',  'quiz_rel_question');
 define('TABLE_QUIZ_QUESTION_OPTION','quiz_question_option');
 
 // Linked resource table
+//@todo table exists?
 define('TABLE_LINKED_RESOURCES', 'resource');
 
 // New SCORM tables

+ 48 - 3
main/inc/lib/database.lib.php

@@ -17,6 +17,8 @@
  */
 /*	CONSTANTS */
 
+define('DB_COURSE_PREFIX', 'c_');
+
 require_once 'database.constants.inc.php';
 
 /*		DATABASE CLASS
@@ -164,7 +166,8 @@ class Database {
      * - if you don't specify this, you work on the current course.
      */
     public static function get_course_table($short_table_name, $database_name = '') {
-        return self::format_glued_course_table_name(self::fix_database_parameter($database_name), $short_table_name);
+    	return self::format_table_name(self::get_main_database(), DB_COURSE_PREFIX.$short_table_name);
+        //return self::format_glued_course_table_name(self::fix_database_parameter($database_name), $short_table_name);
     }
 
     /**
@@ -239,7 +242,7 @@ class Database {
      */
     public static function get_course_list() {
         $table = self::get_main_table(TABLE_MAIN_COURSE);
-        return self::store_result(self::query("SELECT * FROM $table"));
+        return self::store_result(self::query("SELECT *, id as real_id FROM $table"));
     }
 
     /**
@@ -252,7 +255,7 @@ class Database {
         $course_code = self::escape_string($course_code);
         $table = self::get_main_table(TABLE_MAIN_COURSE);
         $result = self::generate_abstract_course_field_names(
-            self::fetch_array(self::query("SELECT * FROM $table WHERE code = '$course_code'")));
+            self::fetch_array(self::query("SELECT *, id as real_id FROM $table WHERE code = '$course_code'")));
         return $result === false ? array('db_name' => '') : $result;
     }
 
@@ -691,7 +694,49 @@ class Database {
             $line = $file;
             $file = $connection;
             $connection = null;
+        }        
+        error_log($query);
+        //Check if the table contains a c_ (means a course id)
+        if (strpos($query, 'c_')) {        	
+        	//Check if the table contains inner joins 
+        	if (	
+        		strpos($query, 'INNER JOIN') === false &&  
+        		strpos($query, 'inner join') === false &&
+        		strpos($query, 'left join') === false &&
+        		strpos($query, 'LEFT JOIN') === false &&
+        		strpos($query, 'c_id') === false
+        	) {        		
+        		$limit_list = explode('LIMIT', $query);
+        		$limit = '';
+        		if (isset($limit_list[1])) {
+        			$limit = ' LIMIT '.$limit_list[1];
+        		}
+        		$group_list = explode('GROUP', $limit_list[0]);
+        		$group = '';
+        		if (isset($group_list[1])) {
+        			$group = ' GROUP '.$group_list[1];
+        		}
+        		$order_list = explode('ORDER', $group_list[0]);
+        		$order = '';
+        		if (isset($order_list[1])) {
+        			$order = ' ORDER '.$order_list[1];
+        		}
+	        	$where_list = explode('WHERE', $order_list[0]);
+	        	$select = $where_list[0];
+	        	if (isset($where_list[1])) {	        		
+	        		$where  = $where_list[1].' AND c_id = '.api_get_course_int_id().' ';	        		
+	        		$query 	= $select.' WHERE '.$where.' '.$order.$group.$limit;	        		
+	        		//echo ($query );var_dump('julio');
+	        		//exit;
+	        	} else {
+	        		//check if order ?
+	        		$query = $select. ' WHERE 1 AND c_id = '.api_get_course_int_id().' '.$order.$group.$limit;	    
+	        	}	        	        	
+        	}
+        	//echo ($query);var_dump('d');
         }
+        
+        
         if (!($result = $use_default_connection ? @mysql_query($query) : @mysql_query($query, $connection))) {
             $backtrace = debug_backtrace(); // Retrieving information about the caller statement.
             if (isset($backtrace[0])) {

+ 21 - 15
main/inc/lib/display.lib.php

@@ -1036,21 +1036,25 @@ class Display {
      * @param array     Course information array, containing at least elements 'db' and 'k'
      * @return string   The HTML link to be shown next to the course
      */
-    function show_notification($my_course) {
-        $statistic_database = Database :: get_statistic_database();
+    function show_notification($my_course) {        
+        $t_track_e_access 	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
+        
         $user_id = api_get_user_id();
-        $course_database = $my_course['db'];
-        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST, $course_database);
-        $tool_edit_table = Database::get_course_table(TABLE_ITEM_PROPERTY, $course_database);
-        $course_group_user_table = Database :: get_course_table(TABLE_GROUP_USER, $course_database);
-        $t_track_e_access = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
-        $my_course['k'] = Database::escape_string($my_course['k']);
+        $course_database 			= $my_course['db'];
+        $course_tool_table			= Database::get_course_table(TABLE_TOOL_LIST);
+        $tool_edit_table 			= Database::get_course_table(TABLE_ITEM_PROPERTY);
+                
+        $course_code 	= Database::escape_string($my_course['k']);
+        $course_info	= api_get_course_info($course_code);
+        $course_id 		= $course_info['real_id'];
+        
         $my_course['id_session'] = intval($my_course['id_session']);
         // Get the user's last access dates to all tools of this course
         $sqlLastTrackInCourse = "SELECT * FROM $t_track_e_access ".
                                          " USE INDEX (access_cours_code, access_user_id) ".
-                                         "WHERE access_cours_code = '".$my_course['k']."' ".
-                                         "AND access_user_id = '$user_id' AND access_session_id ='".$my_course['id_session']."'";
+                                         "WHERE access_cours_code = '".$course_code."' AND 
+        										access_user_id = '$user_id' AND 
+        										access_session_id ='".$my_course['id_session']."'";
         $resLastTrackInCourse = Database::query($sqlLastTrackInCourse);
 
         $oldestTrackDate = $oldestTrackDateOrig = '3000-01-01 00:00:00';
@@ -1066,7 +1070,7 @@ class Display {
             $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
             $sql = "SELECT course.creation_date ".
                  "FROM $course_table course ".
-                 "WHERE course.code = '".$my_course['k']."'";
+                 "WHERE course.code = '".$course_code."'";
             $res = Database::query($sql);
             if ($res && Database::num_rows($res)>0) {
                 $row = Database::fetch_array($res);
@@ -1079,7 +1083,9 @@ class Display {
                             " tet.lastedit_type type, tet.to_group_id group_id, ".
                             " ctt.image image, ctt.link link ".
                         " FROM $tool_edit_table tet, $course_tool_table ctt ".
-                        " WHERE tet.lastedit_date > '$oldestTrackDate' ".
+                        " WHERE tet.c_id = $course_id AND
+                        		ctt.c_id = $course_id AND 
+                        		tet.lastedit_date > '$oldestTrackDate' ".
                         " AND ctt.name = tet.tool ".
                         " AND ctt.visibility = '1' ".
                         " AND tet.lastedit_user_id != $user_id AND tet.id_session = '".$my_course['id_session']."' ".
@@ -1119,14 +1125,14 @@ class Display {
                 }
                 // If it's a survey, make sure the user's invited. Otherwise drop it.
                 if ($item_property['tool'] == TOOL_SURVEY) {
-                    $survey_info = survey_manager::get_survey($item_property['ref'], 0, $my_course['k']);
+                    $survey_info = survey_manager::get_survey($item_property['ref'], 0, $course_code);
                     $invited_users = SurveyUtil::get_invited_users($survey_info['code'], $course_database);
                     if (!in_array($user_id, $invited_users['course_users'])) continue;
                 }
                 // If it's a learning path, ensure it is currently visible to the user
                 if ($item_property['tool'] == TOOL_LEARNPATH) {
                     require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
-                    if (!learnpath::is_lp_visible_for_student($item_property['ref'],$user_id, $my_course['k'])) {
+                    if (!learnpath::is_lp_visible_for_student($item_property['ref'],$user_id, $course_code)) {
                         continue;
                     }
 
@@ -1142,7 +1148,7 @@ class Display {
             if (empty($my_course['id_session'])) {
                 $my_course['id_session'] = 0;
             }
-            $retvalue .= '<a href="'.api_get_path(WEB_CODE_PATH).$notification['link'].'?cidReq='.$my_course['k'].'&amp;ref='.$notification['ref'].'&amp;gidReq='.$notification['to_group_id'].'&amp;id_session='.$my_course['id_session'].'">'.'<img title="-- '.get_lang(ucfirst($notification['tool'])).' -- '.get_lang('_title_notification').": ".get_lang($type)." ($lastDate).\"".' src="'.api_get_path(WEB_CODE_PATH).'img/'.$notification['image'].'" border="0" align="absbottom" /></a>&nbsp;';
+            $retvalue .= '<a href="'.api_get_path(WEB_CODE_PATH).$notification['link'].'?cidReq='.$course_code.'&amp;ref='.$notification['ref'].'&amp;gidReq='.$notification['to_group_id'].'&amp;id_session='.$my_course['id_session'].'">'.'<img title="-- '.get_lang(ucfirst($notification['tool'])).' -- '.get_lang('_title_notification').": ".get_lang($type)." ($lastDate).\"".' src="'.api_get_path(WEB_CODE_PATH).'img/'.$notification['image'].'" border="0" align="absbottom" /></a>&nbsp;';
         }
         return $retvalue;
     }

+ 116 - 120
main/inc/lib/document.lib.php

@@ -474,8 +474,8 @@ return 'application/octet-stream';
      * @return array with all document data
      */
     public static function get_all_document_data($_course, $path = '/', $to_group_id = 0, $to_user_id = NULL, $can_see_invisible = false, $search = false) {
-        $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
-        $TABLE_DOCUMENT     = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
+        $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+        $TABLE_DOCUMENT     = Database::get_course_table(TABLE_DOCUMENT);
         $TABLE_COURSE       = Database::get_main_table(TABLE_MAIN_COURSE);
 
         //if to_user_id = NULL -> change query (IS NULL)
@@ -519,7 +519,9 @@ return 'application/octet-stream';
                         WHERE docs.id = last.ref
                         AND last.tool = '".TOOL_DOCUMENT."'
                         AND ".$to_field." = ".$to_value."
-                        AND last.visibility".$visibility_bit . $condition_session;
+                        AND last.visibility".$visibility_bit . $condition_session." AND 
+            			docs.c_id = {$_course['real_id']} AND 
+            			last.c_id = {$_course['real_id']}  ";
         } else {
             $sql = "SELECT docs.id, docs.filetype, docs.path, docs.title, docs.comment, docs.size, docs.readonly, docs.session_id, last.id_session item_property_session_id, last.lastedit_date, last.visibility, last.insert_user_id
                         FROM  ".$TABLE_ITEMPROPERTY."  AS last, ".$TABLE_DOCUMENT."  AS docs
@@ -528,7 +530,9 @@ return 'application/octet-stream';
                         AND docs.path NOT LIKE '".$path.$added_slash."%/%'
                         AND last.tool = '".TOOL_DOCUMENT."'
                         AND ".$to_field." = ".$to_value."
-                        AND last.visibility".$visibility_bit.$condition_session;
+                        AND last.visibility".$visibility_bit.$condition_session." AND 
+            			docs.c_id = {$_course['real_id']} AND 
+            			last.c_id = {$_course['real_id']}  ";
         }
 		
         $result = Database::query($sql);
@@ -649,8 +653,8 @@ return 'application/octet-stream';
      * @return array with paths
      */
     public static function get_all_document_folders ($_course, $to_group_id = '0', $can_see_invisible = false) {
-        $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
-        $TABLE_DOCUMENT     = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
+        $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+        $TABLE_DOCUMENT     = Database::get_course_table(TABLE_DOCUMENT);
 
         $to_group_id = intval($to_group_id);
 
@@ -659,11 +663,12 @@ return 'application/octet-stream';
             $session_id = api_get_session_id();
             $condition_session = api_get_session_condition($session_id);
             $sql = "SELECT DISTINCT path FROM  ".$TABLE_ITEMPROPERTY."  AS last, ".$TABLE_DOCUMENT."  AS docs
-                                WHERE docs.id = last.ref
-                                AND docs.filetype = 'folder'
-                                AND last.tool = '".TOOL_DOCUMENT."'
-                                AND last.to_group_id = ".$to_group_id."
-                                AND last.visibility <> 2 $condition_session";
+					WHERE 	docs.id 			= last.ref AND 
+							docs.filetype 		= 'folder' AND 
+							last.tool 			= '".TOOL_DOCUMENT."' AND 
+							last.to_group_id	= ".$to_group_id." AND 
+            				last.visibility 	<> 2 $condition_session AND 
+            				docs.c_id 			= {$_course['real_id']} ";
 
             $result = Database::query($sql);
 
@@ -692,7 +697,7 @@ return 'application/octet-stream';
                         AND docs.filetype = 'folder'
                         AND last.tool = '".TOOL_DOCUMENT."'
                         AND last.to_group_id = ".$to_group_id."
-                        AND last.visibility = 1 $condition_session";
+                        AND last.visibility = 1 $condition_session AND docs.c_id = {$_course['real_id']} ";
             $visibleresult = Database::query($visible_sql);
             while ($all_visible_folders = Database::fetch_array($visibleresult, 'ASSOC')) {
                 $visiblefolders[] = $all_visible_folders['path'];
@@ -707,7 +712,7 @@ return 'application/octet-stream';
                         AND docs.filetype = 'folder'
                         AND last.tool = '".TOOL_DOCUMENT."'
                         AND last.to_group_id = ".$to_group_id."
-                        AND last.visibility = 0 $condition_session";
+                        AND last.visibility = 0 $condition_session AND docs.c_id = {$_course['real_id']} ";
             $invisibleresult = Database::query($invisible_sql);
             while ($invisible_folders = Database::fetch_array($invisibleresult, 'ASSOC')) {
                 //condition for the session
@@ -721,7 +726,7 @@ return 'application/octet-stream';
                                 AND docs.filetype = 'folder'
                                 AND last.tool = '".TOOL_DOCUMENT."'
                                 AND last.to_group_id = ".$to_group_id."
-                                AND last.visibility = 1 $condition_session";
+                                AND last.visibility = 1 $condition_session AND docs.c_id = {$_course['real_id']}  ";
                 $folder_in_invisible_result = Database::query($folder_in_invisible_sql);
                 while ($folders_in_invisible_folder = Database::fetch_array($folder_in_invisible_result, 'ASSOC')) {
                     $invisiblefolders[] = $folders_in_invisible_folder['path'];
@@ -730,20 +735,15 @@ return 'application/octet-stream';
             //if both results are arrays -> //calculate the difference between the 2 arrays -> only visible folders are left :)
             if (is_array($visiblefolders) && is_array($invisiblefolders)) {
                 $document_folders = array_diff($visiblefolders, $invisiblefolders);
-
-                //sort($document_folders);
                 natsort($document_folders);
-
                 return $document_folders;
-            }
-            //only visible folders found
-            elseif (is_array($visiblefolders)) {
+            } elseif (is_array($visiblefolders)) {
+            	//only visible folders found
                 //sort($visiblefolders);
                 natsort($visiblefolders);
                 return $visiblefolders;
-            }
-            //no visible folders found
-            else {
+            } else {
+            	//no visible folders found
                 return false;
             }
         }
@@ -763,16 +763,19 @@ return 'application/octet-stream';
         if (!(!empty($document_id) && is_numeric($document_id))) {
             $document_id = self::get_document_id($_course, $file);
         }
-
-        $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
-        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
-
+        $TABLE_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
+		$course_id 		= $_course['real_id'];
+		
         if ($to_delete) {
             if (self::is_folder($_course, $document_id)) {
                 if (!empty($file)) {
                     $path = Database::escape_string($file);
                     $what_to_check_sql = "SELECT td.id, readonly, tp.insert_user_id FROM ".$TABLE_DOCUMENT." td , $TABLE_PROPERTY tp
-                                          WHERE tp.ref= td.id and (path='".$path."' OR path LIKE BINARY '".$path."/%' ) ";
+                                          WHERE td.c_id = $course_id AND
+                                          		tp.c_id = $course_id AND
+                    							tp.ref= td.id AND 
+                    							(path='".$path."' OR path LIKE BINARY '".$path."/%' ) ";
                     //get all id's of documents that are deleted
                     $what_to_check_result = Database::query($what_to_check_sql);
 
@@ -800,7 +803,10 @@ return 'application/octet-stream';
 
         if (!empty($document_id)) {
             $sql= 'SELECT a.insert_user_id, b.readonly FROM '.$TABLE_PROPERTY.' a,'.$TABLE_DOCUMENT.' b
-                   WHERE a.ref = b.id and a.ref='.$document_id.' LIMIT 1';
+                   WHERE 
+            			a.c_id = $course_id AND
+                        b.c_id = $course_id AND
+            			a.ref = b.id and a.ref='.$document_id.' LIMIT 1';
             $resultans   =  Database::query($sql);
             $doc_details =  Database ::fetch_array($resultans, 'ASSOC');
 
@@ -818,10 +824,10 @@ return 'application/octet-stream';
      * @return boolean true/false
      **/
     public static function is_folder($_course, $document_id) {
-        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
-        //if (!empty($document_id))
+        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
+		$course_id = $_course['real_id'];
         $document_id = Database::escape_string($document_id);
-        $result = Database::fetch_array(Database::query('SELECT filetype FROM '.$TABLE_DOCUMENT.' WHERE id='.$document_id.''), 'ASSOC');
+        $result = Database::fetch_array(Database::query("SELECT filetype FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND id= $document_id"), 'ASSOC');
         return $result['filetype'] == 'folder';
     }
 
@@ -836,15 +842,18 @@ return 'application/octet-stream';
      * @todo now only files/folders in a folder get visibility 2, we should rename them too.
      */
     public static function delete_document($_course, $path, $base_work_dir) {
-        $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $_course['dbName']);
-        $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
+        $TABLE_DOCUMENT 	= Database :: get_course_table(TABLE_DOCUMENT);
+        $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+        
+        $course_id = $_course['real_id'];
+        
         //first, delete the actual document...
         $document_id = self :: get_document_id($_course, $path);
         $new_path = $path.'_DELETED_'.$document_id;
         $current_session_id = api_get_session_id();
         if ($document_id) {
             if (api_get_setting('permanently_remove_deleted_files') == 'true') { //deleted files are *really* deleted
-                $what_to_delete_sql = "SELECT id FROM ".$TABLE_DOCUMENT." WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
+                $what_to_delete_sql = "SELECT id FROM ".$TABLE_DOCUMENT." WHERE c_id = $course_id AND path='".$path."' OR path LIKE BINARY '".$path."/%'";
                 //get all id's of documents that are deleted
                 $what_to_delete_result = Database::query($what_to_delete_sql);
 
@@ -890,10 +899,10 @@ return 'application/octet-stream';
                     if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path)) {
                         if(rename($base_work_dir.$path, $base_work_dir.$new_path)) {
                             self::unset_document_as_template($document_id, api_get_course_id(), api_get_user_id());
-                            $sql = "UPDATE $TABLE_DOCUMENT set path='".$new_path."' WHERE id='".$document_id."'";
+                            $sql = "UPDATE $TABLE_DOCUMENT set path='".$new_path."' WHERE c_id = $course_id AND id='".$document_id."'";
                             if (Database::query($sql)) {
                                 //if it is a folder it can contain files
-                                $sql = "SELECT id,path FROM ".$TABLE_DOCUMENT." WHERE path LIKE BINARY '".$path."/%'";
+                                $sql = "SELECT id,path FROM ".$TABLE_DOCUMENT." WHERE c_id = $course_id AND path LIKE BINARY '".$path."/%'";
                                 $result = Database::query($sql);
                                 if ($result && Database::num_rows($result) > 0) {
                                     while ($deleted_items = Database::fetch_array($result, 'ASSOC')) {
@@ -933,7 +942,7 @@ return 'application/octet-stream';
                         // item_property and the document table.
                         error_log(__FILE__.' '.__LINE__.': System inconsistency detected. The file or directory '.$base_work_dir.$path.' seems to have been removed from the filesystem independently from the web platform. To restore consistency, the elements using the same path will be removed from the database',0);
 
-                        $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path='".$path."' OR path LIKE BINARY '".$path."/%'";
+                        $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND path='".$path."' OR path LIKE BINARY '".$path."/%'";
                         $res = Database::query($sql);
 
                         self::delete_document_from_search_engine(api_get_course_id(), $document_id);
@@ -991,9 +1000,10 @@ return 'application/octet-stream';
      * @return int id of document / false if no doc found
      */
     public static function get_document_id($course_info, $path) {
-        $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
+        $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
+        $course_id = $course_info['real_id'];
         $path = Database::escape_string($path);
-        $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE path LIKE BINARY '$path'";
+        $sql = "SELECT id FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND path LIKE BINARY '$path'";
         $result = Database::query($sql);
         if ($result && Database::num_rows($result) == 1) {
             $row = Database::fetch_array($result);
@@ -1012,14 +1022,16 @@ return 'application/octet-stream';
      */
     public static function get_document_data_by_id($id, $course_code, $load_parents = false) {
         $course_info = api_get_course_info($course_code);
+        $course_id 	 = $course_info['real_id'];
+        
         if (empty($course_info)) {
             return false;
         }
         $www = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/document';
         
-        $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
+        $TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
         $id = intval($id);
-        $sql = "SELECT * FROM $TABLE_DOCUMENT WHERE id = $id ";
+        $sql = "SELECT * FROM $TABLE_DOCUMENT WHERE c_id = $course_id AND id = $id ";
         $result = Database::query($sql);
         if ($result && Database::num_rows($result) == 1) {
             $row = Database::fetch_array($result,'ASSOC');
@@ -1137,8 +1149,10 @@ return 'application/octet-stream';
      * @param array  $course the _course array info of the document's course
      */
     public static function is_visible($doc_path, $course, $session_id = 0, $file_type = 'file') {
-        $docTable  = Database::get_course_table(TABLE_DOCUMENT, $course['dbName']);
-        $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY, $course['dbName']);
+        $docTable  = Database::get_course_table(TABLE_DOCUMENT);
+        $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY);
+        
+        $course_id = $course['real_id'];
         //note the extra / at the end of doc_path to match every path in the document table that is part of the document path
         $doc_path = Database::escape_string($doc_path);
 
@@ -1156,7 +1170,12 @@ return 'application/octet-stream';
             $file_type = 'file';
         }
 
-        $sql  = "SELECT visibility FROM $docTable d, $propTable ip WHERE d.id=ip.ref AND ip.tool='".TOOL_DOCUMENT."' $condition AND filetype='$file_type' AND locate(concat(path,'/'),'".$doc_path."/')=1";
+        $sql  = "SELECT visibility FROM $docTable d, $propTable ip
+        		 WHERE 	d.c_id  = $course_id  AND
+        		 		ip.c_id = $course_id AND        		  
+        				d.id = ip.ref AND 
+        				ip.tool = '".TOOL_DOCUMENT."' $condition AND 
+        				filetype = '$file_type' AND locate(concat(path,'/'),'".$doc_path."/')=1";
 
         $result = Database::query($sql);
         $is_visible = false;
@@ -1258,33 +1277,8 @@ return 'application/octet-stream';
     		}
     	} elseif ($admins_can_see_everything && api_is_platform_admin()) {
             return true;
-        }
-    	
+        }    	
     	return false;
-    	
-    	/*
-        $docTable  = Database::get_course_table(TABLE_DOCUMENT, 	 $course['dbName']);
-        $propTable = Database::get_course_table(TABLE_ITEM_PROPERTY, $course['dbName']);        
-        $condition = "AND id_session IN  ('$session_id', '0') ";
-        if (!in_array($file_type, array('file','folder'))) {
-            $file_type = 'file';
-        }
-
-        // The " d.filetype='file' " let the user see a file even if the folder is hidden see #2198
-        $sql  = "SELECT visibility FROM $docTable d, $propTable ip WHERE d.id = ip.ref AND ip.tool='".TOOL_DOCUMENT."' $condition AND filetype='$file_type' AND d.id = $id";
-        $result = Database::query($sql);
-        $is_visible = false;
-        if (Database::num_rows($result) > 0) {
-            $row = Database::fetch_array($result,'ASSOC');
-            if ($row['visibility'] == 1) {            	
-                $is_visible = $_SESSION['is_allowed_in_course'] || api_is_platform_admin();
-            }
-        }
-        
-        //improved protection of documents viewable directly through the url: incorporates the same protections of the course at the url of documents:  access allowed for the whole world Open, access allowed for users registered on the platform Private access, document accessible only to course members (see the Users list), Completely closed; the document is only accessible to the course admin and teaching assistants.
-        //return $_SESSION ['is_allowed_in_course'] || api_is_platform_admin();
-        return $is_visible;
-        */
     }
 
 
@@ -1332,28 +1326,28 @@ return 'application/octet-stream';
 
     /**
      * allow replace user info in file html
-     * @param string The course id
+     * @param string The course code
      * @return string The html content of the certificate
      */
-    function replace_user_info_into_html($user_id, $course_id, $is_preview = false) {
-        $user_id = intval($user_id);
-        $course_info = api_get_course_info($course_id);
-        $tbl_document = Database::get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
-        $document_id = self::get_default_certificate_id($course_id);
+    function replace_user_info_into_html($user_id, $course_code, $is_preview = false) {
+        $user_id 		= intval($user_id);
+        $course_info 	= api_get_course_info($course_code);
+        $tbl_document 	= Database::get_course_table(TABLE_DOCUMENT);
+        $course_id 		= $course_info['real_id']; 
+        $document_id 	= self::get_default_certificate_id($course_code);
 
-        $sql = 'SELECT path FROM '.$tbl_document.' WHERE id="'.Database::escape_string($document_id).'" ';
+        $sql = "SELECT path FROM $tbl_document WHERE c_id = $course_id AND id = $document_id";
 
         $rs = Database::query($sql);
         $new_content = '';
         $all_user_info = array();
         if (Database::num_rows($rs)) {
             $row=Database::fetch_array($rs);
-           $filepath = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document'.$row['path'];
-
+            $filepath = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document'.$row['path'];
             if (is_file($filepath)) {
                 $my_content_html = file_get_contents($filepath);
             }
-            $all_user_info = self::get_all_info_to_certificate($user_id, $course_id, $is_preview);            
+            $all_user_info = self::get_all_info_to_certificate($user_id, $course_code, $is_preview);            
             $info_to_be_replaced_in_content_html=$all_user_info[0];
             $info_to_replace_in_content_html=$all_user_info[1];
             $new_content=str_replace($info_to_be_replaced_in_content_html,$info_to_replace_in_content_html, $my_content_html);
@@ -1502,7 +1496,8 @@ return 'application/octet-stream';
      */
     function get_document_id_of_directory_certificate () {
         $tbl_document=Database::get_course_table(TABLE_DOCUMENT);
-        $sql='SELECT id FROM '.$tbl_document.' WHERE path="/certificates" ';
+        $course_id = api_get_course_int_id();
+        $sql = "SELECT id FROM $tbl_document WHERE c_id = $course_id AND path='/certificates' ";
         $rs=Database::query($sql);
         $row=Database::fetch_array($rs);
         return $row['id'];
@@ -1994,7 +1989,7 @@ return 'application/octet-stream';
         } else {
             $destination = $destiny_path.'/'.$file_name;
         }
-        var_dump("From $original ", "to $destination");
+        //var_dump("From $original ", "to $destination");
         $original_count     = count(explode('/', $original));
         $destination_count  = count(explode('/', $destination));
         if ($original_count == $destination_count) {
@@ -2008,8 +2003,7 @@ return 'application/octet-stream';
         } else {
             $mode = 'inside';
         }
-        echo $original_count.' '.$destination_count;
-        var_dump($mode);
+        //echo $original_count.' '.$destination_count; var_dump($mode);
         //We do not select the $original_path becayse the file was already moved 
         $content_html = file_get_contents($destiny_path.'/'.$file_name);
         $destination_file = $destiny_path.'/'.$file_name;
@@ -2018,14 +2012,14 @@ return 'application/octet-stream';
         $pre_original = strstr($original_path, 'document');
         $pre_destin   = strstr($destiny_path, 'document');
         
-        var_dump ("pre_original $pre_original");
-        var_dump ("pre_destin $pre_destin");
+        //var_dump ("pre_original $pre_original");
+        //var_dump ("pre_destin $pre_destin");
 
         $pre_original = substr($pre_original, 8, strlen($pre_original));
         $pre_destin = substr($pre_destin, 8, strlen($pre_destin));
         
-        var_dump ("pre_original $pre_original");
-        var_dump ("pre_destin $pre_destin");
+        //var_dump ("pre_original $pre_original");
+        //var_dump ("pre_destin $pre_destin");
 
         $levels = count(explode('/', $pre_destin)) - 1 ;
         $link_to_add = '';
@@ -2049,10 +2043,10 @@ return 'application/octet-stream';
             $pre_destin = '..'.$pre_destin.'/';
         }
 
-        var_dump($pre_original);
+        //var_dump($pre_original);
         
         $levels = explode('/', $pre_original);
-        var_dump($levels);
+        //var_dump($levels);
         
         $count_pre_destination_levels = 0;
         foreach($levels as $item) {
@@ -2065,17 +2059,17 @@ return 'application/octet-stream';
         if ($count_pre_destination_levels == 0 ) {
             $count_pre_destination_levels = 1;
         }
-        echo '$count_pre_destination_levels '. $count_pre_destination_levels;
+        //echo '$count_pre_destination_levels '. $count_pre_destination_levels;
         $pre_remove = '';
         for ($i=1; $i <= $count_pre_destination_levels; $i++) {
             $pre_remove .='..\/';
         }
          
-        var_dump(' link to add '.$link_to_add.'  -- remove '.$pre_remove);
+        //var_dump(' link to add '.$link_to_add.'  -- remove '.$pre_remove);
 
         $orig_source_html   = DocumentManager::get_resources_from_source_html($content_html);
 
-        var_dump($orig_source_html);
+        //var_dump($orig_source_html);
          
         foreach ($orig_source_html as $source) {
 
@@ -2300,14 +2294,16 @@ return 'application/octet-stream';
      */
     function documents_total_space($to_group_id = '0') {
         $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
-        $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
-
-        $sql = "SELECT SUM(size)
-        FROM  ".$TABLE_ITEMPROPERTY."  AS props, ".$TABLE_DOCUMENT."  AS docs
-        WHERE docs.id = props.ref
-        AND props.tool = '".TOOL_DOCUMENT."'
-        AND props.to_group_id='".$to_group_id."'
-        AND props.visibility <> 2";
+        $TABLE_DOCUMENT 	= Database::get_course_table(TABLE_DOCUMENT);
+		$course_id = api_get_course_int_id();
+		
+        $sql = "SELECT SUM(size) FROM  ".$TABLE_ITEMPROPERTY."  AS props, ".$TABLE_DOCUMENT."  AS docs
+		        WHERE 	props.c_id 	= $course_id AND
+		        		docs.c_id 	= $course_id AND		        
+		        		docs.id 	= props.ref AND 
+		        		props.tool 	= '".TOOL_DOCUMENT."' AND 
+		        		props.to_group_id='".$to_group_id."' AND 
+        				props.visibility <> 2";
 
         $result = Database::query($sql);
 
@@ -2327,11 +2323,9 @@ return 'application/octet-stream';
         $course_quota_m = round($course_quota / 1000000);
         $already_consumed_space_m = round($already_consumed_space / 1000000);
 
-
         $message = get_lang('MaximumAllowedQuota') . ' <strong>'.$course_quota_m.' megabyte</strong>.<br />';
         $message .= get_lang('CourseCurrentlyUses') . ' <strong>' . $already_consumed_space_m . ' megabyte</strong>.<br />';
 
-
         $percentage = $already_consumed_space / $course_quota * 100;
 
         $percentage = round($percentage, 1);
@@ -2462,9 +2456,7 @@ return 'application/octet-stream';
     
     function get_document_preview($course_info, $lp_id = false, $target = '', $session_id = 0) {
     	
-    	if (!isset($course_info['dbName'])) {
-    		$course_info = api_get_course_info($course_info['code']);
-    	}  
+    	$course_info = api_get_course_info($course_info['code']);    	  
     	
     	if (empty($course_info) || !is_array($course_info)) {
     		return '';
@@ -2504,8 +2496,8 @@ return 'application/octet-stream';
         }
             	
     	$tbl_course 	= Database::get_main_table(TABLE_MAIN_COURSE);
-    	$tbl_doc 		= Database::get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
-    	$tbl_item_prop 	= Database::get_course_table(TABLE_ITEM_PROPERTY, $course_info['dbName']);
+    	$tbl_doc 		= Database::get_course_table(TABLE_DOCUMENT);
+    	$tbl_item_prop 	= Database::get_course_table(TABLE_ITEM_PROPERTY);
     	
     	$path = '/';
     	$path = Database::escape_string(str_replace('_', '\_', $path));
@@ -2515,13 +2507,15 @@ return 'application/octet-stream';
     	//$condition_session = " AND (id_session = '$session_id' OR (id_session = '0' AND insert_date <= (SELECT creation_date FROM $tbl_course WHERE code = '".$course_info['code']."' )))";
     	$condition_session = " AND (id_session = '$session_id' OR  id_session = '0' )";
     	
-		$sql_doc = "SELECT last.visibility, docs.* ".
-    				" FROM  $tbl_item_prop AS last, $tbl_doc AS docs ".
-    	            " WHERE docs.id = last.ref ".
+		$sql_doc = "SELECT last.visibility, docs.*  
+					FROM  $tbl_item_prop AS last, $tbl_doc AS docs 
+    	            WHERE docs.id = last.ref ".
     	            "   AND docs.path LIKE '".$path.$added_slash."%' ".
     	            "   AND docs.path NOT LIKE '%_DELETED_%' ".
     	            "   AND last.tool = '".TOOL_DOCUMENT."' $condition_session ". 
-    	            "   AND last.visibility = '1' ".
+    	            "   AND last.visibility = '1' AND ".
+    	            "	docs.c_id = {$course_info['real_id']} AND 
+    	            	last.c_id = {$course_info['real_id']} ".
 					"ORDER BY docs.path ASC";
     	$res_doc 	= Database::query($sql_doc);
     	$resources  = Database::store_result($res_doc, 'ASSOC');
@@ -2580,7 +2574,6 @@ return 'application/octet-stream';
 		    		if (empty($resource['title'])) {
 		    			$resource['title'] = basename($resource['path']);
 		    		}
-		    		//eval ('$resources_sorted'.$path_to_eval.'['.$resource['id'].'] = "'.$resource['title']."/". $last_path.'";');
 		    		eval ('$resources_sorted'.$path_to_eval.'['.$resource['id'].'] = "'.$data.'" ; ');
 		    	} else {
 		    		eval ('$resources_sorted'.$path_to_eval.'["'.$last_path.'"]["id"]='.$resource['id'].';');
@@ -2589,7 +2582,7 @@ return 'application/octet-stream';
     	}
     	
     	$label = get_lang('Documents');
-    	//var_dump($resources_sorted);
+
     	$new_array[$label] = array('id' => 0, 'files' => $resources_sorted);
     	
     	$write_result = self::write_resources_tree($course_info, $session_id, $new_array, 0, $lp_id, $target);
@@ -2645,9 +2638,9 @@ return 'application/octet-stream';
     public function write_resources_tree($course_info, $session_id, $resources_sorted, $num = 0, $lp_id = false, $target = '') {
     	require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php';
     	
-    	$img_path = api_get_path(WEB_IMG_PATH);
-    	$img_sys_path = api_get_path(SYS_CODE_PATH).'img/';
-    	$web_code_path = api_get_path(WEB_CODE_PATH);
+    	$img_path 		= api_get_path(WEB_IMG_PATH);
+    	$img_sys_path 	= api_get_path(SYS_CODE_PATH).'img/';
+    	$web_code_path 	= api_get_path(WEB_CODE_PATH);
     	
     	$return = '';
     	if (count($resources_sorted) > 0) {
@@ -2762,6 +2755,7 @@ return 'application/octet-stream';
     		return false;
     	}    	
     }
+    
     /**
      * Index a given document.
      * @param   int     Document ID inside its corresponding course
@@ -2788,8 +2782,10 @@ return 'application/octet-stream';
         $sys_course_path  = api_get_path(SYS_COURSE_PATH);
         $base_work_dir    = $sys_course_path.$course_dir;
         
-        $table_document = Database::get_course_table(TABLE_DOCUMENT,$course_info['db_name']);
-        $qry = "SELECT path, title FROM $table_document WHERE id = '$docid' LIMIT 1";
+        $course_id = $course_info['real_id'];
+        $table_document = Database::get_course_table(TABLE_DOCUMENT);
+        
+        $qry = "SELECT path, title FROM $table_document WHERE c_id = $course_id AND id = '$docid' LIMIT 1";
         $result = Database::query($qry);
         if (Database::num_rows($result) == 1) {
             $row = Database::fetch_array($result);

+ 50 - 36
main/inc/lib/events.lib.inc.php

@@ -379,9 +379,11 @@ function create_event_exercice($exo_id) {
 	$tbl_exe = Database::get_course_table(TABLE_QUIZ_TEST);
 	$now = api_get_utc_datetime();
 	$uid = api_get_user_id();
+	
+	$course_id = api_get_course_int_id();
 
     // First, check the exercise exists
-    $sql_exe_id="SELECT exercises.id FROM $tbl_exe as exercises WHERE exercises.id=$exo_id";
+    $sql_exe_id="SELECT exercises.id FROM $tbl_exe as exercises WHERE c_id = $course_id AND exercises.id=$exo_id";
     $res_exe_id=Database::query($sql_exe_id);
     if ($res_exe_id === false) { return false; } //sql error
     if (Database::num_rows($res_exe_id)<1) { return false;} //exe not found
@@ -588,9 +590,15 @@ function get_attempt_count($user_id, $exerciseId, $lp_id, $lp_item_id,$lp_item_v
 	$lp_item_id 	= intval($lp_item_id);
     $lp_item_view_id= intval($lp_item_view_id);
 	
-   	$sql = "SELECT count(*) as count FROM $stat_table WHERE exe_exo_id = '$exerciseId'
-            AND exe_user_id = '$user_id' AND status != 'incomplete'
-            AND orig_lp_id 	= $lp_id AND orig_lp_item_id = $lp_item_id AND orig_lp_item_view_id = $lp_item_view_id AND exe_cours_id = '".api_get_course_id()."' AND session_id = '" . api_get_session_id() . "'";
+   	$sql = "SELECT count(*) as count FROM $stat_table WHERE 	
+   				exe_exo_id 			= '$exerciseId' AND 
+   				exe_user_id 		= '$user_id' AND
+   				status 				!= 'incomplete' AND 
+   				orig_lp_id 			= $lp_id AND 
+   				orig_lp_item_id 	= $lp_item_id AND 
+   				orig_lp_item_view_id = $lp_item_view_id AND 
+   				exe_cours_id = '".api_get_course_id()."' AND 
+   				session_id = '" . api_get_session_id() . "'";
 
     $query = Database::query($sql);
     if (Database::num_rows($query) > 0 ) {
@@ -601,11 +609,39 @@ function get_attempt_count($user_id, $exerciseId, $lp_id, $lp_item_id,$lp_item_v
     } 
 }
 
+function get_attempt_count_not_finished($user_id, $exerciseId, $lp_id, $lp_item_id) {
+	$stat_table 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+	$user_id 		= intval($user_id);
+	$exerciseId 	= intval($exerciseId);
+	$lp_id 			= intval($lp_id);
+	$lp_item_id 	= intval($lp_item_id);
+	$lp_item_view_id= intval($lp_item_view_id);
+
+	$sql = "SELECT count(*) as count FROM $stat_table WHERE
+   				exe_exo_id 			= $exerciseId AND 
+   				exe_user_id 		= $user_id AND
+   				status 				!= 'incomplete' AND 
+   				orig_lp_id 			= $lp_id AND 
+   				orig_lp_item_id 	= $lp_item_id AND
+   				exe_cours_id = '".api_get_course_id()."' AND 
+   				session_id = '" . api_get_session_id() . "'";
+
+	$query = Database::query($sql);
+	if (Database::num_rows($query) > 0 ) {
+		$attempt = Database :: fetch_array($query,'ASSOC');
+		return $attempt['count'];
+	} else {
+		return 0;
+	}
+}
+
+
 
 function delete_student_lp_events($user_id, $lp_id, $course, $session_id) {
         
-	$lp_view_table         = Database::get_course_table(TABLE_LP_VIEW, $course['dbName']);
-    $lp_item_view_table    = Database::get_course_table(TABLE_LP_ITEM_VIEW, $course['dbName']);
+	$lp_view_table         = Database::get_course_table(TABLE_LP_VIEW);
+    $lp_item_view_table    = Database::get_course_table(TABLE_LP_ITEM_VIEW);
+    $course_id 			   = $course['real_id'];
     
     $track_e_exercises     = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
     $track_attempts        = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
@@ -616,15 +652,15 @@ function delete_student_lp_events($user_id, $lp_id, $course, $session_id) {
     $session_id            = intval($session_id);
     
     //make sure we have the exact lp_view_id
-    $sqlview       = "SELECT id FROM $lp_view_table WHERE user_id = $user_id AND lp_id = $lp_id AND session_id = $session_id ";                    
+    $sqlview       = "SELECT id FROM $lp_view_table WHERE c_id = $course_id AND user_id = $user_id AND lp_id = $lp_id AND session_id = $session_id ";                    
     $resultview    = Database::query($sqlview);
     $view          = Database::fetch_array($resultview, 'ASSOC');
     $lp_view_id    = $view['id'];                  
     
-    $sql_delete = "DELETE FROM $lp_item_view_table  WHERE lp_view_id = $view_id ";
+    $sql_delete = "DELETE FROM $lp_item_view_table  WHERE c_id = $course_id AND lp_view_id = $view_id ";
     $result = Database::query($sql_delete);
         
-    $sql_delete = "DELETE FROM $lp_view_table  WHERE user_id = $user_id AND lp_id= $lp_id AND session_id= $session_id ";
+    $sql_delete = "DELETE FROM $lp_view_table  WHERE c_id = $course_id AND user_id = $user_id AND lp_id= $lp_id AND session_id= $session_id ";
     $result = Database::query($sql_delete);
     
     $select_all_attempts = "SELECT exe_id FROM $track_e_exercises WHERE exe_user_id = $user_id AND session_id= $session_id  AND exe_cours_id = '{$course['code']}' AND orig_lp_id = $lp_id";    
@@ -965,8 +1001,7 @@ function get_all_exercise_event_from_lp($exercise_id, $course_code, $session_id
 	$table_track_attempt   = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $course_code = Database::escape_string($course_code);
     $exercise_id = intval($exercise_id);
-    $session_id = intval($session_id);
-    
+    $session_id = intval($session_id);    
   
     $sql = "SELECT * FROM $table_track_exercises WHERE status = ''  AND exe_cours_id = '$course_code' AND exe_exo_id = '$exercise_id' AND session_id = $session_id AND orig_lp_id !=0 AND orig_lp_item_id != 0";
     
@@ -982,34 +1017,13 @@ function get_all_exercise_event_from_lp($exercise_id, $course_code, $session_id
     }
     return $list;
 }
-/*
-function get_all_exercise_event_from_lp($exercise_id, $course_db, $session_id ) {
-	$lp_item_table = Database  :: get_course_table(TABLE_LP_ITEM,$course_db);
-	$lp_item_view_table = Database  :: get_course_table(TABLE_LP_ITEM_VIEW,$course_db);
-	$lp_view_table = Database  :: get_course_table(TABLE_LP_VIEW,$course_db);
-	
-	$exercise_id 	= intval($exercise_id);
-	$session_id 	= intval($session_id);
-	
-	$sql = "SELECT  title, user_id, score , iv.max_score, status, session_id 
-			FROM $lp_item_table as i INNER JOIN $lp_item_view_table iv ON (i.id = iv.lp_item_id ) INNER JOIN $lp_view_table v ON iv.lp_view_id = v.id 
-			WHERE path = $exercise_id AND status ='completed' AND session_id = $session_id";
-	$res = Database::query($sql);
-	$list = array();	
-	
-	while($row = Database::fetch_array($res,'ASSOC')) {		
-		$list[$row['exe_id']]['question_list'][$row['question_id']] = $row;				
-	}
-	//echo '<pre>'; print_r($list);
-	return $list;
-}*/
-
 
 
-function get_all_exercises_from_lp($lp_id, $course_db) {
-	$lp_item_table = Database  :: get_course_table(TABLE_LP_ITEM,$course_db);
+function get_all_exercises_from_lp($lp_id, $course_id) {
+	$lp_item_table = Database  :: get_course_table(TABLE_LP_ITEM);
+	$course_id = intval($course_id);
 	$lp_id = intval($lp_id);
-	$sql = "SELECT * FROM $lp_item_table WHERE lp_id = '".$lp_id."'  ORDER BY parent_item_id, display_order";
+	$sql = "SELECT * FROM $lp_item_table WHERE c_id = $course_id AND lp_id = '".$lp_id."'  ORDER BY parent_item_id, display_order";
 	$res = Database::query($sql);
 	$my_exercise_list = array();	
 	while($row = Database::fetch_array($res,'ASSOC')) {

+ 1 - 1
main/inc/lib/fckeditor/myconfig.php

@@ -142,7 +142,7 @@ if (api_get_setting('youtube_for_students') == 'true') {
     }
 }
 
-// googlemaps : Adds a dilog for inserting Google maps.
+// googlemaps : Adds a dialog for inserting Google maps.
 if ((api_get_setting('enabled_googlemaps') == 'true')) {
     $config['LoadPlugin'][] = 'googlemaps';
 

+ 15 - 20
main/inc/lib/fileDisplay.lib.php

@@ -228,33 +228,28 @@ function folder_size($dir_name)
  * @param 	boolean $can_see_invisible
  * @return 	Total size
  */
-function get_total_folder_size($path, $can_see_invisible = false)
-{
+function get_total_folder_size($path, $can_see_invisible = false) {
     $table_itemproperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
-    $table_document = Database::get_course_table(TABLE_DOCUMENT);
-    $tool_document = TOOL_DOCUMENT;
+    $table_document 	= Database::get_course_table(TABLE_DOCUMENT);
+    $tool_document 		= TOOL_DOCUMENT;
+    
+    $course_id 			= api_get_course_int_id();
 
     $visibility_rule = 'props.visibility ' . ($can_see_invisible ? '<> 2' : '= 1');
 
-    $sql = <<<EOQ
-SELECT SUM(size)
-    FROM $table_itemproperty AS props, $table_document AS docs
-    WHERE docs.id = props.ref
-        AND props.tool = '$tool_document'
-        AND path LIKE '$path/%'
-        AND $visibility_rule
-EOQ;
+    $sql = "SELECT SUM(size) FROM $table_itemproperty AS props, $table_document AS docs
+    		WHERE 	docs.c_id 	= $course_id AND
+    				props.c_id 	= $course_id AND    		
+    				docs.id 	= props.ref AND 
+    				props.tool 	= '$tool_document' AND 
+    				path LIKE '$path/%' AND 
+    				$visibility_rule";
 
     $result = Database::query($sql);
-
-    if($result && Database::num_rows($result) != 0)
-    {
+    if($result && Database::num_rows($result) != 0) {
         $row = Database::fetch_row($result);
         return $row[0] == null ? 0 : $row[0];
-    }
-    else
-    {
+    } else {
         return 0;
     }
-}
-?>
+}

+ 22 - 15
main/inc/lib/fileUpload.lib.php

@@ -822,10 +822,10 @@ function add_document($_course, $path, $filetype, $filesize, $title, $comment =
 	$filetype      = Database::escape_string($filetype);
 	$filesize      = intval($filesize);
 	
-	$table_document = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
-	$sql = "INSERT INTO $table_document (path, filetype, size, title, comment, readonly, session_id)
-	        VALUES ('$path','$filetype','$filesize','".
-	Database::escape_string($title)."', '$comment', $readonly, $session_id)";
+	$table_document = Database::get_course_table(TABLE_DOCUMENT);
+	$sql = "INSERT INTO $table_document (c_id, path, filetype, size, title, comment, readonly, session_id)
+	        VALUES ({$_course['real_id']}, '$path','$filetype','$filesize','".Database::escape_string($title)."', '$comment', $readonly, $session_id)";
+	
 	if (Database::query($sql)) {
 		//display_message("Added to database (id ".Database::insert_id().")!");
 		return Database::insert_id();
@@ -846,11 +846,14 @@ function add_document($_course, $path, $filetype, $filesize, $title, $comment =
  * @return boolean true /false
  */
 function update_existing_document($_course, $document_id, $filesize, $readonly = 0) {
-	$document_table = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
-	$document_id = intval($document_id);
-	$filesize = intval($filesize);
-	$readonly = intval($readonly);
-	$sql = "UPDATE $document_table SET size = '$filesize' , readonly = '$readonly' WHERE id = $document_id";
+	$document_table = Database::get_course_table(TABLE_DOCUMENT);
+	$document_id 	= intval($document_id);
+	$filesize 		= intval($filesize);
+	$readonly 		= intval($readonly);
+	$course_id 		= $_course['real_id'];
+	
+	$sql = "UPDATE $document_table SET size = '$filesize' , readonly = '$readonly' 
+			WHERE c_id = $course_id AND id = $document_id";
 	if (Database::query($sql)) {
 		return true;
 	} else {
@@ -880,7 +883,7 @@ function item_property_update_on_folder($_course, $path, $user_id) {
 		$path = substr($path, 0, strlen($path) - 1);
 	}
 
-	$TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
+	$TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
 
 	// Get the time
 	$time = date('Y-m-d H:i:s', time());
@@ -890,7 +893,7 @@ function item_property_update_on_folder($_course, $path, $user_id) {
 	// if file is updated, subsubfolder, subfolder and folder are updated
 
 	$exploded_path = explode('/', $path);
-
+	$course_id = api_get_course_int_id();
 	foreach ($exploded_path as $key => & $value) {
 		// We don't want a slash before our first slash
 		if ($key != 0) {
@@ -901,7 +904,8 @@ function item_property_update_on_folder($_course, $path, $user_id) {
 			$folder_id = DocumentManager::get_document_id($_course, $newpath);
 
 			if ($folder_id) {
-				$sql = "UPDATE $TABLE_ITEMPROPERTY SET lastedit_date='$time',lastedit_type='DocumentInFolderUpdated', lastedit_user_id='$user_id' WHERE tool='".TOOL_DOCUMENT."' AND ref='$folder_id'";
+				$sql = "UPDATE $TABLE_ITEMPROPERTY SET lastedit_date='$time',lastedit_type='DocumentInFolderUpdated', lastedit_user_id='$user_id' 
+						WHERE c_id = $course_id AND tool='".TOOL_DOCUMENT."' AND ref='$folder_id'";
 				Database::query($sql);
 			}
 		}
@@ -1044,13 +1048,16 @@ function create_unexisting_directory($_course, $user_id, $session_id, $to_group_
 	if ($title == null) {
 		$title = basename($desired_dir_name);
 	}
+	$course_id = $_course['real_id'];
+	
 	if (mkdir($base_work_dir.$desired_dir_name.$nb, api_get_permissions_for_new_directories(), true)) {
 		// Check if pathname already exists inside document table
-		$tbl_document = Database::get_course_table(TABLE_DOCUMENT, $_course['dbName']);
-		$sql = "SELECT path FROM $tbl_document WHERE path='".$desired_dir_name.$nb."'";
+		$tbl_document = Database::get_course_table(TABLE_DOCUMENT);
+		$sql = "SELECT path FROM $tbl_document WHERE c_id = $course_id AND path='".$desired_dir_name.$nb."'";
+	
 		$rs = Database::query($sql);
 		if (Database::num_rows($rs) == 0) {
-			$document_id = add_document($_course, $desired_dir_name.$nb, 'folder', 0, $title);
+			$document_id = add_document($_course, $desired_dir_name.$nb, 'folder', 0, $title);			
 			if ($document_id) {
 				// Update document item_property					
 				if ($visibility !== '') {

+ 30 - 16
main/inc/lib/glossary.lib.php

@@ -59,7 +59,7 @@ class GlossaryManager {
 		$glossary_table  = Database::get_course_table(TABLE_GLOSSARY);
         $session_id = intval($session_id);
         $sql_filter = api_get_session_condition($session_id);
-		$sql = 'SELECT description FROM '.$glossary_table.' WHERE name like trim("'.Database::escape_string($glossary_name).'")'.$sql_filter;
+		$sql = 'SELECT description FROM '.$glossary_table.' WHERE name LIKE trim("'.Database::escape_string($glossary_name).'")'.$sql_filter;
 		$rs = Database::query($sql);
 		if (Database::num_rows($rs) > 0) {
 		     $row = Database::fetch_array($rs);
@@ -91,14 +91,14 @@ class GlossaryManager {
 		$session_id = api_get_session_id();
 
 		// check if the glossary term already exists
-		if (GlossaryManager::glossary_exists($values['glossary_title']))
-		{
+		if (GlossaryManager::glossary_exists($values['glossary_title'])) {
 			// display the feedback message
 			Display::display_error_message(get_lang('GlossaryTermAlreadyExistsYouShouldEditIt'));
 			return false;
 		} else {
-			$sql = "INSERT INTO $t_glossary (name, description, display_order, session_id)
+			$sql = "INSERT INTO $t_glossary (c_id, name, description, display_order, session_id)
 					VALUES(
+						".api_get_course_int_id().",
 						'".Database::escape_string($values['glossary_title'])."',
 						'".Database::escape_string($values['glossary_comment'])."',
 						'".(int)($max_glossary_item + 1)."',
@@ -128,9 +128,11 @@ class GlossaryManager {
 	function update_glossary($values) {
 		// Database table definition
 		$t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
+		
+		$course_id = api_get_course_int_id();
+		
 		// check if the glossary term already exists
-		if (GlossaryManager::glossary_exists($values['glossary_title'],$values['glossary_id']))
-		{
+		if (GlossaryManager::glossary_exists($values['glossary_title'],$values['glossary_id'])) {
 			// display the feedback message
 			Display::display_error_message(get_lang('GlossaryTermAlreadyExistsYouShouldEditIt'));
 			return false;
@@ -138,7 +140,7 @@ class GlossaryManager {
 			$sql = "UPDATE $t_glossary SET
 							name 		= '".Database::escape_string($values['glossary_title'])."',
 							description	= '".Database::escape_string($values['glossary_comment'])."'
-					WHERE glossary_id = ".Database::escape_string($values['glossary_id']);
+					WHERE c_id = $course_id AND glossary_id = ".Database::escape_string($values['glossary_id']);
 			$result = Database::query($sql);
 			if ($result === false) { return false; }
 			//update glossary into item_property
@@ -159,7 +161,8 @@ class GlossaryManager {
 	function get_max_glossary_item() {
 		// Database table definition
 		$t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
-		$get_max = "SELECT MAX(display_order) FROM $t_glossary";
+		$course_id = api_get_course_int_id();
+		$get_max = "SELECT MAX(display_order) FROM $t_glossary WHERE c_id = $course_id ";
 		$res_max = Database::query($get_max);
 		if (Database::num_rows($res_max)==0) {
 			return 0;
@@ -186,8 +189,7 @@ class GlossaryManager {
 		$t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
 
 		$sql = "SELECT name FROM $t_glossary WHERE name = '".Database::escape_string($term)."'";
-		if ($not_id<>'')
-		{
+		if ($not_id<>'') {
 			$sql .= " AND glossary_id <> '".Database::escape_string($not_id)."'";
 		}
 		$result = Database::query($sql);
@@ -219,7 +221,12 @@ class GlossaryManager {
                         ip.lastedit_date    as update_date,						 
 						g.session_id 
 				   FROM $t_glossary g, $t_item_propery ip
-                   WHERE g.glossary_id = ip.ref AND tool = '".TOOL_GLOSSARY."' AND g.glossary_id = '".intval($glossary_id)."' ";
+                   WHERE 	g.glossary_id 	= ip.ref AND 
+                   			tool 			= '".TOOL_GLOSSARY."' AND 
+							g.glossary_id 	= '".intval($glossary_id)."' AND
+							g.c_id			= ".api_get_course_int_id()." AND
+							ip.c_id			= ".api_get_course_int_id()."
+					";
 		$result = Database::query($sql);
 		if ($result === false || Database::num_rows($result) != 1) {
 			return false;
@@ -238,9 +245,11 @@ class GlossaryManager {
 	function delete_glossary($glossary_id) {
 		// Database table definition
 		$t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
+		$course_id = api_get_course_int_id();
+		
 		if (empty($glossary_id)) { return false; }
 
-		$sql = "DELETE FROM $t_glossary WHERE glossary_id='".Database::escape_string($glossary_id)."'";
+		$sql = "DELETE FROM $t_glossary WHERE c_id = $course_id AND glossary_id='".Database::escape_string($glossary_id)."'";
 		$result = Database::query($sql);
         if ($result === false or Database::affected_rows() < 1) { return false; }
 		//update item_property (delete)
@@ -328,9 +337,11 @@ class GlossaryManager {
 	function get_number_glossary_terms($session_id=0) {
 		// Database table definition
 		$t_glossary = Database :: get_course_table(TABLE_GLOSSARY);
+		$course_id = api_get_course_int_id();
+		
 		$session_id = intval($session_id);
 		$sql_filter = api_get_session_condition($session_id, true, true);
-		$sql = "SELECT count(glossary_id) as total FROM $t_glossary WHERE 1=1 $sql_filter";
+		$sql = "SELECT count(glossary_id) as total FROM $t_glossary WHERE 1=1 AND c_id = $course_id $sql_filter";
 		$res = Database::query($sql);
 		if ($res === false) { return 0; }
 		$obj = Database::fetch_object($res);
@@ -377,8 +388,10 @@ class GlossaryManager {
 					   $col2
 					   glossary.session_id as session_id
 				FROM $t_glossary glossary, $t_item_propery ip
-				WHERE glossary.glossary_id = ip.ref
-				AND tool = '".TOOL_GLOSSARY."' $condition_session
+				WHERE 	glossary.glossary_id = ip.ref AND 
+						tool = '".TOOL_GLOSSARY."' $condition_session AND
+						glossary.c_id = ".api_get_course_int_id()." AND
+						ip.c_id = ".api_get_course_int_id()."
 		        ORDER BY col$column $direction 
 		        LIMIT $from,$number_of_items";
         $res = Database::query($sql);
@@ -489,7 +502,8 @@ class GlossaryManager {
 
 		$i = 1;
 		while ($data = Database::fetch_array($res)) {
-			$sql_reorder = "UPDATE $t_glossary SET display_order = $i WHERE glossary_id = '".Database::escape_string($data['glossary_id'])."'";
+			$sql_reorder = "UPDATE $t_glossary SET display_order = $i 
+							WHERE glossary_id = '".Database::escape_string($data['glossary_id'])."'";
 			Database::query($sql_reorder);
 			$i++;
 		}

+ 161 - 139
main/inc/lib/groupmanager.lib.php

@@ -82,20 +82,26 @@ class GroupManager {
 		$course_db = '';
 		$my_user_id=api_get_user_id();
 		$my_status_of_user_in_course='';
+		/*
 		if ($course_code != null) {
 			$course_info = Database :: get_course_info($course_code);
 			$course_db = $course_info['database'];
 		} else {
 			$my_course_code=api_get_course_id();
 		}
-		$table_group = Database :: get_course_table(TABLE_GROUP, $course_db);
-		$table_user = Database :: get_main_table(TABLE_MAIN_USER);
-		$table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
-		$table_group_user = Database :: get_course_table(TABLE_GROUP_USER, $course_db);
+		*/
+		$course_info 	= api_get_course_info($course_code);
+		
+		$course_id = $course_info['real_id'];
+				
+		$table_group 		= Database :: get_course_table(TABLE_GROUP);
+		$table_user 		= Database :: get_main_table(TABLE_MAIN_USER);
+		$table_course 		= Database :: get_main_table(TABLE_MAIN_COURSE);
+		$table_group_user 	= Database :: get_course_table(TABLE_GROUP_USER);
 
 		//condition for the session
 		$session_id = api_get_session_id();
-		$my_status_of_user_in_course = CourseManager::get_user_in_course_status($my_user_id,$my_course_code);
+		$my_status_of_user_in_course = CourseManager::get_user_in_course_status($my_user_id, $course_info['code']);
 
 		$is_student_in_session = false;
 		if (is_null($my_status_of_user_in_course) || $my_status_of_user_in_course=='') {//into session
@@ -119,10 +125,9 @@ class GroupManager {
 						COUNT(ug2.id) number_of_members
 					FROM ".$table_group." g
 					LEFT JOIN ".$table_group_user." ug
-					ON ug.group_id = g.id AND ug.user_id = '".$_user['user_id']."'
+					ON ug.group_id = g.id AND ug.user_id = '".api_get_user_id()."'
 					LEFT JOIN ".$table_group_user." ug2
 					ON ug2.group_id = g.id";
-
 		} elseif ($my_status_of_user_in_course==STUDENT || $is_student_in_session===true || $_SESSION['studentview'] == 'studentview') {
 						$sql = "SELECT  g.id ,
 						g.name ,
@@ -137,22 +142,29 @@ class GroupManager {
 						COUNT(ug2.id) number_of_members
 					FROM ".$table_group." g
 					LEFT JOIN ".$table_group_user." ug
-					ON ug.group_id = g.id AND ug.user_id = '".$_user['user_id']."'
+					ON ug.group_id = g.id AND ug.user_id = '".api_get_user_id()."'
 					LEFT JOIN ".$table_group_user." ug2
 					ON ug2.group_id = g.id";
 		}
+		
+		$sql .= "WHERE 1=1 ";
 
-		if ($category != null){
-			$sql .= " WHERE g.category_id = '".Database::escape_string($category)."' ";
+		if ($category != null) {
+			$sql .= "  AND  g.category_id = '".Database::escape_string($category)."' ";
 			$session_condition = api_get_session_condition($session_id);
 			if(!empty($session_condition))
 				$sql .= $session_condition;
-		}
-		else
-			$session_condition = api_get_session_condition($session_id, false);
-			if(!empty($session_condition))
+		} else
+			$session_condition = api_get_session_condition($session_id, true);
+	
+		$sql .= " AND 	g.c_id = $course_id AND
+						ug.c_id = $course_id
+		";
+		
+		if(!empty($session_condition))
 			$sql .= $session_condition;
 		$sql .= " GROUP BY g.id ORDER BY UPPER(g.name)";
+		
 		if (!api_is_anonymous()) {
 			$groupList = Database::query($sql);
 		} else {
@@ -162,14 +174,13 @@ class GroupManager {
 		$groups = array ();
 		$thisGroup= array();
 			while ($thisGroup = Database::fetch_array($groupList)) {
-				if ($thisGroup['category_id'] == VIRTUAL_COURSE_CATEGORY)
-				{
+				if ($thisGroup['category_id'] == VIRTUAL_COURSE_CATEGORY) {
 					$sql = "SELECT title FROM $table_course WHERE code = '".$thisGroup['name']."'";
 					$obj = Database::fetch_object(Database::query($sql));
 					$thisGroup['name'] = $obj->title;
 				}
-				if($thisGroup['session_id']!=0)
-				{
+				
+				if($thisGroup['session_id']!=0) {
 					$sql_session = 'SELECT name FROM '.Database::get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$thisGroup['session_id'];
 					$rs_session = Database::query($sql_session);
 					if (Database::num_rows($rs_session)>0) {
@@ -196,14 +207,27 @@ class GroupManager {
 		$table_group = Database :: get_course_table(TABLE_GROUP);
 		$table_forum = Database :: get_course_table(TABLE_FORUM);
 		$category = self :: get_category($category_id);
+		
+		$course_id = api_get_course_int_id();
 
 		if (intval($places) == 0) //if the amount of users per group is not filled in, use the setting from the category
 		{
 			$places = $category['max_student'];
 		}
 		$sql = "INSERT INTO ".$table_group." SET
-				category_id='".Database::escape_string($category_id)."', max_student = '".$places."', doc_state = '".$category['doc_state']."',
-				calendar_state = '".$category['calendar_state']."', work_state = '".$category['work_state']."', announcements_state = '".$category['announcements_state']."', forum_state = '".$category['forum_state']."', wiki_state = '".$category['wiki_state']."', chat_state = '".$category['chat_state']."', self_registration_allowed = '".$category['self_reg_allowed']."',  self_unregistration_allowed = '".$category['self_unreg_allowed']."', session_id='".Database::escape_string($my_id_session)."'";
+				c_id = $course_id , 
+				category_id='".Database::escape_string($category_id)."', 
+				max_student = '".$places."', 
+				doc_state = '".$category['doc_state']."',
+				calendar_state = '".$category['calendar_state']."', 
+				work_state = '".$category['work_state']."', 
+				announcements_state = '".$category['announcements_state']."', 
+				forum_state = '".$category['forum_state']."', 
+				wiki_state = '".$category['wiki_state']."', 
+				chat_state = '".$category['chat_state']."', 
+				self_registration_allowed = '".$category['self_reg_allowed']."',  
+				self_unregistration_allowed = '".$category['self_unreg_allowed']."', 
+				session_id='".Database::escape_string($my_id_session)."'";
 		Database::query($sql);
 		$lastId = Database::insert_id();
 
@@ -218,8 +242,8 @@ class GroupManager {
 
 		// create a forum if needed
 		if ($category['forum_state'] >= 0) {
-			include_once(api_get_path(SYS_CODE_PATH).'forum/forumconfig.inc.php');
-			include_once(api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php');
+			require_once api_get_path(SYS_CODE_PATH).'forum/forumconfig.inc.php';
+			require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
 
 			$forum_categories = get_forum_categories();
 			$values['forum_title'] = $name;
@@ -351,32 +375,27 @@ class GroupManager {
 	 * @return integer              - number of groups deleted.
 	 */
 	public static function delete_groups($group_ids, $course_code = null) {
-		$course_db = '';
+		/*$course_db = '';
 		if ($course_code != null) {
 			$course = Database :: get_course_info($course_code);
 			$course['path'] = $course['directory'];
 			$course_db = $course['database'];
-		} else {
-			$course = api_get_course_info();
-		}
+		} else {			
+		}*/		
+		$course_info = api_get_course_info($course_code);
+		$course_id	 = $course_info['real_id'];   
 
 		// Database table definitions
-		$group_table 			= Database :: get_course_table(TABLE_GROUP, $course_db);
-		$group_user_table 		= Database :: get_course_table(TABLE_GROUP_USER, $course_db);
-		$forum_table 			= Database :: get_course_table(TABLE_FORUM, $course_db);
-		$forum_post_table 		= Database :: get_course_table(TABLE_FORUM_POST, $course_db);
-		//$forum_post_text_table 	= Database :: get_course_table(TOOL_FORUM_POST_TEXT_TABLE, $course_db);
-		$forum_topic_table 		= Database :: get_course_table(TABLE_FORUM_POST, $course_db);
-
+		$group_table 			= Database :: get_course_table(TABLE_GROUP);
+		$forum_table 			= Database :: get_course_table(TABLE_FORUM);
+				
 		$group_ids = is_array($group_ids) ? $group_ids : array ($group_ids);
 		$group_ids = array_map('intval',$group_ids);
 
 		if (api_is_course_coach()) { 
 		    //a coach can only delete courses from his session
-			for($i=0 ; $i<count($group_ids) ; $i++)
-			{
-				if(!api_is_element_in_the_session(TOOL_GROUP,$group_ids[$i]))
-				{
+			for($i=0 ; $i<count($group_ids) ; $i++) {
+				if(!api_is_element_in_the_session(TOOL_GROUP,$group_ids[$i])) {
 					array_splice($group_ids,$i,1);
 					$i--;
 				}
@@ -396,7 +415,7 @@ class GroupManager {
 		*/
 		// Unsubscribe all users
 		self :: unsubscribe_all_users($group_ids);
-		$sql = 'SELECT id, secret_directory, session_id FROM '.$group_table.' WHERE id IN ('.implode(' , ', $group_ids).')';
+		$sql = "SELECT id, secret_directory, session_id FROM $group_table WHERE c_id = $course_id AND id IN (".implode(' , ', $group_ids).")";
 		$db_result = Database::query($sql);
 		$forum_ids = array ();
 
@@ -425,10 +444,10 @@ class GroupManager {
 		}
 
 		// delete the groups
-		$sql = "DELETE FROM ".$group_table." WHERE id IN ('".implode("' , '", $group_ids)."')";
+		$sql = "DELETE FROM ".$group_table." WHERE c_id = $course_id AND id IN ('".implode("' , '", $group_ids)."')";
 		Database::query($sql);
 
-		$sql2 = "DELETE FROM ".$forum_table." WHERE forum_of_group IN ('".implode("' , '", $group_ids)."')";
+		$sql2 = "DELETE FROM ".$forum_table." WHERE c_id = $course_id AND forum_of_group IN ('".implode("' , '", $group_ids)."')";
 		Database::query($sql2);
 
 		return Database::affected_rows();
@@ -530,27 +549,20 @@ class GroupManager {
 		return $obj->number_of_groups;
 	}
 
-
-	/*==============================================================================
-	*	GROUPCATEGORY FUNCTIONS
-	  ==============================================================================*/
+	//GROUPCATEGORY FUNCTIONS
+	  
 	/**
 	 * Get all categories
 	 * @param string $course_code The cours (default = current course)
 	 */
 	public static function get_categories ($course_code = null) {
-		$course_db = '';
-		if ($course_code != null)
-		{
-			$course_info = Database :: get_course_info($course_code);
-			$course_db = $course_info['database'];
-		}
-		$table_group_cat = Database :: get_course_table(TABLE_GROUP_CATEGORY, $course_db);
-		$sql = "SELECT * FROM $table_group_cat ORDER BY display_order";
+		$course_info = api_get_course_info($course_code);
+		$course_id	 = $course_info['real_id'];
+		$table_group_cat = Database :: get_course_table(TABLE_GROUP_CATEGORY);
+		$sql = "SELECT * FROM $table_group_cat WHERE c_id = $course_id ORDER BY display_order";
 		$res = Database::query($sql);
 		$cats = array ();
-		while ($cat = Database::fetch_array($res))
-		{
+		while ($cat = Database::fetch_array($res)) {
 			$cats[] = $cat;
 		}
 		return $cats;
@@ -561,15 +573,12 @@ class GroupManager {
 	 * @param string $course_code The course (default = current course)
 	 */
 	public static function get_category ($id, $course_code = null) {
-		$course_db = '';
-		if ($course_code != null)
-		{
-			$course_info = Database :: get_course_info($course_code);
-			$course_db = $course_info['database'];
-		}
+		$course_info = api_get_course_info($course_code);
+		$course_id	 = $course_info['real_id'];
+		
 		$id = Database::escape_string($id);
-		$table_group_cat = Database :: get_course_table(TABLE_GROUP_CATEGORY, $course_db);
-		$sql = "SELECT * FROM $table_group_cat WHERE id = $id";
+		$table_group_cat = Database :: get_course_table(TABLE_GROUP_CATEGORY);
+		$sql = "SELECT * FROM $table_group_cat WHERE c_id = $course_id AND id = $id";
 		$res = Database::query($sql);
 		return Database::fetch_array($res);
 	}
@@ -580,17 +589,18 @@ class GroupManager {
 	 * current course)
 	 * @return array The category
 	 */
-	public static function get_category_from_group ($group_id, $course_code = null) {
-		$course_db = '';
-		if ($course_code != null)
-		{
-			$course_info = Database :: get_course_info($course_code);
-			$course_db = $course_info['database'];
-		}
-		$table_group = Database :: get_course_table(TABLE_GROUP, $course_db);
-		$table_group_cat = Database :: get_course_table(TABLE_GROUP_CATEGORY, $course_db);
+	public static function get_category_from_group ($group_id, $course_code = null) {	
+		$table_group 		= Database :: get_course_table(TABLE_GROUP);
+		$table_group_cat 	= Database :: get_course_table(TABLE_GROUP_CATEGORY);
+		
+		$course_info = api_get_course_info($course_code);
+		$course_id	 = $course_info['real_id'];
+		
 		$group_id = Database::escape_string($group_id);
-		$sql = "SELECT gc.* FROM $table_group_cat gc, $table_group g WHERE gc.id = g.category_id AND g.id=$group_id";
+		$sql = "SELECT gc.* FROM $table_group_cat gc, $table_group g 
+				WHERE 	gc.c_id = $course_id AND 
+						g.c_id = $course_id AND
+						gc.id = g.category_id AND g.id=$group_id";
 		$res = Database::query($sql);
 		$cat = Database::fetch_array($res);
 		return $cat;
@@ -602,27 +612,22 @@ class GroupManager {
 	 * deleted (default = current course)
 	 */
 	public static function delete_category ($cat_id, $course_code = null) {
-		$course_db = '';
-		if ($course_code != null)
-		{
-			$course_info = Database :: get_course_info($course_code);
-			$course_db = $course_info['database'];
-		}
-		$table_group = Database :: get_course_table(TABLE_GROUP, $course_db);
-		$table_group_cat = Database :: get_course_table(TABLE_GROUP_CATEGORY, $course_db);
-		$cat_id = Database::escape_string($cat_id);
-		$sql = "SELECT id FROM $table_group WHERE category_id='".$cat_id."'";
+		$course_info = api_get_course_info($course_code);
+		$course_id	 = $course_info['real_id'];
+		
+		$table_group 		= Database :: get_course_table(TABLE_GROUP);
+		$table_group_cat 	= Database :: get_course_table(TABLE_GROUP_CATEGORY);
+		$cat_id 			= Database::escape_string($cat_id);
+		$sql = "SELECT id FROM $table_group WHERE c_id = $course_id AND category_id='".$cat_id."'";
 		$res = Database::query($sql);
-		if (Database::num_rows($res) > 0)
-		{
+		if (Database::num_rows($res) > 0) {
 			$groups_to_delete = array ();
-			while ($group = Database::fetch_object($res))
-			{
+			while ($group = Database::fetch_object($res)) {
 				$groups_to_delete[] = $group->id;
 			}
 			self :: delete_groups($groups_to_delete);
 		}
-		$sql = "DELETE FROM $table_group_cat WHERE id='".$cat_id."'";
+		$sql = "DELETE FROM $table_group_cat WHERE c_id = $course_id  AND id='".$cat_id."'";
 		Database::query($sql);
 	}
 	/**
@@ -635,18 +640,20 @@ class GroupManager {
 	 * @param int $groups_per_user
 	 */
 	public static function create_category ($title, $description, $doc_state, $work_state, $calendar_state, $announcements_state, $forum_state, $wiki_state,
-											$chat_state = 1, $self_registration_allowed = 0, $self_unregistration_allowed = 0, $maximum_number_of_students = 8, $groups_per_user = 0)
-	{
+											$chat_state = 1, $self_registration_allowed = 0, $self_unregistration_allowed = 0, $maximum_number_of_students = 8, $groups_per_user = 0) {
 		$table_group_category = Database :: get_course_table(TABLE_GROUP_CATEGORY);
-		$sql = "SELECT MAX(display_order)+1 as new_order FROM $table_group_category ";
+		
+		$course_id = api_get_course_int_id();
+		
+		$sql = "SELECT MAX(display_order)+1 as new_order FROM $table_group_category WHERE c_id = $course_id ";
 		$res = Database::query($sql);
 		$obj = Database::fetch_object($res);
-		if (!isset ($obj->new_order))
-		{
+		if (!isset ($obj->new_order)) {
 			$obj->new_order = 1;
 		}
-		$sql = "INSERT INTO ".$table_group_category."
-					SET title='".Database::escape_string($title)."',
+		$sql = "INSERT INTO ".$table_group_category." SET
+					c_id =  $course_id , 
+					title='".Database::escape_string($title)."',
 					display_order ='".$obj->new_order."',
 					description='".Database::escape_string($description)."',
 					doc_state = '".Database::escape_string($doc_state)."',
@@ -662,9 +669,8 @@ class GroupManager {
 					max_student = '".Database::escape_string($maximum_number_of_students)."' ";
 		Database::query($sql);
 		$id = Database::insert_id();
-		if ($id == VIRTUAL_COURSE_CATEGORY)
-		{
-			$sql = "UPDATE  ".$table_group_category." SET id = ". ($id +1)." WHERE id = $id";
+		if ($id == VIRTUAL_COURSE_CATEGORY) {
+			$sql = "UPDATE  ".$table_group_category." SET id = ". ($id +1)." WHERE c_id = $course_id AND id = $id";
 			Database::query($sql);
 			return $id +1;
 		}
@@ -684,6 +690,9 @@ class GroupManager {
 	public static function update_category ($id, $title, $description, $doc_state, $work_state, $calendar_state, $announcements_state, $forum_state, $wiki_state, $chat_state, $self_registration_allowed, $self_unregistration_allowed, $maximum_number_of_students, $groups_per_user) {
 		$table_group_category = Database :: get_course_table(TABLE_GROUP_CATEGORY);
 		$id = Database::escape_string($id);
+		
+		$course_id = api_get_course_int_id();
+		
 		$sql = "UPDATE ".$table_group_category."
 				SET title='".Database::escape_string($title)."',
 				description='".Database::escape_string($description)."',
@@ -698,7 +707,7 @@ class GroupManager {
 				self_reg_allowed = '".Database::escape_string($self_registration_allowed)."',
 				self_unreg_allowed = '".Database::escape_string($self_unregistration_allowed)."',
 				max_student = ".Database::escape_string($maximum_number_of_students)."
-				WHERE id=$id";
+				WHERE c_id = $course_id AND id=$id";
 		Database::query($sql);
 	}
 
@@ -727,6 +736,7 @@ class GroupManager {
 		$obj = Database::fetch_object($res);
 		return $obj->current_max;
 	}
+	
 	/**
 	 * Swaps the display-order of two categories
 	 * @param int $id1 The id of the first category
@@ -750,10 +760,8 @@ class GroupManager {
 
 
 
-	/*==============================================================================
-	*	GROUP USERS FUNCTIONS
-	  ==============================================================================*/
-
+	//GROUP USERS FUNCTIONS
+	
 	/**
 	 * Get all users from a given group
 	 * @param int $group_id The group
@@ -823,11 +831,17 @@ class GroupManager {
 		 * Retrieve all the groups where enrollment is still allowed
 		 * (reverse) ordered by the number of place available
 		 */
+        
+        $course_id = api_get_course_int_id();
+        
 		$sql = "SELECT g.id gid, g.max_student-count(ug.user_id) nbPlaces, g.max_student
 				FROM ".$group_table." g
 				LEFT JOIN  ".$group_user_table." ug
-				ON    g.id = ug.group_id
-				WHERE g.id IN (".implode(',', $group_ids).")
+				ON g.id = ug.group_id
+				WHERE 
+					g.c_id = $course_id AND
+					ug.c_id = $course_id AND				 
+					g.id IN (".implode(',', $group_ids).")
 				GROUP BY (g.id)
 				HAVING (nbPlaces > 0 OR g.max_student = ".MEMBER_PER_GROUP_NO_LIMIT.")
 				ORDER BY nbPlaces DESC";
@@ -842,7 +856,6 @@ class GroupManager {
 		 * of group they are already enrolled
 		 */
 		for ($i = 0; $i < count($complete_user_list); $i ++) {
-
 			//find # of groups the user is enrolled in
 			$number_of_groups = self :: user_in_number_of_groups($complete_user_list[$i]["user_id"],$category['id']);
 			//add # of groups to user list
@@ -868,7 +881,7 @@ class GroupManager {
 		/*
 		 * Retrieve the present state of the users repartion in groups
 		 */
-		$sql = "SELECT user_id uid, group_id gid FROM ".$group_user_table;
+		$sql = "SELECT user_id uid, group_id gid FROM ".$group_user_table." WHERE c_id = $course_id ";
 		$result = Database::query($sql);
 		while ($member = Database::fetch_array($result, 'ASSOC')) {
 			$groupUser[$member['gid']][] = $member['uid'];
@@ -876,7 +889,6 @@ class GroupManager {
 		
 		$changed = true;
 		while ($changed) {
-
 			$changed = false;
 			reset($group_available_place);
 			arsort($group_available_place);
@@ -935,12 +947,19 @@ class GroupManager {
 	 * @return int The number of groups the user is subscribed in.
 	 */
 	public static function user_in_number_of_groups ($user_id, $cat_id) {
-		$table_group_user = Database :: get_course_table(TABLE_GROUP_USER);
-		$table_group = Database :: get_course_table(TABLE_GROUP);
-		$user_id = Database::escape_string($user_id);
-		$cat_id = Database::escape_string($cat_id);
-
-		$sql = 'SELECT  COUNT(*) AS number_of_groups FROM '.$table_group_user.' gu, '.$table_group.' g WHERE gu.user_id = \''.$user_id.'\' AND g.id = gu.group_id AND g.category_id=  \''.$cat_id.'\'';
+		$table_group_user 	= Database :: get_course_table(TABLE_GROUP_USER);
+		$table_group 		= Database :: get_course_table(TABLE_GROUP);
+		$user_id 			= Database::escape_string($user_id);
+		$cat_id 			= Database::escape_string($cat_id);
+		
+		$course_id = api_get_course_int_id();
+		
+		$sql = "SELECT  COUNT(*) AS number_of_groups FROM $table_group_user gu, $table_group g 
+				WHERE 	gu.c_id 	= $course_id AND
+						g.c_id 		= $course_id AND
+						gu.user_id 	= $user_id AND 
+						g.id 		= gu.group_id AND 
+						g.category_id =  $cat_id";
 		$db_result = Database::query($sql);
 		$db_object = Database::fetch_object($db_result);
 		return $db_object->number_of_groups;
@@ -1038,14 +1057,16 @@ class GroupManager {
 		$table_group_user = Database :: get_course_table(TABLE_GROUP_USER);
 		$order_clause = api_sort_by_first_name() ? ' ORDER BY u.firstname, u.lastname' : ' ORDER BY u.lastname, u.firstname';
 		$group_id = Database::escape_string($group_id);
-		$sql = "SELECT ug.id, u.user_id, u.lastname, u.firstname, u.email
-			FROM ".$table_user." u, ".$table_group_user." ug
-			WHERE ug.group_id='".$group_id."'
-			AND ug.user_id=u.user_id". $order_clause;
+		$course_id = api_get_course_int_id();
+		
+		$sql = "SELECT ug.id, u.user_id, u.lastname, u.firstname, u.email 
+				FROM ".$table_user." u, ".$table_group_user." ug 
+				WHERE 	ug.c_id = $course_id AND 
+						ug.group_id='".$group_id."' AND 
+						ug.user_id=u.user_id". $order_clause;
 		$db_result = Database::query($sql);
 		$users = array ();
-		while ($user = Database::fetch_object($db_result))
-		{
+		while ($user = Database::fetch_object($db_result)) {
 			$member['user_id'] = $user->user_id;
 			$member['firstname'] = $user->firstname;
 			$member['lastname'] = $user->lastname;
@@ -1067,14 +1088,16 @@ class GroupManager {
 		$table_group_tutor = Database :: get_course_table(TABLE_GROUP_TUTOR);
 		$order_clause = api_sort_by_first_name() ? ' ORDER BY u.firstname, u.lastname' : ' ORDER BY u.lastname, u.firstname';
 		$group_id = Database::escape_string($group_id);
+		$course_id = api_get_course_int_id();
+		
 		$sql = "SELECT tg.id, u.user_id, u.lastname, u.firstname, u.email
 			FROM ".$table_user." u, ".$table_group_tutor." tg
-			WHERE tg.group_id='".$group_id."'
-			AND tg.user_id=u.user_id".$order_clause;
+			WHERE 	tg.c_id = $course_id AND 
+					tg.group_id='".$group_id."' AND 
+					tg.user_id=u.user_id".$order_clause;
 		$db_result = Database::query($sql);
 		$users = array ();
-		while ($user = Database::fetch_object($db_result))
-		{
+		while ($user = Database::fetch_object($db_result)) {
 			if (!$id_only)
 			{
 				$member['user_id'] = $user->user_id;
@@ -1099,12 +1122,12 @@ class GroupManager {
 	public static function subscribe_users ($user_ids, $group_id) {
 		$user_ids = is_array($user_ids) ? $user_ids : array ($user_ids);
 		$result = true;
-		foreach ($user_ids as $index => $user_id)
-		{
-			$table_group_user = Database :: get_course_table(TABLE_GROUP_USER);
+		$course_id = api_get_course_int_id();
+		$table_group_user = Database :: get_course_table(TABLE_GROUP_USER);
+		foreach ($user_ids as $index => $user_id) {			
 			$user_id = Database::escape_string($user_id);
 			$group_id = Database::escape_string($group_id);
-			$sql = "INSERT INTO ".$table_group_user." (user_id, group_id) VALUES ('".$user_id."', '".$group_id."')";
+			$sql = "INSERT INTO ".$table_group_user." (c_id, user_id, group_id) VALUES ('$course_id', '".$user_id."', '".$group_id."')";
 			$result &= Database::query($sql);
 		}
 		return $result;
@@ -1121,13 +1144,13 @@ class GroupManager {
 	public static function subscribe_tutors ($user_ids, $group_id) {
 		$user_ids = is_array($user_ids) ? $user_ids : array ($user_ids);
 		$result = true;
-		foreach ($user_ids as $index => $user_id)
-		{
-			$table_group_tutor = Database :: get_course_table(TABLE_GROUP_TUTOR);
+		$course_id = api_get_course_int_id();
+		$table_group_tutor = Database :: get_course_table(TABLE_GROUP_TUTOR);
+		
+		foreach ($user_ids as $index => $user_id) {			
 			$user_id = Database::escape_string($user_id);
 			$group_id = Database::escape_string($group_id);
-
-			$sql = "INSERT INTO ".$table_group_tutor." (user_id, group_id) VALUES ('".$user_id."', '".$group_id."')";
+			$sql = "INSERT INTO ".$table_group_tutor." (c_id, user_id, group_id) VALUES ('$course_id', '".$user_id."', '".$group_id."')";
 			$result &= Database::query($sql);
 		}
 		return $result;
@@ -1143,7 +1166,9 @@ class GroupManager {
 		$user_ids = is_array($user_ids) ? $user_ids : array ($user_ids);
 		$table_group_user = Database :: get_course_table(TABLE_GROUP_USER);
 		$group_id = Database::escape_string($group_id);
-		$result &= Database::query('DELETE FROM '.$table_group_user.' WHERE group_id = '.$group_id.' AND user_id IN ('.implode(',', $user_ids).')');
+		$course_id = api_get_course_int_id();		
+		
+		$result &= Database::query('DELETE FROM '.$table_group_user.' WHERE c_id = '.$course_id.' AND group_id = '.$group_id.' AND user_id IN ('.implode(',', $user_ids).')');
 	}
 	/**
 	 * Unsubscribe all users from one or more groups
@@ -1208,12 +1233,9 @@ class GroupManager {
 
 		$sql = "SELECT * FROM ".$table_group_tutor." WHERE user_id='".$user_id."' AND group_id='".$group_id."'";
 		$result = Database::query($sql);
-		if (Database::num_rows($result)>0)
-		{
+		if (Database::num_rows($result)>0) {
 			return true;
-		}
-		else
-		{
+		} else {
 			return false;
 		}
 	}
@@ -1294,7 +1316,7 @@ class GroupManager {
 	 * @param integer $user_id: the ID of the user you want to know all its
 	 * group memberships
 	 */
-	public static function get_group_ids ($course_db,$user_id) {
+	public static function get_group_ids ($course_db, $user_id) {
 		$groups = array();
 		$tbl_group = Database::get_course_table(TABLE_GROUP_USER,$course_db);
 		$user_id = Database::escape_string($user_id);

+ 25 - 17
main/inc/lib/link.lib.php

@@ -1,5 +1,4 @@
 <?php
-
 /* For licensing terms, see /license.txt */
 
 /**
@@ -79,11 +78,12 @@ function addlinkcategory($type) {
 
 			$session_id = api_get_session_id();
 
-			$sql = "INSERT INTO " . $tbl_link . " (url, title, description, category_id, display_order, on_homepage, target, session_id)
-			        VALUES ('" . Database :: escape_string($urllink) . "','" . Database :: escape_string($title) . "','" . Database :: escape_string($description) . "','" .
+			$sql = "INSERT INTO " . $tbl_link . " (c_id, url, title, description, category_id, display_order, on_homepage, target, session_id)
+			        VALUES (".api_get_course_int_id().", '".Database :: escape_string($urllink) . "','" . Database :: escape_string($title) . "','" . Database :: escape_string($description) . "','" .			        
 			Database :: escape_string($selectcategory) . "','" . Database :: escape_string($order) . "', '" . Database :: escape_string($onhomepage) . "','" .
 			Database :: escape_string($target) . "','" . Database :: escape_string($session_id) . "')";
-			$catlinkstatus = get_lang('LinkAdded');
+			
+			$catlinkstatus = get_lang('LinkAdded');			
 			Database :: query($sql);
 			$link_id = Database :: insert_id();
 
@@ -151,9 +151,9 @@ function addlinkcategory($type) {
 				if ($did) {
 					// Save it to db.
 					$tbl_se_ref = Database :: get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
-					$sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
+					$sql = 'INSERT INTO %s (c_id, id, course_code, tool_id, ref_id_high_level, search_did)
 					                        VALUES (NULL , \'%s\', \'%s\', %s, %s)';
-					$sql = sprintf($sql, $tbl_se_ref, $courseid, TOOL_LINK, $link_id, $did);
+					$sql = sprintf($sql, $tbl_se_ref, api_get_course_int_id(), $courseid, TOOL_LINK, $link_id, $did);
 					Database :: query($sql);
 				}
 			}
@@ -177,8 +177,8 @@ function addlinkcategory($type) {
 			$order = $orderMax +1;
 			$order = intval($order);
 			$session_id = api_get_session_id();
-			$sql = "INSERT INTO ".$tbl_categories." (category_title, description, display_order, session_id) 
-			        VALUES ('" .Database::escape_string($category_title) . "', '" . Database::escape_string($description) . "', '$order', '$session_id')";
+			$sql = "INSERT INTO ".$tbl_categories." (c_id, category_title, description, display_order, session_id) 
+			        VALUES (".api_get_course_int_id().", '" .Database::escape_string($category_title) . "', '" . Database::escape_string($description) . "', '$order', '$session_id')";
 			Database :: query($sql);
 
 			$catlinkstatus = get_lang('CategoryAdded');
@@ -216,12 +216,10 @@ function deletelinkcategory($type) {
 			$sql = "UPDATE $tbl_link SET on_homepage='0' WHERE id='" . intval($_GET['id']) . "'";
 			Database :: query($sql);
 		}
-
 		api_item_property_update($_course, TOOL_LINK, $id, 'delete', api_get_user_id());
 		delete_link_from_search_engine(api_get_course_id(), $id);
 		$catlinkstatus = get_lang('LinkDeleted');
 		unset ($id);
-
 		Display :: display_confirmation_message(get_lang('LinkDeleted'));
 	}
 
@@ -460,9 +458,9 @@ function editlinkcategory($type) {
 						$sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
 						$sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $link_id);
 						Database :: query($sql);
-						$sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
+						$sql = 'INSERT INTO %s (c_id, id, course_code, tool_id, ref_id_high_level, search_did)
 						        VALUES (NULL , \'%s\', \'%s\', %s, %s)';
-						$sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_LINK, $link_id, $did);
+						$sql = sprintf($sql, $tbl_se_ref, api_get_course_int_id(), $course_id, TOOL_LINK, $link_id, $did);
 						Database :: query($sql);
 					}
 				}
@@ -537,7 +535,14 @@ function showlinksofcategory($catid) {
 	$condition_session = api_get_session_condition($session_id, true, true);
 	$catid = intval($catid);
 
-	$sqlLinks = "SELECT * FROM " . $tbl_link . " link, " . $TABLE_ITEM_PROPERTY . " itemproperties WHERE itemproperties.tool='" . TOOL_LINK . "' AND link.id=itemproperties.ref AND link.category_id='" . $catid . "' AND (itemproperties.visibility='0' OR itemproperties.visibility='1') $condition_session ORDER BY link.display_order DESC";
+	$sqlLinks = "SELECT * FROM " . $tbl_link . " link, " . $TABLE_ITEM_PROPERTY . " itemproperties 
+				 WHERE  itemproperties.tool='" . TOOL_LINK . "' AND 
+						link.id=itemproperties.ref AND 
+						link.category_id='" . $catid . "' AND 
+						(itemproperties.visibility='0' OR itemproperties.visibility='1') 
+						$condition_session AND
+						link.c_id = ".api_get_course_int_id()." 
+						ORDER BY link.display_order DESC";
 	$result = Database :: query($sqlLinks);
 	$numberoflinks = Database :: num_rows($result);
 	if ($numberoflinks > 0) {
@@ -585,7 +590,9 @@ function showlinksofcategory($catid) {
     
     				echo '<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;sec_token='.$token.'&amp;action=editlink&amp;category=' . (!empty ($category) ? $category : '') . '&amp;id=' . $myrow[0] . '&amp;urlview=' . $urlview . '" title="' . get_lang('Modify') . '">' . 
     						Display :: return_icon('edit.png', get_lang('Modify'), array (), 22) . '</a>';
+    				
     				// DISPLAY MOVE UP COMMAND only if it is not the top link.
+    				/*
     				if ($i != 1) {
     					echo '<a href="' . api_get_self() . '?' . api_get_cidreq() .  '&amp;sec_token='.$token.'&amp;urlview=' . $urlview . '&amp;up=', $myrow[0], '" title="' . get_lang('Up') . '">' . Display :: return_icon('up.png', get_lang('Up'), array (), 22) . '', "</a>\n";
     				} else {
@@ -597,7 +604,7 @@ function showlinksofcategory($catid) {
     					echo '<a href="' . api_get_self() . '?' . api_get_cidreq() .  '&amp;sec_token='.$token.'&amp;urlview=' . $urlview . '&amp;down=' . $myrow[0] . '" title="' . get_lang('Down') . '">' . Display :: return_icon('down.png', get_lang('Down'), array (), 22) . '', "</a>\n";
     				} else {
     					echo Display :: return_icon('down_na.png', get_lang('Down'), array (), 22) . '', "</a>\n";
-    				}
+    				}*/
     
     				if ($myrow['visibility'] == '1') {
     					echo '<a href="link.php?' . api_get_cidreq() .  '&amp;sec_token='.$token.'&amp;action=invisible&amp;id=' . $myrow[0] . '&amp;scope=link&amp;urlview=' . $urlview . '" title="' . get_lang('Hide') . '">' . Display :: return_icon('visible.png', get_lang('Hide'), array (), 22) . '</a>';
@@ -738,7 +745,8 @@ function get_cat($catname) {
 
 	$result = Database :: query("SELECT MAX(display_order) FROM " . $tbl_categories);
 	list ($max_order) = Database :: fetch_row($result);
-	Database :: query("INSERT INTO " . $tbl_categories . " (category_title, description, display_order) VALUES ('" . Database::escape_string($catname) . "','','" . ($max_order +1) . "')");
+	Database :: query("INSERT INTO " . $tbl_categories . " (c_id, category_title, description, display_order) 
+					   VALUES (".api_get_course_int_id().", '" . Database::escape_string($catname) . "','','" . ($max_order +1) . "')");
 	return Database :: insert_id();
 }
 
@@ -764,13 +772,13 @@ function put_link($url, $cat, $title, $description, $on_homepage, $hidden) {
 		$result = Database :: query("SELECT MAX(display_order) FROM  $tbl_link WHERE category_id='" . intval($cat) . "'");
 		list ($max_order) = Database :: fetch_row($result);
 
-		Database :: query("INSERT INTO $tbl_link (url, title, description, category_id, display_order, on_homepage) VALUES ('" . Database :: escape_string($url) . "','" . Database :: escape_string($title) . "','" . Database :: escape_string($description) . "','" . intval($cat) . "','" . (intval($max_order) + 1) . "','" . intval($on_homepage) . "')");
+		Database :: query("INSERT INTO $tbl_link (c_id, url, title, description, category_id, display_order, on_homepage) 
+						   VALUES (".api_get_course_int_id().", '" . Database :: escape_string($url) . "','" . Database :: escape_string($title) . "','" . Database :: escape_string($description) . "','" . intval($cat) . "','" . (intval($max_order) + 1) . "','" . intval($on_homepage) . "')");
 
 		$id = Database :: insert_id();
 		$ipu = 'LinkAdded';
 		$rv = 2; // 2 = new
 	}
-
 	global $_course, $nameTools, $_user;
 	api_item_property_update($_course, TOOL_LINK, $id, $ipu, $_user['user_id']);
 

+ 79 - 44
main/inc/lib/main_api.lib.php

@@ -1012,15 +1012,12 @@ function api_get_course_path($course_code = null) {
  * @param string    Optional: course code
  * @return mixed    The value of that setting in that table. Return -1 if not found.
  */
-function api_get_course_setting($setting_name, $course_code = null) {
-    if (!empty($course_code)) {
-        $course_info = api_get_course_info($course_code);
-        $table = Database::get_course_table(TABLE_COURSE_SETTING, $course_info['dbName']);
-    } else {
-        $table = Database::get_course_table(TABLE_COURSE_SETTING);
-    }
+function api_get_course_setting($setting_name, $course_code = null) {    
+    $course_info = api_get_course_info($course_code);    
+	$table 		 = Database::get_course_table(TABLE_COURSE_SETTING);
+    
     $setting_name = Database::escape_string($setting_name);
-    $sql = "SELECT value FROM $table WHERE variable = '$setting_name'";
+    $sql = "SELECT value FROM $table WHERE c_id = {$course_info['real_id']} AND variable = '$setting_name'";
     $res = Database::query($sql);
     if (Database::num_rows($res) > 0) {
         $row = Database::fetch_array($res);
@@ -2342,6 +2339,7 @@ function api_not_allowed($print_headers = false) {
 	$template_file = $tpl->get_template('layout/layout_1_col.tpl');
 	
     $origin = isset($_GET['origin']) ? $_GET['origin'] : '';
+    
     if ($origin == 'learnpath') {
 	$htmlHeadXtra[]= '<style type="text/css" media="screen, projection">
 					/*<![CDATA[*/
@@ -2402,9 +2400,9 @@ function api_not_allowed($print_headers = false) {
 		}
         die();
 	}
-
+	
 	if (!empty($user) && !api_is_anonymous()) {
-	$tpl->display($template_file);
+		$tpl->display($template_file);
         exit;
     }    
 
@@ -2412,6 +2410,7 @@ function api_not_allowed($print_headers = false) {
 	$msg = Display::return_message(get_lang('NotAllowed').'<br /><br /><a href="'.$home_url.'">'.get_lang('PleaseLoginAgainFromHomepage').'</a><br />', 'error', false);
 	$msg = Display::div($msg, array('align'=>'center'));
 	$tpl->assign('content', $msg);
+	
 	$tpl->display($template_file);
     exit;
 }
@@ -2464,8 +2463,14 @@ function api_get_item_visibility($_course, $tool, $id, $session=0) {
     $tool = Database::escape_string($tool);
     $id = Database::escape_string($id);
     $session = (int) $session;
-    $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
-    $sql = "SELECT visibility FROM $TABLE_ITEMPROPERTY WHERE tool = '$tool' AND ref = $id AND (id_session = $session OR id_session = 0) ORDER BY id_session DESC, lastedit_date DESC";
+    $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+    $course_id	 = $_course['real_id'];
+    $sql = "SELECT visibility FROM $TABLE_ITEMPROPERTY 
+    		WHERE 	c_id = $course_id AND 
+    				tool = '$tool' AND 
+    				ref = $id AND 
+    				(id_session = $session OR id_session = 0) 
+    		ORDER BY id_session DESC, lastedit_date DESC";
     $res = Database::query($sql);
     if ($res === false || Database::num_rows($res) == 0) { return -1; }
     $row = Database::fetch_array($res);
@@ -2505,10 +2510,6 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us
     $start_visible  = ($start_visible == 0) ? '0000-00-00 00:00:00' : $start_visible;
     $end_visible    = ($end_visible == 0) ? '0000-00-00 00:00:00' : $end_visible;
     $to_filter      = '';
-    //$time           = time();
-    //$time           = date('Y-m-d H:i:s', $time);
-    // According to http://support.chamilo.org/projects/chamilo-18/wiki/Date_and_time_management
-    // @todo Fix $start_visible and $end_visible
     $time           = api_get_utc_datetime();
 
     if (!empty($session_id)) {
@@ -2518,7 +2519,7 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us
     }
 
     // Definition of tables.
-    $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $_course['dbName']);
+    $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
 
     if ($to_user_id <= 0) {
         $to_user_id = null; // No to_user_id set
@@ -2540,11 +2541,13 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us
     if (!empty($session_id)) {
         $condition_session = " AND id_session = '$session_id' ";
     }
+    
+    $course_id	 = $_course['real_id'];
 
-    $filter = "tool='$tool' AND ref='$item_id' $condition_session ";
+    $filter = "c_id = $course_id AND tool='$tool' AND ref='$item_id' $condition_session ";
 
     if ($item_id == '*') {
-        $filter = "tool='$tool' AND visibility<>'2' $condition_session"; // For all (not deleted) items of the tool
+        $filter = "c_id = $course_id  AND tool='$tool' AND visibility<>'2' $condition_session"; // For all (not deleted) items of the tool
     }
     // Check whether $to_user_id and $to_group_id are passed in the function call.
     // If both are not passed (both are null) then it is a message for everybody and $to_group_id should be 0 !
@@ -2561,23 +2564,27 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us
 
     // Update if possible
     $set_type = '';
-
+    
+    
     switch ($lastedit_type) {
         case 'delete' : // delete = make item only visible for the platform admin.
             $visibility = '2';
-
             if (!empty($session_id)) {
-
                 // Check whether session id already exist into itemp_properties for updating visibility or add it.
-                $sql = "select id_session FROM $TABLE_ITEMPROPERTY WHERE tool = '$tool' AND ref='$item_id' AND id_session = '$session_id'";
+                $sql = "SELECT id_session FROM $TABLE_ITEMPROPERTY 
+                		WHERE c_id = $course_id AND tool = '$tool' AND ref='$item_id' AND id_session = '$session_id'";
                 $rs = Database::query($sql);
                 if (Database::num_rows($rs) > 0) {
                     $sql = "UPDATE $TABLE_ITEMPROPERTY
-                            SET lastedit_type='".str_replace('_', '', ucwords($tool))."Deleted', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility', id_session = '$session_id' $set_type
+                            SET lastedit_type		= '".str_replace('_', '', ucwords($tool))."Deleted', 
+                            	lastedit_date		= '$time', 
+                            	lastedit_user_id	= '$user_id', 
+                            	visibility			= '$visibility', 
+                            	id_session 			= '$session_id' $set_type
                             WHERE $filter";
                 } else {
-                    $sql = "INSERT INTO $TABLE_ITEMPROPERTY (tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
-                            VALUES ('$tool','$item_id','$time', '$user_id', '$time', '$lastedit_type','$user_id', '$to_value', '$visibility', '$start_visible','$end_visible', '$session_id')";
+                    $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
+                            VALUES ($course_id, '$tool','$item_id','$time', '$user_id', '$time', '$lastedit_type','$user_id', '$to_value', '$visibility', '$start_visible','$end_visible', '$session_id')";
                 }
 
             } else {
@@ -2598,8 +2605,8 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us
                             SET lastedit_type='".str_replace('_', '', ucwords($tool))."Visible', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility', id_session = '$session_id' $set_type
                             WHERE $filter";
                 } else {
-                    $sql = "INSERT INTO $TABLE_ITEMPROPERTY (tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
-                            VALUES ('$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
+                    $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
+                            VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
                 }
             } else {
                 $sql = "UPDATE $TABLE_ITEMPROPERTY
@@ -2620,8 +2627,8 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us
                             SET lastedit_type='".str_replace('_', '', ucwords($tool))."Invisible', lastedit_date='$time', lastedit_user_id='$user_id', visibility='$visibility', id_session = '$session_id' $set_type
                             WHERE $filter";
                 } else {
-                    $sql = "INSERT INTO $TABLE_ITEMPROPERTY (tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
-                            VALUES ('$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
+                    $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, id_session)
+                            VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
                 }
 
             } else {
@@ -2638,11 +2645,12 @@ function api_item_property_update($_course, $tool, $item_id, $lastedit_type, $us
                     SET lastedit_date='$time', lastedit_user_id='$user_id' $set_type
                     WHERE $filter";
     }
+    
     $res = Database::query($sql);
     // Insert if no entries are found (can only happen in case of $lastedit_type switch is 'default').
     if (Database::affected_rows() == 0) {
-        $sql = "INSERT INTO $TABLE_ITEMPROPERTY (tool,ref,insert_date,insert_user_id,lastedit_date,lastedit_type,   lastedit_user_id,$to_field,  visibility,   start_visible,   end_visible, id_session)
-                VALUES ('$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
+        $sql = "INSERT INTO $TABLE_ITEMPROPERTY (c_id, tool,ref,insert_date,insert_user_id,lastedit_date,lastedit_type,   lastedit_user_id,$to_field,  visibility,   start_visible,   end_visible, id_session)
+                VALUES ($course_id, '$tool', '$item_id', '$time', '$user_id', '$time', '$lastedit_type', '$user_id', '$to_value', '$visibility', '$start_visible', '$end_visible', '$session_id')";
         
         $res = Database::query($sql);
         if (!$res) {
@@ -2664,12 +2672,13 @@ function api_get_item_property_by_tool($tool, $course_code, $session_id = null)
     $tool           = Database::escape_string($tool);
     
     // Definition of tables.
-    $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+    $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $session_condition = '';
     $session_id = intval($session_id);
     $session_condition = ' AND id_session = '.$session_id;
+    $course_id	 = $course_info['real_id'];
     
-    $sql = "SELECT * FROM $item_property_table WHERE tool = '$tool'  $session_condition ";
+    $sql = "SELECT * FROM $item_property_table WHERE c_id = $course_id AND tool = '$tool'  $session_condition ";
     $rs  = Database::query($sql);
     $item_property_id = '';
     $list = array();
@@ -2694,8 +2703,9 @@ function api_get_item_property_id($course_code, $tool, $ref) {
     $ref            = intval($ref);  
 
     // Definition of tables.
-    $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
-    $sql = "SELECT id FROM $TABLE_ITEMPROPERTY WHERE tool = '$tool' AND ref = '$ref'";
+    $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+    $course_id	 = $course_info['real_id'];
+    $sql = "SELECT id FROM $TABLE_ITEMPROPERTY WHERE c_id = $course_id AND tool = '$tool' AND ref = '$ref'";
     $rs  = Database::query($sql);
     $item_property_id = '';
     if (Database::num_rows($rs) > 0) {
@@ -2758,8 +2768,10 @@ function api_get_item_property_info($course_id, $tool, $ref, $session_id = 0) {
     $ref            = intval($ref);
 
     // Definition of tables.
-    $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY, $course_info['dbName']);
-   	$sql = "SELECT * FROM $TABLE_ITEMPROPERTY WHERE tool = '$tool' AND ref = $ref ";
+    $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
+    $course_id	 = $course_info['real_id'];
+    
+   	$sql = "SELECT * FROM $TABLE_ITEMPROPERTY WHERE c_id = $course_id AND tool = '$tool' AND ref = $ref ";
    	if (!empty($session_id)) {
    		$session_id = intval($session_id);
    		$sql .= "AND id_session = $session_id ";
@@ -3337,7 +3349,7 @@ function copyr($source, $dest, $exclude = array(), $copied_files = array()) {
 
 // TODO: Using DIRECTORY_SEPARATOR is not recommended, this is an obsolete approach. Documentation header to be added here.
 function copy_folder_course_session($pathname, $base_path_document, $session_id, $course_info, $document) {
-    $table = Database :: get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
+    $table = Database :: get_course_table(TABLE_DOCUMENT);
     $session_id = intval($session_id);
     // Check whether directory already exists.
     if (is_dir($pathname) || empty($pathname)) {
@@ -3349,6 +3361,8 @@ function copy_folder_course_session($pathname, $base_path_document, $session_id,
         trigger_error('copy_folder_course_session(): File exists', E_USER_WARNING);
         return false;
     }
+    
+    $course_id	 = $course_info['real_id'];
 
     $folders = explode(DIRECTORY_SEPARATOR,str_replace($base_path_document.DIRECTORY_SEPARATOR,'',$pathname));
 
@@ -3370,7 +3384,14 @@ function copy_folder_course_session($pathname, $base_path_document, $session_id,
                 mkdir($new_pathname, api_get_permissions_for_new_directories());
 
                 // Insert new folder with destination session_id.
-                $sql = "INSERT INTO ".$table." SET path = '$path', comment = '".Database::escape_string($document->comment)."', title = '".Database::escape_string(basename($new_pathname))."' ,filetype='folder', size= '0', session_id = '$session_id'";
+                $sql = "INSERT INTO ".$table." SET
+                		c_id = $course_id,  
+                		path = '$path',                 
+                		comment = '".Database::escape_string($document->comment)."', 
+                		title = '".Database::escape_string(basename($new_pathname))."' ,
+                		filetype='folder', 
+                		size= '0', 
+                		session_id = '$session_id'";
                 Database::query($sql);
                 $document_id = Database::insert_id();
                 api_item_property_update($course_info,TOOL_DOCUMENT,$document_id,'FolderCreated',api_get_user_id(),0,0,null,null,$session_id);
@@ -4225,8 +4246,9 @@ function api_is_element_in_the_session($tool, $element_id, $session_id = null) {
             break;
         default: return false;
     }
-
-    $sql = 'SELECT session_id FROM '.$table_tool.' WHERE '.$key_field.'='.intval($element_id);
+    $course_id = api_get_course_int_id();
+    
+    $sql = "SELECT session_id FROM $table_tool WHERE c_id = $course_id AND $key_field =  ".intval($element_id);
     $rs = Database::query($sql);
     if ($element_session_id = Database::result($rs, 0, 0)) {
         if ($element_session_id == intval($session_id)) { // The element belongs to the session.
@@ -4676,7 +4698,8 @@ function api_check_term_condition($user_id) {
  */
 function api_get_tool_information($tool_id) {
     $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
-    $sql = 'SELECT * FROM '.$t_tool.' WHERE id="'.Database::escape_string($tool_id).'"';
+    $course_id = api_get_course_int_id();
+    $sql = "SELECT * FROM $t_tool WHERE c_id = $course_id AND id = ".Database::escape_string($tool_id);
     $rs  = Database::query($sql);
     return Database::fetch_array($rs);
 }
@@ -4688,7 +4711,8 @@ function api_get_tool_information($tool_id) {
  */
 function api_get_tool_information_by_name($name) {
     $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
-    $sql = 'SELECT * FROM '.$t_tool.' WHERE name="'.Database::escape_string($name).'"';
+    $course_id = api_get_course_int_id();
+    $sql = "SELECT * FROM $t_tool WHERE c_id = $course_id  AND name = '".Database::escape_string($name)."' ";
     $rs  = Database::query($sql);
     return Database::fetch_array($rs, 'ASSOC');
 }
@@ -5262,3 +5286,14 @@ function api_get_home_path() {
 	}
 	return $home;
 }
+
+
+function api_get_course_table_condition($and = true) {
+	$course_id = api_get_course_int_id();
+	$condition = '';
+	$condition_add = $and ? " AND " : " WHERE ";
+	if (!empty($course_id)) {
+		$condition = " $condition_add c_id = $course_id";
+	}
+	return $condition;
+}

+ 6 - 3
main/inc/lib/notebook.lib.php

@@ -50,9 +50,11 @@ class NotebookManager
 		}
 		// Database table definition
 		$t_notebook = Database :: get_course_table(TABLE_NOTEBOOK);
+		$course_id = api_get_course_int_id();
 
-		$sql = "INSERT INTO $t_notebook (user_id, course, session_id, title, description, creation_date,update_date,status)
+		$sql = "INSERT INTO $t_notebook (c_id, user_id, course, session_id, title, description, creation_date,update_date,status)
 				VALUES(
+					 $course_id,
 					'".api_get_user_id()."',
 					'".Database::escape_string(api_get_course_id())."',
 					'".Database::escape_string($_SESSION['id_session'])."',
@@ -198,8 +200,9 @@ class NotebookManager
 		$condition_session = api_get_session_condition($session_id);
 
 		$cond_extra = ($_SESSION['notebook_view']== 'update_date')?" AND update_date <> '0000-00-00 00:00:00'":" ";
-
-		$sql = "SELECT * FROM $t_notebook WHERE user_id = '".api_get_user_id()."' $condition_session $cond_extra $order_by";
+		$course_id = api_get_course_int_id();
+		
+		$sql = "SELECT * FROM $t_notebook WHERE c_id = $course_id AND user_id = '".api_get_user_id()."' $condition_session $cond_extra $order_by";
 		$result = Database::query($sql);
 		while ($row = Database::fetch_array($result)) {
 			//validacion when belongs to a session

+ 4 - 2
main/inc/lib/sessionmanager.lib.php

@@ -1525,8 +1525,10 @@ class SessionManager {
                                         api_item_property_update($course_info, TOOL_LEARNPATH, $lp_id, 'invisible', api_get_user_id(), 0 ,0, 0, 0);
                                     }
                                 }
-                                $quiz_table   = Database::get_course_table(TABLE_QUIZ_TEST, $course_info['db_name']);
-                                $sql = "UPDATE $quiz_table SET active = 0 ";
+                                $quiz_table   = Database::get_course_table(TABLE_QUIZ_TEST);
+                                $course_id	 = $course_info['real_id'];
+                                //@todo check this query
+                                $sql = "UPDATE $quiz_table SET active = 0 WHERE c_id = $course_id ";
                                 $result=Database::query($sql);                                
                             }
                             $new_short_courses[] = $course_info['code'];

+ 7 - 8
main/inc/lib/social.lib.php

@@ -398,19 +398,18 @@ class SocialManager extends UserManager {
 		// Table definitions
 		$main_user_table 		 = Database :: get_main_table(TABLE_MAIN_USER);
 		$tbl_session 			 = Database :: get_main_table(TABLE_MAIN_SESSION);
-		$course_database 		 = $my_course['db'];
-		$course_tool_table 		 = Database :: get_course_table(TABLE_TOOL_LIST, $course_database);
-		$tool_edit_table 		 = Database :: get_course_table(TABLE_ITEM_PROPERTY, $course_database);
-		$course_group_user_table = Database :: get_course_table(TOOL_USER, $course_database);
-
+		
 		$user_id = api_get_user_id();
 		$course_system_code = $my_course['k'];
 		$course_visual_code = $my_course['c'];
 		$course_title = $my_course['i'];
 		$course_directory = $my_course['d'];
 		$course_teacher = $my_course['t'];
+		
 		$course_teacher_email = isset($my_course['email'])?$my_course['email']:'';
 		$course_info = Database :: get_course_info($course_system_code);
+		
+		$course_id = $course_info['real_id'];
 
 		$course_access_settings = CourseManager :: get_access_settings($course_system_code);
 
@@ -455,12 +454,12 @@ class SocialManager extends UserManager {
 
 		//display course entry
 		$result .= '<div id="div_'.$count.'">';
-		$result .= '<h3><img src="../img/nolines_plus.gif" id="btn_'.$count.'" onclick="toogle_course(this,\''.$course_database.'\' )">';
+		$result .= '<h3><img src="../img/nolines_plus.gif" id="btn_'.$count.'" onclick="toogle_course(this,\''.$course_id.'\' )">';
 		$result .= $s_htlm_status_icon;
 
 		//show a hyperlink to the course, unless the course is closed and user is not course admin
 		if ($course_visibility != COURSE_VISIBILITY_CLOSED || $user_in_course_status == COURSEMANAGER) {
-			$result .= '<a href="javascript:void(0)" id="ln_'.$count.'"  onclick=toogle_course(this,\''.$course_database.'\');>&nbsp;'.$course_title.'</a>';
+			$result .= '<a href="javascript:void(0)" id="ln_'.$count.'"  onclick=toogle_course(this,\''.$course_id.'\');>&nbsp;'.$course_title.'</a>';
 		} else {
 			$result .= $course_display_title." "." ".get_lang('CourseClosed')."";
 		}
@@ -737,7 +736,7 @@ class SocialManager extends UserManager {
 		    	foreach ($course_list_code as $course) {
 		    		$course_info = api_get_course_info($course['code']);
 		    		if (!empty($course_info)) {		    		
-		    			$content = AnnouncementManager::get_all_annoucement_by_user_course($course_info['dbName'], $my_announcement_by_user_id);	    			
+		    			$content = AnnouncementManager::get_all_annoucement_by_user_course($course_info['code'], $my_announcement_by_user_id);	    			
 		    			
 		    	  		if (!empty($content)) {	    	  			
 		    				$url = Display::url(Display::return_icon('announcement.png',get_lang('Announcements')).$course_info['name'].' ('.$content['count'].')', api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$course['code']);

+ 11 - 481
main/inc/lib/surveymanager.lib.php

@@ -4,481 +4,7 @@
 *	This library provides functions for user management.
 *	Include/require it in your code to use its functionality.
 *
-*	@author Bart Mollet, main author
 *	@package chamilo.library
-
-*/
-//@todo This class is deprecated
-/*
-class SurveyManager {
-	private function __construct() {
-
-	}
-	//Possible  deprecated method
-	function get_survey_author($authorid)
-	{
-			$user_table = Database :: get_main_table(TABLE_MAIN_USER);
-			$authorid = Database::escape_string($authorid);
-		    $sql_query = "SELECT * FROM $user_table WHERE user_id='$authorid'";
-			$res = Database::query($sql_query);
-			$firstname=@Database::result($res,0,'firstname');
-			return $firstname;
-	}
-
-	//Possible  deprecated method
-	function get_author($db_name,$survey_id)
-	{
-	    //$table_survey = Database :: get_course_table(TABLE_SURVEY);
-	    $survey_id = Database::escape_string($survey_id);
-		$sql = "SELECT author FROM $db_name.survey WHERE survey_id='$survey_id'";
-		$res = Database::query($sql);
-		$author=@Database::result($res,0,'author');
-		return $author;
-	}
-	//Possible  deprecated method
-	function get_surveyid($db_name,$group_id)
-	{
-	    //$group_table = Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP);
-	    $group_id = Database::escape_string($group_id);
-		$sql = "SELECT survey_id FROM $db_name.survey_group WHERE group_id='$group_id'";
-		$res = Database::query($sql);
-		$surveyid=@Database::result($res,0,'survey_id');
-		return $surveyid;
-	}
-
-	public static function get_groupname ($db_name,$gid) {
-		//$grouptable = Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP);
-		$gid = Database::escape_string($gid);
-		$sql = "SELECT * FROM $db_name.survey_group WHERE group_id='$gid'";
-		$res=Database::query($sql);
-		$code=@Database::result($res,0,'groupname');
-		return($code);
-	}
-
-	//Possible  deprecated method
-	function insert_into_group ($survey_id,$group_title,$introduction,$tb) {
-		$survey_id = Database::escape_string($survey_id);
-		$group_title = Database::escape_string($group_title);
-		$introduction = Database::escape_string($introduction);
-
-		$sql="INSERT INTO $tb (group_id,survey_id,group_title,introduction) values('','$survey_id','$group_title','$introduction')";
-		$result=Database::query($sql);
-		return Database::insert_id();
-	}
-	//Possible  deprecated method
-	function get_survey_code ($table_survey,$survey_code)
-	{
-		$survey_code = Database::escape_string($survey_code);
-		$sql="SELECT code FROM $table_survey where code='$survey_code'";
-		//echo $sql;
-		//exit;
-		$result=Database::query($sql);
-		$code=@Database::result($result,0,'code');
-		//echo $code;exit;
-		return($code);
-	}
-	//Possible  deprecated method
-	function get_survey_list()
-	{
-		$survey_table = Database :: get_course_table(TABLE_SURVEY);
-		$sql_query = "SELECT survey_id,title FROM $survey_table where title!='' ";
-		$sql_result = Database::query($sql_query);
-		echo "<select name=\"author\">";
-		echo "<option value=\"\"><--Select Survey--></optional>";
-		while ($result =@Database::fetch_array($sql_result))
-		{
-			echo "\n<option value=\"".$result[survey_id]."\">".$result[title]."</option>";
-		}
-		echo "</select>";
-	}
-	//Possible  deprecated method
-	function create_survey ($surveycode,$surveytitle, $surveysubtitle, $author, $survey_language, $availablefrom, $availabletill,$isshare, $surveytemplate, $surveyintroduction, $surveythanks, $table_survey, $table_group)
-		{
-			//$table_survey = Database :: get_course_table(TABLE_SURVEY);
-			$sql = "INSERT INTO $table_survey (code,title, subtitle, author,lang,avail_from,avail_till, is_shared,template,intro,surveythanks,creation_date) values('$surveycode','$surveytitle','$surveysubtitle','$author','$survey_language','$availablefrom','$availabletill','$isshare','$surveytemplate','$surveyintroduction','$surveythanks',curdate())";
-			$result = Database::query($sql);
-			//$result = Database::query($sql);
-			$survey_id = Database::insert_id();
-			$sql2 = "INSERT INTO $table_group(group_id,survey_id,groupname,introduction) values('','$survey_id','No Group','This is your Default Group')";
-			$result = Database::query($sql2);
-			return $survey_id;
-		}
-	//Possible  deprecated method
-	//Possible  deprecated method
-	function create_survey_attach($surveycode,$surveytitle, $surveysubtitle, $author, $survey_language, $availablefrom, $availabletill,$isshare, $surveytemplate, $surveyintroduction, $surveythanks, $table_survey, $table_group)
-	{
-			//$table_survey = Database :: get_course_table(TABLE_SURVEY);
-			$sql = "INSERT INTO $table_survey (code,title, subtitle, author,lang,avail_from,avail_till, is_shared,template,intro,surveythanks,creation_date) values('$surveycode','$surveytitle','$surveysubtitle','$author','$survey_language','$availablefrom','$availabletill','$isshare','$surveytemplate','$surveyintroduction','$surveythanks',curdate())";
-			$result = Database::query($sql);
-			$survey_id = Database::insert_id();
-			return $survey_id;
-	}
-	
-	//Possible  deprecated method
-
-	function update_survey($surveyid,$surveycode,$surveytitle, $surveysubtitle, $author, $survey_language, $availablefrom, $availabletill,$isshare, $surveytemplate, $surveyintroduction, $surveythanks, $cidReq,$table_course) {	  
-          
-          $sql_course = "SELECT * FROM $table_course WHERE code = '$cidReq'";
-          $res_course = Database::query($sql_course);
-          $obj_course=@Database::fetch_object($res_course);
-          $curr_dbname = $obj_course->db_name ;         
-          
-		  $sql = "UPDATE $curr_dbname.survey SET code='$surveycode', title='$surveytitle', subtitle='$surveysubtitle', lang='$survey_language',   avail_from='$availablefrom', avail_till='$availabletill', is_shared='$isshare', template='$surveytemplate', intro='$surveyintroduction',surveythanks='$surveythanks'
-		  		  WHERE survey_id='$surveyid'";
-		  Database::query($sql);
-		  return $curr_dbname;
-	}
-
-	
-	// Possible  deprecated method
-	 
-	function update_question($qid,$qtype,$caption,$alignment,$answers,$open_ans,$curr_dbname)
-	{
-      	for($i=0;$i<10;$i++)
-		{
-		   $k=$i+1;
-		   $a.$k= $answers[$i];
-		}
-		$anst = $answerT;
-		$ansd = $answerD;
-		$sql = "UPDATE $curr_dbname.questions SET qtype='$qtype',caption='$caption',alignment='$alignment',a1='$answers[0]',a2='$answers[1]',a3='$answers[2]',a4='$answers[3]',a5='$answers[4]',a6='$answers[5]',a7='$answers[6]',a8='$answers[7]',a9='$answers[8]',a10='$answers[9]' WHERE qid='$qid'";
-		$result = Database::query($sql);
-		return Database::insert_id();
-	}
-	
-	
-	//Possible  deprecated method
-	 
-	 function get_question_type($questionid)
-	 {
-	  $table_question = Database :: get_course_table(TABLE_MAIN_SURVEYQUESTION);
-	  $questionid = Database::escape_string($questionid);
-	  $sql = "SELECT * FROM $table_question WHERE qid='$questionid'";
-			$res=Database::query($sql);
-			$code=@Database::result($res,0,'type');
-			return($code);
-	 }
-
-	//Possible  deprecated method
-	 
-	 function no_of_question($db_name,$gid)
-	 {
-	  //$table_question = Database :: get_course_table(TABLE_MAIN_SURVEYQUESTION);
-	  $gid = Database::escape_string($gid);
-	  $sql = "SELECT * FROM $db_name.questions WHERE gid='$gid'";
-			$res=Database::query($sql);
-			$code=@Database::num_rows($res);
-			return($code);
-	 }
-
-	
-	 //Possible  deprecated method
-	 
-	function get_data($id, $field)
-	{
-		global $_course;
-		$sql='SELECT '.$field.' FROM '.$_course['dbName'].'.survey WHERE survey_id='.intval($id);
-		$res=Database::query($sql);
-		$code=@Database::result($res,0);
-		return($code);
-
-	}
-	
-	//Possible  deprecated method
-	 
-	function get_all_datas($id)
-	{
-		global $_course;
-		$sql='SELECT * FROM '.$_course['dbName'].'.survey WHERE survey_id='.intval($id);
-		$res=Database::query($sql);
-		return Database::fetch_object($res);
-	}
-	//Possible  deprecated method
-	function get_surveyname($db_name,$sid)
-	{
-			//$surveytable=Database:: get_course_table(TABLE_SURVEY);
-			$sid = Database::escape_string($sid);
-			$sql="SELECT * FROM $db_name.survey WHERE survey_id=$sid";
-			$res=Database::query($sql);
-			$code=@Database::result($res,0,'title');
-			return($code);
-	}
-	//Possible  deprecated method
-	function get_surveyname_display($sid)
-	{
-			$sid = Database::escape_string($sid);
-			$surveytable=Database:: get_course_table(TABLE_SURVEY);
-			$sql="SELECT * FROM $surveytable WHERE survey_id=$sid";
-			$res=Database::query($sql);
-			$code=@Database::result($res,0,'title');
-			return($code);
-	}
-
-	//Possible  deprecated method
-	function import_questions($import_type, $ids)
-	{
-			//$groupname=surveymanager::get_groupname($gid_arr[$index]);
-			switch ($import_type) {
-				case "survey":
-				{
-
-				}
-				case "groups":
-				{
-				 foreach ($ids as $gid){
-				 $sql="insert into $table_question SELECT ('',gid,qtype,caption,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,at,ad,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10) FROM $table_question where gid=$gid";
-				 }
-				}
-				case "questions":
-				{
-
-				}
-			}
-			$table_question = Database :: get_course_table(TABLE_MAIN_SURVEYQUESTION);
-			if(isset($selected_group)){
-			 if($selected_group!=''){
-			  $sql = "SELECT $table_group('survey_id', 'groupname') values('$sid', '$groupname')";
-				$res = Database::query($sql);
-				$sql = "INSERT INTO $table_group('survey_id', 'groupname') values('$sid', '$groupname')";
-				$res = Database::query($sql);
-				$gid_arr[$index]+= Database::insert_id();
-				$groupids=implode(",",$gid_arr);
-			  }
-			}
-
-			echo $groupids;
-	}
-
-	
-	 // This function deletes a survey and all the groups and question belonging to it.
-	 //* @param unknown_type $survey_id
-	 
-	 // @author unknown
-	 // @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, cleanup and refactoring
-	 
-	 
-	public static function delete_survey($survey_id)
-	{
-		$table_survey 	= Database :: get_course_table(TABLE_SURVEY);
-		$table_group 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP);
-		$table_question = Database :: get_course_table(TABLE_MAIN_SURVEYQUESTION);
-
-		$survey_id = Database::escape_string($survey_id);
-
-		// Deleting the survey
-		$sql = "DELETE FROM $table_survey WHERE survey_id='".$survey_id."'";
-		Database::query($sql);
-
-		// Deleting all the questions of the survey
-		$sql = "SELECT * FROM $table_group WHERE survey_id='".$survey_id."'";
-		$res = Database::query($sql);
-		while($obj = Database::fetch_object($res))
-		{
-			$sql = "DELETE FROM $table_question WHERE gid='".$obj->group_id."'";
-			Database::query($sql);
-		}
-
-		// Deleting the groups of the survey
-		$sql = "DELETE FROM $table_group WHERE survey_id='".$survey_id."'";
-		Database::query($sql);
-		return true;
-	}
-
-
-	function delete_group($group_id)
-	{
-		// Database table definitions
-		// @todo use database constants for the survey tables 
-		$table_question 	= Database :: get_course_table(TABLE_MAIN_SURVEYQUESTION);
-		$table_survey_group = Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP);
-
-		$sql = "DELETE FROM $table_question WHERE gid='".$group_id."'";
-		Database::query($sql);
-		$sql = "DELETE FROM $table_survey_group WHERE group_id='".$group_id."'";
-		Database::query($sql);
-	}
-	
-	 // Possible  deprecated method
-
-	function select_group_list($survey_id, $seleced_groupid='', $extra_script='')
-	{
-		$group_table = Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP);
-		$sql = "SELECT * FROM $group_table WHERE survey_id='$survey_id'";
-		$sql_result = Database::query($sql);
-		if(Database::num_rows($sql_result)>0)
-		{
-			$str_group_list = "";
-			$str_group_list .= "<select name=\"exiztinggroup\" $extra_script>\n";
-
-			while($result=Database::fetch_array($sql_result))
-			{
-			 $selected = ($seleced_groupid==$result[group_id])?"selected":"";
-			 $str_group_list .= "\n<option value=\"".$result[group_id]."\" ".$selected.">".$result[groupname]."</option>\n";
-			}
-
-			$str_group_list .= "</select>";
-			return $str_group_list;
-
-		}
-		else
-		{
-			return false;
-		}
-
-	}
-
-
-	 //Possible  deprecated method
-
-	function display_imported_group($sid,$table_group,$table_question)
-	{
-
-		 $sql = "SELECT group_id FROM $table_group WHERE survey_id='$sid'";
-		$res = Database::query($sql);
-		$num = @Database::num_rows($res);
-		//echo "ths is num".$num;
-		$parameters = array();
-		$displays = array();
-		while($obj = @Database::fetch_object($res))
-		{
-
-			$groupid = $obj->group_id;
-			$query = "SELECT * FROM $table_question WHERE gid = '$groupid'";
-			$result = Database::query($query);
-		  while($object = @Database::fetch_object($result))
-			{
-				$display = array();
-				$display[] = '<input type="checkbox" name="course[]" value="'.$object->qid.'"/>';
-				$display[] = $object->caption;
-				$display[] = $object->qtype;
-				$id = $object->gid;
-				//echo "THIS IS GROUP NAME ID".$id;
-				$gname = surveymanager::get_groupname($id);
-				$display[] = $gname;
-				$displays[] = $display;
-			}
-		}
-			$table_header[] = array('', false);
-			$table_header[] = array(get_lang('Question'), true);
-			$table_header[] = array(get_lang('QuestionType'), true);
-			$table_header[] = array(get_lang('Group'), true);
-			Display :: display_sortable_table($table_header, $displays, array (), array (), $parameters);
-	}
-
-	
-	//   Possible  deprecated method
-	 
-	function attach_survey($surveyid,$newsurveyid,$db_name,$curr_dbname)
-	//For attaching the whole survey with its groups and questions
-	  {
-	 $sql = "SELECT *  FROM $db_name.survey_group WHERE survey_id = '$surveyid'";
-     $res = Database::query($sql);
-	 while($obj=@Database::fetch_object($res))
-     {
-		 $groupname=addslashes($obj->groupname);
-		 $introduction=addslashes($obj->introduction);
-	   $sql_insert = "INSERT INTO $curr_dbname.survey_group(group_id,survey_id,groupname,introduction) values('','$newsurveyid','$groupname','$introduction')";
-	   $resnext = Database::query($sql_insert);
-	   $groupid = Database::insert_id();
-	   $sql_q = "SELECT *  FROM $db_name.questions WHERE gid = '$obj->group_id'";
-	   $res_q = Database::query($sql_q);
-       while($obj_q = Database::fetch_object($res_q))
-	   {
-		 $caption1=addslashes($obj_q->caption);
-		      $a1=addslashes($obj_q->a1);
-			  $a2=addslashes($obj_q->a2);
-			  $a3=addslashes($obj_q->a3);
-			  $a4=addslashes($obj_q->a4);
-			  $a5=addslashes($obj_q->a5);
-			  $a6=addslashes($obj_q->a6);
-			  $a7=addslashes($obj_q->a7);
-			  $a8=addslashes($obj_q->a8);
-			  $a9=addslashes($obj_q->a9);
-			  $a10=addslashes($obj_q->a10);
-              $at=addslashes($obj_q->at);
-			  $ad=addslashes($obj_q->ad);
-			  $r1=addslashes($obj_q->r1);
-			  $r2=addslashes($obj_q->r2);
-			  $r3=addslashes($obj_q->r3);
-			  $r4=addslashes($obj_q->r4);
-			  $r5=addslashes($obj_q->r5);
-			  $r6=addslashes($obj_q->r6);
-			  $r7=addslashes($obj_q->r7);
-			  $r8=addslashes($obj_q->r8);
-			  $r9=addslashes($obj_q->r9);
-			  $r10=addslashes($obj_q->r10);
-		 $sql_sort = "SELECT max(sortby) AS sortby FROM $curr_dbname.questions ";
-         $res_sort=Database::query($sql_sort);
-         $rs=Database::fetch_object($res_sort);
-	     $sortby=$rs->sortby;
-	     if(empty($sortby))
-	     {$sortby=1;}
-	     else{$sortby=$sortby+1;}
-		 $sql_q_insert = "INSERT INTO $curr_dbname.questions (qid,gid,survey_id,qtype,caption,alignment,sortby,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,at,ad,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10) values('','$groupid','$newsurveyid','$obj_q->qtype','$caption1','$obj_q->alignment','$sortby','$a1','$a2','$a3','$a4','$a5','$a6','$a7','$a8','$a9','$a10','$at','$ad','$r1','$r2','$r3','$r4','$r5','$r6','$r7','$r8','$r9','$r10')";
-	    Database::query($sql_q_insert);
-	   }
-     }
-   }
-
-	
-	// Possible  deprecated method
-	 
-   function update_group($groupid,$surveyid,$groupnamme,$introduction,$curr_dbname)
-	{
-		$sql = "UPDATE $curr_dbname.survey_group SET group_id='$groupid', survey_id='$surveyid', groupname='$groupnamme', introduction='$introduction' WHERE group_id='$groupid'";
-		Database::query($sql);
-	}
-
-	
-	 //  Possible  deprecated method
-	 
-	function create_course_survey_rel($cidReq,$survey_id,$table_course,$table_course_survey_rel)
-	{
-	 $sql = "SELECT * FROM $table_course WHERE code = '$cidReq'";
-	 $res = Database::query($sql);
-	 $obj=@Database::fetch_object($res);
-	 $db_name = $obj->db_name ;
-	 $sql="INSERT INTO $table_course_survey_rel(id,course_code,db_name,survey_id) values('','$cidReq','$db_name','$survey_id')";
-
-	 Database::query($sql);
-	 return $db_name;
-	}
-
-	
-	//  Possible  deprecated method
-	 
-	function pick_surveyname($sid)
-	{
-		$surveytable=Database:: get_course_table(TABLE_SURVEY);
-		$sql="SELECT * FROM $surveytable WHERE survey_id=$sid";
-		$res=Database::query($sql);
-		$code=@Database::result($res,0,'title');
-		return($code);
-	}
-
-	 // Possible  deprecated method
-	 
-	function pick_author($survey_id)
-	{
-	    $survey_table = Database :: get_course_table(TABLE_SURVEY);
-		$sql = "SELECT author FROM $survey_table WHERE survey_id='$survey_id'";
-		$res = Database::query($sql);
-		$author=@Database::result($res,0,'author');
-		return $author;
-	}
-
-	function get_status()
-	{
-		global $_user;
-
-		$table_user = Database::get_main_table(TABLE_MAIN_USER);
-		$sqlm = "SELECT  status FROM  $table_user WHERE user_id = '".Database::escape_string($_user['user_id'])."'";
-		$resm = Database::query($sqlm);
-		$objm=@Database::fetch_object($resm);
-		$ss = $objm->status ;
-		return $ss;
-	}
-}
 */
 
 /**
@@ -505,13 +31,18 @@ class SurveyTree {
 		if ($search_restriction) {
 			$search_restriction = ' AND '.$search_restriction;
 		}
+		
+		$course_id = api_get_course_int_id();
+		
 
 		$sql = "SELECT survey.survey_id , survey.parent_id, survey_version, survey.code as name
-		FROM $table_survey survey
-		LEFT JOIN  $table_survey_question  survey_question
-		ON survey.survey_id = survey_question.survey_id , $table_user user
-		WHERE survey.author = user.user_id
-		GROUP BY survey.survey_id";
+				FROM $table_survey survey LEFT JOIN $table_survey_question  survey_question
+				ON survey.survey_id = survey_question.survey_id , $table_user user
+				WHERE
+					survey.c_id 			=  $course_id AND 
+					survey_question.c_id 	=  $course_id AND 
+					survey.author 			= user.user_id
+				GROUP BY survey.survey_id";
 
 		$res = Database::query($sql);
 		$surveys_parents = array ();
@@ -599,5 +130,4 @@ class SurveyTree {
 		}
 		return $result;
 	}
-}
-?>
+}

+ 12 - 5
main/inc/lib/thematic.lib.php

@@ -27,8 +27,11 @@ class Thematic
 	private $thematic_advance_content;
 	private	$start_date;
 	private $duration;
+	private $course_int_id;
 
-	public function __construct() {}
+	public function __construct() {
+		$this->course_int_id = api_get_course_int_id();
+	}
 	
 	
 	/**
@@ -278,7 +281,8 @@ class Thematic
 		
 		if (empty($id)) {
 			// insert
-			$sql = "INSERT INTO $tbl_thematic(title, content, active, display_order, session_id) VALUES ('$title', '$content', 1, ".(intval($max_thematic_item)+1).", $session_id) ";
+			$sql = "INSERT INTO $tbl_thematic (c_id, title, content, active, display_order, session_id) 
+					VALUES ($this->course_int_id, '$title', '$content', 1, ".(intval($max_thematic_item)+1).", $session_id) ";
 			Database::query($sql);
 			$last_id = Database::insert_id();
 			if (Database::affected_rows()) {
@@ -631,7 +635,8 @@ class Thematic
 
 		if (empty($id)) {			
 			// Insert
-			$sql = "INSERT INTO $tbl_thematic_advance (thematic_id, attendance_id, content, start_date, duration) VALUES ($tematic_id, $attendance_id, '$content', '".api_get_utc_datetime($start_date)."', '$duration') ";
+			$sql = "INSERT INTO $tbl_thematic_advance (c_id, thematic_id, attendance_id, content, start_date, duration) 
+					VALUES ($this->course_int_id, $tematic_id, $attendance_id, '$content', '".api_get_utc_datetime($start_date)."', '$duration') ";
 			Database::query($sql);
 			$last_id = Database::insert_id();
             if (Database::affected_rows()) {
@@ -813,7 +818,8 @@ class Thematic
                 }                
             } else {            
                 // insert
-    			$ins = "INSERT INTO $tbl_thematic_plan(thematic_id, title, description, description_type) VALUES($thematic_id, '$title', '$description', $description_type) ";    		
+    			$ins = "INSERT INTO $tbl_thematic_plan (c_id, thematic_id, title, description, description_type) 
+    					VALUES ($this->course_int_id, $thematic_id, '$title', '$description', $description_type) ";    		
     			Database::query($ins);
                 $last_id = Database::insert_id();
     			$affected_rows = Database::affected_rows();
@@ -823,7 +829,8 @@ class Thematic
             }            
 		} else {		    
 			// insert
-			$ins = "INSERT INTO $tbl_thematic_plan(thematic_id, title, description, description_type) VALUES($thematic_id, '$title', '$description', $description_type) ";			
+			$ins = "INSERT INTO $tbl_thematic_plan (c_id, thematic_id, title, description, description_type) 
+					VALUES($this->course_int_id, $thematic_id, '$title', '$description', $description_type) ";			
 			Database::query($ins);
             $last_id = Database::insert_id();
 			$affected_rows = Database::affected_rows();

+ 112 - 65
main/inc/lib/tracking.lib.php

@@ -335,9 +335,9 @@ class Tracking {
 		$course_code = Database::escape_string($course_code);
 		// get the informations of the course
 		$a_course = CourseManager :: get_course_information($course_code);
-		if(!empty($a_course['db_name'])) {
+		if (!empty($a_course)) {
 			// table definition
-			$tbl_course_quiz = Database::get_course_table(TABLE_QUIZ_TEST,$a_course['db_name']);
+			$tbl_course_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
 			$tbl_stats_exercise = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
 
 			// Compose a filter based on optional exercise given
@@ -353,7 +353,8 @@ class Tracking {
 				$session_id = intval($session_id);
 				$condition_session = " AND session_id = $session_id ";
 			}
-			$sql = "SELECT count(id) FROM $tbl_course_quiz WHERE active <> -1 $condition_quiz ";			
+			$sql = "SELECT count(id) FROM $tbl_course_quiz 
+					WHERE c_id = {$a_course['real_id']} AND active <> -1 $condition_quiz ";			
 			$count_quiz = Database::fetch_row(Database::query($sql));
 
 			$quiz_avg_total_score = 0;
@@ -366,7 +367,8 @@ class Tracking {
 				}
 
 				if (empty($exercise_id)) {
-					$sql = "SELECT id FROM $tbl_course_quiz WHERE active <> -1 $condition_quiz";
+					$sql = "SELECT id FROM $tbl_course_quiz 
+							WHERE c_id = {$a_course['real_id']} AND active <> -1 $condition_quiz";
 					$exercises = Database::fetch_row(Database::query($sql));
 					$exercise_list = array();
 					$exercise_id = 0;
@@ -462,21 +464,21 @@ class Tracking {
 
 		// get the informations of the course
 		$a_course = CourseManager :: get_course_information($course_code);
-		if (!empty($a_course['db_name'])) {
+		if (!empty($a_course)) {
 			// table definition
-			$tbl_course_lp_view = Database :: get_course_table(TABLE_LP_VIEW, $a_course['db_name']);
-			$tbl_course_lp = Database :: get_course_table(TABLE_LP_MAIN, $a_course['db_name']);
+			$tbl_course_lp_view = Database :: get_course_table(TABLE_LP_VIEW);
+			$tbl_course_lp = Database :: get_course_table(TABLE_LP_MAIN);
 
 			// Compose a filter based on optional learning paths list given
 			$condition_lp = "";
 
 			if (!empty($lp_ids)) {
 				if (count($lp_ids) > 0) {
-					$condition_lp =" WHERE id IN(".implode(',',$lp_ids).") ";
+					$condition_lp ="  AND id IN(".implode(',',$lp_ids).") ";
 				}
 			}
 			$session_id = intval($session_id);
-			$sql = "SELECT id FROM $tbl_course_lp lp $condition_lp";
+			$sql = "SELECT id FROM $tbl_course_lp lp WHERE c_id = {$a_course['real_id']} $condition_lp";
 			$res_count_lp = Database::query($sql);
 			// count the number of learning paths
 			$lp_id = array();
@@ -502,7 +504,9 @@ class Tracking {
 					// Get last view for each student (in case of multi-attempt)
 					// Also filter on LPs of this session
 					$sql_maxes = "SELECT MAX(view_count), progress FROM $tbl_course_lp_view lp_view ".
-                             "WHERE $condition_user session_id = $session_id AND lp_view.lp_id IN (".implode(',',$lp_id).") ".
+                             	"WHERE 	c_id = {$a_course['real_id']} AND 
+                             			$condition_user session_id = $session_id AND 
+                             			lp_view.lp_id IN (".implode(',',$lp_id).") ".
                              "GROUP BY lp_id, user_id";                
 					$res_maxes = Database::query($sql_maxes);
 					$sum =  0;
@@ -559,14 +563,16 @@ class Tracking {
 
 			$course = CourseManager :: get_course_information($course_code);
 
-			if (!empty($course['db_name'])) {
+			if (!empty($course)) {
 
 				// get course tables names
-				$tbl_quiz_questions = Database :: get_course_table(TABLE_QUIZ_QUESTION,$course['db_name']);
-				$lp_table           = Database :: get_course_table(TABLE_LP_MAIN,$course['db_name']);
-				$lp_item_table      = Database :: get_course_table(TABLE_LP_ITEM,$course['db_name']);
-				$lp_view_table      = Database :: get_course_table(TABLE_LP_VIEW,$course['db_name']);
-				$lp_item_view_table = Database :: get_course_table(TABLE_LP_ITEM_VIEW,$course['db_name']);
+				$tbl_quiz_questions = Database :: get_course_table(TABLE_QUIZ_QUESTION);
+				$lp_table           = Database :: get_course_table(TABLE_LP_MAIN);
+				$lp_item_table      = Database :: get_course_table(TABLE_LP_ITEM);
+				$lp_view_table      = Database :: get_course_table(TABLE_LP_VIEW);
+				$lp_item_view_table = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
+				
+				$course_id = $course['real_id'];
 
 				// Compose a filter based on optional learning paths list given
 
@@ -589,9 +595,9 @@ class Tracking {
 				// database (and if no list was given, get them all)
 
 				if (empty($session_id)) {
-					$sql = "SELECT DISTINCT(id), use_max_score FROM $lp_table  WHERE session_id = 0 $condition_lp ";
+					$sql = "SELECT DISTINCT(id), use_max_score FROM $lp_table WHERE c_id = $course_id AND session_id = 0 $condition_lp ";
 				} else {
-					$sql = "SELECT DISTINCT(id), use_max_score FROM $lp_table WHERE 1 $condition_lp ";
+					$sql = "SELECT DISTINCT(id), use_max_score FROM $lp_table WHERE c_id = $course_id $condition_lp ";
 				}
 
 				$res_row_lp   = Database::query($sql);
@@ -625,7 +631,11 @@ class Tracking {
 					// Getting latest LP result for a student
 					//@todo problem when a  course have more than 1500 users
 					$sql = "SELECT MAX(view_count) as vc, id, progress, lp_id, user_id  FROM $lp_view_table
-                            WHERE lp_id IN (".implode(',',$lp_list).") $condition_user1 AND session_id = $session_id GROUP BY lp_id, user_id";
+                            WHERE 	c_id = $course_id AND 
+                            		lp_id IN (".implode(',',$lp_list).") 
+                            		$condition_user1 AND 
+									session_id = $session_id 
+							GROUP BY lp_id, user_id";
 					if ($debug) echo $sql;
 					$rs_last_lp_view_id = Database::query($sql);
 
@@ -648,7 +658,8 @@ class Tracking {
 							if ($get_only_latest_attempt_results) {
 								//if (1) {
 								//Getting lp_items done by the user
-								$sql  = "SELECT DISTINCT lp_item_id FROM $lp_item_view_table WHERE lp_view_id = $lp_view_id ORDER BY lp_item_id";
+								$sql  = "SELECT DISTINCT lp_item_id FROM $lp_item_view_table 
+										WHERE c_id = $course_id AND lp_view_id = $lp_view_id ORDER BY lp_item_id";
 								$res_lp_item = Database::query($sql);
 
 								while ($row_lp_item = Database::fetch_array($res_lp_item,'ASSOC')) {
@@ -657,9 +668,13 @@ class Tracking {
 									//Getting the most recent attempt
 									$sql = "SELECT lp_iv.id as lp_item_view_id, lp_iv.score as score,lp_i.max_score, lp_iv.max_score as max_score_item_view, lp_i.path, lp_i.item_type, lp_i.id as iid
                                             FROM $lp_item_view_table as lp_iv INNER JOIN $lp_item_table as lp_i ON lp_i.id = lp_iv.lp_item_id AND (lp_i.item_type='sco' OR lp_i.item_type='".TOOL_QUIZ."') 
-                                            WHERE lp_item_id = $my_lp_item_id AND lp_view_id = $lp_view_id ORDER BY view_count DESC LIMIT 1";
+                                            WHERE 	lp_iv.c_id = $course_id AND 
+                                            		lp_i.c_id  = $course_id AND
+													lp_item_id = $my_lp_item_id AND 
+													lp_view_id = $lp_view_id 
+											ORDER BY view_count DESC 
+											LIMIT 1";
 									$res_lp_item_result = Database::query($sql);
-
 									while ($row_max_score = Database::fetch_array($res_lp_item_result,'ASSOC')) {
 										$list[]= $row_max_score;
 									}
@@ -669,7 +684,9 @@ class Tracking {
 								// max_score of each item if it is a sco or a TOOL_QUIZ
 								$sql_max_score = "SELECT lp_iv.id as lp_item_view_id, lp_iv.score as score,lp_i.max_score, lp_iv.max_score as max_score_item_view, lp_i.path, lp_i.item_type, lp_i.id as iid
                                                   FROM $lp_item_view_table as lp_iv INNER JOIN $lp_item_table as lp_i ON lp_i.id = lp_iv.lp_item_id AND (lp_i.item_type='sco' OR lp_i.item_type='".TOOL_QUIZ."') 
-                                                  WHERE lp_view_id = $lp_view_id ";
+                                                  WHERE lp_iv.c_id = $course_id AND 
+                                            			lp_i.c_id  = $course_id AND
+														lp_view_id = $lp_view_id ";
 								if ($debug) echo $sql_max_score.'<br />';
 
 								$res_max_score = Database::query($sql_max_score);
@@ -784,7 +801,7 @@ class Tracking {
 					if ($debug) var_dump($lp_list);
 					foreach($lp_list as $lp_id) {
 						//Check if LP have a score we asume that all SCO have an score
-						$sql = "SELECT count(id) as count FROM $lp_item_table WHERE (item_type = 'quiz' OR item_type = 'sco') AND lp_id = ".$lp_id;
+						$sql = "SELECT count(id) as count FROM $lp_item_table WHERE c_id = $course_id AND  (item_type = 'quiz' OR item_type = 'sco') AND lp_id = ".$lp_id;
 						if ($debug) echo $sql;
 						$result_have_quiz = Database::query($sql);
 
@@ -835,34 +852,33 @@ class Tracking {
 			$student_id = intval($student_id);
 			$total_time = 0;
 
-			if (!empty($course['db_name'])) {
+			if (!empty($course)) {
 
-				$lp_table   = Database :: get_course_table(TABLE_LP_MAIN, $course['db_name']);
-				$t_lpv         = Database :: get_course_table(TABLE_LP_VIEW, $course['db_name']);
-				$t_lpiv     = Database :: get_course_table(TABLE_LP_ITEM_VIEW, $course['db_name']);
+				$lp_table   = Database :: get_course_table(TABLE_LP_MAIN);
+				$t_lpv      = Database :: get_course_table(TABLE_LP_VIEW);
+				$t_lpiv     = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
+				
+				$course_id	 = $course['real_id'];
 
 				// Compose a filter based on optional learning paths list given
 				$condition_lp = "";
 				if(count($lp_ids) > 0) {
-					$condition_lp =" WHERE id IN(".implode(',',$lp_ids).") ";
+					$condition_lp =" AND id IN(".implode(',',$lp_ids).") ";
 				}
 
 				// Compose a filter based on optional session id
 				$condition_session = "";
 				$session_id = intval($session_id);
 
+				
 				if (isset($session_id)) {
-					if (count($lp_ids) > 0) {
-						$condition_session = " AND session_id = $session_id ";
-					} else {
-						$condition_session = " WHERE session_id = $session_id ";
-					}
+					$condition_session = " AND session_id = $session_id ";
 				}
 
 				// Check the real number of LPs corresponding to the filter in the
 				// database (and if no list was given, get them all)
 				//$res_row_lp = Database::query("SELECT DISTINCT(id) FROM $lp_table $condition_lp $condition_session");
-				$res_row_lp = Database::query("SELECT DISTINCT(id) FROM $lp_table $condition_lp");
+				$res_row_lp = Database::query("SELECT DISTINCT(id) FROM $lp_table WHERE c_id = $course_id $condition_lp");
 				$count_row_lp = Database::num_rows($res_row_lp);
 
 				// calculates time
@@ -873,8 +889,12 @@ class Tracking {
                             FROM '.$t_lpiv.' AS item_view
                             INNER JOIN '.$t_lpv.' AS view
                                 ON item_view.lp_view_id = view.id
-                                AND view.lp_id = '.$lp_id.'
-                                AND view.user_id = '.$student_id.' AND session_id = '.$session_id;
+                                WHERE
+                                item_view.c_id 		= '.$course_id.' AND
+                                view.c_id 			= '.$course_id.' AND 
+                                view.lp_id 			= '.$lp_id.'
+                                AND view.user_id 	= '.$student_id.' AND 
+								session_id 			= '.$session_id;
 
 						$rs = Database::query($sql);
 						if (Database :: num_rows($rs) > 0) {
@@ -900,15 +920,17 @@ class Tracking {
 			$last_time = 0;
 			$session_id = intval($session_id);
 
-			if (!empty($course['db_name'])) {
+			if (!empty($course)) {
+				
+				$course_id	 = $course['real_id'];
 
-				$lp_table    = Database :: get_course_table(TABLE_LP_MAIN, $course['db_name']);
-				$t_lpv       = Database :: get_course_table(TABLE_LP_VIEW, $course['db_name']);
-				$t_lpiv      = Database :: get_course_table(TABLE_LP_ITEM_VIEW, $course['db_name']);
+				$lp_table    = Database :: get_course_table(TABLE_LP_MAIN);
+				$t_lpv       = Database :: get_course_table(TABLE_LP_VIEW);
+				$t_lpiv      = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
 
 				// Check the real number of LPs corresponding to the filter in the
 				// database (and if no list was given, get them all)
-				$res_row_lp = Database::query("SELECT id FROM $lp_table WHERE id = $lp_id ");
+				$res_row_lp = Database::query("SELECT id FROM $lp_table WHERE c_id = $course_id AND id = $lp_id ");
 				$count_row_lp = Database::num_rows($res_row_lp);
 
 				// calculates last connection time
@@ -917,8 +939,11 @@ class Tracking {
                         FROM ' . $t_lpiv . ' AS item_view
                         INNER JOIN ' . $t_lpv . ' AS view
                             ON item_view.lp_view_id = view.id
-                            AND view.lp_id = '.$lp_id.'
-                            AND view.user_id = '.$student_id.' 
+                            WHERE
+                            item_view.c_id 		= '.$course_id.' AND
+                            view.c_id 			= '.$course_id.' AND  
+                            view.lp_id 			= '.$lp_id.'
+                            AND view.user_id 	= '.$student_id.' 
                             AND view.session_id = '.$session_id;
 					$rs = Database::query($sql);
 					if (Database :: num_rows($rs) > 0) {
@@ -1338,16 +1363,16 @@ class Tracking {
 		 * @return    int            Count of assignments
 		 */
 		public static function count_student_assignments($student_id, $course_code, $session_id = null) {
-			require_once (api_get_path(LIBRARY_PATH) . 'course.lib.php');
-
 			// protect datas
 			$course_code = Database::escape_string($course_code);
 			// get the informations of the course
 			$a_course = CourseManager :: get_course_information($course_code);
-			if (!empty($a_course['db_name'])) {
+			if (!empty($a_course)) {
 				// table definition
-				$tbl_item_property          = Database :: get_course_table(TABLE_ITEM_PROPERTY, $a_course['db_name']);
-				$tbl_student_publication = Database :: get_course_table(TABLE_STUDENT_PUBLICATION, $a_course['db_name']);
+				$tbl_item_property          = Database :: get_course_table(TABLE_ITEM_PROPERTY);
+				$tbl_student_publication 	= Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
+				
+				$course_id	 = $course_info['real_id'];
 
 				$condition_user = "";
 				if (is_array($student_id)) {
@@ -1362,7 +1387,13 @@ class Tracking {
 					$condition_session = " AND pub.session_id = $session_id ";
 				}
 
-				$sql = "SELECT count(ip.tool) FROM $tbl_item_property ip INNER JOIN $tbl_student_publication pub ON ip.ref = pub.id WHERE ip.tool='work' $condition_user $condition_session ";
+				$sql = "SELECT count(ip.tool) 
+						FROM $tbl_item_property ip INNER JOIN $tbl_student_publication pub 
+								ON ip.ref = pub.id 
+						WHERE 	ip.c_id  = $course_id AND 
+								pub.c_id  = $course_id AND
+								ip.tool='work' 
+								$condition_user $condition_session ";
 				$rs = Database::query($sql);
 				$row = Database::fetch_row($rs);
 				return $row[0];
@@ -1388,17 +1419,19 @@ class Tracking {
 			// get the informations of the course
 			$a_course = CourseManager :: get_course_information($course_code);
 
-			if(!empty($a_course['db_name']))
-			{
+			if (!empty($a_course)) {
+				
 				// table definition
-				$tbl_forum_post = Database :: get_course_table(TABLE_FORUM_POST, $a_course['db_name']);
-				$tbl_forum         = Database :: get_course_table(TABLE_FORUM, $a_course['db_name']);
+				$tbl_forum_post = Database :: get_course_table(TABLE_FORUM_POST);
+				$tbl_forum      = Database :: get_course_table(TABLE_FORUM);
+				
+				$course_id	 = $a_course['real_id'];
 
 				$condition_user = "";
 				if (is_array($student_id)) {
-					$condition_user = " WHERE post.poster_id IN (".implode(',',$student_id).") ";
+					$condition_user = " AND post.poster_id IN (".implode(',',$student_id).") ";
 				} else {
-					$condition_user = " WHERE post.poster_id = '$student_id' ";
+					$condition_user = " AND post.poster_id = '$student_id' ";
 				}
 
 				$condition_session = "";
@@ -1407,12 +1440,17 @@ class Tracking {
 					$condition_session = " AND forum.session_id = $session_id";
 				}
 
-				$sql = "SELECT 1 FROM $tbl_forum_post post INNER JOIN $tbl_forum forum ON forum.forum_id = post.forum_id $condition_user $condition_session ";
+				$sql = "SELECT 1 FROM $tbl_forum_post post INNER JOIN $tbl_forum forum 
+						ON forum.forum_id = post.forum_id 
+						
+						WHERE 	post.c_id  = $course_id AND
+								forum.c_id = $course_id
+								$condition_user $condition_session 
+				";
+				
 				$rs = Database::query($sql);
 				return Database::num_rows($rs);
-			}
-			else
-			{
+			} else {
 				return null;
 			}
 		}
@@ -1429,15 +1467,24 @@ class Tracking {
 			// get the informations of the course
 			$a_course = CourseManager :: get_course_information($course_code);
 			$count = 0;
-			if (!empty($a_course['db_name'])) {
-				$tbl_posts = Database :: get_course_table(TABLE_FORUM_POST, $a_course['db_name']);
-				$tbl_forums = Database :: get_course_table(TABLE_FORUM, $a_course['db_name']);
+			if (!empty($a_course)) {
+				$tbl_posts 		= Database :: get_course_table(TABLE_FORUM_POST);
+				$tbl_forums 	= Database :: get_course_table(TABLE_FORUM);
+				
 				$condition_session = '';
 				if (isset($session_id)) {
 					$session_id = intval($session_id);
-					$condition_session = ' WHERE f.session_id = '. $session_id;
+					$condition_session = ' AND f.session_id = '. $session_id;
 				}
-				$sql = "SELECT count(*) FROM $tbl_posts p INNER JOIN $tbl_forums f ON f.forum_id = p.forum_id $condition_session ";
+				
+				$course_id	 = $a_course['real_id'];
+				
+				$sql = "SELECT count(*) FROM $tbl_posts p INNER JOIN $tbl_forums f 
+						ON f.forum_id = p.forum_id
+						WHERE 	p.c_id = $course_id AND 
+								f.c_id = $course_id
+								$condition_session						  
+						";
 				$result = Database::query($sql);
 				$row = Database::fetch_row($result);
 				$count = $row[0];

+ 5 - 6
main/inc/tool_navigation_menu.inc.php

@@ -17,9 +17,7 @@ require_once api_get_path(LIBRARY_PATH).'course_home.lib.php'; // For using the
  * Build the navigation items to show in a course menu
  * @param boolean $include_admin_tools
  */
-function get_navigation_items($include_admin_tools = false) {
-
-	
+function get_navigation_items($include_admin_tools = false) {	
 	global $is_courseMember;
 	global $_user;
 	global $_course;
@@ -35,7 +33,7 @@ function get_navigation_items($include_admin_tools = false) {
 
 		$user_id = api_get_user_id();
 
-		$course_tools_table = Database :: get_course_table(TABLE_TOOL_LIST, $database);
+		$course_tools_table = Database :: get_course_table(TABLE_TOOL_LIST);
 
 		/*	Link to the Course homepage */
 
@@ -44,8 +42,9 @@ function get_navigation_items($include_admin_tools = false) {
 		$navigation_items['home']['name'] = get_lang('CourseHomepageLink');
 
 		/*	Link to the different tools */
+		$course_id = api_get_course_int_id();
 
-		$sql_menu_query = "SELECT * FROM $course_tools_table WHERE visibility='1' and admin='0' ORDER BY id ASC";
+		$sql_menu_query = "SELECT * FROM $course_tools_table WHERE c_id = $course_id AND visibility='1' and admin='0' ORDER BY id ASC";
 		$sql_result = Database::query($sql_menu_query);
 		while ($row = Database::fetch_array($sql_result)) {
 			$navigation_items[$row['id']] = $row;
@@ -61,7 +60,7 @@ function get_navigation_items($include_admin_tools = false) {
 
 		if ($include_admin_tools) {
 			$course_settings_sql = "SELECT name,image FROM $course_tools_table
-									WHERE link='course_info/infocours.php'";
+									WHERE c_id = $course_id  AND link='course_info/infocours.php'";
 			$sql_result = Database::query($course_settings_sql);
 			$course_setting_info = Database::fetch_array($sql_result);
 			$course_setting_visual_name = CourseHome::translate_tool_name($course_setting_info);

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

@@ -1644,7 +1644,7 @@ function display_database_settings_form($installType, $dbHostForm, $dbUsernameFo
       <?php endif; ?>
     </tr>
     <?php
-
+echo '<tr>';
     //database user username
     $example_login = get_lang('EG').' root';
     display_database_parameter($installType, get_lang('DBLogin'), 'dbUsernameForm', $dbUsernameForm, $example_login);
@@ -1652,35 +1652,24 @@ function display_database_settings_form($installType, $dbHostForm, $dbUsernameFo
     //database user password
     $example_password = get_lang('EG').' '.api_generate_password();
     display_database_parameter($installType, get_lang('DBPassword'), 'dbPassForm', $dbPassForm, $example_password);
-    ?>
     
-    <tr id="optional_param6">
-    	<td><?php echo get_lang('SingleDb'); ?> </td>
-        <?php if ($installType == INSTALL_TYPE_UPDATE): ?>
-        <td><input type="hidden" name="singleDbForm" value="<?php echo $singleDbForm; ?>" /><?php echo $singleDbForm ? get_lang('One') : get_lang('Several'); ?></td>
-        <?php else: ?>
-        <td>
-        	<input class="checkbox" type="radio" name="singleDbForm" value="1" id="singleDb1" <?php echo $singleDbForm ? 'checked="checked" ' : ''; ?> onclick="javascript: show_hide_tracking_and_user_db(this.id);" /> <label for="singleDb1"><?php echo get_lang('One'); ?></label>
-            <input class="checkbox" type="radio" name="singleDbForm" value="0" id="singleDb0" <?php echo $singleDbForm ? '' : 'checked="checked" '; ?> onclick="javascript: show_hide_tracking_and_user_db(this.id);" /> <label for="singleDb0"><?php echo get_lang('Several'); ?></label>
-		</td>
-        <?php endif; ?>
-        <td>&nbsp;</td>
-	</tr>
+    ?>
+
         
 	<?php 
 
     //Fields for the four standard Chamilo databases    
     if ($installType != INSTALL_TYPE_UPDATE) {        
-        echo '<tr><td colspan="3">';
+        /*echo '<tr><td colspan="3">';
         echo '<a href="#;" onclick="javascript:show_hide_option();" id="optionalparameters">
         	  <img style="vertical-align:middle;" src="../img/div_show.gif" alt="show-hide" /> '.get_lang('OptionalParameters').'</a>';
-        echo '</td></tr>';
+        echo '</td></tr>';*/
     }
     ?>    
     <input type="hidden" name="enableTrackingForm" value="1" />
     <?php   
     
-    $style = 'style="display:none;"';    
+    $style = '';    
     if ($installType == INSTALL_TYPE_UPDATE) {
         $style = '';
     } 

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

@@ -146,6 +146,11 @@ $installation_settings['{ADMINLANGUAGE}'] = $languageForm;
 $installation_settings['{HASHFUNCTIONMODE}'] = $encryptPassForm;
 load_main_database($installation_settings);
 
+
+require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php'; 
+update_Db_course();
+
+
 /**
  * Creating the tables of the tracking database
  */

+ 1 - 5
main/link/link.php

@@ -203,7 +203,6 @@ if (api_is_allowed_to_edit(null, true) && isset($_GET['action'])) {
 			
 			$clean_link_id = trim(Security::remove_XSS($_GET['id']));
 		}
-
 		echo '	<div class="row">
 					<div class="label">
 						<span class="form_required">*</span> '.get_lang('Url').'
@@ -212,7 +211,6 @@ if (api_is_allowed_to_edit(null, true) && isset($_GET['action'])) {
 						<input type="text" name="urllink" size="50" value="' . (empty($urllink) ? 'http://' : Security::remove_XSS($urllink)) . '" />
 					</div>
 				</div>';
-
 		echo '	<div class="row">
 					<div class="label">
 						'.get_lang('LinkName').'
@@ -260,7 +258,6 @@ if (api_is_allowed_to_edit(null, true) && isset($_GET['action'])) {
 			echo '		</div>
 					</div>';
 		}
-
 		echo '	<div class="row">
 					<div class="label">
 						'.get_lang('OnHomepage').'?
@@ -429,8 +426,7 @@ if (empty($_GET['action']) || ($_GET['action'] != 'editlink' && $_GET['action']
 	$sqlLinks = "SELECT * FROM ".$tbl_link." WHERE category_id=0 OR category_id IS NULL";
 	$result = Database::query($sqlLinks);
 	$numberofzerocategory = Database::num_rows($result);
-	echo '<table class="data_table">';
-	
+	echo '<table class="data_table">';	
 	if ($numberofzerocategory !== 0) {	    
 		echo '<tr><th style="font-weight: bold; text-align:left;padding-left: 10px;">'.get_lang('General').'</th></tr>';
 		echo '</table>';

+ 0 - 2
main/mySpace/access_details.php

@@ -162,9 +162,7 @@ $(function() {
 //Changes END
 
 Display :: display_header('');
-$tbl_userinfo_def = Database :: get_course_table(TABLE_USER_INFO);
 $main_user_info = api_get_user_info($user_id);
-
 $result_to_print = '';
 $main_date_array = array();
 

+ 1 - 1
main/mySpace/lp_tracking.php

@@ -89,7 +89,7 @@ Display :: display_header($nameTools);
 
 $lp_id = intval($_GET['lp_id']);
 
-$sql = 'SELECT name	FROM '.Database::get_course_table(TABLE_LP_MAIN, $course_info['db_name']).'	WHERE id='.$lp_id;
+$sql = 'SELECT name	FROM '.Database::get_course_table(TABLE_LP_MAIN).' WHERE c_id = '.$course_info['real_id'].' AND id='.$lp_id;
 $rs  = Database::query($sql);
 $lp_title = Database::result($rs, 0, 0);
 echo '<div class ="actions">';

+ 8 - 7
main/mySpace/myStudents.php

@@ -723,10 +723,8 @@ if (empty($_GET['details'])) {
 			get_lang('LastConnexion')
 		);
 
-		$t_lp 					= Database :: get_course_table(TABLE_LP_MAIN, $info_course['db_name']);
-		$tbl_stats_exercices 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-		$tbl_quiz_questions 	= Database :: get_course_table(TABLE_QUIZ_QUESTION, $info_course['db_name']);
-
+		$t_lp = Database :: get_course_table(TABLE_LP_MAIN, $info_course['db_name']);
+				
 		// csv export headers
 		$csv_content[] = array ();
 		$csv_content[] = array (
@@ -739,9 +737,9 @@ if (empty($_GET['details'])) {
 		);
 
         if (empty($session_id)) {
-            $sql_lp = " SELECT lp.name, lp.id FROM $t_lp lp WHERE session_id = 0 ORDER BY lp.display_order";
+            $sql_lp = " SELECT lp.name, lp.id FROM $t_lp lp WHERE session_id = 0 AND c_id = {$info_course['real_id']} ORDER BY lp.display_order";
         } else {
-        	$sql_lp = " SELECT lp.name, lp.id FROM $t_lp lp ORDER BY lp.display_order";
+        	$sql_lp = " SELECT lp.name, lp.id FROM $t_lp lp WHERE c_id = {$info_course['real_id']}  ORDER BY lp.display_order";
         }
 		$rs_lp = Database::query($sql_lp);
 		$token = Security::get_token();        
@@ -878,7 +876,10 @@ if (empty($_GET['details'])) {
 
 		$t_quiz = Database :: get_course_table(TABLE_QUIZ_TEST, $info_course['db_name']);
 		$sql_exercices = "SELECT quiz.title, id FROM " . $t_quiz . " AS quiz
-						  WHERE active='1' AND quiz.session_id = $session_id ORDER BY quiz.title ASC ";
+						  WHERE quiz.c_id =  ".$info_course['real_id']." AND
+						  		active='1' AND 
+								quiz.session_id = $session_id 
+							ORDER BY quiz.title ASC ";
 
 		$result_exercices = Database::query($sql_exercices);
 		$i = 0;

+ 5 - 13
main/newscorm/aicc.class.php

@@ -237,8 +237,7 @@ class aicc extends learnpath {
         $res = Database::query($sql);
         if (Database::num_rows($res) < 1) { error_log('New LP - Database for '.$course_code.' not found '.__FILE__.' '.__LINE__, 0); return -1; }
         $row = Database::fetch_array($res);
-        $dbname = Database::get_course_table_prefix().$row['db_name'].Database::get_database_glue();
-
+        
         $new_lp = Database::get_course_table(TABLE_LP_MAIN);
         $new_lp_item = Database::get_course_table(TABLE_LP_ITEM);
         $get_max = "SELECT MAX(display_order) FROM $new_lp";
@@ -252,12 +251,9 @@ class aicc extends learnpath {
 
         $this->config_encoding = "ISO-8859-1"; // TODO: We may apply detection for this value, see the function api_detect_encoding().
 
-        $sql = "INSERT INTO $new_lp " .
-                "(lp_type, name, ref, description, " .
-                "path, force_commit, default_view_mod, default_encoding, " .
-                "js_lib, content_maker,display_order)" .
+        $sql = "INSERT INTO $new_lp (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib, content_maker,display_order)" .
                 "VALUES " .
-                "(3,'".$this->course_title."', '".$this->course_id."','".$this->course_description."'," .
+                "($this->course_id, 3, '".$this->course_title."', '".$this->course_id."','".$this->course_description."'," .
                 "'".$this->subdir."', 0, 'embedded', '".$this->config_encoding."'," .
                 "'aicc_api.php','".$this->course_creator."',$dsp)";
         if ($this->debug > 2) { error_log('New LP - In import_aicc(), inserting path: '. $sql, 0); }
@@ -288,13 +284,9 @@ class aicc extends learnpath {
             $previous = 0;
             $prereq = $oAu->prereq_string;
             //$previous = (!empty($this->au_order_list_new_id[x]) ? $this->au_order_list_new_id[x] : 0); // TODO: Deal with the previous.
-            $sql_item = "INSERT INTO $new_lp_item " .
-                    "(lp_id,item_type,ref,title," .
-                    "path,min_score,max_score, $field_add" .
-                    "parent_item_id,previous_item_id,next_item_id," .
-                    "prerequisite,display_order) " .
+            $sql_item = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order) " .
                     "VALUES " .
-                    "($lp_id, 'au','".$oAu->identifier."','".$title."'," .
+                    "($this->course_id, $lp_id, 'au','".$oAu->identifier."','".$title."'," .
                     "'$path',0,100, $value_add" .
                     "$parent, $previous, 0, " .
                     "'$prereq', 0" .

+ 94 - 60
main/newscorm/learnpath.class.php

@@ -88,20 +88,23 @@ class learnpath {
         // Check params.
         // Check course code.
         $course_db = '';
+        
+        $this->course_id = api_get_course_int_id();
+        
         if ($this->debug > 0) {error_log('New LP - In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')', 0); }
         if (empty($course)) {
             $this->error = 'Course code is empty';
             return false;
         } else {
             $main_table = Database::get_main_table(TABLE_MAIN_COURSE);
-            //$course = Database::escape_string($course);
-            $course = $this->escape_string($course);
+            $course = $this->escape_string($course);            
             $sql = "SELECT * FROM $main_table WHERE code = '$course'";
             if ($this->debug > 2) { error_log('New LP - learnpath::__construct() '.__LINE__.' - Querying course: '.$sql, 0); }
             $res = Database::query($sql);
             if (Database::num_rows($res) > 0) {
-                $this->cc = $course;
-                $row_course = Database::fetch_array($res); 
+                $this->cc 			= $course;                
+                $row_course = Database::fetch_array($res);
+                $this->course_id 	= $row_course['id'];
                 $course_db = $row_course['db_name'];
             } else {
                 $this->error = 'Course code does not exist in database ('.$sql.')';
@@ -208,7 +211,7 @@ class learnpath {
                 error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - NOT Found previous view', 0);
             }
             $this->attempt = 1;
-            $sql_ins = "INSERT INTO $lp_table (lp_id,user_id,view_count, session_id) VALUES ($lp_id,$user_id,1,$session_id)";
+            $sql_ins = "INSERT INTO $lp_table (c_id, lp_id,user_id,view_count, session_id) VALUES ($this->course_id, $lp_id,$user_id,1,$session_id)";
             $res_ins = Database::query($sql_ins);
             $this->lp_view_id = Database :: insert_id();
             if ($this->debug > 2) {
@@ -330,9 +333,8 @@ class learnpath {
                   $this->items[$row['id']]->set_status($this->default_status);
                 }
                 // Add that row to the lp_item_view table so that we have something to show in the stats page.
-                $sql_ins = "INSERT INTO $lp_item_view_table " .
-                    "(lp_item_id, lp_view_id, view_count, status) VALUES " .
-                    "(" . $row['id'] . "," . $this->lp_view_id . ",1,'not attempted')";
+                $sql_ins = "INSERT INTO $lp_item_view_table (c_id, lp_item_id, lp_view_id, view_count, status) 
+                	VALUES ($this->course_id, ".$row['id'] . "," . $this->lp_view_id . ",1,'not attempted')";
                 if ($this->debug > 2) {
                     error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - Inserting blank item_view : ' . $sql_ins, 0);
                 }
@@ -428,22 +430,29 @@ class learnpath {
 
         $new_item_id = -1;
         $id = $this->escape_string($id);
-
+        
+        $course_id = api_get_course_int_id();
+        
+        
         if ($type == 'quiz') {
             $sql = 'SELECT SUM(ponderation)
 					FROM ' . Database :: get_course_table(TABLE_QUIZ_QUESTION) . ' as quiz_question
                     INNER JOIN  ' . Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION) . ' as quiz_rel_question
                     ON quiz_question.id = quiz_rel_question.question_id
-                    AND quiz_rel_question.exercice_id = ' . $id;
+                    WHERE 	quiz_rel_question.exercice_id = ' . $id." AND 
+	            			quiz_question.c_id = $course_id AND 
+	            			quiz_rel_question.c_id = $course_id ";
             $rsQuiz = Database::query($sql);
             $max_score = Database :: result($rsQuiz, 0, 0);
         } else {
             $max_score = 100;
         }
-
+        
+        
         if ($prerequisites != 0) {
-            $sql_ins = "INSERT INTO " . $tbl_lp_item . " ( ".
-                                "lp_id, ".
+            $sql_ins = "INSERT INTO " . $tbl_lp_item . " (
+            					c_id, 
+                                lp_id, ".
                                 "item_type, ".
                                 "ref, ".
                                 "title, ".
@@ -456,8 +465,9 @@ class learnpath {
                                 "display_order, ".
                                 "prerequisite, ".
                                 "max_time_allowed ".
-                            ") VALUES ( ".
-                                $this->get_id() . ", ".
+                            ") VALUES ( 
+                            	$course_id , 
+                                ".$this->get_id() . ", ".
                                 "'" . $type . "', ".
                                 "'', ".
                                 "'" . $title . "', ".
@@ -475,6 +485,7 @@ class learnpath {
             // Insert new item.
             $sql_ins = "
                             INSERT INTO " . $tbl_lp_item . " ( ".
+            					"c_id, ".
                                 "lp_id, ".
                                 "item_type, ".
                                 "ref, ".
@@ -488,6 +499,7 @@ class learnpath {
                                 "display_order, ".
                                 "max_time_allowed ".
                             ") VALUES (".
+            					$course_id. ",".
                                 $this->get_id() . ",".
                                 "'" . $type . "',".
                                 "'',".
@@ -586,8 +598,6 @@ class learnpath {
      */
     public function add_lp($course, $name, $description = '', $learnpath = 'guess', $origin = 'zip', $zipname = '', $publicated_on = '', $expired_on = '') {
         global $charset;
-
-        //if ($this->debug > 0) { error_log('New LP - In learnpath::add_lp()', 0); }
         $tbl_lp = Database :: get_course_table(TABLE_LP_MAIN);
         // Check course code exists.
         // Check lp_name doesn't exist, otherwise append something.
@@ -619,6 +629,8 @@ class learnpath {
         } else {
             $expired_on   = Database::escape_string(api_get_utc_datetime($expired_on));
         }
+        
+        $course_id = api_get_course_int_id();
 
         while (Database :: num_rows($res_name)) {
             // There is already one such name, update the current one a bit.
@@ -656,14 +668,13 @@ class learnpath {
                     $row = Database :: fetch_array($res_max);
                     $dsp = $row[0] + 1;
                 }
-                $sql_insert = "INSERT INTO $tbl_lp (lp_type,name,description,path,default_view_mod, default_encoding,display_order,content_maker,content_local,js_lib,session_id, created_on, publicated_on, expired_on) " .
-                              "VALUES ($type,'$name','$description','','embedded','UTF-8','$dsp','Chamilo','local','','".$session_id."', '".api_get_utc_datetime()."' , '".$publicated_on."' , '".$expired_on."')";
+                
+                $sql_insert = "INSERT INTO $tbl_lp (c_id, lp_type,name,description,path,default_view_mod, default_encoding,display_order,content_maker,content_local,js_lib,session_id, created_on, publicated_on, expired_on) " .
+                              "VALUES ($course_id, $type,'$name','$description','','embedded','UTF-8','$dsp','Chamilo','local','','".$session_id."', '".api_get_utc_datetime()."' , '".$publicated_on."' , '".$expired_on."')";
 
-                //if ($this->debug > 2) { error_log('New LP - Inserting new lp '.$sql_insert, 0); }
                 $res_insert = Database::query($sql_insert);
                 $id = Database :: insert_id();
                 if ($id > 0) {
-
                     // Insert into item_property.
                     api_item_property_update(api_get_course_info(), TOOL_LEARNPATH, $id, 'LearnpathAdded', api_get_user_id());
                     return $id;
@@ -1866,11 +1877,12 @@ class learnpath {
      * @param	boolean	Whether to return null if no record was found (true), or 0 (false) (optional, defaults to false)
      * @return	integer	Current progress value as found in the database
      */
-    public function get_db_progress($lp_id, $user_id, $mode = '%', $course_db = '', $sincere = false,$session_id = 0) {
+    public function get_db_progress($lp_id, $user_id, $mode = '%', $course_code = '', $sincere = false,$session_id = 0) {
         //if ($this->debug > 0) { error_log('New LP - In learnpath::get_db_progress()', 0); }
         $session_id = intval($session_id);
+        $course_info = api_get_course_info($course_code);
         $session_condition = api_get_session_condition($session_id);
-        $table = Database :: get_course_table(TABLE_LP_VIEW, $course_db);
+        $table = Database :: get_course_table(TABLE_LP_VIEW);
         $sql = "SELECT * FROM $table WHERE lp_id = $lp_id AND user_id = $user_id $session_condition";
         $res = Database::query($sql);
         $view_id = 0;
@@ -1886,28 +1898,34 @@ class learnpath {
         if (empty ($progress)) {
             $progress = '0';
         }
+        
+        $course_id = $course_info['real_id'];
+        
         if ($mode == '%') {
             return $progress . '%';
         } else {
             // Get the number of items completed and the number of items total.
-            $tbl = Database :: get_course_table(TABLE_LP_ITEM, $course_db);
-            $sql = "SELECT count(*) FROM $tbl WHERE lp_id = " . $lp_id . "
-                                AND item_type NOT IN('dokeos_chapter','chapter','dir')";
+            $tbl = Database :: get_course_table(TABLE_LP_ITEM);
+            $sql = "SELECT count(*) FROM $tbl 
+            		WHERE c_id = $course_id AND lp_id = " . $lp_id . " AND item_type NOT IN('dokeos_chapter','chapter','dir')";
             $res = Database::query($sql);
             $row = Database :: fetch_array($res);
             $total = $row[0];
-            $tbl_item_view = Database :: get_course_table(TABLE_LP_ITEM_VIEW, $course_db);
-            $tbl_item = Database :: get_course_table(TABLE_LP_ITEM, $course_db);
-
+            $tbl_item_view = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
+            $tbl_item = Database :: get_course_table(TABLE_LP_ITEM);
+            
             //$sql = "SELECT count(distinct(lp_item_id)) FROM $tbl WHERE lp_view_id = ".$view_id." AND status IN ('passed','completed','succeeded')";
             // Trying as also counting browsed and failed items.
             $sql = "SELECT count(distinct(lp_item_id))
-                                FROM $tbl_item_view as item_view
-                                INNER JOIN $tbl_item as item
-                                    ON item.id = item_view.lp_item_id
-                                    AND item_type NOT IN('dokeos_chapter','chapter','dir')
-                                WHERE lp_view_id = " . $view_id . "
-                                AND status IN ('passed','completed','succeeded','browsed','failed')"; //echo '<br />';
+                    FROM $tbl_item_view as item_view
+                    INNER JOIN $tbl_item as item
+                    ON item.id = item_view.lp_item_id
+                    AND item_type NOT IN('dokeos_chapter','chapter','dir')
+                    WHERE
+                    	item_view.c_id 	= $course_id AND
+                    	item.c_id 		= $course_id  AND 
+                    	lp_view_id 		= " . $view_id . " AND 
+            			status IN ('passed','completed','succeeded','browsed','failed')"; //echo '<br />';
             $res = Database::query($sql);
             $row = Database :: fetch_array($res);
             $completed = $row[0];
@@ -1929,17 +1947,17 @@ class learnpath {
      * @return string	The mediaplayer HTML
      */
     public function get_mediaplayer($autostart='true') {
-
         global $_course;
+        $tbl_lp_item 		= Database :: get_course_table(TABLE_LP_ITEM);
+        $tbl_lp_item_view 	= Database :: get_course_table(TABLE_LP_ITEM_VIEW);
 
-        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
-        $tbl_lp_item_view = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
-
+        $course_id = api_get_course_int_id();
+        
         // Getting all the information about the item.
-        $sql = "SELECT * FROM " . $tbl_lp_item . " as lp inner join " . $tbl_lp_item_view . " as lp_view on lp.id = lp_view.lp_item_id " .
-                "WHERE lp.id = '" . $_SESSION['oLP']->current . "'";
+        $sql = "SELECT * FROM " . $tbl_lp_item . " as lp INNER  JOIN " . $tbl_lp_item_view . " as lp_view on lp.id = lp_view.lp_item_id " .
+                "WHERE lp.id = '" . $_SESSION['oLP']->current . "' AND lp.c_id = $course_id AND lp_view.c_id = $course_id";
         $result = Database::query($sql);
-        $row = Database::fetch_assoc($result);
+        $row 	= Database::fetch_assoc($result);
         $output = '';
 
         if (!empty ($row['audio'])) {
@@ -2861,13 +2879,19 @@ class learnpath {
         }
 
         $file = '';
-        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
-        $lp_item_table = Database :: get_course_table(TABLE_LP_ITEM);
-        $lp_item_view_table = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
-        $item_id = Database::escape_string($item_id);
-
-        $sel = "SELECT l.lp_type as ltype, l.path as lpath, li.item_type as litype, li.path as lipath, li.parameters as liparams " .
-               "FROM $lp_table l, $lp_item_table li WHERE li.id = $item_id AND li.lp_id = l.id";
+        $lp_table 			= Database::get_course_table(TABLE_LP_MAIN);
+        $lp_item_table 		= Database::get_course_table(TABLE_LP_ITEM);
+        $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
+        $item_id 			= Database::escape_string($item_id);
+        
+        $course_id = api_get_course_int_id();
+
+        $sel = "SELECT l.lp_type as ltype, l.path as lpath, li.item_type as litype, li.path as lipath, li.parameters as liparams 
+        		FROM $lp_table l, $lp_item_table li 
+        		WHERE 	l.c_id = $course_id AND
+        				li.c_id = $course_id AND 
+        				li.id = $item_id AND 
+        				li.lp_id = l.id";
         if ($this->debug > 2) {
             error_log('New LP - In learnpath::get_link() - selecting item ' . $sel, 0);
         }
@@ -3104,19 +3128,20 @@ class learnpath {
         }
         // When missing $attempt_num, search for a unique lp_view record for this lp and user.
         $lp_view_table = Database :: get_course_table(TABLE_LP_VIEW);
-        $sql = "SELECT id, view_count FROM $lp_view_table " .
-        "WHERE lp_id = " . $this->get_id() . " " .
-        "AND user_id = " . $this->get_user_id() . " " .
-        $search .
-        " ORDER BY view_count DESC";
+        
+        $course_id = api_get_course_int_id();
+        
+        $sql = "SELECT id, view_count FROM $lp_view_table 
+        		WHERE lp_id = " . $this->get_id() ." AND user_id = " . $this->get_user_id() . " " .$search .
+        		" ORDER BY view_count DESC";
         $res = Database::query($sql);
         if (Database :: num_rows($res) > 0) {
             $row = Database :: fetch_array($res);
             $this->lp_view_id = $row['id'];
         } else {
             // There is no database record, create one.
-            $sql = "INSERT INTO $lp_view_table(lp_id,user_id,view_count)" .
-            "VALUES (" . $this->get_id() . "," . $this->get_user_id() . ",1)";
+            $sql = "INSERT INTO $lp_view_table (c_id, lp_id,user_id,view_count) VALUES 
+            		($course_id, " . $this->get_id() . "," . $this->get_user_id() . ",1)";
             $res = Database::query($sql);
             $id = Database :: insert_id();
             $this->lp_view_id = $id;
@@ -3565,6 +3590,9 @@ class learnpath {
         $session_condition = api_get_session_condition($session_id);
 
         $tbl_tool = Database :: get_course_table(TABLE_TOOL_LIST);
+        
+        $course_id = api_get_course_int_id();
+        
         $link = 'newscorm/lp_controller.php?action=view&lp_id=' . $lp_id.'&id_session='.$session_id;
         $sql = "SELECT * FROM $tbl_tool where name='$name' and image='scormbuilder.gif' and link LIKE '$link%' $session_condition";
         $result = Database::query($sql);
@@ -3574,7 +3602,8 @@ class learnpath {
         if (($set_visibility == 'i') && ($num > 0)) {
             $sql = "DELETE FROM $tbl_tool WHERE (name='$name' and image='scormbuilder.gif' and link LIKE '$link%' $session_condition)";
         } elseif (($set_visibility == 'v') && ($num == 0)) {
-            $sql = "INSERT INTO $tbl_tool (name, link, image, visibility, admin, address, added_tool, session_id) VALUES ('$name','$link','scormbuilder.gif','$v','0','pastillegris.gif',0, $session_id)";            
+            $sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES 
+            	    ($course_id, '$name','$link','scormbuilder.gif','$v','0','pastillegris.gif',0, $session_id)";            
         } else {            
             // Parameter and database incompatible, do nothing.
         }
@@ -3597,9 +3626,10 @@ class learnpath {
         // Call autosave method to save the current progress.
         //$this->index = 0;
         $session_id = api_get_session_id();
+        $course_id = api_get_course_int_id();
         $lp_view_table = Database :: get_course_table(TABLE_LP_VIEW);
-        $sql = "INSERT INTO $lp_view_table (lp_id, user_id, view_count, session_id) " .
-        "VALUES (" . $this->lp_id . "," . $this->get_user_id() . "," . ($this->attempt + 1) . ", $session_id)";
+        $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) " .
+        	   "VALUES ($course_id, " . $this->lp_id . "," . $this->get_user_id() . "," . ($this->attempt + 1) . ", $session_id)";
         if ($this->debug > 2) {
             error_log('New LP - Inserting new lp_view for restart: ' . $sql, 0);
         }
@@ -5175,6 +5205,8 @@ class learnpath {
      */
     public function display_edit_item($item_id) {
         global $_course; // It will disappear.
+        $course_id = api_get_course_int_id();
+        
         $return = '';
         if (is_numeric($item_id)) {
             $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
@@ -5199,7 +5231,9 @@ class learnpath {
                     $sql_step = " SELECT lp.*, doc.path as dir
                                     FROM " . $tbl_lp_item . " as lp
                                     LEFT JOIN " . $tbl_doc . " as doc ON doc.id = lp.path
-                                    WHERE lp.id = " . Database :: escape_string($item_id);
+                                    WHERE 	lp.c_id = $course_id AND 
+                    						doc.c_id = $course_id AND 
+                    						lp.id = " . Database :: escape_string($item_id);
                     $res_step = Database::query($sql_step);
                     $row_step = Database :: fetch_array($res_step);
                     $return .= $this->display_manipulate($item_id, $row['item_type']);

+ 9 - 9
main/newscorm/learnpathItem.class.php

@@ -72,6 +72,7 @@ class learnpathItem {
 		// Get items table.
 		if (self::debug > 0) { error_log('New LP - In learnpathItem constructor: '.$db_id.','.$user_id, 0); }
 		$items_table = Database::get_course_table(TABLE_LP_ITEM, $course_db);
+		$this->course_id = api_get_course_int_id();
 		$id = (int) $db_id;
 		$sql = "SELECT * FROM $items_table WHERE id = $id";
 		//error_log('New LP - Creating item object from DB: '.$sql, 0);
@@ -2130,9 +2131,9 @@ class learnpathItem {
 		 			}else{
 		 				// Insert new one.
 		 				$ivai_sql = "INSERT INTO $iva_table " .
-		 						"(lp_iv_id, order_id, objective_id, status, score_raw, score_min, score_max )" .
+		 						"(c_id, lp_iv_id, order_id, objective_id, status, score_raw, score_min, score_max )" .
 		 						"VALUES" .
-		 						"(".$lp_iv_id.", ".$index.",'".Database::escape_string($objective[0])."','".Database::escape_string($objective[1])."'," .
+		 						"($this->course_id, ".$lp_iv_id.", ".$index.",'".Database::escape_string($objective[0])."','".Database::escape_string($objective[1])."'," .
 		 						"'".Database::escape_string($objective[2])."','".Database::escape_string($objective[4])."','".Database::escape_string($objective[3])."')";
 		 				$ivai_res = Database::query($ivai_sql);
 		 				//error_log($ivai_sql);
@@ -2184,7 +2185,7 @@ class learnpathItem {
 	  			$this->restart();
 
 	  			$sql = "INSERT INTO $item_view_table " .
-			 			"(total_time, " .
+			 			"(c_id, total_time, " .
 			 			"start_time, " .
 			 			"score, " .
 			 			"status, " .
@@ -2196,7 +2197,7 @@ class learnpathItem {
 			 			//"max_time_allowed," .
 			 			"lesson_location)" .
 			 			"VALUES" .
-			 			"(".$this->get_total_time()."," .
+			 			"($this->course_id, ".$this->get_total_time()."," .
 			 			"".$this->current_start_time."," .
 			 			"".$this->get_score()."," .
 			 			"'".$this->get_status(false)."'," .
@@ -2230,7 +2231,7 @@ class learnpathItem {
 		 		}*/
 
 			 	$sql = "INSERT INTO $item_view_table " .
-			 			"(total_time, " .
+			 			"(c_id, total_time, " .
 			 			"start_time, " .
 			 			"score, " .
 			 			"status, " .
@@ -2242,7 +2243,7 @@ class learnpathItem {
 			 			//"max_time_allowed," .
 			 			"lesson_location)" .
 			 			"VALUES" .
-			 			"(".$this->get_total_time()."," .
+			 			"($this->course_id, ".$this->get_total_time()."," .
 			 			"".$this->current_start_time."," .
 			 			"".$this->get_score()."," .
 			 			"'".$this->get_status(false)."'," .
@@ -2425,12 +2426,11 @@ class learnpathItem {
 			 				$ivau_res = Database::query($ivau_sql);
 			 			} else {
 			 				// Insert new one.
-			 				$ivai_sql = "INSERT INTO $iva_table " .
-			 						"(order_id, lp_iv_id, interaction_id, interaction_type, " .
+			 				$ivai_sql = "INSERT INTO $iva_table (c_id, order_id, lp_iv_id, interaction_id, interaction_type, " .
 			 						"weighting, completion_time, correct_responses, " .
 			 						"student_response, result, latency)" .
 			 						"VALUES" .
-			 						"(".$index.",".$lp_iv_id.",'".Database::escape_string($interaction[0])."','".Database::escape_string($interaction[1])."'," .
+			 						"($this->course_id, ".$index.",".$lp_iv_id.",'".Database::escape_string($interaction[0])."','".Database::escape_string($interaction[1])."'," .
 			 						"'".Database::escape_string($interaction[3])."','".Database::escape_string($interaction[2])."','".Database::escape_string($correct_resp)."'," .
 			 						"'".Database::escape_string($interaction[5])."','".Database::escape_string($interaction[6])."','".Database::escape_string($interaction[7])."'" .
 			 						")";

+ 19 - 23
main/newscorm/learnpath_functions.inc.php

@@ -64,8 +64,8 @@ function deleteitem($id) {
  */
 function deletemodule($parent_item_id) {
     global $learnpath_id;
-    $tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
-    $tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+    $tbl_learnpath_item 	= Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+    $tbl_learnpath_chapter 	= Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
 
     // Added for multi-level behaviour - slightly recursive.
     $sql = "SELECT * FROM $tbl_learnpath_chapter WHERE lp_id=$learnpath_id";
@@ -80,7 +80,8 @@ function deletemodule($parent_item_id) {
     }
 
     // Get this chapter's display order.
-    $sql = "SELECT display_order, parent_item_id FROM $tbl_learnpath_chapter WHERE id=$parent_item_id and lp_id=$learnpath_id";
+    $sql = "SELECT display_order, parent_item_id FROM $tbl_learnpath_chapter 
+    		WHERE id=$parent_item_id and lp_id=$learnpath_id";
     $result = Database::query($sql);
     if (Database::num_rows($result) == 0) {
         return false;
@@ -122,7 +123,7 @@ function deletepath($path_id) {
 
     //@TODO check how this function is used before uncommenting the following
     //also delete all elements inside that path
-    $sql = "SELECT * FROM $tbl_learnpath_chapter WHERE lp_id=$path_id";
+    $sql = "SELECT * FROM $tbl_learnpath_chapter WHERE lp_id = $path_id";
     $result = Database::query($sql);
     while ($row = Database::fetch_array($result)) {
         deletemodule($row['id']);
@@ -216,7 +217,7 @@ function movemodule($direction, $id) {
     }
 
     // Select all chapters of first level (parent_item_id = 0).
-    $sql = "SELECT * FROM $tbl_learnpath_chapter where (lp_id=$learnpath_id AND parent_item_id = 0) ORDER BY display_order $sortDirection";
+    $sql = "SELECT * FROM $tbl_learnpath_chapter WHERE (lp_id=$learnpath_id AND parent_item_id = 0) ORDER BY display_order $sortDirection";
     $result = Database::query($sql);
     $previousrow = '';
 
@@ -260,13 +261,12 @@ function movemodule($direction, $id) {
  * @note This function is currently never used!
  */
 function insert_item($type = 'item', $name, $chapter_description = '', $parent_id = 0, $learnpath_id = 0, $params = null) {
-    $tbl_learnpath_chapter = Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
-    $tbl_learnpath_item = Database :: get_course_table(TABLE_LEARNPATH_ITEM);
+    $tbl_learnpath_chapter	= Database :: get_course_table(TABLE_LEARNPATH_CHAPTER);
+    $tbl_learnpath_item 	= Database :: get_course_table(TABLE_LEARNPATH_ITEM);
 
     // Getting the last order number from the chapters table, in this learnpath, for the parent chapter given.
     $sql = "SELECT * FROM $tbl_learnpath_chapter
-            WHERE lp_id=$learnpath_id
-            AND parent_item_id = $parent_id
+            WHERE lp_id=$learnpath_id  AND parent_item_id = $parent_id
             ORDER BY display_order DESC";
     $result = Database::query($sql);
     $row = Database::fetch_array($result);
@@ -274,17 +274,17 @@ function insert_item($type = 'item', $name, $chapter_description = '', $parent_i
 
     // Getting the last order number of the items.
     $sql = "SELECT * FROM $tbl_learnpath_item
-            AND parent_item_id = $parent_id
+            WHERE parent_item_id = $parent_id
             ORDER BY display_order DESC";
     $result = Database::query($sql);
     $row = Database::fetch_array($result);
     $last_item_order = $row['display_order'];
     $new_order = max($last_chapter_order, $last_item_order) + 1;
-
+	$course_id = api_get_course_int_id();
     if ($type === 'chapter') {
-        $sql = "INSERT INTO $tbl_learnpath_chapter
-                        (lp_id, chapter_name, chapter_description, display_order)
-                        VALUES ('".domesticate($learnpath_id)."',
+        $sql = "INSERT INTO $tbl_learnpath_chapter (c_id, lp_id, chapter_name, chapter_description, display_order)
+				VALUES ( $course_id, 
+						'".domesticate($learnpath_id)."',
                         '".domesticate(htmlspecialchars($name))."',
                         '".domesticate(htmlspecialchars($chapter_description))."',
                         $new_order )";
@@ -294,11 +294,8 @@ function insert_item($type = 'item', $name, $chapter_description = '', $parent_i
         }
         $id = Database :: insert_id();
     } elseif ($type === 'item') {
-        $sql = "INSERT INTO $tbl_learnpath_item
-                        (parent_item_id, item_type, display_order)
-                        VALUES ('".domesticate($parent_id)."',
-                        '".domesticate(htmlspecialchars($type))."',
-                        $new_order )";
+        $sql = "INSERT INTO $tbl_learnpath_item (c_id, parent_item_id, item_type, display_order) VALUES 
+        		($course_id, '".domesticate($parent_id)."','".domesticate(htmlspecialchars($type))."', $new_order )";
         $result = Database::query($sql);
         if ($result === false) {
             return false;
@@ -544,7 +541,7 @@ function display_all_learnpath() {
     $result = Database::query($sql);
     $i = 1;
     $num_modules = Database::num_rows($result);
-
+    
     while ($row = Database::fetch_array($result)) {
         // Other grey color : #E6E6E6
         echo "<tr><td bgcolor=\"$color2\" width=400><b>&nbsp;";
@@ -557,11 +554,11 @@ function display_all_learnpath() {
             echo "<td bgcolor=\"$color2\" align=center><a href='".api_get_self()."?action=editpath&id=".$row['lp_id']."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/edit.gif\" border=\"0\" title=\"$lang_edit_learnpath\"></a></td>";
             echo "<td bgcolor=\"$color2\" align=center><a href='".api_get_self()."?action=deletepath&id=".$row['lp_id']."'&SQMSESSID=36812c2dea7d8d6e708d5e6a2f09b0b9><img src=\"../img/delete.gif\" border=\"0\" title=\"$lang_delete_learnpath\" onclick=\"javascript: return confirmation('".$row['learnpath_name']."');\"></a></td>";
             $id = $row['lp_id'];
-            $sql2 = "SELECT * FROM $tbl_learnpath_main where lp_id=$id";
+            $sql2 = "SELECT * FROM $tbl_learnpath_main WHERE lp_id=$id";
             $result2 = Database::query($sql2);
             $row2 = Database::fetch_array($result2);
             $name = $row2['learnpath_name'];
-            $sql3 = "SELECT * FROM $tbl_tool where (name=\"$name\" and image='scormbuilder.gif')";
+            $sql3 = "SELECT * FROM $tbl_tool WHERE (name=\"$name\" AND image='scormbuilder.gif')";
             $result3 = Database::query($sql3);
             $row3 = Database::fetch_array($result3);
             if (($row3['visibility']) == '1') {
@@ -590,7 +587,6 @@ function display_learnpath_items($categoryid) {
     $result_items = Database::query($sql_items);
     $number_items = Database::num_rows($result_items);
     $i = 1;
-    //error_log('Selected item under '.$categoryid, 0);
 
     while ($row_items = Database::fetch_array($result_items)) {
         echo "<tr><td colspan='2' valign='top'>";

+ 1 - 0
main/newscorm/lp_content.php

@@ -77,6 +77,7 @@ if ($dokeos_chapter) {
             break;
     }
 }
+
 if ($debug > 0) { error_log('New lp - In lp_content.php - File url is '.$src, 0); }
 $_SESSION['oLP']->set_previous_item($lp_item_id);
 

+ 26 - 11
main/newscorm/lp_stats.php

@@ -83,11 +83,14 @@ $output .= '<tr><td><table border="0" class="data_table"><tr>'.
 // the database table.
 
 $course_info            = api_get_course_info($course_code);
-$TBL_LP_ITEM            = Database :: get_course_table(TABLE_LP_ITEM, $course_info['db_name']);
-$TBL_LP_ITEM_VIEW       = Database :: get_course_table(TABLE_LP_ITEM_VIEW, $course_info['db_name']);
-$TBL_LP_VIEW            = Database :: get_course_table(TABLE_LP_VIEW, $course_info['db_name']);
-$tbl_quiz_questions     = Database :: get_course_table(TABLE_QUIZ_QUESTION, $course_info['db_name']);
-$TBL_QUIZ               = Database :: get_course_table(TABLE_QUIZ_TEST, $course_info['db_name']);
+
+$course_id = $course_info['real_id']; 
+
+$TBL_LP_ITEM            = Database :: get_course_table(TABLE_LP_ITEM);
+$TBL_LP_ITEM_VIEW       = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
+$TBL_LP_VIEW            = Database :: get_course_table(TABLE_LP_VIEW);
+$tbl_quiz_questions     = Database :: get_course_table(TABLE_QUIZ_QUESTION);
+$TBL_QUIZ               = Database :: get_course_table(TABLE_QUIZ_TEST);
 $tbl_stats_exercices    = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
 $tbl_stats_attempts     = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
@@ -127,9 +130,11 @@ if (isset($_GET['lp_id']) && isset($_GET['my_lp_id'])) {
 
     if (Database::num_rows($res_path) > 0) {
         if ($origin != 'tracking') {
-            $sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . (int)$row_path['path'] . '"   AND status <> "incomplete"  AND exe_user_id="' . api_get_user_id() . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '"  AND session_id = '.$session_id.' ORDER BY exe_date';
+            $sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' 
+            				 WHERE exe_exo_id="' . (int)$row_path['path'] . '"   AND status <> "incomplete"  AND exe_user_id="' . api_get_user_id() . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '"  AND session_id = '.$session_id.' ORDER BY exe_date';
         } else {
-            $sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . (int)$row_path['path'] . '"   AND status <> "incomplete"  AND exe_user_id="' . $student_id . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '"  AND session_id = '.$session_id.' ORDER BY exe_date';
+            $sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' 
+            				 WHERE exe_exo_id="' . (int)$row_path['path'] . '"   AND status <> "incomplete"  AND exe_user_id="' . $student_id . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '"  AND session_id = '.$session_id.' ORDER BY exe_date';
         }
     }
 }
@@ -154,7 +159,11 @@ if (is_array($list) && count($list) > 0) {
             " i.item_type as item_type, iv.view_count as iv_view_count, " .
             " iv.id as iv_id, path as path" .
             " FROM $TBL_LP_ITEM as i, $TBL_LP_ITEM_VIEW as iv, $TBL_LP_VIEW as v" .
-            " WHERE i.id = iv.lp_item_id " .
+            " WHERE
+            	i.c_id = $course_id AND
+            	iv.c_id = $course_id AND
+            	v.c_id = $course_id AND            	 
+            	i.id = iv.lp_item_id " .
             " AND i.id = $my_item_id " .
             " AND iv.lp_view_id = v.id " .
             " AND i.lp_id = $lp_id " .
@@ -170,7 +179,11 @@ if (is_array($list) && count($list) > 0) {
             " i.item_type as item_type, iv.view_count as iv_view_count, " .
             " iv.id as iv_id, path as path " .
             " FROM $TBL_LP_ITEM as i, $TBL_LP_ITEM_VIEW as iv, $TBL_LP_VIEW as v " .
-            " WHERE i.id = iv.lp_item_id " .
+            " WHERE i.id = iv.lp_item_id
+            	i.c_id = $course_id AND
+            	iv.c_id = $course_id AND
+            	v.c_id = $course_id AND        
+            " .
             " AND i.id = $my_item_id " .
             " AND iv.lp_view_id = v.id " .
             " AND i.lp_id = $lp_id " .
@@ -475,8 +488,10 @@ if (is_array($list) && count($list) > 0) {
                         //echo $subtotal_time ;
                         //$time = learnpathItem :: get_scorm_time('js', $subtotal_time);
                         // Selecting the max score from an attempt.
-                        $sql = "SELECT SUM(t.ponderation) as maxscore from ( SELECT distinct question_id, marks,ponderation FROM $tbl_stats_attempts as at " .
-                              "INNER JOIN  $tbl_quiz_questions as q  on(q.id = at.question_id) where exe_id ='$id_last_attempt' ) as t";
+                        $sql = "SELECT SUM(t.ponderation) as maxscore FROM ( 
+                        			SELECT distinct question_id, marks,ponderation FROM $tbl_stats_attempts as at INNER JOIN  $tbl_quiz_questions as q 
+                        			ON(q.id = at.question_id) 
+                        			WHERE exe_id ='$id_last_attempt' ) as t";
 
                         $result = Database::query($sql);
                         $row_max_score = Database :: fetch_array($result);

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

@@ -182,12 +182,14 @@ function file_or_folder($filefolder) {
 function store_resources($source_type, $source_id) {
     global $_course;
     $resource_table = Database::get_course_table(TABLE_LINKED_RESOURCES);
-
+    $course_id = api_get_course_int_id();
+    
     $addedresource = $_SESSION['addedresource'];
     $addedresourceid = $_SESSION['addedresourceid'];
     if ($_SESSION['addedresource']) {
         foreach ($addedresource as $resource_type) {
-            $sql="INSERT INTO $resource_table (source_type, source_id, resource_type, resource_id) VALUES ('$source_type', '$source_id', '$resource_type', '".$addedresourceid[key($addedresource)]."')";
+            $sql="INSERT INTO $resource_table (c_id, source_type, source_id, resource_type, resource_id) VALUES 
+            ($course_id, '$source_type', '$source_id', '$resource_type', '".$addedresourceid[key($addedresource)]."')";
             Database::query($sql);
             $i=key($addedresource);
             next($addedresource);

+ 9 - 7
main/newscorm/resourcelinker.php

@@ -83,6 +83,8 @@ if ($from_learnpath == 'yes') {
     unset ($_SESSION['addedresourceassigned']);
 }
 
+$course_id = api_get_course_int_id();
+
 // Process a new chapter?
 if (!empty ($_POST['add_chapter']) && !empty ($_POST['title'])) {
     $title = $_POST['title'];
@@ -110,8 +112,8 @@ if (!empty ($_POST['add_chapter']) && !empty ($_POST['title'])) {
     }
     $order = $lastorder_item + 1;
 
-    $sql = "INSERT INTO $tbl_lp_item "."(lp_id,item_type,title,parent_item_id,previous_item_id, next_item_id, display_order) " .
-            "VALUES "."($learnpath_id,'dokeos_chapter','$title', $chapter_id, $previous, 0, $order )";
+    $sql = "INSERT INTO $tbl_lp_item "."(c_id, lp_id,item_type,title,parent_item_id,previous_item_id, next_item_id, display_order) " .
+            "VALUES "."($course_id, $learnpath_id,'dokeos_chapter','$title', $chapter_id, $previous, 0, $order )";
     //error_log('New LP - Inserting new resource: '.$sql, 0);
     $res = Database::query($sql);
     $my_id = Database::insert_id($res);
@@ -139,7 +141,7 @@ if (!empty ($_POST['external_link_submit'])) {
                 $external_link = 'http://'.$external_link;
             }
 
-            $sql = "INSERT INTO $link_table (url, title, category_id) VALUES ('$external_link','$external_link','$add_2_links')";
+            $sql = "INSERT INTO $link_table (c_id, url, title, category_id) VALUES ($course_id, '$external_link','$external_link','$add_2_links')";
             $result = Database::query($sql);
             $addedresource[] = "Link";
             $addedresourceid[] = Database::insert_id();
@@ -199,8 +201,8 @@ if ($add) {
             // In the case we added a chapter, add this into the chapters list with the correct parent_id.
             if ($addedresource_item == 'Chap') {
                 $sql = "INSERT INTO $tbl_lp_item " .
-                        "(lp_id,item_type,title,parent_item_id,previous_item_id,next_item_id,display_order) " .
-                        "VALUES (".$learnpath_id.",'dokeos_chapter','".$learnpath_chapter_name."',".$chapter_id.",$previous,0,".$lastorder.")";
+                        "(c_id, lp_id,item_type,title,parent_item_id,previous_item_id,next_item_id,display_order) " .
+                        "VALUES ($course_id, ".$learnpath_id.",'dokeos_chapter','".$learnpath_chapter_name."',".$chapter_id.",$previous,0,".$lastorder.")";
                 //error_log('New LP - Inserting new resource: '.$sql, 0);
                 $res = Database::query($sql);
                 $my_id = Database::insert_id($res);
@@ -293,8 +295,8 @@ if ($add) {
                         break;
 
                 }
-                $sql = "INSERT INTO $tbl_lp_item (lp_id, title, parent_item_id, item_type, ref, previous_item_id, next_item_id, display_order) " .
-                        "VALUES ($learnpath_id, '$title','$chapter_id', '$addedresource_item','$addedresourceid[$i]',$previous,0,'".$lastorder."')";
+                $sql = "INSERT INTO $tbl_lp_item (c_id, lp_id, title, parent_item_id, item_type, ref, previous_item_id, next_item_id, display_order) " .
+                        "VALUES ($course_id, $learnpath_id, '$title','$chapter_id', '$addedresource_item','$addedresourceid[$i]',$previous,0,'".$lastorder."')";
                 //error_log('New LP - Inserting new resource: '.$sql, 0);
                 $result = Database::query($sql);
                 $my_id = Database::insert_id($result);

Some files were not shown because too many files changed in this diff