Julio Montoya há 13 anos atrás
pai
commit
fce8990d72
100 ficheiros alterados com 2921 adições e 2151 exclusões
  1. 0 2
      main/admin/access_url_edit.php
  2. 0 1
      main/admin/archive_cleanup.php
  3. 0 7
      main/admin/calendar_ical_export.php
  4. 17 17
      main/admin/course_add.php
  5. 5 4
      main/admin/course_edit.php
  6. 20 24
      main/admin/course_information.php
  7. 21 17
      main/admin/course_list.php
  8. 1 1
      main/admin/session_course_user.php
  9. 3 16
      main/admin/settings.lib.php
  10. 166 38
      main/admin/settings.php
  11. 18 11
      main/admin/special_exports.php
  12. 9 8
      main/admin/user_add.php
  13. 11 9
      main/admin/user_edit.php
  14. 31 29
      main/admin/user_list.php
  15. 56 49
      main/admin/user_move_stats.php
  16. 53 37
      main/announcements/announcements.inc.php
  17. 63 80
      main/announcements/announcements.php
  18. 4 2
      main/announcements/download.php
  19. 2 5
      main/blog/blog.php
  20. 2 4
      main/blog/blog_admin.php
  21. 14 14
      main/calendar/agenda.inc.php
  22. 26 14
      main/calendar/agenda.lib.php
  23. 21 13
      main/calendar/agenda_js.php
  24. 3 3
      main/calendar/myagenda.inc.php
  25. 5 3
      main/chat/chat_chat.php
  26. 1 1
      main/chat/chat_hidden.php
  27. 3 2
      main/chat/chat_message.php
  28. 12 3
      main/chat/chat_whoisonline.php
  29. 1 5
      main/course_description/add.php
  30. 1 1
      main/course_description/course_description_controller.php
  31. 3 2
      main/course_home/course_home.php
  32. 32 27
      main/course_info/infocours.php
  33. 213 170
      main/coursecopy/classes/CourseBuilder.class.php
  34. 95 102
      main/coursecopy/classes/CourseRecycler.class.php
  35. 262 221
      main/coursecopy/classes/CourseRestorer.class.php
  36. 15 10
      main/coursecopy/classes/CourseSelectForm.class.php
  37. 11 13
      main/create_course/add_course.php
  38. 47 22
      main/css/base.css
  39. 1 3
      main/css/base_chamilo.css
  40. 2 2
      main/document/create_document.php
  41. 3 4
      main/document/document.php
  42. 13 9
      main/document/downloadfolder.inc.php
  43. 41 30
      main/dropbox/dropbox_class.inc.php
  44. 12 9
      main/dropbox/dropbox_functions.inc.php
  45. 1 1
      main/exercice/addlimits.php
  46. 5 8
      main/exercice/admin.php
  47. 10 12
      main/exercice/answer.class.php
  48. 1 1
      main/exercice/answer_admin.inc.php
  49. 1 1
      main/exercice/exercice.php
  50. 20 19
      main/exercice/exercise.class.php
  51. 1 1
      main/exercice/exercise_show.php
  52. 1 1
      main/exercice/mark_free_answer.php
  53. 1 1
      main/exercice/overview.php
  54. 37 31
      main/exercice/question.class.php
  55. 4 6
      main/exercice/question_list_admin.inc.php
  56. 2 2
      main/exercice/result.php
  57. 122 90
      main/forum/forumfunction.inc.php
  58. 1 1
      main/forum/index.php
  59. 5 7
      main/forum/viewforum.php
  60. 1 1
      main/forum/viewforumcategory.php
  61. 2 8
      main/glossary/index.php
  62. 5 6
      main/gradebook/gradebook.php
  63. 12 2
      main/gradebook/gradebook_add_cat.php
  64. 5 0
      main/gradebook/gradebook_add_eval.php
  65. 25 36
      main/gradebook/gradebook_add_link.php
  66. 17 35
      main/gradebook/gradebook_edit_all.php
  67. 14 18
      main/gradebook/gradebook_edit_link.php
  68. 19 15
      main/gradebook/gradebook_result.class.php
  69. 84 40
      main/gradebook/index.php
  70. 8 14
      main/gradebook/lib/be/attendancelink.class.php
  71. 10 11
      main/gradebook/lib/be/category.class.php
  72. 1 5
      main/gradebook/lib/be/dropboxlink.class.php
  73. 1 0
      main/gradebook/lib/be/evaluation.class.php
  74. 5 14
      main/gradebook/lib/be/exerciselink.class.php
  75. 16 8
      main/gradebook/lib/be/forumthreadlink.class.php
  76. 10 21
      main/gradebook/lib/be/learnpathlink.class.php
  77. 13 6
      main/gradebook/lib/be/studentpublicationlink.class.php
  78. 13 16
      main/gradebook/lib/be/surveylink.class.php
  79. 39 9
      main/gradebook/lib/fe/catform.class.php
  80. 211 12
      main/gradebook/lib/fe/displaygradebook.php
  81. 29 5
      main/gradebook/lib/fe/evalform.class.php
  82. 125 26
      main/gradebook/lib/fe/gradebooktable.class.php
  83. 22 15
      main/gradebook/lib/fe/linkaddeditform.class.php
  84. 5 9
      main/gradebook/lib/fe/linkform.class.php
  85. 7 8
      main/gradebook/lib/gradebook_data_generator.class.php
  86. 27 7
      main/gradebook/lib/gradebook_functions.inc.php
  87. 1 1
      main/gradebook/lib/scoredisplay.class.php
  88. 3 12
      main/inc/ajax/exercise.ajax.php
  89. 9 16
      main/inc/ajax/social.ajax.php
  90. 2 1
      main/inc/introductionSection.inc.php
  91. 179 147
      main/inc/lib/add_course.lib.inc.php
  92. 43 17
      main/inc/lib/attendance.lib.php
  93. 1 1
      main/inc/lib/banner.lib.php
  94. 235 258
      main/inc/lib/blog.lib.php
  95. 39 54
      main/inc/lib/course.lib.php
  96. 38 32
      main/inc/lib/course_description.lib.php
  97. 39 14
      main/inc/lib/course_home.lib.php
  98. 4 0
      main/inc/lib/database.constants.inc.php
  99. 49 9
      main/inc/lib/database.lib.php
  100. 22 16
      main/inc/lib/display.lib.php

+ 0 - 2
main/admin/access_url_edit.php

@@ -17,8 +17,6 @@ if (!api_get_multiple_access_url()) {
 	exit;
 }
 
-require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-require_once api_get_path(LIBRARY_PATH).'security.lib.php';
 require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
 
 // Create the form

+ 0 - 1
main/admin/archive_cleanup.php

@@ -11,7 +11,6 @@ $cidReset = true;
 
 // including some necessary files
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;

+ 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();

+ 17 - 17
main/admin/course_add.php

@@ -149,17 +149,17 @@ if ($form->validate()) {
     }
     $keys = define_course_keys($code, '', $_configuration['db_prefix']);
     if (count($keys)) {
-        $current_course_code = $keys['currentCourseCode'];
-        $current_course_id = $keys['currentCourseId'];
-        $current_course_db_name = $keys['currentCourseDbName'];
+        $current_course_code 		= $keys['currentCourseCode'];
+        $current_course_id 			= $keys['currentCourseId'];                
+        $current_course_repository 	= $keys['currentCourseRepository'];
+        $expiration_date 			= time() + $firstExpirationDelay;
         
-        $current_course_repository = $keys['currentCourseRepository'];
-        $expiration_date = time() + $firstExpirationDelay;
         prepare_course_repository($current_course_repository, $current_course_id);
-        update_Db_course($current_course_db_name);
-        $pictures_array = fill_course_repository($current_course_repository, $exemplary_content);
-        fill_Db_course($current_course_db_name, $current_course_repository, $course_language, $pictures_array, $exemplary_content);
-        register_course($current_course_id, $current_course_code, $current_course_repository, $current_course_db_name, $tutor_name, $category, $title, $course_language, $teacher_id, $expiration_date, $course_teachers);
+        //update_Db_course($current_course_db_name);
+        $pictures_array = fill_course_repository($current_course_repository, $exemplary_content);        
+        $course_id = register_course($current_course_id, $current_course_code, $current_course_repository, '', $tutor_name, $category, $title, $course_language, $teacher_id, $expiration_date, $course_teachers);
+        fill_Db_course($course_id, $current_course_repository, $course_language, $pictures_array, $exemplary_content);
+        
         $sql = "UPDATE $table_course SET disk_quota = '".$disk_quota."', visibility = '".Database::escape_string($course['visibility'])."', subscribe = '".Database::escape_string($course['subscribe'])."', unsubscribe='".Database::escape_string($course['unsubscribe'])."' WHERE code = '".$current_course_id."'";
         Database::query($sql);
         header('Location: course_list.php');
@@ -167,12 +167,12 @@ if ($form->validate()) {
     }
 }
 
-// The header.
-Display::display_header($tool_name);
-
 // Display the form.
-$form->display();
-
-/* FOOTER */
-
-Display :: display_footer();
+$content = $form->return_form();
+
+$tpl = new Template($tool_name);
+$tpl->assign('actions', $actions);
+$tpl->assign('message', $message);
+$tpl->assign('content', $content);
+$template = $tpl->get_template('layout/layout_1_col.tpl');
+$tpl->display($template);

+ 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();

+ 21 - 17
main/admin/course_list.php

@@ -167,6 +167,9 @@ if (isset ($_POST['action'])) {
             break;
     }
 }
+$content = '';
+$message = '';
+$actions = '';
 
 if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
     // Get all course categories
@@ -174,7 +177,7 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
     $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
     $interbreadcrumb[] = array('url' => 'course_list.php', 'name' => get_lang('CourseList'));
     $tool_name = get_lang('SearchACourse');
-    Display :: display_header($tool_name);
+    
     //api_display_tool_title($tool_name);
     $form = new FormValidator('advanced_course_search', 'get');
     $form->addElement('header', '', $tool_name);
@@ -202,19 +205,19 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
     $defaults['keyword_subscribe'] = '%';
     $defaults['keyword_unsubscribe'] = '%';
     $form->setDefaults($defaults);
-    $form->display();
+    $content .= $form->return_form();
 } else {
     $interbreadcrumb[] = array ('url' => 'index.php', "name" => get_lang('PlatformAdmin'));
     $tool_name = get_lang('CourseList');
-    Display :: display_header($tool_name);
+    
     if (isset($_GET['action'])) {
         switch ($_GET['action']) {
             case 'show_msg':
                 if (!empty($_GET['warn'])) {
-                    Display::display_warning_message(urldecode($_GET['warn']));
+                    $message = Display::return_message(urldecode($_GET['warn']), 'warning');
                 }
                 if (!empty($_GET['msg'])) {
-                    Display::display_normal_message(urldecode($_GET['msg']));
+                    $message = Display::return_message(urldecode($_GET['msg']));
                 }
                 break;
             default:
@@ -235,17 +238,15 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
     $form->addElement('style_submit_button', 'submit', get_lang('SearchCourse'), 'class="search"');
     $form->addElement('static', 'search_advanced_link', null, '<a href="course_list.php?search=advanced">'.get_lang('AdvancedSearch').'</a>');
     
-    echo '<div style="float: right; margin-top: 5px; margin-right: 5px;">';    
-    echo '<a href="course_add.php">'.Display::return_icon('new_course.png', get_lang('AddCourse'),'','32').'</a> ';
+    $actions .= '<div style="float: right; margin-top: 5px; margin-right: 5px;">';    
+    $actions .= '<a href="course_add.php">'.Display::return_icon('new_course.png', get_lang('AddCourse'),'','32').'</a> ';
     
     if (api_get_setting('course_validation') == 'true') {    
-        echo '<a href="course_request_review.php">'.Display::return_icon('course_request_pending.png', get_lang('ReviewCourseRequests'),'','32').'</a>';
+        $actions .= '<a href="course_request_review.php">'.Display::return_icon('course_request_pending.png', get_lang('ReviewCourseRequests'),'','32').'</a>';
     }
-    echo '</div>';
-
-    echo '<div class="actions">';
-        $form->display();
-    echo '</div>';
+    $actions .= '</div>';    
+    $actions .= $form->return_form();
+    
     // Create a sortable table with the course data
     $table = new SortableTable('courses', 'get_number_of_courses', 'get_course_data', 2);
     $parameters=array();
@@ -276,9 +277,12 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
     $table->set_header(8, get_lang('Action'), false, 'width="150px"');
     $table->set_column_filter(8, 'modify_filter');
     $table->set_form_actions(array('delete_courses' => get_lang('DeleteCourse')), 'course');
-    $table->display();
+    $content .= $table->return_table();
 }
 
-/* FOOTER */
-
-Display :: display_footer();
+$tpl = new Template($tool_name);
+$tpl->assign('actions', $actions);
+$tpl->assign('message', $message);
+$tpl->assign('content', $content);
+$template = $tpl->get_template('layout/layout_1_col.tpl');
+$tpl->display($template);

+ 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 " .

+ 3 - 16
main/admin/settings.lib.php

@@ -11,20 +11,7 @@
  * @package chamilo.admin
  */
 
-/**
- * The function that retrieves all the possible settings for a certain config setting
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- */
-function get_settings_options($var) {
-    $table_settings_options = Database :: get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
-    $sql = "SELECT * FROM $table_settings_options WHERE variable='$var'";
-    $result = Database::query($sql);
-    while ($row = Database::fetch_array($result)) {
-        $temp_array = array ('value' => $row['value'], 'display_text' => $row['display_text']);
-        $settings_options_array[] = $temp_array;
-    }
-    return $settings_options_array;
-}
+
 
 /**
  * This function allows easy activating and inactivating of plugins
@@ -512,7 +499,7 @@ function handle_search() {
     
     
     
-    $values = get_settings_options('search_enabled');   
+    $values = api_get_settings_options('search_enabled');   
     $form->addElement('header', null, get_lang('SearchEnabledTitle'));    
      
     $group = array ();
@@ -549,7 +536,7 @@ function handle_search() {
         // Search_show_unlinked_results.
         //$form->addElement('header', null, get_lang('SearchShowUnlinkedResultsTitle'));
         //$form->addElement('label', null, get_lang('SearchShowUnlinkedResultsComment'));
-        $values = get_settings_options('search_show_unlinked_results');
+        $values = api_get_settings_options('search_show_unlinked_results');
         $group = array ();
         foreach ($values as $key => $value) {
             $element = & $form->createElement('radio', 'search_show_unlinked_results', '', get_lang($value['display_text']), $value['value']);

+ 166 - 38
main/admin/settings.php

@@ -26,7 +26,6 @@ $cidReset = true;
 
 // Including some necessary library files.
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once api_get_path(LIBRARY_PATH).'dashboard.lib.php';
@@ -63,15 +62,44 @@ if (isset($_GET['delete_watermark'])) {
     $watermark_deleted = PDF::delete_watermark();    
 }
 
+if (isset($_POST['new_model']) && isset($_POST['number_evaluations']) && !empty($_POST['new_model'])) {
+	$count = intval($_POST['number_evaluations']);
+	$string_to_save = '';
+	for ($i = 1; $i<=$count;$i++) {
+		$sum = "+";
+		if ($i == $count) {
+			$sum = "";
+		}
+		//Note: We use rand here because there is a unique index in the settings_options table. The 'variable' and 'value' fields must be unique 
+		$string_to_save .= rand(1, 3).'*X'.$sum;
+	}
+	$string_to_save .= "/".$count;
+	$array_to_save = array();
+	
+	$array_to_save['variable'] 		= 'grading_model';
+	$array_to_save['display_text'] 	= $_POST['new_model'];
+	$array_to_save['value']		 	= $string_to_save;
+	var_dump($array_to_save);
+	$result = api_set_setting_option($array_to_save);
+}
+
+if (isset($_GET['action']) &&  $_GET['action'] == 'delete_grading') {
+	$id = intval($_GET['id']);
+	api_delete_setting_option($id);
+}
+
+
 // Build the form.
 if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', 'stylesheets', 'Search'))) {
     $form = new FormValidator('settings', 'post', 'settings.php?category='.$_GET['category']);
+    
     $renderer = & $form->defaultRenderer();
+    $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}<!-- BEGIN label_2 --><span class="help-block">{label_2}</span><!-- END label_2 --></div></div>');
+    
     /*$renderer->setHeaderTemplate('<div class="sectiontitle">{header}</div>');
     $renderer->setElementTemplate('<div class="sectionvalue">{element}</div><div class="sectioncomment">{label}</div>'."\n");*/
     
     //$renderer->setHeaderTemplate('<div class="sectiontitle">{header}</div>');
-    $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}<!-- BEGIN label_2 --><span class="help-block">{label_2}</span><!-- END label_2 --></div></div>');
     
     $my_category = Database::escape_string($_GET['category']);
 
@@ -109,6 +137,7 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
 
     $default_values = array();
     foreach ($settings as $row) {
+    	
         // Settings to avoid
         $rows_to_avoid = array('gradebook_enable');
         if (in_array($row['variable'], $rows_to_avoid)) { continue; }
@@ -155,7 +184,9 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
                 // There is no else{} statement because we load the default $row['selected_value'] of the main Chamilo site.
             }
         }
