Yannick Warnier 13 år sedan
förälder
incheckning
91c1302562
100 ändrade filer med 4190 tillägg och 3264 borttagningar
  1. 3 3
      index.php
  2. 9 4
      main/admin/add_courses_to_session.php
  3. 6 3
      main/admin/course_add.php
  4. 5 3
      main/admin/course_edit.php
  5. 3 5
      main/admin/index.php
  6. 1 1
      main/admin/resume_session.php
  7. 4 5
      main/admin/session_category_list.php
  8. 82 35
      main/admin/session_list.php
  9. 28 26
      main/admin/settings.php
  10. 14 9
      main/admin/skills_gradebook.php
  11. 4 5
      main/admin/skills_profile.php
  12. 2 2
      main/admin/system_announcements.php
  13. 1 1
      main/admin/user_information.php
  14. 27 11
      main/announcements/announcements.php
  15. 0 1
      main/auth/courses.php
  16. 162 38
      main/calendar/agenda.lib.php
  17. 2 1
      main/calendar/agenda_js.php
  18. 23 26
      main/chat/chat_functions.lib.php
  19. 8 12
      main/chat/chat_hidden.php
  20. 1 1
      main/chat/chat_whoisonline.php
  21. 7 5
      main/course_info/legal.php
  22. 3 2
      main/create_course/add_course.php
  23. 128 8
      main/css/base.css
  24. 6 1
      main/document/document.php
  25. 2 1
      main/document/downloadfolder.inc.php
  26. 49 89
      main/document/edit_document.php
  27. 34 10
      main/exercice/exercice.php
  28. 10 20
      main/exercice/exercise.lib.php
  29. 30 29
      main/exercice/exercise_report.php
  30. 1 1
      main/exercice/exercise_submit.php
  31. 3 3
      main/exercice/hotspot.class.php
  32. 30 11
      main/exercice/live_stats.php
  33. 2 2
      main/exercice/overview.php
  34. 15 6
      main/exercice/stats.php
  35. 17 10
      main/exercice/testcategory.class.php
  36. 14 20
      main/exercice/tests_category.php
  37. 1 1
      main/group/group.php
  38. 8 9
      main/group/group_space.php
  39. BIN
      main/img/alt_star.gif
  40. BIN
      main/img/icons/22/add_na.png
  41. BIN
      main/img/icons/22/warning.png
  42. BIN
      main/img/icons/32/activity_monitor.png
  43. BIN
      main/img/icons/32/import.png
  44. 20 5
      main/inc/ajax/agenda.ajax.php
  45. 25 0
      main/inc/ajax/course.ajax.php
  46. 11 8
      main/inc/ajax/course_home.ajax.php
  47. 12 9
      main/inc/ajax/exercise.ajax.php
  48. 10 32
      main/inc/ajax/link.ajax.php
  49. 47 8
      main/inc/ajax/model.ajax.php
  50. 24 7
      main/inc/lib/auth.lib.php
  51. 9 40
      main/inc/lib/blog.lib.php
  52. 200 7
      main/inc/lib/course.lib.php
  53. 3 2
      main/inc/lib/database.constants.inc.php
  54. 36 17
      main/inc/lib/database.lib.php
  55. 32 17
      main/inc/lib/database.mysqli.lib.php
  56. 31 1
      main/inc/lib/display.lib.php
  57. 9 1
      main/inc/lib/document.lib.php
  58. 15 10
      main/inc/lib/events.lib.inc.php
  59. 4 6
      main/inc/lib/fckeditor/editor/plugins/ImageManager/Classes/ImageManager.php
  60. 3 5
      main/inc/lib/groupmanager.lib.php
  61. 1 1
      main/inc/lib/link.lib.php
  62. 2 1
      main/inc/lib/main_api.lib.php
  63. 1 1
      main/inc/lib/message.lib.php
  64. 1 1
      main/inc/lib/model.lib.php
  65. 74 33
      main/inc/lib/sessionmanager.lib.php
  66. 2 2
      main/inc/lib/skill.lib.php
  67. 10 3
      main/inc/lib/system_announcements.lib.php
  68. 57 10
      main/inc/lib/template.lib.php
  69. 2086 2086
      main/inc/lib/tracking.lib.php
  70. 9 6
      main/inc/lib/urlmanager.lib.php
  71. 7 17
      main/inc/lib/userportal.lib.php
  72. 16 6
      main/inc/local.inc.php
  73. 36 32
      main/install/db_main.sql
  74. 16 7
      main/install/migrate-db-1.8.8-1.9.0-pre.sql
  75. 1 1
      main/link/link.php
  76. 7 8
      main/metadata/md_document.php
  77. 7 5
      main/metadata/md_link.php
  78. 1 0
      main/mySpace/access_details.php
  79. 4 4
      main/mySpace/index.php
  80. 9 9
      main/mySpace/myStudents.php
  81. 1 2
      main/mySpace/myspace.lib.php
  82. 3 0
      main/mySpace/student.php
  83. 3 3
      main/newscorm/learnpath.class.php
  84. 56 44
      main/newscorm/lp_list.php
  85. 141 115
      main/newscorm/resourcelinker.inc.php
  86. 1 10
      main/social/group_add.php
  87. 1 10
      main/social/group_edit.php
  88. 6 6
      main/social/groups.php
  89. 55 51
      main/survey/fillsurvey.php
  90. 20 17
      main/survey/preview.php
  91. 5 3
      main/survey/question.php
  92. 0 6
      main/survey/reporting.php
  93. 117 97
      main/survey/survey.lib.php
  94. 12 11
      main/survey/survey.php
  95. 8 8
      main/survey/survey_invite.php
  96. 34 15
      main/template/default/admin/settings_index.tpl
  97. 56 15
      main/template/default/agenda/month.tpl
  98. 47 13
      main/template/default/auth/courses_categories.php
  99. 24 2
      main/template/default/layout/head.tpl
  100. 17 8
      main/template/default/layout/header.tpl

+ 3 - 3
index.php

@@ -26,6 +26,7 @@ if (!api_is_anonymous()) {
 	$header_title = " ";
 }
 
+$htmlHeadXtra[] = api_get_jquery_ui_js();
 $htmlHeadXtra[] = api_get_jquery_libraries_js(array('bxslider'));
 $htmlHeadXtra[] ='
 <script type="text/javascript">
@@ -181,6 +182,8 @@ if (!api_is_anonymous()) {
 	}
 }
 
+$controller->tpl->assign('hot_courses',             $controller->return_hot_courses());
+
 $controller->tpl->assign('announcements_block', 	$controller->return_announcements());
 $controller->tpl->assign('home_page_block', 		$controller->return_home_page());
 $controller->tpl->assign('notice_block',			$controller->return_notice());
@@ -190,7 +193,4 @@ if (api_is_platform_admin() || api_is_drh()) {
     $controller->tpl->assign('skills_block',            $controller->return_skills_links());
 }
 
-
-
-
 $controller->tpl->display_two_col_template();

+ 9 - 4
main/admin/add_courses_to_session.php

@@ -15,7 +15,6 @@ require_once '../inc/global.inc.php';
 
 // including additonal libraries
 
-require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
 require_once api_get_path(LIBRARY_PATH).'add_courses_to_session_functions.lib.php';
 
 $id_session = intval($_GET['id_session']);
@@ -134,7 +133,11 @@ if ($_POST['formSent']) {
 		}
 		if(!$exists) {
 			$sql_insert_rel_course= "INSERT INTO $tbl_session_rel_course(id_session,course_code) VALUES('$id_session','$enreg_course')";
-			Database::query($sql_insert_rel_course );
+			Database::query($sql_insert_rel_course);
+            
+            $course_info = api_get_course_info($enreg_course);
+            CourseManager::update_course_ranking($course_info['real_id'], $id_session);
+            
 			//We add in the existing courses table the current course, to not try to add another time the current course
 			$existingCourses[]=array('course_code'=>$enreg_course);
 			$nbr_users=0;
@@ -152,10 +155,12 @@ if ($_POST['formSent']) {
 	}
 
 	foreach($existingCourses as $existingCourse) {
-		if(!in_array($existingCourse['course_code'], $CourseList)){
+		if(!in_array($existingCourse['course_code'], $CourseList)) {
+		    $course_info = api_get_course_info($existingCourse['course_code']);
+            CourseManager::remove_course_ranking($course_info['real_id'], $id_session);
 			Database::query("DELETE FROM $tbl_session_rel_course WHERE course_code='".$existingCourse['course_code']."' AND id_session=$id_session");
 			Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE course_code='".$existingCourse['course_code']."' AND id_session=$id_session");
-
+            
 		}
 	}
 	$nbr_courses=count($CourseList);

+ 6 - 3
main/admin/course_add.php

@@ -110,20 +110,21 @@ $group[]= $form->createElement('radio', 'unsubscribe', get_lang('Unsubscription'
 $group[]= $form->createElement('radio', 'unsubscribe', null, get_lang('NotAllowedToUnsubscribe'), 0);
 $form->addGroup($group,'', get_lang('Unsubscription'), '<br />');
 
-
-$form->add_textfield('disk_quota', get_lang('CourseQuota'));
+$form->addElement('text','disk_quota',array(get_lang('CourseQuota'), null, get_lang('MB')));
 $form->addRule('disk_quota', get_lang('ThisFieldShouldBeNumeric'), 'numeric');
 $form->add_progress_bar();
 $form->addElement('style_submit_button', 'submit', get_lang('CreateCourse'), 'class="add"');
 
 // Set some default values.
 $values['course_language']  = api_get_setting('platformLanguage');
-$values['disk_quota']       = api_get_setting('default_document_quotum');
+$values['disk_quota']       = round(api_get_setting('default_document_quotum')/1024/1024, 1);
+
 $values['visibility']       = COURSE_VISIBILITY_OPEN_PLATFORM;
 $values['subscribe']        = 1;
 $values['unsubscribe']      = 0;
 reset($teachers);
 //$values['course_teachers'] = key($teachers);
+
 $form->setDefaults($values);
 
 // Validate the form
@@ -134,6 +135,8 @@ if ($form->validate()) {
     $teacher_id      = $course['tutor_id'];
     $course_teachers = $course['course_teachers'];
     
+    $course['disk_quota'] = $course['disk_quota']*1024*1024;
+    
     $course['exemplary_content']    = empty($course['exemplary_content']) ? false : true;
     $course['teachers']             = $course_teachers;
     //$course['tutor_name']           = $tutor_name;

+ 5 - 3
main/admin/course_edit.php

@@ -168,11 +168,12 @@ $group[]= $form->createElement('radio', 'unsubscribe', null, get_lang('NotAllowe
 $form->addGroup($group,'', get_lang('Unsubscription'), '<br />');
 
 
-$form->addElement('text','disk_quota',array(get_lang('CourseQuota'), null, get_lang('MB')));
+$form->addElement('text','disk_quota',array(get_lang('CourseQuota'),null,  get_lang('MB')));
 $form->addRule('disk_quota', get_lang('ThisFieldIsRequired'),'required');
 $form->addRule('disk_quota',get_lang('ThisFieldShouldBeNumeric'),'numeric');
 
 $list_course_extra_field = CourseManager::get_course_extra_field_list($course_code);
+//@todo this is wrong
 foreach ($list_course_extra_field as $extra_field) {
 	switch ($extra_field['field_type']) {
 		/* case USER_FIELD_TYPE_TEXT:
@@ -182,7 +183,8 @@ foreach ($list_course_extra_field as $extra_field) {
 			$checked = (array_key_exists('extra_field_value', $extra_field) && $extra_field['extra_field_value'] == 1)? array('checked'=>'checked'): '';
 			$form->addElement('hidden', '_extra_'.$extra_field['field_variable'], 0);
 			$field_display_text=$extra_field['field_display_text'];
-			$form->addElement('checkbox', 'extra_'.$extra_field['field_variable'], array(get_lang('SpecialCourse'), get_lang('AllUsersAreAutomaticallyRegistered')) , get_lang($extra_field['field_default_value']), $checked);
+			//$form->addElement('checkbox', 'extra_'.$extra_field['field_variable'], array(get_lang('SpecialCourse'), get_lang('AllUsersAreAutomaticallyRegistered')) , get_lang($extra_field['field_default_value']), $checked);
+			$form->addElement('checkbox', 'extra_'.$extra_field['field_variable'], array(null, get_lang('AllUsersAreAutomaticallyRegistered')) , get_lang('SpecialCourse'), $checked);
 			break;
 		/* case USER_FIELD_TYPE_SELECT_MULTIPLE:
 		case USER_FIELD_TYPE_DATE:
@@ -192,8 +194,8 @@ foreach ($list_course_extra_field as $extra_field) {
 	}
 }
 $form->addElement('style_submit_button', 'button', get_lang('ModifyCourseInfo'),'onclick="valide()"; class="save"');
-// Set some default values
 
+// Set some default values
 $course_db_name = $course['db_name'];
 $course['disk_quota'] = round($course['disk_quota']/1024/1024, 1);
 $course['title'] = api_html_entity_decode($course['title'], ENT_QUOTES, $charset);

+ 3 - 5
main/admin/index.php

@@ -24,6 +24,7 @@ $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script(true);
 
 $nameTools = get_lang('PlatformAdmin');
+$htmlHeadXtra[] = api_get_jquery_ui_js();
 
 // Displaying the header
 $message = '';
@@ -249,7 +250,7 @@ if (api_is_platform_admin()) {
     $items = array();
     $items[] = array('url'=>'skills.php',           'label' => get_lang('SkillsTree'));
     $items[] = array('url'=>'skills_profile.php',   'label' => get_lang('SkillsProfile'));
-    $items[] = array('url'=>'skills_gradebook.php', 'label' => get_lang('SkillsGradebook'));   
+    $items[] = array('url'=>'skills_gradebook.php', 'label' => get_lang('SkillsAndGradebooks'));   
     
     $blocks['skills']['items'] = $items;
     
@@ -271,10 +272,7 @@ if (api_is_platform_admin()) {
 	$items[] = array('url'=>'../../documentation/optimization.html', 	'label' => get_lang('OptimizationGuide'));
 	$items[] = array('url'=>'http://www.chamilo.org/extensions', 	'label' => get_lang('ChamiloExtensions'));	
 	
-	$blocks['chamilo']['items'] = $items;
-    
-    
-    
+	$blocks['chamilo']['items'] = $items;    
 	
 	// Try to display a maximum before we check the chamilo version and all that.
 	//session_write_close(); //close session to avoid blocking concurrent access

+ 1 - 1
main/admin/resume_session.php

@@ -256,7 +256,7 @@ else {
 		//hide_course_breadcrumb the parameter has been added to hide the name of the course, that appeared in the default $interbreadcrumb
 		echo '
 		<tr>
-			<td>'.$course['title'].' ('.$course['visual_code'].')</td>
+			<td>'.Display::url($course['title'].' ('.$course['visual_code'].')', api_get_path(WEB_COURSE_PATH).$course['code'].'/?id_session='.$id_session),'</td>
 			<td>'.$coach.'</td>
 			<td>'.$course['nbr_users'].'</td>
 			<td>

+ 4 - 5
main/admin/session_category_list.php

@@ -5,12 +5,11 @@ $language_file='admin';
 $cidReset=true;
 
 require_once  '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
-require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
 
 api_protect_admin_script(true);
+
 // setting the section (for the tabs)
-$this_section=SECTION_PLATFORM_ADMIN;
+$this_section = SECTION_PLATFORM_ADMIN;
 $htmlHeadXtra[] = '<script language="javascript">
 				function selectAll(idCheck,numRows,action) {
 					for(i=0;i<numRows;i++) {
@@ -24,8 +23,8 @@ $htmlHeadXtra[] = '<script language="javascript">
 				}
 				</script>';
 
-$tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
-$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_category   = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
+$tbl_session            = Database::get_main_table(TABLE_MAIN_SESSION);
 
 $page=intval($_GET['page']);
 $action= Security::remove_XSS($_REQUEST['action']);

+ 82 - 35
main/admin/session_list.php

@@ -43,21 +43,38 @@ Display::display_header($tool_name);
 $url            = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions';
 
 //The order is important you need to check the the $column variable in the model.ajax.php file 
-$columns        = array(get_lang('Name'), get_lang('NumberOfCourses'), get_lang('SessionCategoryName'), get_lang('StartDate'), get_lang('EndDate'), get_lang('Coach'),  get_lang('Visibility'), get_lang('Actions'));
+$columns        = array(get_lang('Name'), get_lang('NumberOfCourses'), get_lang('SessionCategoryName'), 
+                        get_lang('StartDate'), get_lang('EndDate'), get_lang('Coach'),  get_lang('Status'), get_lang('Visibility'), get_lang('Actions'));
 
+//$activeurl = '?sidx=session_active';
 //Column config
 $column_model   = array(
-                        array('name'=>'name',           'index'=>'s.name',          'width'=>'120',  'align'=>'left', 'search' => 'true'),                        
-                        array('name'=>'nbr_courses',    'index'=>'s.nbr_courses',   'width'=>'30',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'category_name',  'index'=>'sc.name',         'width'=>'80',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'date_start',     'index'=>'s.date_start',    'width'=>'40',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'date_end',       'index'=>'s.date_end',      'width'=>'40',   'align'=>'left', 'search' => 'true'),
-                        array('name'=>'coach_name',     'index'=>'coach_name',      'width'=>'80',   'align'=>'left', 'search' => 'false'),                        
+                        array('name'=>'name',           'index'=>'name',          'width'=>'120',  'align'=>'left', 'search' => 'true'),                        
+                        array('name'=>'nbr_courses',    'index'=>'nbr_courses',   'width'=>'30',   'align'=>'left', 'search' => 'true'),
+                        array('name'=>'category_name',  'index'=>'category_name', 'width'=>'70',   'align'=>'left', 'search' => 'true'),
+                        array('name'=>'date_start',     'index'=>'date_start',    'width'=>'40',   'align'=>'left', 'search' => 'true'),
+                        array('name'=>'date_end',       'index'=>'date_end',      'width'=>'40',   'align'=>'left', 'search' => 'true'),
+                        array('name'=>'coach_name',     'index'=>'coach_name',     'width'=>'80',   'align'=>'left', 'search' => 'false'),                        
+                        
+                        array('name'=>'status',         'index'=>'session_active',  'width'=>'40',   'align'=>'left', 'search' => 'true', 'stype'=>'select',
+                                 
+                              
+                              
+                              //for the bottom bar
+                              'searchoptions' => array(                                                
+                                                'defaultValue'  => '1', 
+                                                'value'         => '1:'.get_lang('Active').';0:'.get_lang('Inactive')),
+                             
+                              //for the top bar                              
+                              'editoptions' => array('value' => ':'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive'))),
+                                          
+                                   
                         array('name'=>'visibility',     'index'=>'visibility',      'width'=>'40',   'align'=>'left', 'search' => 'false'),                        
                         array('name'=>'actions',        'index'=>'actions',         'width'=>'100',  'align'=>'left','formatter'=>'action_formatter','sortable'=>'false', 'search' => 'false')
                        );            
 //Autowidth             
 $extra_params['autowidth'] = 'true';
+
 //height auto 
 $extra_params['height'] = 'auto';
 $extra_params['excel'] = 'excel';
@@ -67,7 +84,7 @@ $extra_params['rowList'] = array(10, 20 ,30);
 
 //With this function we can add actions to the jgrid (edit, delete, etc)
 $action_links = 'function action_formatter(cellvalue, options, rowObject) {
-                         return \'<a href="resume_session.php?id_session=\'+options.rowId+\'">'.Display::return_icon('edit.png',get_lang('Edit'),'',22).'</a>'.
+                         return \'<a href="session_edit.php?page=resume_session.php&id=\'+options.rowId+\'">'.Display::return_icon('edit.png',get_lang('Edit'),'',22).'</a>'.
                          '&nbsp;<a href="add_users_to_session.php?page=session_list.php&id_session=\'+options.rowId+\'">'.Display::return_icon('user_subscribe_session.png',get_lang('SubscribeUsersToSession'),'',22).'</a>'.
                          '&nbsp;<a href="add_courses_to_session.php?page=session_list.php&id_session=\'+options.rowId+\'">'.Display::return_icon('courses_to_session.png',get_lang('SubscribeCoursesToSession'),'',22).'</a>'.
                          '&nbsp;<a onclick="javascript:if(!confirm('."\'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES))."\'".')) return false;"  href="session_list.php?action=copy&idChecked=\'+options.rowId+\'">'.Display::return_icon('copy.png',get_lang('Copy'),'',22).'</a>'.
@@ -76,45 +93,75 @@ $action_links = 'function action_formatter(cellvalue, options, rowObject) {
                  }';
 ?>
 <script>
+
+
+function setSearchSelect(columnName) {    
+    $("#sessions").jqGrid('setColProp', columnName,
+    {                   
+       searchoptions:{
+            dataInit:function(el){                            
+                $("option[value='1']",el).attr("selected", "selected");
+                setTimeout(function(){
+                    $(el).trigger('change');
+                },1000);
+            }
+        }
+    });
+}
+
+
 $(function() {
     <?php 
         echo Display::grid_js('sessions', $url,$columns,$column_model,$extra_params, array(), $action_links,true);      
     ?>
-
-$("#sessions").jqGrid('navGrid','#sessions_pager', {edit:false,add:false,del:false},
-    {height:280,reloadAfterSubmit:false}, // edit options 
-    {height:280,reloadAfterSubmit:false}, // add options 
-    {reloadAfterSubmit:false}, // del options 
-    {width:500} // search options
-);
-/*
-// add custom button to export the data to excel
-jQuery("#sessions").jqGrid('navButtonAdd','#sessions_pager',{
-       caption:"", 
-       onClickButton : function () { 
-           jQuery("#sessions").excelExport();
-       } 
-});
-
-jQuery('#sessions').jqGrid('navButtonAdd','#sessions_pager',{id:'pager_csv',caption:'',title:'Export To CSV',onClickButton : function(e)
-{
-    try {
-        jQuery("#sessions").jqGrid('excelExport',{tag:'csv', url:'grid.php'});
-    } catch (e) {
-        window.location= 'grid.php?oper=csv';
+    
+    setSearchSelect("status");    
+    
+    $("#sessions").jqGrid('navGrid','#sessions_pager', {edit:false,add:false,del:false},
+        {height:280,reloadAfterSubmit:false}, // edit options 
+        {height:280,reloadAfterSubmit:false}, // add options 
+        {reloadAfterSubmit:false}, // del options 
+        {width:500} // search options
+    );
+    /*
+    // add custom button to export the data to excel
+    jQuery("#sessions").jqGrid('navButtonAdd','#sessions_pager',{
+           caption:"", 
+           onClickButton : function () { 
+               jQuery("#sessions").excelExport();
+           } 
+    });
+    
+    jQuery('#sessions').jqGrid('navButtonAdd','#sessions_pager',{id:'pager_csv',caption:'',title:'Export To CSV',onClickButton : function(e)
+    {
+        try {
+            jQuery("#sessions").jqGrid('excelExport',{tag:'csv', url:'grid.php'});
+        } catch (e) {
+            window.location= 'grid.php?oper=csv';
+        }
+    },buttonicon:'ui-icon-document'})
+    */
+   
+    
+    //Adding search options
+    var options = {
+        'stringResult': true,
+        'autosearch' : true,
+        'searchOnEnter':false,        
     }
-},buttonicon:'ui-icon-document'})
-*/
-
+    jQuery("#sessions").jqGrid('filterToolbar',options);    
+    var sgrid = $("#sessions")[0];
+    sgrid.triggerToolbar();
+    
+     
 });
-</script>
 
+</script>
 <div class="actions">
 <?php 
 echo '<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_add.php">'.Display::return_icon('new_session.png',get_lang('AddSession'),'','32').'</a>';
 echo '<a href="'.api_get_path(WEB_CODE_PATH).'admin/add_many_session_to_category.php">'.Display::return_icon('session_to_category.png',get_lang('AddSessionsInCategories'),'','32').'</a>';
 echo '<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_category_list.php">'.Display::return_icon('folder.png',get_lang('ListSessionCategory'),'','32').'</a>';
 echo '</div>';
-
 echo Display::grid_html('sessions');
 Display::display_footer();

+ 28 - 26
main/admin/settings.php

@@ -39,6 +39,14 @@ $_SESSION['this_section'] = $this_section;
 // Access restrictions.
 api_protect_admin_script();
 
+// Settings to avoid
+$settings_to_avoid = array(
+    'gradebook_enable'                  => 'false', 
+    'use_document_title'                => 'true',
+    'example_material_course_creation'  => 'true' // ON by default - now we have this option when  we create a course 
+);
+
+
 // Submit stylesheets.
 if (isset($_POST['submit_stylesheets'])) {
     $message = store_stylesheets();
@@ -88,7 +96,6 @@ if (isset($_GET['action']) &&  $_GET['action'] == 'delete_grading') {
 	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']);
@@ -145,17 +152,6 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
         }
     }
     
-    
-    //Settings to avoid 
-    
-    // Settings to avoid
-    $settings_to_avoid = array(
-        'gradebook_enable', //
-        'use_document_title', // ON by default 
-        'example_material_course_creation', // ON by default - now we have this option when  we create a course 
-    );
-    
-    
     $default_values = array();
     foreach ($settings as $row) {
     	if (in_array($row['variable'], $settings_to_avoid)) { continue; }
@@ -490,7 +486,7 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
     if ($form->validate()) {
         $values = $form->exportValues();
         $pdf_export_watermark_path = $_FILES['pdf_export_watermark_path'];
-            
+         
         if (isset($pdf_export_watermark_path) && !empty($pdf_export_watermark_path['name'])) {       
             $pdf_export_watermark_path_result = PDF::upload_watermark($pdf_export_watermark_path['name'], $pdf_export_watermark_path['tmp_name']);  
             if ($pdf_export_watermark_path_result) {
@@ -501,21 +497,20 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
             unset($update_values['pdf_export_watermark_path']);
         }
 
-        // Set true for allow_message_tool variable if social tool is actived.
+        // Set true for allow_message_tool variable if social tool is actived       
         
-        
-        $values['dropbox_max_filesize'] = $values['dropbox_max_filesize']*1024*1024;
+        $values['dropbox_max_filesize']        = $values['dropbox_max_filesize']*1024*1024;
         $values['message_max_upload_filesize'] = $values['message_max_upload_filesize']*1024*1024;
          
-         
         if ($values['allow_social_tool'] == 'true') {
             $values['allow_message_tool'] = 'true';
         }
         // quick patch to avoid gradebook_enable's value to be blanked
+        /*
         if ($my_category == 'Gradebook') {
             $gb = 'false';
         	$gb = api_get_setting('gradebook_enable');
-        }
+        }*/
 
         // The first step is to set all the variables that have type=checkbox of the category
         // to false as the checkbox that is unchecked is not in the $_POST data and can
@@ -525,14 +520,21 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
         $r = api_set_settings_category($my_category, 'false', $_configuration['access_url'], array('checkbox', 'radio'));
         // quick patch to avoid gradebook_enable's value to be blanked
         if ($my_category == 'Gradebook') {
-            api_set_setting('gradebook_enable', $gb, null, $my_category, $_configuration['access_url']);
+            //api_set_setting('gradebook_enable', $gb, null, $my_category, $_configuration['access_url']);
         }
-        //$sql = "UPDATE $table_settings_current SET selected_value='false' WHERE category='$my_category' AND type='checkbox'";
-        //$result = Database::query($sql);
+        
+        foreach($settings_to_avoid as $key => $value) {
+            api_set_setting($key, $value, null, null, $_configuration['access_url']);    
+        }        
+        
+        
+        
         // Save the settings.
         $keys = array();
-        //$gradebook_score_display_custom_values = array();        
-        foreach ($values as $key => $value) { 	
+               
+        foreach ($values as $key => $value) {
+            if (in_array($key, $settings_to_avoid)) { continue; }
+                      	
             // Treat gradebook values in separate function.
             //if (strpos($key, 'gradebook_score_display_custom_values') === false) {
                 if (!is_array($value)) {
@@ -603,7 +605,7 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
 	                            $keys[] = $key;
 	                            break;
 	                        }
-	                    }	
+	                    }
 	                    foreach ($value as $subkey => $subvalue) {	             
 	                        $result = api_set_setting($key, 'true', $subkey, null, $_configuration['access_url']);	
 	                    }
@@ -615,11 +617,11 @@ if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', '
         $user_id = api_get_user_id();
         $category = $_GET['category'];
         event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
-
-
+        
         // Add event configuration settings variable to the system log.
         if (is_array($keys) && count($keys) > 0) {
             foreach ($keys as $variable) {
+                if (in_array($key, $settings_to_avoid)) { continue; }
                 event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_VARIABLE, $variable, api_get_utc_datetime(), $user_id);
             }
         }

+ 14 - 9
main/admin/skills_gradebook.php

@@ -24,10 +24,10 @@ $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'display';
 
 // setting breadcrumbs
 
-$tool_name = get_lang('SkillGradebook');
+$tool_name = get_lang('SkillsAndGradebooks');
 $interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
 if ($action == 'add_skill') {
-    $interbreadcrumb[]=array('url' => 'skills_gradebook.php','name' => get_lang('SkillGradebook'));
+    $interbreadcrumb[]=array('url' => 'skills_gradebook.php','name' => get_lang('SkillsAndGradebooks'));
     $tool_name = get_lang('Add');    
 }
 
@@ -42,13 +42,14 @@ Display::display_header($tool_name);
 $url            = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_gradebooks';
 
 //The order is important you need to check the the $column variable in the model.ajax.php file 
-$columns        = array(get_lang('Name'), get_lang('Skills'), get_lang('Actions'));
+$columns        = array(get_lang('Name'), get_lang('CertificatesFiles'), get_lang('Skills'), get_lang('Actions'));
 
 //Column config
 $column_model   = array(
-                        array('name'=>'name',           'index'=>'name',    'width'=>'200', 'align'=>'left'),
-                        array('name'=>'skills',         'index'=>'skills',  'width'=>'300', 'align'=>'left','sortable'=>'false'),
-                        array('name'=>'actions',        'index'=>'actions', 'width'=>'100', 'align'=>'left','formatter'=>'action_formatter','sortable'=>'false')
+                        array('name'=>'name',           'index'=>'name',        'width'=>'150', 'align'=>'left'),
+                        array('name'=>'certificate',    'index'=>'certificate', 'width'=>'25', 'align'=>'left', 'sortable'=>'false'),
+                        array('name'=>'skills',         'index'=>'skills',      'width'=>'300', 'align'=>'left', 'sortable'=>'false'),
+                        array('name'=>'actions',        'index'=>'actions',     'width'=>'30', 'align'=>'left','formatter'=>'action_formatter','sortable'=>'false')
                        );            
 //Autowidth             
 $extra_params['autowidth'] = 'true';
@@ -57,15 +58,19 @@ $extra_params['height'] = 'auto';
 
 //With this function we can add actions to the jgrid (edit, delete, etc)
 $action_links = 'function action_formatter(cellvalue, options, rowObject) {
-                         return \'<a href="?action=add_skill&id=\'+options.rowId+\'">'.Display::return_icon('addd.gif', get_lang('AddSkill'),'',22).'</a>'.
-                         '\'; 
+                        //certificates
+                        if (rowObject[4] == 1) {            
+                            return \'<a href="?action=add_skill&id=\'+options.rowId+\'">'.Display::return_icon('add.png', get_lang('AddSkill'),'',22).'</a>'.'\';
+                        } else {
+                            return \''.Display::return_icon('add_na.png', get_lang('YourGradebookFirstNeedsACertificateInOrderToBeLinkedToASkill'),'',22).''.'\';
+                        }
                  }';
 ?>
 <script>
 $(function() {
 <?php 
     // grid definition see the $career->display() function
-    echo Display::grid_js('gradebooks',  $url,$columns,$column_model,$extra_params, array(), $action_links,true);       
+    echo Display::grid_js('gradebooks', $url, $columns, $column_model, $extra_params, array(), $action_links,true);       
 ?> 
 });
 </script>

+ 4 - 5
main/admin/skills_profile.php

@@ -65,7 +65,7 @@ $user_list = array();
 $count_skills = count($skills);
 
 $users  = $skill_rel_user->get_user_by_skills($skills);
-    
+
 if (!empty($users)) {
     foreach($users as $user) {            
         $user_info = api_get_user_info($user['user_id']);
@@ -74,6 +74,7 @@ if (!empty($users)) {
         $user_skills = array();
         $found_counts = 0 ;
         foreach($my_user_skills as $my_skill) {
+            
             $found = false;
             if (in_array($my_skill['skill_id'], $skills)) {
                 $found = true;
@@ -94,7 +95,7 @@ if (!empty($users)) {
     }
 }
 
-//var_dump($user_list);
+
 
 //$tpl->assign('user_list', $user_list);
 $tpl->assign('order_user_list', $ordered_user_list);
@@ -116,12 +117,10 @@ if (!empty($skills)) {
 
 $total_skills_to_search = $skill->get_skills_info($total_skills_to_search);
 $skill_list = array();
-foreach($total_skills_to_search as &$skill_info) {
+foreach($total_skills_to_search as $skill_info) {
     $skill_list[$skill_info['id']] = $skill_info;        
 }
 
-
-
 $action = isset($_REQUEST['a']) ? $_REQUEST['a'] : null;
 $id     = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : null;
 

+ 2 - 2
main/admin/system_announcements.php

@@ -122,8 +122,8 @@ if (isset ($_GET['action']) && $_GET['action'] == 'edit') {
     $values['visible_guest'] 	= $announcement->visible_guest ;
     $values['lang'] 			= $announcement->lang;
     $values['action']			= 'edit';
-  $groups = SystemAnnouncementManager :: get_announcement_groups($announcement->id);
-  $values['group'] = isset($groups[0]['group_id']) ? $groups[0]['group_id'] : 0;
+    $groups = SystemAnnouncementManager :: get_announcement_groups($announcement->id);
+    $values['group'] = isset($groups[0]['group_id']) ? $groups[0]['group_id'] : 0;
     $action_todo = true;
 }
 

+ 1 - 1
main/admin/user_information.php

@@ -216,7 +216,7 @@ if ($_configuration['multiple_access_urls']) {
     $url_list= UrlManager::get_access_url_from_user($user['user_id']);
     if (count($url_list) > 0) {
         $header = array();
-        $header[] = array (get_lang('URL'), true);
+        $header[] = array ('URL', true);
         $data = array ();
         foreach ($url_list as $url) {
             $row = array();

+ 27 - 11
main/announcements/announcements.php

@@ -427,24 +427,25 @@ if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_ed
 				    	// send to the created 'userlist'
 					    $sqlmail = "SELECT user_id, lastname, firstname, email
 									FROM $tbl_user
-						       		WHERE user_id IN (".$userlist.")";
+						       		WHERE active = 1 AND user_id IN (".$userlist.")";
 				    } else if (empty($_POST['not_selected_form'])) {
 			    		if(empty($_SESSION['id_session']) || api_get_setting('use_session_mode')=='false') {
 				    		// send to everybody
 				    		$sqlmail = "SELECT user.user_id, user.email, user.lastname, user.firstname
 					                    FROM $tbl_course_user, $tbl_user
-					                    WHERE course_code='".Database::escape_string($_course['sysCode'])."'
-					                    AND course_rel_user.user_id = user.user_id AND relation_type <>".COURSE_RELATION_TYPE_RRHH." ";
+					                    WHERE  active = 1 AND 
+					                           course_code='".Database::escape_string($_course['sysCode'])."' AND
+					                           course_rel_user.user_id = user.user_id AND 
+					                           relation_type <>".COURSE_RELATION_TYPE_RRHH." ";
 			    		} else {
 			    			$sqlmail = "SELECT user.user_id, user.email, user.lastname, user.firstname
-					                    FROM $tbl_user
-										INNER JOIN $tbl_session_course_user
-										ON $tbl_user.user_id = $tbl_session_course_user.id_user
-										AND $tbl_session_course_user.course_code = '".$_course['id']."'
-										AND $tbl_session_course_user.id_session = ".api_get_session_id();
+					                    FROM $tbl_user INNER JOIN $tbl_session_course_user
+										ON $tbl_user.user_id = $tbl_session_course_user.id_user AND
+										active = 1 AND
+										$tbl_session_course_user.course_code = '".$_course['id']."' AND
+										$tbl_session_course_user.id_session = ".api_get_session_id();
 			    		}
 			    	}
-
 					if ($sqlmail != '') {
 						$rs_mail = Database::query($sqlmail);
 
@@ -482,7 +483,10 @@ 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'];
@@ -501,7 +505,7 @@ if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_ed
 								$time = $time+30;
 								$sql="INSERT INTO $table_reminder(sid,db_name,email,subject,content,reminder_choice,reminder_time,avail_till) values('$surveyid','$db_name','$mailid','".addslashes($emailSubject)."','".addslashes($mail_body)."','1','$time','$end_date')";
 								Database::query($sql);
-							}
+							}*/
 						}
 						AnnouncementManager::update_mail_sent($insert_id);
 						$message = $added_and_sent;
@@ -1067,7 +1071,19 @@ if ($display_announcement_list) {
 
 	if (!isset($_GET['action']) || !in_array($_GET['action'], array('add', 'modify','view')))
 	if ($num_rows == 0) {
-		Display::display_warning_message(get_lang('NoAnnouncements'));
+		if ((api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) and (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath')) {
+	        echo '<div id="no-data-view">';
+            echo '<h2>'.get_lang('Announcements').'</h2>';
+            echo Display::return_icon('valves.png', '', array(), 64);
+            echo '<div class="controls">';    
+            echo Display::url(get_lang('AddAnnouncement'), api_get_self()."?".api_get_cidreq()."&action=add&origin=".(empty($_GET['origin'])?'':$_GET['origin']) , array('class' => 'a_button white'));
+            echo '</div>';
+            echo '</div>';                   
+        } else {
+            //echo "<a href='".api_get_self()."?".api_get_cidreq()."&action=add&origin=".(empty($_GET['origin'])?'':$_GET['origin'])."'>".Display::return_icon('new_announce.png',get_lang('AddAnnouncement'),'','32')."</a>";
+           Display::display_warning_message(get_lang('NoAnnouncements'));        
+        }
+    
 	} else {    
     	$iterator = 1;
     	$bottomAnnouncement = $announcement_number;

+ 0 - 1
main/auth/courses.php

@@ -19,7 +19,6 @@ require_once '../inc/global.inc.php';
 require_once api_get_path(LIBRARY_PATH).'auth.lib.php'; 
 require_once api_get_path(LIBRARY_PATH).'app_view.php';
 require_once 'courses_controller.php';
-//require_once api_get_path(LIBRARY_PATH).'debug.lib.inc.php';
 require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
 
 if (api_get_setting('show_courses_descriptions_in_catalog') == 'true') {

+ 162 - 38
main/calendar/agenda.lib.php

@@ -41,7 +41,7 @@ class Agenda {
 	 * @param 	string	agendaDay, agendaWeek, month
 	 * @param	string	personal, course or global (only works for personal by now) 
 	 */
-	function add_event($start, $end, $all_day, $view, $title, $content, $users_to_send = array()) {
+	function add_event($start, $end, $all_day, $view, $title, $content, $users_to_send = array(), $add_as_announcement = false) {
 		
 		$start 		= date('Y-m-d H:i:s', $start);
 		$end 		= date('Y-m-d H:i:s', $end);			
@@ -57,7 +57,7 @@ class Agenda {
 				$attributes['title'] 	= $title;
 				$attributes['text'] 	= $content;
 				$attributes['date'] 	= $start;
-				$attributes['enddate'] 	= $end;
+				$attributes['enddate'] 	= $end;                
 				$attributes['all_day'] 	= $all_day;
 				$id = Database::insert($this->tbl_personal_agenda, $attributes);
 				break;
@@ -67,14 +67,14 @@ class Agenda {
 				$attributes['content'] 		= $content;
 				$attributes['start_date'] 	= $start;
 				$attributes['end_date'] 	= $end;
-				$attributes['all_day'] 		= $all_day;
+				$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);
                 
-                if ($id) {			
+                if ($id) {
     				//api_item_property_update($this->course, TOOL_CALENDAR_EVENT, $id, "AgendaAdded", api_get_user_id(), '','',$start, $end);                    
                     $group_id = api_get_group_id();
                     if ((!is_null($users_to_send)) or (!empty($group_id))) {
@@ -99,8 +99,11 @@ class Agenda {
                             }
                         }
                     }
-                }                              
-                              
+
+                    if (isset($add_as_announcement) && !empty($add_as_announcement)) {
+                      self::store_agenda_item_as_announcement($id);
+                    }  
+                }             
 			
 				break;
 			case 'admin':				
@@ -115,6 +118,76 @@ class Agenda {
 		}				
 		return $id;				
 	}
+
+
+    /* copycat of the agenda.inc.php @todo try to fix it */
+      
+    function store_agenda_item_as_announcement($item_id){
+        $table_agenda  = Database::get_course_table(TABLE_AGENDA);
+        $table_ann     = Database::get_course_table(TABLE_ANNOUNCEMENT);
+        $course_id     = api_get_course_int_id();
+        //check params
+        if(empty($item_id) or $item_id != strval(intval($item_id))) {return -1;}
+        //get the agenda item
+    
+        $item_id = Database::escape_string($item_id);
+        $sql = "SELECT * FROM $table_agenda WHERE c_id = $course_id AND id = ".$item_id;
+        $res = Database::query($sql);
+                
+        if (Database::num_rows($res)>0) {
+            $row = Database::fetch_array($res);
+            
+            //we have the agenda event, copy it
+            //get the maximum value for display order in announcement table
+            $sql_max = "SELECT MAX(display_order) FROM $table_ann WHERE c_id = $course_id ";
+            $res_max = Database::query($sql_max);
+            $row_max = Database::fetch_array($res_max);
+            $max = intval($row_max[0])+1;       
+            //build the announcement text
+            $content = $row['content'];
+            //insert announcement
+            $session_id = api_get_session_id();
+            
+            
+            $sql_ins = "INSERT INTO $table_ann (c_id, title,content,end_date,display_order,session_id) " .
+                        "VALUES ($course_id, '".Database::escape_string($row['title'])."','".Database::escape_string($content)."','".Database::escape_string($row['end_date'])."','$max','$session_id')";
+            $res_ins = Database::query($sql_ins);
+            if ($res > 0) {
+                $ann_id = Database::insert_id();
+                //Now also get the list of item_properties rows for this agenda_item (calendar_event)
+                //and copy them into announcement item_properties
+                $table_props = Database::get_course_table(TABLE_ITEM_PROPERTY);
+                $sql_props = "SELECT * FROM $table_props WHERE c_id = $course_id AND tool ='calendar_event' AND ref='$item_id'";
+                $res_props = Database::query($sql_props);
+                if(Database::num_rows($res_props)>0) {
+                    while($row_props = Database::fetch_array($res_props)) {
+                        //insert into announcement item_property
+                        $time = api_get_utc_datetime();
+                        $sql_ins_props = "INSERT INTO $table_props " .
+                                "(c_id, tool, insert_user_id, insert_date, " .
+                                "lastedit_date, ref, lastedit_type," .
+                                "lastedit_user_id, to_group_id, to_user_id, " .
+                                "visibility, start_visible, end_visible)" .
+                                " VALUES " .
+                                "($course_id, 'announcement','".$row_props['insert_user_id']."','".$time."'," .
+                                "'$time','$ann_id','AnnouncementAdded'," .
+                                "'".$row_props['last_edit_user_id']."','".$row_props['to_group_id']."','".$row_props['to_user_id']."'," .
+                                "'".$row_props['visibility']."','".$row_props['start_visible']."','".$row_props['end_visible']."')";
+                        $res_ins_props = Database::query($sql_ins_props);
+                        if($res_ins_props <= 0){
+                            return -1;
+                        } else {
+                            //copy was a success
+                            return $ann_id;
+                        }
+                    }
+                }
+            } else {
+                return -1;
+            }
+        }
+        return -1;
+    }
 	
 	function edit_event($id, $start, $end, $all_day, $view, $title, $content) {		
 		$start 		= date('Y-m-d H:i:s', $start);
@@ -190,12 +263,18 @@ class Agenda {
 				break;
 			case 'personal':
 			default:
+                //Getting personal events
 				$this->get_personal_events($start, $end);
+                
+                //Getting platform/admin events
 				$this->get_platform_events($start, $end);
+                
+                //Getting course events
 				$my_course_list = array();
+                
 				if (!api_is_anonymous()) {
 					$my_course_list = CourseManager::get_courses_list_by_user_id(api_get_user_id(), true);
-				}				
+				}
 				if (!empty($my_course_list)) {
 					foreach($my_course_list as $course_info_item) {
 						if (isset($course_id) && !empty($course_id)) {
@@ -290,6 +369,7 @@ class Agenda {
 		$start  = api_get_utc_datetime($start);	
 		$end  	= api_get_utc_datetime($end);
 		$user_id = api_get_user_id();
+        
 		$sql 	= "SELECT * FROM ".$this->tbl_personal_agenda."
 				   WHERE date >= '".$start."' AND (enddate <='".$end."' OR enddate IS NULL) AND user = $user_id";
 		
@@ -302,6 +382,9 @@ class Agenda {
 				$event['className'] 	= 'personal';
 				$event['borderColor'] 	= $event['backgroundColor'] = $this->event_personal_color;
 				$event['editable'] 		= true;
+                
+                $event['sent_to']       = get_lang('Me');
+                $event['type']          = 'personal';
 				
 				if (!empty($row['date']) && $row['date'] != '0000-00-00 00:00:00') {
 					$event['start'] = $this->format_event_date($row['date']);
@@ -310,7 +393,7 @@ class Agenda {
 				if (!empty($row['enddate']) && $row['enddate'] != '0000-00-00 00:00:00') {
 					$event['end'] = $this->format_event_date($row['enddate']);				
 				}
-				$event['description'] = $row['text']; 
+				$event['description'] = $row['text'];
 				$event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
 				$my_events[] = $event;
 				$this->events[]= $event;
@@ -323,7 +406,21 @@ class Agenda {
         
 		$course_id = $course_info['real_id'];
         
-		$group_memberships 	= GroupManager::get_group_ids($course_id, api_get_user_id());	
+        $group_list = GroupManager::get_group_list(null, $course_info['code']);        
+        $group_name_list = array();
+        
+        if (!empty($group_list)) {
+            foreach($group_list as $group) {
+                $group_name_list[$group['id']]= $group['name'];
+            }
+        }
+        
+        if (!api_is_allowed_to_edit()) {
+            $group_memberships 	= GroupManager::get_group_ids($course_id, api_get_user_id());
+        } else {
+            $group_memberships = array_keys($group_name_list);            
+        }
+        
 		$tlb_course_agenda	= Database::get_course_table(TABLE_AGENDA);
 		$tbl_property 		= Database::get_course_table(TABLE_ITEM_PROPERTY);
 	
@@ -334,36 +431,38 @@ class Agenda {
         }
 	
 		if (is_array($group_memberships) && count($group_memberships) >0 ) {
-			$sql = "SELECT DISTINCT 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  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";
+		    if (api_is_allowed_to_edit()) {
+		        $where_condition = "( ip.to_group_id is null OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) ";
+            } else {
+                $where_condition = "( ip.to_user_id = $user_id OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) ";
+            }
+            
+            $sql = "SELECT DISTINCT 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  AND 
+                            ip.tool         ='".TOOL_CALENDAR_EVENT."' AND 
+                            $where_condition AND
+                            ip.visibility   = '1' AND
+                            agenda.c_id     = $course_id AND
+                            ip.c_id         = $course_id";
+                            
+		    
+			
 		} else {
-			if (api_is_allowed_to_edit()) {
-    	         $sql="SELECT DISTINCT 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
-                                AND ip.tool='".TOOL_CALENDAR_EVENT."'                                
-                                AND ip.visibility='1' AND 
-                                agenda.c_id = $course_id AND
-                                ip.c_id = $course_id
-                                ";				
-			} else {
-		        $sql="SELECT DISTINCT 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 
-                            AND ip.tool='".TOOL_CALENDAR_EVENT."'
-                            AND ( ip.to_user_id=$user_id OR ip.to_group_id='0')
-                            AND ip.visibility='1' AND 
-                            agenda.c_id = $course_id AND
-                            ip.c_id = $course_id ";
-			    
-		
-			}
+		    if (api_is_allowed_to_edit()) {
+		        $where_condition = "";                
+            } else {
+                $where_condition = "( ip.to_user_id=$user_id OR ip.to_group_id='0') AND ";
+            }         
+            $sql="SELECT DISTINCT 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 AND
+                    ip.tool='".TOOL_CALENDAR_EVENT."' AND
+                    $where_condition
+                    ip.visibility='1' AND 
+                    agenda.c_id = $course_id AND
+                    ip.c_id = $course_id";  
+			
 		}
 		
 		$result = Database::query($sql);
@@ -393,6 +492,7 @@ class Agenda {
 				}
 				
 				$event['editable'] 		= false;
+				
 				if (api_is_allowed_to_edit() && $this->type == 'course') {
 					$event['editable'] 		= true;
 				}	
@@ -403,6 +503,28 @@ class Agenda {
 				if (!empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00') {
 					$event['end'] = $this->format_event_date($row['end_date']);
 				}	
+                
+                $event['sent_to'] = '';
+                $event['type']    = $this->type;
+                
+                
+                //Event Sent to a group?
+                if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {                    
+                    $event['sent_to'] = $group_name_list[$row['to_group_id']];
+                    $event['type']    = 'group';    
+                }
+
+                //Event sent to a user?
+                if (isset($row['to_user_id'])) {
+                    $event['sent_to'] = $row['to_user_id'];
+                }
+                
+                //Event sent to everyone!
+                if (empty($event['sent_to'])) {
+                    $event['sent_to'] = get_lang('Everyone');
+                }
+                
+                
 				$event['description'] = $row['content'];
 				
 				$event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;					
@@ -438,6 +560,8 @@ class Agenda {
 				$event['allDay'] 	  	= 'false';
 				$event['borderColor'] 	= $event['backgroundColor'] = $this->event_platform_color;
 				$event['editable'] 		= false;
+                
+                $event['type']          = 'admin';
 				
 				if (api_is_platform_admin() && $this->type == 'admin') {
 					$event['editable'] 		= true;

+ 2 - 1
main/calendar/agenda_js.php

@@ -72,7 +72,8 @@ $tpl->assign('button_text', 		json_encode(array(	'today'	=> get_lang('Today'),
 //Calendar Type : course, admin, personal
 $tpl->assign('type', $type);
 //Calendar type label
-$tpl->assign('type_label', get_lang($type.'Calendar'));
+
+$tpl->assign('type_label', get_lang(ucfirst($type).'Calendar'));
 
 //Current user can add event?
 $tpl->assign('can_add_events', $can_add_events);

+ 23 - 26
main/chat/chat_functions.lib.php

@@ -10,10 +10,11 @@
  */
 function exit_of_chat($user_id) {
 	$user_id = intval($user_id);
+    $course_id = api_get_course_int_id();
 	$list_course = array();
  	$list_course = CourseManager::get_courses_list_by_user_id($user_id);
 
-	$group_id = intval($_SESSION['id_group']);
+	$group_id   = intval($_SESSION['id_group']);
 	$session_id = intval($_SESSION['id_session']);
 	
 	$extra_condition = '';
@@ -22,11 +23,11 @@ function exit_of_chat($user_id) {
 	} else {
 		$extra_condition = api_get_session_condition($session_id);
 	}
-
+    $extra_condition.= " AND course_id = $course_id";
  	foreach ($list_course as $courses) {
- 		$response = user_connected_in_chat($user_id,$courses['db_name']);
+ 		$response = user_connected_in_chat($user_id);
  		if ($response === true) {
- 			$tbl_chat_connected = Database::get_course_chat_connected_table($courses['db_name']);
+ 			$tbl_chat_connected = Database::get_course_table(CHAT_CONNECTED_TABLE);
  			$sql = 'DELETE FROM '.$tbl_chat_connected.' WHERE user_id='.$user_id.$extra_condition;
  			Database::query($sql);
  		}
@@ -39,12 +40,14 @@ function exit_of_chat($user_id) {
  * @param string the database name
  * @return boolean
  */
-function user_connected_in_chat ($user_id, $database_name) {
- 	$tbl_chat_connected = Database::get_course_chat_connected_table($database_name);
+function user_connected_in_chat ($user_id) {
+ 	$tbl_chat_connected = Database::get_course_table(CHAT_CONNECTED_TABLE);
 
  	$group_id 	= intval($_SESSION['id_group']);
 	$session_id = intval($_SESSION['id_session']);
 	$user_id 	= intval($user_id);
+    $course_id = api_get_course_int_id();
+    
 	$extra_condition = '';
 	
 	if (!empty($group_id)) {
@@ -53,7 +56,7 @@ function user_connected_in_chat ($user_id, $database_name) {
 		$extra_condition = api_get_session_condition($session_id);
 	}
 
- 	$sql = 'SELECT COUNT(*) AS count FROM '.$tbl_chat_connected .' c WHERE user_id='.$user_id.$extra_condition;
+ 	$sql = 'SELECT COUNT(*) AS count FROM '.$tbl_chat_connected .' c WHERE c_id = '.$course_id.' AND user_id='.$user_id.$extra_condition;
  	$result = Database::query($sql);
  	$count  = Database::fetch_array($result,'ASSOC');
  	return $count['count'] == 1;
@@ -63,16 +66,12 @@ function user_connected_in_chat ($user_id, $database_name) {
  * @param string $database_name (optional)
  * @return void
  */
-function disconnect_user_of_chat($database_name = '') {
-
+function disconnect_user_of_chat() {
 	$list_info_user_in_chat = array();
-
-	if (!empty($database_name)) {
-		$list_info_user_in_chat = users_list_in_chat($database_name);
-	} else {
-		$list_info_user_in_chat = users_list_in_chat();
-	}
-
+    $course_id = api_get_course_int_id();
+    $list_info_user_in_chat = users_list_in_chat();
+    $course_id = api_get_course_int_id();
+    
 	$cd_date           = date('Y-m-d',time());
 	$cdate_h           = date('H',time());
 	$cdate_m           = date('i',time());
@@ -87,14 +86,9 @@ function disconnect_user_of_chat($database_name = '') {
 			$date_db_s  = date('s', strtotime($list_info_user['last_connection']));
 			$date_count_time_seconds=$date_db_h*3600 + $date_db_m*60 + $date_db_s;
 			if ($cd_date == $date_db_date) {
-				if (($cd_count_time_seconds - $date_count_time_seconds) > 5) {
-
-					$tbl_chat_connected = Database::get_course_chat_connected_table();
-					if (!empty($database_name))	{
-						$tbl_chat_connected = Database::get_course_chat_connected_table($database_name);
-					}
-
-			 		$sql = 'DELETE FROM '.$tbl_chat_connected.' WHERE user_id='.$list_info_user['user_id'];
+				if (($cd_count_time_seconds - $date_count_time_seconds) > 5) {					
+                    $tbl_chat_connected = Database::get_course_table(CHAT_CONNECTED_TABLE);					
+			 		$sql = 'DELETE FROM '.$tbl_chat_connected.' WHERE c_id = '.$course_id.' AND user_id ='.$list_info_user['user_id'];
 			 		Database::query($sql);
 				}
 			}
@@ -106,9 +100,11 @@ function disconnect_user_of_chat($database_name = '') {
  * @param string $database_name (optional)
  * @return array user list in chat
  */
-function users_list_in_chat ($database_name = '') {
+function users_list_in_chat() {
 	$list_users_in_chat = array();
- 	$tbl_chat_connected = Database::get_course_chat_connected_table($database_name);
+ 	$tbl_chat_connected = Database::get_course_table(CHAT_CONNECTED_TABLE);
+    $course_id = api_get_course_int_id();
+    
  	$group_id = intval($_SESSION['id_group']);
 	$session_id = intval($_SESSION['id_session']);
 	$extra_condition = '';
@@ -117,6 +113,7 @@ function users_list_in_chat ($database_name = '') {
 	} else{
 		$extra_condition = api_get_session_condition($session_id, false);
 	}
+    $extra_condition.= " AND c_id = $course_id ";
  	$sql = 'SELECT user_id,last_connection FROM '.$tbl_chat_connected.$extra_condition;
  	$result = Database::query($sql);
  	while ($row = Database::fetch_array($result, 'ASSOC')) {

+ 8 - 12
main/chat/chat_hidden.php

@@ -16,12 +16,13 @@ define('FRAME', 'hidden');
 $language_file = array('chat');
 
 require_once '../inc/global.inc.php';
-require_once api_get_path(LIBRARY_PATH).'course.lib.php';
 require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
 require_once 'chat_functions.lib.php';
 
 $tbl_user 				= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_chat_connected 	= Database::get_course_chat_connected_table();
+$tbl_chat_connected 	= Database::get_course_table(CHAT_CONNECTED_TABLE);
+
+$course_id = api_get_course_int_id();
 
 $query = "SELECT username FROM $tbl_user WHERE user_id='".$_user['user_id']."'";
 $result = Database::query($query);
@@ -31,10 +32,6 @@ list($pseudo_user) = Database::fetch_row($result);
 $isAllowed = !(empty($pseudo_user) || !$_cid);
 $isMaster = (bool)$is_courseAdmin;
 
-/*if(!$isAllowed) {
-	exit();
-}*/
-
 $date_now = date('Y-m-d');
 
 $group_id = intval($_SESSION['_gid']);
@@ -49,6 +46,8 @@ if (!empty($group_id)) {
 	$extra_condition = $session_condition;
 }
 
+$extra_condition.= " AND c_id = $course_id";
+
 // get chat path
 $chat_path = '';
 $document_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
@@ -83,9 +82,9 @@ $result = Database::query($sql);
 // The user_id exists so we must do an UPDATE and not a INSERT
 $current_time = date('Y-m-d H:i:s');
 if (Database::num_rows($result) == 0) {
-	$query = "INSERT INTO $tbl_chat_connected(user_id,last_connection,session_id,to_group_id) VALUES('".$_user['user_id']."','$current_time','$session_id','$group_id')";
+	$query = "INSERT INTO $tbl_chat_connected(c_id, user_id,last_connection,session_id,to_group_id) VALUES($course_id, '".$_user['user_id']."','$current_time','$session_id','$group_id')";
 } else {
-	$query = "UPDATE $tbl_chat_connected set last_connection='".$current_time."' WHERE user_id='".$_user['user_id']."' AND session_id='$session_id' AND to_group_id='$group_id'";
+	$query = "UPDATE $tbl_chat_connected set last_connection='".$current_time."' WHERE c_id = $course_id AND user_id='".$_user['user_id']."' AND session_id='$session_id' AND to_group_id='$group_id'";
 }
 
 Database::query($query);
@@ -112,12 +111,10 @@ if (api_get_setting('show_navigation_menu') != 'false') {
    }
 }
 ?>
-
 <form name="formHidden" method="post" action="<?php echo api_get_self().'?cidReq='.$_GET['cidReq']; ?>">
 <input type="hidden" name="chat_size_old" value="<?php echo $chat_size_new; ?>">
 <input type="hidden" name="connected_old" value="<?php echo $connected_new; ?>">
 </form>
-
 <?php
 
 if ($_SESSION["origin"] == 'whoisonline') {  //check if our target has denied our request or not
@@ -132,5 +129,4 @@ if ($_SESSION["origin"] == 'whoisonline') {  //check if our target has denied ou
 		$result = Database::query($sql);
 	}
 }
-
-require 'footer_frame.inc.php';
+require 'footer_frame.inc.php';

+ 1 - 1
main/chat/chat_whoisonline.php

@@ -60,7 +60,7 @@ if (!empty($course)) {
 						t3.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND 
 						t3.course_code = '".$_course['sysCode']."' AND 
 						t2.last_connection>'".$date_inter."' $extra_condition 
-						ORDER BY username";
+						ORDER BY username";                        
 		$result = Database::query($query);
 		$users = Database::store_result($result);
 	} else {

+ 7 - 5
main/course_info/legal.php

@@ -32,9 +32,9 @@ $form->addElement('style_submit_button', null, get_lang('Accept'), 'class="save"
 
 if ($form->validate()) {
     $accept_legal = $form->exportValue('accept_legal');
-    
+        
     if ($accept_legal == 1 ) {
-        CourseManager::save_user_legal($user_id, $course_code, $session_id);
+        $result = CourseManager::save_user_legal($user_id, $course_code, $session_id);        
     }
 }
 
@@ -52,11 +52,13 @@ if (empty($session_id)) {
         api_not_allowed();
     }    
 } else {
+    if (api_is_platform_admin()) {
+        header('Location: '.$url);
+    }
     $user_session_status = SessionManager::get_user_status_in_session($user_id, $course_code, $session_id);
     
-    if (isset($user_session_status)) {
-        
-        $user_accepted_legal = CourseManager::is_user_accepted_legal($user_id, $course_code, $session_id);
+    if (isset($user_session_status)) {        
+        $user_accepted_legal = CourseManager::is_user_accepted_legal($user_id, $course_code, $session_id);        
         if ($user_accepted_legal) {
             //Redirect to course session home
             header('Location: '.$url);

+ 3 - 2
main/create_course/add_course.php

@@ -118,8 +118,9 @@ $form->addRule('wanted_code', get_lang('Max'), 'maxlength', $maxlength);
     $form->addRule('wanted_code', get_lang('ThisFieldIsRequired'), 'required');
 }*/
 
-// The teacher.
-$titular = & $form->add_textfield('tutor_name', array(get_lang('Professor'), get_lang('ExplicationTrainers')), null, array('size' => '60', 'disabled' => 'disabled'));
+// The teacher
+//get_lang('ExplicationTrainers')
+$titular = & $form->add_textfield('tutor_name', array(get_lang('Professor'), null), null, array('size' => '60', 'disabled' => 'disabled'));
 //$form->applyFilter('tutor_name', 'html_filter');
 
 if ($course_validation_feature) {

+ 128 - 8
main/css/base.css

@@ -1368,9 +1368,9 @@ a.personal_agenda:hover, a.personal_agenda:hover {
     font-size: 0.8em;
     margin-right: 10px;
     overflow: hidden;
-    padding: 7px 10px;
+    padding: 13px;
     text-align: center;
-    width: 40px;
+    width: 47px;
     margin-bottom: 65px;
 }
 
@@ -1810,8 +1810,8 @@ button:hover {
     float:left;
     margin:10px;
     padding:12px;
-    width:250px;
-    min-height:294px;
+    width:95%;
+    /* min-height:294px; */
     color: #BBBBBB; 
 }
 
@@ -1843,19 +1843,24 @@ button:hover {
 }
 
 .categories-course-description {
-    margin-left:10px;
+    margin-left:18px;
     font-family:arial;
     font-size:11px;
     margin-bottom: 10px;
+	float:left;
+}
+
+.categories-course-links div {
+	padding-left:10px;
 }
 
 .categories-course-description .course-block-title {
     font-family: arial;
-    font-size: large;
+    font-size: medium;
     margin-bottom: 10px;
     color: #222222;
-    min-height:60px;
 }
+
 .categories-course-description .course-block-teacher {
     font-size: large;
     font-style: italic;
@@ -3781,7 +3786,7 @@ form div.error input, form div.error textarea {
   -webkit-border-radius: 3px;
   -moz-border-radius: 3px;
   border-radius: 3px;
-  width:120px;
+    width:134px;
 }
 
 .label_tag.personal_event { 
@@ -3790,10 +3795,17 @@ form div.error input, form div.error textarea {
 .label_tag.admin_event { 
      background:red;
 }
+
 .label_tag.course_event { 
      background:#458B00;
 }
 
+.label_tag.group_event { 
+     background:#A0522D;
+}
+
+
+
 
 .label_tag.important {
     background-color: #c43c35;
@@ -4050,3 +4062,111 @@ input.liteoption {
     text-align: left;
     vertical-align: middle;
 }
+
+#no-data-view {
+    padding: 20px 0 0px;
+    text-align: center;
+}
+
+div#no-data-view img {
+    margin-bottom: 25px;
+}
+
+
+div#no-data-view h2 {
+    border: 0 none;
+    color: #212121;
+    font-size: 18px;
+    font-weight: bold;
+    margin: 0 0 6px;
+    padding: 0;
+}
+
+div#no-data-view div.controls {
+    padding-top: 1px;
+}
+
+
+
+
+    /*             styles for the star rater                */  
+    .star-rating{
+        list-style:none;
+        margin: 0px;
+        padding:0px;
+        width: 125px;
+        height: 25px;
+        position: relative;
+        overflow:hidden;
+        background: url(../img/alt_star.gif) top left repeat-x;        
+    }
+    .star-rating li{
+        padding:0px;
+        margin:0px;
+        width:25px;
+        height:25px;
+        /*\*/
+        float: left;
+        /* */
+    }
+    .star-rating li a{
+        display:block;
+        width:25px;
+        height: 25px;
+        line-height:25px;       
+        text-decoration: none;
+        text-indent: -9000px;
+        z-index: 20;
+        position: absolute;
+        padding: 0px;
+        overflow:hidden;
+    }
+    .star-rating li a:hover{
+        background: url(../img/alt_star.gif) left bottom;
+        z-index: 2;
+        left: 0px;
+        border:none;
+    }
+    .star-rating a.one-star{
+        left: 0px;
+    }
+    .star-rating a.one-star:hover{
+        width:25px;
+    }
+    .star-rating a.two-stars{
+        left:25px;
+    }
+    .star-rating a.two-stars:hover{
+        width: 50px;
+    }
+    .star-rating a.three-stars{
+        left: 50px;
+    }
+    .star-rating a.three-stars:hover{
+        width: 75px;
+    }
+    .star-rating a.four-stars{
+        left: 75px;
+    }   
+    .star-rating a.four-stars:hover{
+        width: 100px;
+    }
+    .star-rating a.five-stars{
+        left: 100px;
+    }
+    .star-rating a.five-stars:hover{
+        width: 125px;
+    }
+    .star-rating li.current-rating{
+        background: url(../img/alt_star.gif) left center;
+        position: absolute;
+        height: 25px;
+        display: block;
+        text-indent: -9000px;
+        z-index: 1;
+    }
+    
+    /* remove halo effect in firefox   */
+    a:active{
+        outline: none;
+    }       

+ 6 - 1
main/document/document.php

@@ -57,6 +57,11 @@ unset($_SESSION['paint_dir']);
 DocumentManager::create_directory_certificate_in_course(api_get_course_id());
 
 $course_info 	 = api_get_course_info();
+
+if (empty($course_info)) {
+    api_not_allowed();
+}
+
 $course_dir      = $course_info['path'].'/document';
 $sys_course_path = api_get_path(SYS_COURSE_PATH);
 $base_work_dir   = $sys_course_path.$course_dir;
@@ -944,7 +949,7 @@ if (isset($docs_and_folders) && is_array($docs_and_folders)) {
         // Size (or total size of a directory)
         $size = $document_data['filetype'] == 'folder' ? get_total_folder_size($document_data['path'], $is_allowed_to_edit) : $document_data['size'];
         
-        // Get the title or the basename depending on what we're using
+        // Get the title or the basename depending on what we're using        
         if ($use_document_title == 'true' && $document_data['title'] != '') {
             $document_name = $document_data['title'];
         } else {

+ 2 - 1
main/document/downloadfolder.inc.php

@@ -61,11 +61,12 @@ 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 
+			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 
+					props.c_id          = ".$course_id." AND
 					docs.c_id 			= ".$course_id." ";
 	$query = Database::query($sql);
 	// Add tem to the zip file

+ 49 - 89
main/document/edit_document.php

@@ -87,7 +87,7 @@ if (api_is_in_group()) {
 }
 
 if (isset($_GET['id'])) {
-    $document_data = DocumentManager::get_document_data_by_id($_GET['id'], api_get_course_id());
+    $document_data  = DocumentManager::get_document_data_by_id($_GET['id'], api_get_course_id(), true);
     $document_id    = $document_data['id'];
     $file           = $document_data['path'];
     $parent_id      = DocumentManager::get_document_id(api_get_course_info(), dirname($file));    
@@ -96,12 +96,12 @@ if (isset($_GET['id'])) {
     
     $doc            = basename($file);
     $my_cur_dir_path = Security::remove_XSS($_GET['curdirpath']);
+    $readonly = $document_data['readonly'];
 }
 
 if (empty($document_data)) {
     api_not_allowed();
-}
-  
+}  
 
 /*
 //I'm in the certification module?
@@ -153,31 +153,6 @@ $noPHP_SELF = true;
 
 /*	Other initialization code */
 
-/* Please, do not modify this dirname formatting */
-
-if (strstr($dir, '..')) {
-	$dir = '/';
-}
-
-if ($dir[0] == '.') {
-	$dir = substr($dir, 1);
-}
-
-if ($dir[0] != '/') {
-	$dir = '/'.$dir;
-}
-
-if ($dir[strlen($dir) - 1] != '/') {
-	$dir .= '/';
-}
-
-$filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
-
-if (!is_dir($filepath)) {
-	$filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
-	$dir = '/';
-}
-
 $dbTable = Database::get_course_table(TABLE_DOCUMENT);
 $course_id = api_get_course_int_id();
 
@@ -193,6 +168,19 @@ if (!$is_certificate_mode)
 else
 	$interbreadcrumb[]= array (	'url' => '../gradebook/'.$_SESSION['gradebook_dest'], 'name' => get_lang('Gradebook'));
 
+
+// Interbreadcrumb for the current directory root path
+if (empty($document_data['parents'])) {
+    $interbreadcrumb[] = array('url' => '#', 'name' => $document_data['title']);
+} else {    
+    foreach($document_data['parents'] as $document_sub_data) {
+        if ($document_data['title'] == $document_sub_data['title']) {
+            continue;
+        }
+        $interbreadcrumb[] = array('url' => $document_sub_data['document_url'], 'name' => $document_sub_data['title']);
+    }
+}
+
 if (!is_allowed_to_edit) {
 	api_not_allowed(true);
 }
@@ -208,9 +196,7 @@ if (!is_allowed_to_edit()) {
 
 /* MAIN TOOL CODE */
 
-/*	Code to change the comment
-	Step 2. React on POST data
-	(Step 1 see below) */
+/*	Code to change the comment	*/
 
 if (isset($_POST['comment'])) {
 	// Fixing the path if it is wrong	
@@ -222,31 +208,16 @@ if (isset($_POST['comment'])) {
 	$info_message     = get_lang('fileModified');
 }
 
-/*	Code to change the name
-	Step 2. react on POST data - change the name
-	(Step 1 see below) */
-
+/*	Code to rename the file name */
+//var_dump($_POST['renameTo']);
 if (isset($_POST['renameTo'])) {
-	$info_message = change_name($baseWorkDir, $_GET['sourceFile'], $_POST['renameTo'], $dir, $doc);
-}
-
-/*	Code to change the comment
-	Step 1. Create dialog box. */
-
-/** TODO: Check whether this code is still used **/
-/* Search the old comment */  // RH: metadata: added 'id,'
-$result = Database::query("SELECT id, comment, title FROM $dbTable WHERE c_id = $course_id AND id = ".$document_id);
-
-while ($row = Database::fetch_array($result, 'ASSOC')) {
-	$oldComment = $row['comment'];
-	$oldTitle   = $row['title'];
-	$docId      = $row['id'];  // RH: metadata
+    $info_message = change_name($baseWorkDir, $_GET['sourceFile'], $_POST['renameTo'], $dir, $doc);
 }
 
 /*	WYSIWYG HTML EDITOR - Program Logic */
 
 if ($is_allowed_to_edit) {
-	if ($_POST['formSent'] == 1) {
+	if ($_POST['formSent'] == 1) {	    
 		if (isset($_POST['renameTo'])) {
 			$_POST['filename'] = disable_dangerous_file($_POST['renameTo']);
 			$extension = explode('.', $_POST['filename']);
@@ -262,11 +233,7 @@ if ($is_allowed_to_edit) {
 		if (!strstr($content, '/css/frames.css')) {
 			$content=str_replace('</title></head>', '</title><link rel="stylesheet" href="../css/frames.css" type="text/css" /></head>', $content);
 		}
-		/*
-        if (!ctype_alnum($_POST['extension'])) {
-            header('Location: document.php?msg=WeirdExtensionDeniedInPost');
-            exit ();
-	    }*/
+
         $extension = $_POST['extension'];
 		$file = $dir.$filename.'.'.$extension;
 		$read_only_flag = $_POST['readonly'];
@@ -277,16 +244,13 @@ if ($is_allowed_to_edit) {
 
 		if (empty($filename)) {
 			$msgError = get_lang('NoFileName');
-		} else {		    
-		    if ($document_data['filetype'] == 'file') {
-                $file_size = filesize($filepath.$filename.'.'.$extension);
-		    } else {
-		        $file_size = filesize($filepath.$filename);		        
-		    }		    
+		} else {
+		    		    
+		    $file_size = filesize($document_data['absolute_path']);	    
+		    		    
 			if ($read_only_flag == 0) {
 				if (!empty($content)) {
-					if ($fp = @fopen($filepath.$filename.'.'.$extension, 'w')) {
-						$content = text_filter($content);
+					if ($fp = @fopen($document_data['absolute_path'], 'w')) {						
 						// For flv player, change absolute paht temporarely to prevent from erasing it in the following lines
 						$content = str_replace(array('flv=h', 'flv=/'), array('flv=h|', 'flv=/|'), $content);
 
@@ -300,7 +264,10 @@ if ($is_allowed_to_edit) {
 
  						fputs($fp, $content);
 						fclose($fp);
-						if (!is_dir($filepath.'css')) {
+                        
+                        $filepath = $document_data['absolute_parent_path'];
+                        
+						if (!is_dir($filepath.'css')) {						    
 							mkdir($filepath.'css', api_get_permissions_for_new_directories());
 							$doc_id = add_document($_course, $dir.'css', 'folder', 0, 'css');
 							api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id(), null, null, null, null, $current_session_id);
@@ -328,9 +295,8 @@ if ($is_allowed_to_edit) {
 							//header('Location: document.php?id='.urlencode($dir));
 							
 							$my_id = DocumentManager::get_document_id($_course, $dir_modified);
-							header('Location: document.php?id='.$my_id);
-							
-							exit ();
+							header('Location: document.php?id='.$my_id);							
+							exit;
 						} else {
 							//$msgError = get_lang('Impossible');
 						}
@@ -352,25 +318,24 @@ if ($is_allowed_to_edit) {
 }
 
 // Replace relative paths by absolute web paths (e.g. './' => 'http://www.chamilo.org/courses/ABC/document/')
-if (file_exists($filepath.$doc)) {
-	$extension = explode('.', $doc);
-	$extension = $extension[sizeof($extension) - 1];
-	$filename = str_replace('.'.$extension, '', $doc);
-	$extension = strtolower($extension);
+if (file_exists($document_data['absolute_path'])) {	
+    $path_info = pathinfo($document_data['absolute_path']);
+    $filename = $path_info['filename'];    
+    $extension = $path_info['extension'];
 
 	if (in_array($extension, array('html', 'htm'))) {
-		$content = file($filepath.$doc);
+		$content = file($document_data['absolute_path']);
 		$content = implode('', $content);
 		$path_to_append = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$dir;
-		$content = str_replace('="./', '="'.$path_to_append, $content);
-		$content = str_replace('mp3player.swf?son=.%2F', 'mp3player.swf?son='.urlencode($path_to_append), $content);
+	//	$content = str_replace('="./', '="'.$path_to_append, $content);
+		//$content = str_replace('mp3player.swf?son=.%2F', 'mp3player.swf?son='.urlencode($path_to_append), $content);
 	}
 }
 
 /*	Display user interface */
 
 // Display the header
-$nameTools = get_lang('EditDocument') . ': '.Security::remove_XSS($oldTitle);
+$nameTools = get_lang('EditDocument') . ': '.Security::remove_XSS($document_data['title']);
 Display::display_header($nameTools, 'Doc');
 
 
@@ -386,15 +351,8 @@ if (isset($info_message)) {
 	}
 }
 
-
-// Readonly
-$sql = 'SELECT id, readonly FROM '.$dbTable.' WHERE path LIKE BINARY "'.$dir.$doc.'"';
-$rs = Database::query($sql);
-$readonly = Database::result($rs, 0, 'readonly');
-$doc_id = Database::result($rs, 0, 'id');
-
 // Owner
-$document_info  = api_get_item_property_info(api_get_course_int_id(),'document', $doc_id);
+$document_info  = api_get_item_property_info(api_get_course_int_id(),'document', $document_id);
 $owner_id       = $document_info['insert_user_id'];
 $last_edit_date = $document_info['lastedit_date'];
 
@@ -416,9 +374,10 @@ if ($owner_id == api_get_user_id() || api_is_platform_admin() || $is_allowed_to_
 	$form->addElement('hidden', 'origin');
 	$form->addElement('hidden', 'origin_opt');
 
-	if ($use_document_title) {
-		$form->add_textfield('title', get_lang('Title'));
-		$defaults['title'] = $oldTitle;
+    $form->add_textfield('title', get_lang('Title'));
+    
+	if ($use_document_title) {		
+		$defaults['title'] = $document_data['title'];
 	} else {
 		$form->addElement('hidden', 'renameTo');
 	}
@@ -443,7 +402,7 @@ if ($owner_id == api_get_user_id() || api_is_platform_admin() || $is_allowed_to_
 	}
 
 	if (!$group_document && !is_my_shared_folder(api_get_user_id(), $my_cur_dir_path, $current_session_id)) {
-		$metadata_link = '<a href="../metadata/index.php?eid='.urlencode('Document.'.$docId).'">'.get_lang('AddMetadata').'</a>';
+		$metadata_link = '<a href="../metadata/index.php?eid='.urlencode('Document.'.$document_data['id']).'">'.get_lang('AddMetadata').'</a>';
 
 		//Updated on field
 		$last_edit_date = api_get_local_time($last_edit_date, null, date_default_timezone_get());
@@ -474,7 +433,7 @@ if ($owner_id == api_get_user_id() || api_is_platform_admin() || $is_allowed_to_
 	$defaults['file_path'] = Security::remove_XSS($_GET['file']);
 	$defaults['commentPath'] = $file;
 	$defaults['renameTo'] = $file_name;
-	$defaults['comment'] = $oldComment;
+	$defaults['comment'] = $document_data['comment'];
 	$defaults['origin'] = Security::remove_XSS($_GET['origin']);
 	$defaults['origin_opt'] = Security::remove_XSS($_GET['origin_opt']);
 
@@ -520,6 +479,7 @@ Display::display_footer();
 	It returns nothing.
 */
 function change_name($base_work_dir, $source_file, $rename_to, $dir, $doc) {
+    var_dump($source_file, $rename_to);
 	$file_name_for_change = $base_work_dir.$dir.$source_file;
 	//api_display_debug_info("call my_rename: params $file_name_for_change, $rename_to");
     $rename_to = disable_dangerous_file($rename_to); // Avoid renaming to .htaccess file

+ 34 - 10
main/exercice/exercice.php

@@ -34,6 +34,7 @@ require_once 'exercise.class.php';
 require_once 'exercise.lib.php';
 require_once 'question.class.php';
 require_once 'answer.class.php';
+require_once 'testcategory.class.php';
 require_once api_get_path(LIBRARY_PATH) . 'fileManage.lib.php';
 require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
 require_once 'hotpotatoes.lib.php';
@@ -532,7 +533,7 @@ if (!empty($exercise_list)) {
                     $title = Display::tag('font', $row['title'], array('style'=>'color:grey'));
                 } else {
                     $title = $row['title'];
-                }            
+                }
                     
                 $count = intval(count_exercise_result_not_validated($my_exercise_id, $course_code, $session_id));
                 
@@ -555,8 +556,11 @@ if (!empty($exercise_list)) {
                                     
                 if ($session_id == $row['session_id']) {
                     //Settings
-                    $actions =  Display::url(Display::return_icon('edit.png',get_lang('Edit'),'',22), 'admin.php?'.api_get_cidreq().'&exerciseId='.$row['id']);                        
-                    $actions .='<a href="exercise_report.php?' . api_get_cidreq() . '&exerciseId='.$row['id'].'">'.Display :: return_icon('test_results.png', get_lang('Results'),'',22).'</a>';                        
+                    $actions =  Display::url(Display::return_icon('edit.png',get_lang('Edit'),'',22), 'admin.php?'.api_get_cidreq().'&exerciseId='.$row['id']);
+                    
+                    //Exercise results                        
+                    $actions .='<a href="exercise_report.php?' . api_get_cidreq() . '&exerciseId='.$row['id'].'">'.Display :: return_icon('test_results.png', get_lang('Results'),'',22).'</a>';                    
+                                            
                     //Export
                     $actions .= Display::url(Display::return_icon('cd.gif', get_lang('CopyExercise')),       '', array('onclick'=>"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToCopy'),ENT_QUOTES,$charset))." ".addslashes($row['title'])."?"."')) return false;",'href'=>'exercice.php?'.api_get_cidreq().'&choice=copy_exercise&sec_token='.$token.'&exerciseId='.$row['id']));
                     //Clean exercise                    
@@ -571,9 +575,8 @@ if (!empty($exercise_list)) {
                     $actions .= Display::url(Display::return_icon('export_qti2.png','IMS/QTI','','22'),        'exercice.php?choice=exportqti2&exerciseId='.$row['id']);
                 } else { 
                     // not session                 
-                    $actions = Display::return_icon('edit_na.png', get_lang('ExerciseEditionNotAvailableInSession'));                        
-                    
-                    $actions .='<a href="exercise_report.php?' . api_get_cidreq() . '&exerciseId='.$row['id'].'">'.Display :: return_icon('test_results.png', get_lang('Results'),'',22).'</a>';                        
+                    $actions = Display::return_icon('edit_na.png', get_lang('ExerciseEditionNotAvailableInSession'));                    
+                    $actions .='<a href="exercise_report.php?' . api_get_cidreq() . '&exerciseId='.$row['id'].'">'.Display :: return_icon('test_results.png', get_lang('Results'),'',22).'</a>';                                            
                     $actions .= Display::url(Display::return_icon('cd.gif',   get_lang('CopyExercise')),     '',  array('onclick'=>"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToCopy'),ENT_QUOTES,$charset))." ".addslashes($row['title'])."?"."')) return false;",'href'=>'exercice.php?'.api_get_cidreq().'&choice=copy_exercise&sec_token='.$token.'&exerciseId='.$row['id']));                           
                 }
                 
@@ -652,7 +655,7 @@ if (!empty($exercise_list)) {
                         WHERE   exe_exo_id      = ".$row['id']." AND 
                                 exe_user_id     = ".api_get_user_id()." AND 
                                 exe_cours_id    = '".api_get_course_id()."' AND 
-                                status         <> 'incomplete' AND 
+                                status          <> 'incomplete' AND 
                                 orig_lp_id      = 0 AND 
                                 orig_lp_item_id = 0 AND 
                                 session_id      =  '" . api_get_session_id() . "'
@@ -709,15 +712,26 @@ if (!empty($exercise_list)) {
                     } else {                            
                         $attempt_text = get_lang('CantShowResults');
                     }
-                }                    
+                }
+                       
+                $class_tip = '';
                 
                 if (empty($num)) {
                     $num = '';
-                }                        
+                } else {
+                    $class_tip = 'link_tooltip';
+                    //@todo use sprintf and show the results validated by the teacher
+                    if ($num == 1 ) {
+                        $num = $num.' '.get_lang('Result');
+                    } else {
+                        $num = $num.' '.get_lang('Results');
+                    }
+                    $num = '<span class="tooltip" style="display: none;">'.$num.'</span>';
+                }                 
                 $item .=  Display::tag('td', $attempt_text);
                                  
                 //See results
-                $actions =' '.$num.' <a href="exercise_report.php?' . api_get_cidreq() . '&exerciseId='.$row['id'].'">   '.Display::return_icon('test_results.png', get_lang('Results'),'',22).' </a>';
+                $actions = '<a class="'.$class_tip.'" id="tooltip_'.$row['id'].'" href="exercise_report.php?' . api_get_cidreq() . '&exerciseId='.$row['id'].'">'.$num.Display::return_icon('test_results.png', get_lang('Results'),'',22).' </a>';
             }                
             $class = 'row_even';
             if ($count % 2) {
@@ -729,6 +743,16 @@ if (!empty($exercise_list)) {
             $count++;
         } // end foreach()
     } 
+} else {
+    if ($is_allowedToEdit && $origin != 'learnpath') {  
+        echo '<div id="no-data-view">';
+        echo '<h2>'.get_lang('Quiz').'</h2>';
+        echo Display::return_icon('quiz.png', '', array(), 64);
+        echo '<div class="controls">';    
+        echo Display::url(get_lang('NewEx'), 'exercise_admin.php?' . api_get_cidreq(), array('class' => 'a_button white'));
+        echo '</div>';
+        echo '</div>';
+    }
 }
 // end exercise list
 

+ 10 - 20
main/exercice/exercise.lib.php

@@ -27,8 +27,6 @@ $main_course_user_table     = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 $TBL_TRACK_EXERCICES        = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
 $TBL_TRACK_ATTEMPT          = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
-
-
 /**
  * Shows a question
  * 
@@ -352,8 +350,6 @@ function showQuestion($questionId, $only_questions = false, $origin = false, $cu
 					api_preg_match_all('/\[[^]]+\]/', $user_choice[0]['answer'], $student_answer_list);
 					$student_answer_list = $student_answer_list[0];
 				}
-				
-				//var_dump($teacher_answer_list, $student_answer_list);				
 								
 				if (!empty($teacher_answer_list) && !empty($student_answer_list)) {
 				    $teacher_answer_list = $teacher_answer_list[0];
@@ -756,6 +752,8 @@ function get_count_exam_results() {
     // I know it's bad to add a static integer here... but
     // it factorise function get_exam_results_data
     // and I think it worths it.
+    //This is not bad for the hardcoded value, this is bad because you call 2 times get_exam_results_data()! jm
+    //@todo use a real count select I know the sql constructions are 
     $tabres = get_exam_results_data(0, 9999999, 0, "ASC");
     return count($tabres);
 }
@@ -771,21 +769,13 @@ function get_exam_results_data($from, $number_of_items, $column, $direction) {
     
     $is_tutor                   = api_is_allowed_to_edit(true);
     $is_tutor_course            = api_is_course_tutor();
-    $tbl_course_rel_user        = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-    $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_EXERCICE_ANSWER        = Database :: get_course_table(TABLE_QUIZ_ANSWER);
-    $TBL_EXERCICE_QUESTION      = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
-    $TBL_EXERCICES              = Database :: get_course_table(TABLE_QUIZ_TEST);
-    $TBL_QUESTIONS              = Database :: get_course_table(TABLE_QUIZ_QUESTION);
+    
+    $TBL_USER                   = Database :: get_main_table(TABLE_MAIN_USER);    
+    $TBL_EXERCICES              = Database :: get_course_table(TABLE_QUIZ_TEST);    
     $TBL_TRACK_EXERCICES        = 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);
-    $TBL_TRACK_ATTEMPT_RECORDING= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
-    $TBL_LP_ITEM_VIEW           = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
-    $TBL_LP_ITEM                = Database :: get_course_table(TABLE_LP_ITEM);
-    $TBL_LP_VIEW                = Database :: get_course_table(TABLE_LP_VIEW);
+    $TBL_TRACK_ATTEMPT_RECORDING= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);    
     $TBL_GROUP_REL_USER         = Database :: get_course_table(TABLE_GROUP_USER);
     
     $session_id_and = ' AND te.session_id = ' . api_get_session_id() . ' ';
@@ -992,7 +982,7 @@ function get_exam_results_data($from, $number_of_items, $column, $direction) {
         $number_of_items    = intval($number_of_items);
         $sql               .= " ORDER BY col$column $direction ";
         $sql               .= " LIMIT $from, $number_of_items";
-    
+        
         $results = array();
         
         $resx = Database::query($sql);
@@ -1006,7 +996,7 @@ function get_exam_results_data($from, $number_of_items, $column, $direction) {
         $lang_nostartdate = get_lang('NoStartDate') . ' / ';    
         
         if (is_array($results)) {
-            $users_array_id = array ();
+            $users_array_id = array();
             if ($_GET['gradebook'] == 'view') {
                 $filter_by_no_revised = true;
                 $from_gradebook = true;
@@ -1137,12 +1127,12 @@ function get_exam_results_data($from, $number_of_items, $column, $direction) {
                         }
                     } else {
                     	$attempt_url 	= api_get_path(WEB_CODE_PATH).'exercice/result.php?'.api_get_cidreq().'&id='.$results[$i]['exid'].'&id_session='.api_get_session_id().'&height=500&width=750';
-                    	$attempt_link 	= Display::url(get_lang('Show'), $attempt_url, array('class'=>'thickbox'))."&nbsp;&nbsp;&nbsp;";
+                    	$attempt_link 	= Display::url(get_lang('Show'), $attempt_url, array('class'=>'thickbox a_button white small'))."&nbsp;&nbsp;&nbsp;";
                     	
                     	$html_link.= $attempt_link;
                     	
                         if ($revised) {
-                        	$html_link.= Display::span(get_lang('Validated'), array('class'=>'label_tag notice'));                            
+                        	$html_link.= Display::span(get_lang('Validated'), array('class'=>'label_tag success'));                            
                         } else {
                         	$html_link.= Display::span(get_lang('NotValidated'), array('class'=>'label_tag notice'));                            
                         }

+ 30 - 29
main/exercice/exercise_report.php

@@ -27,7 +27,6 @@ $htmlHeadXtra[] = api_get_jquery_ui_js();
 // Access control
 api_protect_course_script(true);
 
-
 // including additional libraries
 require_once 'exercise.class.php';
 require_once 'exercise.lib.php';
@@ -61,18 +60,23 @@ $TBL_LP_ITEM_VIEW           = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
 $TBL_LP_ITEM                = Database :: get_course_table(TABLE_LP_ITEM);
 
 
-$course_id = api_get_course_int_id();
+$course_id      = api_get_course_int_id();
+$exercise_id    = isset($_REQUEST['exerciseId']) ? intval($_REQUEST['exerciseId']) : null;
 
+if (empty($exercise_id)) {
+    api_not_allowed();
+}
 
-if (empty ($exerciseId)) {
-    $exerciseId = intval($_REQUEST['exerciseId']);
+if (!empty($exercise_id))
+    $parameters['exerciseId'] = $exercise_id;
+if (!empty($_GET['path'])) {
+    $parameters['path'] = Security::remove_XSS($_GET['path']);
 }
 
-// 
 // filter display by student group
 // if $_GET['filterByGroup'] = -1 => do not filter
 // else, filter by group_id (0 for no group)
-//
+
 $filterByGroup = -1;
 if (isset($_GET['filterByGroup']) && is_numeric($_GET['filterByGroup'])) {
     $filterByGroup = Security::remove_XSS($_GET['filterByGroup']);
@@ -142,7 +146,7 @@ if ($_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_G
     $from              = $teacher_info['mail'];
     $from_name         = api_get_person_name($teacher_info['firstname'], $teacher_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
     
-    $url               = api_get_path(WEB_CODE_PATH) . 'exercice/exercise_report.php?' . api_get_cidreq() . '&id_session='.$session_id.'&exerciseId='.$exerciseId; 
+    $url               = api_get_path(WEB_CODE_PATH) . 'exercice/exercise_report.php?' . api_get_cidreq() . '&id_session='.$session_id.'&exerciseId='.$exercise_id; 
 
     $my_post_info      = array();
     $post_content_id   = array();
@@ -252,11 +256,9 @@ if ($is_allowedToEdit && $origin != 'learnpath') {
               Display::return_icon('save.png',   get_lang('Export'),'',32).'</a>';          
     }
 } else {
-    $actions .= '<a href="' . api_add_url_param($_SERVER['REQUEST_URI'], 'show=test') . '">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'','32').'</a>';
+    $actions .= '<a href="exercice.php">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'','32').'</a>';
 }
 
-
-
 //Deleting an attempt
 if ($_GET['delete'] == 'delete' && ($is_allowedToEdit || api_is_coach()) && !empty ($_GET['did']) && $_GET['did'] == strval(intval($_GET['did']))) {
     $sql = 'DELETE FROM ' . $TBL_TRACK_EXERCICES . ' WHERE exe_id = ' . intval($_GET['did']); //_GET[did] filtered by entry condition    
@@ -265,11 +267,10 @@ if ($_GET['delete'] == 'delete' && ($is_allowedToEdit || api_is_coach()) && !emp
     Database::query($sql);
     
     $filter=Security::remove_XSS($_GET['filter']);
-    header('Location: exercise_report.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&filter=' . $filter . '&exerciseId='.$exerciseId.'&filter_by_user='.$_GET['filter_by_user']);
+    header('Location: exercise_report.php?cidReq=' . Security::remove_XSS($_GET['cidReq']) . '&filter=' . $filter . '&exerciseId='.$exercise_id.'&filter_by_user='.$_GET['filter_by_user']);
     exit;
 }
 
-
 if (api_is_allowed_to_edit(null,true)) {
     if (!$_GET['filter']) {
         $filter_by_not_revised = true;
@@ -289,6 +290,13 @@ if (api_is_allowed_to_edit(null,true)) {
         default :
             null;
     }
+    
+    //Report by question
+    $actions .= Display::url(Display::return_icon('statistics_admin.gif', get_lang("ReportByQuestion")), 'stats.php?exerciseId='.$exercise_id);
+    
+    //Live results
+    $actions .='<a href="live_stats.php?' . api_get_cidreq() . '&exerciseId='.$exercise_id.'">'.Display :: return_icon('activity_monitor.png', get_lang('LiveResults'),'',32).'</a>';
+    
     if (!empty($_GET['exerciseId']) && empty($_GET['filter_by_user'])) {
         if ($_GET['filter'] == '1' or !isset ($_GET['filter']) or $_GET['filter'] == 0 ) {
             $view_result = '<a href="' . api_get_self() . '?cidReq=' . api_get_course_id() . '&filter=2&id_session='.intval($_GET['id_session']).'&exerciseId='.intval($_GET['exerciseId']).'&gradebook='.$gradebook.'" >'.Display :: return_icon('exercice_check.png', get_lang('ShowCorrectedOnly'),'','32').'</a>';
@@ -296,14 +304,12 @@ if (api_is_allowed_to_edit(null,true)) {
             $view_result = '<a href="' .api_get_self() . '?cidReq=' . api_get_course_id() . '&filter=1&id_session='.intval($_GET['id_session']).'&exerciseId='.intval($_GET['exerciseId']).'&gradebook='.$gradebook.'" >'.Display :: return_icon('exercice_uncheck.png', get_lang('ShowUnCorrectedOnly'),'','32').'</a>';
         }
         $actions .= $view_result;
-        // 
+         
         // filter by student group menu
-        // 
-        $exercice_id = intval($_GET['exerciseId']);
         $actions .= "<script type='text/javascript'>";
         $actions .= "      function doFilterByGroup() {";
         $actions .= "          var IdGroup = document.getElementById('groupFilter').value;";
-        $actions .= "          var goToUrl = \"".api_get_self()."?".api_get_cidreq()."&filter=$filter&gradebook=$gradebook&exerciseId=$exercice_id;$quiz_results_per_page&filterByGroup=\"+IdGroup;";
+        $actions .= "          var goToUrl = \"".api_get_self()."?".api_get_cidreq()."&filter=$filter&gradebook=$gradebook&exerciseId=$exercise_id;$quiz_results_per_page&filterByGroup=\"+IdGroup;";
         $actions .= "          self.location.href=goToUrl;";
         $actions .= "      }";
         $actions .= "        </script>";
@@ -311,15 +317,11 @@ if (api_is_allowed_to_edit(null,true)) {
         $actions .= Display::return_icon('group.gif', get_lang("FilterByGroup"));
         $actions .= displayGroupMenu("groupFilter", $filterByGroup, "doFilterByGroup()")."&nbsp;";
     }
+    
 }
 
 $parameters=array('cidReq'=>Security::remove_XSS($_GET['cidReq']),'filter' => Security::remove_XSS($_GET['filter']),'gradebook' =>Security::remove_XSS($_GET['gradebook']));
-$exercise_id = intval($_GET['exerciseId']);
-if (!empty($exercise_id))
-    $parameters['exerciseId'] = $exercise_id;
-if (!empty($_GET['path'])) {
-    $parameters['path'] = Security::remove_XSS($_GET['path']);
-}
+
 
 $table = new SortableTable('quiz_results', 'get_count_exam_results', 'get_exam_results_data', 1, 10);
 $table->set_additional_parameters($parameters);
@@ -339,7 +341,7 @@ if ($is_allowedToEdit || $is_tutor) {
 	$table->set_header(6, get_lang('Date'));    
 	$table->set_header(7, get_lang('Score'),false);
     $table->set_header(8, get_lang('Status'), false);
-	$table->set_header(9, get_lang('CorrectTest'), false);   
+	$table->set_header(9, get_lang('Actions'), false);   
 	
 } else {
     $table->set_header(0, get_lang('Exercice'));
@@ -350,13 +352,12 @@ if ($is_allowedToEdit || $is_tutor) {
 }	 
 $content = $table->return_table();	
 
-
 if ($is_allowedToEdit || $is_tutor) {
     $nameTools = get_lang('StudentScore');              
     $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook","name" => get_lang('Exercices'));
     $objExerciseTmp = new Exercise();        
-    if ($objExerciseTmp->read($exerciseId)) {
-        $interbreadcrumb[] = array("url" => "admin.php?exerciseId=".$exerciseId, "name" => $objExerciseTmp->name);    
+    if ($objExerciseTmp->read($exercise_id)) {
+        $interbreadcrumb[] = array("url" => "admin.php?exerciseId=".$exercise_id, "name" => $objExerciseTmp->name);    
     }
 } else {
     $nameTools = get_lang('YourScore');
@@ -400,9 +401,9 @@ $extra =  '<script type="text/javascript">
     </script>';
 
 $extra .= '<div id="dialog-confirm" title="'.get_lang("ConfirmYourChoice").'">';
-    $extra .= Display::tag('p', Display::input('radio', 'export_format', 'csv', array('checked'=>'1', 'id'=>'export_format_csv_label')). Display::tag('label', get_lang('ExportAsCSV'), array('for'=>'export_format_csv_label')));
-    $extra .= Display::tag('p', Display::input('radio', 'export_format', 'xls', array('id'=>'export_format_xls_label')). Display::tag('label', get_lang('ExportAsXLS'), array('for'=>'export_format_xls_label')));   
-    $extra .= Display::tag('p', Display::input('checkbox', 'load_extra_data',  '0',array('id'=>'load_extra_data_id')). Display::tag('label', get_lang('LoadExtraData'), array('for'=>'load_extra_data_id')));
+$extra .= Display::tag('p', Display::input('radio', 'export_format', 'csv', array('checked'=>'1', 'id'=>'export_format_csv_label')). Display::tag('label', get_lang('ExportAsCSV'), array('for'=>'export_format_csv_label')));
+$extra .= Display::tag('p', Display::input('radio', 'export_format', 'xls', array('id'=>'export_format_xls_label')). Display::tag('label', get_lang('ExportAsXLS'), array('for'=>'export_format_xls_label')));   
+$extra .= Display::tag('p', Display::input('checkbox', 'load_extra_data',  '0',array('id'=>'load_extra_data_id')). Display::tag('label', get_lang('LoadExtraData'), array('for'=>'load_extra_data_id')));
 $extra .= '</div>';
 if ($is_allowedToEdit) 
     echo $extra;

+ 1 - 1
main/exercice/exercise_submit.php

@@ -853,7 +853,7 @@ if (!empty($error)) {
                         data: "'.$params.'&type=simple&question_id="+question_id+"&"+my_choice+"&"+hotspot+"&"+remind_list,                                 
                         success: function(return_value) {
                         	if (return_value == "ok") {
-                        		$("#save_for_now_"+question_id).html("'.addslashes(Display::return_icon('accept.png', get_lang('Ok'), array(), 22)).'");
+                        		$("#save_for_now_"+question_id).html("'.addslashes(Display::return_icon('save.png', get_lang('Saved'), array(), 22)).'");
                         	} else if (return_value == "error") {
                         		$("#save_for_now_"+question_id).html("'.addslashes(Display::return_icon('error.png', get_lang('Error'), array(), 22)).'");
                         	} else if (return_value == "one_per_page") {

+ 3 - 3
main/exercice/hotspot.class.php

@@ -41,14 +41,14 @@ class HotSpot extends Question {
 		global $text, $class;
 		if(!isset($_GET['editQuestion'])) {
 			$renderer = $form->defaultRenderer();
-			$form->addElement('html', '<div class="row"><div class="label"></div><div class="formw">'.get_lang('UploadJpgPicture').'</div></div>');
-			$form->addElement('file','imageUpload','<span class="form_required">*</span><img src="../img/hotspots.png" />');
+			//$form->addElement('html', '<div class="row"><div class="label"></div><div class="formw">'.get_lang('UploadJpgPicture').'</div></div>');
+			$form->addElement('file','imageUpload',array('<span class="form_required">*</span><img src="../img/hotspots.png" />', get_lang('UploadJpgPicture')) );
 
 			// setting the save button here and not in the question class.php
 			// Saving a question
 			$form->addElement('style_submit_button','submitQuestion',get_lang('GoToQuestion'), 'class="'.$class.'"');
 
-			$renderer->setElementTemplate('<div class="row"><div class="label" style="margin-top:-30px;">{label}</div><div class="formw" >{element}</div></div>','imageUpload');
+			$renderer->setElementTemplate('<div class="row"><div class="label" style="margin-top:-30px;">{label}</div><div class="formw" >{element}<span class="help-block">{label_2}</div></div>','imageUpload');
 			$form->addRule('imageUpload', get_lang('OnlyImagesAllowed'), 'filetype', array ('jpg', 'jpeg', 'png', 'gif'));
 			$form->addRule('imageUpload', get_lang('NoImage'), 'uploadedfile');
 		} else {

+ 30 - 11
main/exercice/live_stats.php

@@ -10,6 +10,13 @@ require_once 'exercise.lib.php';
 $this_section = SECTION_COURSES;
 $exercise_id = (isset($_GET['exerciseId']) && !empty($_GET['exerciseId'])) ? intval($_GET['exerciseId']) : 0;
 
+// Access control
+api_protect_course_script(true);
+
+if (!api_is_allowed_to_edit()) {
+    api_not_allowed();
+}
+
 $objExercise = new Exercise();
 $result = $objExercise->read($exercise_id);
 
@@ -30,19 +37,18 @@ Display::display_header($tool_name);
 //jqgrid will use this URL to do the selects
 
 $minutes = 60;
-
-$url = api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=get_live_stats&exercise_id='.$objExercise->id.'&minutes='.$minutes;
+$url     = api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=get_live_stats&exercise_id='.$objExercise->id.'&minutes='.$minutes;
 
 //The order is important you need to check the the $column variable in the model.ajax.php file 
-$columns        = array(get_lang('Firstname'), get_lang('Lastname'), get_lang('Date'), get_lang('QuestionsAlreadyAnswered'), get_lang('Score'));
+$columns        = array(get_lang('FirstName'), get_lang('LastName'), get_lang('Date'), get_lang('QuestionsAlreadyAnswered'), get_lang('Score'));
 
 //Column config
 $column_model   = array(
-                        array('name'=>'firstname',  'index'=>'firstname',   'width'=>'100', 'align'=>'left'),
-                        array('name'=>'lastname',   'index'=>'lastname',    'width'=>'100', 'align'=>'left'),
-                        array('name'=>'start_date', 'index'=>'start_date',   'width'=>'100', 'align'=>'left'),
-                        array('name'=>'question',   'index'=>'count_questions',    'width'=>'100', 'align'=>'left'),
-                        array('name'=>'score',      'index'=>'score',       'width'=>'100', 'align'=>'left','sortable'=>'false'),
+                        array('name'=>'firstname',  'index'=>'firstname',       'width'=>'100', 'align'=>'left'),
+                        array('name'=>'lastname',   'index'=>'lastname',        'width'=>'100', 'align'=>'left'),
+                        array('name'=>'start_date', 'index'=>'start_date',      'width'=>'100', 'align'=>'left'),
+                        array('name'=>'question',   'index'=>'count_questions', 'width'=>'100', 'align'=>'left'),
+                        array('name'=>'score',      'index'=>'score',           'width'=>'100', 'align'=>'left','sortable'=>'false'),
                        );            
 //Autowidth             
 $extra_params['autowidth'] = 'true';
@@ -59,16 +65,29 @@ $action_links = 'function action_formatter(cellvalue, options, rowObject) {
   */                      
 ?>
 <script>
+
+function refreshGrid() {
+    var grid = $("#live_stats");
+    grid.trigger("reloadGrid");
+    t = setTimeout("refreshGrid()", 10000);
+}
+
 $(function() {
-<?php 
-    echo Display::grid_js('live_stats',  $url, $columns, $column_model, $extra_params, array(), $action_links,true);       
-?> 
+    <?php 
+        echo Display::grid_js('live_stats',  $url, $columns, $column_model, $extra_params, array(), $action_links,true);       
+    ?>
+    refreshGrid();
 });
 </script>
 <?php
 
+$actions = '<a href="exercise_report.php?exerciseId='.intval($_GET['exerciseId']).'">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'','32').'</a>';
+echo $actions = Display::div($actions, array('class'=> 'actions'));
+
 echo '<h2>'.$objExercise->name.'</h2>';
 
+echo Display::tag('h4', get_lang('StudentsWhoAreTakingTheExerciseRightNow'));
+
 echo Display::grid_html('live_stats');  
 
 Display::display_footer();

+ 2 - 2
main/exercice/overview.php

@@ -114,9 +114,9 @@ if (!empty($attempts)) {
 		$counter--;
 		$score = show_score($attempt_result['exe_result'], $attempt_result['exe_weighting']);
 		$attempt_url 	= api_get_path(WEB_CODE_PATH).'exercice/result.php?'.api_get_cidreq().'&id='.$attempt_result['exe_id'].'&id_session='.api_get_session_id().'&height=500&width=750';
-		$attempt_link 	= Display::url(get_lang('Show'), $attempt_url, array('class'=>'thickbox'));
+		$attempt_link 	= Display::url(get_lang('Show'), $attempt_url, array('class'=>'thickbox a_button white small'));
 		
-		$teacher_revised = Display::span(get_lang('Validated'), array('class'=>'label_tag notice'));
+		$teacher_revised = Display::span(get_lang('Validated'), array('class'=>'label_tag success'));
 			//$attempt_link = get_lang('NoResult');
 			//$attempt_link = Display::return_icon('quiz_na.png', get_lang('NoResult'), array(), 22);
 		if ($attempt_result['attempt_revised'] == 0) {

+ 15 - 6
main/exercice/stats.php

@@ -8,6 +8,7 @@ $language_file = array('exercice', 'tracking');
 require_once '../inc/global.inc.php';
 require_once 'exercise.lib.php';
 $this_section = SECTION_COURSES;
+
 $exercise_id = (isset($_GET['exerciseId']) && !empty($_GET['exerciseId'])) ? intval($_GET['exerciseId']) : 0;
 
 $objExercise = new Exercise();
@@ -29,7 +30,7 @@ $headers = array(
 	get_lang('LowestScore'), 
 	get_lang('AverageScore'),
 	get_lang('HighestScore'),
-	get_lang('MaximumScore')	
+	get_lang('Weighting')	
 );
 
 if (!empty($question_list)) {
@@ -39,10 +40,10 @@ if (!empty($question_list)) {
 		
 		$data[$question_id]['name'] 						= cut($question_obj->question, 100);
 		$data[$question_id]['students_who_try_exercise'] 	= $exercise_stats['users'];
-		$data[$question_id]['lowest_score'] 				= $exercise_stats['min'];
-		$data[$question_id]['average_score'] 				= $exercise_stats['average'];
-		$data[$question_id]['highest_score'] 				= $exercise_stats['max'];
-		$data[$question_id]['max_score'] 					= $question_obj->weighting;
+		$data[$question_id]['lowest_score'] 				= round($exercise_stats['min'], 2);
+		$data[$question_id]['average_score'] 				= round($exercise_stats['average'], 2);
+		$data[$question_id]['highest_score'] 				= round($exercise_stats['max'], 2);
+		$data[$question_id]['max_score'] 					= round($question_obj->weighting, 2);
 	}
 }
 
@@ -80,6 +81,14 @@ $headers = array(
 $interbreadcrumb[] = array ("url" => "exercice.php?gradebook=$gradebook", "name" => get_lang('Exercices'));
 $interbreadcrumb[] = array ("url" => "admin.php?exerciseId=$exercise_id","name" => $objExercise->name);
 
-$tpl = new Template(get_lang('Stats'));
+$tpl = new Template(get_lang('ReportByQuestion'));
+
+//$actions = array();
+//$actions[]= array(get_lang('Back'), Display::return_icon('back.png', get_lang('Back'), 'exercise_report.php?'.$exercise_id));
+//$tpl->set_actions($actions);
+
+$actions = '<a href="exercise_report.php?exerciseId='.intval($_GET['exerciseId']).'">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'','32').'</a>';
+$actions = Display::div($actions, array('class'=> 'actions'));
+$content = $actions.$content;
 $tpl->assign('content', $content);
 $tpl->display_one_col_template();

+ 17 - 10
main/exercice/testcategory.class.php

@@ -14,7 +14,7 @@ class Testcategory {
 	 If you give an in_id and no in_name, you get info concerning the category of id=in_id
 	 otherwise, you've got an category objet avec your in_id, in_name, in_descr
 	 */
-	function Testcategory($in_id=0, $in_name, $in_description="") {
+	function Testcategory($in_id=0, $in_name = '', $in_description="") {
 		if ($in_id != 0 && $in_name == "") {
 			$tmpobj = new Testcategory();
 			$tmpobj->getCategory($in_id);
@@ -69,17 +69,20 @@ class Testcategory {
 		}		
 	}
 	
-	/** remove catagory with id=in_id from the database if no question use this category
+	/** 
+     * Removes the category with id=in_id from the database if no question use this category
+     * @todo I'm removing the $in_id parameter because it seems that you're using $this->id instead of $in_id after confirmation delete this
+     * jmontoya 
 	 */
-	function removeCategory($in_id) {
+	//function removeCategory($in_id) {
+    function removeCategory() {
 		$t_cattable = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
 		$v_id = Database::escape_string($this->id);
 		$sql = "DELETE FROM $t_cattable WHERE id=$v_id AND c_id=".api_get_course_int_id();
 		$res = Database::query($sql);
 		if (Database::affected_rows() <= 0) {
 			return false;
-		}
-		else {
+		} else {
 			return true;
 		}		
 	}
@@ -87,7 +90,8 @@ class Testcategory {
 
 	/** modify category name or description of category with id=in_id 
 	 */
-	function modifyCategory($in_id, $in_name, $in_description) {
+	//function modifyCategory($in_id, $in_name, $in_description) {
+    function modifyCategory() {
 		$t_cattable = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
 		$v_id = Database::escape_string($this->id);
 		$v_name = Database::escape_string($this->name);
@@ -102,18 +106,21 @@ class Testcategory {
 		}
 	}
 	
-	/** get number of question of category id=in_id
+	/** 
+     * Gets the number of question of category id=in_id
+     * @todo I'm removing the $in_id parameter because it seems that you're using $this->id instead of $in_id after confirmation delete this
+     * jmontoya
 	 */
-	function getCategoryQuestionsNumber($in_id) {
+	//function getCategoryQuestionsNumber($in_id) {
+	function getCategoryQuestionsNumber() {
 		$t_reltable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
 		$in_id = Database::escape_string($this->id);
 		$sql = "SELECT count(*) AS nb FROM $t_reltable WHERE category_id=$in_id AND c_id=".api_get_course_int_id();
-		$res = Database::query($sql, __FILE__, __LINE__);
+		$res = Database::query($sql);
 		$row = Database::fetch_array($res);
 		return $row['nb'];
 	}
 	
-	
 	function display($in_color="#E0EBF5") {
 		echo "<textarea style='background-color:$in_color; width:60%; height:100px;'>";
 		print_r($this);

+ 14 - 20
main/exercice/tests_category.php

@@ -28,7 +28,9 @@ include('question.class.php');
 include('testcategory.class.php');
 include('../inc/global.inc.php');
 include('exercise.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+
+//Library already added in global.inc.php
+//require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
 
 $this_section=SECTION_COURSES;
 
@@ -41,8 +43,7 @@ $interbreadcrumb[]=array("url" => "exercice.php","name" => get_lang('Exercices')
 Display::display_header(get_lang('Category'));
 
 // Action handling: add, edit and remove
-if (isset($_GET['action']) && $_GET['action'] == 'addcategory') 
-{			
+if (isset($_GET['action']) && $_GET['action'] == 'addcategory') {
 	add_category_form(Security::remove_XSS($_GET['action']));
 }
 else if (isset($_GET['action']) && $_GET['action'] == 'editcategory') {
@@ -58,15 +59,10 @@ else {
 
 Display::display_footer();
 
-// **********************************************************************************
 // ******                       FUNCTIONS                        ********************
-// **********************************************************************************
 
-// ------------------------------------------------------------------------
 // form to edit a category
-// ------------------------------------------------------------------------
 function edit_category_form($in_action) {
-	
 	if (isset($_GET['category_id']) && is_numeric($_GET['category_id'])) {
 		$category_id = Security::remove_XSS($_GET['category_id']);
 		$objcat = new Testcategory($category_id);
@@ -203,9 +199,8 @@ function add_category_form($in_action) {
 }
 
 
-// ------------------------------------------------------------------------
 // Display add category button
-// ------------------------------------------------------------------------
+
 function display_add_category() {
 	echo '<div class="actions">';
 	echo '<a href="exercice.php?'.api_get_cidreq().'">'.Display::return_icon('back.png', get_lang('GoBackToQuestionList'),'',32).'</a>';			
@@ -215,19 +210,20 @@ function display_add_category() {
 }
 
 
-// ------------------------------------------------------------------------
 // Display category list
-// ------------------------------------------------------------------------
+
 function display_categories() {
+    $course_id = api_get_course_int_id();
 	$t_cattable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
-	$sql = "SELECT * FROM $t_cattable ORDER BY title";
-	$res = Database::query($sql, __FILE__, __LINE__);
+	$sql = "SELECT * FROM $t_cattable WHERE c_id = $course_id ORDER BY title";
+	$res = Database::query($sql);
 	while ($row = Database::fetch_array($res)) {
-		// le titre avec le nombre de questions qui sont dans cette catégorie
+		// le titre avec le nombre de questions qui sont dans cette cat�gorie
 		$tmpobj = new Testcategory($row['id']);
 		$nb_question = $tmpobj->getCategoryQuestionsNumber();
 		echo '<div class="sectiontitle" id="id_cat'.$row['id'].'">';
-		echo "<span style='float:right'>".$nb_question.get_lang('NbCategory')."</span>";
+        $nb_question_label = $nb_question == 1 ? $nb_question.' '.get_lang('Question') : $nb_question.' '.get_lang('Questions'); 
+		echo "<span style='float:right'>".$nb_question_label."</span>";
 		echo $row['title'];
 		echo '</div>';
 		echo '<div class="sectioncomment">';
@@ -256,7 +252,7 @@ function display_categories() {
 // ------------------------------------------------------------------------
 function display_goback() {
 	echo '<div class="actions">';
-	echo '<a href="'.api_get_self().'">'.Display::return_icon('back.png', '', 32).' '.get_lang('BackToCategoryList').'</a>';
+	echo '<a href="'.api_get_self().'">'.Display::return_icon('back.png', get_lang('BackToCategoryList'), array(),  32).'</a>';
 	echo '</div>';
 }
 
@@ -269,6 +265,4 @@ function protectJSDialogQuote($in_txt) {
 	$res = str_replace("'", "\'", $res);
 	$res = str_replace('"', "\'\'", $res);	// super astuce pour afficher les " dans les boite de dialogue
 	return $res;
-}
-
-?>
+}

+ 1 - 1
main/group/group.php

@@ -156,7 +156,7 @@ if (api_is_allowed_to_edit(false, true)) {
 echo '<div class="actions">';
 if (api_is_allowed_to_edit(false, true)) {
 	echo '<a href="group_creation.php?'.api_get_cidreq().'">'.Display::return_icon('new_group.png', get_lang('NewGroupCreate'),'','32').'</a>';
-	if (Database::count_rows(Database::get_course_table(TABLE_GROUP)) > 0) {
+	if (CourseManager::count_rows_course_table(Database::get_course_table(TABLE_GROUP),api_get_session_id(), api_get_course_int_id()) > 0) {
 		//echo '<a href="group_overview.php?'.api_get_cidreq().'">'.Display::return_icon('group_view.gif').'&nbsp;'.get_lang('GroupOverview').'</a>&nbsp;';
 		echo '<a href="group_overview.php?'.api_get_cidreq().'">'.Display::return_icon('group_summary.png', get_lang('GroupOverview'),'','32').'</a>';
 	}

+ 8 - 9
main/group/group_space.php

@@ -53,7 +53,7 @@ if ($current_group['doc_state'] != 1 && $current_group['calendar_state'] != 1 &&
 
 /*	Header */
 
-Display::display_header($nameTools.' '.stripslashes($current_group['name']), 'Group');
+Display::display_header($nameTools.' '.Security::remove_XSS($current_group['name']), 'Group');
 
 /*	Introduction section (editable by course admin) */
 
@@ -302,14 +302,14 @@ $table->display();
  */
 function get_number_of_group_users() {
 	global $current_group;
+    $course_id = api_get_course_int_id();
 
 	// Database table definition
 	$table_group_user = Database :: get_course_table(TABLE_GROUP_USER);
 
 	// Query
-	$sql = "SELECT count(id) AS number_of_users
-				FROM ".$table_group_user."
-				WHERE group_id='".Database::escape_string($current_group['id'])."'";
+	$sql = "SELECT count(id) AS number_of_users FROM ".$table_group_user."
+				WHERE c_id = $course_id AND group_id='".Database::escape_string($current_group['id'])."'";
 	$result = Database::query($sql);
 	$return = Database::fetch_array($result,'ASSOC');
 	return $return['number_of_users'];
@@ -338,8 +338,7 @@ function get_group_user_data($from, $number_of_items, $column, $direction) {
 
 	// Query
 	if (api_get_setting('show_email_addresses') == 'true') {
-		$sql = "SELECT
-					user.user_id 	AS col0,
+		$sql = "SELECT user.user_id 	AS col0,
 				".(api_is_western_name_order() ?
 				"user.firstname 	AS col1,
 				user.lastname 	AS col2,"
@@ -349,7 +348,7 @@ function get_group_user_data($from, $number_of_items, $column, $direction) {
 				)."
 					user.email		AS col3
 					FROM ".$table_user." user, ".$table_group_user." group_rel_user
-					WHERE group_rel_user.c_id = $course_id group_rel_user.user_id = user.user_id
+					WHERE group_rel_user.c_id = $course_id AND group_rel_user.user_id = user.user_id
 					AND group_rel_user.group_id = '".Database::escape_string($current_group['id'])."'";
 		$sql .= " ORDER BY col$column $direction ";
 		$sql .= " LIMIT $from,$number_of_items";
@@ -366,7 +365,7 @@ function get_group_user_data($from, $number_of_items, $column, $direction) {
 						)."
 						user.email		AS col3
 						FROM ".$table_user." user, ".$table_group_user." group_rel_user
-						WHERE group_rel_user.user_id = user.user_id
+						WHERE group_rel_user.c_id = $course_id AND group_rel_user.user_id = user.user_id
 						AND group_rel_user.group_id = '".Database::escape_string($current_group['id'])."'";
 			$sql .= " ORDER BY col$column $direction ";
 			$sql .= " LIMIT $from,$number_of_items";
@@ -381,7 +380,7 @@ function get_group_user_data($from, $number_of_items, $column, $direction) {
 						user.firstname 	AS col2 "
 						)."
 						FROM ".$table_user." user, ".$table_group_user." group_rel_user
-						WHERE group_rel_user.user_id = user.user_id
+						WHERE group_rel_user.c_id = $course_id AND  group_rel_user.user_id = user.user_id
 						AND group_rel_user.group_id = '".Database::escape_string($current_group['id'])."'";
 			$sql .= " ORDER BY col$column $direction ";
 			$sql .= " LIMIT $from,$number_of_items";

BIN
main/img/alt_star.gif


BIN
main/img/icons/22/add_na.png


BIN
main/img/icons/22/warning.png


BIN
main/img/icons/32/activity_monitor.png


BIN
main/img/icons/32/import.png


+ 20 - 5
main/inc/ajax/agenda.ajax.php

@@ -13,30 +13,45 @@ require_once api_get_path(SYS_CODE_PATH).'calendar/agenda.lib.php';
 $action = isset($_REQUEST['a']) ? $_REQUEST['a'] : null;
 $type   = isset($_REQUEST['type']) && in_array($_REQUEST['type'], array('personal', 'course', 'admin')) ? $_REQUEST['type'] : 'personal';
 
+if ($type =='course') {
+    // Access control
+    api_protect_course_script(true);
+}
+
 $agenda = new Agenda();
 
 $agenda->type = $type; //course,admin or personal
 
 switch ($action) {
 	case 'add_event':
-		echo $agenda->add_event($_REQUEST['start'], $_REQUEST['end'], $_REQUEST['all_day'], $_REQUEST['view'], $_REQUEST['title'], $_REQUEST['content'], $_REQUEST['users_to_send']);
+        if (!api_is_allowed_to_edit(null, true) && $type == 'course') {
+            break;
+        }
+		echo $agenda->add_event($_REQUEST['start'], $_REQUEST['end'], $_REQUEST['all_day'], $_REQUEST['view'], 
+		                        $_REQUEST['title'], $_REQUEST['content'], $_REQUEST['users_to_send'], $_REQUEST['add_as_annonuncement']);
 		break;		
 	case 'edit_event':
-		$id_list 	= explode('_', $_REQUEST['id']);		
-		//$type 		= $id_list[0];
+        if (!api_is_allowed_to_edit(null, true) && $type == 'course') {
+            break;
+        }
+		$id_list 	= explode('_', $_REQUEST['id']);
 		$id 		= $id_list[1];		
 		$agenda->edit_event($id, $_REQUEST['start'], $_REQUEST['end'], $_REQUEST['all_day'], $_REQUEST['view'], $_REQUEST['title'], $_REQUEST['content']);
 		break;
 	case 'delete_event':
+        if (!api_is_allowed_to_edit(null, true) && $type == 'course') {
+            break;
+        }
 		$id_list 	= explode('_', $_REQUEST['id']);
-		//$type 		= $id_list[0];
 		$id 		= $id_list[1];		
 		$agenda->delete_event($id);		
 		break;
 	case 'move_event':
+        if (!api_is_allowed_to_edit(null, true) && $type == 'course') {
+            break;
+        }
 		$day_delta 		= $_REQUEST['day_delta'];
 		$minute_delta 	= $_REQUEST['minute_delta'];
-		//$type 			= $_REQUEST['type'][0];
 		$id 			= explode('_', $_REQUEST['id']);
 		$id				= $id[1];
 		$agenda->move_event($id, $day_delta, $minute_delta);		

+ 25 - 0
main/inc/ajax/course.ajax.php

@@ -0,0 +1,25 @@
+<?php
+/* For licensing terms, see /license.txt */
+/**
+ * Responses to AJAX calls
+ */
+
+require_once '../global.inc.php';
+
+$action = $_REQUEST['a'];
+
+$user_id = api_get_user_id();
+
+switch ($action) {    
+    case 'add_course_vote':
+        if (!api_is_anonymous()) {
+     	    $course_id = intval($_REQUEST['course_id']);
+            $star      = intval($_REQUEST['star']);
+            $result    = CourseManager::add_course_vote($user_id, $star, $course_id, 0);
+            echo $result;            
+        }
+        break;
+    default:
+        echo '';
+}
+exit;

+ 11 - 8
main/inc/ajax/course_home.ajax.php

@@ -71,21 +71,24 @@ switch ($action) {
 	case 'show_course_information' :
 	
 		$language_file = array('course_description');
-		require_once '../global.inc.php';			
-        if (api_is_anonymous()) {
-            exit;
-        }		
+		require_once '../global.inc.php';
 		
-		// Get the name of the database course.
-		$database_course        = CourseManager::get_name_database_course($_GET['code']);
-		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION, $database_course);		
+		// Get the name of the database course.		
+		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
 		
 		$course_info = api_get_course_info($_GET['code']);
 		
+		if ($course_info['visibility'] != COURSE_VISIBILITY_OPEN_WORLD) {
+			if (api_is_anonymous()) {
+				exit;
+			}		
+		}
+		
+		
 		echo Display::tag('h2', $course_info['name']);
 		echo '<br />';
 	
-		$sql = "SELECT * FROM $tbl_course_description WHERE session_id = 0 ORDER BY id";
+		$sql = "SELECT * FROM $tbl_course_description WHERE c_id = ".$course_info['real_id']." AND session_id = 0 ORDER BY id";
 		$result = Database::query($sql);
 		if (Database::num_rows($result) > 0 ) {		        
 		    while ($description = Database::fetch_object($result)) {

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

@@ -15,6 +15,10 @@ $course_id = api_get_course_int_id();
 
 switch ($action) {
     case 'get_live_stats':
+        if (!api_is_allowed_to_edit(null, true)) {
+            break;
+        }    
+        
         // 1. Setting variables needed by jqgrid 
         $action = $_GET['a'];
         $exercise_id = intval($_GET['exercise_id']);
@@ -61,18 +65,18 @@ switch ($action) {
             $start = 0;
         }        
         
-        
-        
         $sql = "SELECT count_questions, exe_user_id, firstname, lastname, aa.status, start_date, exe_result, exe_weighting, exe_result/exe_weighting as score, exe_duration, questions_to_check, orig_lp_id
                 FROM $user_table u INNER JOIN (
                     SELECT  t.exe_user_id, count(question_id) as count_questions, status,
                     start_date, exe_result, exe_weighting, exe_result/exe_weighting as score, exe_duration, questions_to_check, orig_lp_id
-                    FROM  $track_attempt a INNER JOIN $track_exercise  t
-                    WHERE a.exe_id = t.exe_id AND exe_user_id = a.user_id AND $where_condition  
-                group by exe_user_id                    
-                ) as aa 
+                    FROM  $track_exercise  t LEFT JOIN   $track_attempt a ON (a.exe_id = t.exe_id AND  t.exe_user_id = a.user_id ) 
+                    WHERE t.status = 'incomplete' AND
+                          $where_condition  
+                GROUP BY exe_user_id                    
+                ) as aa
                 ON aa.exe_user_id = user_id                    
-                ORDER BY $sidx $sord LIMIT  $start ,  $limit ";
+                ORDER BY $sidx $sord LIMIT $start, $limit";
+                //echo $sql;
         $result = Database::query($sql);
         $results = array();
         
@@ -101,8 +105,7 @@ switch ($action) {
                 $i++; 
             }
         } 
-        echo json_encode($response); 
-        
+        echo json_encode($response);
         break;            
     case 'update_question_order':
         if (api_is_allowed_to_edit(null, true)) {    

+ 10 - 32
main/inc/ajax/link.ajax.php

@@ -6,43 +6,21 @@
 
 require_once '../global.inc.php';
 
-api_protect_course_script(true);
-
 $action = $_REQUEST['a'];
 
+$user_id = api_get_user_id();
+
 switch ($action) {    
-    case 'check_url':
-        if (api_is_allowed_to_edit(null, true)) {
-     	    $url = $_REQUEST['url'];
-     	                
-     	    //Check if curl is available     	    
-     	    if  (!in_array('curl', get_loaded_extensions())) {
-                echo '';
-                exit;
-     	    }
-            // set URL and other appropriate options            
-            $defaults = array(
-                CURLOPT_URL => $url,
-                CURLOPT_HEADER => 0,
-                CURLOPT_RETURNTRANSFER => TRUE,
-                CURLOPT_TIMEOUT => 4
-            );
-            //create a new cURL resource
-            
-            $ch = curl_init();
-            curl_setopt_array($ch, $defaults);        
+    case 'course_vote':
+        if (!api_is_anonymous()) {
+     	    $course_id = intval($_REQUEST['course_id']);
+            $star      = intval($_REQUEST['star']);
             
-            // grab URL and pass it to the browser
-            $result = curl_exec($ch);    
-            
-            // close cURL resource, and free up system resources
-            curl_close($ch);
-            
-            if($result) {
-                echo Display::return_icon('accept.png', get_lang('Ok'));
-            } else {
-                echo Display::return_icon('wrong.gif', get_lang('Wrong'));
+            if (!in_array($star, array(1,2,3,4,5))) {
+                //trying to hack the star rating ...
+                exit;
             }
+            CourseManager::add_course_vote($user_id, $course_id, 0);
         }
         break;
     default:

+ 47 - 8
main/inc/ajax/model.ajax.php

@@ -3,6 +3,8 @@
 
 //@todo this could be integrated in the inc/lib/model.lib.php + try to clean this file
 
+$language_file = array('admin');
+
 require_once '../global.inc.php';
 
 api_protect_admin_script(true);
@@ -43,6 +45,9 @@ $ops = array(
 
 function get_where_clause($col, $oper, $val) {
     global $ops;
+    if (empty($col)){
+        return '';
+    } 
     if($oper == 'bw' || $oper == 'bn') $val .= '%';
     if($oper == 'ew' || $oper == 'en' ) $val = '%'.$val;
     if($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') $val = '%'.$val.'%';
@@ -51,12 +56,34 @@ function get_where_clause($col, $oper, $val) {
 }
 
 $where_condition = ""; //if there is no search request sent by jqgrid, $where should be empty
-$search_field    = isset($_REQUEST['searchField']) ? $_REQUEST['searchField'] : false;
-$search_oper     = isset($_REQUEST['searchOper']) ? $_REQUEST['searchOper']: false;
+
+$search_field    = isset($_REQUEST['searchField'])  ? $_REQUEST['searchField']  : false;
+$search_oper     = isset($_REQUEST['searchOper'])   ? $_REQUEST['searchOper']   : false;
 $search_string   = isset($_REQUEST['searchString']) ? $_REQUEST['searchString'] : false;
 
 if ($_REQUEST['_search'] == 'true') {
-    $where_condition = get_where_clause($search_field, $search_oper, $search_string);
+    $where_condition = ' 1 = 1 ';
+    $where_condition_in_form = get_where_clause($search_field, $search_oper, $search_string);
+        
+    if (!empty($where_condition_in_form)) {
+        $where_condition .= ' AND '.$where_condition_in_form;
+    }
+    
+    $filters   = isset($_REQUEST['filters']) ? json_decode($_REQUEST['filters']) : false;
+    if (!empty($filters)) {
+        $where_condition .= ' AND ( ';
+        $counter = 0;
+        foreach ($filters->rules as $key=>$rule) {
+            $where_condition .= get_where_clause($rule->field,$rule->op, $rule->data);
+            
+            if ($counter < count($filters->rules) -1) {     
+                $where_condition .= $filters->groupOp;
+            }
+            $counter++;
+        }
+        $where_condition .= ' ) ';
+    }
+        
 }
 
 // get index row - i.e. user click to sort $sord = $_GET['sord']; 
@@ -120,11 +147,11 @@ if ($_REQUEST['oper'] == 'del') {
 $columns = array();
 switch ($action) {    
     case 'get_sessions':
-        $columns = array('name', 'nbr_courses','category_name', 'date_start','date_end', 'coach_name', 'visibility');        
+        $columns = array('name', 'nbr_courses','category_name', 'date_start','date_end', 'coach_name', 'session_active', 'visibility');        
         $result = SessionManager::get_sessions_admin(array('where'=> $where_condition, 'order'=>"$sidx $sord", 'limit'=> "$start , $limit"));        
         break;
     case 'get_gradebooks': 
-        $columns = array('name', 'skills', 'actions');                
+        $columns = array('name', 'certificates','skills', 'actions', 'has_certificates');                
         if (!in_array($sidx, $columns)) {
             $sidx = 'name';
         }
@@ -135,21 +162,33 @@ switch ($action) {
                 continue;
             }
             $skills = $obj->get_skills_by_gradebook($item['id']);
+            
             //Fixes bug when gradebook doesn't have names
             if (empty($item['name'])) {
                 $item['name'] = $item['course_code'];                 
+            } else {
+                //$item['name'] =  $item['name'].' ['.$item['course_code'].']';
             }
+                 
+            $item['name'] = Display::url($item['name'], api_get_path(WEB_CODE_PATH).'gradebook/index.php?id_session=0&cidReq='.$item['course_code']);
+                         
             if (!empty($item['certif_min_score']) && !empty($item['document_id'])) {
-                $item['name'] .= '* (with_certificate)'; 
+                $item['certificates'] = Display::return_icon('accept.png', get_lang('WithCertificate'), array(), 22);
+                 $item['has_certificates'] = '1'; 
             } else {
-                $item['name'] .= ' (No certificate)';
+                $item['certificates'] = Display::return_icon('warning.png', get_lang('NoCertificate'), array(), 22);
+                $item['has_certificates'] = '0';
             }
+            
             $skills_string = '';
             if (!empty($skills)) {
                 foreach($skills as $skill) {
                     $item['skills'] .= Display::span($skill['name'], array('class' => 'label_tag skill'));  
                 }
-            }          
+            }
+            
+           
+                    
             $new_result[] = $item;
         } 
         $result = $new_result;

+ 24 - 7
main/inc/lib/auth.lib.php

@@ -429,6 +429,8 @@ class Auth
         $tbl_course               = Database::get_main_table(TABLE_MAIN_COURSE);
         $TABLE_COURSE_FIELD       = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
         $TABLE_COURSE_FIELD_VALUE = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
+        $table_course_ranking       = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
+        
 
         // get course list auto-register
         $sql = "SELECT course_code FROM $TABLE_COURSE_FIELD_VALUE tcfv INNER JOIN $TABLE_COURSE_FIELD tcf ON tcfv.field_id = tcf.id 
@@ -449,22 +451,24 @@ class Auth
         
         if (!empty($random_value)) {
             $random_value = intval($random_value);
-            $sql = "SELECT * FROM $tbl_course WHERE 1 $without_special_courses ORDER BY RAND() LIMIT $random_value";
+            $sql = "SELECT * FROM $tbl_course course, (SELECT CEIL(MAX($tbl_course.id) * RAND()) AS randId FROM $tbl_course ) AS someRandId 
+            WHERE course.id >= someRandId.randId $without_special_courses";
         
             if ($_configuration['multiple_access_urls']) {
                 $url_access_id = api_get_current_access_url_id();                
                 $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-                $sql = "SELECT * FROM $tbl_course as course INNER JOIN $tbl_url_rel_course as url_rel_course
-                        ON (url_rel_course.course_code=course.code)
-                        WHERE access_url_id = $url_access_id $without_special_courses ORDER BY RAND() LIMIT $random_value";
+                
+                //$table_course_ranking ranking
+                //AND ranking.c_id
+                $sql = "SELECT * FROM $tbl_course course, (SELECT CEIL(MAX($tbl_course.id) * RAND()) AS randId FROM $tbl_course INNER JOIN $tbl_url_rel_course as url_rel_course
+                        ON (url_rel_course.course_code=$tbl_course.code) WHERE access_url_id = $url_access_id ) AS someRandId
+                        WHERE course.id AND course.id >= someRandId.randId $without_special_courses $without_special_courses";
             }
             
-            $sql = "SELECT * FROM $tbl_course course, (SELECT CEIL(MAX($tbl_course.id) * RAND()) AS randId FROM $tbl_course) AS someRandId 
-                    WHERE course.id >= someRandId.randId $without_special_courses";
+            
             
         } else {
             $category_code = Database::escape_string($category_code);
-            //$my_category = (empty($category) ? " IS NULL" : "='".$category."'");
             $sql = "SELECT * FROM $tbl_course WHERE category_code='$category_code' $without_special_courses ORDER BY title ";
             
             //showing only the courses of the current Chamilo access_url_id
@@ -487,7 +491,20 @@ class Auth
                 if ($row['tutor_name'] == '0') {
                     $row['tutor_name'] = get_lang('NoManager');
                 }
+                
+                $point_info = CourseManager::get_course_ranking($row['id'], 0);
+                
+                $points = 0;
+                $users_who_voted = 0;
+                if (!empty($point_info['users'])) {
+                    $users_who_voted = $point_info['users'];
+                    $points = $point_info['points']/$point_info['users'] * 100 / 5;    
+                }
+                
                 $courses[] = array(
+                                    'real_id'           => $row['id'],
+                                    'point_average'     => $points,
+                                    'users_who_voted'   => $users_who_voted,                                    
                                     'code'              => $row['code'],
                                     'directory'         => $row['directory'],
                                     'db'                => $row['db_name'],

+ 9 - 40
main/inc/lib/blog.lib.php

@@ -357,8 +357,7 @@ class Blog {
 		$current_date		= date('Y-m-d H:i:s',time());
 		$course_id 			= api_get_course_int_id();
 
-		if(!empty($_FILES['user_upload']['name']))
-		{
+		if(!empty($_FILES['user_upload']['name'])) {
 			require_once('fileUpload.lib.php');
 			$upload_ok = process_uploaded_file($_FILES['user_upload']);
 			$has_attachment=true;
@@ -379,8 +378,7 @@ class Blog {
 
 			$last_id=Database::insert_id();
 
-			if ($has_attachment)
-			{
+			if ($has_attachment) {
 				$courseDir   = $_course['path'].'/upload/blog';
 				$sys_course_path = api_get_path(SYS_COURSE_PATH);
 				$updir = $sys_course_path.$courseDir;
@@ -461,7 +459,7 @@ class Blog {
 	 */
 	public static function create_task ($blog_id, $title, $description, $articleDelete, $articleEdit, $commentsDelete, $color) {
 		// Init
-		$tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
+		$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();
@@ -518,7 +516,7 @@ class Blog {
 	 */
 	public static function edit_task($blog_id, $task_id, $title, $description, $articleDelete, $articleEdit, $commentsDelete, $color) {
 		// Init
-		$tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS);
+		$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();
@@ -2611,8 +2609,7 @@ class Blog {
 					</div>
 				</div>
 			</form>
-			<div style="clear: both; margin-bottom:10px;"></div>
-			';
+			<div style="clear: both; margin-bottom:10px;"></div>';
 
 	}
 
@@ -2621,10 +2618,10 @@ class Blog {
 	 *
 	 */
 	public static function display_edit_blog_form ($blog_id) {
-		// Init
+	    $course_id = api_get_course_int_id();		
 		$tbl_blogs = Database::get_course_table(TABLE_BLOGS);
 
-		$sql = "SELECT blog_id, blog_name, blog_subtitle FROM $tbl_blogs WHERE blog_id = '".(int)$blog_id."'";
+		$sql = "SELECT blog_id, blog_name, blog_subtitle FROM $tbl_blogs WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."'";
 		$result = Database::query($sql);
 		$blog = Database::fetch_array($result);
 
@@ -2679,6 +2676,7 @@ class Blog {
 	 */
 	public static function display_blog_list () {
 		global $charset, $_user;
+        $course_id = api_get_course_int_id();
 		// Init
 		$counter = 0;
 
@@ -2688,7 +2686,7 @@ class Blog {
 		$session_id = api_get_session_id();
 		$condition_session = api_get_session_condition($session_id, false);
 
-		$sql = 'SELECT blog_name,blog_subtitle,visibility,blog_id FROM '.$tbl_blogs.' ORDER BY date_creation DESC ';
+		$sql = "SELECT blog_name,blog_subtitle,visibility,blog_id FROM $tbl_blogs WHERE c_id = $course_id ORDER BY date_creation DESC";
 		$result = Database::query($sql);
 		if (Database::num_rows($result)) {
 			while ($row_project=Database::fetch_row($result)) {
@@ -2742,35 +2740,6 @@ class Blog {
 			$table->set_header(2, get_lang('Modify'));
 			$table->display();
 		}
-
-		/*$sql = "SELECT blog_id, blog_name, blog_subtitle, visibility FROM $tbl_blogs ORDER BY blog_name";
-		$result = Database::query($sql);
-
-		while($blog = Database::fetch_array($result))
-		{
-			$counter++;
-			$css_class = (($counter % 2)==0) ? "row_odd" : "row_even";
-			$visibility_icon = ($blog['visibility'] == '0') ? "invisible.gif" : "visible.gif";
-			$visibility_class = ($blog['visibility'] == '0') ? ' class="invisible"' : "";
-			$visibility_set  = ($blog['visibility'] == '0') ? 1 : 0;
-
-			echo	'<tr class="' . $css_class . '" valign="top">',
-						 '<td width="290"' . $visibility_class . '>'.stripslashes($blog['blog_name']) . '</td>',
-						 '<td' . $visibility_class . '>'.stripslashes($blog['blog_subtitle']) . '</td>',
-						 '<td width="200">',
-						 	'<a href="' .api_get_self(). '?action=edit&amp;blog_id=' . $blog['blog_id'] . '">',
-							'<img src="../img/edit.gif" border="0" title="' . get_lang('EditBlog') . '" />',
-							"</a>\n",
-							'<a href="' .api_get_self(). '?action=delete&amp;blog_id=' . $blog['blog_id'] . '" ',
-							'onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)). '\')) return false;" >',
-							'<img src="../img/delete.gif" border="0" title="' . get_lang('DeleteBlog') . '" />',
-							"</a>\n",
-							'<a href="' .api_get_self(). '?action=visibility&amp;blog_id=' . $blog['blog_id'] . '">',
-							'<img src="../img/' . $visibility_icon . '" border="0" title="' . get_lang('Visible') . '" />',
-							"</a>\n",
-						 '</td>',
-					'</tr>';
-		}*/
 	}
 
 }

+ 200 - 7
main/inc/lib/course.lib.php

@@ -161,13 +161,15 @@ class CourseManager {
                     prepare_course_repository($course_info['directory'], $course_info['code']);
                     $pictures_array = fill_course_repository($course_info['directory'], $params['exemplary_content']);                      
                     fill_Db_course($course_id, $course_info['directory'], $course_info['course_language'], $pictures_array, $params['exemplary_content']);
+                    
+                    self::update_course_ranking($course_info['real_id'], 0);
+                    
                     return $course_info;                    
                 }
             }
         }
         return false;            
     }
-    
 
     /**
      * Returns all the information of a given coursecode
@@ -2706,7 +2708,7 @@ class CourseManager {
         }
 
         if (!empty($with_special_courses)) {
-            $sql = "SELECT course.code, course.visual_code, course.subscribe subscr, course.unsubscribe unsubscr,
+            $sql = "SELECT course.id, course.code, course.visual_code, course.subscribe subscr, course.unsubscribe unsubscr,
                                 course.title title, course.tutor_name tutor, course.db_name, course.directory, course_rel_user.status status,
                                 course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat, course_rel_user.user_id, course.visibility
                                 FROM $tbl_course course
@@ -2764,12 +2766,9 @@ class CourseManager {
                             echo '<a id="document_preview_'.$course['id'].'_0" class="document_preview" href="javascript:void(0);">'.Display::return_icon('folder.png', get_lang('Documents'), array('align' => 'absmiddle'),22).'</a>';
                             echo Display::div('', array('id' => 'document_result_'.$course['id'].'_0', 'class'=>'document_preview_container'));
                         }
-                        echo '</div>';
-                        
+                        echo '</div>';                                                
                     }
 
-
-
                     $course_visibility = $course['visibility'];
                     if ($course_visibility != COURSE_VISIBILITY_CLOSED || $course['status'] == COURSEMANAGER) {
                         $course_title = '<a href="'.api_get_path(WEB_COURSE_PATH).$course['directory'].'/?id_session=0&amp;autoreg=1">'.$course['title'].'</a>';
@@ -3434,4 +3433,198 @@ class CourseManager {
         }
     }
     
-} //end class CourseManager
+    public function get_course_ranking($course_id, $session_id = null, $url_id = null) {
+        $table_course_ranking       = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
+        
+        $session_id = !isset($session_id)   ? api_get_session_id() : intval($session_id);
+        $url_id     = empty($url_id)        ? api_get_current_access_url_id() : intval($url_id);
+        
+        $params = array(
+            'c_id'          => $course_id,
+            'session_id'    => $session_id,
+            'url_id'        => $url_id,
+            'creation_date' => $now,
+        );
+         
+        $result = Database::select('id, accesses, points, users', $table_course_ranking, array('where' => array('c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');
+        return $result;
+    }
+    
+    /**
+     * 
+     * Updates the course ranking 
+     * @param int   course id
+     * @param int   session id
+     * @param id    url id
+     * 
+     **/    
+    public function update_course_ranking($course_id = null, $session_id = null, $url_id = null, $points_to_add = null, $add_access = true, $add_user = true) {        
+        //Course catalog stats modifications see #4191        
+        $table_course_ranking       = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
+                
+        $now = api_get_utc_datetime();
+        
+        $course_id  = empty($course_id)     ? api_get_course_int_id() : intval($course_id);
+        $session_id = !isset($session_id)   ? api_get_session_id() : intval($session_id);
+        $url_id     = empty($url_id)        ? api_get_current_access_url_id() : intval($url_id);
+        
+        $params = array(
+            'c_id'          => $course_id,
+            'session_id'    => $session_id,
+            'url_id'        => $url_id,
+            'creation_date' => $now,
+        );
+         
+        $result = Database::select('id, accesses, points, users', $table_course_ranking, array('where' => array('c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');        
+        
+        // Problem here every thime we load the courses/XXXX/index.php course home page we update the access 
+        
+        if (empty($result)) {
+            if ($add_access) {
+                $params['accesses'] = 1;    
+            }            
+            //The votes and users are empty
+            if (isset($points_to_add) && !empty($points_to_add)) {
+               $params['points'] = intval($points_to_add);
+            }
+            if ($add_user) {
+                $params['users'] = 1;
+            }
+            $result = Database::insert($table_course_ranking, $params);
+        } else {
+            $my_params = array();
+            
+            if ($add_access) {        
+                $my_params['accesses'] = intval($result['accesses']) + 1;
+            }
+            if (isset($points_to_add) && !empty($points_to_add)) {                
+               $my_params['points'] = $result['points'] + $points_to_add;               
+            }
+            if ($add_user) {
+                $my_params['users']  = $result['users'] + 1;
+            }
+
+            if (!empty($my_params)) {
+                $result = Database::update($table_course_ranking, $my_params, array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
+            }        
+        }
+        return $result;
+    }
+
+
+    /**
+     * Add user vote to a course
+     * 
+     * @param   int user id
+     * @param   int vote [1..5]
+     * @param   int course id
+     * @param   int session id
+     * @param   int url id 
+     *  
+     */
+    
+    public function add_course_vote($user_id, $vote, $course_id, $session_id = null, $url_id = null) {
+        $table_user_course_vote     = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
+        
+        $course_id  = empty($course_id)     ? api_get_course_int_id() : intval($course_id);
+        $session_id = !isset($session_id)   ? api_get_session_id() : intval($session_id);
+        $url_id     = empty($url_id)        ? api_get_current_access_url_id() : intval($url_id);
+        $vote       = intval($vote);
+        
+        if (!in_array($vote, array(1,2,3,4,5))) {
+            return false;
+        }
+        
+        $params = array(
+            'user_id'       => intval($user_id),
+            'c_id'          => $course_id,
+            'session_id'    => $session_id,
+            'url_id'        => $url_id,
+            'vote'          => $vote
+        );
+        
+        $action_done = false;
+        
+        $result = Database::select('id, vote', $table_user_course_vote, array('where' => array('user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');
+
+        if (empty($result)) {            
+            $result = Database::insert($table_user_course_vote, $params);
+            $points_to_add = $vote;
+            $add_user = true;
+            $action_done = 'added';
+        } else {            
+            $my_params = array('vote' => $vote);
+            $points_to_add = $vote - $result['vote'];
+            $add_user = false;
+            $result = Database::update($table_user_course_vote, $my_params, array('user_id = ? AND c_id = ? AND session_id = ? AND url_id = ?' => $params));
+            $action_done = 'updated';
+        }
+        //Current points 
+        
+        if (!empty($points_to_add)) {
+            self::update_course_ranking($course_id, $session_id, $url_id, $points_to_add, false, $add_user);
+        }
+        return $action_done;
+        
+    }
+    
+    /**
+     * Remove course ranking + user votes
+     * 
+     * @param   int course id
+     * @param   int session id
+     * @param   int url id 
+     * 
+     */
+    public function remove_course_ranking($course_id, $session_id, $url_id = null) {
+        $table_course_ranking       = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
+        $table_user_course_vote     = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
+        if (!empty($course_id) && isset($session_id)) {
+            
+            $url_id     = empty($url_id) ? api_get_current_access_url_id() : intval($url_id);
+            $params = array(
+                'c_id'          => $course_id,
+                'session_id'    => $session_id,
+                'url_id'        => $url_id,                
+            );
+            Database::delete($table_course_ranking,   array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
+            Database::delete($table_user_course_vote, array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
+        }
+    }
+	
+	//Stats functions
+    
+    function return_hot_courses($days = 30, $limit = 5) {
+		$limit  = intval($limit);
+        $table_course_access	= Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);                
+		$today					= api_get_utc_datetime();
+		$today_diff				= time() -intval($days)*24*60*60;
+		$today_diff				= api_get_utc_datetime($today_diff);
+		//WHERE login_course_date <= '$today' AND login_course_date >= '$today_diff'
+		
+		//$table_course_access table uses the now() and interval ... 
+		
+        $sql = "SELECT COUNT(course_access_id) course_count, course_code FROM $table_course_access 
+				WHERE login_course_date <= now() AND login_course_date > DATE_SUB(now(), INTERVAL $days DAY)
+				GROUP BY course_code
+				ORDER BY course_count DESC 
+				LIMIT $limit";
+		$result = Database::query($sql);
+		$courses = array();
+		if (Database::num_rows($result)) {
+			$courses = Database::store_result($result, 'ASSOC');
+			foreach ($courses as &$my_course) {
+				$my_course['extra_info'] = api_get_course_info($my_course['course_code']);				
+			}
+		}		
+		return $courses;
+    }
+	
+	function return_most_accessed_courses($limit = 5) {
+		$table_course_ranking	= Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);        
+        $params['url_id']		= api_get_current_access_url_id();
+        
+        $result = Database::select('c_id, accesses, points, users', $table_course_ranking, array('where' => array('url_id = ?' => $params), 'order' => array('accesses DESC'), 'limit' => $limit), 'all', true);
+        return $result;
+	}    
+} //end class CourseManager

+ 3 - 2
main/inc/lib/database.constants.inc.php

@@ -132,14 +132,15 @@ define('TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY',     'track_e_item_property');
 define('TABLE_STATISTIC_TRACK_E_OPEN',              'track_e_open');
 
 define('TABLE_STATISTIC_TRACK_FILTERED_TERMS',      'track_filtered_terms');
-
-
 define('TABLE_STATISTIC_TRACK_C_BROWSERS',          'track_c_browsers');
 define('TABLE_STATISTIC_TRACK_C_COUNTRIES',         'track_c_countries');
 define('TABLE_STATISTIC_TRACK_C_OS',                'track_c_os');
 define('TABLE_STATISTIC_TRACK_C_PROVIDERS',         'track_c_providers');
 define('TABLE_STATISTIC_TRACK_C_REFERERS',          'track_c_referers');
 
+//Course catalog stats see #4191
+define('TABLE_STATISTIC_TRACK_COURSE_RANKING',      'track_course_ranking');
+define('TABLE_MAIN_USER_REL_COURSE_VOTE',           'user_course_vote');
 
 
 // SCORM database tables

+ 36 - 17
main/inc/lib/database.lib.php

@@ -378,7 +378,7 @@ class Database {
      * @return int The number of rows in the given table.
      */
     public static function count_rows($table) {
-        $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table"));
+        $obj = self::fetch_object(self::query("SELECT COUNT(*) AS n FROM $table"));   // 
         return $obj->n;
     }
 
@@ -1154,7 +1154,7 @@ class Database {
      * @todo known issues, it doesn't work when using LIKE conditions example: array('where'=>array('course_code LIKE "?%"'))
     */
 
-    public static function select($columns = '*' , $table_name,  $conditions = array(), $type_result = 'all', $option = 'ASSOC') {
+    public static function select($columns, $table_name,  $conditions = array(), $type_result = 'all', $option = 'ASSOC') {
         $conditions = self::parse_conditions($conditions);
         
         //@todo we could do a describe here to check the columns ...
@@ -1170,7 +1170,7 @@ class Database {
         }
 
         $sql    = "SELECT $clean_columns FROM $table_name $conditions";
-	    //echo $sql.'<br />';
+	//echo $sql.'<br />';
         $result = self::query($sql);
         $array = array();
         //if (self::num_rows($result) > 0 ) {
@@ -1237,28 +1237,47 @@ class Database {
                         $return_value = " WHERE $where_return" ;
                     }
                     break;
-                case 'order':
-                    $order_array = explode(' ', $condition_data);
-                    if (!empty($order_array)) {
-                        if (count($order_array) > 1 && !empty($order_array[0])) {                            
-                            $order_array[0] = self::escape_string($order_array[0]);
-                            if (!empty($order_array[1])) {
-                                $order_array[1] = strtolower($order_array[1]);
-                                $order = 'desc';
-                                if (in_array($order_array[1], array('desc', 'asc'))) {
-                                    $order = $order_array[1];
+                case 'order':                    
+                    $order_array = $condition_data;                
+                    
+                    if (!empty($order_array)) {                           
+                        if (count($order_array) >= 1 && !empty($order_array[0])) {                            
+                            $order_array = self::escape_string($order_array[0]);
+                            
+                            $new_order_array = explode(',', $order_array);
+                            
+                            $temp_value = array();
+                 
+                            foreach($new_order_array as $element) {
+                                $element = explode(' ', $element);
+                                $element = array_filter($element);
+                                $element = array_values($element);
+                                
+                                if (!empty($element[1])) {
+                                    $element[1] = strtolower($element[1]);
+                                    $order = 'DESC';
+                                    if (in_array($element[1], array('desc', 'asc'))) {
+                                        $order = $element[1];
+                                    }                            
+                                    $temp_value[]= $element[0].' '.$order.' ';                                       
+                                } else {
+                                    //by default DESC
+                                    $temp_value[]= $element[0].' DESC ';                                       
                                 }
                             }
-                            $return_value .= ' ORDER BY '.$order_array[0].'  '.$order;
-                        }  else {
-                            $return_value .= ' ORDER BY '.$order_array[0].' DESC ';                            
+                            if (!empty($temp_value)) {
+                                $return_value .= ' ORDER BY '.implode(', ', $temp_value);                                
+                            } else {
+                                //$return_value .= '';
+                            }
                         }
                     }                    
                     break;
                 case 'limit':
                     $limit_array = explode(',', $condition_data);
+                    
                     if (!empty($limit_array)) {
-                        if (count($limit_array) > 1) {
+                        if (count($limit_array) > 1) {                            
                             $return_value .= ' LIMIT '.intval($limit_array[0]).' , '.intval($limit_array[1]);
                         }  else {
                             $return_value .= ' LIMIT '.intval($limit_array[0]);

+ 32 - 17
main/inc/lib/database.mysqli.lib.php

@@ -1092,9 +1092,7 @@ class Database {
         }
 
 
-         $sql    = "SELECT $clean_columns FROM $table_name $conditions";
-
-
+        $sql    = "SELECT $clean_columns FROM $table_name $conditions";
 
         $result = self::query($sql);
         $array = array();
@@ -1158,23 +1156,40 @@ class Database {
                     }
                 break;
                 case 'order':
-                    $order_array = explode(' ', $condition_data);
-
-                    if (!empty($order_array)) {
-                        if (count($order_array) > 1) {
-                            $order_array[0] = self::escape_string($order_array[0]);
-                            if (!empty($order_array[1])) {
-                                $order_array[1] = strtolower($order_array[1]);
-                                $order = 'desc';
-                                if (in_array($order_array[1], array('desc', 'asc'))) {
-                                    $order = $order_array[1];
+                    $order_array = $condition_data;                
+                    
+                    if (!empty($order_array)) {                           
+                        if (count($order_array) >= 1 && !empty($order_array[0])) {                            
+                            $order_array = self::escape_string($order_array[0]);
+                            
+                            $new_order_array = explode(',', $order_array);
+                            
+                            $temp_value = array();
+                 
+                            foreach($new_order_array as $element) {
+                                $element = explode(' ', $element);
+                                $element = array_filter($element);
+                                $element = array_values($element);
+                                
+                                if (!empty($element[1])) {
+                                    $element[1] = strtolower($element[1]);
+                                    $order = 'DESC';
+                                    if (in_array($element[1], array('desc', 'asc'))) {
+                                        $order = $element[1];
+                                    }                            
+                                    $temp_value[]= $element[0].' '.$order.' ';                                       
+                                } else {
+                                    //by default DESC
+                                    $temp_value[]= $element[0].' DESC ';                                       
                                 }
                             }
-                            $return_value .= ' ORDER BY '.$order_array[0].'  '.$order;
-                        }  else {
-                            $return_value .= ' ORDER BY '.$order_array[0].' DESC ';
+                            if (!empty($temp_value)) {
+                                $return_value .= ' ORDER BY '.implode(', ', $temp_value);                                
+                            } else {
+                                //$return_value .= '';
+                            }
                         }
-                    }
+                    } 
                 break;
 
                 case 'limit':

+ 31 - 1
main/inc/lib/display.lib.php

@@ -1098,7 +1098,7 @@ class Display {
                 // If it's a survey, make sure the user's invited. Otherwise drop it.
                 if ($item_property['tool'] == TOOL_SURVEY) {
                     $survey_info = survey_manager::get_survey($item_property['ref'], 0, $course_code);
-                    $invited_users = SurveyUtil::get_invited_users($survey_info['code'], $course_database);
+                    $invited_users = SurveyUtil::get_invited_users($survey_info['code'], $course_code);
                     if (!in_array($user_id, $invited_users['course_users'])) continue;
                 }
                 // If it's a learning path, ensure it is currently visible to the user
@@ -1271,4 +1271,34 @@ class Display {
         }
         return $output;
     }
+
+    /**
+     * 
+     * 
+     * @param   int     id of the class
+     * @param   int     percentage 0-100 %
+     * @param   string  url that will be added (for the jquery stuff)
+     **/
+    public function return_rating_system($id, $percentage, $url, $number_of_users_who_voted = null) {
+        $percentage = intval($percentage);
+        if (!empty($percentage)) {
+            $percentage = $percentage*125/100;
+        }
+        $html = '<ul id = "'.$id.'" class="star-rating">
+            <li class="current-rating" style="width:'.$percentage.'px;"></li>
+            <li><a href="javascript:void(0)" rel="'.$url.'&star=1" title="'.get_lang('OneStarOutOf5').'"  class="one-star">1</a></li>
+            <li><a href="javascript:void(0)" rel="'.$url.'&star=2" title="'.get_lang('TwoStarsOutOf5').'" class="two-stars">2</a></li>
+            <li><a href="javascript:void(0)" rel="'.$url.'&star=3" title="'.get_lang('ThreeStarsOutOf5').'" class="three-stars">3</a></li>
+            <li><a href="javascript:void(0)" rel="'.$url.'&star=4" title="'.get_lang('FourStarsOutOf5').'" class="four-stars">4</a></li>
+            <li><a href="javascript:void(0)" rel="'.$url.'&star=5" title="'.get_lang('FiveStarsOutOf5').'" class="five-stars">5</a></li>
+        </ul>';
+        
+        //if (!isset($number_of_users_who_voted)) {
+            $label = $number_of_users_who_voted == 1 ? get_lang('Vote') : get_lang('Votes'); 
+            $html .= Display::span($number_of_users_who_voted.' '.$label, array('id' =>  'vote_label_'.$id));
+            $html .= ' '.Display::span(' ', array('id' =>  'vote_label2_'.$id));
+        //}
+        return $html;
+        
+    }
 } //end class Display

+ 9 - 1
main/inc/lib/document.lib.php

@@ -1053,6 +1053,14 @@ return 'application/octet-stream';
             
             $row['url'] 			= api_get_path(WEB_CODE_PATH).'document/showinframes.php?cidReq='.$course_code.'&id='.$id;
             $row['document_url'] 	= api_get_path(WEB_CODE_PATH).'document/document.php?cidReq='.$course_code.'&id='.$id;
+            
+            $row['absolute_path']   = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document'.$row['path'];
+
+            $pathinfo = pathinfo($row['path']);
+            
+            $row['absolute_parent_path']   = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document'.$pathinfo['dirname'].'/';
+        
+
             $row['direct_url'] 		= $www.$path;
             
             if (dirname($row['path']) == '.') { 
@@ -2192,7 +2200,7 @@ return 'application/octet-stream';
                         if (!empty($comment)) {
                         	$params['comment'] = trim($comment);
                         }         
-                        Database::update($table_document, $params, array('id = ?' =>$docid));                                           
+                        Database::update($table_document, $params, array('id = ? AND c_id = ? ' => array($docid, $course_info['real_id'])));                                           
                     }
 
                     // Showing message when sending zip files

+ 15 - 10
main/inc/lib/events.lib.inc.php

@@ -26,6 +26,7 @@ $TABLETRACK_EXERCICES 	    = Database::get_statistic_table(TABLE_STATISTIC_TRACK
 $TABLETRACK_LASTACCESS 	    = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS); //for "what's new" notification
 $TABLETRACK_DEFAULT 	    = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
 
+
 /* FUNCTIONS */
 /**
  * @author Sebastien Piraux <piraux_seb@hotmail.com>
@@ -106,32 +107,36 @@ function event_login() {
  * @desc Record information for access event for courses
  */
 function event_access_course() {
-	global $_user;
-	global $_cid;
-	global $TABLETRACK_ACCESS;
-	global $TABLETRACK_LASTACCESS; //for "what's new" notification
-
+	global $_user, $TABLETRACK_ACCESS,  $TABLETRACK_LASTACCESS;
+	
 	$id_session = api_get_session_id();	
-	$reallyNow = api_get_utc_datetime();
+	$now        = api_get_utc_datetime();    
+    $_cid       = api_get_course_id();    
+    
 	if ($_user['user_id']) {
 		$user_id = "'".$_user['user_id']."'";
 	} else {
 		$user_id = "0"; // no one
 	}
 	$sql = "INSERT INTO ".$TABLETRACK_ACCESS."  (access_user_id, access_cours_code, access_date, access_session_id) VALUES
-		    (".$user_id.", '".$_cid."', '".$reallyNow."','".$id_session."')";
+		    (".$user_id.", '".$_cid."', '".$now."','".$id_session."')";
 	$res = Database::query($sql);
+	
 	// added for "what's new" notification
-	$sql = "UPDATE $TABLETRACK_LASTACCESS  SET access_date = '$reallyNow' 
+	$sql = "UPDATE $TABLETRACK_LASTACCESS  SET access_date = '$now' 
 			WHERE access_user_id = $user_id AND access_cours_code = '$_cid' AND access_tool IS NULL AND access_session_id=".$id_session;
 	$res = Database::query($sql);
+    
 	if (Database::affected_rows() == 0) {
 		$sql = "INSERT INTO $TABLETRACK_LASTACCESS (access_user_id, access_cours_code, access_date, access_session_id)
-				VALUES (".$user_id.", '".$_cid."', '$reallyNow', '".$id_session."')";
+				VALUES (".$user_id.", '".$_cid."', '$now', '".$id_session."')";
 		$res = Database::query($sql);
 	}
 	// end "what's new" notification
-	return 1;
+	
+    //Course catalog stats modifications see #4191    
+    CourseManager::update_course_ranking();
+    return 1;
 }
 
 /**

+ 4 - 6
main/inc/lib/fckeditor/editor/plugins/ImageManager/Classes/ImageManager.php

@@ -117,8 +117,7 @@ class ImageManager
 		}
 
 		$user_id = api_get_user_id();
-		while (false !== ($entry = $d->read()))
-		{
+		while (false !== ($entry = $d->read())) {
 			//If it is a directory, and it doesn't start with
 			// a dot, and if is it not the thumbnail directory
 			if(is_dir($base.$entry)
@@ -133,15 +132,14 @@ class ImageManager
 				$relative = Files::fixPath($path.$entry);
 				$fullpath = Files::fixPath($base.$entry);
 
-				if ($in_group && strpos($fullpath, '_groupdocs') !== false && strpos($fullpath, $group_directory) === false)
-				{
+				if ($in_group && strpos($fullpath, '_groupdocs') !== false && strpos($fullpath, $group_directory) === false) {
 					continue;
 				}
 				global $_course;
-				if (isset($_course['dbName']) && $_course<>'-1') {
+				if (!empty($_course)) {
 					$base_dir = substr($fullpath, 0, strpos($fullpath,'/document/')+9); //
 					$new_dir  = substr($fullpath, strlen($base_dir),-1); //
-					$doc_id = DocumentManager::get_document_id($_course, $new_dir );
+					$doc_id = DocumentManager::get_document_id($_course, $new_dir);
 					$visible_status= api_get_item_visibility($_course,TOOL_DOCUMENT,$doc_id);
 				}
 

+ 3 - 5
main/inc/lib/groupmanager.lib.php

@@ -434,11 +434,12 @@ class GroupManager {
 	 * @return array All properties. Array-keys are name, tutor_id, description, maximum_number_of_students, directory and visibility of tools
 	 */
 	public static function get_group_properties ($group_id) {
+	    $course_id = api_get_course_int_id();
 		if (empty($group_id) or !is_integer(intval($group_id)) ) {
 			return null;
 		}
 		$table_group = Database :: get_course_table(TABLE_GROUP);
-		$sql = 'SELECT   *  FROM '.$table_group.' WHERE id = '.Database::escape_string($group_id);
+		$sql = "SELECT * FROM $table_group WHERE c_id = $course_id AND id = ".Database::escape_string($group_id);
 		$db_result = Database::query($sql);
 
 			$db_object = Database::fetch_object($db_result);
@@ -730,10 +731,7 @@ class GroupManager {
 		$sql = "UPDATE $table_group_cat SET display_order=$cat1->display_order WHERE id = $cat2->id AND c_id = $course_id ";
 		Database::query($sql);
 	}
-
-
-
-
+    
 	//GROUP USERS FUNCTIONS
 	
 	/**

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

@@ -401,7 +401,7 @@ function editlinkcategory($type) {
 			"category_id='" . Database :: escape_string($_POST['selectcategory']) . "', " .
 			"display_order='" . $max_display_order . "', " .
 			"on_homepage='" . Database :: escape_string($onhomepage) . " ' $mytarget " .
-			" WHERE id='" . intval($_POST['id']) . "'";
+			" WHERE c_id = $course_id AND id='" . intval($_POST['id']) . "'";
 			Database :: query($sql);
 
 			// Update search enchine and its values table if enabled.

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

@@ -1152,7 +1152,8 @@ function api_get_course_info($course_code = null) {
         }
         return $_course;
     }
-    global $_course;    
+    global $_course;
+    if ($_course == '-1') $_course = array();
     return $_course;
 }
 

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

@@ -953,7 +953,7 @@ class MessageManager
 				$html .= '<div class="topic_div">';
 				
 				    $items = $topic['count'];				    
-				    $reply_label = ($items == 1) ? get_lang('Reply'): get_lang('Replies');
+				    $reply_label = ($items == 1) ? get_lang('GroupReply'): get_lang('GroupReplies');
 				    $html .= '<table width="100%"><tr><td width="20px" valign="top">'; 
 				    $html .= Display::div(Display::tag('span', $items).$reply_label, array('class' =>'group_discussions_replies'));
 				    $html .= '</td><td width="150px"  valign="top">';

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

@@ -84,7 +84,7 @@ class Model {
      * Get the count of elements
      */
     public function get_count() {        
-        $row = Database::select('count(*) as count', $this->table, array(),'first');
+        $row = Database::select('count(*) as count', $this->table, array('where' => array('parent_id = ?' => '0')),'first');
         return $row['count'];
     }
         

+ 74 - 33
main/inc/lib/sessionmanager.lib.php

@@ -19,8 +19,8 @@
 */
 class SessionManager {    
 	private function __construct() {
-
 	}
+    
     /**
      * Fetches a session from the database
      * @param   int     Session ID
@@ -135,18 +135,19 @@ class SessionManager {
 							   VALUES('".$name."','$date_start','$date_end','$id_coach',".api_get_user_id().",".$nb_days_acess_before.", ".$nb_days_acess_after.", ".$id_session_category.", ".$id_visibility.")";
 				Database::query($sql_insert);
 				$session_id = Database::insert_id();
-				
-				//Adding to the correct URL				
-				require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';				
                 
-                $tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-                $access_url_id = api_get_current_access_url_id();
-                UrlManager::add_session_to_url($session_id,$access_url_id);            
-
-				// add event to system log				
-				$user_id = api_get_user_id();
-				event_system(LOG_SESSION_CREATE, LOG_SESSION_ID, $session_id, api_get_utc_datetime(), $user_id);
-
+                if (!empty($session_id)) {                	
+    				//Adding to the correct URL				
+    				require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';				
+                    
+                    $tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+                    $access_url_id = api_get_current_access_url_id();
+                    UrlManager::add_session_to_url($session_id,$access_url_id);            
+    
+    				// add event to system log				
+    				$user_id = api_get_user_id();
+    				event_system(LOG_SESSION_CREATE, LOG_SESSION_ID, $session_id, api_get_utc_datetime(), $user_id);
+    		    }
 				return $session_id;
 			}
 		}
@@ -193,11 +194,12 @@ class SessionManager {
         $num = $recorset['total_rows'];
         return $num;    
     }
+    
     /**
      * Gets the admin session list callback of the admin/session_list.php page
      * @param array order and limit keys
      */
-    function get_sessions_admin($options) {
+    public function get_sessions_admin($options) {
         $tbl_session            = Database::get_main_table(TABLE_MAIN_SESSION);
         $tbl_session_category   = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);        
         $tbl_user               = Database::get_main_table(TABLE_MAIN_USER);        
@@ -207,19 +209,31 @@ class SessionManager {
         if (api_is_session_admin()==true) {
             $where.=" AND s.session_admin_id = $user_id ";
         }        
-        
-        if (!empty($options['where'])) {
-           $where .= ' AND '.$options['where']; 
-        }
-        
+      
         $coach_name = " CONCAT (u.lastname , ' ', u.firstname) as coach_name ";
+        
         if (api_is_western_name_order()) {            
             $coach_name = " CONCAT (u.firstname, ' ', u.lastname) as coach_name ";
-        }
-        $query = "SELECT s.name, nbr_courses, s.date_start, s.date_end, $coach_name , sc.name as category_name, s.visibility, u.user_id, s.id   ".
-            " FROM $tbl_session s ".
-                " LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id ".
-                " INNER JOIN $tbl_user u ON s.id_coach = u.user_id ".
+        }        
+
+        $today = api_get_utc_datetime();
+        $today = api_strtotime($today);
+        
+        $today = date('Y-m-d', $today);
+        
+        $select = "SELECT * FROM (SELECT 
+                IF ( 
+                    (s.date_start <= '$today' AND '$today' < s.date_end) OR 
+                    (s.date_start  = '0000-00-00' AND s.date_end  = '0000-00-00' ) OR
+                    (s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
+                    ('$today' < s.date_end AND '0000-00-00' = s.date_start)
+                , 1, 0) 
+                as session_active, 
+                s.name, nbr_courses, s.date_start, s.date_end, $coach_name, sc.name as category_name, s.visibility, u.user_id, s.id";
+                   
+        $query = "$select FROM $tbl_session s 
+                LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id 
+                INNER JOIN $tbl_user u ON s.id_coach = u.user_id ".
              $where;
              
         if ($_configuration['multiple_access_urls']) {
@@ -227,31 +241,52 @@ class SessionManager {
             $access_url_id = api_get_current_access_url_id();
             if ($access_url_id != -1) {
                 $where.= " AND ar.access_url_id = $access_url_id ";
-                $query = "SELECT s.id, s.name, s.nbr_courses, s.date_start, s.date_end, u.firstname, u.lastname , sc.name as category_name , s.visibility, u.user_id
+                $query = "$select
                  FROM $tbl_session s
                     LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
                     INNER JOIN $tbl_user u ON s.id_coach = u.user_id
                     INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
                  $where";
             }
-        }         
-        $query .= "ORDER BY ".$options['order']." LIMIT ".$options['limit'];              
-       
-        $result     = Database::query($query);
+        }  
+        $query .= ") AS session_table";   
+        
+          
+        if (!empty($options['where'])) {
+           $query .= ' WHERE '.$options['where']; 
+        }
+            
+        $query .= " ORDER BY ".$options['order']." LIMIT ".$options['limit'];
+                 
+       // echo $query;
+        $result = Database::query($query);
         $formatted_sessions = array();
         if (Database::num_rows($result)) {
             $sessions   = Database::store_result($result);
             foreach ($sessions as $session) {
                 $session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
                 
-                $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);  
+                $session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
+                
+                if ($session['date_start'] == '0000-00-00' && $session['date_end'] == '0000-00-00') {
+                //    $session['session_active'] = 1;
+                }
+                
+                if ($session['session_active'] == 1) {
+                    $session['session_active'] = Display::return_icon('accept.png', get_lang('Active'), array(), 22);
+                } else {
+                    $session['session_active'] = Display::return_icon('error.png', get_lang('Inactive'), array(), 22);
+                }
+                     
            
                 if ($session['date_start'] == '0000-00-00') {
                     $session['date_start'] = '';
                 }
                 if ($session['date_end'] == '0000-00-00') {
                     $session['date_end'] = '';
-                }                
+                }
+                
+                     
                 switch ($session['visibility']) {
                     case SESSION_VISIBLE_READ_ONLY: //1
                         $session['visibility'] =  get_lang('ReadOnly');
@@ -1086,11 +1121,16 @@ class SessionManager {
 	public static function delete_session_category($id_checked, $delete_session = false,$from_ws = false){
 		$tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 		$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
-		if(is_array($id_checked)) {
-			$id_checked=Database::escape_string(implode(',',$id_checked));
+		if (is_array($id_checked)) {
+			$id_checked = Database::escape_string(implode(',',$id_checked));
 		} else {
-			$id_checked=intval($id_checked);
+			$id_checked = intval($id_checked);
 		}
+		
+		//Setting session_category_id to 0
+		$sql = "UPDATE $tbl_session SET session_category_id = 0 WHERE session_category_id IN (".$id_checked.")";
+        $result = Database::query($sql);
+        
 		$sql = "SELECT id FROM $tbl_session WHERE session_category_id IN (".$id_checked.")";
 		$result = @Database::query($sql);
 		while ($rows = Database::fetch_array($result)) {
@@ -1109,6 +1149,7 @@ class SessionManager {
 
 		// Add event to system log		
 		$user_id = api_get_user_id();
+        
 		event_system(LOG_SESSION_CATEGORY_DELETE, LOG_SESSION_CATEGORY_ID, $id_checked, api_get_utc_datetime(), $user_id);
 
 

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

@@ -331,6 +331,7 @@ class Skill extends Model {
         $sql = "SELECT id, name, description, parent_id, relation_type 
                 FROM {$this->table} s INNER JOIN {$this->table_skill_rel_skill} ss ON (s.id = ss.skill_id) 
                 $id_condition";
+                
         $result = Database::query($sql);
         $skills = array();        
         
@@ -507,11 +508,10 @@ class Skill extends Model {
    
     public function get_user_skills($user_id, $get_skill_data = false) {
         $user_id = intval($user_id);        
-        //$sql = 'SELECT skill.*, user.* FROM '.$this->table_skill_rel_user.' user INNER JOIN '.$this->table_skill.' skill
-        
         $sql = 'SELECT DISTINCT s.id, s.name FROM '.$this->table_skill_rel_user.' u INNER JOIN '.$this->table.' s 
                 ON u.skill_id = s.id
                 WHERE user_id = '.$user_id;
+                
         $result = Database::query($sql);
         $skills = Database::store_result($result, 'ASSOC');
         $clean_skill = array();        

+ 10 - 3
main/inc/lib/system_announcements.lib.php

@@ -531,14 +531,17 @@ class SystemAnnouncementManager {
 		$user_table = Database :: get_main_table(TABLE_MAIN_USER);
 		
 		if ($teacher <> 0 AND $student == 0) {
-			$sql = "SELECT firstname, lastname, email, status FROM $user_table u $url_condition WHERE email<>'' AND status = '1' AND active = 1";
+			$sql = "SELECT firstname, lastname, email, status FROM $user_table u $url_condition WHERE status = '1' ";
 		}
+        
 		if ($teacher == 0 AND $student <> 0) {
-			$sql = "SELECT firstname, lastname, email, status FROM $user_table u $url_condition WHERE email<>'' AND status = '5' AND active = 1 ";
+			$sql = "SELECT firstname, lastname, email, status FROM $user_table u $url_condition WHERE status = '5' ";
 		}
+        
 		if ($teacher<> 0 AND $student <> 0) {
-			$sql = "SELECT firstname, lastname, email FROM $user_table u $url_condition WHERE email<>'' AND active = 1 ";
+			$sql = "SELECT firstname, lastname, email FROM $user_table u $url_condition WHERE 1=1 ";
 		}
+        
 		if (!empty($language)) { //special condition because language was already treated for SQL insert before
 			$sql .= " AND language = '".Database::escape_string($language)."' ";
 		}
@@ -547,10 +550,14 @@ class SystemAnnouncementManager {
 		if ($_configuration['multiple_access_urls']) {		
 		  $sql .= " AND access_url_id = '".$current_access_url_id."' ";
         }
+        
+        //Sent to active users
+        $sql .= " AND email <>'' AND active = 1 ";
 		
 		if ((empty($teacher) or $teacher == '0') AND  (empty($student) or $student == '0')) {
 			return true;
 		}        
+        
 		$result = Database::query($sql);
 		if ($result === false) {
 			return false;

+ 57 - 10
main/inc/lib/template.lib.php

@@ -26,11 +26,14 @@ class Template extends Smarty {
 		$this->cache_lifetime 	= Smarty::CACHING_OFF; // no caching
 		//$this->cache_lifetime 	= 120;
 		
-		//By default we show the header and footer
+		//header and footer are showed by default
 		$this->set_footer($show_footer);
 		$this->set_header($show_header);
 		
-		$this->set_system_parameters();		
+		//Setting system variables
+		$this->set_system_parameters();
+        
+        //Setting user variables 
 		$this->set_user_parameters();
 		
 		//Creating a Smarty modifier - Now we can call the get_lang from a template!!! Just use {"MyString"|get_lang} 
@@ -38,16 +41,33 @@ class Template extends Smarty {
 		$this->registerPlugin("modifier","get_path", "api_get_path");
 		$this->registerPlugin("modifier","get_setting", "api_get_setting");
 		
-		//To load a smarty plugin				
+		//To load a smarty plugin
 		//$this->loadPlugin('smarty_function_get_lang');
+		
+		//To the the smarty installation
 		//$this->testInstall();			
+		
 		$this->set_header_parameters();
-		$this->set_footer_parameters();		
+		$this->set_footer_parameters();
+        
 		$this->assign('style', $this->style);
 	}
 
+    /*
+     * Use smarty to parse the actions menu
+     * @todo finish it!
+     * */
+    function set_actions($actions) {
+        $action_string = '';
+        if (!empty($actions)) {
+            foreach($actions as $action) {                
+            }
+        }
+        $this->assign('actions', $actions);        
+    }
+
 	/**
-	 * Shortcut to display a 1 col layout
+	 * Shortcut to display a 1 col layout (index.php)
 	 * */
 	function display_one_col_template() {		
 		$tpl = $this->get_template('layout/layout_1_col.tpl');
@@ -55,7 +75,7 @@ class Template extends Smarty {
 	}
 	
 	/**
-	* Shortcut to display a 2 col layout
+	* Shortcut to display a 2 col layout (userportal.php)
 	* */	
 	function display_two_col_template() {		
 		$tpl = $this->get_template('layout/layout_2_col.tpl');
@@ -77,8 +97,6 @@ class Template extends Smarty {
         $tpl = $this->get_template('layout/no_layout.tpl');
         $this->display($tpl);
     }
-    
-    
 	
 	/**	  
 	 * Sets the footer visibility 
@@ -90,11 +108,33 @@ class Template extends Smarty {
 	}
 	/**
 	 * Sets the header visibility
-	 * 
+	 * @param bool true if we show the header
 	 */
 	function set_header($status) {
 		$this->show_header = $status;
-		$this->assign('show_header', $status);	
+		$this->assign('show_header', $status);
+        
+        $show_admin_toolbar = api_get_setting('show_admin_toolbar');
+        $show_toolbar = 0;
+        
+        switch($show_admin_toolbar) {
+            case 'do_not_show':                
+                break;
+            case 'show_to_admin':
+                if (api_is_platform_admin()) {
+                    $show_toolbar = 1;
+                }
+                break;    
+            case 'show_to_admin_and_teachers':
+                if (api_is_platform_admin() || api_is_allowed_to_edit()) {
+                    $show_toolbar = 1;
+                }
+                break;
+            case 'show_to_all':
+                $show_toolbar = 1;
+                break;                               
+        }        
+        $this->assign('show_toolbar', $show_toolbar);
 	}
 		
 	function get_template($name) {
@@ -107,8 +147,15 @@ class Template extends Smarty {
 		if (api_get_user_id() && !api_is_anonymous()) {
 			$user_info = api_get_user_info();			
 			$user_info['logged'] = 1;
+            
+            $user_info['is_admin'] = 0;
+            if (api_is_platform_admin()) {
+                $user_info['is_admin'] = 1;    
+            }
+            
 			$user_info['messages_count'] = MessageManager::get_new_messages();
 		}		
+        //Setting the $_u array that could be use in any template 
 		$this->assign('_u', $user_info);
 	}	
 	

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 2086 - 2086
main/inc/lib/tracking.lib.php


+ 9 - 6
main/inc/lib/urlmanager.lib.php

@@ -535,12 +535,11 @@ class UrlManager
 	 * @param array user list
 	 * @param int access_url_id
 	 * */
-	public static function update_urls_rel_course($course_list,$access_url_id)
-	{
+	public static function update_urls_rel_course($course_list,$access_url_id) {
 		$table_course			= Database :: get_main_table(TABLE_MAIN_COURSE);
 		$table_url_rel_course	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 
-		$sql = "SELECT course_code FROM $table_url_rel_course WHERE access_url_id=".Database::escape_string($access_url_id);
+		$sql = "SELECT course_code FROM $table_url_rel_course WHERE access_url_id=".intval($access_url_id);
 		$result = Database::query($sql);
 		$existing_courses = array();
 
@@ -549,9 +548,11 @@ class UrlManager
 		}
 
 		//adding courses
-		foreach($course_list as $course) {
-			if(!in_array($course, $existing_courses)) {
-				UrlManager::add_course_to_url($course,$access_url_id);
+		foreach($course_list as $course_code) {
+			if(!in_array($course_code, $existing_courses)) {
+				UrlManager::add_course_to_url($course_code, $access_url_id);
+                $course_info = api_get_course_info($course_code);
+                CourseManager::update_course_ranking($course_info['real_id'], 0, $access_url_id);
 			}
 		}
 
@@ -559,6 +560,8 @@ class UrlManager
 		foreach($existing_courses as $existing_course) {
 			if(!in_array($existing_course, $course_list)) {
 				UrlManager::delete_url_rel_course($existing_course,$access_url_id);
+                $course_info = api_get_course_info($existing_course);
+                CourseManager::update_course_ranking($course_info['real_id'], 0, $access_url_id);
 			}
 		}
 	}

+ 7 - 17
main/inc/lib/userportal.lib.php

@@ -391,20 +391,9 @@ class IndexManager {
 	}
     
     function return_skills_links() {
-        $content = '<ul class="menulist">';
-        
-/*        $content .= Display::tag('li', Display::url(get_lang('SkillsTree'), api_get_path(WEB_CODE_PATH).'admin/skills.php'));
-        
-        $content .= Display::tag('li', Display::url(get_lang('SkillsProfile'), api_get_path(WEB_CODE_PATH).'admin/skills_profile.php'));
-        
-        $content .= Display::tag('li', Display::url(get_lang('SkillsGradebook'), api_get_path(WEB_CODE_PATH).'admin/skills_gradebook.php'));
-  */      
+        $content = '<ul class="menulist">';      
         $content .= Display::tag('li', Display::url(get_lang('MySkills'), api_get_path(WEB_CODE_PATH).'social/skills_tree.php'));
-        
-        
-        
-        $content .= '</ul>';
-        
+        $content .= '</ul>';        
         $html = self::show_right_block(get_lang("Skills"), $content);
         return $html;
     }
@@ -444,10 +433,7 @@ class IndexManager {
 			}
 		}
 		return '<div id="login_fail">'.$message.'</div>';
-	}
-	
-	
-	
+	}	
 	
 	/**
 	 * Display list of courses in a category.
@@ -1338,4 +1324,8 @@ class IndexManager {
 			}
 		}
 	}
+
+	function return_hot_courses() {
+		return CourseManager::return_hot_courses();		
+	}
 }

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

@@ -800,11 +800,21 @@ if (isset($cidReset) && $cidReset) { // course session data refresh requested or
         if (!isset($_SESSION['login_as'])) {
             
             $course_tracking_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
+            
+            /* 
+             * When $_configuration['session_lifetime'] is too big 100 hours (in order to let users take exercises with no problems)
+             * the function Tracking::get_time_spent_on_the_course() returns big values (200h) due the condition: 
+             * login_course_date > now() - INTERVAL $session_lifetime SECOND
+             * 
+            */
+            /*
             if (isset($_configuration['session_lifetime'])) {
                 $session_lifetime    = $_configuration['session_lifetime'];
             } else {
                 $session_lifetime    = 3600; // 1 hour
-            }
+            }*/
+            
+            $session_lifetime    = 3600; // 1 hour
 
             $course_code = $_course['sysCode'];
             $time = api_get_datetime();
@@ -883,7 +893,7 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) { // ses
             if (Database::num_rows($result) > 0) { // this  user have a recorded state for this course
                 $cuData = Database::fetch_array($result);                
                 
-                if ($_course['activate_legal'] == 1) {                    
+                if ($_course['activate_legal'] == 1 && !api_is_platform_admin()) {                    
                     $user_is_subscribed = CourseManager::is_user_accepted_legal($_user['user_id'], $_course['id'], $session_id);                    
                     if (!$user_is_subscribed) {
                         $url = api_get_path(WEB_CODE_PATH).'course_info/legal.php?course_code='.$_course['code'].'&session_id='.$session_id;
@@ -918,7 +928,7 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) { // ses
 				$result = Database::query($sql);
                 $row 	= Database::store_result($result);
            
-                if (isset($row) && $row[0]['id_coach'] == $_user['user_id']) {
+                if (isset($row) && isset($row[0]) && $row[0]['id_coach'] == $_user['user_id']) {
 					$_courseUser['role'] = 'Professor';
 	                $is_courseMember     = true;
 	                $is_courseTutor      = true;
@@ -931,7 +941,7 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) { // ses
 	                	$is_courseAdmin = false;
 					}
 					api_session_register('_courseUser');
-	            } elseif(isset($row) && $row[0]['session_admin_id']==$_user['user_id']) { 
+	            } elseif( isset($row) && isset($row[0]) && $row[0]['session_admin_id']==$_user['user_id']) { 
 					$_courseUser['role'] = 'Professor';
 	                $is_courseMember     = false;
 	                $is_courseTutor      = false;
@@ -1060,8 +1070,8 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) { // ses
 
 if ((isset($gidReset) && $gidReset) || (isset($cidReset) && $cidReset)) { // session data refresh requested
 	if ($gidReq && $_cid ) { // have keys to search data
-		$group_table = Database::get_course_table(TABLE_GROUP);
-		$sql = "SELECT * FROM $group_table WHERE id = '$gidReq'";
+		$group_table = Database::get_course_table(TABLE_GROUP);    
+		$sql = "SELECT * FROM $group_table WHERE c_id = ".$_course['real_id']." AND id = '$gidReq'";
 		$result = Database::query($sql);
 		if (Database::num_rows($result) > 0) { // This group has recorded status related to this course
 			$gpData = Database::fetch_array($result);

+ 36 - 32
main/install/db_main.sql

@@ -855,7 +855,8 @@ VALUES
 ('allow_teacher_change_gradebook_grading_model', NULL, 'radio', 'Gradebook', 'false', 'AllowTeacherChangeGradebookGradingModelTitle', 'AllowTeacherChangeGradebookGradingModelComment', NULL, NULL, 1),
 ('grading_model', 'grading_model', 'custom', 'Gradebook', 'false', 'GradingModelTitle', 'GradingModelComment', NULL, NULL, 1),
 ('allow_users_to_change_email_with_no_password', NULL, 'radio', 'User', 'false', 'AllowUsersToChangeEmailWithNoPasswordTitle', 'AllowUsersToChangeEmailWithNoPasswordComment', NULL, NULL, 0),
-('chamilo_database_version',NULL,'textfield',NULL, '1.9.0.16305','DokeosDatabaseVersion','', NULL, NULL, 0);
+('show_admin_toolbar', NULL, 'radio', 'Platform', 'true', 'ShowAdminToolbarTitle', 'ShowAdminToolbarComment', NULL, NULL, 1),
+('chamilo_database_version',NULL,'textfield',NULL, '1.9.0.16368','DokeosDatabaseVersion','', NULL, NULL, 0);
 
 /*
 ('use_custom_pages',NULL,'radio','Platform','false','UseCustomPages','useCustomPagesComment','platform',NULL,0),
@@ -1163,7 +1164,11 @@ VALUES
 ('grading_model', '1*X+1*X+1*X+1*X/4', 'Model 3'),
 ('grading_model', '1*X+2*X+1*X+2*X/6', 'Model 4'),
 ('allow_users_to_change_email_with_no_password', 'true', 'Yes'),
-('allow_users_to_change_email_with_no_password', 'false', 'No');
+('allow_users_to_change_email_with_no_password', 'false', 'No'),
+('show_admin_toolbar', 'do_not_show', 'DoNotShow'),
+('show_admin_toolbar', 'show_to_admin', 'ShowToAdminsOnly'), 
+('show_admin_toolbar', 'show_to_admin_and_teachers', 'ShowToAdminsAndTeachers'),
+('show_admin_toolbar', 'show_to_all', 'ShowToAllUsers');
 
 /*
 ('use_custom_pages','true','Yes'),
@@ -2813,35 +2818,34 @@ CREATE TABLE skill_rel_profile (
 
 
 
+CREATE TABLE track_course_ranking (
+ id   int unsigned not null PRIMARY KEY AUTO_INCREMENT,
+ c_id  int unsigned not null,
+ session_id  int unsigned not null default 0,
+ url_id  int unsigned not null default 0, 
+ accesses int unsigned not null default 0,
+ points int unsigned not null default 0,
+ users int unsigned not null default 0,
+ creation_date datetime not null
+);
+
+ALTER TABLE track_course_ranking ADD INDEX idx_tcc_cid (c_id);
+ALTER TABLE track_course_ranking ADD INDEX idx_tcc_sid (session_id);
+ALTER TABLE track_course_ranking ADD INDEX idx_tcc_urlid (url_id);
+ALTER TABLE track_course_ranking ADD INDEX idx_tcc_creation_date (creation_date);
+
+CREATE TABLE user_course_vote(
+  id int unsigned not null AUTO_INCREMENT PRIMARY KEY,
+  c_id int unsigned not null,
+  user_id int unsigned not null,  
+  session_id int unsigned not null default 0,
+  url_id int unsigned not null default 0,
+  vote int unsigned not null default 0
+);
+
+ALTER TABLE user_course_vote ADD INDEX idx_ucv_cid (c_id);
+ALTER TABLE user_course_vote ADD INDEX idx_ucv_uid (user_id);
+ALTER TABLE user_course_vote ADD INDEX idx_ucv_cuid (user_id, c_id);
+
 
 
---
--- Table structure for event alert sending
--- Pending check and approval
--- CREATE TABLE event_type (
---   id int unsigned NOT NULL AUTO_INCREMENT,
---   name varchar(50) NOT NULL,
---   name_lang_var varchar(40) NOT NULL,
---   desc_lang_var varchar(50) NOT NULL,
---   PRIMARY KEY (id)
--- );
--- 
--- CREATE TABLE event_type_message (
---   id int unsigned NOT NULL AUTO_INCREMENT,
---   event_type_id int NOT NULL,
---   language_id int NOT NULL,
---   message varchar(200) NOT NULL,
---   subject varchar(60) NOT NULL,
---   PRIMARY KEY (id)
--- );
--- 
--- CREATE TABLE user_rel_event_type (
---   id int NOT NULL AUTO_INCREMENT,
---   user_id int unsigned NOT NULL,
---   event_type_id int unsigned NOT NULL,
---   PRIMARY KEY (id)
--- );
--- 
--- INSERT INTO event_type VALUES (1, 'course_deleted','courseDeletedTitle','courseDeletedComment'),(2,'course_created','courseCreatedTitle','courseCreatedComment'),(3,'user_deleted','userDeletedTitle','userDeletedComment'),(4,'user_created','userCreatedTitle','userCreatedComment'), (5, 'session_created','sessionCreatedTitle','sessionCreatedComment'), (6,'session_deleted','sessionDeletedTitle','sessionDeletedComment'), (7,'session_category_created','sessionCategoryCreatedTitle','sessionCategoryCreatedComment'),(8,'session_category_deleted','sessionCategoryDeletedTitle','sessionCategoryDeletedComment'),(9,'settings_changed','settingsChangedTitle','settingsChangedComment'),(10,'user_subscribed','userSubscribedTitle','userSubscribedComment'), (11,'user_unsubscribed','userUnsubscribedTitle','userUnsubscribedComment');
--- 
--- INSERT INTO event_type_message (id,event_type_id,language_id,message,subject) VALUES (1,4,10,'ReportMessageUserCreated',''),(2,1,10,'DeleteCourse',''),(3,2,10,'CreateCourse',''),(4,3,10,'ReportMessageUserDeleted',''),(6,5,10,'CreateSessionTest',''),(7,6,10,'DeleteSession',''),(8,7,10,'CreateSessionCategory',''),(9,8,10,'DeleteSessionCategory',''),(10,9,10,'ChangeSetting',''),(11,10,10,'Subscribe',''),(12,11,10,'Unsubscribe','');

+ 16 - 7
main/install/migrate-db-1.8.8-1.9.0-pre.sql

@@ -123,11 +123,25 @@ INSERT INTO settings_options (variable, value, display_text) VALUES ('enable_hel
 ALTER TABLE gradebook_category MODIFY COLUMN weight FLOAT NOT NULL;
 ALTER TABLE gradebook_link MODIFY COLUMN weight FLOAT  NOT NULL;
 
--- Do not move this query
-UPDATE settings_current SET selected_value = '1.9.0.16305' WHERE variable = 'chamilo_database_version';
+INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_hr_skills_management', NULL, 'radio', 'Gradebook', 'true', 'AllowHRSkillsManagementTitle', 'AllowHRSkillsManagementComment', NULL, NULL, 1);
+
+INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_hr_skills_management', 'true', 'Yes');
+INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_hr_skills_management', 'false', 'No');
+
+INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('show_admin_toolbar', NULL, 'radio', 'Platform', 'true', 'ShowAdminToolbarTitle', 'ShowAdminToolbarComment', NULL, NULL, 1);
+
+INSERT INTO settings_options (variable, value, display_text) VALUES ('show_admin_toolbar', 'do_not_show', 'DoNotShow');
+INSERT INTO settings_options (variable, value, display_text) VALUES ('show_admin_toolbar', 'show_to_admin', 'ShowToAdminsOnly');
+INSERT INTO settings_options (variable, value, display_text) VALUES ('show_admin_toolbar', 'show_to_admin_and_teachers', 'ShowToAdminsAndTeachers');
+INSERT INTO settings_options (variable, value, display_text) VALUES ('show_admin_toolbar', 'show_to_all', 'ShowToAllUsers');
+
 
 
 
+
+-- Do not move this query
+UPDATE settings_current SET selected_value = '1.9.0.16368' WHERE variable = 'chamilo_database_version';
+
 -- xxSTATSxx
 ALTER TABLE track_e_exercices ADD COLUMN questions_to_check TEXT  NOT NULL DEFAULT '';
 --CREATE TABLE track_filtered_terms (id int, user_id int, course_id int, session_id int, tool_id char(12), filtered_term varchar(255), created_at datetime);
@@ -140,11 +154,6 @@ CREATE TABLE stored_values_stack (user_id INT NOT NULL, sco_id INT NOT NULL, sta
 ALTER TABLE stored_values_stack ADD KEY (user_id, sco_id, course_id, sv_key, stack_order);
 ALTER TABLE stored_values_stack ADD UNIQUE (user_id, sco_id, course_id, sv_key, stack_order);
 
-INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('allow_hr_skills_management', NULL, 'radio', 'Gradebook', 'true', 'AllowHRSkillsManagementTitle', 'AllowHRSkillsManagementComment', NULL, NULL, 1);
-
-INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_hr_skills_management', 'true', 'Yes');
-INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_hr_skills_management', 'false', 'No');
-
 -- xxUSERxx
 
 -- xxCOURSExx

+ 1 - 1
main/link/link.php

@@ -218,7 +218,7 @@ if (api_is_allowed_to_edit(null, true) && isset($_GET['action'])) {
 		}
 		echo '	<div class="row">
 					<div class="label">
-						<span class="form_required">*</span> '.get_lang('Url').'
+						<span class="form_required">*</span> URL
 					</div>
 					<div class="formw">
 						<input type="text" name="urllink" size="50" value="' . (empty($urllink) ? 'http://' : Security::remove_XSS($urllink)) . '" />

+ 7 - 8
main/metadata/md_document.php

@@ -149,9 +149,9 @@ function mdo_add_breadcrump_nav()
 }
 
 
-function mdobject($_course, $id)
-{
+function mdobject($_course, $id) {
     global $ieee_dcmap_e, $ieee_dcmap_v;  // md_funcs
+    $course_id = api_get_course_int_id();
 
     $this->mdo_course = $_course; $this->mdo_type = 'Document';
     $this->mdo_id = $id; $this->mdo_eid = $this->mdo_type . '.' . $id;
@@ -159,10 +159,9 @@ function mdobject($_course, $id)
     $this->mdo_dcmap_e = $ieee_dcmap_e; $this->mdo_dcmap_v = $ieee_dcmap_v;
 
     $document_table = Database::get_course_table(TABLE_DOCUMENT);
-    if (($docinfo = @Database::fetch_array(Database::query(
-            "SELECT path,title,comment,filetype FROM $document_table WHERE id='" .
-            addslashes($id) . "'"))))
-    {
+    $sql = "SELECT path,title,comment,filetype FROM $document_table WHERE c_id = $course_id AND id='" .intval($id) . "'";
+    
+    if (($docinfo = Database::fetch_array(Database::query($sql)))) {
         $this->mdo_path =     $docinfo['path'];
         $this->mdo_title =    $docinfo['title'];
         $this->mdo_comment =  $docinfo['comment'];
@@ -170,8 +169,8 @@ function mdobject($_course, $id)
         $this->mdo_group =    '';  // 2005-05-30: find group_id, if any
 
         $group_info = Database::get_course_table(TABLE_GROUP);
-        if (($result = Database::query(
-                "SELECT id,secret_directory FROM $group_info")))
+        $sql = "SELECT id,secret_directory FROM $group_info WHERE c_id = $course_id";
+        if (($result = Database::query($sql)))
             while (($row = Database::fetch_array($result)))
                 if (($secdir = $row['secret_directory'] . '/') ==
                         substr($this->mdo_path, 0, strlen($secdir)))

+ 7 - 5
main/metadata/md_link.php

@@ -135,6 +135,8 @@ function mdo_override(&$xmlDoc)  // by ref!
 
 function mdo_storeback(&$xmlDoc)  // by ref!
 {
+    $course_id = api_get_course_int_id();
+    
     if (!$this->mdo_url) return;  // no record in link table, most probably
 
     if (!($v = $xmlDoc->xmd_value('metadata/lom/technical/location'))) return;
@@ -164,7 +166,7 @@ function mdo_storeback(&$xmlDoc)  // by ref!
 
     $link_table = Database::get_course_table(TABLE_LINK);
     if ($u) Database::query("UPDATE $link_table SET " . substr($u, 2) .
-        " WHERE id='" . addslashes($this->mdo_id) . "'");
+        " WHERE c_id = $course_id AND id='" . addslashes($this->mdo_id) . "'");
 }
 
 
@@ -186,7 +188,8 @@ function mdo_add_breadcrump_nav()
 function mdobject($_course, $id)
 {
     global $ieee_dcmap_e, $ieee_dcmap_v;  // md_funcs
-
+    $course_id = api_get_course_int_id();
+    
     $this->mdo_course = $_course; $this->mdo_type = 'Link';
     $this->mdo_id = $id; $this->mdo_eid = $this->mdo_type . '.' . $id;
 
@@ -194,8 +197,7 @@ function mdobject($_course, $id)
 
     $link_table = Database::get_course_table(TABLE_LINK);
     if (($linkinfo = @Database::fetch_array(Database::query(
-            "SELECT url,title,description,category_id FROM $link_table WHERE id='" .
-            addslashes($id) . "'"))))
+            "SELECT url,title,description,category_id FROM $link_table WHERE c_id = $course_id AND id='" .intval($id) . "'"))))
     {
         $this->mdo_url =         $linkinfo['url'];
         $this->mdo_title =       $linkinfo['title'];
@@ -204,7 +206,7 @@ function mdobject($_course, $id)
 
         $linkcat_table = Database::get_course_table(TABLE_LINK_CATEGORY);
         if (($catinfo = @Database::fetch_array(Database::query(
-                "SELECT category_title FROM $linkcat_table WHERE id='" .
+                "SELECT category_title FROM $linkcat_table WHERE c_id = $course_id AND id='" .
                 addslashes($lci) . "'"))))
             $this->mdo_category_title =    $catinfo['category_title'];
     }

+ 1 - 0
main/mySpace/access_details.php

@@ -160,6 +160,7 @@ $(function() {
 </script>';
 
 //Changes END
+$interbreadcrumb[] = array ('url' => '#', 'name' => get_lang('AccessDetails'));
 
 Display :: display_header('');
 $main_user_info = api_get_user_info($user_id);

+ 4 - 4
main/mySpace/index.php

@@ -367,10 +367,10 @@ if (api_is_allowed_to_create_course() && $view == 'teacher') {
 		$table->set_additional_parameters($parameters);
 		$table -> set_header(0, get_lang('CourseTitle'), false, 'align="center"');
 		$table -> set_header(1, get_lang('NbStudents'), false);
-		$table -> set_header(2, get_lang('AvgTimeSpentInTheCourse').Display :: return_icon('info3.gif', get_lang('TimeOfActiveByTraining'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
-		$table -> set_header(3, get_lang('AvgStudentsProgress').Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
-		$table -> set_header(4, get_lang('AvgCourseScore').Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
-		$table -> set_header(5, get_lang('AvgExercisesScore').Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
+		$table -> set_header(2, get_lang('AvgTimeSpentInTheCourse').' '.Display :: return_icon('info3.gif', get_lang('TimeOfActiveByTraining'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
+		$table -> set_header(3, get_lang('AvgStudentsProgress').' '.Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
+		$table -> set_header(4, get_lang('AvgCourseScore').' '.Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
+		$table -> set_header(5, get_lang('AvgExercisesScore').' '.Display :: return_icon('info3.gif', get_lang('AvgAllUsersInAllCourses'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
 		$table -> set_header(6, get_lang('AvgMessages'), false);
 		$table -> set_header(7, get_lang('AvgAssignments'), false);
 		$table -> set_header(8, get_lang('Details'), false);

+ 9 - 9
main/mySpace/myStudents.php

@@ -511,11 +511,11 @@ if (!empty($student_id)) {
 						<td align="left"><?php echo  $time_spent_on_the_course ?></td>
 					</tr>
 					<tr>
-						<td align="right"><?php echo get_lang('Progress'); Display :: display_icon('info3.gif', get_lang('ScormAndLPProgressTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px'));?></td>
+						<td align="right"><?php echo get_lang('Progress').' '; Display :: display_icon('info3.gif', get_lang('ScormAndLPProgressTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px'));?></td>
 						<td align="left"><?php echo $avg_student_progress.'%' ?></td>
 					</tr>
 					<tr>
-						<td align="right"><?php echo get_lang('Score'); Display :: display_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px')); ?>
+						<td align="right"><?php echo get_lang('Score').' '; Display :: display_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px')); ?>
 						</td>
 						<td align="left"><?php if (is_numeric($avg_student_score)) { echo $avg_student_score.'%';} else { echo $avg_student_score ;}  ?></td>
 					</tr>
@@ -634,7 +634,7 @@ if (empty($_GET['details'])) {
     
     				$scoretotal_display = '0/0 (0%)';
     				if (!empty($scoretotal)) {
-    					$scoretotal_display =  round($scoretotal[0],2).'/'.round($scoretotal[1],2).'('.round(($scoretotal[0] / $scoretotal[1]) * 100,2) . ' %)';
+    					$scoretotal_display =  round($scoretotal[0],1).'/'.round($scoretotal[1],1).' ('.round(($scoretotal[0] / $scoretotal[1]) * 100,2) . ' %)';
     				}
     	 
     				$progress = Tracking::get_avg_student_progress($info_user['user_id'], $course_code, null, $session_id);
@@ -712,11 +712,11 @@ if (empty($_GET['details'])) {
         <table class="data_table">
             <tr>
                 <th><?php echo get_lang('Learnpaths');?></th>
-                <th><?php echo get_lang('Time'); Display :: display_icon('info3.gif', get_lang('TotalTimeByCourse'), array ('align' => 'absmiddle', 'hspace' => '3px')); ?></th>
-                <th><?php echo get_lang('AverageScore'); Display :: display_icon('info3.gif', get_lang('AverageIsCalculatedBasedInAllAttempts'), array ( 'align' => 'absmiddle', 'hspace' => '3px')); ?></th>
-                <th><?php echo get_lang('LatestAttemptAverageScore'); Display :: display_icon('info3.gif', get_lang('AverageIsCalculatedBasedInTheLatestAttempts'), array ( 'align' => 'absmiddle', 'hspace' => '3px')); ?></th>
-                <th><?php echo get_lang('Progress'); Display :: display_icon('info3.gif', get_lang('LPProgressScore'), array ('align' => 'absmiddle','hspace' => '3px')); ?></th>
-                <th><?php echo get_lang('LastConnexion'); Display :: display_icon('info3.gif', get_lang('LastTimeTheCourseWasUsed'), array ('align' => 'absmiddle','hspace' => '3px')); ?></th>
+                <th><?php echo get_lang('Time').' '; Display :: display_icon('info3.gif', get_lang('TotalTimeByCourse'), array ('align' => 'absmiddle', 'hspace' => '3px')); ?></th>
+                <th><?php echo get_lang('AverageScore').' '; Display :: display_icon('info3.gif', get_lang('AverageIsCalculatedBasedInAllAttempts'), array ( 'align' => 'absmiddle', 'hspace' => '3px')); ?></th>
+                <th><?php echo get_lang('LatestAttemptAverageScore').' '; Display :: display_icon('info3.gif', get_lang('AverageIsCalculatedBasedInTheLatestAttempts'), array ( 'align' => 'absmiddle', 'hspace' => '3px')); ?></th>
+                <th><?php echo get_lang('Progress').' '; Display :: display_icon('info3.gif', get_lang('LPProgressScore'), array ('align' => 'absmiddle','hspace' => '3px')); ?></th>
+                <th><?php echo get_lang('LastConnexion').' '; Display :: display_icon('info3.gif', get_lang('LastTimeTheCourseWasUsed'), array ('align' => 'absmiddle','hspace' => '3px')); ?></th>
                 <?php       
                     echo '<th>'.get_lang('Details').'</th>'; 
                     if (api_is_course_admin()) {
@@ -841,7 +841,7 @@ if (empty($_GET['details'])) {
 		<table class="data_table">
 			<tr>
 				<th><?php echo get_lang('Exercices'); ?></th>
-				<th><?php echo get_lang('AverageScore').Display :: return_icon('info3.gif', get_lang('AverageScore'), array('align' => 'absmiddle', 'hspace' => '3px')) ?></th>
+				<th><?php echo get_lang('AverageScore').' '.Display :: return_icon('info3.gif', get_lang('AverageScore'), array('align' => 'absmiddle', 'hspace' => '3px')) ?></th>
 				<th><?php echo get_lang('Attempts'); ?></th>
 				<th><?php echo get_lang('LatestAttempt'); ?></th>
 				<th><?php echo get_lang('AllAttempts'); ?></th>

+ 1 - 2
main/mySpace/myspace.lib.php

@@ -2,7 +2,6 @@
 /* For licensing terms, see /license.txt */
 require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
 require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
-require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
 class MySpace {
 
@@ -1346,7 +1345,7 @@ class MySpace {
 		// database table definition
 		$access_url_id = api_get_current_access_url_id();
 	 	$tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-		$main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
+		$main_user_table = Database::get_main_table(TABLE_MAIN_USER);
 
 		if ($_configuration['multiple_access_urls']) {
 			$condition_multi_url = ", $tbl_url_rel_user as url_user WHERE user.user_id=url_user.user_id AND access_url_id='$access_url_id'";

+ 3 - 0
main/mySpace/student.php

@@ -280,6 +280,9 @@ if (api_is_allowed_to_create_course() || api_is_drh()) {
 			$row[] = $string_date;
 
 			if ($export_csv) {
+			    
+			    $row[count($row) - 1] = strip_tags($row[count($row) - 1]);
+                $row[count($row) - 2] = strip_tags($row[count($row) - 2]);
 				$csv_content[] = $row;
 			}
 

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

@@ -857,7 +857,7 @@ class learnpath {
         // Delete lp item id.
         foreach ($this->items as $id => $dummy) {
             //$this->items[$id]->delete();
-            $sql_del_view = "DELETE FROM $lp_item_view WHERE lp_item_id = '" . $id . "'";
+            $sql_del_view = "DELETE FROM $lp_item_view WHERE c_id = $course_id AND lp_item_id = '" . $id . "'";
             $res_del_item_view = Database::query($sql_del_view);
         }
 
@@ -3424,7 +3424,7 @@ class learnpath {
             while ($row = Database :: fetch_array($res)) {
                 if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
                     $need_fix = true;
-                    $sql_u = "UPDATE $lp_table SET display_order = $i WHERE id = " . $row['id'];
+                    $sql_u = "UPDATE $lp_table SET display_order = $i WHERE c_id = ".$course_id." AND id = " . $row['id'];
                     $res_u = Database::query($sql_u);
                 }
                 $row['display_order'] = $i;
@@ -3451,7 +3451,7 @@ class learnpath {
     public function move_down($lp_id) {
         $course_id = api_get_course_int_id(); 
         $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
-        $sql = "SELECT * FROM $lp_table ORDER BY display_order";
+        $sql = "SELECT * FROM $lp_table WHERE c_id = ".$course_id." ORDER BY display_order";
         $res = Database::query($sql);
         if ($res === false)
             return false;

+ 56 - 44
main/newscorm/lp_list.php

@@ -90,9 +90,9 @@ if ($is_allowed_to_edit) {
     }
 
     echo '<div class="actions">';
-    echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_lp">'.Display::return_icon('new_learnpath.png', get_lang('_add_learnpath'),'','32').'</a>' .
+    echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_lp">'.Display::return_icon('add.png', get_lang('_add_learnpath'),'','32').'</a>' .
         str_repeat('&nbsp;', 3).
-        '<a href="../upload/index.php?'.api_get_cidreq().'&curdirpath=/&tool='.TOOL_LEARNPATH.'">'.Display::return_icon('import_scorm.png', get_lang('UploadScorm'),'','32').'</a>';
+        '<a href="../upload/index.php?'.api_get_cidreq().'&curdirpath=/&tool='.TOOL_LEARNPATH.'">'.Display::return_icon('import.png', get_lang('UploadScorm'),'','32').'</a>';
     if (api_get_setting('service_ppt2lp', 'active') == 'true') {
         echo str_repeat('&nbsp;', 3).'<a href="../upload/upload_ppt.php?'.api_get_cidreq().'&curdirpath=/&tool='.TOOL_LEARNPATH.'">
 		'.Display::return_icon('import_powerpoint.png', get_lang('PowerPointConvert'),'','32').'</a>';
@@ -101,49 +101,52 @@ if ($is_allowed_to_edit) {
     echo '</div>';
 }
 
-echo '<table width="100%" border="0" cellspacing="2" class="data_table">';
-$is_allowed_to_edit ? $colspan = 9 : $colspan = 3;
 
-if (!empty($curDirPath)) {
-    if (substr($curDirPath, 1, 1) == '/') {
-        $tmpcurDirPath=substr($curDirPath,1,strlen($curDirPath));
-    } else {
-        $tmpcurDirPath = $curDirPath;
-    }
-    ?>
-    <!-- current dir name -->
-    <tr>
-        <td colspan="<?php echo $colspan; ?>" align="left" bgcolor="#4171B5">
-            <img src="../img/opendir.gif" align="absbottom" vspace="2" hspace="3" alt="open_dir" />
-            <font color="#ffffff"><b><?php echo $tmpcurDirPath; ?></b></font>
-        </td>
-    </tr>
-    <?php
-}
-
-/* CURRENT DIRECTORY */
-
-echo '<tr>';
-       
-if ($is_allowed_to_edit) {
-    echo '<th width="50%">'.get_lang('Title').'</th>';
-    echo '<th>'.get_lang('PublicationDate').'</th>';
-    echo '<th>'.get_lang('ExpirationDate').'</th>';
-    echo '<th>'.get_lang('Progress')."</th>";
-    echo '<th width="240px">'.get_lang('AuthoringOptions')."</th>";
-} else {
-    echo '<th width="50%">'.get_lang('Title').'</th>';
-    echo '<th>'.get_lang('Progress')."</th>";
-    echo '<th>'.get_lang('Actions')."</th>";
-}
-echo '</tr>';
 
 /* DISPLAY SCORM LIST */
 $list       = new LearnpathList(api_get_user_id());
 $flat_list  = $list->get_flat_list();
 
-//var_dump($flat_list);
-if (is_array($flat_list)) {
+
+if (!empty($flat_list)) {
+    
+    echo '<table width="100%" border="0" cellspacing="2" class="data_table">';
+    $is_allowed_to_edit ? $colspan = 9 : $colspan = 3;
+
+    if (!empty($curDirPath)) {
+        if (substr($curDirPath, 1, 1) == '/') {
+            $tmpcurDirPath=substr($curDirPath,1,strlen($curDirPath));
+        } else {
+            $tmpcurDirPath = $curDirPath;
+        }
+        ?>
+        <!-- current dir name -->
+        <tr>
+            <td colspan="<?php echo $colspan; ?>" align="left" bgcolor="#4171B5">
+                <img src="../img/opendir.gif" align="absbottom" vspace="2" hspace="3" alt="open_dir" />
+                <font color="#ffffff"><b><?php echo $tmpcurDirPath; ?></b></font>
+            </td>
+        </tr>
+        <?php
+    }
+    
+    /* CURRENT DIRECTORY */
+    
+    echo '<tr>';
+           
+    if ($is_allowed_to_edit) {
+        echo '<th width="50%">'.get_lang('Title').'</th>';
+        echo '<th>'.get_lang('PublicationDate').'</th>';
+        echo '<th>'.get_lang('ExpirationDate').'</th>';
+        echo '<th>'.get_lang('Progress')."</th>";
+        echo '<th width="240px">'.get_lang('AuthoringOptions')."</th>";
+    } else {
+        echo '<th width="50%">'.get_lang('Title').'</th>';
+        echo '<th>'.get_lang('Progress')."</th>";
+        echo '<th>'.get_lang('Actions')."</th>";
+    }
+    echo '</tr>';
+
     $test_mode      = api_get_setting('server_type');
     $max            = count($flat_list);
     $counter        = 0;
@@ -502,8 +505,17 @@ if (is_array($flat_list)) {
         $current ++; //counter for number of elements treated
     } // end foreach ($flat_list)
     // TODO: Erint some user-friendly message if counter is still = 0 to tell nothing can be displayd yet.
-} // end if ( is_array($flat_list)
-echo "</table>";
-echo "<br /><br />";
-/* FOOTER */
-Display::display_footer();
+    echo "</table>";
+} else {
+    if ($is_allowed_to_edit) {
+        echo '<div id="no-data-view">';
+        echo '<h2>'.get_lang('LearningPaths').'</h2>';
+        echo Display::return_icon('scorms.png', '', array(), 64);
+        echo '<div class="controls">';    
+        echo Display::url(get_lang('_add_learnpath'), api_get_self().'?'.api_get_cidreq().'&action=add_lp' , array('class' => 'a_button white'));
+        echo '</div>';
+        echo '</div>'; 
+    }
+}
+
+Display::display_footer();

+ 141 - 115
main/newscorm/resourcelinker.inc.php

@@ -75,10 +75,15 @@ function show_documents($folder) {
     } else {
         $visibility = "ip.visibility='1'";
     }
+    
+    $course_id = api_get_course_int_id();
 
     $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $document_table = Database::get_course_table(TABLE_DOCUMENT);
-    $sql = "SELECT * from $document_table docs , $item_property_table ip WHERE docs.id=ip.ref AND ip.tool = '".TOOL_DOCUMENT."' AND $visibility AND ip.to_group_id = 0 AND ip.to_user_id IS NULL  ORDER BY docs.path ASC";
+    $sql = "SELECT * from $document_table docs , $item_property_table ip 
+            WHERE   docs.c_id = $course_id AND 
+                    ip.c_id = $course_id AND 
+                    docs.id=ip.ref AND ip.tool = '".TOOL_DOCUMENT."' AND $visibility AND ip.to_group_id = 0 AND ip.to_user_id IS NULL  ORDER BY docs.path ASC";
     $result = Database::query($sql);
     while ($row = Database::fetch_array($result)) {
         if (!$folder) {
@@ -166,10 +171,8 @@ function show_documents($folder) {
 function file_or_folder($filefolder) {
     global $_course;
     global $baseServDir;
-
     $courseDir   = $_course['path'].'/document';
     $baseWorkDir = api_get_path(SYS_COURSE_PATH).$courseDir;
-
     return (is_dir($baseWorkDir.$filefolder) ? 1 : 0);
 }
 
@@ -211,6 +214,7 @@ function store_resources($source_type, $source_id) {
  */
 function display_addedresource_link($type, $id, $style = '') {
     global $_course;
+    $course_id = api_get_course_int_id();
 
     // Styling the link of the added resource.
     if ($style != '') {
@@ -219,58 +223,60 @@ function display_addedresource_link($type, $id, $style = '') {
 
     switch ($type) {
         case 'Agenda':
-            $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE id=$id");
+            $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
+            $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
             echo '<img src="../img/agenda.gif" align="middle" /> <a href="../calendar/agenda.php"'.$styling.'>'.$myrow['title']."</a><br />\n";
             break;
         case 'Ad_Valvas':
-            $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $tbl_announcement WHERE id=$id");
+            $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
+            $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
             echo '<img src="../img/valves.gif" align="middle" /> <a href="../announcements/announcements.php"'.$styling.'>'.$myrow['title']."</a><br />\n";
             break;
         case 'Link':
-            $TABLETOOLLINK = Database::get_course_table(TABLE_LINK,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE id=$id");
+            $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
+            $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
             echo '<img src="../img/links.gif" align="middle" /> <a href="#" onclick="javascript:window.open(\'../link/link_goto.php?link_id='.$myrow['id'].'&amp;link_url='.urlencode($myrow['url'])."','MyWindow','width=500,height=400,top='+((screen.height-400)/2)+',left='+((screen.width-500)/2)+',scrollbars=1,resizable=1,menubar=1'); return false;\"".$styling.'>'.$myrow['title']."</a><br />\n";
             break;
         case 'Exercise':
-            $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE id=$id");
+            $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
+            $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
             echo '<img src="../img/quiz.gif" align="middle" /> <a href="../exercice/exercise_submit.php?exerciseId='.$myrow['id'].'"'.$styling.'>'.$myrow['title']."</a><br />\n";
             break;
-        case 'Forum':
-            //incredibly deprecated (2011-02-09)
-            $TBL_FORUMS = $_course['dbNameGlu'].'bb_forums';
-            $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE forum_id=$id");
+        case 'Forum':           
+            $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
+            $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id=$id");
             $myrow = Database::fetch_array($result);
             echo '<img src="../img/forum.gif" align="middle" /> <a href="../phpbb/viewforum.php?forum='.$myrow['forum_id'].'&amp;md5='.$myrow['md5'].'"'.$styling.'>'.$myrow['forum_name']."</a><br />\n";
             break;
         case 'Thread':  //=topics
+            //@deprecated bb_posts, bb_posts_text, bb_forums
+            /*
             $tbl_posts		= $_course['dbNameGlu'].'bb_posts';
             $tbl_posts_text	= $_course['dbNameGlu'].'bb_posts_text';
             $TBL_FORUMS		= $_course['dbNameGlu'].'bb_forums';
             $result = Database::query("SELECT * FROM $tbl_posts posts, $TBL_FORUMS forum WHERE forum.forum_id=posts.forum_id and post_id=$id");
             $myrow = Database::fetch_array($result);
             // grabbing the title of the post
-            $sql_title = "SELECT * FROM $tbl_posts_text WHERE post_id=".$myrow["post_id"];
+            $sql_title = "SELECT * FROM $tbl_posts_text WHERE c_id = $course_id AND post_id=".$myrow["post_id"];
             $result_title = Database::query($sql_title);
             $myrow_title = Database::fetch_array($result_title);
             echo '<img src="../img/forum.gif" align="middle" /> <a href="../phpbb/viewtopic.php?topic='.$myrow['topic_id'].'&amp;forum='.$myrow['forum_id'].'&amp;md5='.$myrow['md5'].'"'.$styling.'>'.$myrow_title['post_title']."</a><br />\n";
+             */
             break;
         case 'Post':
-            $tbl_post = Database::get_course_table(TABLE_FORUM_POST,$_course['dbName']);
-            $sql = "SELECT * FROM $tbl_post p WHERE post_id = $id";
+            $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
+            $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND post_id = $id";
             $result = Database::query($sql);
             $post = Database::fetch_object($result);
             echo '<img src="../img/forum.gif" align="middle" /> <a href="../phpbb/viewtopic.php?topic='.$post->topic_id.'&amp;forum='.$post->forum_id.'"'.$styling.'>'.$post->post_title."</a><br />\n";
             break;
         case 'Document':
-            $dbTable = Database::get_course_table(TABLE_DOCUMENT,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $dbTable WHERE id=$id");
+            $dbTable = Database::get_course_table(TABLE_DOCUMENT);
+            $result = Database::query("SELECT * FROM $dbTable WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
             $pathname = explode('/',$myrow['path']); // Making a correct name for the link.
             $last = count($pathname) - 1;  // Making a correct name for the link.
@@ -319,8 +325,11 @@ function display_addedresource_link($type, $id, $style = '') {
 function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_path, $builder, $icon, $level = 0) {
     global $_course, $learnpath_id, $tbl_learnpath_item, $items;
     global $curDirPath, $_configuration, $enableDocumentParsing, $_course, $_user, $_cid;
+    
+    $course_id = api_get_course_int_id();
+    
 
-    $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM,$_course['dbName']);
+    $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
     $hyperlink_target_parameter = ''; //or e.g. 'target="_blank"'
 
     $length = ((($builder == 'builder') && ($icon == 'nolink')) ? 65 : 32);
@@ -333,11 +342,11 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
     switch ($type) {
         case TOOL_CALENDAR_EVENT:
         case 'Agenda':
-            $TABLEAGENDA 		= Database::get_course_table(TABLE_AGENDA,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE id=$id");
+            $TABLEAGENDA 		= Database::get_course_table(TABLE_AGENDA);
+            $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
 
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
             $result = Database::query($sql);	$row = Database::fetch_array($result);
             if ($row['title'] != '') { $myrow['title'] = $row['title']; }
             $desc = $row['description'];
@@ -375,13 +384,16 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
 
         case TOOL_ANNOUNCEMENT:
         case 'Ad_Valvas':
-            $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $tbl_announcement WHERE id=$id");
+            $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
+            $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
 
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
-            $result = Database::query($sql);	$row = Database::fetch_array($result);
-            if ($row['title'] != '') { $myrow['content'] = $row['title']; }
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
+            $result = Database::query($sql);	
+            $row = Database::fetch_array($result);
+            if ($row['title'] != '') {
+                 $myrow['content'] = $row['title']; 
+            }
             $desc = $row['description'];
             $ann_id = $row['item_id'];
             echo str_repeat("&nbsp;&gt;", $level);
@@ -427,12 +439,13 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
 
         case TOOL_LINK:
         case 'Link':
-            $TABLETOOLLINK	= Database::get_course_table(TABLE_LINK,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE id=$id");
+            $TABLETOOLLINK	= Database::get_course_table(TABLE_LINK);
+            $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
 
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
-            $result = Database::query($sql);	$row = Database::fetch_array($result);
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
+            $result = Database::query($sql);	
+            $row = Database::fetch_array($result);
             if ($row['title'] != '') { $myrow['title'] = $row['title']; }
             $desc=$row['description'];
             echo str_repeat("&nbsp;&gt;", $level);
@@ -476,8 +489,8 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
 
         case TOOL_QUIZ:
         case 'Exercise':
-            $TBL_EXERCICES  = Database::get_course_table(TABLE_QUIZ_TEST,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE id=$id");
+            $TBL_EXERCICES  = Database::get_course_table(TABLE_QUIZ_TEST);
+            $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
 
             if ($builder == 'builder') { $origin = 'builder'; }
@@ -525,9 +538,9 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
 
         case 'hotpotatoes':
         case 'HotPotatoes':
-            $TBL_DOCUMENT  = Database::get_course_table(TABLE_DOCUMENT,$_course['dbName']);
+            $TBL_DOCUMENT  = Database::get_course_table(TABLE_DOCUMENT);
             $documentPath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
-            $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE id=$id");
+            $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
             $path = $myrow['path'];
             $name = GetQuizName($path, $documentPath);
@@ -576,11 +589,11 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
 
         case TOOL_FORUM:
         case 'Forum':
-            $TBL_FORUMS = Database::get_course_table(TABLE_FORUM,$_course['database']);
-            $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE forum_id=$id");
+            $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
+            $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id=$id");
             $myrow = Database::fetch_array($result);
 
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
             $result = Database::query($sql);	$row = Database::fetch_array($result);
             if ($row['title'] != '') { $myrow["forum_name"] = $row['title']; }
             $desc = $row['description'];
@@ -619,8 +632,8 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
 
         case TOOL_THREAD:
         case 'Thread':  //forum post
-            $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD, $_course['database']);
-            $sql = "SELECT * FROM $tbl_topics where topic_id=$id";
+            $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
+            $sql = "SELECT * FROM $tbl_topics where c_id = $course_id AND topic_id=$id";
             $result = Database::query($sql);
             $myrow = Database::fetch_array($result);
 
@@ -663,14 +676,15 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
         case TOOL_POST:
         case 'Post':
         //deprecated
-            $tbl_posts = Database::get_course_table(TABLE_FORUM_POST,$_course['dbName']);
-            $TBL_FORUMS = Database::get_course_table(TABLE_FORUM,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $tbl_posts where post_id=$id");
+            $tbl_posts = Database::get_course_table(TABLE_FORUM_POST);
+            $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
+            $result = Database::query("SELECT * FROM $tbl_posts where c_id = $course_id AND post_id=$id");
             $myrow = Database::fetch_array($result);
             // Grabbing the title of the post.
             
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
-            $result = Database::query($sql);	$row=Database::fetch_array($result);
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
+            $result = Database::query($sql);	
+            $row=Database::fetch_array($result);
             if ($row['title'] != '') { $myrow['post_title'] = $row['title']; }
             $desc = $row['description'];
             echo str_repeat("&nbsp;&gt;", $level);
@@ -714,8 +728,8 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
 
         case TOOL_DOCUMENT:
         case 'Document':
-            $dbTable = Database::get_course_table(TABLE_DOCUMENT,$_course['dbName']);
-            $mysql = "SELECT * FROM $dbTable WHERE id=$id";
+            $dbTable = Database::get_course_table(TABLE_DOCUMENT);
+            $mysql = "SELECT * FROM $dbTable WHERE c_id = $course_id AND id=$id";
             //error_log('New LP - Querying document table: '.$mysql,0);
             $result = Database::query($mysql);
             $myrow = Database::fetch_array($result);
@@ -776,7 +790,7 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
         case 'assignments':
         case 'Assignments':
             $name = get_lang('Assignments');
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
             $result = Database::query($sql);
             $row = Database::fetch_array($result);
             if ($row['title'] != '') { $name=$row['title']; }
@@ -817,7 +831,7 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
         case TOOL_DROPBOX:
         case 'Dropbox':
             $name = get_lang('Dropbox');
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
             $result = Database::query($sql);
             $row = Database::fetch_array($result);
             if ($row['title'] != '') { $name = $row['title']; }
@@ -856,7 +870,7 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
         case 'introduction_text':
         case 'Introduction_text':
             $name = get_lang('IntroductionText');
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
             $result = Database::query($sql);	$row = Database::fetch_array($result);
             if ($row['title'] != '') { $name = $row['title']; }
             $desc = $row['description'];
@@ -896,7 +910,7 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
         case TOOL_COURSE_DESCRIPTION:
         case 'Course_description':
             $name = get_lang('CourseDescription');
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
             $result = Database::query($sql);	$row = Database::fetch_array($result);
             if ($row['title'] != '') { $name = $row['title']; }
             $desc = $row['description'];
@@ -935,8 +949,9 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
         case TOOL_GROUP:
         case 'Groups':
             $name = get_lang('Groups');
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
-            $result = Database::query($sql);	$row = Database::fetch_array($result);
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
+            $result = Database::query($sql);	
+            $row = Database::fetch_array($result);
             if ($row['title'] != '') { $name=$row['title']; }
             $desc = $row['description'];
             echo str_repeat("&nbsp;&gt;", $level);
@@ -973,8 +988,9 @@ function display_addedresource_link_in_learnpath($type, $id, $completed, $id_in_
         case TOOL_USER:
         case 'Users':
             $name = get_lang('Users');
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
-            $result = Database::query($sql);	$row = Database::fetch_array($result);
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
+            $result = Database::query($sql);	
+            $row = Database::fetch_array($result);
             if ($row['title'] != '') { $name = $row['title']; }
             $desc = $row['description'];
             echo str_repeat("&nbsp;&gt;", $level);
@@ -1025,6 +1041,7 @@ function get_addedresource_link_in_learnpath($type, $id, $id_in_path) {
     global $curDirPath, $_configuration, $enableDocumentParsing, $_user, $_cid;
 
     $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
+    $course_id = api_get_course_int_id();
     $hyperlink_target_parameter = ''; // or e.g. target='_blank'
     $builder = 'player';
     $origin = 'learnpath';
@@ -1036,11 +1053,11 @@ function get_addedresource_link_in_learnpath($type, $id, $id_in_path) {
 
     switch ($type) {
         case 'Agenda':
-            $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE id=$id");
+            $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
+            $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
 
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
             $result = Database::query($sql);	$row = Database::fetch_array($result);
             if ($row['title'] != '') { $myrow['title'] = $row['title']; }
             $desc = $row['description'];
@@ -1055,7 +1072,7 @@ function get_addedresource_link_in_learnpath($type, $id, $id_in_path) {
 
         case 'Ad_Valvas':
             $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
-            $result = Database::query("SELECT * FROM $tbl_announcement WHERE id=$id");
+            $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
 
             if ($builder != 'builder') {
@@ -1066,12 +1083,13 @@ function get_addedresource_link_in_learnpath($type, $id, $id_in_path) {
             break;
 
         case 'Link':
-            $TABLETOOLLINK	= Database::get_course_table(TABLE_LINK,$_course['dbName']);
-            $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE id=$id");
+            $TABLETOOLLINK	= Database::get_course_table(TABLE_LINK);
+            $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
 
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
-            $result = Database::query($sql);	$row = Database::fetch_array($result);
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
+            $result = Database::query($sql);	
+            $row = Database::fetch_array($result);
 
             $thelink = $myrow['url'];
             if ($builder != 'builder') {
@@ -1089,7 +1107,7 @@ function get_addedresource_link_in_learnpath($type, $id, $id_in_path) {
             if ($builder == 'builder') { $origin = 'builder'; }
               // This is needed for the exercise_submit.php can delete the session info about tests.
 
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
             $result = Database::query($sql);	$row = Database::fetch_array($result);
             if ($row['title'] != '') { $myrow['title'] = $row['title']; }
 
@@ -1121,13 +1139,13 @@ function get_addedresource_link_in_learnpath($type, $id, $id_in_path) {
 
         case 'Forum':
         //deprecated
-            $TBL_FORUMS = Database::get_course_table(TABLE_FORUM,$_course['dbName']);  // TODO: This is the old table name, it should be corrected.
-            $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE forum_id=$id");
+            $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);  // TODO: This is the old table name, it should be corrected.
+            $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id=$id");
             $myrow = Database::fetch_array($result);
 
             if ($builder == 'builder') { $origin = 'builder'; }
 
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
             $result = Database::query($sql);	$row = Database::fetch_array($result);
             if ($row['title'] != '') { $myrow['forum_name'] = $row['title']; }
 
@@ -1143,14 +1161,14 @@ function get_addedresource_link_in_learnpath($type, $id, $id_in_path) {
 
         case 'Thread':  //forum post
         //deprecated
-            $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD,$_course['dbName']);
-            $tbl_posts = Database::get_course_table(TABLE_FORUM_POST,$_course['dbName']);
-            $TBL_FORUMS = Database::get_course_table(TABLE_FORUM,$_course['dbName']);
-            $sql = "SELECT * FROM $tbl_topics where topic_id=$id";
+            $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
+            $tbl_posts = Database::get_course_table(TABLE_FORUM_POST);
+            $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
+            $sql = "SELECT * FROM $tbl_topics where c_id = $course_id AND topic_id=$id";
             $result = Database::query($sql);
             $myrow = Database::fetch_array($result);
 
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
             $result = Database::query($sql);	$row = Database::fetch_array($result);
 
             if ($builder != 'builder') {
@@ -1162,14 +1180,15 @@ function get_addedresource_link_in_learnpath($type, $id, $id_in_path) {
 
         case 'Post':
         //deprecated
-            $tbl_posts = Database::get_course_table(TABLE_FORUM_POST,$_course['dbName']);
-            $TBL_FORUMS = $_course['dbNameGlu']."bb_forums";
-            $result = Database::query("SELECT * FROM $tbl_posts where post_id=$id");
+            $tbl_posts = Database::get_course_table(TABLE_FORUM_POST);
+            
+            $result = Database::query("SELECT * FROM $tbl_posts where c_id = $course_id AND post_id=$id");
             $myrow = Database::fetch_array($result);
             // Grabbing the title of the post.
 
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
-            $result = Database::query($sql);	$row = Database::fetch_array($result);
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
+            $result = Database::query($sql);	
+            $row = Database::fetch_array($result);
             if ($row['title'] != '') { $myrow['post_title'] = $row['title']; }
             $desc = $row['description'];
             //$link .= str_repeat("&nbsp;&gt;", $level);
@@ -1187,7 +1206,7 @@ function get_addedresource_link_in_learnpath($type, $id, $id_in_path) {
             break;
 
         case 'Document':
-            $dbTable = Database::get_course_table(TABLE_DOCUMENT,$_course['dbName']);
+            $dbTable = Database::get_course_table(TABLE_DOCUMENT);
             $result = Database::query("SELECT * FROM $dbTable WHERE id=$id");
             $myrow = Database::fetch_array($result);
 
@@ -1195,8 +1214,9 @@ function get_addedresource_link_in_learnpath($type, $id, $id_in_path) {
             $last = count($pathname) - 1;  // Making a correct name for the link.
             $filename = $pathname[$last];  // Making a correct name for the link.
 
-            $sql = "select * from $tbl_lp_item where id=$id_in_path";
-            $result = Database::query($sql);	$row = Database::fetch_array($result);
+            $sql = "select * from $tbl_lp_item where c_id = $course_id AND id=$id_in_path";
+            $result = Database::query($sql);	
+            $row = Database::fetch_array($result);
 
             if ($builder != 'builder') {
                 $link .= api_get_self()."?action=closelesson&source_forum=".$_GET['source_forum']."&how=complete&id_in_path=$id_in_path&learnpath_id=$learnpath_id&type=Document&origin=$origin&docurl=".$myrow["path"]."#$id_in_path";
@@ -1299,8 +1319,9 @@ function delete_one_added_resource($source_type, $source_id, $resource_type, $re
  */
 function delete_added_resource($type, $id) {
     global $_course;
-    $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES,$_course['dbName']);
-    $sql = "DELETE FROM $TABLERESOURCE WHERE source_type='$type' and source_id='$id'";
+    $course_id = api_get_course_int_id();
+    $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES);
+    $sql = "DELETE FROM $TABLERESOURCE WHERE c_id = $course_id AND source_type='$type' and source_id='$id'";
     Database::query($sql);
 }
 
@@ -1310,8 +1331,9 @@ function delete_added_resource($type, $id) {
  */
 function delete_all_resources_type($type) {
   global $_course;
-  $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES,$_course['dbName']);
-  $sql = "DELETE FROM $TABLERESOURCE WHERE source_type='$type'";
+  $course_id = api_get_course_int_id();
+  $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES);
+  $sql = "DELETE FROM $TABLERESOURCE WHERE c_id = $course_id AND source_type='$type'";
   Database::query($sql);
 }
 
@@ -1320,8 +1342,9 @@ function delete_all_resources_type($type) {
  */
 function check_added_resources($type, $id) {
     global $_course, $origin;
-    $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES,$_course['dbName']);
-    $sql = "SELECT * FROM $TABLERESOURCE WHERE source_type='$type' and source_id='$id'";
+    $course_id = api_get_course_int_id();
+    $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES);
+    $sql = "SELECT * FROM $TABLERESOURCE WHERE c_id = $course_id AND source_type='$type' and source_id='$id'";
     $result = Database::query($sql);
     $number_added = Database::num_rows($result);
     if ($number_added != 0)
@@ -1336,9 +1359,10 @@ function check_added_resources($type, $id) {
  */
 function edit_added_resources($type, $id) {
     global $_course;
-    $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES,$_course['dbName']);
+    $course_id = api_get_course_int_id();
+    $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES);
 
-    $sql="SELECT * FROM $TABLERESOURCE WHERE source_type='$type' and source_id=$id";
+    $sql="SELECT * FROM $TABLERESOURCE WHERE c_id = $course_id AND source_type='$type' and source_id=$id";
     $result=Database::query($sql);
     while ($row=Database::fetch_array($result))
     {
@@ -1356,9 +1380,10 @@ function edit_added_resources($type, $id) {
  */
 function update_added_resources($type, $id) {
     global $_course;
-    $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES,$_course['dbName']);
+    $course_id = api_get_course_int_id();
+    $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES);
     // delete all the added resources for this item in the database;
-    $sql="DELETE FROM $TABLERESOURCE WHERE source_type='$type' AND source_id='$id'";
+    $sql="DELETE FROM $TABLERESOURCE WHERE c_id = $course_id AND source_type='$type' AND source_id='$id'";
     //echo $sql;
     Database::query($sql);
 
@@ -1373,13 +1398,14 @@ function update_added_resources($type, $id) {
  * this function is to display the resources that were added to a specific item
  */
 function display_added_resources($type, $id, $style = '') {
+    $course_id = api_get_course_int_id();
     // The array containing the icons
     $arr_icons = array('Agenda'=>'../img/agenda.gif', 'Ad Valvas'=>'../img/valves.gif', 'Link'=>'../img/links.gif', 'Exercise'=>'../img/quiz.gif' );
 
     global $_course, $origin;
-    $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES,$_course['dbName']);
+    $TABLERESOURCE = Database::get_course_table(TABLE_LINKED_RESOURCES);
 
-    $sql = "SELECT * FROM $TABLERESOURCE WHERE source_type='$type' and source_id='$id'";
+    $sql = "SELECT * FROM $TABLERESOURCE WHERE c_id = $course_id AND source_type='$type' and source_id='$id'";
     $result = Database::query($sql);
     while ($row=Database::fetch_array($result)) {
         if ($origin != 'learnpath') {
@@ -1482,8 +1508,9 @@ function showorhide_addresourcelink($type, $id) {
  * @todo use the constants for the type definitions.
  */
 function rl_get_html_resource_link($course_code, $type, $id, $style='', $new_window = true) {
-    //$_course = Database::get_course_info($course_code);
     $_course = Database::get_course_info($course_code);
+    
+    $course_id = api_get_course_int_id();
 
     // Styling the link of the added resource
     if ($style != '') $styling = ' class="'.$style.'"';
@@ -1493,57 +1520,57 @@ function rl_get_html_resource_link($course_code, $type, $id, $style='', $new_win
 
     switch ($type) {
         case TOOL_CALENDAR_EVENT:
-            $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA,$_course['database']);
-            $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE id=$id");
+            $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
+            $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
             $output = '<img src="../img/agenda.gif" align="middle" /> <a href="../calendar/agenda.php"'.$styling.' '.$target.'>'.$myrow['title']."</a><br />\n";
             break;
         case TOOL_ANNOUNCEMENT:
-            $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT,$_course['database']);
-            $result = Database::query("SELECT * FROM $tbl_announcement WHERE id=$id");
+            $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
+            $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
             $output = '<img src="../img/valves.gif" align="middle" /> <a href="../announcements/announcements.php"'.$styling.' '.$target.'>'.$myrow['title']."</a><br />\n";
             break;
         case TOOL_LINK:
             //doesn't take $target into account
-            $TABLETOOLLINK = Database::get_course_table(TABLE_LINK,$_course['database']);
-            $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE id=$id");
+            $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
+            $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
             $output = '<img src="../img/links.gif" align="middle" /> <a href="#" onclick="javascript:window.open(\'../link/link_goto.php?link_id='.$myrow['id'].'&amp;link_url='.urlencode($myrow['url'])."','MyWindow','width=500,height=400,top='+((screen.height-400)/2)+',left='+((screen.width-500)/2)+',scrollbars=1,resizable=1,menubar=1'); return false;\"".$styling.'>'.$myrow['title']."</a><br />\n";
             break;
         case TOOL_QUIZ:
-            $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST,$_course['database']);
-            $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE id=$id");
+            $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
+            $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
             $output = '<img src="../img/quiz.gif" align="middle" /> <a href="../exercice/exercise_submit.php?exerciseId='.$myrow['id'].'"'.$styling.' '.$target.'>'.$myrow['title']."</a><br />\n";
             break;
         case TOOL_FORUM:
-            $TBL_FORUMS = Database::get_course_table(TABLE_FORUM,$_course['database']);
-            $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE forum_id=$id");
+            $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
+            $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id=$id");
             $myrow = Database::fetch_array($result);
             $output = '<img src="../img/forum.gif" align="middle" /> <a href="../phpbb/viewforum.php?forum='.$myrow['forum_id'].'&md5='.$myrow['md5'].'"'.$styling.' '.$target.'>'.$myrow['forum_name']."</a><br />\n";
             break;
         case TOOL_THREAD:  //=topics
-            //$tbl_forum 		= Database::get_course_table(TABLE_FORUM,$_course['database']);
-            //$tbl_thread 	= Database::get_course_table(TABLE_FORUM_THREAD,$_course['database']);
-            $tbl_post 		= Database::get_course_table(TABLE_FORUM_POST,$_course['database']);
+            //$tbl_forum 		= Database::get_course_table(TABLE_FORUM);
+            //$tbl_thread 	= Database::get_course_table(TABLE_FORUM_THREAD);
+            $tbl_post 		= Database::get_course_table(TABLE_FORUM_POST);
             // grabbing the title of the post
-            $sql_title = "SELECT * FROM $tbl_post WHERE post_id=".$id;
+            $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
             $result_title = Database::query($sql_title);
             $myrow_title = Database::fetch_array($result_title);
             $output = '<img src="../img/forum.gif" align="middle" /> <a href="../phpbb/viewtopic.php?topic='.$myrow_title['thread_id'].'&forum='.$myrow_title['forum_id'].'" '.$styling.' '.$target.'>'.$myrow_title['post_title']."</a><br />\n";
             break;
         case TOOL_POST:
-            $tbl_post = Database::get_course_table(TABLE_FORUM_POST,$_course['database']);
+            $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
             //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
-            $sql = "SELECT * FROM $tbl_post p WHERE p.post_id = $id";
+            $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
             $result = Database::query($sql);
             $post = Database::fetch_array($result);
             $output = '<img src="../img/forum.gif" align="middle" /> <a href="../phpbb/viewtopic.php?topic='.$post['thread_id'].'&forum='.$post['forum_id'].'"'.$styling.' '.$target.'>'.$post['post_title']."</a><br />\n";
             break;
         case TOOL_DOCUMENT:
-            $tbl_doc = Database::get_course_table(TABLE_DOCUMENT,$_course['database']);
-            $result = Database::query("SELECT * FROM $tbl_doc WHERE id=$id");
+            $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
+            $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND id=$id");
             $myrow = Database::fetch_array($result);
             $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
             $last = count($pathname) - 1;  // Making a correct name for the link.
@@ -1810,6 +1837,5 @@ function rl_get_resource_name($course_code, $learnpath_id, $id_in_path) {
             break;
         */
     }
-
     return stripslashes($output);
-}
+}

+ 1 - 10
main/social/group_add.php

@@ -36,16 +36,7 @@ function text_longitud(){
       textarea = document.forms[0].description.value;
    }
 }
-</script>
-
-<style>
-div.row div.label {
-    width:15%;
-}
-div.row div.formw {
-    width:80%;
-}
-</style>';
+</script>';
 
 $table_message = Database::get_main_table(TABLE_MESSAGE);
 

+ 1 - 10
main/social/group_edit.php

@@ -36,16 +36,7 @@ function textarea_maxlength(){
       textarea = document.forms[0].description.value;
    }
 }
-</script>
-
-<style>
-div.row div.label {
-    width:15%;
-}
-div.row div.formw {
-    width:80%;
-}
-</style>';
+</script>';
 
 $group_id = isset($_GET['id']) ? intval($_GET['id']) : intval($_POST['id']);
 $tool_name = get_lang('GroupEdit');

+ 6 - 6
main/social/groups.php

@@ -274,9 +274,9 @@ if ($group_id != 0 ) {
 			$content = MessageManager::display_messages_for_group($group_id);
 			if ($is_group_member) {
     			if (empty($content)) {		
-    				$create_thread_link =  '<a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=400&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&action=add_message_group" class="a_button orange medium thickbox" title="'.get_lang('ComposeMessage').'">'.get_lang('YouShouldCreateATopic').'</a></li>';
+    				$create_thread_link =  '<a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=400&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&action=add_message_group" class="a_button white medium thickbox" title="'.get_lang('ComposeMessage').'">'.get_lang('YouShouldCreateATopic').'</a></li>';
     			} else {
-    			    $create_thread_link = '<a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=400&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&action=add_message_group" class="a_button orange medium thickbox" title="'.get_lang('ComposeMessage').'">'.get_lang('NewTopic').'</a>';
+    			    $create_thread_link = '<a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=400&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&action=add_message_group" class="a_button white medium thickbox" title="'.get_lang('ComposeMessage').'">'.get_lang('NewTopic').'</a>';
     			     			    
     			}			
 			}
@@ -478,11 +478,11 @@ if ($group_id != 0 ) {
 	        			$my_group_content = Display::return_sortable_grid('mygroups', array(), $grid_my_groups, array('hide_navigation'=>true, 'per_page' => 2), $query_vars, false, array(true, true, true,false));
 	        		}
         	   		if (api_get_setting('allow_students_to_create_groups_in_social') == 'true') {
-    	        	    $create_group_item =  '<a class="a_button orange medium" href="'.api_get_path(WEB_PATH).'main/social/group_add.php">'.get_lang('CreateASocialGroup').'</a>';
+    	        	    $create_group_item =  '<a class="a_button white medium" href="'.api_get_path(WEB_PATH).'main/social/group_add.php">'.get_lang('CreateASocialGroup').'</a>';
     	        	    //$my_group_content = $create_group_item. $my_group_content;
         	        } else {        	           
     	            	if (api_is_allowed_to_edit(null,true)) {
-    	            	    $create_group_item =  '<a class="a_button orange medium" href="'.api_get_path(WEB_PATH).'main/social/group_add.php">'.get_lang('CreateASocialGroup').'</a>';
+    	            	    $create_group_item =  '<a class="a_button white medium" href="'.api_get_path(WEB_PATH).'main/social/group_add.php">'.get_lang('CreateASocialGroup').'</a>';
     	        	        //$my_group_content = $create_group_item. $my_group_content;
     	            	}
         	        }
@@ -514,11 +514,11 @@ if ($group_id != 0 ) {
 	        	$my_group_content = Display::return_sortable_grid('mygroups', array(), $grid_my_groups, array('hide_navigation'=>true, 'per_page' => 2), $query_vars, false, array(true, true, true,false));           
 	        }
    	        if (api_get_setting('allow_students_to_create_groups_in_social') == 'true') {
-                $create_group_item =  '<a class="a_button orange medium" href="'.api_get_path(WEB_PATH).'main/social/group_add.php">'.get_lang('CreateASocialGroup').'</a>';
+                $create_group_item =  '<a class="a_button white medium" href="'.api_get_path(WEB_PATH).'main/social/group_add.php">'.get_lang('CreateASocialGroup').'</a>';
                 //$my_group_content = $create_group_item. $my_group_content;
             } else {
                 if (api_is_allowed_to_edit(null,true)) {
-                    $create_group_item =  '<a class="a_button orange medium" href="'.api_get_path(WEB_PATH).'main/social/group_add.php">'.get_lang('CreateASocialGroup').'</a>';
+                    $create_group_item =  '<a class="a_button white medium" href="'.api_get_path(WEB_PATH).'main/social/group_add.php">'.get_lang('CreateASocialGroup').'</a>';
                     //$my_group_content  = $create_group_item. $my_group_content;
                 }
             }

+ 55 - 51
main/survey/fillsurvey.php

@@ -24,7 +24,7 @@ if (!isset($_GET['cidReq'])) {
 }
 
 // Including the global initialization file
-require '../inc/global.inc.php';
+require_once '../inc/global.inc.php';
 
 // Including additional libraries
 //require_once api_get_path(LIBRARY_PATH).'survey.lib.php';
@@ -41,14 +41,18 @@ Display :: display_header(get_lang('ToolSurvey'));
 // getting all the course information
 $_course = CourseManager::get_course_information($_GET['course']);
 
+$course_id = api_get_course_int_id();
+
 // Database table definitions
-$table_survey 					= Database :: get_course_table(TABLE_SURVEY, $_course['db_name']);
-$table_survey_answer			= Database :: get_course_table(TABLE_SURVEY_ANSWER, $_course['db_name']);
-$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION, $_course['db_name']);
-$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION, $_course['db_name']);
+$table_survey 					= Database :: get_course_table(TABLE_SURVEY);
+$table_survey_answer			= Database :: get_course_table(TABLE_SURVEY_ANSWER);
+$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
+$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
+$table_survey_invitation        = Database :: get_course_table(TABLE_SURVEY_INVITATION);
+
 $table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
 $table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-$table_survey_invitation 		= Database :: get_course_table(TABLE_SURVEY_INVITATION, $_course['db_name']);
+
 
 // First we check if the needed parameters are present
 if ((!isset($_GET['course']) || !isset($_GET['invitationcode']))&& !isset($_GET['user_id'])) {
@@ -69,7 +73,7 @@ if ($invitationcode == 'auto' && isset($_GET['scode'])){
     $scode = Database::escape_string($_GET['scode']); // Survey_code of the survey
     $autoInvitationcode = "auto-$userid-$scode"; // New invitation code from userid
     // The survey code must exist in this course, or the URL is invalid
-    $sql = "SELECT * FROM $table_survey WHERE code ='" . $scode . "'";
+    $sql = "SELECT * FROM $table_survey WHERE c_id = $course_id AND code ='" . $scode . "'";
     $result = Database::query($sql);
     if (Database :: num_rows($result) > 0) { // Ok
         // Check availability
@@ -77,11 +81,11 @@ if ($invitationcode == 'auto' && isset($_GET['scode'])){
         $tempdata  = survey_manager :: get_survey($row['survey_id']);
         check_time_availability($tempdata); //exit if survey not available anymore
         // Check for double invitation records (insert should be done once)
-        $sql = "SELECT user from $table_survey_invitation WHERE invitation_code = '".Database::escape_string($autoInvitationcode)."'";
+        $sql = "SELECT user from $table_survey_invitation WHERE c_id = $course_id AND invitation_code = '".Database::escape_string($autoInvitationcode)."'";
         $result = Database::query($sql);
         if (Database :: num_rows($result) == 0) { // Ok
             $sql = "INSERT INTO $table_survey_invitation (c_id, survey_code,user, invitation_code, invitation_date) ";
-            $sql .= " values ($course_id, \"$scode\", \"$userid\", \"$autoInvitationcode\", now())";
+            $sql .= " VALUES ($course_id, \"$scode\", \"$userid\", \"$autoInvitationcode\", now())";
             Database::query($sql);
         }
         // From here we use the new invitationcode auto-userid-surveycode string
@@ -91,7 +95,7 @@ if ($invitationcode == 'auto' && isset($_GET['scode'])){
 }
 
 // Now we check if the invitationcode is valid
-$sql = "SELECT * FROM $table_survey_invitation WHERE invitation_code = '" . Database :: escape_string($invitationcode) . "'";
+$sql = "SELECT * FROM $table_survey_invitation WHERE c_id = $course_id AND invitation_code = '" . Database :: escape_string($invitationcode) . "'";
 $result = Database::query($sql); // false = suppress errors
 if (Database::num_rows($result) < 1) {
 	Display :: display_error_message(get_lang('WrongInvitationCode'), false);
@@ -109,7 +113,7 @@ if ($survey_invitation['answered'] == 1 && !isset($_GET['user_id'])) {
 
 // Checking if there is another survey with this code.
 // If this is the case there will be a language choice
-$sql = "SELECT * FROM $table_survey WHERE code='".Database::escape_string($survey_invitation['survey_code'])."'";
+$sql = "SELECT * FROM $table_survey WHERE c_id = $course_id AND code='".Database::escape_string($survey_invitation['survey_code'])."'";
 $result = Database::query($sql);
 
 if (Database::num_rows($result) > 1) {
@@ -129,7 +133,7 @@ if (Database::num_rows($result) > 1) {
 		exit();
 	}
 } else {
-	$row=Database::fetch_array($result, 'ASSOC');
+	$row = Database::fetch_array($result, 'ASSOC');
 	$survey_invitation['survey_id'] = $row['survey_id'];
 }
 
@@ -141,12 +145,13 @@ $survey_data['survey_id'] = $survey_invitation['survey_id'];
 if (count($_POST) > 0) {
     if ($survey_data['survey_type'] === '0') {
 		// Getting all the types of the question (because of the special treatment of the score question type
-		$sql = "SELECT * FROM $table_survey_question WHERE survey_id = '".Database::escape_string($survey_invitation['survey_id'])."'";
+		$sql = "SELECT * FROM $table_survey_question WHERE c_id = $course_id AND survey_id = '".Database::escape_string($survey_invitation['survey_id'])."'";
 		$result = Database::query($sql);
 
 		while ($row = Database::fetch_array($result, 'ASSOC')) {
 			$types[$row['question_id']] = $row['type'];
 		}
+		
 
 		// Looping through all the post values
 		foreach ($_POST as $key => & $value) {
@@ -174,7 +179,7 @@ if (count($_POST) > 0) {
 				// All the other question types (open question, multiple choice, percentage, ...)
 				else {
 					if ($types[$survey_question_id] == 'percentage') {
-						$sql = "SELECT * FROM $table_survey_question_option WHERE question_option_id='".Database::escape_string($value)."'";
+						$sql = "SELECT * FROM $table_survey_question_option WHERE c_id = $course_id AND question_option_id='".Database::escape_string($value)."'";
 						$result = Database::query($sql);
 						$row = Database::fetch_array($result, 'ASSOC');
 						$option_value = $row['option_text'];
@@ -200,7 +205,7 @@ if (count($_POST) > 0) {
 			$shuffle= ' ORDER BY RAND() ';
 		}
 		$sql = "SELECT * FROM $table_survey_question
-				WHERE survey_id = '".Database::escape_string($survey_invitation['survey_id'])."'
+				WHERE c_id = $course_id AND survey_id = '".Database::escape_string($survey_invitation['survey_id'])."'
 				AND survey_group_pri='0' $shuffle";
 		$result = Database::query($sql);
         // There is only one question type for conditional surveys
@@ -215,7 +220,7 @@ if (count($_POST) > 0) {
 				// Finding the question id by removing 'question'
 				$survey_question_id = str_replace('question', '', $key);
 				// We select the correct answer and the puntuacion
-				$sql = "SELECT value FROM $table_survey_question_option WHERE question_option_id='".Database::escape_string($value)."'";
+				$sql = "SELECT value FROM $table_survey_question_option WHERE c_id = $course_id AND question_option_id='".Database::escape_string($value)."'";
 				$result = Database::query($sql);
 				$row = Database::fetch_array($result, 'ASSOC');
 				$option_value = $row['value'];
@@ -271,8 +276,7 @@ if ($survey_data['form_fields']!='' && $survey_data['anonymous'] == 0 && is_arra
 		}
 	}
 
-	// We use the same form as in auth/profile.php
-	require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+	// We use the same form as in auth/profile.php	
 	$form = new FormValidator('profile', 'post', api_get_self() . "?" . str_replace('&show_form=1', '&show_form=1', $_SERVER['QUERY_STRING']), null,
 		array('style' => 'width: 75%; float: ' . ($text_dir == 'rtl' ? 'right;' : 'left;'))
 	);
@@ -573,7 +577,7 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 	if ($survey_data['survey_type'] === '0') {
 		if (empty($_SESSION['paged_questions'])) {
     		$sql = "SELECT * FROM $table_survey_question
-    				WHERE survey_id = '".Database::escape_string($survey_invitation['survey_id'])."'
+    				WHERE c_id = $course_id AND survey_id = '".Database::escape_string($survey_invitation['survey_id'])."'
     				ORDER BY sort ASC";
     		$result = Database::query($sql);
     		while ($row = Database::fetch_array($result, 'ASSOC')) {
@@ -602,10 +606,9 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 					survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
 					FROM $table_survey_question survey_question
 					LEFT JOIN $table_survey_question_option survey_question_option
-					ON survey_question.question_id = survey_question_option.question_id
+					ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id
 					WHERE survey_question.survey_id = '" . Database :: escape_string($survey_invitation['survey_id']) . "'
-					AND survey_question.question_id NOT IN (SELECT sa.question_id FROM ".$table_survey_answer." sa WHERE sa.user='".$my_user_id."') AND
-					survey_question_option.c_id = $course_id AND
+					AND survey_question.question_id NOT IN (SELECT sa.question_id FROM ".$table_survey_answer." sa WHERE sa.user='".$my_user_id."') AND					
 					survey_question.c_id =  $course_id 
 					ORDER BY survey_question.sort, survey_question_option.sort ASC";
 			} else {
@@ -613,11 +616,10 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 					survey_question.question_id, survey_question.survey_id, survey_question.survey_question, survey_question.display, survey_question.sort, survey_question.type, survey_question.max_value,
 					survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
 					FROM $table_survey_question survey_question
-					LEFT JOIN $table_survey_question_option survey_question_option
-					ON survey_question.question_id = survey_question_option.question_id
+					LEFT JOIN $table_survey_question_option survey_question_option 
+					ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id
 					WHERE survey_question.survey_id = '".Database::escape_string($survey_invitation['survey_id'])."' AND 
-					survey_question.question_id IN (".implode(',',$paged_questions[$_GET['show']]).") AND
-					survey_question_option.c_id = $course_id AND
+					survey_question.question_id IN (".implode(',',$paged_questions[$_GET['show']]).") AND					
 					survey_question.c_id =  $course_id 
 					ORDER BY survey_question.sort, survey_question_option.sort ASC";
 			}
@@ -666,8 +668,10 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 			$sql = "SELECT survey_group_pri, user, SUM(value) as value
 					FROM $table_survey_answer as survey_answer INNER JOIN $table_survey_question as survey_question
 					ON  (survey_question.question_id = survey_answer.question_id)
-					WHERE survey_answer.survey_id='".$my_survey_id."' AND
-					survey_answer.user='".$current_user."'
+					WHERE  survey_answer.survey_id='".$my_survey_id."' AND
+					       survey_answer.user='".$current_user."' AND
+					       survey_answer.c_id = $course_id AND 
+					       survey_question.c_id = $course_id AND 
 					GROUP BY survey_group_pri
 					ORDER BY survey_group_pri
 					";
@@ -684,12 +688,19 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 			// Get the total score for each group of questions
 			$totals = array();
 			$sql = "SELECT SUM(temp.value) as value, temp.survey_group_pri FROM
-					(SELECT MAX(value) as value,  survey_group_pri, survey_question.question_id
+					(
+					SELECT MAX(value) as value,  survey_group_pri, survey_question.question_id
 					FROM $table_survey_question as survey_question
 					INNER JOIN $table_survey_question_option as survey_question_option
 					ON (survey_question.question_id = survey_question_option.question_id)
-					WHERE survey_question.survey_id='".$my_survey_id."'  AND  survey_group_sec1='0' AND survey_group_sec2='0'
-					GROUP BY survey_group_pri, survey_question.question_id) as temp
+					WHERE  survey_question.survey_id='".$my_survey_id."'  AND
+					       survey_question.c_id = $course_id AND
+					       survey_question_option.c_id = $course_id AND
+					       survey_group_sec1='0' AND 
+					       survey_group_sec2='0'
+					GROUP BY survey_group_pri, survey_question.question_id
+                    ) as temp
+                    
 					GROUP BY temp.survey_group_pri
 					ORDER BY temp.survey_group_pri";
 
@@ -716,14 +727,7 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 
 			// Sort the results by score (getting a list of group IDs by score into $groups)
 			arsort($final_results);
-			$groups=array_keys($final_results);
-			/*
-            echo '<pre>';
-			echo 'Group id =>  %';
-			echo '<br />';
-			print_r($final_results);
-            echo '</pre>';
-		    */
+			$groups=array_keys($final_results);		
 			$result = array();
 			$count_result = 0;
 			foreach ($final_results as $key => & $sub_result) {
@@ -778,8 +782,6 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 				// We force the exit of the survey undeterminated
 				$equal_count=10;
 			}
-			//echo '<pre>';
-			//print_r($result);
 
             // If we have only 3 or less equal scores (i.e. 0,1 or 2 equalities), then we can use the three first groups
 			if ($equal_count < 4) {
@@ -857,7 +859,7 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 					if (empty($_SESSION['page_questions_sec']) && !is_array($_SESSION['page_questions_sec']) && count($_SESSION['page_questions_sec'] == 0)) {
 
     					$sql = "SELECT * FROM $table_survey_question
-    								 WHERE survey_id = '".$my_survey_id."'
+    								 WHERE c_id = $course_id AND survey_id = '".$my_survey_id."'
     							  	 AND ($secondary )
     								 ORDER BY sort ASC";
     					$result = Database::query($sql);
@@ -898,9 +900,10 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 								survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
 								FROM $table_survey_question survey_question
 								LEFT JOIN $table_survey_question_option survey_question_option
-								ON survey_question.question_id = survey_question_option.question_id
-								WHERE survey_question.survey_id = '".$my_survey_id."'
-								AND survey_question.question_id IN (".implode(',',$paged_questions_sec[$val]).")
+								ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id 
+								WHERE   survey_question.survey_id = '".$my_survey_id."' AND
+								        survey_question.c_id = $course_id AND 
+								        survey_question.question_id IN (".implode(',',$paged_questions_sec[$val]).")
 								ORDER  $shuffle ";
 
 						$result = Database::query($sql);
@@ -952,7 +955,7 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 
             if (empty($_SESSION['paged_questions'])) {
     			$sql = "SELECT * FROM $table_survey_question
-    						 WHERE survey_id = '".Database::escape_string($survey_invitation['survey_id'])."'
+    						 WHERE c_id = $course_id AND survey_id = '".Database::escape_string($survey_invitation['survey_id'])."'
     					  	 AND survey_group_sec1='0' AND survey_group_sec2='0'
     						 ORDER ".$order_sql." ";
     			//echo '<br />'; echo '<br />';
@@ -1001,9 +1004,10 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 							survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
 							FROM $table_survey_question survey_question
 							LEFT JOIN $table_survey_question_option survey_question_option
-							ON survey_question.question_id = survey_question_option.question_id
-							WHERE survey_question.survey_id = '" . Database :: escape_string($survey_invitation['survey_id']) . "'
-							AND survey_question.question_id IN (" .$imploded. ")
+							ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id 
+							WHERE    survey_question.survey_id = '" . Database :: escape_string($survey_invitation['survey_id']) . "' AND
+							         survey_question.c_id = $course_id  AND
+							         survey_question.question_id IN (" .$imploded. ")
 							ORDER $order_sql ";
 					$result = Database::query($sql);
 					$question_counter_max = Database :: num_rows($result);
@@ -1042,7 +1046,7 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 }
 
 // Selecting the maximum number of pages
-$sql = "SELECT * FROM $table_survey_question WHERE type='".Database::escape_string('pagebreak')."' AND survey_id='".Database::escape_string($survey_invitation['survey_id'])."'";
+$sql = "SELECT * FROM $table_survey_question WHERE c_id = $course_id AND type='".Database::escape_string('pagebreak')."' AND survey_id='".Database::escape_string($survey_invitation['survey_id'])."'";
 $result = Database::query($sql);
 $numberofpages = Database::num_rows($result) + 1;
 
@@ -1208,4 +1212,4 @@ function check_time_availability($surv_data) {
         Display :: display_footer();
         exit;
     }
-}
+}

+ 20 - 17
main/survey/preview.php

@@ -27,6 +27,8 @@ $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUEST
 $table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
 $table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
 
+$course_id = api_get_course_int_id();
+
 // We exit here if ther is no valid $_GET parameter
 if (!isset($_GET['survey_id']) || !is_numeric($_GET['survey_id'])){
 	Display :: display_header(get_lang('SurveyPreview'));
@@ -94,29 +96,30 @@ if (api_is_course_admin() || (api_is_course_admin() && $_GET['isStudentView'] ==
 		$questions_displayed = array();
 		$paged_questions = array();
 		$counter = 0;
-		$sql = "SELECT * FROM $table_survey_question
-			WHERE survey_id = '".Database::escape_string($survey_id)."'
+		$sql = "SELECT * FROM $table_survey_question 
+		        WHERE c_id = $course_id AND survey_id = '".Database::escape_string($survey_id)."'
 				ORDER BY sort ASC";
 		$result = Database::query($sql);
-
-		while ($row = Database::fetch_array($result)) {
-			if ($row['type'] == 'pagebreak') {
-				$counter++;
-			} else {
-				$paged_questions[$counter][] = $row['question_id'];
-			}
-		}
-		
-		$course_id = api_get_course_int_id();
+        $questions_exists = true;
+        if (Database::num_rows($result)) {
+    		while ($row = Database::fetch_array($result)) {
+    			if ($row['type'] == 'pagebreak') {
+    				$counter++;
+    			} else {
+    				$paged_questions[$counter][] = $row['question_id'];
+    			}
+    		}
+        } else {
+            $questions_exists = false;
+        }
 		
 		if (array_key_exists($_GET['show'], $paged_questions)) {
 			$sql = "SELECT survey_question.question_id, survey_question.survey_id, survey_question.survey_question, survey_question.display, survey_question.sort, survey_question.type, survey_question.max_value,
 							survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
 					FROM $table_survey_question survey_question LEFT JOIN $table_survey_question_option survey_question_option
-					ON survey_question.question_id = survey_question_option.question_id
+					ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id 
 					WHERE 	survey_question.survey_id = '".Database::escape_string($survey_id)."' AND 
-							survey_question.question_id IN (".Database::escape_string(implode(',',$paged_questions[$_GET['show']])).") AND
-							survey_question_option.c_id = $course_id AND
+							survey_question.question_id IN (".Database::escape_string(implode(',',$paged_questions[$_GET['show']])).") AND							
 							survey_question.c_id =  $course_id 
 					ORDER BY survey_question.sort, survey_question_option.sort ASC";
 
@@ -143,7 +146,7 @@ if (api_is_course_admin() || (api_is_course_admin() && $_GET['isStudentView'] ==
 		}
 	}
 	// Selecting the maximum number of pages
-	$sql = "SELECT * FROM $table_survey_question WHERE type='".Database::escape_string('pagebreak')."' AND survey_id='".Database::escape_string($survey_id)."'";
+	$sql = "SELECT * FROM $table_survey_question WHERE c_id = $course_id AND type='".Database::escape_string('pagebreak')."' AND survey_id='".Database::escape_string($survey_id)."'";
 	$result = Database::query($sql);
 	$numberofpages = Database::num_rows($result) + 1;
 	// Displaying the form with the questions
@@ -166,7 +169,7 @@ if (api_is_course_admin() || (api_is_course_admin() && $_GET['isStudentView'] ==
 		echo '<br /><button type="submit" name="next_survey_page" class="next">'.get_lang('NextQuestion').'   </button>';
 	}
 	if ($show >= $numberofpages && $_GET['show'] || (isset($_GET['show']) && count($questions) == 0)) {
-		if (count($questions) == 0) {
+		if ($questions_exists == false) {
 			echo '<p>'.get_lang('ThereAreNotQuestionsForthisSurvey').'</p>';
 		}
 		echo '<button type="submit" name="finish_survey" class="next">'.get_lang('FinishSurvey').'  </button>';

+ 5 - 3
main/survey/question.php

@@ -12,10 +12,9 @@
 $language_file = 'survey';
 
 // Including the global initialization file
-require '../inc/global.inc.php';
+require_once '../inc/global.inc.php';
 
 // Including additional libraries
-//require_once api_get_path(LIBRARY_PATH).'survey.lib.php';
 require_once 'survey.lib.php';
 
 $htmlHeadXtra[] = '<script type="text/javascript">
@@ -49,9 +48,12 @@ if ($request_index != $is_valid_request) {
 $table_survey 					= Database :: get_course_table(TABLE_SURVEY);
 $table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
 $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
+
 $table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
 $table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
 
+$course_id = api_get_course_int_id();
+
 // Getting the survey information
 $survey_data = survey_manager::get_survey($_GET['survey_id']);
 if (empty($survey_data)) {
@@ -68,7 +70,7 @@ if (api_strlen(strip_tags($survey_data['title'])) > 40) {
 }
 
 if ($survey_data['survey_type'] == 1) {
-	$sql = 'SELECT id FROM '.Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP).' WHERE survey_id = '.(int)$_GET['survey_id'].' LIMIT 1';
+	$sql = 'SELECT id FROM '.Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP).' WHERE c_id = '.$course_id.' AND survey_id = '.(int)$_GET['survey_id'].' LIMIT 1';
 	$rs = Database::query($sql);
 	if(Database::num_rows($rs)===0) {
 		header('Location: survey.php?survey_id='.(int)$_GET['survey_id'].'&message='.'YouNeedToCreateGroups');

+ 0 - 6
main/survey/reporting.php

@@ -61,9 +61,6 @@ if ($_POST['export_report']) {
 	}
 }
 
-// Including additional libraries
-require_once api_get_path(LIBRARY_PATH).'course.lib.php';
-
 // Checking the parameters
 SurveyUtil::check_parameters();
 
@@ -76,9 +73,6 @@ if (!api_is_allowed_to_edit(false, true)) {
 }
 
 // Database table definitions
-$table_survey 					= Database :: get_course_table(TABLE_SURVEY);
-$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
-$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
 $table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
 $table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
 $user_info 						= Database :: get_main_table(TABLE_MAIN_SURVEY_REMINDER); // TODO: To be checked. TABLE_MAIN_SURVEY_REMINDER has not been defined.

+ 117 - 97
main/survey/survey.lib.php

@@ -262,7 +262,7 @@ class survey_manager {
 		} else {
 
 			// Check whether the code doesn't soon exists in this language
-			$sql = 'SELECT 1 FROM '.$table_survey.' WHERE  c_id = '.$course_id.' AND code="'.Database::escape_string($values['survey_code']).'" AND lang="'.Database::escape_string($values['survey_language']).'" AND survey_id!='.intval($values['survey_id']);
+			$sql = 'SELECT 1 FROM '.$table_survey.' WHERE c_id = '.$course_id.' AND code="'.Database::escape_string($values['survey_code']).'" AND lang="'.Database::escape_string($values['survey_language']).'" AND survey_id!='.intval($values['survey_id']);
 			$rs = Database::query($sql);
 			if (Database::num_rows($rs) > 0) {
 				$return['message'] = 'ThisSurveyCodeSoonExistsInThisLanguage';
@@ -394,14 +394,16 @@ class survey_manager {
 		
 		if ($shared) {
 			$table_survey = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY);
+			 // Deleting the survey
+            $sql = "DELETE FROM $table_survey WHERE survey_id='".Database::escape_string($survey_id)."'";
+            $res = Database::query($sql);
+		} else {
+		    $sql = "DELETE FROM $table_survey WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'";
+            $res = Database::query($sql);
 		}
 
-		// Deleting the survey
-		$sql = "DELETE from $table_survey WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'";
-		$res = Database::query($sql);
-
 		// Deleting groups of this survey
-		$sql = "DELETE from $table_survey_question_group WHERE c_id = $course_id AND  survey_id='".Database::escape_string($survey_id)."'";
+		$sql = "DELETE FROM $table_survey_question_group WHERE c_id = $course_id AND  survey_id='".Database::escape_string($survey_id)."'";
 		$res = Database::query($sql);
 
 		// Deleting the questions of the survey
@@ -414,6 +416,8 @@ class survey_manager {
 	}
 
 	function copy_survey($parent_survey, $new_survey_id) {
+	    $course_id = api_get_course_int_id();
+        
 		// Database table definitions
 		$table_survey 					= Database::get_course_table(TABLE_SURVEY);
 		$table_survey_question_group 	= Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
@@ -421,7 +425,7 @@ class survey_manager {
 		$table_survey_options 			= Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
 		$parent_survey 					= Database::escape_string($parent_survey);
 		// Get groups
-		$sql = "SELECT * from $table_survey_question_group WHERE survey_id='".$parent_survey."'";
+		$sql = "SELECT * from $table_survey_question_group WHERE c_id = $course_id AND  survey_id='".$parent_survey."'";
 		$res = Database::query($sql);
 		if (Database::num_rows($res) === 0) {
 			return true;
@@ -436,7 +440,7 @@ class survey_manager {
 		}
 
 		// Get questions
-		$sql = "SELECT * FROM $table_survey_question WHERE survey_id='".$parent_survey."'";
+		$sql = "SELECT * FROM $table_survey_question WHERE c_id = $course_id AND survey_id='".$parent_survey."'";
 		$res = Database::query($sql);
 		while($row = Database::fetch_array($res, 'ASSOC')){
 			$sql2 = 'INSERT INTO '.$table_survey_question.' (c_id, survey_id,survey_question,survey_question_comment,type,display,sort,shared_question_id,max_value,survey_group_pri,survey_group_sec1,survey_group_sec2) VALUES '.
@@ -447,7 +451,7 @@ class survey_manager {
 		}
 
 		// Get questions options
-		$sql = "SELECT * FROM $table_survey_options WHERE  survey_id='".$parent_survey."'";
+		$sql = "SELECT * FROM $table_survey_options WHERE c_id = $course_id AND survey_id='".$parent_survey."'";
 		$res = Database::query($sql);
 		while($row = Database::fetch_array($res ,'ASSOC')){
 			$sql3 = 'INSERT INTO '.$table_survey_options.' (c_id, question_id,survey_id,option_text,sort,value) VALUES ('.
@@ -468,9 +472,11 @@ class survey_manager {
 	 */
 	function empty_survey($survey_id) {
 		// Database table definitions
-		$table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
-		$table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
-		$table_survey = Database :: get_course_table(TABLE_SURVEY);
+		$table_survey_invitation      = Database :: get_course_table(TABLE_SURVEY_INVITATION);
+		$table_survey_answer          = Database :: get_course_table(TABLE_SURVEY_ANSWER);
+		$table_survey                 = Database :: get_course_table(TABLE_SURVEY);
+        
+        $course_id = api_get_course_int_id();
 
 		$datas = survey_manager::get_survey($survey_id);
 		$session_where = '';
@@ -478,13 +484,13 @@ class survey_manager {
 			$session_where = ' AND session_id = "'.api_get_session_id().'" ';
 		}
 
-		$sql = 'DELETE FROM '.$table_survey_invitation.' WHERE survey_code = "'.Database::escape_string($datas['code']).'" '.$session_where.' ';
+		$sql = 'DELETE FROM '.$table_survey_invitation.' WHERE c_id = '.$course_id.' AND survey_code = "'.Database::escape_string($datas['code']).'" '.$session_where.' ';
 		Database::query($sql);
 
-		$sql = 'DELETE FROM '.$table_survey_answer.' WHERE survey_id='.intval($survey_id);
+		$sql = 'DELETE FROM '.$table_survey_answer.' WHERE c_id = '.$course_id.' AND survey_id='.intval($survey_id);
 		Database::query($sql);
 
-		$sql = 'UPDATE '.$table_survey.' SET invited=0, answered=0 WHERE survey_id='.intval($survey_id);
+		$sql = 'UPDATE '.$table_survey.' SET invited=0, answered=0 WHERE c_id = '.$course_id.' AND survey_id='.intval($survey_id);
 		Database::query($sql);
 
 		return true;
@@ -532,17 +538,6 @@ class survey_manager {
 	 * @version February 2007
 	 */
 	function get_complete_survey_structure($survey_id, $shared = 0) {
-		// Database table definitions
-		$table_survey 					= Database :: get_course_table(TABLE_SURVEY);
-		$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
-		$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
-
-		if ($shared != 0) {
-			$table_survey 					= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
-			$table_survey_question 			= Database :: get_course_table(TABLE_SHARED_SURVEY_QUESTION);
-			$table_survey_question_option 	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
-		}
-
 		$structure = survey_manager::get_survey($survey_id, $shared);
 		$structure['questions'] = survey_manager::get_questions($survey_id);
 	}
@@ -933,13 +928,17 @@ class survey_manager {
 	 * @version January 2007
 	 */
 	function delete_all_survey_questions($survey_id, $shared = false) {
+	    $course_id = api_get_course_int_id();
+        
 		// Table definitions
 		$table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
-        $sql = "DELETE from $table_survey_question WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'";
+        $course_condition = " c_id = $course_id AND ";
 		if ($shared) {
-			$table_survey_question 	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
-            $sql = "DELETE from $table_survey_question WHERE survey_id='".Database::escape_string($survey_id)."'";
+		    $course_condition = "";
+			$table_survey_question 	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);            
 		}
+		
+		$sql = "DELETE FROM $table_survey_question WHERE $course_condition survey_id='".Database::escape_string($survey_id)."'";
 
 		// Deleting the survey questions
 		
@@ -1022,6 +1021,7 @@ class survey_manager {
 	 * @todo writing the update statement when editing a question
 	 */
 	function save_question_options($form_content, $survey_data) {
+	    $course_id = api_get_course_int_id();
 		// A percentage question type has options 1 -> 100
 		if ($form_content['type'] == 'percentage') {
 			for($i = 1; $i < 101; $i++) {
@@ -1038,13 +1038,11 @@ class survey_manager {
 
 		// We are editing a question so we first have to remove all the existing options from the database
 		if (is_numeric($form_content['question_id'])) {
-			$sql = "DELETE FROM $table_survey_question_option WHERE question_id = '".Database::escape_string($form_content['question_id'])."'";
+			$sql = "DELETE FROM $table_survey_question_option WHERE c_id = $course_id AND question_id = '".Database::escape_string($form_content['question_id'])."'";
 			$result = Database::query($sql);
 		}
 
 		$counter = 1;
-		$course_id = api_get_course_int_id();
-		
 		if (is_array($form_content['answers'])) {
 			//foreach ($form_content['answers'] as $key => $answer) {
 			for ($i = 0; $i < count($form_content['answers']); $i++) {
@@ -1112,14 +1110,20 @@ class survey_manager {
 	 * @version January 2007
 	 */
 	function delete_all_survey_questions_options($survey_id, $shared = false) {
+	    
 		// Table definitions
 		$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
+        $course_id = api_get_course_int_id();
+        $course_condition = " c_id = $course_id AND ";
 		if ($shared) {
-			$table_survey_question 	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
+		    $course_condition = "";
+			$table_survey_question 	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);            
 		}
+        
+        $sql = "DELETE from $table_survey_question_option WHERE $course_condition survey_id='".Database::escape_string($survey_id)."'";
 
 		// Deleting the options of the survey questions
-		$sql = "DELETE from $table_survey_question_option WHERE survey_id='".Database::escape_string($survey_id)."'";
+		
 		$res = Database::query($sql);
 		return true;
 	}
@@ -1136,14 +1140,18 @@ class survey_manager {
 	 * @version March 2007
 	 */
 	function delete_survey_question_option($survey_id, $question_id, $shared = false) {
+	    $course_id = api_get_course_int_id();
+        $course_condition = " c_id = $course_id AND ";
+        
 		// Table definitions
 		$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
 		if ($shared) {
+		    $course_condition = "";
 			$table_survey_question 	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
 		}
 
 		// Deleting the options of the survey questions
-		$sql = "DELETE from $table_survey_question_option WHERE survey_id='".Database::escape_string($survey_id)."' AND question_id='".Database::escape_string($question_id)."'";
+		$sql = "DELETE from $table_survey_question_option WHERE $course_condition survey_id='".Database::escape_string($survey_id)."' AND question_id='".Database::escape_string($question_id)."'";
 		$res = Database::query($sql);
 		return true;
 	}
@@ -1373,6 +1381,7 @@ class survey_question {
 	 * @version January 2007
 	 */
 	function handle_action($form_content) {
+	    $course_id = api_get_course_int_id();
 		global $config;
 
 		// Moving an answer up
@@ -1415,7 +1424,7 @@ class survey_question {
 			$message = survey_manager::save_question($form_content);
 
 			if ($message == 'QuestionAdded' || $message == 'QuestionUpdated' ) {
-				$sql='SELECT COUNT(*) FROM '.Database :: get_course_table(TABLE_SURVEY_QUESTION).' WHERE survey_id = '.intval($_GET['survey_id']);
+				$sql='SELECT COUNT(*) FROM '.Database :: get_course_table(TABLE_SURVEY_QUESTION).' WHERE c_id = '.$course_id.' AND survey_id = '.intval($_GET['survey_id']);
 				$res = Database :: fetch_array (Database::query($sql));
 
 				if ($config['survey']['debug']) {
@@ -2162,9 +2171,10 @@ class SurveyUtil {
 		// Table definitions
 		$tbl_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
 		$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
+        $course_id = api_get_course_int_id();
 
 		// Getting the information of the question
-		$sql = "SELECT * FROM $tbl_survey_question WHERE survey_id='".Database::escape_string($survey_id)."' ORDER BY sort ASC";
+		$sql = "SELECT * FROM $tbl_survey_question WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."' ORDER BY sort ASC";
 		$result = Database::query($sql);
 		$total = Database::num_rows($result);
 		$counter = 1;
@@ -2393,7 +2403,9 @@ class SurveyUtil {
 	 * @version February 2007 - Updated March 2008
 	 */
 	function display_user_report() {
-		global $people_filled, $survey_data;
+	    $course_id = api_get_course_int_id();
+	    
+		global $people_filled, $survey_data;		
 
 		// Database table definitions
 		$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
@@ -2438,8 +2450,7 @@ class SurveyUtil {
 		echo '<option value="reporting.php?action='.Security::remove_XSS($_GET['action']).'&amp;survey_id='.Security::remove_XSS($_GET['survey_id']).'">'.get_lang('SelectUser').'</option>';
 
 		foreach ($people_filled as $key => & $person) {
-			if ($survey_data['anonymous'] == 0)
-			{
+			if ($survey_data['anonymous'] == 0) {
 				$name = api_get_person_name($person['firstname'], $person['lastname']);
 				$id = $person['user_id'];
 				if ($id == '') {
@@ -2466,11 +2477,10 @@ class SurveyUtil {
 			$sql = "SELECT 	survey_question.question_id, survey_question.survey_id, survey_question.survey_question, survey_question.display, survey_question.max_value, survey_question.sort, survey_question.type,
 							survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
 					FROM $table_survey_question survey_question
-					LEFT JOIN $table_survey_question_option survey_question_option
-					ON survey_question.question_id = survey_question_option.question_id
+					LEFT JOIN $table_survey_question_option survey_question_option 
+					ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id 
 					WHERE 	survey_question.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
-							survey_question.c_id = $course_id AND
-							survey_question_option.c_id = $course_id 
+							survey_question.c_id = $course_id
 					ORDER BY survey_question.sort, survey_question_option.sort ASC";
 			$result = Database::query($sql);
 			while ($row = Database::fetch_array($result, 'ASSOC')) {
@@ -2486,7 +2496,7 @@ class SurveyUtil {
 			}
 
 			// Getting all the answers of the user
-			$sql = "SELECT * FROM $table_survey_answer WHERE survey_id = '".Database::escape_string($_GET['survey_id'])."' AND user = '".Database::escape_string($_GET['user'])."'";
+			$sql = "SELECT * FROM $table_survey_answer WHERE c_id = $course_id AND survey_id = '".Database::escape_string($_GET['survey_id'])."' AND user = '".Database::escape_string($_GET['user'])."'";
 			$result = Database::query($sql);
 			while ($row = Database::fetch_array($result, 'ASSOC')) {
 				$answers[$row['question_id']][] = $row['option_id'];
@@ -2537,6 +2547,7 @@ class SurveyUtil {
 	 * @version February 2007 - Updated March 2008
 	 */
 	function display_question_report($survey_data) {
+	    $course_id = api_get_course_int_id();
 		// Database table definitions
 		$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
 		$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
@@ -2568,7 +2579,7 @@ class SurveyUtil {
 			echo '</div>';
 
 			// Getting the question information
-			$sql = "SELECT * FROM $table_survey_question WHERE survey_id='".Database::escape_string($_GET['survey_id'])."' AND type<>'pagebreak' AND type<>'comment' ORDER BY sort ASC LIMIT ".$offset.",1";
+			$sql = "SELECT * FROM $table_survey_question WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."' AND type<>'pagebreak' AND type<>'comment' ORDER BY sort ASC LIMIT ".$offset.",1";
 			$result = Database::query($sql);
 			$question = Database::fetch_array($result);
 
@@ -2594,7 +2605,7 @@ class SurveyUtil {
 			$options = SurveyUtil::display_question_report_score($survey_data, $question, $offset);
 		} elseif ($question['type'] == 'open') {
 			/** @todo Also get the user who has answered this */
-			$sql = "SELECT * FROM $table_survey_answer WHERE survey_id='".Database::escape_string($_GET['survey_id'])."'
+			$sql = "SELECT * FROM $table_survey_answer WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."'
 						AND question_id = '".Database::escape_string($question['question_id'])."'";
 			$result = Database::query($sql);
 			while ($row = Database::fetch_array($result)) {
@@ -2603,7 +2614,7 @@ class SurveyUtil {
 		} else {
 			// Getting the options
 			$sql = "SELECT * FROM $table_survey_question_option
-						WHERE survey_id='".Database::escape_string($_GET['survey_id'])."'
+						WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."'
 						AND question_id = '".Database::escape_string($question['question_id'])."'
 						ORDER BY sort ASC";
 			$result = Database::query($sql);
@@ -2612,8 +2623,9 @@ class SurveyUtil {
 			}
 			// Getting the answers
 			$sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
-						WHERE survey_id='".Database::escape_string($_GET['survey_id'])."'
-						AND question_id = '".Database::escape_string($question['question_id'])."'
+						WHERE c_id = $course_id AND 
+						      survey_id='".Database::escape_string($_GET['survey_id'])."' AND
+						      question_id = '".Database::escape_string($question['question_id'])."'
 						GROUP BY option_id, value";
 			$result = Database::query($sql);
 			while ($row = Database::fetch_array($result)) {
@@ -2671,7 +2683,7 @@ class SurveyUtil {
 				$sql_restriction = "AND value='".Database::escape_string($_GET['value'])."'";
 			}
 
-			$sql = "SELECT user FROM $table_survey_answer WHERE option_id = '".Database::escape_string($_GET['viewoption'])."' $sql_restriction";
+			$sql = "SELECT user FROM $table_survey_answer WHERE c_id = $course_id AND option_id = '".Database::escape_string($_GET['viewoption'])."' $sql_restriction";
 			$result = Database::query($sql);
 			while ($row = Database::fetch_array($result)) {
 			    $user_info = api_get_user_info($row['user']);
@@ -2688,6 +2700,7 @@ class SurveyUtil {
 	 * @return	void 	(direct output)
 	 */
 	function display_question_report_score($survey_data, $question, $offset) {
+	    $course_id = api_get_course_int_id();
 		// Database table definitions
 		$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
 		$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
@@ -2697,7 +2710,7 @@ class SurveyUtil {
 
 		// Getting the options
 		$sql = "SELECT * FROM $table_survey_question_option
-					WHERE  c_id = $course_id AND 
+					WHERE c_id = $course_id AND 
 					       survey_id='".Database::escape_string($_GET['survey_id'])."'
 					AND question_id = '".Database::escape_string($question['question_id'])."'
 					ORDER BY sort ASC";
@@ -2931,7 +2944,7 @@ class SurveyUtil {
 		// Getting all the answers of the users
 		$old_user = '';
 		$answers_of_user = array();
-		$sql = "SELECT * FROM $table_survey_answer WHERE survey_id='".Database::escape_string($_GET['survey_id'])."' ORDER BY user ASC";
+		$sql = "SELECT * FROM $table_survey_answer WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."' ORDER BY user ASC";
 		$result = Database::query($sql);
 		while ($row = Database::fetch_array($result)) {
 			if ($old_user != $row['user'] && $old_user != '') {
@@ -2975,9 +2988,9 @@ class SurveyUtil {
 				} else {
 					$user_displayed = '-';
 				}
-				echo '		<th><a href="'.api_get_self().'?action=userreport&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.$user.'">'.$user_displayed.'</a></th>'; // the user column
+				echo '<th><a href="'.api_get_self().'?action=userreport&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.$user.'">'.$user_displayed.'</a></th>'; // the user column
 			} else {
-				echo '		<th>'.$user.'</th>'; // the user column
+				echo '<th>'.$user.'</th>'; // the user column
 			}
 		} else {
 			echo '<th>-</th>';
@@ -2997,8 +3010,7 @@ class SurveyUtil {
 					echo '<td align="center">';
 					echo $answers_of_user[$question_id]['0']['option_id'];
 					echo '</td>';
-				}
-				else {
+				} else {
 					foreach ($possible_option as $option_id => & $value) {
 						if ($questions[$question_id]['type'] == 'percentage') {
 							if (!empty($answers_of_user[$question_id][$option_id])) {
@@ -3057,12 +3069,11 @@ class SurveyUtil {
 
 		$sql = "SELECT questions.question_id, questions.type, questions.survey_question, count(options.question_option_id) as number_of_options
 				FROM $table_survey_question questions LEFT JOIN $table_survey_question_option options
-				ON questions.question_id = options.question_id "
-				." WHERE questions.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
-				questions.c_id = $course_id AND
-				options.c_id = $course_id	
-				GROUP BY questions.question_id "
-				." ORDER BY questions.sort ASC";
+				ON questions.question_id = options.question_id  AND options.c_id = $course_id
+				WHERE   questions.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
+				        questions.c_id = $course_id					
+				GROUP BY questions.question_id 
+				ORDER BY questions.sort ASC";
 		$result = Database::query($sql);
 		while ($row = Database::fetch_array($result)) {
 			// We show the questions if
@@ -3100,11 +3111,9 @@ class SurveyUtil {
 						survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
 				FROM $table_survey_question survey_question
 				LEFT JOIN $table_survey_question_option survey_question_option
-				ON survey_question.question_id = survey_question_option.question_id
+				ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id
 				WHERE survey_question.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
-				survey_question.c_id = $course_id AND
-				survey_question_option.c_id = $course_id			
-				
+				survey_question.c_id = $course_id								
 				ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
 		$result = Database::query($sql);
 		$possible_answers = array();
@@ -3128,7 +3137,7 @@ class SurveyUtil {
 		// Getting all the answers of the users
 		$old_user = '';
 		$answers_of_user = array();
-		$sql = "SELECT * FROM $table_survey_answer WHERE survey_id='".Database::escape_string($_GET['survey_id'])."'";
+		$sql = "SELECT * FROM $table_survey_answer WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."'";
 		if ($user_id != 0) {
 			$sql .= "AND user='".Database::escape_string($user_id)."' ";
 		}
@@ -3260,11 +3269,10 @@ class SurveyUtil {
 
 		// First line (questions)
 		$sql = "SELECT questions.question_id, questions.type, questions.survey_question, count(options.question_option_id) as number_of_options
-				FROM $table_survey_question questions LEFT JOIN $table_survey_question_option options ON questions.question_id = options.question_id 
+				FROM $table_survey_question questions LEFT JOIN $table_survey_question_option options 
+				     ON questions.question_id = options.question_id AND options.c_id = $course_id    
 				WHERE questions.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
-				questions.c_id = $course_id AND
-				options.c_id = $course_id	
-				
+				questions.c_id = $course_id
 				GROUP BY questions.question_id 
 				ORDER BY questions.sort ASC";
 		$result = Database::query($sql);
@@ -3304,10 +3312,9 @@ class SurveyUtil {
 						survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
 				FROM $table_survey_question survey_question
 				LEFT JOIN $table_survey_question_option survey_question_option
-				ON survey_question.question_id = survey_question_option.question_id
+				ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id
 				WHERE survey_question.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
-				survey_question.c_id = $course_id AND
-				survey_question_option.c_id = $course_id				
+				survey_question.c_id = $course_id								
 				ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
 		$result = Database::query($sql);
 		$possible_answers = array();
@@ -3332,7 +3339,7 @@ class SurveyUtil {
 		$column = 0;
 		$old_user = '';
 		$answers_of_user = array();
-		$sql = "SELECT * FROM $table_survey_answer WHERE survey_id='".Database::escape_string($_GET['survey_id'])."' ";
+		$sql = "SELECT * FROM $table_survey_answer WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."' ";
 		if ($user_id != 0) {
 			$sql .= "AND user='".Database::escape_string($user_id)."' ";
 		}
@@ -3608,13 +3615,14 @@ class SurveyUtil {
 	 * @version February 2007 - Updated March 2008
 	 */
 	function get_answers_of_question_by_user($survey_id, $question_id) {
+	    $course_id = api_get_course_int_id();
 		// Database table definitions
 		$table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
 		$table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
 		$table_survey_answer 			= Database :: get_course_table(TABLE_SURVEY_ANSWER);
 
 		$sql = "SELECT * FROM $table_survey_answer
-					WHERE survey_id='".Database::escape_string($survey_id)."'
+					WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'
 					AND question_id='".Database::escape_string($question_id)."'
 					ORDER BY USER ASC";
 		$result = Database::query($sql);
@@ -3678,6 +3686,7 @@ class SurveyUtil {
 	 * @todo use survey_id parameter instead of $_GET
 	 */
 	function get_survey_invitations_data() {
+	    $course_id = api_get_course_int_id();
 		// Database table definition
 		$table_survey_invitation 		= Database :: get_course_table(TABLE_SURVEY_INVITATION);
 		$table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
@@ -3689,7 +3698,7 @@ class SurveyUtil {
 					'' as col4
 					FROM $table_survey_invitation survey_invitation
 			LEFT JOIN $table_user user ON  survey_invitation.user = user.user_id
-			WHERE survey_invitation.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND session_id='".api_get_session_id()."'  ";
+			WHERE survey_invitation.c_id = $course_id AND survey_invitation.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND session_id='".api_get_session_id()."'  ";
 		$res = Database::query($sql);
 		while ($row = Database::fetch_array($res)) {
 			$survey_invitation_data[] = $row;
@@ -3708,10 +3717,12 @@ class SurveyUtil {
 	 * @version January 2007
 	 */
 	function get_number_of_survey_invitations() {
+	    $course_id = api_get_course_int_id();
+	    
 		// Database table definition
 		$table_survey_invitation 		= Database :: get_course_table(TABLE_SURVEY_INVITATION);
 
-		$sql = "SELECT count(user) AS total FROM $table_survey_invitation WHERE survey_id='".Database::escape_string($_GET['survey_id'])."' AND session_id='".api_get_session_id()."' ";
+		$sql = "SELECT count(user) AS total FROM $table_survey_invitation WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."' AND session_id='".api_get_session_id()."' ";
 		$res = Database::query($sql);
 		$row = Database::fetch_array($res,'ASSOC');
 		return $row['total'];
@@ -3727,6 +3738,7 @@ class SurveyUtil {
 	 * @version January 2007
 	 */
 	function save_invite_mail($mailtext, $mail_subject, $reminder = 0) {
+	    $course_id = api_get_course_int_id();
 		// Database table definition
 		$table_survey = Database :: get_course_table(TABLE_SURVEY);
 
@@ -3737,7 +3749,8 @@ class SurveyUtil {
 			$mail_field = 'reminder_mail';
 		}
 
-		$sql = "UPDATE $table_survey SET mail_subject='".Database::escape_string($mail_subject)."', $mail_field = '".Database::escape_string($mailtext)."' WHERE survey_id = '".Database::escape_string($_GET['survey_id'])."'";
+		$sql = "UPDATE $table_survey SET mail_subject='".Database::escape_string($mail_subject)."', $mail_field = '".Database::escape_string($mailtext)."' 
+		        WHERE c_id = $course_id AND survey_id = '".Database::escape_string($_GET['survey_id'])."'";
 		$result = Database::query($sql);
 	}
 
@@ -3880,18 +3893,20 @@ class SurveyUtil {
 	 * @version January 2007
 	 */
 	function update_count_invited($survey_code) {
+	    $course_id = api_get_course_int_id();
+        
 		// Database table definition
 		$table_survey_invitation 	= Database :: get_course_table(TABLE_SURVEY_INVITATION);
 		$table_survey 				= Database :: get_course_table(TABLE_SURVEY);
 
 		// Counting the number of people that are invited
-		$sql = "SELECT count(user) as total FROM $table_survey_invitation WHERE survey_code = '".Database::escape_string($survey_code)."'";
+		$sql = "SELECT count(user) as total FROM $table_survey_invitation WHERE c_id = $course_id AND survey_code = '".Database::escape_string($survey_code)."'";
 		$result = Database::query($sql);
 		$row = Database::fetch_array($result);
 		$total_invited = $row['total'];
 
 		// Updating the field in the survey table
-		$sql = "UPDATE $table_survey SET invited = '".Database::escape_string($total_invited)."' WHERE code = '".Database::escape_string($survey_code)."'";
+		$sql = "UPDATE $table_survey SET invited = '".Database::escape_string($total_invited)."' WHERE c_id = $course_id AND code = '".Database::escape_string($survey_code)."'";
 		$result = Database::query($sql);
 	}
 
@@ -3907,13 +3922,15 @@ class SurveyUtil {
 	 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 	 * @version January 2007
 	 */
-	function get_invited_users($survey_code, $course_db = '') {
-		// Database table definition
-		if (!empty($course_db)) {
-			$table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION,$course_db);
-		} else {
-			$table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
-		}
+	function get_invited_users($survey_code, $course_code = '') {
+	    if (!empty($course_code)) {
+            $course_info = api_get_course_info($course_code);
+            $course_id = $course_info['real_id'];
+        } else {
+            $course_id = api_get_course_int_id();    
+        }
+	    
+	    $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
 	 	$table_user = Database :: get_main_table(TABLE_MAIN_USER);
 
 		// Selecting all the invitations of this survey AND the additional emailaddresses (the left join)
@@ -3921,7 +3938,7 @@ class SurveyUtil {
 		$sql = "SELECT user
 				FROM $table_survey_invitation as table_invitation
 				LEFT JOIN $table_user as table_user
-						ON table_invitation.user = table_user.user_id
+						ON table_invitation.user = table_user.user_id AND table_invitation.c_id = $course_id
 				WHERE survey_code='".Database::escape_string($survey_code)."'".$order_clause;
 
 		$defaults = array();
@@ -3952,10 +3969,11 @@ class SurveyUtil {
 	 * @version September 2007
 	 */
 	function get_invitations($survey_code) {
+	    $course_id = api_get_course_int_id();    
 		// Database table definition
 		$table_survey_invitation 	= Database :: get_course_table(TABLE_SURVEY_INVITATION);
 
-		$sql = "SELECT * FROM $table_survey_invitation WHERE survey_code = '".Database::escape_string($survey_code)."'";
+		$sql = "SELECT * FROM $table_survey_invitation WHERE c_id = $course_id AND survey_code = '".Database::escape_string($survey_code)."'";
 		$result = Database::query($sql);
 		$return = array();
 		while ($row = Database::fetch_array($result)) {
@@ -4182,9 +4200,13 @@ class SurveyUtil {
 	 */
 	function get_number_of_surveys() {
 		global $table_survey;
+        $course_id = api_get_course_int_id();
+        
 		$search_restriction = SurveyUtil::survey_search_restriction();
 		if ($search_restriction) {
-			$search_restriction = 'WHERE '.$search_restriction;
+			$search_restriction = 'WHERE c_id = '.$course_id.' AND '.$search_restriction;
+		} else {
+		    $search_restriction = "WHERE c_id = $course_id";
 		}
 		$sql = "SELECT count(survey_id) AS total_number_of_items FROM ".$table_survey.' '.$search_restriction;
 		$res = Database::query($sql);
@@ -4358,6 +4380,7 @@ class SurveyUtil {
 	 */
 	function survey_list_user($user_id) {
 		global $_course;
+        $course_id = api_get_course_int_id();
 
 		// Database table definitions
 		$table_survey_question   = Database :: get_course_table(TABLE_SURVEY_QUESTION);
@@ -4367,7 +4390,7 @@ class SurveyUtil {
 		$table_user 			 = Database :: get_main_table(TABLE_MAIN_USER);
 		$all_question_id = array();
 
-		$sql = 'SELECT question_id from '.$table_survey_question;
+		$sql = 'SELECT question_id from '.$table_survey_question." WHERE c_id = $course_id";
 		$result = Database::query($sql);
 
 		while($row=Database::fetch_array($result, 'ASSOC')) {
@@ -4377,7 +4400,7 @@ class SurveyUtil {
 		$count = 0;
 		for ($i = 0; $i < count($all_question_id); $i++) {
 			$sql = 'SELECT COUNT(*) as count FROM '.$table_survey_answer.' 
-					WHERE question_id='.Database::escape_string($all_question_id[$i]['question_id']).' AND user='.api_get_user_id();
+					WHERE c_id = '.$course_id.' AND question_id='.Database::escape_string($all_question_id[$i]['question_id']).' AND user='.api_get_user_id();
 			$result = Database::query($sql);
 			while ($row = Database::fetch_array($result, 'ASSOC')) {
 				if ($row['count'] == 0) {
@@ -4390,9 +4413,6 @@ class SurveyUtil {
 				break;
 			}
 		}
-		
-		$course_id = api_get_course_int_id(); 
-
 		echo '<table class="data_table">';
 		echo '<tr>';
 		echo '	<th>'.get_lang('SurveyName').'</th>';

+ 12 - 11
main/survey/survey.php

@@ -19,9 +19,7 @@ require_once '../inc/global.inc.php';
 $this_section = SECTION_COURSES;
 
 // Including additional libraries
-//require_once api_get_path(LIBRARY_PATH).'survey.lib.php';
 require_once 'survey.lib.php';
-require_once api_get_path(LIBRARY_PATH).'course.lib.php';
 
 /** @todo this has to be moved to a more appropriate place (after the display_header of the code)*/
 // Coach can't view this page
@@ -44,6 +42,8 @@ $user_info 						= Database :: get_main_table(TABLE_MAIN_SURVEY_REMINDER); // TO
 
 $survey_id = intval($_GET['survey_id']);
 
+$course_id = api_get_course_int_id();
+
 // Breadcrumbs
 $interbreadcrumb[] = array ('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
 
@@ -77,7 +77,8 @@ if ($is_survey_type_1 && $_GET['action'] == 'addgroup' || $_GET['action'] == 'de
 
 	if (($_GET['action'] == 'addgroup')) {
 		if (!empty($_POST['group_id'])) {
-			Database::query('UPDATE '.$table_survey_question_group.' SET description = \''.Database::escape_string($_POST['description']).'\' WHERE id = \''.Database::escape_string($_POST['group_id']).'\'');
+			Database::query('UPDATE '.$table_survey_question_group.' SET description = \''.Database::escape_string($_POST['description']).'\' 
+			                 WHERE c_id = '.$course_id.' AND id = \''.Database::escape_string($_POST['group_id']).'\'');
 			$sendmsg = 'GroupUpdatedSuccessfully';
 		} elseif(!empty($_POST['name'])) {
 			Database::query('INSERT INTO '.$table_survey_question_group.' (c_id, name,description,survey_id) values ('.$course_id.', \''.Database::escape_string($_POST['name']).'\',\''.Database::escape_string($_POST['description']).'\',\''.Database::escape_string($survey_id).'\') ');
@@ -88,7 +89,7 @@ if ($is_survey_type_1 && $_GET['action'] == 'addgroup' || $_GET['action'] == 'de
 	}
 
 	if ($_GET['action'] == 'deletegroup'){
-		Database::query('DELETE FROM '.$table_survey_question_group.' WHERE id = '.Database::escape_string($_GET['gid']).' and survey_id = '.Database::escape_string($survey_id));
+		Database::query('DELETE FROM '.$table_survey_question_group.' WHERE c_id = '.$course_id.' AND id = '.Database::escape_string($_GET['gid']).' and survey_id = '.Database::escape_string($survey_id));
 		$sendmsg = 'GroupDeletedSuccessfully';
 	}
 	header('Location:survey.php?survey_id='.$survey_id.'&sendmsg='.$sendmsg);
@@ -103,6 +104,7 @@ $my_action_survey		= Security::remove_XSS($_GET['action']);
 $my_question_id_survey  = Security::remove_XSS($_GET['question_id']);
 $my_survey_id_survey    = Security::remove_XSS($_GET['survey_id']);
 $message_information    = Security::remove_XSS($_GET['message']);
+
 if (isset($_GET['action'])) {
 	if (($_GET['action'] == 'moveup' || $_GET['action'] == 'movedown') && isset($_GET['question_id'])) {
 		survey_manager::move_survey_question($my_action_survey,$my_question_id_survey,$my_survey_id_survey);
@@ -176,7 +178,7 @@ echo '	</tr>';
 
 // Displaying the table contents with all the questions
 $question_counter = 1;
-$sql = "SELECT * FROM $table_survey_question_group WHERE survey_id = '".Database::escape_string($survey_id)."' ORDER BY id";
+$sql = "SELECT * FROM $table_survey_question_group WHERE c_id = '.$course_id.' AND survey_id = '".Database::escape_string($survey_id)."' ORDER BY id";
 $result = Database::query($sql);
 $groups = array();
 while ($row = Database::fetch_array($result)) {
@@ -185,13 +187,12 @@ while ($row = Database::fetch_array($result)) {
 $sql = "SELECT survey_question.*, count(survey_question_option.question_option_id) as number_of_options
 			FROM $table_survey_question survey_question
 			LEFT JOIN $table_survey_question_option survey_question_option
-			ON survey_question.question_id = survey_question_option.question_id
-			WHERE 
-			survey_question.survey_id 	= '".Database::escape_string($survey_id)."' AND 
-			survey_question.c_id 		= $course_id AND 
-			survey_question_option.c_id = $course_id
+			ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id
+			WHERE    survey_question.survey_id 	= '".Database::escape_string($survey_id)."' AND 
+			         survey_question.c_id 		= $course_id
 			GROUP BY survey_question.question_id
 			ORDER BY survey_question.sort ASC";
+			
 $result = Database::query($sql);
 $question_counter_max = Database::num_rows($result);
 while ($row = Database::fetch_array($result, 'ASSOC')) {
@@ -275,7 +276,7 @@ if ($is_survey_type_1) {
 	echo '		<th width="100">'.get_lang('Modify').'</th>';
 	echo '	</tr>';
 
-	$sql = 'SELECT id,name,description FROM '.$table_survey_question_group.' WHERE survey_id = '.Database::escape_string($survey_id).' ORDER BY name';
+	$sql = 'SELECT id,name,description FROM '.$table_survey_question_group.' WHERE c_id = '.$course_id.' AND survey_id = '.Database::escape_string($survey_id).' ORDER BY name';
 
 	$rs = Database::query($sql);
 	while($row = Database::fetch_array($rs,ASSOC)){

+ 8 - 8
main/survey/survey_invite.php

@@ -38,7 +38,9 @@ $table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
 $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
 $table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
 $table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
-$user_info 			= Database::get_main_table(TABLE_MAIN_SURVEY_REMINDER); // TODO: To be checked. TABLE_MAIN_SURVEY_REMINDER has not been defined.
+$user_info 			            = Database::get_main_table(TABLE_MAIN_SURVEY_REMINDER); // TODO: To be checked. TABLE_MAIN_SURVEY_REMINDER has not been defined.
+
+$course_id = api_get_course_int_id();
 
 // Getting the survey information
 $survey_id = Security::remove_XSS($_GET['survey_id']);
@@ -70,7 +72,7 @@ Display::display_header($tool_name,'Survey');
 
 // Checking if there is another survey with this code.
 // If this is the case there will be a language choice
-$sql = "SELECT * FROM $table_survey WHERE code='".Database::escape_string($survey_data['code'])."'";
+$sql = "SELECT * FROM $table_survey WHERE c_id = $course_id AND code='".Database::escape_string($survey_data['code'])."'";
 $result = Database::query($sql);
 if (Database::num_rows($result) > 1) {
 	Display::display_warning_message(get_lang('IdenticalSurveycodeWarning'));
@@ -112,15 +114,13 @@ $users->setElementTemplate('
 $users->setButtonAttributes('add', array('class' => 'arrowr'));
 $users->setButtonAttributes('remove', array('class' => 'arrowl'));
 // Additional users
-$form->addElement('textarea', 'additional_users', get_lang('AdditonalUsers'), array('cols' => 50, 'rows' => 2));
-// Additional users comment
-$form->addElement('static', null, null, get_lang('AdditonalUsersComment'));
+$form->addElement('textarea', 'additional_users', array(get_lang('AdditonalUsers'), get_lang('AdditonalUsersComment')), array('cols' => 50, 'rows' => 2));
+
 // The title of the mail
 $form->addElement('text', 'mail_title', get_lang('MailTitle'), array('size' => '80'));
 // The text of the mail
-$form->addElement('html_editor', 'mail_text', get_lang('MailText'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '150'));
-// Some explanation of the mail
-$form->addElement('static', null, null, get_lang('UseLinkSyntax'));
+$form->addElement('html_editor', 'mail_text', array(get_lang('MailText'), get_lang('UseLinkSyntax')), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '150'));
+
 $form->addElement('checkbox', 'send_mail', '', get_lang('SendMail'));
 // You cab send a reminder to unanswered people if the survey is not anonymous
 if ($survey_data['anonymous'] != 1) {

+ 34 - 15
main/template/default/admin/settings_index.tpl

@@ -1,16 +1,35 @@
+<script>
+$(function() {
+    //$("#settings").tabs();
+});
+</script>
 
-{foreach $blocks as $key => $block }
-	<div class="admin_section">
-	<h4>{$block.icon} {$block.label}</h4>
-		<div style="list-style-type:none">
-			{$block.search_form}
-		</div>
-		{if $block.items}
-	    	<ul>
-		    	{foreach $block.items as $url}
-		    		<li><a href="{$url.url}">{$url.label}</a></li>	    	
-				{/foreach}
-			</ul>    	
-    	{/if}
-    </div>
-{/foreach}
+<div id="settings">
+    <!--
+    <ul>
+        <li><a href="#tabs-1">Users</a></li>
+        <li><a href="#tabs-2">Courses</a></li>
+        <li><a href="#tabs-3">Platform</a></li>
+        <li><a href="#tabs-4">Aenean lacinia</a></li>
+        <li><a href="#tabs-5">Aenean lacinia</a></li>
+        <li><a href="#tabs-6">Aenean lacinia</a></li>
+        <li><a href="#tabs-7">Aenean lacinia</a></li>
+        <li><a href="#tabs-8">Aenean lacinia</a></li>        
+    </ul>
+    -->        
+    {foreach $blocks as $key => $block name=block_loop  }        
+        <div id="tabs-{$smarty.foreach.block_loop.index +1}" class="admin_section">
+    	   <h4>{$block.icon} {$block.label}</h4>
+    	   <div style="list-style-type:none">
+    			{$block.search_form}
+    	   </div>
+    		{if $block.items}
+    	    	<ul>
+    		    	{foreach $block.items as $url}
+    		    		<li><a href="{$url.url}">{$url.label}</a></li>	    	
+    				{/foreach}
+    			</ul>    	
+        	{/if}
+        </div>
+    {/foreach}
+</div>

+ 56 - 15
main/template/default/agenda/month.tpl

@@ -29,7 +29,7 @@ $(document).ready(function() {
 		autoOpen: false,
 		modal	: false, 
 		width	: 550, 
-		height	: 400
+		height	: 450
    	});
 
 	var title = $( "#title" ),
@@ -82,13 +82,17 @@ $(document).ready(function() {
 		dayNamesShort: 	{$day_names_short},		
 		selectable	: true,
 		selectHelper: true,
+		//add event
 		select: function(start, end, allDay, jsEvent, view) {
 			/* When selecting one day or several days */
 			
 			var start_date 	= Math.round(start.getTime() / 1000);
 			var end_date 	= Math.round(end.getTime() / 1000);
 			
-			$('#visible_to_input').show();		
+			$('#visible_to_input').show();
+			$('#add_as_announcement_div').show();
+			
+			$('#visible_to_read_only').hide();
 			
 			//Cleans the selected attr 	
 		    clean_user_select();
@@ -115,7 +119,8 @@ $(document).ready(function() {
 					$('#end_date').html(' - ' + end.toDateString());					
 				}
 				$('#color_calendar').html('{$type_label}');
-				$('#color_calendar').addClass('label_tag');
+				$('#color_calendar').removeClass('group_event');
+				$('#color_calendar').addClass('label_tag');				
 				$('#color_calendar').addClass('{$type}_event');
 				
 				allFields.removeClass( "ui-state-error" );		
@@ -123,7 +128,7 @@ $(document).ready(function() {
 				
 				$("#dialog-form").dialog({				
 					buttons: {
-						"Add event": function() {
+						{"Add"|get_lang}: function() {
 							var bValid = true;
 							bValid = bValid && checkLength( title, "title", 1, 255 );
 							//bValid = bValid && checkLength( content, "content", 1, 255 );
@@ -159,7 +164,7 @@ $(document).ready(function() {
 	        
 	    },
 		eventClick: function(calEvent, jsEvent, view) {
-			
+			//edit event
 			if (calEvent.editable) {									
 				var start_date 	= Math.round(calEvent.start.getTime() / 1000);
 				if (calEvent.allDay == 1) {				
@@ -169,10 +174,19 @@ $(document).ready(function() {
 				}
 				
 				$('#visible_to_input').hide();
+				$('#visible_to_read_only').show();				
+				$('#add_as_announcement_div').hide();
+				
+				$("#visible_to_read_only_users").html(calEvent.sent_to);
 				
 				$('#color_calendar').html('{$type_label}');
 				$('#color_calendar').addClass('label_tag');
-				$('#color_calendar').addClass('{$type}_event');
+								
+				$('#color_calendar').removeClass('course_event');
+				$('#color_calendar').removeClass('personal_event');
+				$('#color_calendar').removeClass('group_event');
+				
+				$('#color_calendar').addClass(calEvent.type+'_event');
 				
 				$('#start_date').html(calEvent.start.getDate() +"/"+ calEvent.start.getMonth() +"/"+calEvent.start.getFullYear());
 				
@@ -191,7 +205,7 @@ $(document).ready(function() {
 				
 				$("#dialog-form").dialog({				
 					buttons: {
-						"Edit" : function() {
+						{"Edit"|get_lang} : function() {
 							
 							var bValid = true;
 							bValid = bValid && checkLength( title, "title", 1, 255 );
@@ -203,9 +217,10 @@ $(document).ready(function() {
 								success:function() {
 									calEvent.title 			= $("#title").val();
 									calEvent.start 			= calEvent.start;
-									calEvent.end 			= calEvent.end;
+									calEvent.end 			= calEvent.end;									
 									calEvent.allDay 		= calEvent.allDay;
-									calEvent.description 	= $("#content").val();								
+									calEvent.description 	= $("#content").val();
+																	
 									calendar.fullCalendar('updateEvent', 
 											calEvent,
 											true // make the event "stick"
@@ -215,7 +230,7 @@ $(document).ready(function() {
 								}							
 							});
 						},
-						"Delete": function() { 
+						{"Delete"|get_lang}: function() { 
 							$.ajax({
 								url: delete_url,
 								success:function() {
@@ -258,17 +273,29 @@ $(document).ready(function() {
 
 <div id="dialog-form" style="display:none;">
 	<div style="width:500px">
-	<form id="add_event_form" name="form">	    
-	    {if !empty($visible_to)} 
+	<form id="add_event_form" name="form">
+	      
+	    {if !empty($visible_to) } 
     	    <div id="visible_to_input" class="row">      
                 <div class="label">
                     <label for="date">{"To"|get_lang}</label>
                 </div>
                 <div class="formw">
-                    {$visible_to}
+                    {$visible_to}                    
                 </div>                  
             </div>
         {/if}
+        
+         <div id="visible_to_read_only" class="row" style="display:none">      
+                <div class="label">
+                    <label for="date">{"To"|get_lang}</label>
+                </div>
+                <div class="formw">
+                    <div id="visible_to_read_only_users"></div>                  
+                </div>                  
+         </div>
+        
+          
         	
 		<div class="row">		
 			<div class="label">
@@ -293,7 +320,8 @@ $(document).ready(function() {
 			<div class="formw">
 				<input type="text" name="title" id="title" size="40" />				
 			</div>
-		</div>		
+		</div>
+				
 		<div class="row">
 			<div class="label">
 				<label for="name">{"Description"|get_lang}</label>
@@ -302,8 +330,21 @@ $(document).ready(function() {
 				<textarea name="content" id="content" cols="40" rows="7"></textarea>
 			</div>
 		</div>	
+		
+		{if $type == 'course'}
+		<div id="add_as_announcement_div">
+    		 <div class="row">
+                <div class="label">                    
+                </div>      
+                <div class="formw">
+                    <input type="checkbox" name="add_as_annonuncement" id="add_as_annonuncement" />
+                    <label for="add_as_annonuncement">{"AddAsAnnouncement"|get_lang}</label>
+                </div>
+            </div>
+        </div>
+		{/if}
 	</form>
 	</div>
 </div>
-<div id='loading' style='left:140px;position:absolute; display:none'>{"Loading"|get_lang}...</div>
+<div id='loading' style='left:180px;top:10px;position:absolute; display:none'>{"Loading"|get_lang}...</div>
 <div id='calendar'></div>

+ 47 - 13
main/template/default/auth/courses_categories.php

@@ -20,7 +20,33 @@ $stok = Security::get_token();
     <?php } ?>
 */
 
-if (intval($_GET['hidden_links']) != 1) { ?>
+?>
+
+<script>
+    $(document).ready( function() {
+       $('.star-rating li a').click(function(){
+           
+           var id = $(this).parents('ul').attr('id');
+                      
+           $('#vote_label2_' + id).html('<?php echo Display::return_icon('loading1.gif');?>');
+           
+           $.ajax({
+               url: $(this).attr('rel'),
+               success: function(data) {
+                   if(data == 'added') {                                                
+                        //$('#vote_label_' + id).html('Saved');
+                        $('#vote_label2_' + id).html("<?php echo get_lang('Saved')?>");
+                   }
+                   if(data == 'updated') {
+                        $('#vote_label2_' + id).html("<?php echo get_lang('Saved')?>");
+                   }
+               },
+           })
+       });
+    });
+</script>
+
+<?php if (intval($_GET['hidden_links']) != 1) { ?>
 
 <div id="actions" class="actions">
 	<span id="categories-search">
@@ -110,6 +136,9 @@ if (intval($_GET['hidden_links']) != 1) { ?>
         if (!empty($search_term)) {
             echo "<p><strong>".get_lang('SearchResultsFor')." ".Security::remove_XSS($_POST['search_term'])."</strong><br />";
         }
+        
+        $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
+      
 
         if (!empty($browse_courses_in_category)) {
 
@@ -128,14 +157,13 @@ if (intval($_GET['hidden_links']) != 1) { ?>
                 } else {
                     $course_medium_image = api_get_path(WEB_IMG_PATH).'without_picture.png'; // without picture
                 }
+                
+                $rating = Display::return_rating_system($course['code'].'_rating', $course['point_average'], $ajax_url.'&course_id='.$course['real_id'], $course['users_who_voted']);
 
+                //<div class="course-block-main-item"><div class="left">'.get_lang('Teacher').'</div><div class="course-block-teacher right">'.$tutor_name.'</div></div>
+                //<div class="course-block-main-item"><div class="left">'.get_lang('CreationDate').'</div><div class="course-block-date">'.api_format_date($creation_date,DATE_FORMAT_SHORT).'</div></div>
                 echo '<div class="categories-block-course">
-                        <div class="categories-content-course">
-                            <div class="categories-course-description">
-                                <div class="course-block-title">'.$title.'</div>
-                                <div class="course-block-main-item"><div class="left">'.get_lang('Teacher').'</div><div class="course-block-teacher right">'.$tutor_name.'</div></div>
-                                <div class="course-block-main-item"><div class="left">'.get_lang('CreationDate').'</div><div class="course-block-date">'.api_format_date($creation_date,DATE_FORMAT_SHORT).'</div></div>
-                            </div>';
+                        <div class="categories-content-course">';
                 
                 echo '<div class="categories-course-picture"><center>';
                 if (api_get_setting('show_courses_descriptions_in_catalog') == 'true') {
@@ -144,18 +172,24 @@ if (intval($_GET['hidden_links']) != 1) { ?>
                     echo '</a>';
                 } else {
                     echo '<img src="'.$course_medium_image.'" />';
-                }
-                
-                echo '</center>
-                            </div>
-                            <div class="course-block-popularity"><span>'.get_lang('ConnectionsLastMonth').'</span><div class="course-block-popularity-score">'.$count_connections.'</div></div>';
+                }                
+                echo '</center></div>';
+				
+				
+				echo '<div class="categories-course-description">
+						<div class="course-block-title">'.cut($title, 60).'</div>
+						'.$rating.'
+					 </div>';
+				
+				echo '<div class="course-block-popularity"><span>'.get_lang('ConnectionsLastMonth').'</span><div class="course-block-popularity-score">'.$count_connections.'</div></div>';
                 echo '</div>';
                 
                 echo '<div class="categories-course-links">';
                     // we display the icon to subscribe or the text already subscribed
                     if (!in_array($course['code'], $user_coursecodes)) {
                         if ($course['subscribe'] == SUBSCRIBE_ALLOWED) {
-                            echo '<div class="course-link-desc left"><a class="a_button orange medium" href="'. api_get_self().'?action=subscribe_course&amp;sec_token='.$stok.'&amp;subscribe_course='.$course['code'].'&amp;search_term='.$search_term.'&amp;category_code='.$code.'">'.get_lang('Subscribe').'</a></div>';
+                            echo '<div class="course-link-desc right">
+								<a class="a_button gray small" href="'. api_get_self().'?action=subscribe_course&amp;sec_token='.$stok.'&amp;subscribe_course='.$course['code'].'&amp;search_term='.$search_term.'&amp;category_code='.$code.'">'.get_lang('Subscribe').'</a></div>';
                         }
                     }
                     if (api_get_setting('show_courses_descriptions_in_catalog') == 'true') {

+ 24 - 2
main/template/default/layout/head.tpl

@@ -46,8 +46,30 @@ if ( ( navigator.userAgent.toLowerCase().indexOf('msie') != -1 ) && ( navigator.
 {$favico}
 
 <script type="text/javascript">
-$(document).ready(function(){	
-	$('.topbar').dropdown();	
+$(document).ready(function(){
+	$('.topbar').dropdown();
+
+	$('.ajax').live('click', function() {
+		var url     = this.href;
+		var dialog  = $("#dialog");
+		if ($("#dialog").length == 0) {
+			dialog  = $('<div id="dialog" style="display:hidden"></div>').appendTo('body');
+		}
+
+		// load remote content
+		dialog.load(
+				url,                    
+				{},
+				function(responseText, textStatus, XMLHttpRequest) {
+					dialog.dialog({
+						modal	: true, 
+						width	: 540, 
+						height	: 400,              
+					});	                    
+		});
+		//prevent the browser to follow the link
+		return false;
+	});
 });
 </script>
 

+ 17 - 8
main/template/default/layout/header.tpl

@@ -1,9 +1,11 @@
 <!-- Topbar -->
-{if $_u.status == 1}
+{if $show_toolbar == 1}
     <div class="topbar">
         <div class="topbar-inner">
             <div class="container-fluid">
-                <h3><a href="{'WEB_PATH'|get_path}">Chamilo</a></h3>
+                <h3><a href="{'WEB_PATH'|get_path}">{"siteName"|api_get_setting}</a></h3>
+                
+                {if $_u.logged}
                 <ul class="nav">
                     <li class="active"><a href="{'WEB_PATH'|get_path}/user_portal.php">{"MyCourses"|get_lang}</a></li>
                     <li class="dropdown">
@@ -23,6 +25,7 @@
                             <li><a href="{'WEB_CODE_PATH'|get_path}dashboard/">{"Dashboard"|get_lang}</a></li>
                         </ul>
                     </li>
+                    {if $_u.is_admin == 1}
                     <li class="dropdown">
                         <a class="dropdown-toggle" href="#">{'Administration'|get_lang}</a>
                         <ul class="dropdown-menu">
@@ -33,10 +36,17 @@
                             <li><a href="{'WEB_CODE_PATH'|get_path}admin/settings.php">{"Settings"|get_lang}</a></li>
                         </ul>
                     </li>
-                 </ul>
-                    <form action="{'WEB_CODE_PATH'|get_path}admin/user_list.php" method="get">
-                    <input type="text" placeholder="{'SearchUsers'|get_lang}" name="keyword">
-                    </form>
+                    {/if}
+                </ul>
+                {/if}
+                
+                {if $_u.is_admin == 1}
+                <form action="{'WEB_CODE_PATH'|get_path}admin/user_list.php" method="get">
+                <input type="text" placeholder="{'SearchUsers'|get_lang}" name="keyword">
+                </form>
+                {/if}
+                
+                {if $_u.logged}
                     <ul class="nav secondary-nav">
                         <li><a href="{'WEB_CODE_PATH'|get_path}social/home.php"><img src="{$_u.avatar_small}"/></a></li>
                         <li class="dropdown">
@@ -52,6 +62,7 @@
                         </li>
                         <li><a href="{'WEB_PATH'|get_path}index.php?logout=logout">Logout</a></li>
                     </ul>
+                {/if}
             </div>
         </div><!-- /topbar-inner -->
     </div><!-- /topbar -->
@@ -68,5 +79,3 @@
 
 {* menu *}
 {$header3}
-
-

Vissa filer visades inte eftersom för många filer har ändrats