-
+		
+          
+        
         switch ($row['type']) {
             case 'textfield':            	
                 if ($row['variable'] == 'account_valid_duration') {
@@ -219,7 +250,7 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
             	}
                 break;
             case 'radio':
-                $values = get_settings_options($row['variable']);
+                $values = api_get_settings_options($row['variable']);
                 $group = array ();
                 if (is_array($values )) {
                     foreach ($values as $key => $value) {
@@ -284,6 +315,69 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
                 $form->addElement('select', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])), call_user_func('select_'.$row['variable']), $hideme);
                 $default_values[$row['variable']] = $row['selected_value'];
                 break;
+
+            case 'custom_gradebook':
+            case 'custom':
+            	$values = api_get_settings_options($row['variable']);
+            	
+            	//$renderer = & $form->defaultRenderer();
+            	//$renderer->setElementTemplate('{label} - {element}<!-- BEGIN label_2 --><span class="help-block">{label_2}</span><!-- END label_2 -->');
+            	
+            	$numbers = array();
+            	for($j=1;$j<=20;$j++) {
+            		$numbers[$j] = $j;
+            	}
+            	
+            	if (!empty($values)) {            		
+            		foreach($values as $option) {
+            			$group = array();
+            			$id = $option['id'];            			            			
+            			$option_id = $row['variable']."[$id]";            			
+            			$group[] = $form->createElement('text', $option_id.'[display_text]', array(get_lang($row['title']), get_lang($row['comment'])),'class="begin_model"');
+            			
+            			$default_values[$option_id.'[display_text]'] = $option['display_text'];
+            			$parts = api_grading_model_functions($option['value'], 'to_array');            			
+            			$denominator = $parts['denominator'];            			
+            			$j = 1;            			
+            			foreach($parts['items'] as $item) {  
+            				$letter = $item['letter'];
+            				$value  = $item['value'];
+            				$group[] =$form->createElement('static','<div>');
+            				$class = 'number';
+            				if ($j == 1) {
+            					$class = 'first_number'; 
+            				}
+            				$group[] = $form->createElement('select', $option_id.'[items]['.$j.']', array('dd'), $numbers, array('class'=>$class));
+            				$sum = ' ';
+            				if ($j != count($parts['items'])) {
+            					$sum = ' + ';
+            				}
+            				//$group[] =$form->createElement('static',' * '.$letter.$sum);
+            				
+            				$default_values[$option_id.'[items]['.$j.']'] = $value;            				
+            				$j++;            				
+            			}
+            			
+            			$group[] = $form->createElement('select', $option_id.'[denominator]', array('/'), $numbers,'class="denominator"');            			
+            			$group[] = $form->createElement('button', "delete", get_lang('Delete'), array('type'=>'button', 'id'=>$id, 'onclick'=>"delete_grading_model('$id');"));
+            			
+            			$default_values[$option_id.'[denominator]'] = $denominator;
+            			$form->addGroup($group, '', get_lang($row['title']), ' ');
+            		}     		
+            	}
+            	
+            	//New Grading Model form
+            	$group = array();
+            	
+            	$group[] = $form->createElement('text',   'new_model', array(get_lang('AddNewModel')));            	
+            	$group[] = $form->createElement('select', 'number_evaluations', array(''), $numbers,''); 
+            	
+            	$form->addGroup($group, '', get_lang('AddNewModel'), "&nbsp;&nbsp;".get_lang('NumberOfSubEvalidations')."&nbsp;");
+            	
+            	$form->addElement('style_submit_button', null, get_lang('Add'), 'class="add"');
+            	
+            	
+            	break;
             /*
              * Used to display custom values for the gradebook score display
              */
@@ -348,8 +442,7 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
                 }
                 break;
                 */
-        }
-        
+        }        
         
         if ($row['variable'] == 'pdf_export_watermark_enable') {
         	$url =  PDF::get_watermark($course_code);
@@ -363,9 +456,7 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
         }
         if ($row['variable'] == 'timezone_value') {
             $form->addElement('html', sprintf(get_lang('LocalTimeUsingPortalTimezoneXIsY'),$row['selected_value'],api_get_local_time()));
-        }
-
-        	
+        }       	
     }
 
     $form->addElement('html', '<div style="text-align: right; clear: both;">');
@@ -413,14 +504,13 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
         //$result = Database::query($sql);
         // Save the settings.
         $keys = array();
-        //$gradebook_score_display_custom_values = array();
-        foreach ($values as $key => $value) {
+        //$gradebook_score_display_custom_values = array();        
+        foreach ($values as $key => $value) { 	
             // Treat gradebook values in separate function.
             //if (strpos($key, 'gradebook_score_display_custom_values') === false) {
                 if (!is_array($value)) {
-                    $old_value = api_get_setting($key);
-
-                    switch ($key) {
+                    $old_value = api_get_setting($key);                    
+                    switch ($key) {                    	
                     	case 'header_extra_content':
                     		file_put_contents(api_get_path(SYS_PATH).api_get_home_path().'/header_extra_content.txt', $value);                    		
                     		$value = api_get_home_path().'/header_extra_content.txt';
@@ -455,34 +545,42 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
                                 $value = $old_value;
                             }
                             break;
-
                     }
-
                     if ($old_value != $value) $keys[] = $key;
                     $result = api_set_setting($key, $value, null, null, $_configuration['access_url']);
-
                 } else {
-
-                    $sql = "SELECT subkey FROM $table_settings_current WHERE variable = '$key'";
-                    $res = Database::query($sql);
-                    $subkeys = array();
-                    while ($row_subkeys = Database::fetch_array($res)) {
-                        // If subkey is changed:
-                        if ((isset($value[$row_subkeys['subkey']]) && api_get_setting($key, $row_subkeys['subkey']) == 'false') ||
-                            (!isset($value[$row_subkeys['subkey']]) && api_get_setting($key, $row_subkeys['subkey']) == 'true')) {
-                            $keys[] = $key;
-                            break;
-                        }
-                    }
-
-                    foreach ($value as $subkey => $subvalue) {
-
-                        //$sql = "UPDATE $table_settings_current SET selected_value='true' WHERE variable='$key' AND subkey = '$subkey'";
-                        //$result = Database::query($sql);
-
-                        $result = api_set_setting($key, 'true', $subkey, null, $_configuration['access_url']);
-
-                    }
+                	if ($key == 'grading_model') {            		
+                		foreach ($value as $my_key => $option) {
+                			$array_to_save = array();               			
+                			//build this: 1*X+2*X+3*X/4
+                			$string_to_save = '';
+                			foreach ($option['items'] as $item) {
+                				$string_to_save .= $item.'*X+';
+                			}
+                			$string_to_save = substr($string_to_save, 0, strlen($string_to_save)- 1) . '/'.$option['denominator'];
+                			
+                			$array_to_save['display_text'] 	= $option['display_text'];
+                			$array_to_save['value'] 		= $string_to_save;
+                			$array_to_save['id'] 			= $my_key;               			
+                			
+                			$result = api_set_setting_option($array_to_save);
+                		}
+                	} else {
+	                    $sql = "SELECT subkey FROM $table_settings_current WHERE variable = '$key'";
+	                    $res = Database::query($sql);
+	                    $subkeys = array();
+	                    while ($row_subkeys = Database::fetch_array($res)) {
+	                        // If subkey is changed:
+	                        if ((isset($value[$row_subkeys['subkey']]) && api_get_setting($key, $row_subkeys['subkey']) == 'false') ||
+	                            (!isset($value[$row_subkeys['subkey']]) && api_get_setting($key, $row_subkeys['subkey']) == 'true')) {
+	                            $keys[] = $key;
+	                            break;
+	                        }
+	                    }	
+	                    foreach ($value as $subkey => $subvalue) {	             
+	                        $result = api_set_setting($key, 'true', $subkey, null, $_configuration['access_url']);	
+	                    }
+                	}
                 }
         }
 
@@ -501,6 +599,34 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
     }
 }
 
+
+$htmlHeadXtra[] = '<script language="javascript">
+
+function delete_grading_model(id) {
+	window.location = "settings.php?category=Gradebook&action=delete_grading&id=" + id;
+}
+
+	$(document).ready(function() {
+		var elements = ["B","C","D","E","F","G","H","I", "J", "K", "L","M","N","O","P","Q","R"];		
+		var i = 0;		
+		$(".formw").each(function(index) {
+			 $(this).find("*").each(function(index2) {			 		
+				if ($(this).hasClass("first_number")) {
+					$(this).before("<b>( A * </b>");	
+				}
+				if ($(this).hasClass("denominator")) {
+					$(this).before("<b> \) /  </b>");						
+				}
+				if ($(this).hasClass("number")) {
+					$(this).before("<b> + " + elements[i] + " * </b>");
+					i++;
+				}					
+			});
+			i = 0;
+		});
+	});
+</script>';
+
 // Including the header (banner).
 Display :: display_header($tool_name);
 
@@ -526,6 +652,8 @@ $action_images['timezones']     = 'timezone.png';
 $action_images['extra']     	= 'wizard.png';
 $action_images['tracking']     	= 'statistics.png';
 
+$action_images['gradebook2']    = 'gradebook.png';
+
 // Grabbing the categories.
 $resultcategories = api_get_settings_categories(array('stylesheets', 'Plugins', 'Templates', 'Search'));
 

+ 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'],

+ 9 - 8
main/admin/user_add.php

@@ -409,13 +409,14 @@ if( $form->validate()) {
 	$form->setConstants(array('sec_token' => $token));
 }
 
-// Display form
-Display::display_header($tool_name);
-//api_display_tool_title($tool_name);
 if(!empty($message)){
-	Display::display_normal_message(stripslashes($message));
+	$message = Display::return_message(stripslashes($message));
 }
-$form->display();
-
-// Footer
-Display::display_footer();
+$content .= $form->return_form();
+
+$tpl = new Template($tool_name);
+$tpl->assign('actions', $actions);
+$tpl->assign('message', $message);
+$tpl->assign('content', $content);
+$template = $tpl->get_template('layout/layout_1_col.tpl');
+$tpl->display($template);

+ 11 - 9
main/admin/user_edit.php

@@ -424,11 +424,9 @@ if ( $form->validate()) {
 	}
 }
 
-Display::display_header($tool_name);
-
 if ($error_drh) {
 	$err_msg = get_lang('StatusCanNotBeChangedToHumanResourcesManager');
-	Display::display_error_message($err_msg);
+	$message = Display::return_message($err_msg, 'error');
 }
 
 // USER PICTURE
@@ -454,13 +452,17 @@ $big_image_height = $big_image_size['height'];
 $url_big_image = $big_image.'?rnd='.time();
 
 if ($image == '') {
-	echo '<img '.$img_attributes.' />';
+	$content .= '<img '.$img_attributes.' />';
 } else {
-	echo '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
+	$content .= '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
 }
 
 // Display form
-$form->display();
-
-// Footer
-Display::display_footer();
+$content .= $form->return_form();
+
+$tpl = new Template($tool_name);
+$tpl->assign('actions', $actions);
+$tpl->assign('message', $message);
+$tpl->assign('content', $content);
+$template = $tpl->get_template('layout/layout_1_col.tpl');
+$tpl->display($template);

+ 31 - 29
main/admin/user_list.php

@@ -767,7 +767,9 @@ if (isset($_GET['keyword']) || isset($_GET['keyword_firstname'])) {
 }
 
 
-Display :: display_header($tool_name, "");
+//Display :: display_header($tool_name, "");
+
+$message = '';
 
 //api_display_tool_title($tool_name);
 if (isset ($_GET['action'])) {
@@ -780,32 +782,32 @@ if (isset ($_GET['action'])) {
                 	if ($_GET['warn'] == 'session_message'){
                 		$_GET['warn'] = $_SESSION['session_message_import_users'];
                 	}
-                	Display::display_warning_message(urldecode($_GET['warn']),false);
+                	$message = Display::return_message(urldecode($_GET['warn']),'warning', false);
                 }
                 if (!empty($_GET['message'])) {
-                    Display :: display_confirmation_message(stripslashes($_GET['message']));
+                    $message = Display :: return_message(stripslashes($_GET['message']), 'confirmation');
                 }
 				break;
 			case 'delete_user' :
 				if (api_is_platform_admin()) {
 					if ($delete_user_available) {
 						if ($user_id != $_user['user_id'] && UserManager :: delete_user($_GET['user_id'])) {
-							Display :: display_confirmation_message(get_lang('UserDeleted'));
+							$message = Display :: return_message(get_lang('UserDeleted'), 'confirmation');
 						} else {
-							Display :: display_error_message(get_lang('CannotDeleteUserBecauseOwnsCourse'));
+							$message = Display :: return_message(get_lang('CannotDeleteUserBecauseOwnsCourse'), 'error');
 						}
 					} else {
-						Display :: display_error_message(get_lang('CannotDeleteUser'));
+						$message = Display :: return_message(get_lang('CannotDeleteUser'),'error');
 					}
 				}
 				break;
 			case 'lock' :
 				$message=lock_unlock_user('lock',$_GET['user_id']);
-				Display :: display_normal_message($message);
+				$message =Display :: return_message($message);
 				break;
 			case 'unlock';
 				$message=lock_unlock_user('unlock',$_GET['user_id']);
-				Display :: display_normal_message($message);
+				$message =Display :: return_message($message);
 				break;
 
 		}
@@ -822,23 +824,17 @@ if (isset ($_POST['action'])) {
 					$number_of_selected_users = count($_POST['id']);
 					$number_of_deleted_users = 0;
 					if (is_array($_POST['id'])) {
-						foreach ($_POST['id'] as $index => $user_id)
-						{
-							if($user_id != $_user['user_id'])
-							{
-								if(UserManager :: delete_user($user_id))
-								{
+						foreach ($_POST['id'] as $index => $user_id) {
+							if($user_id != $_user['user_id']) {
+								if(UserManager :: delete_user($user_id)) {
 									$number_of_deleted_users++;
 								}
 							}
 						}
 					}
-					if($number_of_selected_users == $number_of_deleted_users)
-					{
+					if($number_of_selected_users == $number_of_deleted_users) {
 						Display :: display_confirmation_message(get_lang('SelectedUsersDeleted'));
-					}
-					else
-					{
+					} else {
 						Display :: display_error_message(get_lang('SomeUsersNotDeleted'));
 					}
 				}
@@ -854,18 +850,17 @@ $renderer =& $form->defaultRenderer();
 $renderer->setElementTemplate('<span>{element}</span> ');
 $form->addElement('text','keyword',get_lang('keyword'), 'size="25"');
 $form->addElement('style_submit_button', 'submit',get_lang('Search'),'class="search"');
-//$form->addElement('static','search_advanced_link',null,'<a href="user_list.php?search=advanced">'.get_lang('AdvancedSearch').'</a>');
-
-    $form->addElement('static','search_advanced_link',null,'<a href="javascript://" class = "advanced_parameters" onclick="display_advanced_search_form();"><span id="img_plus_and_minus">&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).' '.get_lang('AdvancedSearch').'</span></a>');
+$form->addElement('static','search_advanced_link',null,'<a href="javascript://" class = "advanced_parameters" onclick="display_advanced_search_form();"><span id="img_plus_and_minus">&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).' '.get_lang('AdvancedSearch').'</span></a>');
 
-echo '<div class="actions" style="width:100%;">';
+$actions  = '';
 if (api_is_platform_admin()) {
-	echo '<span style="float:right;">'.
+	$actions .= '<span style="float:right;">'.
 		 '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_add.php">'.Display::return_icon('new_user.png',get_lang('AddUsers'),'','32').'</a>'.
 		 '</span>';
 }
-$form->display();
-echo '</div>';
+$actions .=$form->return_form();
+
+
 if (isset ($_GET['keyword'])) {
 	$parameters = array ('keyword' => Security::remove_XSS($_GET['keyword']));
 } elseif (isset ($_GET['keyword_firstname'])) {
@@ -970,7 +965,7 @@ $defaults['keyword_inactive'] = 1;
 $form->setDefaults($defaults);
 $form->addElement('html','</div>');
 
-$form->display();
+$form = $form->return_form();
 
 $table = new SortableTable('users', 'get_number_of_users', 'get_user_data', (api_is_western_name_order() xor api_sort_by_first_name()) ? 3 : 2);
 $table->set_additional_parameters($parameters);
@@ -1000,6 +995,13 @@ $table->set_column_filter(9, 'modify_filter');
 
 if (api_is_platform_admin())
 	$table->set_form_actions(array ('delete' => get_lang('DeleteFromPlatform')));
-$table->display();
+$table = $table->return_table();
+
+
+$tpl = new Template($tool_name);
 
-Display :: display_footer();
+$tpl->assign('actions', $actions);
+$tpl->assign('message', $message);
+$tpl->assign('content', $form.$table);
+$template = $tpl->get_template('layout/layout_1_col.tpl');
+$tpl->display($template);

+ 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;
 			}

+ 63 - 80
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'];
@@ -578,7 +549,7 @@ if(api_is_allowed_to_edit(false,true))  {
 } else {
 	// students only get to see the visible announcements
 		if (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath') {
-			$group_memberships=GroupManager::get_group_ids($_course['dbName'], $_user['user_id']);
+			$group_memberships=GroupManager::get_group_ids($_course['real_id'], $_user['user_id']);
 
 			if ((api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
 
@@ -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
@@ -901,7 +875,7 @@ if ($display_announcement_list) {
 		//$group_id=$_SESSION['group'];
 	}
 	$group_id = api_get_group_id();
-	$group_memberships = GroupManager::get_group_ids($_course['dbName'],api_get_user_id());
+	$group_memberships = GroupManager::get_group_ids($_course['real_id'],api_get_user_id());
 
 	if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) {
 		// A.1. you are a course admin with a USER 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();

+ 14 - 14
main/calendar/agenda.inc.php

@@ -66,7 +66,7 @@ function get_calendar_items($select_month, $select_year, $select_day = false) {
 	$TABLEAGENDA         = Database::get_course_table(TABLE_AGENDA);
 	$TABLE_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
 	
-	$group_memberships = GroupManager::get_group_ids($course_info['dbName'], api_get_user_id());
+	$group_memberships = GroupManager::get_group_ids($course_info['real_id'], api_get_user_id());
     $repeats = array();
 
 	/*	CONSTRUCT THE SQL STATEMENT */
@@ -87,7 +87,7 @@ function get_calendar_items($select_month, $select_year, $select_day = false) {
         // => see only the messages of this specific user + the messages of the group (s)he is member of.
         
         if (!empty($_SESSION['user'])) {
-            $group_memberships = GroupManager::get_group_ids($course_info['dbName'], $_SESSION['user']);
+            $group_memberships = GroupManager::get_group_ids($course_info['real_id'], $_SESSION['user']);
 
             $show_user =true;
             $new_group_memberships=array();
@@ -2725,8 +2725,8 @@ function get_agendaitems($month, $year) {
 	//databases of the courses
 	$TABLEAGENDA 		= Database :: get_course_table(TABLE_AGENDA);
 	$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-
-	$group_memberships = GroupManager :: get_group_ids(Database::get_current_course_database(), api_get_user_id());
+	$course_info = api_get_course_info();
+	$group_memberships = GroupManager :: get_group_ids($course_info['real_id'], api_get_user_id());
 	// if the user is administrator of that course we show all the agenda items
 	if (api_is_allowed_to_edit(false,true)) {
 		//echo "course admin";
@@ -2808,12 +2808,12 @@ function display_upcoming_events() {
 	//databases of the courses
 	$TABLEAGENDA 		= Database :: get_course_table(TABLE_AGENDA);
 	$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
-    $mycourse   = api_get_course_info();
-    $myuser     = api_get_user_info();
-    $session_id = api_get_session_id();
+    $mycourse   		= api_get_course_info();
+    $myuser     		= api_get_user_info();
+    $session_id 		= api_get_session_id();
 
 
-	$group_memberships = GroupManager :: get_group_ids($mycourse['dbName'], $myuser['user_id']);
+	$group_memberships = GroupManager :: get_group_ids($mycourse['real_id'], $myuser['user_id']);
 	// if the user is administrator of that course we show all the agenda items
 	if (api_is_allowed_to_edit(false,true)) {
 		//echo "course admin";
@@ -3100,11 +3100,11 @@ function get_day_agendaitems($courses_dbs, $month, $year, $day) {
 	foreach ($courses_dbs as $key => $array_course_info) {
 		//echo $array_course_info['db'];
 		//databases of the courses
-		$TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA, $array_course_info['db_name']);
-		$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $array_course_info['db_name']);
+		$TABLEAGENDA 		= Database :: get_course_table(TABLE_AGENDA);
+		$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 
 		// getting all the groups of the user for the current course
-		$group_memberships = GroupManager :: get_group_ids($array_course_info['db_name'], api_get_user_id());
+		$group_memberships = GroupManager :: get_group_ids($array_course_info['real_id'], api_get_user_id());
 		$course_user_status = CourseManager::get_user_in_course_status(api_get_user_id(), $array_course_info['code']);
 		
 		
@@ -3222,11 +3222,11 @@ function get_week_agendaitems($courses_dbs, $month, $year, $week = '') {
 	// get agenda-items for every course
 	foreach ($courses_dbs as $key => $array_course_info) {
 		//databases of the courses
-		$TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA, $array_course_info["db_name"]);
-		$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $array_course_info["db_name"]);
+		$TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA);
+		$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 
 		// getting all the groups of the user for the current course
-		$group_memberships = GroupManager :: get_group_ids($array_course_info["db_name"], api_get_user_id());
+		$group_memberships = GroupManager :: get_group_ids($array_course_info["real_id"], api_get_user_id());
 		
 		$user_course_status = CourseManager::get_user_in_course_status(api_get_user_id(),$array_course_info["code"]);
 

+ 26 - 14
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);				
@@ -144,12 +145,14 @@ class Agenda {
 	 * @param	int		course id *integer* not the course code 
 	 * 
 	 */
-	function get_events($start, $end, $user_id, $course_id = null) {				
-		switch($this->type) {
+	function get_events($start, $end, $user_id, $course_id = null) {	
+					
+		switch ($this->type) {
 			case 'admin':
 				$this->get_platform_events($start, $end);
 				break;
 			case 'course':
+				
 				$course_info = api_get_course_info_by_id($course_id);				
 				$this->get_course_events($start, $end, $course_info);
 				break;
@@ -285,40 +288,49 @@ class Agenda {
 	}
 	
 	function get_course_events($start, $end, $course_info, $group_id = 0) {
-		$group_memberships 	= GroupManager::get_group_ids($course_info['db_name'], api_get_user_id());
+		$course_id = $course_info['real_id'];
+		$group_memberships 	= GroupManager::get_group_ids($course_id, api_get_user_id());
 	
-		$tlb_course_agenda	= Database::get_course_table(TABLE_AGENDA, $course_info['db_name']);
-		$tbl_property 		= Database::get_course_table(TABLE_ITEM_PROPERTY, $course_info['db_name']);
+		$tlb_course_agenda	= Database::get_course_table(TABLE_AGENDA);
+		$tbl_property 		= Database::get_course_table(TABLE_ITEM_PROPERTY);
 	
 		$user_id = api_get_user_id();
 	
 		if (is_array($group_memberships) && count($group_memberships)>0) {
 			$sql = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
-						FROM ".$tlb_course_agenda." agenda, ".$tbl_property." ip
-	                    WHERE agenda.id = ip.ref   ".$show_all_current."
-	                    AND ip.tool='".TOOL_CALENDAR_EVENT."'
-	                    AND ( ip.to_user_id=$user_id OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") )
-	                    AND ip.visibility='1'
+					FROM ".$tlb_course_agenda." agenda, ".$tbl_property." ip
+	                WHERE 	agenda.id 		= ip.ref  AND 
+	                		ip.tool			='".TOOL_CALENDAR_EVENT."' AND 
+	                		( ip.to_user_id=$user_id OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) AND 
+	                		ip.visibility	= '1' AND
+	                		agenda.c_id = $course_id AND
+	                		ip.c_id = $course_id
+	                		
 	            	";
 		} else {
 			if (api_get_user_id()) {
 				$sql="SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
 	                		FROM ".$tlb_course_agenda." agenda, ".$tbl_property." ip
-	            			WHERE agenda.id = ip.ref   ".$show_all_current." 
+	            			WHERE agenda.id = ip.ref 
 	            				AND ip.tool='".TOOL_CALENDAR_EVENT."'
 	            				AND ( ip.to_user_id=$user_id OR ip.to_group_id='0')
-	                            AND ip.visibility='1'
+	                            AND ip.visibility='1' AND 
+	                            agenda.c_id = $course_id AND
+	                			ip.c_id = $course_id
 	                        ";
 			} else {
 				$sql="SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
 	                                FROM ".$tlb_course_agenda." agenda, ".$tbl_property." ip
-	                                WHERE agenda.id = ip.ref   ".$show_all_current."
+	                                WHERE agenda.id = ip.ref
 	                                AND ip.tool='".TOOL_CALENDAR_EVENT."'
 	                                AND ip.to_group_id='0'
-	                                AND ip.visibility='1'
+	                                AND ip.visibility='1' AND 
+	                                agenda.c_id = $course_id AND
+	                				ip.c_id = $course_id
 	                                ";
 			}
 		}
+		
 		$result = Database::query($sql);
 		$events = array();
 		if (Database::num_rows($result)) {

+ 21 - 13
main/calendar/agenda_js.php

@@ -21,7 +21,7 @@ $htmlHeadXtra[] = api_get_js('fullcalendar/fullcalendar.min.js');
 $htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/fullcalendar/fullcalendar.css');
 $htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/qtip2/jquery.qtip.min.css');
 
-$tpl	= new Template();
+$tpl	= new Template(get_lang('Agenda'));
 $type  	= isset($_REQUEST['type']) && in_array($_REQUEST['type'], array('personal', 'course', 'admin')) ?  $_REQUEST['type'] : 'personal';
 
 if (api_is_platform_admin() && $type == 'admin') {	
@@ -49,23 +49,31 @@ $days 			= api_get_week_days_long();
 $months 		= api_get_months_long();
 $months_short 	= api_get_months_short();
 
-$tpl->assign('month_names', json_encode($months));
-$tpl->assign('month_names_short', json_encode($months_short));
-$tpl->assign('day_names', json_encode($days));
-$tpl->assign('day_names_short', json_encode($day_short));
-
-$tpl->assign('button_text', json_encode(array('today'=>get_lang('Today'), 'month'=>get_lang('Month'), 'week'=>get_lang('Week'), 'day'=>get_lang('Day'))));
-
-
-
+//Setting calendar translations
+$tpl->assign('month_names', 		json_encode($months));
+$tpl->assign('month_names_short', 	json_encode($months_short));
+$tpl->assign('day_names', 			json_encode($days));
+$tpl->assign('day_names_short', 	json_encode($day_short));
+$tpl->assign('button_text', 		json_encode(array(	'today'	=> get_lang('Today'), 
+														'month'	=> get_lang('Month'), 
+														'week'	=> get_lang('Week'), 
+														'day'	=> get_lang('Day'))));
+//Calendar Type : course, admin, personal
 $tpl->assign('type', $type);
+//Calendar type label
+$tpl->assign('type_label', get_lang($type.'Calendar'));
+
+//Current user can add event?
 $tpl->assign('can_add_events', $can_add_events);
- 
-$agenda_ajax_url = api_get_path(WEB_AJAX_PATH).'agenda.ajax.php?type='.$type.'&';
 
+//Setting AJAX caller
+$agenda_ajax_url = api_get_path(WEB_AJAX_PATH).'agenda.ajax.php?type='.$type.'&';
 $tpl->assign('web_agenda_ajax_url', $agenda_ajax_url);
 
+//Loading Agenda template
 $content = $tpl->fetch('default/agenda/month.tpl');
 $tpl->assign('content', $content);
+
+//Loading main Chamilo 1 col template
 $template_file = $tpl->get_template('layout/layout_1_col.tpl');
-$tpl->display($template_file);
+$tpl->display($template_file);

+ 3 - 3
main/calendar/myagenda.inc.php

@@ -32,10 +32,10 @@ function get_myagendaitems($user_id, $courses_dbs, $month, $year) {
 	// get agenda-items for every course
 	foreach ($courses_dbs as $key => $array_course_info) {
 		//databases of the courses
-		$TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA, $array_course_info["db_name"]);
-		$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY, $array_course_info["db_name"]);
+		$TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA);
+		$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 
-		$group_memberships = GroupManager :: get_group_ids($array_course_info["db_name"], $user_id);
+		$group_memberships = GroupManager :: get_group_ids($array_course_info["real_id"], $user_id);
 		$course_user_status = CourseManager::get_user_in_course_status($user_id, $array_course_info["code"]);
 		// if the user is administrator of that course we show all the agenda items
 		if ($course_user_status == '1') {

+ 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) {

+ 32 - 27
main/course_info/infocours.php

@@ -34,16 +34,12 @@ 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() {
@@ -235,6 +231,27 @@ $form->addElement('html', '</div></div>');
 
 
 
+
+// Gradebook SETTINGS
+//$form->addElement('html', '<div class="sectiontitle" style="margin-top: 40px;"><a href="#header" style="float:right;">'.Display::return_icon('top.gif', get_lang('Top')).'</a><a name="chatsettings" id="chatsettings"></a>'.Display::return_icon('chat.png', get_lang('ConfigChat'),'','22').' '.get_lang('ConfigChat').'</div>');
+$form->addElement('html', '<div> <h3>'.Display::return_icon('gradebook.png', get_lang('Gradebook'),'','22').' '.get_lang('Gradebook').'</h3><div>');
+$group = array();
+$models = api_get_settings_options('grading_model');
+foreach ($models as $option) {
+	$grading_parsed = api_grading_model_functions($option['value'], 'decorate');
+	$element = $form->createElement('radio', 'course_grading_model', '', $option['display_text'].': '.$grading_parsed, $option['id']);		
+	$group[] = $element;
+}
+
+$element = $form->createElement('radio', 'course_grading_model', '', get_lang('None'), 0);
+$group[] = $element;
+
+
+$form->addGroup($group, '', array(get_lang('GradingModelTitle')), '', 'li', false); //julio
+
+$form->addElement('style_submit_button', null, get_lang('SaveSettings'), 'class="save"');
+$form->addElement('html', '</div></div>');
+
 // USER RIGHTS
 //$form->addElement('html', '<div class="sectiontitle" style="margin-top: 40px;"><a href="#header" style="float:right;">'.Display::return_icon('top.gif', get_lang('Top')).'</a><a name="userrights" id="userrights"></a>'.Display::return_icon('user.png', get_lang('UserRights'),'','22').' '.get_lang('UserRights').'</div>');
 $form->addElement('html', '<div> <h3>'.Display::return_icon('user.png', get_lang('UserRights'),'','22').' '.get_lang('UserRights').'</h3><div>');
@@ -262,12 +279,9 @@ $form->addElement('html', '</div></div>');
 // CHAT SETTINGS
 //$form->addElement('html', '<div class="sectiontitle" style="margin-top: 40px;"><a href="#header" style="float:right;">'.Display::return_icon('top.gif', get_lang('Top')).'</a><a name="chatsettings" id="chatsettings"></a>'.Display::return_icon('chat.png', get_lang('ConfigChat'),'','22').' '.get_lang('ConfigChat').'</div>');
 $form->addElement('html', '<div> <h3>'.Display::return_icon('chat.png', get_lang('ConfigChat'),'','22').' '.get_lang('ConfigChat').'</h3><div>');
-
 $form->addElement('radio', 'allow_open_chat_window', get_lang('AllowOpenchatWindow'), get_lang('AllowOpenChatWindowActivate'), 1);
 $form->addElement('radio', 'allow_open_chat_window', null, get_lang('AllowOpenChatWindowDeactivate'), 0);
-
 $form->addElement('style_submit_button', null, get_lang('SaveSettings'), 'class="save"');
-
 $form->addElement('html', '</div></div>');
 
 
@@ -367,11 +381,15 @@ $values['enable_lp_auto_launch']                    = api_get_course_setting('en
 
 $values['pdf_export_watermark_text']                = api_get_course_setting('pdf_export_watermark_text');
 
+$values['course_grading_model']                		= api_get_course_setting('course_grading_model');
+
+
 $form->setDefaults($values);
 
 // Validate form
 if ($form->validate() && is_settings_editable()) {
 	$update_values = $form->exportValues();
+	
 /*
     // update course picture
     $picture = $_FILES['picture'];
@@ -387,7 +405,8 @@ if ($form->validate() && is_settings_editable()) {
     }
     
     //Variables that will be saved in the TABLE_MAIN_COURSE table
-    $update_in_course_table = array('title','visual_code', 'course_language','category_code','department_name', 'department_url','visibility',  'subscribe', 'unsubscribe','tutor_name','course_registration_password');
+    $update_in_course_table = array('title','visual_code', 'course_language','category_code','department_name', 'department_url','visibility',  
+    								'subscribe', 'unsubscribe','tutor_name','course_registration_password');
 
 	foreach ($update_values as $index =>$value) {
 		$update_values[$index] = Database::escape_string($value);
@@ -415,10 +434,10 @@ if ($form->validate() && is_settings_editable()) {
     
     foreach($update_values as $key =>$value) {
         //We do not update variables that were already saved in the TABLE_MAIN_COURSE table
-        if (!in_array($key, $update_in_course_table)) {            
-            Database::update($table_course_setting, array('value' => $update_values[$key]), array('variable = ? ' =>$key));
+        if (!in_array($key, $update_in_course_table)) {
+            Database::update($table_course_setting, array('value' => $update_values[$key]), array('variable = ? AND c_id = ?' => array($key, api_get_course_int_id()), true));
         }    	
-    }
+    }    
 	$cidReset = true;
 	$cidReq = $course_code;
 	require '../inc/local.inc.php';
@@ -439,20 +458,6 @@ if (isset($_GET['action']) && $_GET['action'] == 'show_message') {
 	Display :: display_normal_message(get_lang('ModifDone'));
 }
 
-// actions bar
-/*
-echo '<div class="actions">';
-echo '<a href="#coursesettings">'.Display::return_icon('settings.png', get_lang('CourseSettings'),'','32').'</a>';
-echo '<a href="#coursesaccess">'.Display::return_icon('course.png', get_lang('CourseAccess'),'','32').'</a>';
-echo '<a href="#emailnotifications">'.Display::return_icon('mail.png', get_lang('EmailNotifications'),'','32').'</a>';
-echo '<a href="#userrights">'.Display::return_icon('user.png', get_lang('UserRights'),'','32').'</a>';
-echo '<a href="#chatsettings">'.Display::return_icon('chat.png', get_lang('ConfigChat'),'','32').'</a>';
-if (api_get_setting('allow_course_theme') == 'true') {
-	echo '<a href="#learnpath">'.Display::return_icon('scorms.png', get_lang('ConfigLearnpath'),'','32').'</a>';
-}
-echo '<a href="#thematicadvance">'.Display::return_icon('course_progress.png', get_lang('ThematicAdvanceConfiguration'),'','32').'</a>';
-echo '</div>';
-*/
 echo '<script>
 $(function() {
 	$("#course_settings").accordion({

+ 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);
                 }
-            }
+            }            
         }
     }
     

Diff do ficheiro suprimidas por serem muito extensas
+ 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')) {

+ 11 - 13
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,19 @@ 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);
-                $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);
+                //update_Db_course($db_name);
+                $pictures_array = fill_course_repository($directory,  $exemplary_content);                
+                $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 +265,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();

+ 47 - 22
main/css/base.css

@@ -3740,28 +3740,6 @@ form div.error input, form div.error textarea {
     width:400px;
 }
 
-.background_color_personal {
-    background:#3366CC;
-    width:100px;
-    display:block;
-    height:15px;
-}
-
-.background_color_admin {
-    background:red;
-    width:100px;
-    display:block;
-    height:15px;
-}
-
-.background_color_course {
-    background:#458B00;
-    width:100px;
-    display:block;
-    height:15px;
-}
-
-
 .tag {
     background-color: #D3E6EF;
     border-radius: 3px 3px 3px 3px;
@@ -3772,3 +3750,50 @@ form div.error input, form div.error textarea {
     margin: 0 10px 5px 0;
     padding: 0.4em 0.6em;
 }
+
+.label_tag {
+  /* padding: 1px 3px 2px; */
+  padding:5px;
+  background-color: #bfbfbf;
+  font-size: 9.75px;
+  font-weight: bold;
+  color: #ffffff;
+  text-transform: uppercase;
+  -webkit-border-radius: 3px;
+  -moz-border-radius: 3px;
+  border-radius: 3px;
+  width:120px;
+}
+
+.label_tag.personal_event {	
+	 background:#3366CC;
+}
+.label_tag.admin_event { 
+     background:red;
+}
+.label_tag.course_event { 
+     background:#458B00;
+}
+
+
+.label_tag.important {
+  background-color: #c43c35;
+}
+.label_tag.warning {
+  background-color: #f89406;
+}
+.label_tag.success {
+  background-color: #46a546;
+}
+.label_tag.notice {
+  background-color: #62cffc;
+}
+
+
+.invisible {
+    color: #999;
+}
+
+.invisible h2 {
+    color: #999;
+}

+ 1 - 3
main/css/base_chamilo.css

@@ -216,9 +216,7 @@ ul#navigation .student-connect a {
     min-height: 300px;
     background-color: #fff;
 }
-.invisible {
-    color: #999;
-}
+
 .courseadminview table td a, .Authoringview table td a {
     font-weight: bold;
     font-size:13px;

+ 2 - 2
main/document/create_document.php

@@ -155,7 +155,6 @@ require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 require_once api_get_path(SYS_CODE_PATH).'document/document.inc.php';
 require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
-require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
 
 //I'm in the certification module?
@@ -393,6 +392,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 +501,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 - 4
main/document/document.php

@@ -44,7 +44,6 @@ $lib_path = api_get_path(LIBRARY_PATH);
 /* Libraries */
 require_once $lib_path.'document.lib.php';
 require_once $lib_path.'fileUpload.lib.php';
-require_once $lib_path.'formvalidator/FormValidator.class.php';
 require_once $lib_path.'fileDisplay.lib.php';
 require_once $lib_path.'tablesort.lib.php';
 
@@ -590,7 +589,6 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
         $document_to_move = DocumentManager::get_document_data_by_id($_POST['move_file'], api_get_course_id());            
         require_once $lib_path.'fileManage.lib.php';
         // This is needed for the update_db_info function
-        //$dbTable = $_course['dbNameGlu'].'document';
         $dbTable = Database::get_course_table(TABLE_DOCUMENT);
         // Security fix: make sure they can't move files that are not in the document table
         if (!empty($document_to_move)) {
@@ -701,8 +699,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 +713,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

+ 4 - 6
main/exercice/question_list_admin.inc.php

@@ -158,7 +158,7 @@ $(function() {
 echo '<div class="actionsbig">';
 //we filter the type of questions we can add
 Question :: display_type_menu ($objExercise->feedbacktype);
-echo '</div><div style="clear:both;">';
+echo '</div><div style="clear:both;"></div>';
 echo '<div id="message"></div>';
 $token = Security::get_token();
 //deletes a session when using don't know question type (ugly fix)
@@ -212,17 +212,15 @@ if ($nbrQuestions) {
                         echo '<br />';
                         showQuestion($id, false, '', '',false, true);                   
                     echo '</p>';                        
-                 echo '</div>';
-                 
-            echo '</div>';
-            
+                 echo '</div>';                 
+            echo '</div>';            
                 
             unset($objQuestionTmp);
 		}
         echo '</div>';
 	}
 }
-echo '</table></div>';
+echo '</div>';
 if(!$nbrQuestions) {	
   	echo Display::display_warning_message(get_lang('NoQuestion'));
 }

+ 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);

+ 1 - 1
main/forum/index.php

@@ -154,7 +154,7 @@ $forum_list	= get_forums();
 
 // The groups of the user.
 $groups_of_user = array();
-$groups_of_user = GroupManager::get_group_ids($_course['dbName'], $_user['user_id']);
+$groups_of_user = GroupManager::get_group_ids($_course['real_id'], $_user['user_id']);
 // All groups in the course (and sorting them as the id of the group = the key of the array).
 if (!api_is_anonymous()) {
     $all_groups = GroupManager::get_group_list();

+ 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') {

+ 1 - 1
main/forum/viewforumcategory.php

@@ -157,7 +157,7 @@ if ($action_forums != 'add') {
 
     // The groups of the user.
     $groups_of_user = array();
-    $groups_of_user = GroupManager::get_group_ids($_course['dbName'], $_user['user_id']);
+    $groups_of_user = GroupManager::get_group_ids($_course['real_id'], $_user['user_id']);
     // All groups in the course (and sorting them as the id of the group = the key of the array.
     $all_groups = GroupManager::get_group_list();
     if (is_array($all_groups)) {

+ 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();
 		}

+ 12 - 2
main/gradebook/gradebook_add_cat.php

@@ -20,18 +20,24 @@ require_once 'lib/gradebook_functions.inc.php';
 require_once 'lib/fe/catform.class.php';
 api_block_anonymous_users();
 block_students();
-$get_select_cat=Security::remove_XSS($_GET['selectcat']);
+$get_select_cat = intval($_GET['selectcat']);
+
 $catadd = new Category();
 $my_user_id = api_get_user_id();
 $catadd->set_user_id($my_user_id);
-$catadd->set_parent_id(Database::escape_string($get_select_cat));
+$catadd->set_parent_id($get_select_cat);
 $catcourse = Category :: load ($get_select_cat);
+
 if ($_in_course) {
 	$catadd->set_course_code($course_code);
 } else {
 	$catadd->set_course_code($catcourse[0]->get_course_code());
 }
+
+$catadd->set_course_code(api_get_course_id());
+
 $form = new CatForm(CatForm :: TYPE_ADD, $catadd, 'add_cat_form', null, api_get_self() . '?selectcat='.$get_select_cat);
+
 if ($form->validate()) {
 	$values = $form->exportValues();
 	$select_course=isset($values['select_course']) ? $values['select_course'] : array();
@@ -48,6 +54,9 @@ if ($form->validate()) {
 		$cat->set_name($values['name']);
 		$cat->set_course_code($values['course_code']);//?
 	}
+	//Always add the gradebook to the course
+	$cat->set_course_code(api_get_course_id());	
+	
 	$cat->set_description($values['description']);
 	$cat->set_user_id($values['hid_user_id']);
 	$cat->set_parent_id($values['hid_parent_id']);
@@ -66,6 +75,7 @@ if ($form->validate()) {
 if ( !$_in_course ) {
 	$interbreadcrumb[] = array ('url' => Security::remove_XSS($_SESSION['gradebook_dest']).'?selectcat='.$get_select_cat,'name' => get_lang('Gradebook'));
 }
+$interbreadcrumb[]= array (	'url' =>'index.php','name' => get_lang('ToolGradebook'));
 Display :: display_header(get_lang('NewCategory'));
 $form->display();
 Display :: display_footer();

+ 5 - 0
main/gradebook/gradebook_add_eval.php

@@ -33,9 +33,14 @@ if ($form->validate()) {
 	$eval->set_name($values['name']);
 	$eval->set_description($values['description']);
 	$eval->set_user_id($values['hid_user_id']);
+	
 	if (!empty ($values['hid_course_code'])) {
 		$eval->set_course_code($values['hid_course_code']);
 	}
+	
+	//Always add the gradebook to the course
+	$eval->set_course_code(api_get_course_id());
+	
 	$eval->set_category_id($values['hid_category_id']);
 	$eval->set_weight($values['weight']);
 	

+ 25 - 36
main/gradebook/gradebook_add_link.php

@@ -18,22 +18,15 @@ 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']) : '';
-$my_db_course=isset($_GET['course_code'])?$course_info['dbName']:'';
+$course_info = api_get_course_info($_GET['course_code']);
 
-$tbl_forum_thread = Database :: get_course_table(TABLE_FORUM_THREAD,$my_db_course);
+$tbl_forum_thread = Database :: get_course_table(TABLE_FORUM_THREAD);
 $tbl_link=Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+$all_categories = Category :: load();
+
 $category = Category :: load($_GET['selectcat']);
-$typeform = new LinkForm(LinkForm :: TYPE_CREATE,
-						$category[0],
-						null,
-						'create_link',
-						null,
-						api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
-						. '&newtypeselected=' . (isset($_GET['typeselected']) ? Security::remove_XSS($_GET['typeselected']) : '')
-						. '&course_code=' . (empty($_GET['course_code'])?'':Security::remove_XSS($_GET['course_code'])),
-						$_GET['typeselected'])
-						;
+$url = api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat']). '&newtypeselected=' . (isset($_GET['typeselected']) ? Security::remove_XSS($_GET['typeselected']) : ''). '&course_code=' . (empty($_GET['course_code'])?'':Security::remove_XSS($_GET['course_code']));
+$typeform = new LinkForm(LinkForm :: TYPE_CREATE, $category[0], null, 'create_link', null, $url , $_GET['typeselected']);
 
 // if user selected a link type
 if ($typeform->validate() && isset($_GET['newtypeselected'])) {
@@ -46,24 +39,21 @@ if ($typeform->validate() && isset($_GET['newtypeselected'])) {
 
 // link type selected, show 2nd form to retrieve the link data
 if (isset($_GET['typeselected']) && $_GET['typeselected'] != '0') {
-	$addform = new LinkAddEditForm(LinkAddEditForm :: TYPE_ADD,
-								   $category[0],
-								   intval($_GET['typeselected']),
-								   null,
-								   'add_link',
-								   api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
-														. '&typeselected=' . Security::remove_XSS($_GET['typeselected']) . '&course_code=' . Security::remove_XSS($_GET['course_code']));
+	$url = api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat']).'&typeselected=' . Security::remove_XSS($_GET['typeselected']) . '&course_code=' . Security::remove_XSS($_GET['course_code']);
+	$addform = new LinkAddEditForm(LinkAddEditForm :: TYPE_ADD, $all_categories, intval($_GET['typeselected']),null, 'add_link', $url);
 	if ($addform->validate()) {
 		$addvalues = $addform->exportValues();
 		$link= LinkFactory :: create($_GET['typeselected']);
 		$link->set_user_id(api_get_user_id());
-		if($category[0]->get_course_code() == '' && !empty($_GET['course_code'])) {
+		/*
+		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());
-		}
-		$link->set_category_id($category[0]->get_id());
+		}*/
+		$link->set_course_code(api_get_course_id());
+		
+		$link->set_category_id($addvalues['select_gradebook']);
 
 		if ($link->needs_name_and_description()) {
 			$link->set_name($addvalues['name']);
@@ -81,27 +71,26 @@ 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);
-		if ( isset($_GET['typeselected']) && 5==$_GET['typeselected'] && (isset($addvalues['select_link']) && $addvalues['select_link']<>"")) {
+		//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'].';';
-			$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;';
+			$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 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);
 			}
 		}
 		$link->add();
+				
 		$addvalue_result=!empty($addvalues['addresult'])?$addvalues['addresult']:array();
 		if ($addvalue_result == 1) {
 			header('Location: gradebook_add_result.php?selecteval=' . $link->get_ref_id());

+ 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();

+ 14 - 18
main/gradebook/gradebook_edit_link.php

@@ -16,26 +16,20 @@ 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']):'';
 
-$form = new LinkAddEditForm(LinkAddEditForm :: TYPE_EDIT,
-							null,
-							null,
-							$link,
-							'edit_link_form',
-							api_get_self() . '?selectcat=' . $linkcat
-												 . '&editlink=' . $linkedit);
+$cats = Category :: load(null, null, $course_code, null, null, $session_id, false); //already init
 
+$form = new LinkAddEditForm(LinkAddEditForm :: TYPE_EDIT, $cats, null, $link, 'edit_link_form', api_get_self() . '?selectcat=' . $linkcat. '&editlink=' . $linkedit);
 if ($form->validate()) {
 	$values = $form->exportValues();
 	$link->set_weight($values['weight']);
@@ -43,20 +37,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 +62,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

+ 84 - 40
main/gradebook/index.php

@@ -10,7 +10,12 @@ $language_file= 'gradebook';
 $cidReset= false;
 $_in_course = true;
 require_once '../inc/global.inc.php';
-$course_code = api_get_course_id();
+
+$course_code 	= api_get_course_id();
+$stud_id        = api_get_user_id();
+$session_id		= api_get_session_id();
+
+
 //make sure the destination for scripts is index.php instead of gradebook.php
 $_SESSION['gradebook_dest'] = 'index.php';
 
@@ -52,15 +57,14 @@ function confirmation() {
 $tbl_forum_thread = Database :: get_course_table(TABLE_FORUM_THREAD);
 $tbl_attendance   = Database :: get_course_table(TABLE_ATTENDANCE);
 $tbl_grade_links  = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
-$status           = CourseManager::get_user_in_course_status(api_get_user_id(), api_get_course_id());
+$status           = CourseManager::get_user_in_course_status($stud_id, $course_code);
 $filter_confirm_msg = true;
 $filter_warning_msg = true;
 
-$session_id = api_get_session_id();
 ///direct access to one evaluation
 $cats = Category :: load(null, null, $course_code, null, null, $session_id, false); //already init
-if (empty($cats))
-{
+
+if (empty($cats)) {
 	$cats = Category :: load(0, null, $course_code, null, null, $session_id, false);//first time
 	$first_time=1;
 }
@@ -78,10 +82,8 @@ if ( (isset($_GET['selectcat']) && $_GET['selectcat']>0) && (isset($_SESSION['st
 	//Introduction tool: student view
 	Display::display_introduction_section(TOOL_GRADEBOOK, array('ToolbarSet' => 'AssessmentsIntroduction'));
 
-	$category= $_GET['selectcat'];
-	$stud_id=api_get_user_id();
-	$course_code=api_get_course_id();
-	$session_id=api_get_session_id();
+	$category= $_GET['selectcat'];		
+	
 	$cats = Category :: load ($category, null, null, null, null, null, false);
 	$allcat= $cats[0]->get_subcategories($stud_id, $course_code, $session_id);
 	$alleval= $cats[0]->get_evaluations($stud_id);
@@ -98,10 +100,6 @@ if ( (isset($_GET['selectcat']) && $_GET['selectcat']>0) && (isset($_SESSION['st
 
 		//Introduction tool: student view
 		Display::display_introduction_section(TOOL_GRADEBOOK, array('ToolbarSet' => 'AssessmentsIntroduction'));
-
-		$stud_id=api_get_user_id();
-		$course_code=api_get_course_id();
-		$session_id=api_get_session_id();
 		$addparams=array();
 		$cats = Category :: load (0, null, null, null, null, null, false);
 		$allcat= $cats[0]->get_subcategories($stud_id, $course_code, $session_id);
@@ -119,7 +117,7 @@ if ( (isset($_GET['selectcat']) && $_GET['selectcat']>0) && (isset($_SESSION['st
 //this is called when there is no data for the course admin
 if (isset ($_GET['createallcategories'])) {
 	block_students();
-	$coursecat= Category :: get_not_created_course_categories(api_get_user_id());
+	$coursecat= Category :: get_not_created_course_categories($stud_id);
 	if (!count($coursecat) == 0) {
 
 		foreach ($coursecat as $row) {
@@ -127,7 +125,7 @@ if (isset ($_GET['createallcategories'])) {
 			$cat->set_name($row[1]);
 			$cat->set_course_code($row[0]);
 			$cat->set_description(null);
-			$cat->set_user_id(api_get_user_id());
+			$cat->set_user_id($stud_id);
 			$cat->set_parent_id(0);
 			$cat->set_weight(0);
 			$cat->set_visible(0);
@@ -324,6 +322,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 +332,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();
 		}
@@ -351,9 +353,7 @@ if (!empty($course_to_crsind) && !isset($_GET['confirm'])) {
 	if (!isset($_GET['movecat']) && !isset($_GET['moveeval'])) {
 		die ('Error: movecat or moveeval not defined');
 	}
-	$button = '<form name="confirm"
-					 method="post"
-					 action="'.api_get_self() .'?confirm='
+	$button = '<form name="confirm" method="post" action="'.api_get_self() .'?confirm='
 					.(isset($_GET['movecat']) ? '&movecat=' . Security::remove_XSS($_GET['movecat'])
 					: '&moveeval=' . Security::remove_XSS($_GET['moveeval']) )
 					.'&selectcat=' . Security::remove_XSS($_GET['selectcat'])
@@ -573,7 +573,7 @@ else
 if (isset ($_GET['studentoverview'])) {    
     //@todo this code also seems to be deprecated ...    
 	$cats= Category :: load($category);
-	$stud_id= (api_is_allowed_to_create_course() ? null : api_get_user_id());
+	$stud_id= (api_is_allowed_to_create_course() ? null : $stud_id);
 	$allcat= array ();
 	$alleval= $cats[0]->get_evaluations($stud_id, true);
 	$alllink= $cats[0]->get_links($stud_id, true);
@@ -606,10 +606,8 @@ if (isset ($_GET['studentoverview'])) {
     // we have to show the root category and show its subcategories that
     // are inside this course. This is done at the time of calling
     // $cats[0]->get_subcategories(), not at the time of doing Category::load()
-    // $category comes from GET['selectcat']
-    $course_code = api_get_course_id();
-    $session_id = api_get_session_id();
-
+    // $category comes from GET['selectcat']    
+    
     //if $category = 0 (which happens when GET['selectcat'] is undefined)
     // then Category::load() will create a new 'root' category with empty
     // course and session fields in memory (Category::create_root_category())
@@ -627,12 +625,9 @@ if (isset ($_GET['studentoverview'])) {
 	    $cats = Category :: load(null, null, $course_code, null, null, $session_id, false);
         if (empty($cats)) {
             // There is no category for this course+session, so create one
-            $cat= new Category();
-            $course_code = api_get_course_id();
-            $session_id = api_get_session_id();
-            if (!empty($session_id)) {
-            	$my_session_id=api_get_session_id();
-                $s_name = api_get_session_name($my_session_id);
+            $cat= new Category();     
+            if (!empty($session_id)) {            	
+                $s_name = api_get_session_name($session_id);
             	$cat->set_name($course_code.' - '.get_lang('Session').' '.$s_name);
                 $cat->set_session_id($session_id);
             } else {
@@ -640,7 +635,7 @@ if (isset ($_GET['studentoverview'])) {
             }
             $cat->set_course_code($course_code);
             $cat->set_description(null);
-            $cat->set_user_id(api_get_user_id());
+            $cat->set_user_id($stud_id);
             $cat->set_parent_id(0);
             $cat->set_weight(100);
             $cat->set_visible(0);
@@ -657,9 +652,9 @@ if (isset ($_GET['studentoverview'])) {
     //with this fix the teacher only can view 1 gradebook
 	//$stud_id= (api_is_allowed_to_create_course() ? null : api_get_user_id());
     if (api_is_platform_admin()) {
-        $stud_id= (api_is_allowed_to_create_course() ? null : api_get_user_id());
+        $stud_id = (api_is_allowed_to_create_course() ? null : api_get_user_id());
     } else {
-    	$stud_id= api_get_user_id();
+    	$stud_id = $stud_id;
     }
 	$allcat  = $cats[0]->get_subcategories($stud_id, $course_code, $session_id);
 	$alleval = $cats[0]->get_evaluations($stud_id);
@@ -680,7 +675,6 @@ if (isset($_GET['cidReq']) && $_GET['cidReq']!='') {
 } else {
 	$addparams['cidReq']='';
 }
-$gradebooktable = new GradebookTable($cats[0], $allcat, $alleval,$alllink, $addparams);
 $no_qualification = false;
 if (( count($allcat) == 0) && ( count($alleval) == 0 ) && ( count($alllink) == 0 )) {
     $no_qualification = true;
@@ -701,7 +695,7 @@ if ($category != '0') {
 		if (!api_is_allowed_to_edit()) {
 
 			// generating the total score for a course
-			$stud_id         = api_get_user_id();
+			
 			$cats_course     = Category :: load ($category_id, null, null, null, null, null, false);
 			$alleval_course  = $cats_course[0]->get_evaluations($stud_id,true);
 			$alllink_course  = $cats_course[0]->get_links($stud_id,true);
@@ -750,7 +744,7 @@ if ($category != '0') {
 			}
 		} //end hack
 		
-		DisplayGradebook::display_header_gradebook($cats[0], 0, $category_id, $is_course_admin, $is_platform_admin, $simple_search_form, false, true);
+		
 	}
 }
 
@@ -765,14 +759,64 @@ if (api_is_allowed_to_edit(null, true)) {
         if (((isset ($_GET['selectcat']) && $_GET['selectcat']==0) || ((isset($_GET['cidReq']) && $_GET['cidReq']!==''))) || isset($_GET['isStudentView']) && $_GET['isStudentView']=='false') {
             $cats = Category :: load(null, null, $course_code, null, null, $session_id, false);
 			if (!$first_time=1) {
-                DisplayGradebook :: display_reduce_header_gradebook($cats[0],$is_course_admin, $is_platform_admin, $simple_search_form, false, false);
+                
             }
 		}
 	}
 }
 if ($first_time==1 && api_is_allowed_to_edit(null,true)) {
 	echo '<meta http-equiv="refresh" content="0;url='.api_get_self().'?cidReq='.$course_code.'" />';
-} else {
-	$gradebooktable->display();
+} else {		
+	$cats = Category :: load(null, null, $course_code, null, null, $session_id, false); //already init
+	
+	$models = api_get_settings_options('grading_model');
+	$course_grading_model_id = api_get_course_setting('course_grading_model');
+	$grading_model = '';
+	if (!empty($course_grading_model_id)) {
+		foreach($models as $option) {			
+			if (intval($option['id']) == $course_grading_model_id) {
+				$grading_model = $option['value'];
+			}
+		}
+	}
+	
+	$grading_contents = api_grading_model_functions($grading_model, 'to_array');
+	$grading_string   = api_grading_model_functions($grading_model, 'decorate');
+	
+	if (!empty($cats)) {
+		$items = $grading_contents['items'];
+		$i = 0; 
+		foreach ($cats as $cat) {
+			
+			$allcat  = $cat->get_subcategories($stud_id, $course_code, $session_id);
+			$alleval = $cat->get_evaluations($stud_id);
+			$alllink = $cat->get_links($stud_id);
+			
+			if ($cat->get_parent_id() != 0 ) {
+				/*echo Display::tag('h2', $cat->get_name().' ( '.$items[$i]['percentage'].') ');				
+				DisplayGradebook::display_header_gradebook_per_gradebook($cat, 0, $cat->get_id(), $is_course_admin, $is_platform_admin, $simple_search_form, false, true);
+
+				$gradebooktable = new GradebookTable($cat, $allcat, $alleval,$alllink, $addparams);
+				$gradebooktable->display();*/
+				$i++;
+			} else {
+				//This is the father
+				
+				//Create gradebook/add gradebook links
+				DisplayGradebook::display_header_gradebook($cat, 0, $cat->get_id(), $is_course_admin, $is_platform_admin, $simple_search_form, false, true);				
+				
+				if (api_is_allowed_to_edit(null,true)) {
+					//Showing the grading system
+					if (!empty($grading_string)) {
+						Display::display_normal_message($grading_string);
+					}
+				}
+				$gradebooktable = new GradebookTable($cat, $allcat, $alleval,$alllink, $addparams);
+				$gradebooktable->display();
+				
+				//DisplayGradebook :: display_reduce_header_gradebook($cat,$is_course_admin, $is_platform_admin, $simple_search_form, false, false);
+			}
+		}
+	}
 }
 Display :: display_footer();

+ 8 - 14
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);
 	    	}
@@ -156,17 +159,8 @@ class AttendanceLink extends AbstractLink
      * Lazy load function to get the database table of the student publications
      */
     private function get_attendance_table() {
-    	$course_info = Database :: get_course_info($this->get_course_code());
-		$database_name = isset($course_info['db_name']) ? $course_info['db_name'] : '';
-		if ($database_name!='') {
-			if (!isset($this->attendance_table)) {
-				$this->attendance_table = Database :: get_course_table(TABLE_ATTENDANCE, $database_name);
-    		}
-   			return $this->attendance_table;
-		} else {
-			return '';
-		}
-
+    	$this->attendance_table = Database :: get_course_table(TABLE_ATTENDANCE);
+    	return $this->attendance_table;
     }
 
     /**

+ 10 - 11
main/gradebook/lib/be/category.class.php

@@ -97,7 +97,7 @@ class Category implements GradebookItem
 	}
 
 	public function set_parent_id ($parent) {
-		$this->parent = $parent;
+		$this->parent = intval($parent);
 	}
 	/**
      * Filters to int and sets the session ID
@@ -196,7 +196,7 @@ class Category implements GradebookItem
 			$sql .= ' visible = '.intval($visible);
 			$paramcount ++;
 		}
-
+		//echo $sql;
 		$result = Database::query($sql);		
 		if (Database::num_rows($result) > 0) {
 			$allcat = Category::create_category_objects_from_sql_result($result);
@@ -961,22 +961,21 @@ class Category implements GradebookItem
 	public function get_subcategories ($stud_id = null, $course_code = null, $session_id = null) {
 		$cats = array();
 		// 1 student
- 		if (isset($stud_id)) {
+ 		if (isset($stud_id)) { 
 			// special case: this is the root
 			if ($this->id == 0) {
 				return Category::get_root_categories_for_student ($stud_id, $course_code, $session_id);
-			} else {
-				return Category::load(null,null,$course_code,$this->id,
-				api_is_allowed_to_create_course() ? null : 1, $session_id );
+			} else {				
+				return Category::load(null,null,$course_code,$this->id, api_is_allowed_to_create_course() ? null : 1, $session_id );
 			}
 		} else {// all students
 			// course admin
 			if (api_is_allowed_to_create_course() && !api_is_platform_admin()) {
 				// root
 				if ($this->id == 0) {
-					return $this->get_root_categories_for_teacher (api_get_user_id(), $course_code, $session_id, false);
+					return $this->get_root_categories_for_teacher(api_get_user_id(), $course_code, $session_id, false);
 				// inside a course
-                } elseif (!empty($this->course_code)) {
+                } elseif (!empty($this->course_code)) {                	
 					return Category::load(null, null, $this->course_code, $this->id, null, $session_id, false);
                 } elseif (!empty($course_code)) {
                     return Category::load(null, null, $course_code, $this->id, null, $session_id, false);
@@ -1011,9 +1010,9 @@ class Category implements GradebookItem
 			// special case: this is the root
 			if ($this->id == 0) {
 				$evals = Evaluation::get_evaluations_with_result_for_student(0,$stud_id);
-			} else {
-					$evals = Evaluation::load(null,null,$course_code,$this->id,
-					api_is_allowed_to_create_course() ? null : 1);
+			} else { 
+					$evals = Evaluation::load(null,null,$course_code,$this->id, api_is_allowed_to_create_course() ? null : 1);
+					
 			}
 		} else {// all students
 			// course admin

+ 1 - 5
main/gradebook/lib/be/dropboxlink.class.php

@@ -65,11 +65,7 @@ class DropboxLink extends EvalLink
      * Lazy load function to get the dropbox database table
      */
     private function get_dropbox_table () {
-    	if (!isset($this->dropbox_table)) {
-	    	$course_info = Database :: get_course_info($this->get_course_code());
-			$database_name = $course_info['db_name'];
-			$this->dropbox_table = Database :: get_course_table(TABLE_DROPBOX_FILE, $database_name);
-    	}
+    	$this->dropbox_table = Database :: get_course_table(TABLE_DROPBOX_FILE);
    		return $this->dropbox_table;
     }
 

+ 1 - 0
main/gradebook/lib/be/evaluation.class.php

@@ -178,6 +178,7 @@ class Evaluation implements GradebookItem
 			$sql .= ' visible = '.intval($locked);
 			$paramcount ++;
 		}
+		//echo $sql;
 		$result = Database::query($sql);
 		$alleval = Evaluation::create_evaluation_objects_from_sql_result($result);
 		return $alleval;

+ 5 - 14
main/gradebook/lib/be/exerciselink.class.php

@@ -61,11 +61,10 @@ class ExerciseLink 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_main_table(TABLE_MAIN_GRADEBOOK_LINK,$course_info['dbName']);
-		$sql = 'SELECT id,title from '.$this->get_exercise_table().' WHERE active=1 AND session_id='.api_get_session_id().'';
+    	$course_info 		= api_get_course_info($this->course_code);    	
+		$sql = 'SELECT id,title from '.$this->get_exercise_table().' 
+				WHERE c_id = '.$course_info['real_id'].' AND active=1 AND session_id='.api_get_session_id().'';
 		$result = Database::query($sql);
-
 		$cats=array();
 		while ($data=Database::fetch_array($result)) {
 			$cats[] = array ($data['id'], $data['title']);
@@ -214,16 +213,8 @@ class ExerciseLink extends AbstractLink
      * Lazy load function to get the database table of the exercise
      */
     private function get_exercise_table () {
-    	$course_info = Database :: get_course_info($this->get_course_code());
-		$database_name = isset($course_info['db_name']) ? $course_info['db_name'] : '';
-		if ($database_name!='') {
-    		if (!isset($this->exercise_table)) {
-				$this->exercise_table = Database :: get_course_table(TABLE_QUIZ_TEST, $database_name);
-    		}
-   			return $this->exercise_table;
-   		} else {
-   			return '';
-   		}
+    	$this->exercise_table = Database :: get_course_table(TABLE_QUIZ_TEST);
+    	return $this->exercise_table;   		
     }
 
     /**

+ 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);
+    	$tbl_item_property	= Database :: get_course_table(TABLE_ITEM_PROPERTY);
+    	
+		$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)."'";
 	    	}

+ 10 - 21
main/gradebook/lib/be/learnpathlink.class.php

@@ -60,15 +60,12 @@ class LearnpathLink extends AbstractLink
 	 * Generate an array of all learnpaths available.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_all_links()
-    {
+    public function get_all_links() {
     	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_main_table(TABLE_MAIN_GRADEBOOK_LINK,$course_info['dbName']);
-
-		$sql = 'SELECT id,name FROM '.$this->get_learnpath_table().' WHERE session_id = '.api_get_session_id().' ';
+    	$sql = 'SELECT id,name FROM '.$this->get_learnpath_table().' WHERE session_id = '.api_get_session_id().' ';
 		$result = Database::query($sql);
 
 		$cats=array();
@@ -83,12 +80,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 +101,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);
@@ -232,15 +228,8 @@ class LearnpathLink extends AbstractLink
     /**
      * Lazy load function to get the database table of the learnpath
      */
-    private function get_learnpath_table ()
-    {
-    	$course_info = api_get_course_info($this->get_course_code());
-		$database_name = isset($course_info['dbName']) ? $course_info['dbName'] : '';
-		if ($database_name=='') {
-			return '';
-		} elseif (!isset($this->learnpath_table)) {
-			$this->learnpath_table = Database :: get_course_table(TABLE_LP_MAIN, $database_name);
-    	}
+    private function get_learnpath_table () {
+    	$this->learnpath_table = Database :: get_course_table(TABLE_LP_MAIN);
    		return $this->learnpath_table;
     }
 

+ 13 - 6
main/gradebook/lib/be/studentpublicationlink.class.php

@@ -102,11 +102,12 @@ 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);
 
-		$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)) {
+		while ($data = Database::fetch_array($result)) {
 			$cats[] = array ($data['id'], basename($data['url']));
 		}
 		$cats=isset($cats) ? $cats : array();
@@ -118,8 +119,11 @@ 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()."";
+    	$tbl_grade_links = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
+		$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);
@@ -133,7 +137,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);
 

+ 13 - 16
main/gradebook/lib/be/surveylink.class.php

@@ -59,7 +59,8 @@ class SurveyLink extends AbstractLink
     	}
     	$tbl_survey = $this->get_survey_table();
     	$session_id = api_get_session_id();
-    	$sql = 'SELECT survey_id, title, code FROM '.$tbl_survey.' WHERE session_id = '.intval($session_id).'';
+    	$course_id = api_get_course_int_id();
+    	$sql = 'SELECT survey_id, title, code FROM '.$tbl_survey.' WHERE c_id = '.$course_id.' AND session_id = '.intval($session_id).'';
 		$result = Database::query($sql);
 		while ($data = Database::fetch_array($result)) {
 			$links[] = array($data['survey_id'], api_trunc_str($data['code'].': '.self::html_to_text($data['title']), 80));
@@ -107,9 +108,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 +139,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);
@@ -183,16 +188,8 @@ class SurveyLink extends AbstractLink
      * Lazy load function to get the database table of the surveys
      */
     private function get_survey_table() {
-    	$course_info = Database :: get_course_info($this->get_course_code());
-		$database_name = isset($course_info['db_name']) ? $course_info['db_name'] : '';
-		if ($database_name != '') {
-			if (!isset($this->survey_table)) {
-				$this->survey_table = Database :: get_course_table(TABLE_SURVEY, $database_name);
-    		}
-   			return $this->survey_table;
-		} else {
-			return '';
-		}
+    	$this->survey_table = Database :: get_course_table(TABLE_SURVEY);
+   		return $this->survey_table;		
     }
 
     /**

+ 39 - 9
main/gradebook/lib/fe/catform.class.php

@@ -81,19 +81,23 @@ class CatForm extends FormValidator {
 		//check if we are a root category
 		//if so, you can only choose between courses
 		if ($this->category_object->get_parent_id() == '0') {
-			$select = $this->addElement('select','select_course',array(get_lang('PickACourse'),'test'), null);
+			//$select = $this->addElement('select','select_course',array(get_lang('PickACourse'),'test'), null);
 			$coursecat = Category :: get_not_created_course_categories(api_get_user_id());
 			if (count($coursecat)==0) {
-				$select->addoption(get_lang('CourseIndependent'),'COURSEINDEPENDENT','disabled');
+				//$select->addoption(get_lang('CourseIndependent'),'COURSEINDEPENDENT','disabled');
 			} else {
-				$select->addoption(get_lang('CourseIndependent'),'COURSEINDEPENDENT');
+				//$select->addoption(get_lang('CourseIndependent'),'COURSEINDEPENDENT');
 			}
 			//only return courses that are not yet created by the teacher
-
-			foreach($coursecat as $row) {
-				$select->addoption($row[1],$row[0]);
+			if (!empty($coursecat)) {
+				foreach($coursecat as $row) {
+					//$select->addoption($row[1],$row[0]);
+				}
+			} else {
+				//$select->addoption($row[1],$row[0]);
 			}
    			$this->setDefaults(array(
+   				'select_course' => $this->category_object->get_course_code(),
    			   'hid_user_id' => $this->category_object->get_user_id(),
    			   'hid_parent_id' => $this->category_object->get_parent_id()
    			));
@@ -127,15 +131,41 @@ class CatForm extends FormValidator {
 
    	private function build_basic_form() {
 		$this->addElement('hidden', 'zero', 0);
-		//$this->add_textfield('name', get_lang('CategoryName'),true,array('size'=>'54','maxlength'=>'50'));		
-		$this->add_textfield('weight', get_lang('TotalWeight'),true,array('size'=>'4','maxlength'=>'5'));
+		$this->add_textfield('name', get_lang('CategoryName'),true,array('size'=>'54','maxlength'=>'50'));
+
+		$models = api_get_settings_options('grading_model');
+		$course_grading_model_id = api_get_course_setting('course_grading_model');
+		$grading_model = '';
+		if (!empty($course_grading_model_id)) {
+			foreach($models as $option) {			
+				if (intval($option['id']) == $course_grading_model_id) {
+					$grading_model = $option['value'];
+				}
+			}
+		}		
+		
+		$grading_contents = api_grading_model_functions($grading_model, 'to_array');
+		if (!empty($grading_contents)) {
+			
+			$course_code	= api_get_course_id();			
+			$session_id		= api_get_session_id();
+			
+			///direct access to one evaluation
+			$cats  = Category :: load(null, null, $course_code, null, null, $session_id, false); //already init			
+			$count = count($cats) - 1;			
+			$value =  intval($grading_contents['items'][$count]['percentage']);			
+			$this->add_textfield('weight', get_lang('TotalWeight'),true,array('value'=>$value,'size'=>'4','maxlength'=>'5'));			
+			$this->freeze('weight');			
+		}		
+		
+		
 		$this->addElement('static', null, null, '<i>'.get_lang('TotalSumOfWeights').'</i>');
 		
 		$this->add_textfield('certif_min_score', get_lang('CertificateMinScore'),false,array('size'=>'4','maxlength'=>'5'));
    		$this->addElement('hidden','hid_user_id');
    		$this->addElement('hidden','hid_parent_id');
 		$this->addElement('textarea', 'description', get_lang('Description'),array('rows'=>'3','cols' => '34'));
-	//	$this->addElement('checkbox', 'visible',get_lang('Visible'));
+		$this->addElement('checkbox', 'visible',get_lang('Visible'));
 		$this->addElement('style_submit_button', null, get_lang('EditCategory'), 'class="save"');
 		$this->addRule('weight',get_lang('OnlyNumbers'),'numeric');
 		$this->addRule('weight',get_lang('NoDecimals'),'nopunctuation');

+ 211 - 12
main/gradebook/lib/fe/displaygradebook.php

@@ -194,6 +194,191 @@ class DisplayGradebook
 		echo $header;
 	}
 
+	
+	
+	
+	function display_header_gradebook_per_gradebook($catobj, $showtree, $selectcat, $is_course_admin, $is_platform_admin, $simple_search_form, $show_add_qualification = true, $show_add_link = true) {
+
+		//student
+		$status = CourseManager::get_user_in_course_status(api_get_user_id(), api_get_course_id());
+		$objcat = new Category();
+		$course_id = Database::get_course_by_category($selectcat);
+		$message_resource=$objcat->show_message_resource_delete($course_id);
+		
+		if (!$is_course_admin && $status<>1 && $selectcat<>0) {
+			$user_id = api_get_user_id();
+			$user= get_user_info_from_id($user_id);
+		
+			$catcourse= Category :: load($catobj->get_id());
+			$scoredisplay = ScoreDisplay :: instance();
+			$scorecourse = $catcourse[0]->calc_score($user_id);
+		
+			// generating the total score for a course
+			$allevals= $catcourse[0]->get_evaluations($user_id,true);
+			$alllinks= $catcourse[0]->get_links($user_id,true);
+			$evals_links = array_merge($allevals, $alllinks);
+			$item_value=0;
+			$item_total=0;
+			for ($count=0; $count < count($evals_links); $count++) {
+				$item = $evals_links[$count];
+				$score = $item->calc_score($user_id);
+				$my_score_denom=($score[1]==0) ? 1 : $score[1];
+				$item_value+=$score[0]/$my_score_denom*$item->get_weight();
+				$item_total+=$item->get_weight();
+				//$row[] = $scoredisplay->display_score($score,SCORE_DIV_PERCENT);
+			}
+			$item_value = number_format($item_value, 2, '.', ' ');
+			$total_score=array($item_value,$item_total);
+			$scorecourse_display = $scoredisplay->display_score($total_score, SCORE_DIV_PERCENT);
+		
+			$cattotal = Category :: load(0);
+			$scoretotal= $cattotal[0]->calc_score(api_get_user_id());
+			$scoretotal_display = (isset($scoretotal) ? $scoredisplay->display_score($scoretotal, SCORE_PERCENT) : get_lang('NoResultsAvailable'));
+			$scoreinfo = get_lang('StatsStudent') . ' :<b> '.api_get_person_name($user['firstname'], $user['lastname']).'</b><br />';
+			if ((!$catobj->get_id() == '0') && (!isset ($_GET['studentoverview'])) && (!isset ($_GET['search']))) {
+				$scoreinfo.= '<h2>'.get_lang('Total') . ' : ' . $scorecourse_display . '</h2>';
+			}
+		
+			Display :: display_normal_message($scoreinfo, false);
+		}
+		// show navigation tree and buttons?
+		
+		$header = '<div class="actions"><table border=0>';
+		if (($showtree == '1') || (isset ($_GET['studentoverview']))) {
+			$header .= '<tr>';
+			if (!$selectcat == '0') {
+				$header .= '<td style=" "><a href="' . api_get_self() . '?selectcat=' . $catobj->get_parent_id() . '">'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('RootCat'),'','32').'</a></td>';
+			}
+			$header .= '<td style=" ">' . get_lang('CurrentCategory') . '</td>' .
+							'<td style=" "><form name="selector"><select name="selectcat" onchange="document.selector.submit()">';
+			$cats= Category :: load();
+		
+			$tree= $cats[0]->get_tree();
+			unset ($cats);
+				
+			foreach ($tree as $cat) {
+				for ($i= 0; $i < $cat[2]; $i++) {
+					$line .= '&mdash;';
+				}
+				$line=isset($line) ? $line : '';
+				if (isset($_GET['selectcat']) && $_GET['selectcat'] == $cat[0]) {
+					$header .= '<option selected value=' . $cat[0] . '>' . $line . ' ' . $cat[1] . '</option>';
+				} else {
+					$header .= '<option value=' . $cat[0] . '>' . $line . ' ' . $cat[1] . '</option>';
+				}
+				$line= '';
+			}
+			$header .= '</select></form></td>';
+			if (!empty($simple_search_form) && $message_resource===false) {
+				$header .= '<td style="vertical-align: top;">'.$simple_search_form->toHtml().'</td>';
+			} else {
+				$header .= '<td></td>';
+			}
+			if ($is_course_admin && $message_resource===false && $_GET['selectcat']!=0) {
+				/*$header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '"><img src="../img/view_list.gif" alt="' . get_lang('FlatView') . '" /> ' . get_lang('FlatView') . '</a>';
+				 if ($is_course_admin && $message_resource===false) {
+				$header .= '<td style="vertical-align: top;"><a href="gradebook_scoring_system.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() .'"><img src="../img/acces_tool.gif" alt="' . get_lang('ScoreEdit') . '" /> ' . get_lang('ScoreEdit') . '</a>';
+				}*/
+			} elseif (!(isset ($_GET['studentoverview']))) {
+				if ( $message_resource===false ) {
+					//$header .= '<td style="vertical-align: top;"><a href="'.api_get_self().'?'.api_get_cidreq().'&studentoverview=&selectcat=' . $catobj->get_id() . '"><img src="../img/view_list.gif" alt="' . get_lang('FlatView') . '" /> ' . get_lang('FlatView') . '</a>';
+				}
+			} else {
+				$header .= '<td style="vertical-align: top;"><a href="'.api_get_self().'?'.api_get_cidreq().'&studentoverview=&exportpdf=&selectcat=' . $catobj->get_id() . '" target="_blank"><img src="../img/icons/32/.png" alt="' . get_lang('ExportPDF') . '" /> ' . get_lang('ExportPDF') . '</a>';
+			}
+			$header .= '</td></tr>';
+		}
+		$header.='</table></div>';
+		
+		// for course admin & platform admin add item buttons are added to the header
+		$header .= '<div class="actions">';
+		
+		$my_category = $catobj->shows_all_information_an_category($catobj->get_id());
+		$user_id     = api_get_user_id();
+		$course_code = $my_category['course_code'];
+		$status_user = api_get_status_of_user_in_course ($user_id,$course_code);
+		
+		//$header .= '<a href="gradebook_add_cat.php?'.api_get_cidreq().'&selectcat=0"><img src="../img/folder_new.gif" alt="' . get_lang('AddGradebook') . '" /></a></td>';
+		
+		if (api_is_allowed_to_edit(null, true)) {
+			if ($selectcat == '0') {
+				if ($show_add_qualification === true) {
+						
+				}
+				if ($show_add_link) {
+					//$header .= '<td><a href="gradebook_add_eval.php?'.api_get_cidreq().'"><img src="../img/filenew.gif" alt="' . get_lang('NewEvaluation') . '" /> ' . get_lang('NewEvaluation') . '</a>';
+				}
+			} else {
+				if ($show_add_qualification === true && $message_resource===false) {
+					//$header .= '<a href="gradebook_add_cat.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '" ><img src="../img/folder_new.gif" alt="' . get_lang('NewSubCategory') . '" align="absmiddle" /> ' . get_lang('NewSubCategory') . '</a></td>';
+				}
+				$my_category=$catobj->shows_all_information_an_category($catobj->get_id());
+				$my_api_cidreq = api_get_cidreq();
+				if ($my_api_cidreq=='') {
+					$my_api_cidreq='cidReq='.$my_category['course_code'];
+				}
+				if ($show_add_link && !$message_resource) {
+					//$header .= '<td><a href="gradebook_add_eval.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '" >'.Display::return_icon('new_evaluation.png', get_lang('NewEvaluation'),'','32').'</a>';
+					$cats= Category :: load($selectcat);
+					if ($cats[0]->get_course_code() != null && !$message_resource) {
+						//$header .= '<td><a href="gradebook_add_link.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '"><img src="../img/link.gif" alt="' . get_lang('MakeLink') . '" align="absmiddle" /> ' . get_lang('MakeLink') . '</a>';
+						//$header .= '<td><a href="gradebook_add_link.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('new_online_evaluation.png', get_lang('MakeLink'),'','32').'</a>';
+		
+					} else {
+					//	$header .= '<td><a href="gradebook_add_link_select_course.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('new_online_evaluation.png', get_lang('MakeLink'),'','32').'</a>';
+					}
+				}
+		
+				if (!$message_resource) {
+					$myname = $catobj->shows_all_information_an_category($catobj->get_id());
+		
+					$my_course_id=api_get_course_id();
+					$my_file= substr($_SESSION['gradebook_dest'],0,5);
+		
+					$header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('stats.png', get_lang('FlatView'),'','32').'</a>';
+					$header .= '<td style="vertical-align: top;"><a href="gradebook_display_certificate.php?'.$my_api_cidreq.'&amp;cat_id='.(int)$_GET['selectcat'].'">'.Display::return_icon('certificate_list.png', get_lang('GradebookSeeListOfStudentsCertificates'),'','32').'</a>';
+						
+					$visibility_icon    = ($catobj->is_visible() == 0) ? 'invisible' : 'visible';
+					$visibility_command = ($catobj->is_visible() == 0) ? 'set_visible' : 'set_invisible';
+					 
+					//Right icons
+					$modify_icons  = '<a href="gradebook_edit_cat.php?editcat='.$catobj->get_id().'&cidReq='.$catobj->get_course_code().'">'.Display::return_icon('edit.png', get_lang('Edit'),'','32').'</a>';
+					//$modify_icons .= '<a href="../document/document.php?curdirpath=/certificates&'.$my_api_cidreq.'&origin=gradebook&selectcat=' . $catobj->get_id() . '">'.
+					Display::return_icon('certificate.png', get_lang('AttachCertificate'),'','32').'</a>';
+		
+					//$modify_icons .= '<a href="gradebook_edit_all.php?id_session='.intval($_SESSION['id_session']).'&amp;'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('percentage.png', get_lang('EditAllWeights'),'','32').'</a>';
+		
+					//$modify_icons .= '<a href="gradebook_scoring_system.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() .'">'.Display::return_icon('ranking.png', get_lang('ScoreEdit'),'','32').'</a>';
+		
+					//hide or delete are not options available
+					//$modify_icons .= '&nbsp;<a  href="' . api_get_self() . '?visiblecat=' . $catobj->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=0 ">'.Display::return_icon($visibility_icon.'.png', get_lang('Visible'),'','32').'</a>';
+					if ($catobj->get_name() != api_get_course_id()) {
+						$modify_icons .= '&nbsp;<a  href="' . api_get_self() . '?deletecat=' . $catobj->get_id() . '&amp;selectcat=0&amp;cidReq='.$catobj->get_course_code().'" onclick="return confirmation();">'.Display::return_icon('delete.png', get_lang('DeleteAll'),'','32').'</a>';
+					}
+					 
+					$header .= Display::div($modify_icons, array('class'=>'right'));
+						
+				}
+			}
+		} elseif (isset ($_GET['search'])) {
+			$header .= '<b>'.get_lang('SearchResults').' :</b>';
+		}
+		$header .= '</div>';
+		echo $header;		
+		/*
+		if (api_is_allowed_to_edit(null, true)) {
+			$weight = ((intval($catobj->get_weight())>0) ? $catobj->get_weight() : 0);
+			$weight  = Display::tag('h3', get_lang('TotalWeight').' : '.$weight);
+			$min_certification = (intval($catobj->get_certificate_min_score()>0) ? $catobj->get_certificate_min_score() : 0);
+			$min_certification = Display::tag('h3', get_lang('CertificateMinScore').' : '.$min_certification);
+			//@todo show description
+			$description       = (($catobj->get_description() == "" || is_null($catobj->get_description())) ? '' : '<strong>'.get_lang('GradebookDescriptionLog').'</strong>'.': '.$catobj->get_description());
+			Display::display_normal_message($weight.$min_certification, false);
+    		if (!empty($description)) {
+				echo Display::div($description, array());
+			}
+		}*/
+	}
 	/**
 	 * Displays the header for the gradebook containing the navigation tree and links
 	 * @param category_object $currentcat
@@ -208,7 +393,6 @@ class DisplayGradebook
 		//student
 		$status = CourseManager::get_user_in_course_status(api_get_user_id(), api_get_course_id());
 		$objcat = new Category();
-		//$objdat=new Database();
 		$course_id = Database::get_course_by_category($selectcat);
 		$message_resource=$objcat->show_message_resource_delete($course_id);
 
@@ -216,7 +400,7 @@ class DisplayGradebook
 			$user_id = api_get_user_id();
 			$user= get_user_info_from_id($user_id);
 
-			$catcourse= Category :: load($catobj->get_id());
+			$catcourse= Category::load($catobj->get_id());
 			$scoredisplay = ScoreDisplay :: instance();
 			$scorecourse = $catcourse[0]->calc_score($user_id);
 
@@ -234,30 +418,39 @@ class DisplayGradebook
 				$item_total+=$item->get_weight();
 				//$row[] = $scoredisplay->display_score($score,SCORE_DIV_PERCENT);
 			}
+			$children = $catcourse[0]->get_subcategories(api_get_user_id(), api_get_course_id(), api_get_session_id());
+			$count = 1;
+			if (!empty($children)) {
+				$count = count($children);
+			}
+			$item_value = $item_value/$count;
+			$item_total = $item_total / $count;
+			
 			$item_value = number_format($item_value, 2, '.', ' ');
-			$total_score=array($item_value,$item_total);
+			$total_score = array($item_value, $item_total);
+			
 			$scorecourse_display = $scoredisplay->display_score($total_score, SCORE_DIV_PERCENT);
 
 			$cattotal = Category :: load(0);
 			$scoretotal= $cattotal[0]->calc_score(api_get_user_id());
 			$scoretotal_display = (isset($scoretotal) ? $scoredisplay->display_score($scoretotal, SCORE_PERCENT) : get_lang('NoResultsAvailable'));
-			$scoreinfo = get_lang('StatsStudent') . ' :<b> '.api_get_person_name($user['firstname'], $user['lastname']).'</b><br />';
+			//$scoreinfo = get_lang('StatsStudent') . ' :<b> '.api_get_person_name($user['firstname'], $user['lastname']).'</b><br />';
 			if ((!$catobj->get_id() == '0') && (!isset ($_GET['studentoverview'])) && (!isset ($_GET['search']))) {
 				$scoreinfo.= '<h2>'.get_lang('Total') . ' : ' . $scorecourse_display . '</h2>';
 			}
-			//$scoreinfo.= '<br />'.get_lang('Total') . ' : <b>' . $scoretotal_display . '</b>';			
 			Display :: display_normal_message($scoreinfo, false);
 		}
 		// show navigation tree and buttons?
 		
 		$header = '<div class="actions"><table border=0>';
+		
 		if (($showtree == '1') || (isset ($_GET['studentoverview']))) {
 			$header .= '<tr>';
 			if (!$selectcat == '0') {
 				$header .= '<td style=" "><a href="' . api_get_self() . '?selectcat=' . $catobj->get_parent_id() . '">'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('RootCat'),'','32').'</a></td>';
 			}
-			$header .= '<td style=" ">' . get_lang('CurrentCategory') . '</td>' .
-					'<td style=" "><form name="selector"><select name="selectcat" onchange="document.selector.submit()">';
+			$header .= '<td>' . get_lang('CurrentCategory') . '</td>' .
+					'<td><form name="selector"><select name="selectcat" onchange="document.selector.submit()">';
 			$cats= Category :: load();
 
 			$tree= $cats[0]->get_tree();
@@ -291,7 +484,8 @@ class DisplayGradebook
 					//$header .= '<td style="vertical-align: top;"><a href="'.api_get_self().'?'.api_get_cidreq().'&studentoverview=&selectcat=' . $catobj->get_id() . '"><img src="../img/view_list.gif" alt="' . get_lang('FlatView') . '" /> ' . get_lang('FlatView') . '</a>';
 				}
 			} else {
-				$header .= '<td style="vertical-align: top;"><a href="'.api_get_self().'?'.api_get_cidreq().'&studentoverview=&exportpdf=&selectcat=' . $catobj->get_id() . '" target="_blank"><img src="../img/icons/32/.png" alt="' . get_lang('ExportPDF') . '" /> ' . get_lang('ExportPDF') . '</a>';
+				$header .= '<td style="vertical-align: top;"><a href="'.api_get_self().'?'.api_get_cidreq().'&studentoverview=&exportpdf=&selectcat=' . $catobj->get_id() . '" target="_blank">
+							<img src="../img/icons/32/.png" alt="' . get_lang('ExportPDF') . '" /> ' . get_lang('ExportPDF') . '</a>';
 			}
 			$header .= '</td></tr>';
 		}
@@ -305,10 +499,13 @@ class DisplayGradebook
 		$course_code = $my_category['course_code'];
 		$status_user = api_get_status_of_user_in_course ($user_id,$course_code);
 		
+		
 		if (api_is_allowed_to_edit(null, true)) {
+			$header .= '<a href="gradebook_add_cat.php?'.api_get_cidreq().'&selectcat='.$catobj->get_id().'"><img src="../img/icons/32/new_folder.png" alt="' . get_lang('AddGradebook') . '" /></a></td>';			
+			
 			if ($selectcat == '0') {
                 if ($show_add_qualification === true) {
-				   // $header .= '<a href="gradebook_add_cat.php?'.api_get_cidreq().'&selectcat=0"><img src="../img/folder_new.gif" alt="' . get_lang('NewCategory') . '" /> ' . get_lang('NewCategory') . '</a></td>';
+				   
                 }
                 if ($show_add_link) {
 				    //$header .= '<td><a href="gradebook_add_eval.php?'.api_get_cidreq().'"><img src="../img/filenew.gif" alt="' . get_lang('NewEvaluation') . '" /> ' . get_lang('NewEvaluation') . '</a>';
@@ -340,13 +537,14 @@ class DisplayGradebook
                 	$my_course_id=api_get_course_id();
                 	$my_file= substr($_SESSION['gradebook_dest'],0,5);
                 		
-					$header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('stats.png', get_lang('FlatView'),'','32').'</a>';					
-					$header .= '<td style="vertical-align: top;"><a href="gradebook_display_certificate.php?'.$my_api_cidreq.'&amp;cat_id='.(int)$_GET['selectcat'].'">'.Display::return_icon('certificate_list.png', get_lang('GradebookSeeListOfStudentsCertificates'),'','32').'</a>';
+					//$header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('stats.png', get_lang('FlatView'),'','32').'</a>';					
+					//$header .= '<td style="vertical-align: top;"><a href="gradebook_display_certificate.php?'.$my_api_cidreq.'&amp;cat_id='.(int)$_GET['selectcat'].'">'.Display::return_icon('certificate_list.png', get_lang('GradebookSeeListOfStudentsCertificates'),'','32').'</a>';
 					
 					$visibility_icon    = ($catobj->is_visible() == 0) ? 'invisible' : 'visible';
 			        $visibility_command = ($catobj->is_visible() == 0) ? 'set_visible' : 'set_invisible';
 			        
 					//Right icons
+					
             		$modify_icons  = '<a href="gradebook_edit_cat.php?editcat=' . $catobj->get_id() . ' &amp;cidReq='.$catobj->get_course_code().'">'.Display::return_icon('edit.png', get_lang('Edit'),'','32').'</a>';
             		$modify_icons .= '<a href="../document/document.php?curdirpath=/certificates&'.$my_api_cidreq.'&origin=gradebook&selectcat=' . $catobj->get_id() . '">'.
             							Display::return_icon('certificate.png', get_lang('AttachCertificate'),'','32').'</a>';
@@ -369,6 +567,7 @@ class DisplayGradebook
 		$header .= '</div>';
 		echo $header;
 		
+		
 		if (api_is_allowed_to_edit(null, true)) {
             $weight = ((intval($catobj->get_weight())>0) ? $catobj->get_weight() : 0);                        			
     		$weight            = Display::tag('h3', get_lang('TotalWeight').' : '.$weight);    		
@@ -381,7 +580,7 @@ class DisplayGradebook
     		if (!empty($description)) {
     		    echo Display::div($description, array());
     		}
-		}		
+		}
 	}
 
 	function display_reduce_header_gradebook($catobj,$is_course_admin, $is_platform_admin, $simple_search_form, $show_add_qualification = true, $show_add_link = true) {

+ 29 - 5
main/gradebook/lib/fe/evalform.class.php

@@ -370,8 +370,9 @@ class EvalForm extends FormValidator
 	 * Builds a form to add an evaluation
 	 */
 	protected function build_add_form() {
-		$this->setDefaults(array (
-		'hid_user_id' => $this->evaluation_object->get_user_id(), 'hid_category_id' => $this->evaluation_object->get_category_id(), 'hid_course_code' => $this->evaluation_object->get_course_code(), 'created_at' => api_get_utc_datetime()));
+		$this->setDefaults(array (	'hid_user_id' => $this->evaluation_object->get_user_id(), 
+									'hid_category_id' => $this->evaluation_object->get_category_id(), 
+									'hid_course_code' => $this->evaluation_object->get_course_code(), 'created_at' => api_get_utc_datetime()));
 		$this->build_basic_form(0);
 		if ($this->evaluation_object->get_course_code() == null) {
 			$this->addElement('checkbox', 'adduser', get_lang('AddUserToEval'));
@@ -384,8 +385,14 @@ class EvalForm extends FormValidator
 	 * Builds a form to edit an evaluation
 	 */
 	protected function build_editing_form() {
-		$this->setDefaults(array (
-		'hid_id' => $this->evaluation_object->get_id(), 'name' => $this->evaluation_object->get_name(), 'description' => $this->evaluation_object->get_description(), 'hid_user_id' => $this->evaluation_object->get_user_id(), 'hid_course_code' => $this->evaluation_object->get_course_code(), 'hid_category_id' => $this->evaluation_object->get_category_id(), 'created_at' => api_get_utc_datetime($this->evaluation_object->get_date()), 'weight' => $this->evaluation_object->get_weight(), 'max' => $this->evaluation_object->get_max(), 'visible' => $this->evaluation_object->is_visible()));
+		$this->setDefaults(array (	'hid_id' => $this->evaluation_object->get_id(), 
+									'name' 	 => $this->evaluation_object->get_name(), 
+									'description' => $this->evaluation_object->get_description(), 
+									'hid_user_id' => $this->evaluation_object->get_user_id(), 
+									'hid_course_code' => $this->evaluation_object->get_course_code(), 
+									'hid_category_id' => $this->evaluation_object->get_category_id(), 
+									'created_at' => api_get_utc_datetime($this->evaluation_object->get_date()), 
+									'weight' => $this->evaluation_object->get_weight(), 'max' => $this->evaluation_object->get_max(), 'visible' => $this->evaluation_object->is_visible()));
 		$id_current=isset($this->id)?$this->id :null;
 		$this->addElement('hidden', 'hid_id',$id_current);
 		$this->build_basic_form(1);
@@ -404,7 +411,7 @@ class EvalForm extends FormValidator
 		$this->addElement('header', '', $form_title);
 		$this->addElement('hidden', 'zero', 0);
 		$this->addElement('hidden', 'hid_user_id');
-		$this->addElement('hidden', 'hid_category_id');
+		//$this->addElement('hidden', 'hid_category_id');
 		$this->addElement('hidden', 'hid_course_code');
 		$this->add_textfield('name', get_lang('EvaluationName'), true, array (
 			'size' => '54',
@@ -444,6 +451,23 @@ class EvalForm extends FormValidator
 		$this->addRule(array ('weight', 'zero'), get_lang('NegativeValue'), 'compare', '>=');
 		$this->addRule('max', get_lang('OnlyNumbers'), 'numeric');
 		$this->addRule(array ('max', 'zero'), get_lang('NegativeValue'), 'compare', '>=');
+		
+		$select_gradebook = $this->addElement('select', 'hid_category_id', get_lang('SelectGradebook'));
+		
+		$all_categories = Category :: load();
+		
+		if (!empty($all_categories)) {
+			foreach($all_categories as $my_cat) {
+				if ($my_cat->get_course_code() == api_get_course_id()) {
+					if ($my_cat->get_parent_id() == 0 ) {
+						$select_gradebook->addoption(get_lang('Default'), $my_cat->get_id());
+					} else {
+						$select_gradebook->addoption($my_cat->get_name(), $my_cat->get_id());
+					}
+				}			
+			}
+		}
+		
 	}
 	function display() {
 		parent :: display();

+ 125 - 26
main/gradebook/lib/fe/gradebooktable.class.php

@@ -32,32 +32,38 @@ class GradebookTable extends SortableTable {
     	parent :: __construct ('gradebooklist', null, null, (api_is_allowed_to_create_course()?1:0));
 		$this->evals_links = array_merge($evals, $links);
 		$this->currentcat = $currentcat;
+		
 		$this->datagen = new GradebookDataGenerator($cats, $evals, $links);
+				
 		if (isset($addparams)) {
 			$this->set_additional_parameters($addparams);
 		}
+		
 		$column= 0;
 		if (api_is_allowed_to_edit(null, true)) {
 			$this->set_header($column++,'','','width="25px"');
 		}
+		
 		$this->set_header($column++, get_lang('Type'),'','width="35px"');
-		$this->set_header($column++, get_lang('Name'));
-		$this->set_header($column++, get_lang('Description'));
+		$this->set_header($column++, get_lang('Name'), false);
+		//$this->set_header($column++, get_lang('Description'));
 
 		if (api_is_allowed_to_edit(null, true)) {
 			$this->set_header($column++, get_lang('Weight'),'','width="50px"');
 		} else {
 			if (empty($_GET['selectcat']) ) {
-				$this->set_header($column++, get_lang('Evaluation'));
+				$this->set_header($column++, get_lang('Evaluation'), false);
 			} else {
-			    $this->set_header($column++, get_lang('Weight'));
+			    $this->set_header($column++, get_lang('Weight'), false);
 			}
 		}
+		
 		if (api_is_allowed_to_edit(null, true)) {
-			$this->set_header($column++, get_lang('CreationDate'),true, 'width="100px"');
+			//$this->set_header($column++, get_lang('CreationDate'),true, 'width="100px"');
 		} elseif (($status<>1)  && !api_is_allowed_to_create_course() && (!isset($_GET['selectcat']) || $_GET['selectcat']==0)) {
-			$this->set_header($column++, get_lang('Date'),true, 'width="100px"');
+			//$this->set_header($column++, get_lang('Date'),true, 'width="100px"');
 		}
+		
 		//admins get an edit column
 		if (api_is_allowed_to_edit(null, true)) {
 			$this->set_header($column++, get_lang('Modify'), false, 'width="120px"');
@@ -70,10 +76,10 @@ class GradebookTable extends SortableTable {
 	 	    if (empty($_GET['selectcat']) &&  !api_is_allowed_to_create_course()) {
 			    $this->set_header($column++, get_lang('Certificates'),false);
 	 	    } else {
-	 	    	$evals_links = array_merge($evals, $links);
-	 	    	if(count($evals_links)>0) {
-             	    $this->set_header($column++, get_lang('Results'), false);
-             	}
+	 	    	//$evals_links = array_merge($evals, $links);	 	    	
+	 	    	//if (count($evals_links)>0) {
+             	    //$this->set_header($column++, get_lang('Results'), false);
+             	//}
 	 	    }
 		}
     }
@@ -114,27 +120,36 @@ class GradebookTable extends SortableTable {
 				$sorting = GradebookDataGenerator :: GDG_SORT_DATE;
 				break;
 		}
+		
 		if ($this->direction == 'DESC') {
 			$sorting |= GradebookDataGenerator :: GDG_SORT_DESC;
 		} else {
 			$sorting |= GradebookDataGenerator :: GDG_SORT_ASC;
-		}
+		}		
+		
+		$sorting = GradebookDataGenerator :: GDG_SORT_DATE;
+		$sorting |= GradebookDataGenerator :: GDG_SORT_DESC;
+		
 		//status of user in course
 	    $user_id     = api_get_user_id();
 		$course_code = api_get_course_id();
-		$status_user = api_get_status_of_user_in_course ($user_id,$course_code);
+		$status_user = api_get_status_of_user_in_course($user_id, $course_code);
 		$data_array  = $this->datagen->get_data($sorting, $from, $this->per_page);
+		
 
 		// generate the data to display
 		$sortable_data = array();
-		$weight_total_links = 0;
+		$weight_total_links = 0;		
+		
 
-		foreach ($data_array as $data) {
-            // list of items inside the gradebook (exercises, lps, fora, etc)
-			$row  = array ();
+		foreach ($data_array as $data) {			
+			
+            // list of items inside the gradebook (exercises, lps, forums, etc)
+			$row  = array();
 			$item = $data[0];
-			$id   = $item->get_id();   
 			
+			$id   = $item->get_id();							
+						
 			//if the item is invisible, wrap it in a span with class invisible
 			$invisibility_span_open  = (api_is_allowed_to_create_course() && $item->is_visible() == '0') ? '<span class="invisible">' : '';
 			$invisibility_span_close = (api_is_allowed_to_create_course() && $item->is_visible() == '0') ? '</span>' : '';
@@ -142,22 +157,31 @@ class GradebookTable extends SortableTable {
 			if (api_is_allowed_to_edit(null, true)) {
 				$row[] = $this->build_id_column($item);
 			}
-
 			$row[] = $this->build_type_column($item);
-			$row[] = $invisibility_span_open.$this->build_name_link ($item) . $invisibility_span_close;
-			$row[] = $invisibility_span_open.$data[2] . $invisibility_span_close;
+			
+			//Name
+			if (get_class($item) == 'Category') {
+				$row[] = $invisibility_span_open.'<h2>'.$item->get_name().'</h2>'.$invisibility_span_close;
+			} else {
+				$row[] = $invisibility_span_open.$this->build_name_link ($item) . $invisibility_span_close;
+			}
+			
+			//Description
+			//$row[] = $invisibility_span_open.$data[2] . $invisibility_span_close;			
+			
+			//Weight
+			$row[] = $invisibility_span_open .'<h3>'.$data[3] .'% </h3>'.$invisibility_span_close;			
 			if (api_is_allowed_to_edit(null, true)) {
-				$row[] = $invisibility_span_open . $data[3] . $invisibility_span_close;
 				$weight_total_links += intval($data[3]);
 			} else {
 				$cattotal   = Category :: load($_GET['selectcat']);
                 $scoretotal = $cattotal[0]->calc_score(api_get_user_id());                    
                 $item_value = $scoretotal[0];
-                $item_value = number_format($item_value, 2, '.', ' ');
-			   	$row[] = $invisibility_span_open . $data[3] . $invisibility_span_close;			  			   	
+                $item_value = number_format($item_value, 2, '.', ' ');			   				  			   	
 			}
-			
-    		$row[] = $invisibility_span_open.$data[4].$invisibility_span_close;
+						
+			//Date
+    		//$row[] = $invisibility_span_open.$data[4].$invisibility_span_close;
 
 			//Admins get an edit column
 			if (api_is_allowed_to_edit(null, true)) {
@@ -169,13 +193,88 @@ class GradebookTable extends SortableTable {
 			} else {
 				//students get the results and certificates columns
 				if (count($this->evals_links)>0 && $status_user!=1 ) {
-					$value_data=isset($data[5]) ? $data[5] : null;
+					$value_data = isset($data[4]) ? $data[4] : null;
+					
 					if (!is_null($value_data)) {
 						$row[] = $value_data;
 					}
 				}    
 			}
 			$sortable_data[] = $row;
+						
+			// Loading childrens
+			
+			if (get_class($item) == 'Category') {
+				$stud_id		= api_get_user_id();
+				$course_code	= api_get_course_id();
+				$session_id		= api_get_session_id();
+				
+				$cats = Category :: load ($item->get_id(), null, null, null, null, null, true);
+			
+				$allcat  = $cats[0]->get_subcategories($stud_id, $course_code, $session_id);				
+				$alleval = $cats[0]->get_evaluations($stud_id);			
+				$alllink = $cats[0]->get_links($stud_id);
+				
+				$sub_cat_info = new GradebookDataGenerator($allcat, $alleval, $alllink);
+				$data_array  =  $sub_cat_info->get_data($sorting, $from, $this->per_page);				
+				
+				foreach ($data_array as $data) {
+					$row  = array();
+					$item = $data[0];
+					$id   = $item->get_id();							
+								
+					//if the item is invisible, wrap it in a span with class invisible
+					$invisibility_span_open  = (api_is_allowed_to_create_course() && $item->is_visible() == '0') ? '<span class="invisible">' : '';
+					$invisibility_span_close = (api_is_allowed_to_create_course() && $item->is_visible() == '0') ? '</span>' : '';
+		
+					if (api_is_allowed_to_edit(null, true)) {
+						$row[] = $this->build_id_column($item);
+					}
+					$row[] = $this->build_type_column($item);
+					
+					//Name
+					$row[] = $invisibility_span_open."&nbsp;&nbsp;&nbsp;  ".$this->build_name_link($item) . $invisibility_span_close;
+					
+					//Description
+					//$row[] = $invisibility_span_open.$data[2] . $invisibility_span_close;			
+					
+					//Weight
+					$row[] = $invisibility_span_open . $data[3] .'%'.$invisibility_span_close;
+					
+					if (api_is_allowed_to_edit(null, true)) {						
+						//$weight_total_links += intval($data[3]);
+					} else {
+						$cattotal   = Category :: load($_GET['selectcat']);
+		                $scoretotal = $cattotal[0]->calc_score(api_get_user_id());                    
+		                $item_value = $scoretotal[0];
+		                $item_value = number_format($item_value, 2, '.', ' ');					   				  			   	
+					}
+					
+					//Date
+		    		//$row[] = $invisibility_span_open.$data[4].$invisibility_span_close;
+		
+					//Admins get an edit column
+					if (api_is_allowed_to_edit(null, true)) {
+						$cat = new Category();
+						$show_message = $cat->show_message_resource_delete($item->get_course_code());
+						if ($show_message===false) {
+							$row[] = $this->build_edit_column($item); 
+						}
+					} else {
+						//students get the results and certificates columns
+						$eval_n_links = array_merge($alleval, $alllink);
+						
+						if (count($eval_n_links)> 0 && $status_user!=1 ) {
+							$value_data = isset($data[5]) ? $data[5] : null;							
+							if (!is_null($value_data)) {
+								$row[] = $value_data;
+							}
+						}    
+					}					
+					$sortable_data[] = $row;
+				}
+				//add elements			
+			}
 		}
 
 		// warning messages

+ 22 - 15
main/gradebook/lib/fe/linkaddeditform.class.php

@@ -38,44 +38,36 @@ class LinkAddEditForm extends FormValidator
 			$link = $link_object;
 		} elseif (isset ($link_type) && isset ($category_object)) {
 			$link = LinkFactory :: create ($link_type);
+			$link->set_course_code(api_get_course_id());
+			/*
 			$cc = $category_object->get_course_code();
 			if (empty($cc) && !empty($_GET['course_code'])) {
 				$link->set_course_code(Database::escape_string($_GET['course_code']));
 			} else {
 				$link->set_course_code($category_object->get_course_code());
-			}
+			}*/
 		} else {
 			die ('LinkAddEditForm error: define link_type/category_object or link_object');
 		}
 		$defaults = array();
 		$this->addElement('hidden', 'zero', 0);
 
-		if (!empty($_GET['editlink']))
-		{
+		if (!empty($_GET['editlink'])) {
 			$this->addElement('header', '', get_lang('EditLink'));
 		}
 
 		// ELEMENT: name
 		if ($form_type == self :: TYPE_ADD || $link->is_allowed_to_change_name()) {
 			if ($link->needs_name_and_description()) {
-				$this->add_textfield('name',
-									  get_lang('Name'),
-									  true,
-									  array('size'=>'40',
-											'maxlength'=>'40'));
+				$this->add_textfield('name', get_lang('Name'), true, array('size'=>'40', 'maxlength'=>'40'));
 			} else {
-				$select = $this->addElement('select',
-											'select_link',
-											get_lang('ChooseItem'));
+				$select = $this->addElement('select', 'select_link', get_lang('ChooseItem'));				
 				foreach ($link->get_all_links() as $newlink) {
 					$select->addoption($newlink[1],$newlink[0]);
 				}
 			}
 		} else {
-			$this->addElement('static',
-								'label',
-								get_lang('Name'),
-								$link->get_name().' ['.$link->get_type_name().']');
+			$this->addElement('static','label',get_lang('Name'), $link->get_name().' ['.$link->get_type_name().']');
 			$this->addElement('hidden','name_link',$link->get_name(),array('id'=>'name_link'));
 		}
 
@@ -120,6 +112,21 @@ class LinkAddEditForm extends FormValidator
 		if ($form_type == self :: TYPE_EDIT) {
 			$defaults['visible'] = $link->is_visible();
 		}
+		
+		$select_gradebook = $this->addElement('select', 'select_gradebook', get_lang('SelectGradebook'));
+		
+		if (!empty($category_object)) {
+			foreach($category_object as $my_cat) {
+				if ($my_cat->get_course_code() == api_get_course_id()) {
+					if ($my_cat->get_parent_id() == 0 ) {
+						$select_gradebook->addoption(get_lang('Default'), $my_cat->get_id());
+					} else {
+						$select_gradebook->addoption($my_cat->get_name(), $my_cat->get_id());
+					}
+				}			
+			}
+		}
+		
 		// ELEMENT: add results
 		if ($form_type == self :: TYPE_ADD && $link->needs_results()) {
 			$this->addElement('checkbox', 'addresult', get_lang('AddResult'));

+ 5 - 9
main/gradebook/lib/fe/linkform.class.php

@@ -74,14 +74,10 @@ class LinkForm extends FormValidator
 
 	protected function build_create() {
 		$this->addElement('header', '', get_lang('MakeLink'));
-		$select = $this->addElement('select',
-									'select_link',
-									get_lang('ChooseLink'),
-									null,
-									array('onchange' => 'document.create_link.submit()'));
+		$select = $this->addElement('select', 'select_link', get_lang('ChooseLink'), null, array('onchange' => 'document.create_link.submit()'));
 
 		$linktypes = LinkFactory :: get_all_types();
-
+		
 		$select->addoption('['.get_lang('ChooseLink').']', 0);
 
 		$cc = $this->category_object->get_course_code();
@@ -92,13 +88,13 @@ class LinkForm extends FormValidator
 			} elseif(!empty($_GET['course_code'])) {
 				$link->set_course_code(Database::escape_string($_GET['course_code']));
 			}
+			
 			// disable this element if the link works with a dropdownlist
 			// and if there are no links left
-			if (!$link->needs_name_and_description()
-				&& count($link->get_all_links()) == '0') {
+			if (!$link->needs_name_and_description() && count($link->get_all_links()) == '0') {
 				$select->addoption($link->get_type_name(), $linktype, 'disabled');
 			} else {
-					$select->addoption($link->get_type_name(), $linktype);
+				$select->addoption($link->get_type_name(), $linktype);
 			}
 		}
 

+ 7 - 8
main/gradebook/lib/gradebook_data_generator.class.php

@@ -97,14 +97,13 @@ class GradebookDataGenerator
 			$row[] = $item->get_description();
 			$row[] = $item->get_weight();
 			if (api_is_allowed_to_edit(null, true)) {
-				$row[] = $this->build_date_column($item);
-			}
-			
-			if (count($this->evals_links)>0) {
-				if (!api_is_allowed_to_create_course() || $status_user != 1 ) {				    
+				//$row[] = $this->build_date_column($item);
+			}			
+			if (count($this->evals_links) > 0) {
+				if (!api_is_allowed_to_create_course() || $status_user != 1 ) {
 					$row[] = $this->build_result_column($item, $ignore_score_color);
 				}
-			}
+			}			
 		    $data[] = $row;
         }
 		return $data;
@@ -180,9 +179,9 @@ class GradebookDataGenerator
 
 	private function build_result_column($item, $ignore_score_color) {
 		$scoredisplay = ScoreDisplay :: instance();
-		$score = $item->calc_score(api_get_user_id());
+		$score 	     = $item->calc_score(api_get_user_id());
 		
-        if (!empty($score)) {
+        if (!empty($score)) {        	
     		switch ($item->get_item_type()) {
     			// category
     			case 'C' :

+ 27 - 7
main/gradebook/lib/gradebook_functions.inc.php

@@ -202,14 +202,18 @@ function build_edit_icons_cat($cat, $selectcat) {
 		$visibility_icon= ($cat->is_visible() == 0) ? 'invisible' : 'visible';
 		$visibility_command= ($cat->is_visible() == 0) ? 'set_visible' : 'set_invisible';
 		$modify_icons= '<a href="gradebook_edit_cat.php?editcat=' . $cat->get_id() . ' &amp;cidReq='.$cat->get_course_code().'">'.Display::return_icon('edit.png', get_lang('Modify'),'','22').'</a>';
-		$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletecat=' . $cat->get_id() . '&amp;selectcat=' . $selectcat . '&amp;cidReq='.$cat->get_course_code().'" onclick="return confirmation();">'.Display::return_icon('delete.png', get_lang('DeleteAll'),'','22').'</a>';
+		
+		$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visiblecat=' . $cat->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=' . $selectcat . ' ">'.Display::return_icon($visibility_icon.'.png', get_lang('Visible'),'','22').'</a>';
+		
 		//no move ability for root categories
 		if ($cat->is_movable()) {
-			$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?movecat=' . $cat->get_id() . '&amp;selectcat=' . $selectcat . ' &amp;cidReq='.$cat->get_course_code().'"><img src="../img/deplacer_fichier.gif" border="0" title="' . get_lang('Move') . '" alt="" /></a>';
+			/*$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?movecat=' . $cat->get_id() . '&amp;selectcat=' . $selectcat . ' &amp;cidReq='.$cat->get_course_code().'">
+								<img src="../img/icons/22/move.png" border="0" title="' . get_lang('Move') . '" alt="" /></a>';*/
 		} else {
 			//$modify_icons .= '&nbsp;<img src="../img/deplacer_fichier_na.gif" border="0" title="' . get_lang('Move') . '" alt="" />';
 		}
-		$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visiblecat=' . $cat->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=' . $selectcat . ' ">'.Display::return_icon($visibility_icon.'.png', get_lang('Visible'),'','22').'</a>';
+
+		$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletecat=' . $cat->get_id() . '&amp;selectcat=' . $selectcat . '&amp;cidReq='.$cat->get_course_code().'" onclick="return confirmation();">'.Display::return_icon('delete.png', get_lang('DeleteAll'),'','22').'</a>';
 
 		return $modify_icons;
 	}
@@ -359,14 +363,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 {

Diff do ficheiro suprimidas por serem muito extensas
+ 179 - 147
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 ";
@@ -213,12 +216,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',
@@ -261,8 +265,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)."',
@@ -473,9 +476,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 {
@@ -492,7 +499,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 {
@@ -555,11 +566,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);
 				}
 			}
@@ -598,8 +615,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);
 
@@ -771,6 +788,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)) {
@@ -792,7 +811,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)) {
@@ -1028,7 +1051,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();
 		}

+ 1 - 1
main/inc/lib/banner.lib.php

@@ -44,7 +44,7 @@ function get_tabs() {
 	$navigation['myprofile']['title'] = get_lang('ModifyProfile');
 
 	// Link to my agenda
-	$navigation['myagenda']['url'] = api_get_path(WEB_CODE_PATH).'calendar/myagenda.php?view=month&'.(!empty($_course['path']) ? 'coursePath='.$_course['path'].'&amp;courseCode='.$_course['official_code'] : '' );
+	$navigation['myagenda']['url'] = api_get_path(WEB_CODE_PATH).'calendar/agenda_js.php?type=personal';
 	$navigation['myagenda']['title'] = get_lang('MyAgenda');
 
 	// Gradebook

+ 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'];

+ 39 - 54
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);
@@ -1953,7 +1949,7 @@ class CourseManager {
         $tbl_user_course_category   = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
                 
         
-        $special_course_list = self::get_special_course_list();
+        $special_course_list 		= self::get_special_course_list();
         
         $with_special_courses = $without_special_courses = '';
         if (!empty($special_course_list)) {
@@ -1963,7 +1959,7 @@ class CourseManager {
         }
         
         if (!empty($with_special_courses)) {
-            $sql = "SELECT DISTINCT(course.code), course.db_name db_name, course.title , course.id as course_id
+            $sql = "SELECT DISTINCT(course.code), course.db_name db_name, course.title , course.id as course_id, course.id as real_id
                         FROM    ".$tbl_course_user." course_rel_user
                         LEFT JOIN ".$tbl_course." course
                         ON course.code = course_rel_user.course_code
@@ -1984,7 +1980,7 @@ class CourseManager {
 
         // get course list not auto-register. Use Distinct to avoid multiple
         // entries when a course is assigned to a HRD (DRH) as watcher
-        $sql = "SELECT DISTINCT(course.code),course.db_name,course.title , course.id as course_id
+        $sql = "SELECT DISTINCT(course.code),course.db_name,course.title , course.id as course_id, course.id as real_id
                 FROM $tbl_course course
                 INNER JOIN $tbl_course_user cru
                 ON course.code=cru.course_code
@@ -2000,7 +1996,7 @@ class CourseManager {
         }
 
         if ($include_sessions === true) {
-            $r = Database::query("SELECT DISTINCT(c.code), c.db_name, c.title, c.id as course_id
+            $r = Database::query("SELECT DISTINCT(c.code), c.db_name, c.title, c.id as course_id, c.id as real_id
                     FROM ".Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER)." s, ".Database::get_main_table(TABLE_MAIN_COURSE)." c
                     WHERE id_user = $user_id AND s.course_code=c.code");
             while ($row = Database::fetch_array($r, 'ASSOC')) {
@@ -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:

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

@@ -14,6 +14,9 @@
  * CONSTANTS 
  */
 
+//See #3910 defines the default prefix for the single course database
+define('DB_COURSE_PREFIX', 'c_');
+
 // Main database tables
 define('TABLE_MAIN_COURSE',                 'course');
 define('TABLE_MAIN_USER',                   'user');
@@ -194,6 +197,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

+ 49 - 9
main/inc/lib/database.lib.php

@@ -18,7 +18,6 @@
 /*	CONSTANTS */
 require_once 'database.constants.inc.php';
 
-
 /*		DATABASE CLASS
         The class and its methods
 */
@@ -164,7 +163,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 +239,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 +252,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 +691,51 @@ 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, 'insert') 	=== false &&
+        		strpos($query, 'INSERT') === 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])) {
@@ -738,10 +782,6 @@ class Database {
                 echo $info;
             }
         }
-		if(mysql_error()) {
-			error_log($query."\n".mysql_error());
-		}
-		// error_log($query);
         return $result;
     }
 
@@ -1239,7 +1279,7 @@ class Database {
             }
             if (!empty($update_sql)) {
                 //Parsing and cleaning the where conditions
-                $where_return = self::parse_where_conditions($where_conditions);
+                $where_return = self::parse_where_conditions($where_conditions);                
                 $sql    = "UPDATE $table_name SET $update_sql $where_return ";
                 if ($show_query) { echo $sql; echo '<br />'; }
                 $result = self::query($sql);

+ 22 - 16
main/inc/lib/display.lib.php

@@ -1037,21 +1037,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';
@@ -1067,7 +1071,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);
@@ -1080,14 +1084,16 @@ 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']."' ".
                         " ORDER BY tet.lastedit_date";
         $res = Database::query($sql);
         // Get the group_id's with user membership.
-        $group_ids = GroupManager :: get_group_ids($course_database, $user_id);
+        $group_ids = GroupManager :: get_group_ids($my_course['real_id'], $user_id);
         $group_ids[] = 0; //add group 'everyone'
         $notifications = array();
         // Filter all last edits of all tools of the course
@@ -1120,14 +1126,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;
                     }
 
@@ -1143,7 +1149,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;
     }

Alguns ficheiros não foram mostrados porque muitos ficheiros mudaram neste diff