Browse Source

Merge branch '1.9.x' of github.com:chamilo/chamilo-lms into 1.9.x

Francis Gonzales 11 years ago
parent
commit
f4cfba7aea
54 changed files with 2083 additions and 1628 deletions
  1. 2 2
      main/admin/session_course_edit.php
  2. 35 28
      main/admin/user_import.php
  3. 2 2
      main/admin/usergroup_export.php
  4. 34 22
      main/attendance/attendance_calendar.php
  5. 13 12
      main/attendance/attendance_controller.php
  6. 4 5
      main/attendance/attendance_edit.php
  7. 3 3
      main/auth/inscription.php
  8. 31 25
      main/course_description/course_description_controller.php
  9. 30 13
      main/exercice/admin.php
  10. 244 217
      main/exercice/exercice.php
  11. 53 45
      main/exercice/exercise.class.php
  12. 72 84
      main/exercice/exercise_admin.php
  13. 4 4
      main/exercice/overview.php
  14. 194 161
      main/exercice/question_pool.php
  15. 213 89
      main/exercice/testcategory.class.php
  16. 22 61
      main/exercice/tests_category.php
  17. 26 27
      main/gradebook/lib/be/evaluation.class.php
  18. 5 0
      main/inc/introductionSection.inc.php
  19. 6 5
      main/inc/lib/banner.lib.php
  20. 2 2
      main/inc/lib/course.lib.php
  21. 3 3
      main/inc/lib/events.lib.inc.php
  22. 0 4
      main/inc/lib/formvalidator/Element/DateRangePicker.php
  23. 1 0
      main/inc/lib/formvalidator/Element/datepickerdate.php
  24. 5 0
      main/inc/lib/formvalidator/FormValidator.class.php
  25. 11 28
      main/inc/lib/formvalidator/Rule/Date.php
  26. 8 33
      main/inc/lib/formvalidator/Rule/DateCompare.php
  27. 23 0
      main/inc/lib/formvalidator/Rule/DateTimeRule.php
  28. 33 23
      main/inc/lib/gradebook.lib.php
  29. 1 0
      main/inc/lib/groupmanager.lib.php
  30. 1 2
      main/inc/lib/htmlpurifier/library/HTMLPurifier/Filter/AllowIframes.php
  31. 11 11
      main/inc/lib/main_api.lib.php
  32. 1 0
      main/inc/lib/result_set.class.php
  33. 37 43
      main/inc/lib/surveymanager.lib.php
  34. 177 91
      main/inc/lib/tracking.lib.php
  35. 7 27
      main/inc/lib/usergroup.lib.php
  36. 5 5
      main/inc/lib/usermanager.lib.php
  37. 1 1
      main/newscorm/learnpath.class.php
  38. 1 3
      main/newscorm/lp_view.php
  39. 8 11
      main/newscorm/storageapi.php
  40. 54 45
      main/survey/create_new_survey.php
  41. 175 91
      main/survey/fillsurvey.php
  42. 2 3
      main/survey/generate_link.php
  43. 2 1
      main/survey/index.php
  44. 1 6
      main/survey/link.php
  45. 49 29
      main/survey/preview.php
  46. 26 16
      main/survey/question.php
  47. 27 13
      main/survey/reporting.php
  48. 37 20
      main/survey/survey.download.inc.php
  49. 257 203
      main/survey/survey.lib.php
  50. 44 43
      main/survey/survey.php
  51. 8 22
      main/survey/survey_invitation.php
  52. 15 11
      main/survey/survey_invite.php
  53. 7 7
      main/survey/survey_list.php
  54. 50 26
      main/tracking/course_log_resources.php

+ 2 - 2
main/admin/session_course_edit.php

@@ -94,11 +94,11 @@ if ($_configuration['multiple_access_urls']) {
     $access_url_id = api_get_current_access_url_id();
     $sql="SELECT u.user_id,lastname,firstname,username
         FROM $tbl_user u LEFT JOIN $tbl_access_rel_user  a ON(u.user_id= a.user_id)
-        WHERE status='1' AND access_url_id = $access_url_id ".$order_clause;
+        WHERE status='1' AND active = 1 AND access_url_id = $access_url_id ".$order_clause;
 } else {
     $sql="SELECT user_id,lastname,firstname,username
     FROM $tbl_user
-    WHERE status='1'".$order_clause;
+    WHERE status='1' AND active = 1 ".$order_clause;
 }
 
 $result = Database::query($sql);

+ 35 - 28
main/admin/user_import.php

@@ -30,10 +30,14 @@ function validate_data($users)
 
     // 1. Check if mandatory fields are set.
     $mandatory_fields = array('LastName', 'FirstName');
+
     if (api_get_setting('registration', 'email') == 'true') {
         $mandatory_fields[] = 'Email';
     }
-    foreach ($users as $index => $user) {
+    $classExistList = array();
+    $usergroup = new UserGroup();
+
+    foreach ($users as $user) {
         foreach ($mandatory_fields as $field) {
             if (empty($user[$field])) {
                 $user['error'] = get_lang($field.'Mandatory');
@@ -65,17 +69,24 @@ function validate_data($users)
             $user['error'] = get_lang('WrongStatus');
             $errors[] = $user;
         }
-        // 4. Check classname
-        $usergroup = new UserGroup();
-        if (!empty($user['ClassName'])) {
-            $className = explode('|', trim($user['ClassName']));
-            foreach ($className as $class) {
-                if (!$usergroup->usergroup_exists($class)) {
-                    $user['error'] = get_lang('ClassNameNotAvailable');
+
+        // 4. Check ClassId
+        if (!empty($user['ClassId'])) {
+            $classId = explode('|', trim($user['ClassId']));
+            foreach ($classId as $id) {
+                if (in_array($id, $classExistList)) {
+                    continue;
+                }
+                $info = $usergroup->get($id);
+                if (empty($info)) {
+                    $user['error'] = sprintf(get_lang('ClassIdDoesntExists'), $id);
                     $errors[] = $user;
+                } else {
+                    $classExistList[] = $info['id'];
                 }
             }
         }
+
         // 5. Check authentication source
         if (!empty($user['AuthSource'])) {
             if (!in_array($user['AuthSource'], $defined_auth_sources)) {
@@ -84,6 +95,7 @@ function validate_data($users)
             }
         }
     }
+
     return $errors;
 }
 
@@ -128,6 +140,7 @@ function save_data($users)
         $inserted_in_course = array();
     }
     require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
+    $usergroup = new UserGroup();
     $send_mail = $_POST['sendMail'] ? true : false;
     if (is_array($users)) {
         foreach ($users as $user) {
@@ -176,17 +189,13 @@ function save_data($users)
                     }
                 }
             }
-            $usergroup = new UserGroup();
-            if (!empty($user['ClassName'])) {
-                $className = explode('|', trim($user['ClassName']));
-                foreach ($className as $class) {
-                    $classId = $usergroup->get_id_by_name($class);
-                    $usergroup->addUser($user_id, $classId);
+            if (!empty($user['ClassId'])) {
+                $classId = explode('|', trim($user['ClassId']));
+                foreach ($classId as $id) {
+                    $usergroup->subscribe_users_to_usergroup($id, array($user_id), false);
                 }
-                
             }
 
-
             // Saving extra fields.
             global $extra_fields;
 
@@ -306,14 +315,14 @@ if (is_array($extAuthSource)) {
 }
 
 $tool_name = get_lang('ImportUserListXMLCSV');
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 
 set_time_limit(0);
 $extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
 $user_id_error = array();
 $error_message = '';
 
-if ($_POST['formSent'] and $_FILES['import_file']['size'] !== 0) {
+if (isset($_POST['formSent']) && $_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
     $file_type = $_POST['file_type'];
     Security::clear_token();
     $tok = Security::get_token();
@@ -413,14 +422,14 @@ $group[] = $form->createElement(
     '',
     'CSV (<a href="example.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)',
     'csv'
-    );
+);
 $group[] = $form->createElement(
     'radio',
     'file_type',
     null,
     'XML (<a href="example.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)',
     'xml'
-    );
+);
 $form->addGroup($group, '', get_lang('FileType'), '<br/>');
 
 $group = array();
@@ -455,17 +464,14 @@ if ($count_fields > 0) {
 
 ?>
     <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
-
     <blockquote>
 <pre>
-<b>LastName</b>;<b>FirstName</b>;<b>Email</b>;UserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;<span style="color:red;"><?php if (count($list) > 0) echo implode(';', $list).';'; ?></span>Courses;
-<b>xxx</b>;<b>xxx</b>;<b>xxx</b>;xxx;xxx;<?php echo implode('/', $defined_auth_sources); ?>;xxx;xxx;user/teacher/drh;<span style="color:red;"><?php if (count($list_reponse) > 0) echo implode(';', $list_reponse).';'; ?></span>xxx1|xxx2|xxx3;<br />
+<b>LastName</b>;<b>FirstName</b>;<b>Email</b>;UserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;<span style="color:red;"><?php if (count($list) > 0) echo implode(';', $list).';'; ?></span>Courses;ClassId;
+<b>xxx</b>;<b>xxx</b>;<b>xxx</b>;xxx;xxx;<?php echo implode('/', $defined_auth_sources); ?>;xxx;xxx;user/teacher/drh;<span style="color:red;"><?php if (count($list_reponse) > 0) echo implode(';', $list_reponse).';'; ?></span>xxx1|xxx2|xxx3;1;<br />
 </pre>
-    </blockquote>
-
-    <p><?php echo get_lang('XMLMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
-
-    <blockquote>
+</blockquote>
+<p><?php echo get_lang('XMLMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
+<blockquote>
 <pre>
 &lt;?xml version=&quot;1.0&quot; encoding=&quot;<?php echo api_refine_encoding_id(api_get_system_encoding()); ?>&quot;?&gt;
 &lt;Contacts&gt;
@@ -480,6 +486,7 @@ if ($count_fields > 0) {
         &lt;PhoneNumber&gt;xxx&lt;/PhoneNumber&gt;
         &lt;Status&gt;user/teacher/drh<?php if ($result_xml != '') { echo '<br /><span style="color:red;">', $result_xml; echo '</span>'; } ?>&lt;/Status&gt;
         &lt;Courses&gt;xxx1|xxx2|xxx3&lt;/Courses&gt;
+        &lt;ClassId&gt;1&lt;/ClassId&gt;
         &lt;/Contact&gt;
 &lt;/Contacts&gt;
 </pre>

+ 2 - 2
main/admin/usergroup_export.php

@@ -30,7 +30,7 @@ $form->addElement('style_submit_button', 'submit', get_lang('Export'), 'class="s
 
 if ($form->validate()) {
     $user_group = new UserGroup;
-    $header = array(array('name', 'description'));
+    $header = array(array('id', 'name', 'description'));
     $data = $user_group->get_all_for_export();
     $data = array_merge($header, $data);
     $filename = 'export_classes_'.api_get_local_time();
@@ -39,4 +39,4 @@ if ($form->validate()) {
 }
 Display :: display_header($tool_name);
 $form->display();
-Display::display_footer();
+Display::display_footer();

+ 34 - 22
main/attendance/attendance_calendar.php

@@ -15,12 +15,12 @@ if (isset($_SESSION['gradebook'])) {
 	$param_gradebook = '&gradebook='.Security::remove_XSS($_SESSION['gradebook']);
 }
 if (!$is_locked_attendance || api_is_platform_admin()) {
-	echo '<div class="actions">';	
+	echo '<div class="actions">';
 	if ($action == 'calendar_add') {
 		echo '<a href="index.php?'.api_get_cidreq().'&action=calendar_list&attendance_id='.$attendance_id.$param_gradebook.'">'.Display::return_icon('back.png',get_lang('AttendanceCalendar'),'',ICON_SIZE_MEDIUM).'</a>';
 	} else {
 		echo '<a href="index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance_id.$param_gradebook.'">'.Display::return_icon('back.png',get_lang('AttendanceSheet'),'',ICON_SIZE_MEDIUM).'</a>';
-		
+
 		echo '<a href="index.php?'.api_get_cidreq().'&action=calendar_add&attendance_id='.$attendance_id.$param_gradebook.'">'.Display::return_icon('add.png',get_lang('AddDateAndTime'),'',ICON_SIZE_MEDIUM).'</a>';
 		echo '<a onclick="javascript:if(!confirm(\''.get_lang('AreYouSureToDeleteAllDates').'\')) return false;" href="index.php?'.api_get_cidreq().'&action=calendar_all_delete&attendance_id='.$attendance_id.$param_gradebook.'">'.Display::return_icon('clean.png',get_lang('CleanCalendar'),'',ICON_SIZE_MEDIUM).'</a>';
 	}
@@ -47,14 +47,21 @@ if ($error_checkdate) {
 }
 
 if (isset($action) && $action == 'calendar_add') {
-	// calendar add form		
+	// calendar add form
     $form = new FormValidator('attendance_calendar_add','POST','index.php?action=calendar_add&attendance_id='.$attendance_id.$param_gradebook.'&'.api_get_cidreq(),'');
     $form->addElement('header', get_lang('AddADateTime'));
-    $form->addElement('datepicker', 'date_time', '', array('form_name'=>'attendance_calendar_add'), 5);
+    $form->addElement('date_time_picker', 'date_time');
     $defaults['date_time'] = date('Y-m-d H:i', api_strtotime(api_get_local_time()));
 
-    $form->addElement('checkbox', 'repeat', null, get_lang('RepeatDate'),  array('onclick' => "javascript: if(this.checked){document.getElementById('repeat-date-attendance').style.display='block';}else{document.getElementById('repeat-date-attendance').style.display='none';}",
-    ));
+    $form->addElement(
+        'checkbox',
+        'repeat',
+        null,
+        get_lang('RepeatDate'),
+        array(
+            'onclick' => "javascript: if(this.checked){document.getElementById('repeat-date-attendance').style.display='block';}else{document.getElementById('repeat-date-attendance').style.display='none';}",
+        )
+    );
 
     $defaults['repeat'] = $repeat;
 
@@ -62,36 +69,41 @@ if (isset($action) && $action == 'calendar_add') {
         $form->addElement('html', '<div id="repeat-date-attendance" style="display:block">');
     } else {
         $form->addElement('html', '<div id="repeat-date-attendance" style="display:none">');
-    }        
-    $a_repeat_type = array('daily'=>get_lang('RepeatDaily'), 'weekly'=>get_lang('RepeatWeekly'), 'monthlyByDate'=>get_lang('RepeatMonthlyByDate'));        
+    }
+    $a_repeat_type = array(
+        'daily' => get_lang('RepeatDaily'),
+        'weekly' => get_lang('RepeatWeekly'),
+        'monthlyByDate' => get_lang('RepeatMonthlyByDate')
+    );
     $form->addElement('select', 'repeat_type', get_lang('RepeatType') , $a_repeat_type);
-    $form->addElement('datepickerdate', 'end_date_time', get_lang('RepeatEnd'), array('form_name'=>'attendance_calendar_add'));
-    $defaults['end_date_time'] = date('Y-m-d 12:00:00');        
+
+    $form->addElement('date_picker', 'end_date_time', get_lang('RepeatEnd'), array('form_name'=>'attendance_calendar_add'));
+    $defaults['end_date_time'] = date('Y-m-d');
     $form->addElement('html', '</div>');
 
     $defaults['repeat_type'] = 'weekly';
 
     $form->addElement('style_submit_button', null, get_lang('Save'), 'class="save"');
     $form->setDefaults($defaults);
-    $form->display();	
+    $form->display();
 } else {
 	// calendar list
     echo Display::page_subheader(get_lang('CalendarList'));
-	echo '<div class="attendance-calendar-list">';	
+	echo '<div class="attendance-calendar-list">';
 	if (!empty($attendance_calendar)) {
-		foreach ($attendance_calendar as $calendar) {	
-			echo '<div class="attendance-calendar-row">';				
+		foreach ($attendance_calendar as $calendar) {
+			echo '<div class="attendance-calendar-row">';
 				if ((isset($action) && $action == 'calendar_edit') && (isset($calendar_id) && $calendar_id == $calendar['id'])) {
-					// calendar edit form				
-					echo '<div class="attendance-calendar-edit">';				
-						$form = new FormValidator('attendance_calendar_edit','POST','index.php?action=calendar_edit&attendance_id='.$attendance_id.'&calendar_id='.$calendar_id.'&'.api_get_cidreq().$param_gradebook,'');					
-						$form->addElement('datepicker', 'date_time', '', array('form_name'=>'attendance_calendar_edit'), 5);
+					// calendar edit form
+					echo '<div class="attendance-calendar-edit">';
+						$form = new FormValidator('attendance_calendar_edit','POST','index.php?action=calendar_edit&attendance_id='.$attendance_id.'&calendar_id='.$calendar_id.'&'.api_get_cidreq().$param_gradebook,'');
+						$form->addElement('date_time_picker', 'date_time', '', array('form_name'=>'attendance_calendar_edit'), 5);
 						$defaults['date_time'] = $calendar['date_time'];
 						$form->addElement('style_submit_button', null, get_lang('Save'), 'class="save"');
 						$form->addElement('style_submit_button', 'cancel', get_lang('Cancel'), 'class="cancel"');
 						$form->setDefaults($defaults);
 						$form->display();
-					echo '</div>';						
+					echo '</div>';
 				} else {
 					echo Display::return_icon('lp_calendar_event.png', get_lang('DateTime')).' '.substr($calendar['date_time'], 0, strlen($calendar['date_time'])- 3) .'&nbsp;';
 					if (!$is_locked_attendance || api_is_platform_admin()) {
@@ -100,11 +112,11 @@ if (isset($action) && $action == 'calendar_add') {
                         echo '<a onclick="javascript:if(!confirm(\''.get_lang('AreYouSureToDelete').'\')) return false;" href="index.php?'.api_get_cidreq().$param_gradebook.'&action=calendar_delete&calendar_id='.intval($calendar['id']).'&attendance_id='.$attendance_id.'">'.Display::return_icon('delete.png', get_lang('Delete'), array('style'=>'vertical-align:middle'), ICON_SIZE_SMALL).'</a>';
                         echo '</span>';
                     }
-				}	
+				}
 			echo '</div>';
 		}
 	} else {
 		echo Display::return_message(get_lang('ThereAreNoRegisteredDatetimeYet'), 'warning');
 	}
-	echo '</div>';			
-}
+	echo '</div>';
+}

+ 13 - 12
main/attendance/attendance_controller.php

@@ -316,20 +316,21 @@
 				if (!isset($_POST['cancel'])) {
                     if (isset($_POST['repeat'])) {
                         //@todo  check this error_logs
-                        $start_datetime = api_strtotime(api_get_utc_datetime($attendance->build_datetime_from_array($_POST['date_time'])),'UTC');
-                        //error_log('$start_datetime '.$start_datetime);
+                        $start_datetime = api_strtotime(
+                            api_get_utc_datetime($_POST['date_time']), 'UTC'
+                        );
 
-                        $_POST['end_date_time']['H'] = $_POST['date_time']['H'];
-                        $_POST['end_date_time']['i'] = $_POST['date_time']['i'];
-                        //error_log($attendance->build_datetime_from_array($_POST['end_date_time']));
-
-                        $end_datetime = api_strtotime(api_get_utc_datetime($attendance->build_datetime_from_array($_POST['end_date_time'])),'UTC');
-                        //error_log('$end_datetime '.$end_datetime);
-                        $checkdate = checkdate($_POST['end_date_time']['F'], $_POST['end_date_time']['d'], $_POST['end_date_time']['Y']);
+                        $end_datetime = api_strtotime(api_get_utc_datetime($_POST['end_date_time'].' 23:59:59'), 'UTC');
+                        $checkdate = api_is_valid_date(api_get_utc_datetime($_POST['end_date_time'].' 23:59:59'));
 
                         $repeat_type = $_POST['repeat_type'];
                         if (($end_datetime > $start_datetime) && $checkdate) {
-                            $affected_rows = $attendance->attendance_repeat_calendar_add($attendance_id, $start_datetime, $end_datetime, $repeat_type);
+                            $affected_rows = $attendance->attendance_repeat_calendar_add(
+                                $attendance_id,
+                                $start_datetime,
+                                $end_datetime,
+                                $repeat_type
+                            );
                             $action = 'calendar_list';
                         } else {
                             if (!$checkdate) {
@@ -341,7 +342,7 @@
                             $action = 'calendar_add';
                         }
                     } else {
-                        $datetime = $attendance->build_datetime_from_array($_POST['date_time']);
+                        $datetime = $_POST['date_time'];
                         $datetimezone = api_get_utc_datetime($datetime);
                         if (!empty($datetime)) {
 	                       $attendance->set_date_time($datetimezone);
@@ -545,4 +546,4 @@
         Export::export_html_to_pdf($content, $params);
         exit;
     }
-}
+}

+ 4 - 5
main/attendance/attendance_edit.php

@@ -7,7 +7,6 @@
 * @package chamilo.attendance
 */
 
-
 // protect a course script
 api_protect_course_script(true);
 
@@ -41,15 +40,15 @@ $form->add_html_editor('description', get_lang('Description'), false, false, arr
 if (Gradebook::is_active()) {
     if (!empty($attendance_qualify_title) || !empty($attendance_weight)) {
         $advanced = '<a href="javascript://" class="advanced_parameters"><span id="img_plus_and_minus">&nbsp;'.Display::return_icon('div_hide.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).' '.get_lang('AdvancedParameters').'</span></a>';
-        $form->addElement('advanced_settings',$advanced);    
-    
-	$form->addElement('html','<div id="id_qualify" style="display:block">');    
+        $form->addElement('advanced_settings',$advanced);
+
+	$form->addElement('html','<div id="id_qualify" style="display:block">');
 	$form->addElement('checkbox', 'attendance_qualify_gradebook', '', get_lang('QualifyAttendanceGradebook'),array('checked'=>'true','onclick'=>'javascript: if(this.checked){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}'));
 	$form->addElement('html','<div id="options_field" style="display:block">');
     } else {
 	$advanced = '<a href="javascript://" class="advanced_parameters"><span id="img_plus_and_minus">&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).' '.get_lang('AdvancedParameters').'</span></a>';
         $form->addElement('advanced_settings',$advanced);
-	$form->addElement('html','<div id="id_qualify" style="display:none">');    
+	$form->addElement('html','<div id="id_qualify" style="display:none">');
 	$form->addElement('checkbox', 'attendance_qualify_gradebook', '', get_lang('QualifyAttendanceGradebook'),'onclick="javascript: if(this.checked){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"');
 	$form->addElement('html','<div id="options_field" style="display:none">');
     }

+ 3 - 3
main/auth/inscription.php

@@ -544,13 +544,13 @@ if ($form->validate()) {
                     $form_data['button'] = Display::button('next', get_lang('GoToCourse', null, $_user['language']), array('class' => 'btn btn-primary btn-large'));
 
                     $exercise_redirect = intval(Session::read('exercise_redirect'));
-
-                    if (!empty($exercise_redirect)) {
+                    $objExercise = new Exercise();
+                    $result = $objExercise->read($exercise_id);
+                    if (!empty($exercise_redirect) && !empty($result)) {
                         $form_data['action'] = api_get_path(WEB_CODE_PATH).'exercice/overview.php?exerciseId='.intval($exercise_redirect).'&cidReq='.$course_info['code'];
                         $form_data['message'] .= '<br />'.get_lang('YouCanAccessTheExercise');
                         $form_data['button'] = Display::button('next', get_lang('Go', null, $_user['language']), array('class' => 'btn btn-primary btn-large'));
                     }
-
                     if (!empty($form_data['action'])) {
                         header('Location: '.$form_data['action']);
                         exit;

+ 31 - 25
main/course_description/course_description_controller.php

@@ -25,32 +25,38 @@ class CourseDescriptionController { // extends Controller {
 		$this->view = new View($this->toolname);			
 	}
 
-	/**
-	 * It's used for listing course description,
-	 * render to listing view
-	 * @param boolean   	true for listing history (optional)
-	 * @param array 	message for showing by action['edit','add','destroy'] (optional) 
-	 */
-	public function listing($history=false, $messages=array()) {
-		$course_description = new CourseDescription();
-		$session_id = api_get_session_id();
-		$course_description->set_session_id($session_id);        
-		$data = array();		
+    /**
+     * It's used for listing course description,
+     * render to listing view
+     * @param boolean   	true for listing history (optional)
+     * @param array 	message for showing by action['edit','add','destroy'] (optional) 
+     */
+    public function listing($history=false, $messages=array()) {
+        $course_description = new CourseDescription();
+        $session_id = api_get_session_id();
+        $course_description->set_session_id($session_id);        
+        $data = array();		
 
-		$course_description_data = $course_description->get_description_data();	
+        $course_description_data = $course_description->get_description_data();	
         	
-		$data['descriptions'] = $course_description_data['descriptions'];
-		$data['default_description_titles'] = $course_description->get_default_description_title();
-		$data['default_description_title_editable'] = $course_description->get_default_description_title_editable();
-		$data['default_description_icon'] = $course_description->get_default_description_icon();		
-		$data['messages'] = $messages;
-		
-		// render to the view
-		$this->view->set_data($data);
-		$this->view->set_layout('layout'); 
-		$this->view->set_template('listing');		       
-		$this->view->render();				
-	}
+        $data['descriptions'] = $course_description_data['descriptions'];
+        $data['default_description_titles'] = $course_description->get_default_description_title();
+        $data['default_description_title_editable'] = $course_description->get_default_description_title_editable();
+        $data['default_description_icon'] = $course_description->get_default_description_icon();		
+        $data['messages'] = $messages;
+
+        // Fix for chrome XSS filter for videos in iframes - BT#7930
+        $browser = api_get_navigator();
+        if (strpos($data['descriptions'], '<iframe') !== false && $browser['name'] == 'Chrome') {
+            header('X-XSS-Protection: 0');
+        }
+        
+        // render to the view
+        $this->view->set_data($data);
+        $this->view->set_layout('layout'); 
+        $this->view->set_template('listing');		       
+        $this->view->render();				
+    }
 	
 	/**
 	 * It's used for editing a course description,
@@ -229,4 +235,4 @@ class CourseDescriptionController { // extends Controller {
 		}
 		$this->listing(false, $message);		
 	}
-}
+}

+ 30 - 13
main/exercice/admin.php

@@ -66,6 +66,7 @@ $this_section = SECTION_COURSES;
 api_protect_course_script(true);
 
 $is_allowedToEdit = api_is_allowed_to_edit(null,true);
+$sessionId = api_get_session_id();
 
 if (!$is_allowedToEdit) {
 	api_not_allowed(true);
@@ -166,7 +167,7 @@ if (!empty($_GET['action']) && $_GET['action'] == 'exportqti2' && !empty($_GET['
 	exit; //otherwise following clicks may become buggy
 }
 
-// intializes the Exercise object
+// Exercise object creation.
 if (!is_object($objExercise)) {
 	// construction of the Exercise object
 	$objExercise = new Exercise();
@@ -176,7 +177,14 @@ if (!is_object($objExercise)) {
 	    $objExercise->read($exerciseId);
 	}
 	// saves the object into the session
-	Session::write('objExercise',$objExercise);
+	Session::write('objExercise', $objExercise);
+}
+
+// Exercise can be edited in their course.
+if ($objExercise->sessionId != $sessionId) {
+    api_not_allowed(true);
+    /*header('Location: '.api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidreq());
+    exit;*/
 }
 
 // doesn't select the exercise ID if we come from the question pool
@@ -189,7 +197,7 @@ if (!$fromExercise) {
 
 $nbrQuestions = $objExercise->selectNbrQuestions();
 
-// intializes the Question object
+// Question object creation.
 if ($editQuestion || $newQuestion || $modifyQuestion || $modifyAnswers) {
 	if ($editQuestion || $newQuestion) {
 
@@ -219,7 +227,7 @@ if ($cancelExercise) {
 	} else {
         // new exercise
 		// goes back to the exercise list
-		header('Location: exercice.php');
+		header('Location: '.api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidreq());
 		exit();
 	}
 }
@@ -290,7 +298,10 @@ if (isset($_GET['newQuestion']) || isset($_GET['editQuestion']) ) {
 
 // shows a link to go back to the question pool
 if (!$exerciseId && $nameTools != get_lang('ExerciseManagement')){
-	$interbreadcrumb[]=array("url" => "question_pool.php?fromExercise=$fromExercise","name" => get_lang('QuestionPool'));
+	$interbreadcrumb[]=array(
+        "url" => api_get_path(WEB_CODE_PATH)."exercice/question_pool.php?fromExercise=$fromExercise&".api_get_cidreq(),
+        "name" => get_lang('QuestionPool')
+    );
 }
 
 // if the question is duplicated, disable the link of tool name
@@ -451,19 +462,22 @@ $inATest = isset($exerciseId) && $exerciseId > 0;
 if ($inATest) {
     echo '<div class="actions">';
     if (isset($_GET['hotspotadmin']) || isset($_GET['newQuestion']) || isset($_GET['myid']))
-        echo '<a href="admin.php?exerciseId='.$exerciseId.'&'.api_get_cidReq().'">'.Display::return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
+        echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/admin.php?exerciseId='.$exerciseId.'&'.api_get_cidReq().'">'.
+            Display::return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
 
     if (!isset($_GET['hotspotadmin']) && !isset($_GET['newQuestion']) && !isset($_GET['myid']) &&  !isset($_GET['editQuestion'])) {
-        echo '<a href="exercice.php?'.api_get_cidReq().'">'.Display::return_icon('back.png', get_lang('BackToExercisesList'),'',ICON_SIZE_MEDIUM).'</a>';
+        echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidReq().'">'.
+            Display::return_icon('back.png', get_lang('BackToExercisesList'),'',ICON_SIZE_MEDIUM).'</a>';
     }
-    echo '<a href="overview.php?'.api_get_cidreq().'&exerciseId='.$objExercise->id.'&preview=1">'.Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_MEDIUM).'</a>';
+    echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/overview.php?'.api_get_cidreq().'&exerciseId='.$objExercise->id.'&preview=1">'.
+        Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_MEDIUM).'</a>';
 
     echo Display::url(
         Display::return_icon('test_results.png', get_lang('Results'),'',ICON_SIZE_MEDIUM),
-        'exercise_report.php?'.api_get_cidReq().'&exerciseId='.$objExercise->id
+        api_get_path(WEB_CODE_PATH).'exercice/exercise_report.php?'.api_get_cidReq().'&exerciseId='.$objExercise->id
     );
 
-    echo '<a href="exercise_admin.php?'.api_get_cidreq().'&modifyExercise=yes&exerciseId='.$objExercise->id.'">'.
+    echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/exercise_admin.php?'.api_get_cidreq().'&modifyExercise=yes&exerciseId='.$objExercise->id.'">'.
         Display::return_icon('settings.png', get_lang('ModifyExercise'),'',ICON_SIZE_MEDIUM).'</a>';
 
     $maxScoreAllQuestions = 0;
@@ -480,12 +494,15 @@ if ($inATest) {
 } else if (isset($_GET['newQuestion'])) {
 	// we are in create a new question from question pool not in a test
 	echo '<div class="actions">';
-	echo '<a href="admin.php?'.api_get_cidreq().'">.'.Display::return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
+	echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/admin.php?'.api_get_cidreq().'">'.
+        Display::return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
 	echo '</div>';
 } else {
-	// If we are in question_poolbut not in an test, go back to question create in pool
+	// If we are in question_pool but not in an test, go back to question create in pool
 	echo '<div class="actions">';
-	echo '<a href="question_pool.php">'.Display::return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
+	echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/question_pool.php?'.api_get_cidreq().'">'.
+        Display::return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).
+        '</a>';
 	echo '</div>';
 }
 

+ 244 - 217
main/exercice/exercice.php

@@ -414,23 +414,25 @@ $total = $total_exercises + $hp_count;
 
 $token = Security::get_token();
 if ($is_allowedToEdit && $origin != 'learnpath') {
-    echo '<a href="exercise_admin.php?'.api_get_cidreq().'">'.Display :: return_icon('new_exercice.png', get_lang('NewEx'), '', ICON_SIZE_MEDIUM).'</a>';
-    echo '<a href="question_create.php?'.api_get_cidreq().'">'.Display :: return_icon('new_question.png', get_lang('AddQ'), '', ICON_SIZE_MEDIUM).'</a>';
+    echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/exercise_admin.php?'.api_get_cidreq().'">'.
+        Display :: return_icon('new_exercice.png', get_lang('NewEx'), '', ICON_SIZE_MEDIUM).'</a>';
+    echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/question_create.php?'.api_get_cidreq().'">'.
+        Display :: return_icon('new_question.png', get_lang('AddQ'), '', ICON_SIZE_MEDIUM).'</a>';
     // Question category
-    echo '<a href="tests_category.php">';
+    echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/tests_category.php?'.api_get_cidreq().'">';
     echo Display::return_icon('question_category_show.gif', get_lang('QuestionCategory'));
     echo '</a>';
-    echo '<a href="question_pool.php">';
+    echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/question_pool.php?'.api_get_cidreq().'">';
     echo Display::return_icon('database.png', get_lang('QuestionPool'), array('style' => 'width:32px'));
     echo '</a>';
 
     //echo Display::url(Display::return_icon('looknfeel.png', get_lang('Media')), 'media.php?' . api_get_cidreq());
     // end question category
-    echo '<a href="hotpotatoes.php?'.api_get_cidreq().'">'.Display :: return_icon('import_hotpotatoes.png', get_lang('ImportHotPotatoesQuiz'), '', ICON_SIZE_MEDIUM).'</a>';
+    echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/hotpotatoes.php?'.api_get_cidreq().'">'.Display :: return_icon('import_hotpotatoes.png', get_lang('ImportHotPotatoesQuiz'), '', ICON_SIZE_MEDIUM).'</a>';
     // link to import qti2 ...
-    echo '<a href="qti2.php?'.api_get_cidreq().'">'.Display :: return_icon('import_qti2.png', get_lang('ImportQtiQuiz'), '', ICON_SIZE_MEDIUM).'</a>';
-    echo '<a href="aiken.php?'.api_get_cidreq().'">'.Display :: return_icon('import_aiken.png', get_lang('ImportAikenQuiz'), '', ICON_SIZE_MEDIUM).'</a>';
-    echo '<a href="upload_exercise.php?'.api_get_cidreq().'">'.Display :: return_icon('import_excel.png', get_lang('ImportExcelQuiz'), '', ICON_SIZE_MEDIUM).'</a>';
+    echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/qti2.php?'.api_get_cidreq().'">'.Display :: return_icon('import_qti2.png', get_lang('ImportQtiQuiz'), '', ICON_SIZE_MEDIUM).'</a>';
+    echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/aiken.php?'.api_get_cidreq().'">'.Display :: return_icon('import_aiken.png', get_lang('ImportAikenQuiz'), '', ICON_SIZE_MEDIUM).'</a>';
+    echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercice/upload_exercise.php?'.api_get_cidreq().'">'.Display :: return_icon('import_excel.png', get_lang('ImportExcelQuiz'), '', ICON_SIZE_MEDIUM).'</a>';
     echo Display::url(
         Display::return_icon(
             'clean_all.png',
@@ -438,7 +440,7 @@ if ($is_allowedToEdit && $origin != 'learnpath') {
             '',
             array(
                 'onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToEmptyAllTestResults'), ENT_QUOTES, $charset))."')) return false;",
-                'href' => 'exercice.php?'.api_get_cidreq().'&choice=clean_all_test&sec_token='.$token
+                'href' => api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidreq().'&choice=clean_all_test&sec_token='.$token
             )
     );
 }
@@ -597,249 +599,269 @@ if (!empty($exercise_list)) {
                 if ($is_allowedToEdit) {
                     $lp_blocked = null;
                 if ($exercise_obj->exercise_was_added_in_lp == true) {
-                        $lp_blocked = Display::div(get_lang('AddedToLPCannotBeAccessed'), array('class' => 'lp_content_type_label'));
-                    }
+                    $lp_blocked = Display::div(get_lang('AddedToLPCannotBeAccessed'), array('class' => 'lp_content_type_label'));
+                }
 
-                    $visibility = api_get_item_visibility($course_info, TOOL_QUIZ, $my_exercise_id);
+                $visibility = api_get_item_visibility($course_info, TOOL_QUIZ, $my_exercise_id);
 
-                    if ($row['active'] == 0 || $visibility == 0) {
-                        $title = Display::tag('font', $cut_title, array('style' => 'color:grey'));
-                    } else {
-                        $title = $cut_title;
-                    }
+                if ($row['active'] == 0 || $visibility == 0) {
+                    $title = Display::tag('font', $cut_title, array('style' => 'color:grey'));
+                } else {
+                    $title = $cut_title;
+                }
 
-                    $count_exercise_not_validated = intval(count_exercise_result_not_validated($my_exercise_id, $course_code, $session_id));
+                $count_exercise_not_validated = intval(count_exercise_result_not_validated($my_exercise_id, $course_code, $session_id));
 
-                    $move = Display::return_icon('all_directions.png',get_lang('Move'), array('class'=>'moved', 'style'=>'margin-bottom:-0.5em;'));
-                    $move = null;
+                $move = Display::return_icon('all_directions.png',get_lang('Move'), array('class'=>'moved', 'style'=>'margin-bottom:-0.5em;'));
+                $move = null;
 
-                    $class_tip = '';
+                $class_tip = '';
 
-                    if (!empty($count_exercise_not_validated)) {
-                        $results_text = $count_exercise_not_validated == 1 ? get_lang('ResultNotRevised') : get_lang('ResultsNotRevised');
-                        $title .= '<span class="exercise_tooltip" style="display: none;">'.$count_exercise_not_validated.' '.$results_text.' </span>';
-                        $class_tip = 'link_tooltip';
+                if (!empty($count_exercise_not_validated)) {
+                    $results_text = $count_exercise_not_validated == 1 ? get_lang('ResultNotRevised') : get_lang('ResultsNotRevised');
+                    $title .= '<span class="exercise_tooltip" style="display: none;">'.$count_exercise_not_validated.' '.$results_text.' </span>';
+                    $class_tip = 'link_tooltip';
+                }
+                //$class_tip = 'exercise_link';
+                $url = $move.'<a '.$alt_title.' class="'.$class_tip.'" id="tooltip_'.$row['id'].'" href="overview.php?'.api_get_cidreq().$myorigin.$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'"><img src="../img/quiz.gif" /> '.$title.' </a>';
+
+                $item = Display::tag('td', $url.' '.$session_img.$lp_blocked);
+
+                //Count number exercice - teacher
+                $sqlquery = "SELECT count(*) FROM $TBL_EXERCICE_QUESTION
+                             WHERE c_id = $course_id AND exercice_id = $my_exercise_id";
+                $sqlresult = Database::query($sqlquery);
+                $rowi = Database :: result($sqlresult, 0);
+
+                if ($session_id == $row['session_id']) {
+                    //Settings
+                    $actions = Display::url(
+                        Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL),
+                        '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'), '', ICON_SIZE_SMALL).'</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
+                    if ($locked == false) {
+                        $actions .= Display::url(
+                            Display::return_icon('clean.png', get_lang('CleanStudentResults'), '', ICON_SIZE_SMALL),
+                            '',
+                            array(
+                                'onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDeleteResults'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;",
+                                'href' => 'exercice.php?'.api_get_cidreq().'&choice=clean_results&sec_token='.$token.'&exerciseId='.$row['id']
+                            )
+                        );
+                    } else {
+                        $actions .= Display::return_icon('clean_na.png', get_lang('ResourceLockedByGradebook'), '', ICON_SIZE_SMALL);
                     }
-                    //$class_tip = 'exercise_link';
-                    $url = $move.'<a '.$alt_title.' class="'.$class_tip.'" id="tooltip_'.$row['id'].'" href="overview.php?'.api_get_cidreq().$myorigin.$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'"><img src="../img/quiz.gif" /> '.$title.' </a>';
-
-                    $item = Display::tag('td', $url.' '.$session_img.$lp_blocked);
-
-                    //Count number exercice - teacher
-                    $sqlquery = "SELECT count(*) FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND exercice_id = $my_exercise_id";
-                    $sqlresult = Database::query($sqlquery);
-                    $rowi = Database :: result($sqlresult, 0);
 
-                    if ($session_id == $row['session_id']) {
-                        //Settings
-                        $actions = Display::url(Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL), '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'), '', ICON_SIZE_SMALL).'</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
-                        if ($locked == false) {
-                            $actions .= Display::url(Display::return_icon('clean.png', get_lang('CleanStudentResults'), '', ICON_SIZE_SMALL), '', array('onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDeleteResults'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;", 'href' => 'exercice.php?'.api_get_cidreq().'&choice=clean_results&sec_token='.$token.'&exerciseId='.$row['id']));
+                    //Visible / invisible
+                    //Check if this exercise was added in a LP
+                    if ($exercise_obj->exercise_was_added_in_lp == true) {
+                        $actions .= Display::return_icon('invisible.png', get_lang('AddedToLPCannotBeAccessed'), '', ICON_SIZE_SMALL);
+                    } else {
+                        if ($row['active'] == 0 || $visibility == 0) {
+                            $actions .= Display::url(Display::return_icon('invisible.png', get_lang('Activate'), '', ICON_SIZE_SMALL), 'exercice.php?'.api_get_cidreq().'&choice=enable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']);
                         } else {
-                            $actions .= Display::return_icon('clean_na.png', get_lang('ResourceLockedByGradebook'), '', ICON_SIZE_SMALL);
+                            // else if not active
+                            $actions .= Display::url(Display::return_icon('visible.png', get_lang('Deactivate'), '', ICON_SIZE_SMALL), 'exercice.php?'.api_get_cidreq().'&choice=disable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']);
                         }
+                    }
+                    // Export qti ...
+                    $actions .= Display::url(Display::return_icon('export_qti2.png', 'IMS/QTI', '', ICON_SIZE_SMALL), 'exercice.php?choice=exportqti2&exerciseId='.$row['id'].'&'.api_get_cidreq());
+                } 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'), '', ICON_SIZE_SMALL).'</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']));
+                }
 
-                        //Visible / invisible
-                        //Check if this exercise was added in a LP
-                    		if ($exercise_obj->exercise_was_added_in_lp == true) {
-                            $actions .= Display::return_icon('invisible.png', get_lang('AddedToLPCannotBeAccessed'), '', ICON_SIZE_SMALL);
-                        } else {
-                            if ($row['active'] == 0 || $visibility == 0) {
-                                $actions .= Display::url(Display::return_icon('invisible.png', get_lang('Activate'), '', ICON_SIZE_SMALL), 'exercice.php?'.api_get_cidreq().'&choice=enable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']);
-                            } else {
-                                // else if not active
-                                $actions .= Display::url(Display::return_icon('visible.png', get_lang('Deactivate'), '', ICON_SIZE_SMALL), 'exercice.php?'.api_get_cidreq().'&choice=disable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']);
-                            }
-                        }
-                        // Export qti ...
-                        $actions .= Display::url(Display::return_icon('export_qti2.png', 'IMS/QTI', '', ICON_SIZE_SMALL), 'exercice.php?choice=exportqti2&exerciseId='.$row['id'].'&'.api_get_cidreq());
+                //Delete
+                if ($session_id == $row['session_id']) {
+                    if ($locked == false) {
+                        $actions .= Display::url(Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL), '', array('onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDelete'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;", 'href' => 'exercice.php?'.api_get_cidreq().'&choice=delete&sec_token='.$token.'&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'), '', ICON_SIZE_SMALL).'</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']));
+                        $actions .= Display::return_icon('delete_na.png', get_lang('ResourceLockedByGradebook'), '', ICON_SIZE_SMALL);
                     }
+                }
 
-                    //Delete
-                    if ($session_id == $row['session_id']) {
-                        if ($locked == false) {
-                            $actions .= Display::url(Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL), '', array('onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDelete'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;", 'href' => 'exercice.php?'.api_get_cidreq().'&choice=delete&sec_token='.$token.'&exerciseId='.$row['id']));
-                        } else {
-                            $actions .= Display::return_icon('delete_na.png', get_lang('ResourceLockedByGradebook'), '', ICON_SIZE_SMALL);
-                        }
+                // Number of questions
+                $random_label = null;
+                if ($row['random'] > 0 || $row['random'] == -1) {
+                    // if random == -1 means use random questions with all questions
+                    $random_number_of_question = $row['random'];
+                    if ($random_number_of_question == -1) {
+                        $random_number_of_question = $rowi;
                     }
-
-                    // Number of questions
-                    $random_label = null;
-                    if ($row['random'] > 0 || $row['random'] == -1) {
-                        // if random == -1 means use random questions with all questions
-                        $random_number_of_question = $row['random'];
-                        if ($random_number_of_question == -1) {
-                            $random_number_of_question = $rowi;
-                        }
-                        if ($row['random_by_category'] > 0) {
-                            $nbQuestionsTotal = Testcategory::getNumberOfQuestionRandomByCategory($my_exercise_id, $random_number_of_question);
-                            $number_of_questions = $nbQuestionsTotal." ";
-                            $number_of_questions .= ($nbQuestionsTotal > 1) ? get_lang("QuestionsLowerCase") : get_lang("QuestionLowerCase");
-                            $number_of_questions .= " - ";
-                            $number_of_questions .= min(Testcategory::getNumberMaxQuestionByCat($my_exercise_id), $random_number_of_question).' '.get_lang('QuestionByCategory');
-                        } else {
-                            $random_label = ' ('.get_lang('Random').') ';
-                            $number_of_questions = $random_number_of_question.' '.$random_label;
-                            //Bug if we set a random value bigger than the real number of questions
-                            if ($random_number_of_question > $rowi) {
-                                $number_of_questions = $rowi.' '.$random_label;
-                            }
-                        }
+                    if ($row['random_by_category'] > 0) {
+                        $nbQuestionsTotal = Testcategory::getNumberOfQuestionRandomByCategory($my_exercise_id, $random_number_of_question);
+                        $number_of_questions = $nbQuestionsTotal." ";
+                        $number_of_questions .= ($nbQuestionsTotal > 1) ? get_lang("QuestionsLowerCase") : get_lang("QuestionLowerCase");
+                        $number_of_questions .= " - ";
+                        $number_of_questions .= min(Testcategory::getNumberMaxQuestionByCat($my_exercise_id), $random_number_of_question).' '.get_lang('QuestionByCategory');
                     } else {
-                        $number_of_questions = $rowi;
+                        $random_label = ' ('.get_lang('Random').') ';
+                        $number_of_questions = $random_number_of_question.' '.$random_label;
+                        //Bug if we set a random value bigger than the real number of questions
+                        if ($random_number_of_question > $rowi) {
+                            $number_of_questions = $rowi.' '.$random_label;
+                        }
                     }
-
-                    //Attempts
-                    //$attempts = get_count_exam_results($row['id']).' '.get_lang('Attempts');
-                    //$item .=  Display::tag('td',$attempts);
-                    $item .= Display::tag('td', $number_of_questions);
                 } else {
-                    // Student only
+                    $number_of_questions = $rowi;
+                }
 
-                    $visibility = api_get_item_visibility($course_info, TOOL_QUIZ, $my_exercise_id);
+                //Attempts
+                //$attempts = get_count_exam_results($row['id']).' '.get_lang('Attempts');
+                //$item .=  Display::tag('td',$attempts);
+                $item .= Display::tag('td', $number_of_questions);
+            } else {
+                // Student only
 
-                    if ($visibility == 0) {
-                        continue;
-                    }
+                $visibility = api_get_item_visibility($course_info, TOOL_QUIZ, $my_exercise_id);
+
+                if ($visibility == 0) {
+                    continue;
+                }
 
-                    $url = '<a '.$alt_title.'  href="overview.php?'.api_get_cidreq().$myorigin.$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'">'.$cut_title.'</a>';
+                $url = '<a '.$alt_title.'  href="overview.php?'.api_get_cidreq().$myorigin.$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'">'.$cut_title.'</a>';
 
-                    //Link of the exercise
-                    $item = Display::tag('td', $url.' '.$session_img);
+                //Link of the exercise
+                $item = Display::tag('td', $url.' '.$session_img);
 
-                    //count number exercise questions
-                    $sqlquery = "SELECT count(*) FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND exercice_id = ".$row['id'];
-                    $sqlresult = Database::query($sqlquery);
-                    $rowi = Database::result($sqlresult, 0);
+                //count number exercise questions
+                $sqlquery = "SELECT count(*) FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND exercice_id = ".$row['id'];
+                $sqlresult = Database::query($sqlquery);
+                $rowi = Database::result($sqlresult, 0);
 
-                    if ($row['random'] > 0) {
-                        $row['random'].' '.api_strtolower(get_lang(($row['random'] > 1 ? 'Questions' : 'Question')));
-                    } else {
-                        //show results student
-                        $rowi.' '.api_strtolower(get_lang(($rowi > 1 ? 'Questions' : 'Question')));
-                    }
+                if ($row['random'] > 0) {
+                    $row['random'].' '.api_strtolower(get_lang(($row['random'] > 1 ? 'Questions' : 'Question')));
+                } else {
+                    //show results student
+                    $rowi.' '.api_strtolower(get_lang(($rowi > 1 ? 'Questions' : 'Question')));
+                }
 
-                    //This query might be improved later on by ordering by the new "tms" field rather than by exe_id
-                    //Don't remove this marker: note-query-exe-results
-                    $qry = "SELECT * FROM $TBL_TRACK_EXERCICES
-                        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
-                                orig_lp_id      = 0 AND
-                                orig_lp_item_id = 0 AND
-                                session_id      =  '".api_get_session_id()."'
+                //This query might be improved later on by ordering by the new "tms" field rather than by exe_id
+                //Don't remove this marker: note-query-exe-results
+                $qry = "SELECT * FROM $TBL_TRACK_EXERCICES
+                        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
+                            orig_lp_id      = 0 AND
+                            orig_lp_item_id = 0 AND
+                            session_id      =  '".api_get_session_id()."'
                         ORDER BY exe_id DESC";
-                    $qryres = Database::query($qry);
-                    $num = Database :: num_rows($qryres);
-
-                    //Hide the results
-                    $my_result_disabled = $row['results_disabled'];
-
-                    //Time limits are on
-                    if ($time_limits) {
-                        // Examn is ready to be taken
-                        if ($is_actived_time) {
-                            //Show results 	697 	$attempt_text = get_lang('LatestAttempt').' : ';
-                            if ($my_result_disabled == 0 || $my_result_disabled == 2) {
-                                //More than one attempt
-                                if ($num > 0) {
-                                    $row_track = Database :: fetch_array($qryres);
-                                    $attempt_text = get_lang('LatestAttempt').' : ';
-                                    $attempt_text .= show_score($row_track['exe_result'], $row_track['exe_weighting']);
-                                } else {
-                                    //No attempts
-                                    $attempt_text = get_lang('NotAttempted');
-                                }
-                            } else {
-                                $attempt_text = get_lang('CantShowResults');
-                            }
-                        } else {
-                            //Quiz not ready due to time limits 	700 	$attempt_text = get_lang('NotAttempted');
-                            //@todo use the is_visible function
-                            if ($row['start_time'] != '0000-00-00 00:00:00' && $row['end_time'] != '0000-00-00 00:00:00') {
-                                $today = time();
-                                $start_time = api_strtotime($row['start_time'], 'UTC');
-                                $end_time = api_strtotime($row['end_time'], 'UTC');
-                                if ($today < $start_time) {
-                                    $attempt_text = sprintf(get_lang('ExerciseWillBeActivatedFromXToY'), api_convert_and_format_date($row['start_time']), api_convert_and_format_date($row['end_time']));
-                                } else {
-                                    if ($today > $end_time) {
-                                        $attempt_text = sprintf(get_lang('ExerciseWasActivatedFromXToY'), api_convert_and_format_date($row['start_time']), api_convert_and_format_date($row['end_time']));
-                                    }
-                                }
+                $qryres = Database::query($qry);
+                $num = Database :: num_rows($qryres);
 
-                            } else {
-                                //$attempt_text = get_lang('ExamNotAvailableAtThisTime');
-                                if ($row['start_time'] != '0000-00-00 00:00:00') {
-                                    $attempt_text = sprintf(get_lang('ExerciseAvailableFromX'), api_convert_and_format_date($row['start_time']));
-                                }
-                                if ($row['end_time'] != '0000-00-00 00:00:00') {
-                                    $attempt_text = sprintf(get_lang('ExerciseAvailableUntilX'), api_convert_and_format_date($row['end_time']));
-                                }
-                            }
-                        }
-                    } else {
-                        //Normal behaviour
-                        //Show results
+                //Hide the results
+                $my_result_disabled = $row['results_disabled'];
+
+                //Time limits are on
+                if ($time_limits) {
+                    // Examn is ready to be taken
+                    if ($is_actived_time) {
+                        //Show results 	697 	$attempt_text = get_lang('LatestAttempt').' : ';
                         if ($my_result_disabled == 0 || $my_result_disabled == 2) {
+                            //More than one attempt
                             if ($num > 0) {
                                 $row_track = Database :: fetch_array($qryres);
                                 $attempt_text = get_lang('LatestAttempt').' : ';
                                 $attempt_text .= show_score($row_track['exe_result'], $row_track['exe_weighting']);
                             } else {
+                                //No attempts
                                 $attempt_text = get_lang('NotAttempted');
                             }
                         } 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');
+                        //Quiz not ready due to time limits 	700 	$attempt_text = get_lang('NotAttempted');
+                        //@todo use the is_visible function
+                        if ($row['start_time'] != '0000-00-00 00:00:00' && $row['end_time'] != '0000-00-00 00:00:00') {
+                            $today = time();
+                            $start_time = api_strtotime($row['start_time'], 'UTC');
+                            $end_time = api_strtotime($row['end_time'], 'UTC');
+                            if ($today < $start_time) {
+                                $attempt_text = sprintf(get_lang('ExerciseWillBeActivatedFromXToY'), api_convert_and_format_date($row['start_time']), api_convert_and_format_date($row['end_time']));
+                            } else {
+                                if ($today > $end_time) {
+                                    $attempt_text = sprintf(get_lang('ExerciseWasActivatedFromXToY'), api_convert_and_format_date($row['start_time']), api_convert_and_format_date($row['end_time']));
+                                }
+                            }
+
                         } else {
-                            $num = $num.' '.get_lang('Results');
+                            //$attempt_text = get_lang('ExamNotAvailableAtThisTime');
+                            if ($row['start_time'] != '0000-00-00 00:00:00') {
+                                $attempt_text = sprintf(get_lang('ExerciseAvailableFromX'), api_convert_and_format_date($row['start_time']));
+                            }
+                            if ($row['end_time'] != '0000-00-00 00:00:00') {
+                                $attempt_text = sprintf(get_lang('ExerciseAvailableUntilX'), api_convert_and_format_date($row['end_time']));
+                            }
                         }
-                        $num = '<span class="tooltip" style="display: none;">'.$num.'</span>';
                     }
-                    $item .= Display::tag('td', $attempt_text);
-
-                    //See results
-                    //$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'),'',ICON_SIZE_SMALL).' </a>';
-                }
-                $class = 'row_even';
-                if ($count % 2) {
-                    $class = 'row_odd';
+                } else {
+                    //Normal behaviour
+                    //Show results
+                    if ($my_result_disabled == 0 || $my_result_disabled == 2) {
+                        if ($num > 0) {
+                            $row_track = Database :: fetch_array($qryres);
+                            $attempt_text = get_lang('LatestAttempt').' : ';
+                            $attempt_text .= show_score($row_track['exe_result'], $row_track['exe_weighting']);
+                        } else {
+                            $attempt_text = get_lang('NotAttempted');
+                        }
+                    } else {
+                        $attempt_text = get_lang('CantShowResults');
+                    }
                 }
 
-                if ($is_allowedToEdit) {
-                    $item .= Display::tag('td', $actions, array('class' => 'td_actions'));
+                $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>';
                 }
-                echo Display::tag('tr', $item, array('id' => 'exercise_list_'.$my_exercise_id, 'class' => $class));
+                $item .= Display::tag('td', $attempt_text);
+
+                //See results
+                //$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'),'',ICON_SIZE_SMALL).' </a>';
+            }
+            $class = 'row_even';
+            if ($count % 2) {
+                $class = 'row_odd';
+            }
 
-                $count++;
-            } // end foreach()
+            if ($is_allowedToEdit) {
+                $item .= Display::tag('td', $actions, array('class' => 'td_actions'));
+            }
+            echo Display::tag('tr', $item, array('id' => 'exercise_list_'.$my_exercise_id, 'class' => $class));
+
+            $count++;
+        } // end foreach()
     }
 }
 // end exercise list
@@ -849,20 +871,25 @@ $hotpotatoes_exist = false;
 if ($is_allowedToEdit) {
     $sql = "SELECT d.path as path, d.comment as comment, ip.visibility as visibility
             FROM $TBL_DOCUMENT d, $TBL_ITEM_PROPERTY ip
-            WHERE   d.c_id = $course_id AND
-                    ip.c_id = $course_id AND
-                    d.id = ip.ref AND
-                    ip.tool = '".TOOL_DOCUMENT."' AND
-                    (d.path LIKE '%htm%') AND
-                    d.path  LIKE '".Database :: escape_string($uploadPath)."/%/%'
-                    LIMIT ".$from.",".$limit; // only .htm or .html files listed
+            WHERE
+                d.c_id = $course_id AND
+                ip.c_id = $course_id AND
+                d.id = ip.ref AND
+                ip.tool = '".TOOL_DOCUMENT."' AND
+                (d.path LIKE '%htm%') AND
+                d.path  LIKE '".Database :: escape_string($uploadPath)."/%/%'
+            LIMIT ".$from.",".$limit; // only .htm or .html files listed
 } else {
     $sql = "SELECT d.path as path, d.comment as comment, ip.visibility as visibility
             FROM $TBL_DOCUMENT d, $TBL_ITEM_PROPERTY ip
-            WHERE d.c_id = $course_id AND
-                    ip.c_id = $course_id AND
-            d.id = ip.ref AND ip.tool = '".TOOL_DOCUMENT."' AND (d.path LIKE '%htm%')
-            AND   d.path  LIKE '".Database :: escape_string($uploadPath)."/%/%' AND ip.visibility='1'
+            WHERE
+                d.c_id = $course_id AND
+                ip.c_id = $course_id AND
+                d.id = ip.ref AND
+                ip.tool = '".TOOL_DOCUMENT."' AND
+                (d.path LIKE '%htm%') AND
+                d.path  LIKE '".Database :: escape_string($uploadPath)."/%/%' AND
+                ip.visibility='1'
             LIMIT ".$from.",".$limit;
 }
 

+ 53 - 45
main/exercice/exercise.class.php

@@ -28,8 +28,8 @@ $debug = false; //All exercise scripts should depend in this debug variable
 
 require_once dirname(__FILE__).'/../inc/lib/exercise_show_functions.lib.php';
 
-class Exercise {
-
+class Exercise
+{
     public $id;
     public $name;
     public $title;
@@ -60,11 +60,12 @@ class Exercise {
     public $is_gradebook_locked = false;
     public $exercise_was_added_in_lp = false;
     public $force_edit_exercise_in_lp = false;
+    public $sessionId = 0;
 
     /**
      * Constructor of the class
      *
-     * @author - Olivier Brouckaert
+     * @author Olivier Brouckaert
      */
     public function Exercise($course_id = null)
     {
@@ -141,6 +142,7 @@ class Exercise {
             $this->text_when_finished       = $object->text_when_finished;
             $this->display_category_name    = $object->display_category_name;
             $this->pass_percentage          = $object->pass_percentage;
+            $this->sessionId = $object->session_id;
 
             $this->is_gradebook_locked      = api_resource_is_locked_by_gradebook($id, LINK_EXERCISE);
 
@@ -202,8 +204,8 @@ class Exercise {
     /**
      * returns the exercise ID
      *
-     * @author - Olivier Brouckaert
-     * @return - integer - exercise ID
+     * @author Olivier Brouckaert
+     * @return int - exercise ID
      */
     function selectId() {
         return $this->id;
@@ -222,7 +224,7 @@ class Exercise {
     /**
      * returns the number of attempts setted
      *
-     * @return numeric - exercise attempts
+     * @return int - exercise attempts
      */
     function selectAttempts() {
         return $this->attempts;
@@ -230,7 +232,7 @@ class Exercise {
 
     /** returns the number of FeedbackType  *
      *  0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
-     * @return numeric - exercise attempts
+     * @return int - exercise attempts
      */
     function selectFeedbackType() {
         return $this->feedback_type;
@@ -529,7 +531,7 @@ class Exercise {
     /**
      * changes the exercise max attempts
      *
-     * @param numeric $attempts - exercise max attempts
+     * @param int $attempts - exercise max attempts
      */
     function updateAttempts($attempts) {
         $this->attempts=$attempts;
@@ -539,9 +541,10 @@ class Exercise {
     /**
      * changes the exercise feedback type
      *
-     * @param numeric $attempts - exercise max attempts
+     * @param int $attempts - exercise max attempts
      */
-    function updateFeedbackType($feedback_type) {
+    function updateFeedbackType($feedback_type)
+    {
         $this->feedback_type=$feedback_type;
     }
 
@@ -551,7 +554,8 @@ class Exercise {
      * @author Olivier Brouckaert
      * @param string $description - exercise description
      */
-    function updateDescription($description) {
+    function updateDescription($description)
+    {
         $this->description=$description;
     }
 
@@ -561,19 +565,23 @@ class Exercise {
      * @author Isaac flores
      * @param int The expired time of the quiz
      */
-    function updateExpiredTime($expired_time) {
+    function updateExpiredTime($expired_time)
+    {
         $this->expired_time = $expired_time;
     }
 
-    function updatePropagateNegative($value) {
+    function updatePropagateNegative($value)
+    {
         $this->propagate_neg = $value;
     }
 
-    function updateReviewAnswers($value) {
+    function updateReviewAnswers($value)
+    {
         $this->review_answers = (isset($value) && $value) ? true : false;
     }
 
-    function updatePassPercentage($value) {
+    function updatePassPercentage($value)
+    {
         $this->pass_percentage = $value;
     }
 
@@ -584,7 +592,8 @@ class Exercise {
      * @param string $sound - exercise sound file
      * @param string $delete - ask to delete the file
      */
-    function updateSound($sound,$delete) {
+    function updateSound($sound,$delete)
+    {
         global $audioPath, $documentPath;
         $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
 
@@ -615,7 +624,8 @@ class Exercise {
      * @author Olivier Brouckaert
      * @param integer $type - exercise type
      */
-    function updateType($type) {
+    function updateType($type)
+    {
         $this->type=$type;
     }
 
@@ -626,7 +636,8 @@ class Exercise {
      * @author Olivier Brouckaert
      * @param integer $random - 0 if not random, otherwise the draws
      */
-    function setRandom($random) {
+    function setRandom($random)
+    {
         /*if ($random == 'all') {
             $random = $this->selectNbrQuestions();
         }*/
@@ -640,7 +651,8 @@ class Exercise {
      * @author Juan Carlos Rana
      * @param integer $random_answers - random answers
      */
-    function updateRandomAnswers($random_answers) {
+    function updateRandomAnswers($random_answers)
+    {
         $this->random_answers = $random_answers;
     }
 
@@ -658,23 +670,26 @@ class Exercise {
      *
      * @author Olivier Brouckaert
      */
-    function disable() {
+    function disable()
+    {
         $this->active=0;
     }
 
-    function disable_results() {
+    function disable_results()
+    {
         $this->results_disabled = true;
     }
 
-    function enable_results() {
+    function enable_results()
+    {
         $this->results_disabled = false;
     }
 
-    function updateResultsDisabled($results_disabled) {
+    function updateResultsDisabled($results_disabled)
+    {
         $this->results_disabled = intval($results_disabled);
     }
 
-
     /**
      * updates the exercise in the data base
      *
@@ -905,7 +920,8 @@ class Exercise {
      * Creates the form to create / edit an exercise
      * @param FormValidator $form
      */
-    function createForm ($form, $type='full') {
+    function createForm($form, $type='full')
+    {
         global $id;
 
         if (empty($type)){
@@ -924,11 +940,12 @@ class Exercise {
         // Title.
         $form->addElement('text', 'exerciseTitle', get_lang('ExerciseName'), array('class' => 'span6','id'=>'exercise_title'));
 
-        $form->addElement('advanced_settings','
-			<a href="javascript://" onclick=" return show_media()">
+        $form->addElement('advanced_settings',
+            '<a href="javascript://" onclick=" return show_media()">
 				<span id="media_icon">
-					<img style="vertical-align: middle;" src="../img/looknfeel.png" alt="" /> '.addslashes(api_htmlentities(get_lang('ExerciseDescription'))).'
-					</span>
+					<img style="vertical-align: middle;" src="../img/looknfeel.png" alt="" />'.
+                    addslashes(api_htmlentities(get_lang('ExerciseDescription'))).'
+                </span>
 			</a>
 		');
 
@@ -1076,7 +1093,7 @@ class Exercise {
             else
                 $form->addElement('html','<div id="start_date_div" style="display:none;">');
 
-            $form->addElement('datepicker', 'start_time', '', array('form_name'=>'exercise_admin'), 5);
+            $form->addElement('date_time_picker', 'start_time');
 
             $form->addElement('html','</div>');
 
@@ -1087,7 +1104,7 @@ class Exercise {
             else
                 $form->addElement('html','<div id="end_date_div" style="display:none;">');
 
-            $form->addElement('datepicker', 'end_time', '', array('form_name'=>'exercise_admin'), 5);
+            $form->addElement('date_time_picker', 'end_time');
             $form->addElement('html','</div>');
 
             //$check_option=$this->selectType();
@@ -1157,8 +1174,8 @@ class Exercise {
         if ($type == 'full') {
             // rules
             $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric');
-            $form->addRule('start_time', get_lang('InvalidDate'), 'date');
-            $form->addRule('end_time', get_lang('InvalidDate'), 'date');
+            $form->addRule('start_time', get_lang('InvalidDate'), 'datetime');
+            $form->addRule('end_time', get_lang('InvalidDate'), 'datetime');
         }
 
         // defaults
@@ -1271,23 +1288,14 @@ class Exercise {
 
         if ($form->getSubmitValue('activate_start_date_check') == 1) {
             $start_time = $form->getSubmitValue('start_time');
-            $start_time['F'] = sprintf('%02d', $start_time['F']);
-            $start_time['i'] = sprintf('%02d', $start_time['i']);
-            $start_time['d'] = sprintf('%02d', $start_time['d']);
-
-            $this->start_time = api_get_utc_datetime($start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00');
-
+            $this->start_time = api_get_utc_datetime($start_time);
         } else {
             $this->start_time = '0000-00-00 00:00:00';
         }
 
         if ($form->getSubmitValue('activate_end_date_check') == 1) {
             $end_time = $form->getSubmitValue('end_time');
-            $end_time['F'] = sprintf('%02d', $end_time['F']);
-            $end_time['i'] = sprintf('%02d', $end_time['i']);
-            $end_time['d'] = sprintf('%02d', $end_time['d']);
-
-            $this->end_time = api_get_utc_datetime($end_time['Y'].'-'.$end_time['F'].'-'.$end_time['d'].' '.$end_time['H'].':'.$end_time['i'].':00');
+            $this->end_time = api_get_utc_datetime($end_time);
         } else {
             $this->end_time   = '0000-00-00 00:00:00';
         }
@@ -3445,7 +3453,7 @@ class Exercise {
         if (api_get_session_id()) {
             $teachers = CourseManager::get_coach_list_from_course_code($coursecode, api_get_session_id());
         } else {
-            $teachers = CourseManager::get_teacher_list_from_course_code($coursecode);
+            $teachers = CourseManager::get_teacher_list_from_course_code($courseInfo['code']);
         }
 
         if (!empty($teachers)) {

+ 72 - 84
main/exercice/exercise_admin.php

@@ -28,112 +28,100 @@ if (!api_is_allowed_to_edit(null,true)) {
 }
 
 $htmlHeadXtra[] = '<script>
-        function advanced_parameters() {
-            if(document.getElementById(\'options\').style.display == \'none\') {
-                document.getElementById(\'options\').style.display = \'block\';
-                document.getElementById(\'img_plus_and_minus\').innerHTML=\' <img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" /> '.addslashes(api_htmlentities(get_lang('AdvancedParameters'))).'\';
-            } else {
-                document.getElementById(\'options\').style.display = \'none\';
-                document.getElementById(\'img_plus_and_minus\').innerHTML=\' <img style="vertical-align:middle;" src="../img/div_show.gif" alt="" /> '.addslashes(api_htmlentities(get_lang('AdvancedParameters'))).'\';
-            }
+    function advanced_parameters() {
+        if(document.getElementById(\'options\').style.display == \'none\') {
+            document.getElementById(\'options\').style.display = \'block\';
+            document.getElementById(\'img_plus_and_minus\').innerHTML=\' <img style="vertical-align:middle;" src="../img/div_hide.gif" alt="" /> '.addslashes(api_htmlentities(get_lang('AdvancedParameters'))).'\';
+        } else {
+            document.getElementById(\'options\').style.display = \'none\';
+            document.getElementById(\'img_plus_and_minus\').innerHTML=\' <img style="vertical-align:middle;" src="../img/div_show.gif" alt="" /> '.addslashes(api_htmlentities(get_lang('AdvancedParameters'))).'\';
         }
+    }
 
-        function FCKeditor_OnComplete( editorInstance ) {
-               if (document.getElementById ( \'HiddenFCK\' + editorInstance.Name )) {
-                  HideFCKEditorByInstanceName (editorInstance.Name);
-               }
-        }
+    function FCKeditor_OnComplete( editorInstance ) {
+       if (document.getElementById ( \'HiddenFCK\' + editorInstance.Name )) {
+          HideFCKEditorByInstanceName (editorInstance.Name);
+       }
+    }
 
-        function HideFCKEditorByInstanceName ( editorInstanceName ) {
-            if (document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className == "HideFCKEditor" )
-            {
-                  document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className = "media";
-            }
+    function HideFCKEditorByInstanceName ( editorInstanceName ) {
+        if (document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className == "HideFCKEditor" ) {
+              document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className = "media";
         }
+    }
 
-        function show_media() {
-            var my_display = document.getElementById(\'HiddenFCKexerciseDescription\').style.display;
-                if(my_display== \'none\' || my_display == \'\') {
-                    document.getElementById(\'HiddenFCKexerciseDescription\').style.display = \'block\';
-                    document.getElementById(\'media_icon\').innerHTML=\' <img src="../img/looknfeelna.png" alt="" /> '.addslashes(api_htmlentities(get_lang('ExerciseDescription'))).'\';
-                } else {
-                    document.getElementById(\'HiddenFCKexerciseDescription\').style.display = \'none\';
-                    document.getElementById(\'media_icon\').innerHTML=\' <img src="../img/looknfeel.png" alt="" /> '.addslashes(api_htmlentities(get_lang('ExerciseDescription'))).'\';
-                }
+    function show_media() {
+        var my_display = document.getElementById(\'HiddenFCKexerciseDescription\').style.display;
+        if(my_display== \'none\' || my_display == \'\') {
+            document.getElementById(\'HiddenFCKexerciseDescription\').style.display = \'block\';
+            document.getElementById(\'media_icon\').innerHTML=\' <img src="../img/looknfeelna.png" alt="" /> '.addslashes(api_htmlentities(get_lang('ExerciseDescription'))).'\';
+        } else {
+            document.getElementById(\'HiddenFCKexerciseDescription\').style.display = \'none\';
+            document.getElementById(\'media_icon\').innerHTML=\' <img src="../img/looknfeel.png" alt="" /> '.addslashes(api_htmlentities(get_lang('ExerciseDescription'))).'\';
         }
+    }
 
-        function activate_start_date() {
-            if(document.getElementById(\'start_date_div\').style.display == \'none\') {
-                document.getElementById(\'start_date_div\').style.display = \'block\';
-            } else {
-                document.getElementById(\'start_date_div\').style.display = \'none\';
-            }
+    function activate_start_date() {
+        if(document.getElementById(\'start_date_div\').style.display == \'none\') {
+            document.getElementById(\'start_date_div\').style.display = \'block\';
+        } else {
+            document.getElementById(\'start_date_div\').style.display = \'none\';
         }
+    }
 
-        function activate_end_date() {
-            if(document.getElementById(\'end_date_div\').style.display == \'none\') {
-                document.getElementById(\'end_date_div\').style.display = \'block\';
-            } else {
-                document.getElementById(\'end_date_div\').style.display = \'none\';
-            }
+    function activate_end_date() {
+        if(document.getElementById(\'end_date_div\').style.display == \'none\') {
+            document.getElementById(\'end_date_div\').style.display = \'block\';
+        } else {
+            document.getElementById(\'end_date_div\').style.display = \'none\';
         }
+    }
 
+    function feedbackselection() {
+        var index = document.exercise_admin.exerciseFeedbackType.selectedIndex;
 
-        function feedbackselection() {
-            var index = document.exercise_admin.exerciseFeedbackType.selectedIndex;
-
-            if (index == \'1\') {
-                document.exercise_admin.exerciseType[1].checked=true;
-                document.exercise_admin.exerciseType[0].disabled=true;
-            } else {
-                document.exercise_admin.exerciseType[0].disabled=false;
-            }
-        }
-
-        function option_time_expired() {
-            if(document.getElementById(\'timercontrol\').style.display == \'none\')
-            {
-              document.getElementById(\'timercontrol\').style.display = \'block\';
-            } else {
-              document.getElementById(\'timercontrol\').style.display = \'none\';
-            }
+        if (index == \'1\') {
+            document.exercise_admin.exerciseType[1].checked=true;
+            document.exercise_admin.exerciseType[0].disabled=true;
+        } else {
+            document.exercise_admin.exerciseType[0].disabled=false;
         }
+    }
 
-         function check_per_page_one() {
-             /*if (document.getElementById(\'divtimecontrol\').style.display==\'none\') {
-                 document.getElementById(\'divtimecontrol\').style.display=\'block\';
-                 document.getElementById(\'divtimecontrol\').display=block;
-                 document.getElementById(\'timecontrol\').display=none;
-             }*/
-             document.getElementById(\'exerciseType_0\').checked=true;
+    function option_time_expired() {
+        if(document.getElementById(\'timercontrol\').style.display == \'none\')
+        {
+          document.getElementById(\'timercontrol\').style.display = \'block\';
+        } else {
+          document.getElementById(\'timercontrol\').style.display = \'none\';
         }
+    }
 
-        function check_per_page_all() {
-            /*if (document.getElementById(\'divtimecontrol\').style.display==\'block\') {
-                document.getElementById(\'divtimecontrol\').style.display=\'none\';
-                document.getElementById(\'enabletimercontroltotalminutes\').value=\'\';
-            }*/
-
-            if (document.getElementById(\'exerciseType_1\') && document.getElementById(\'exerciseType_1\').checked) {
-                document.getElementById(\'exerciseType_0\').checked = true;
-            }
-        }
+    function check_per_page_one() {
+         document.getElementById(\'exerciseType_0\').checked=true;
+    }
 
-        function check_feedback() {
-            if (document.getElementById(\'result_disabled_1\').checked == true) {
-                document.getElementById(\'result_disabled_0\').checked = true;
-            }
+    function check_per_page_all() {
+        if (document.getElementById(\'exerciseType_1\') && document.getElementById(\'exerciseType_1\').checked) {
+            document.getElementById(\'exerciseType_0\').checked = true;
         }
+    }
 
-        function check_direct_feedback() {
-            document.getElementById(\'option_page_one\').checked = true;
+    function check_feedback() {
+        if (document.getElementById(\'result_disabled_1\').checked == true) {
             document.getElementById(\'result_disabled_0\').checked = true;
         }
+    }
 
-        function check_results_disabled() {
-            document.getElementById(\'exerciseType_2\').checked = true;
-        }
-        </script>';
+    function check_direct_feedback() {
+        document.getElementById(\'option_page_one\').checked = true;
+        document.getElementById(\'result_disabled_0\').checked = true;
+    }
+
+    function check_results_disabled() {
+        document.getElementById(\'exerciseType_2\').checked = true;
+    }
+</script>';
 
 // to correct #4029 Random and number of attempt menu empty added window.onload=advanced_parameters;
 $htmlHeadXtra[] = '<script>

+ 4 - 4
main/exercice/overview.php

@@ -27,7 +27,7 @@ $this_section = SECTION_COURSES;
 
 // Notice for unauthorized people.
 api_protect_course_script(true);
-
+$sessionId = api_get_session_id();
 $exercise_id = isset($_REQUEST['exerciseId']) ? intval($_REQUEST['exerciseId']) : 0;
 
 $objExercise = new Exercise();
@@ -72,14 +72,14 @@ if ($origin != 'learnpath') {
 $html = '';
 $message = '';
 
-$is_allowed_to_edit = api_is_allowed_to_edit(null,true);
+$is_allowed_to_edit = api_is_allowed_to_edit(null, true);
 $edit_link = '';
-if ($is_allowed_to_edit ) {
+if ($is_allowed_to_edit && $objExercise->sessionId == $sessionId) {
 	$edit_link = Display::url(Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL), api_get_path(WEB_CODE_PATH).'exercice/admin.php?'.api_get_cidreq().'&id_session='.api_get_session_id().'&exerciseId='.$objExercise->id);
 }
 
 //Exercise name
-$html .= Display::page_header( $objExercise->name.' '.$edit_link);
+$html .= Display::page_header($objExercise->name.' '.$edit_link);
 
 //Exercise description
 if (!empty($objExercise->description)) {

+ 194 - 161
main/exercice/question_pool.php

@@ -29,43 +29,21 @@ $this_section = SECTION_COURSES;
 
 $is_allowedToEdit = api_is_allowed_to_edit(null,true);
 
-if (empty($delete)) {
-    $delete = intval($_GET['delete']);
-}
-if ( empty ( $recup ) ) {
-    $recup = intval($_GET['recup']);
-}
-if ( empty ( $fromExercise ) ) {
-    $fromExercise = intval($_REQUEST['fromExercise']);
-}
-if(isset($_GET['exerciseId'])){
-	$exerciseId = intval($_GET['exerciseId']);
-}
-
-if (isset($_GET['courseCategoryId'])) {
-	$courseCategoryId = intval($_GET['courseCategoryId']);
-}
-
-$exerciseLevel = -1;
-if(isset($_REQUEST['exerciseLevel'])){
-	$exerciseLevel = intval($_REQUEST['exerciseLevel']);
-}
-if(isset($_GET['answerType'])){
-	$answerType = intval($_REQUEST['answerType']);
-}
-$page = 0;
-if(!empty($_GET['page'])){
-	$page = intval($_GET['page']);
-}
-$copy_question = 0;
-if(!empty($_GET['copy_question'])){
-	$copy_question = intval($_GET['copy_question']);
-}
-
-$session_id      		= intval($_GET['session_id']);
-$selected_course        = intval($_GET['selected_course']);
-$course_id_changed		= intval($_GET['course_id_changed']);	// save the id of the previous course selected by user to reset menu if we detect that user change course hub 13-10-2011
-$exercice_id_changed 	= intval($_GET['exercice_id_changed']); // save the id of the previous exercice selected by user to reset menu if we detect that user change course hub 13-10-2011
+$delete = isset($_GET['delete']) ? intval($_GET['delete']) : null;
+$recup = isset($_GET['recup']) ? intval($_GET['recup']) : null;
+$fromExercise = isset($_REQUEST['fromExercise']) ? intval($_REQUEST['fromExercise']) : null;
+$exerciseId = isset($_REQUEST['exerciseId']) ? intval($_REQUEST['exerciseId']) : null;
+$courseCategoryId = isset($_REQUEST['courseCategoryId']) ? intval($_REQUEST['courseCategoryId']) : null;
+$exerciseLevel = isset($_REQUEST['exerciseLevel']) ? intval($_REQUEST['exerciseLevel']) : -1;
+$answerType = isset($_REQUEST['answerType']) ? intval($_REQUEST['answerType']) : null;
+$page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 0;
+$copy_question = isset($_REQUEST['copy_question']) ? intval($_REQUEST['copy_question']) : 0;
+$session_id = isset($_REQUEST['session_id']) ? intval($_REQUEST['session_id']) : null;
+$selected_course = isset($_GET['selected_course']) ? intval($_GET['selected_course']) : null;
+// save the id of the previous course selected by user to reset menu if we detect that user change course hub 13-10-2011
+$course_id_changed = isset($_GET['course_id_changed']) ? intval($_GET['course_id_changed']) : null;
+// save the id of the previous exercice selected by user to reset menu if we detect that user change course hub 13-10-2011
+$exercice_id_changed = isset($_GET['exercice_id_changed']) ? intval($_GET['exercice_id_changed']) : null;
 
 // by default when we go to the page for the first time, we select the current course
 if (!isset($_GET['selected_course']) && !isset($_GET['exerciseId'])) {
@@ -77,16 +55,20 @@ $documentPath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
 // picture path
 $picturePath = $documentPath.'/images';
 
-if(!($objExcercise instanceOf Exercise) && !empty($fromExercise)) {
+if (empty($objExercise) && !empty($fromExercise)) {
     $objExercise = new Exercise();
     $objExercise->read($fromExercise);
 }
 
 $nameTools = get_lang('QuestionPool');
 $interbreadcrumb[] = array("url" => "exercice.php","name" => get_lang('Exercices'));
-$interbreadcrumb[] = array("url" => "admin.php?exerciseId=".$objExercise->id, "name" => $objExercise->name);
 
-$displayMessage = "";	// messag to be displayed if actions succesfull
+if (!empty($objExercise)) {
+    $interbreadcrumb[] = array("url" => "admin.php?exerciseId=".$objExercise->id, "name" => $objExercise->name);
+}
+
+// message to be displayed if actions succesful
+$displayMessage = "";
 if ($is_allowedToEdit) {
 	//Duplicating a Question
 	if (!isset($_POST['recup']) && $copy_question != 0 && isset($fromExercise)) {
@@ -120,6 +102,7 @@ if ($is_allowedToEdit) {
 		}
 		$displayMessage = get_lang('ItemAdded');
 	}
+
 	// deletes a question from the database and all exercises
 	if ($delete) {
 		// Construction of the Question object
@@ -151,18 +134,15 @@ if ($is_allowedToEdit) {
 		Session::write('objExercise', $objExercise);
 //		header("Location: admin.php?".api_get_cidreq()."&exerciseId=$fromExercise");
 //		exit();
-	}
-	else if( isset($_POST['recup']) && is_array($_POST['recup']) && $fromExercise) {
-		$list_recup 		= $_POST['recup'];
+	} else if( isset($_POST['recup']) && is_array($_POST['recup']) && $fromExercise) {
+		$list_recup = $_POST['recup'];
 
 		foreach ($list_recup as $course_id => $question_data) {
-
 			$origin_course_id   = intval($course_id);
 			$origin_course_info = api_get_course_info_by_id($origin_course_id);
 			$current_course     = api_get_course_info();
 
 			foreach ($question_data as $old_question_id) {
-
 				//Reading the source question
 				$old_question_obj = Question::read($old_question_id, $origin_course_id);
 				if ($old_question_obj) {
@@ -273,7 +253,7 @@ foreach($session_list as $item) {
 	$session_select_list[$item['id']] = $item['name'];
 }
 $select_session_html =  Display::select('session_id', $session_select_list, $session_id, $tabAttrParam);
-echo Display::form_row($labelFormRow, $select_session_html);	// hub 13-10-2011
+echo Display::form_row($labelFormRow, $select_session_html);
 
 // Course list, get course list of session, or for course where user is admin
 if (!empty($session_id) && $session_id != '-1') {
@@ -290,12 +270,17 @@ foreach ($course_list as $item) {
 	$course_select_list[$item['id']] .= $item['title'];
 }
 
-$select_course_html =  Display::select('selected_course', $course_select_list, $selected_course, array('class'=>'chzn-select','onchange'=>'mark_course_id_changed(); submit_form(this);'));
+$select_course_html =  Display::select(
+    'selected_course',
+    $course_select_list,
+    $selected_course,
+    array('class'=>'chzn-select','onchange'=>'mark_course_id_changed(); submit_form(this);')
+);
 echo Display::form_row(get_lang('Course'), $select_course_html);
 
 if (empty($selected_course) || $selected_course == '-1') {
     $course_info = api_get_course_info();
-    reset_menu_exo_lvl_type();    // no course selected, reset menu test / difficult� / type de reponse // hub 13-10-2011
+    reset_menu_exo_lvl_type();    // no course selected, reset menu test / difficult� / type de reponse
 }
 else {
 	$course_info = CourseManager::get_course_information_by_id($selected_course);
@@ -310,42 +295,60 @@ $TBL_EXERCICE_QUESTION      = Database::get_course_table(TABLE_QUIZ_TEST_QUESTIO
 $TBL_EXERCICES              = Database::get_course_table(TABLE_QUIZ_TEST);
 $TBL_QUESTIONS              = Database::get_course_table(TABLE_QUIZ_QUESTION);
 $TBL_REPONSES               = Database::get_course_table(TABLE_QUIZ_ANSWER);
-$TBL_CATEGORY               = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);		// hub 13-10-2011
-$TBL_COURSE_REL_CATEGORY	= Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);  // hub 13-10-2011
+$TBL_CATEGORY               = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
+$TBL_COURSE_REL_CATEGORY	= Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
 
 // Get course categories for the selected course
 
 // get category list for the course $selected_course
-$tabCatList = Testcategory::getCategoriesIdAndName($selected_course);
-$selectCourseCateogry = Display::select('courseCategoryId', $tabCatList, $courseCategoryId, array('class'=>'chzn-select','onchange'=>'submit_form(this);'), false);
-echo Display::form_row(get_lang("QuestionCategory"), $selectCourseCateogry);
-
-// Get exercice list for this course
-
-$exercise_list         = get_all_exercises_for_course_id($course_info, $session_id, $selected_course, false);
+$categoryList = Testcategory::getCategoriesIdAndName($selected_course);
+$selectCourseCategory = Display::select(
+    'courseCategoryId',
+    $categoryList,
+    $courseCategoryId,
+    array('class'=>'chzn-select','onchange'=>'submit_form(this);'),
+    false
+);
+echo Display::form_row(get_lang("QuestionCategory"), $selectCourseCategory);
+
+// Get exercise list for this course
+
+$exercise_list = get_all_exercises_for_course_id($course_info, $session_id, $selected_course, false);
 //Exercise List
 $my_exercise_list = array();
 $my_exercise_list['0']  = get_lang('AllExercises');
 $my_exercise_list['-1'] = get_lang('OrphanQuestions');
 if (is_array($exercise_list)) {
-  foreach($exercise_list as $row) {
-		$my_exercise_list[$row['id']] = "";
-    if ($row['id'] ==  $fromExercise && $selected_course == api_get_course_int_id()) {
-    	$my_exercise_list[$row['id']] = ">&nbsp;&nbsp;&nbsp;&nbsp;";	// hub 13-10-2011
+    foreach($exercise_list as $row) {
+        $my_exercise_list[$row['id']] = "";
+        if ($row['id'] ==  $fromExercise && $selected_course == api_get_course_int_id()) {
+            $my_exercise_list[$row['id']] = ">&nbsp;&nbsp;&nbsp;&nbsp;";
+        }
+        $my_exercise_list[$row['id']] .= $row['title'];
     }
-    $my_exercise_list[$row['id']] .= $row['title'];
-  }
 }
 
 if ($exercice_id_changed == 1) {
 	reset_menu_lvl_type();
 }
-$select_exercise_html =  Display::select('exerciseId', $my_exercise_list, $exerciseId, array('class'=>'chzn-select','onchange'=>'mark_exercice_id_changed(); submit_form(this);'), false);
+$select_exercise_html =  Display::select(
+    'exerciseId',
+    $my_exercise_list,
+    $exerciseId,
+    array('class'=>'chzn-select','onchange'=>'mark_exercice_id_changed(); submit_form(this);'),
+    false
+);
 echo Display::form_row(get_lang('Exercise'), $select_exercise_html);
 
 // Difficulty list (only from 0 to 5)
 
-$select_difficulty_html = Display::select('exerciseLevel', array(-1 => get_lang('All'), 0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5), $exerciseLevel, array('class'=>'chzn-select', 'onchange'=>'submit_form(this);'), false);
+$select_difficulty_html = Display::select(
+    'exerciseLevel',
+    array(-1 => get_lang('All'), 0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5),
+    $exerciseLevel,
+    array('class'=>'chzn-select', 'onchange'=>'submit_form(this);'),
+    false
+);
 echo Display::form_row(get_lang('Difficulty'), $select_difficulty_html);
 
 
@@ -385,9 +388,7 @@ echo "<input type='hidden' id='exercice_id_changed' name='exercice_id_changed' v
 <?php
 echo '<input type="hidden" name="course_id" value="'.$selected_course.'">';
 
-
 // if we have selected an exercise in the list-box 'Filter'
-
 if ($exerciseId > 0) {
 	$where = '';
 	$from = '';
@@ -435,14 +436,8 @@ if ($exerciseId > 0) {
 	if (isset($answerType) && $answerType >0 -1 ) {
 		$answer_where = ' AND type='.$answerType;
 	}
-	/*$sql = "SELECT DISTINCT * FROM $TBL_QUESTIONS qu $from
-            WHERE qu.c_id = $selected_course AND qu.id NOT IN (
-              SELECT question_id FROM $TBL_EXERCICE_QUESTION
-              WHERE c_id=$selected_course
-            ) $level_where $answer_where";*/
 
     // @todo fix this query with the new id field
-
     $sql = " (
                 SELECT q.* FROM $TBL_QUESTIONS q INNER JOIN $TBL_EXERCICE_QUESTION r
                 ON (q.c_id = r.c_id AND q.id = r.question_id)
@@ -483,72 +478,74 @@ if ($exerciseId > 0) {
 	if (isset($answerType) && $answerType > 0) {
 		$filter .= ' AND qu.type='.$answerType.' ';
 	}
-  if (!empty($session_id) && $session_id != '-1') {
-    $main_question_list = array();
-    if (!empty($course_list))
-    foreach ($course_list as $course_item) {
-      if (!empty($selected_course) && $selected_course != '-1') {
-          if ($selected_course != $course_item['id']) {
-          	continue;
-          }
-      }
-      $exercise_list = get_all_exercises($course_item, $session_id);
-      if (!empty($exercise_list)) {
-        foreach ($exercise_list as $exercise) {
-          $my_exercise = new Exercise($course_item['id']);
-          $my_exercise->read($exercise['id']);
-          if (!empty($my_exercise)) {
-            if (!empty($my_exercise->questionList)) {
-              foreach ($my_exercise->questionList as $question_id) {
-              	$question_obj = Question::read($question_id, $course_item['id']);
-                if ($exerciseLevel != '-1')
-                if ($exerciseLevel != $question_obj->level) {
-                	continue;
-                }
-                if ($answerType > 0)
-                if ($answerType != $question_obj->type) {
-                	continue;
+    if (!empty($session_id) && $session_id != '-1') {
+        $main_question_list = array();
+        if (!empty($course_list))
+            foreach ($course_list as $course_item) {
+                if (!empty($selected_course) && $selected_course != '-1') {
+                    if ($selected_course != $course_item['id']) {
+                        continue;
+                    }
                 }
-
-                if ($courseCategoryId > 0 && Testcategory::getCategoryForQuestion($question_obj->id, $selected_course)) {
-                	continue;
-                }
-                if ($objExercise->feedback_type != EXERCISE_FEEDBACK_TYPE_DIRECT) {
-                   if ($question_obj->type == HOT_SPOT_DELINEATION)  {
-                     continue;
-                   }
+                $exercise_list = get_all_exercises($course_item, $session_id);
+                if (!empty($exercise_list)) {
+                    foreach ($exercise_list as $exercise) {
+                        $my_exercise = new Exercise($course_item['id']);
+                        $my_exercise->read($exercise['id']);
+                        if (!empty($my_exercise)) {
+                            if (!empty($my_exercise->questionList)) {
+                                foreach ($my_exercise->questionList as $question_id) {
+                                    $question_obj = Question::read($question_id, $course_item['id']);
+                                    if ($exerciseLevel != '-1') {
+                                        if ($exerciseLevel != $question_obj->level) {
+                                            continue;
+                                        }
+                                    }
+
+                                    if ($answerType > 0) {
+                                        if ($answerType != $question_obj->type) {
+                                            continue;
+                                        }
+                                    }
+                                    if ($courseCategoryId > 0 && Testcategory::getCategoryForQuestion($question_obj->id, $selected_course)) {
+                                        continue;
+                                    }
+                                    if ($objExercise->feedback_type != EXERCISE_FEEDBACK_TYPE_DIRECT) {
+                                        if ($question_obj->type == HOT_SPOT_DELINEATION)  {
+                                            continue;
+                                        }
+                                    }
+                                    $question_row = array(
+                                        'id'			=> $question_obj->id,
+                                        'question'		=> $question_obj->question,
+                                        'type'			=> $question_obj->type,
+                                        'level'			=> $question_obj->level,
+                                        'exercise_id'	=> $exercise['id'],
+                                        'course_id'		=> $course_item['id'],
+                                    );
+                                    $main_question_list[] = $question_row;
+                                }
+                            }
+                        }
+                    }
                 }
-                $question_row = array(	'id'			=> $question_obj->id,
-                						'question'		=> $question_obj->question,
-                						'type'			=> $question_obj->type,
-                						'level'			=> $question_obj->level,
-                						'exercise_id'	=> $exercise['id'],
-                						'course_id'		=> $course_item['id'],
-                );
-                $main_question_list[]    = $question_row;
-              }
             }
-          }
+    } else {
+        // All tests for the course selected, not in session
+        $sql = "SELECT DISTINCT qu.id, question, qu.type, level, q.session_id
+                FROM $TBL_QUESTIONS as qu, $TBL_EXERCICE_QUESTION as qt, $TBL_EXERCICES as q $from
+                WHERE
+                  qu.c_id = $selected_course AND
+                    qt.c_id = $selected_course AND
+                    q.c_id = $selected_course AND
+                    qu.id = qt.question_id AND
+                    q.id = qt.exercice_id $filter
+                ORDER BY session_id ASC";
+        $result = Database::query($sql);
+        while($row = Database::fetch_array($result, 'ASSOC')) {
+            $main_question_list[] = $row;
         }
-      }
     }
-  }
-  else {
-  	//
-    // All tests for the course selected, not in session
-            $sql = "SELECT DISTINCT qu.id, question, qu.type, level, q.session_id
-                    FROM $TBL_QUESTIONS as qu, $TBL_EXERCICE_QUESTION as qt, $TBL_EXERCICES as q $from
-                    WHERE   qu.c_id = $selected_course AND
-                            qt.c_id = $selected_course AND
-                            q.c_id = $selected_course AND
-                            qu.id = qt.question_id AND
-                            q.id = qt.exercice_id $filter
-                    ORDER BY session_id ASC";
-  	$result = Database::query($sql);
-  	while($row = Database::fetch_array($result, 'ASSOC')) {
-  		$main_question_list[] = $row;
-  	}
-  }
 	// forces the value to 0
 	$exerciseId=0;
 }
@@ -607,7 +604,6 @@ $header[] = array(get_lang('Difficulty'), false, array("style"=>"text-align:cent
 $header[] = array($actionLabel, false, array("style"=>"text-align:center"), array("style"=>"text-align:center"), '');
 
 $data = array();
-
 if (is_array($main_question_list)) {
     foreach ($main_question_list as $tabQuestion) {
         $row = array();
@@ -623,13 +619,33 @@ if (is_array($main_question_list)) {
         $row[] = $question_type;
         $row[] = get_question_categorie_for_question($selected_course, $tabQuestion['id']);
         $row[] = $tabQuestion['level'];
-        $row[] = get_action_icon_for_question($actionIcon1, $fromExercise, $tabQuestion['id'], $tabQuestion['type'],
-                    $tabQuestion['question'], $selected_course, $courseCategoryId, $exerciseLevel,
-                    $answerType, $session_id, $exerciseId).
+        $row[] = get_action_icon_for_question(
+                    $actionIcon1,
+                    $fromExercise,
+                    $tabQuestion['id'],
+                    $tabQuestion['type'],
+                    $tabQuestion['question'],
+                    $selected_course,
+                    $courseCategoryId,
+                    $exerciseLevel,
+                    $answerType,
+                    $session_id,
+                    $exerciseId
+                ).
                     "&nbsp;".
-                    get_action_icon_for_question($actionIcon2, $fromExercise, $tabQuestion['id'], $tabQuestion['type'],
-                    $tabQuestion['question'], $selected_course, $courseCategoryId, $exerciseLevel, $answerType,
-                    $session_id, $exerciseId);
+                get_action_icon_for_question(
+                    $actionIcon2,
+                    $fromExercise,
+                    $tabQuestion['id'],
+                    $tabQuestion['type'],
+                    $tabQuestion['question'],
+                    $selected_course,
+                    $courseCategoryId,
+                    $exerciseLevel,
+                    $answerType,
+                    $session_id,
+                    $exerciseId
+                );
         $data[] = $row;
     }
 }
@@ -646,13 +662,11 @@ if (!$nbrQuestions) {
 //}
 Display::display_footer();
 
-
-
 // Some functions here, just for question_pool to ease the code
 
 /*
 	Put the menu entry for level and type to default "Choice"
-	It is usefull if you change the exercice, you need to reset the other menus
+	It is useful if you change the exercise, you need to reset the other menus
 	hubert.borderiou 13-10-2011
 */
 function reset_menu_lvl_type() {
@@ -661,8 +675,8 @@ function reset_menu_lvl_type() {
 	$exerciseLevel = -1;
 }
 /*
-	Put the menu entry for exercice and level and type to default "Choice"
-	It is usefull if you change the course, you need to reset the other menus
+	Put the menu entry for exercise and level and type to default "Choice"
+	It is useful if you change the course, you need to reset the other menus
 	hubert.borderiou 13-10-2011
 */
 
@@ -675,7 +689,8 @@ function reset_menu_exo_lvl_type() {
 
 // return the <a> link to admin question, if needed
 // hubert.borderiou 13-10-2011
-function get_a_tag_for_question($in_addA, $in_fromex, $in_questionid, $in_questiontype, $in_questionname) {
+function get_a_tag_for_question($in_addA, $in_fromex, $in_questionid, $in_questiontype, $in_questionname)
+{
 	$res = $in_questionname;
 	if ($in_addA) {
 		$res = "<a href='admin.php?".api_get_cidreq()."&editQuestion=$in_questionid&type=$in_questiontype&fromExercise=$in_fromex'>".$res."</a>";
@@ -702,12 +717,10 @@ $exerciseId).
 get_action_icon_for_question($actionIcon2, $fromExercise, $tabQuestion['id'], $tabQuestion['type'],
 $tabQuestion['question'], $selected_course, $courseCategoryId, $exerciseLevel, $answerType,
 $session_id, $exerciseId);
-
-
 */
 
 /*
-    Return the <a> html code for delete, add, clone, edit a question hubert.borderiou 13-10-2011
+    Return the <a> html code for delete, add, clone, edit a question
     in_action = the code of the action triggered by the button
     from_exercice = the id of the current exercice from which we click on question pool
     in_questionid = the id of the current question
@@ -720,26 +733,42 @@ $session_id, $exerciseId);
     in_session_id = the id of the session_id chosen in the FILTERING MENU
     in_exercice_id = the id of the exercice chosen in the FILTERING MENU
  */
-function get_action_icon_for_question($in_action, $from_exercice, $in_questionid, $in_questiontype, $in_questionname, $in_selected_course, $in_courseCategoryId, $in_exerciseLevel, $in_answerType, $in_session_id, $in_exercice_id) {
-
+function get_action_icon_for_question(
+    $in_action,
+    $from_exercice,
+    $in_questionid,
+    $in_questiontype,
+    $in_questionname,
+    $in_selected_course,
+    $in_courseCategoryId,
+    $in_exerciseLevel,
+    $in_answerType,
+    $in_session_id,
+    $in_exercice_id
+) {
 	$res = "";
 	$getParams = "&selected_course=$in_selected_course&courseCategoryId=$in_courseCategoryId&exerciseId=$in_exercice_id&exerciseLevel=$in_exerciseLevel&answerType=$in_answerType&session_id=$in_session_id";
-
 	switch ($in_action) {
 		case "delete" :
-			$res = "<a href='".api_get_self()."?".api_get_cidreq()."&delete=$in_questionid$getParams' onclick='return confirm_your_choice()'>";
+			$res = "<a href='".api_get_self()."?".api_get_cidreq().$getParams."&delete=$in_questionid' onclick='return confirm_your_choice()'>";
 			$res .= Display::return_icon("delete.png", get_lang('Delete'));
 			$res .= "</a>";
 			break;
 		case "edit" :
-			$res = get_a_tag_for_question(1, $from_exercice, $in_questionid, $in_questiontype, Display::return_icon("edit.png", get_lang('Modify')));
+			$res = get_a_tag_for_question(
+                1,
+                $from_exercice,
+                $in_questionid,
+                $in_questiontype,
+                Display::return_icon("edit.png", get_lang('Modify'))
+            );
 			break;
 		case "add":
 			// add if question is not already in test
 			$myObjEx = new Exercise();
 			$myObjEx->read($from_exercice);
 			if (!$myObjEx->isInList($in_questionid)) {
-				$res = "<a href='".api_get_self()."?".api_get_cidreq()."&recup=$in_questionid&fromExercise=$from_exercice$getParams'>";
+				$res = "<a href='".api_get_self()."?".api_get_cidreq().$getParams."&recup=$in_questionid&fromExercise=$from_exercice'>";
 				$res .= Display::return_icon("view_more_stats.gif", get_lang('InsertALinkToThisQuestionInTheExercise'));
 				$res .= "</a>";
             } else {
@@ -748,7 +777,7 @@ function get_action_icon_for_question($in_action, $from_exercice, $in_questionid
 			unset($myObjEx);
 			break;
 		case "clone":
-			$res = "<a href='".api_get_self()."?".api_get_cidreq()."&amp;copy_question=$in_questionid&course_id=$in_selected_course&fromExercise=$from_exercice$getParams'>";
+			$res = "<a href='".api_get_self()."?".api_get_cidreq().$getParams."&copy_question=$in_questionid&course_id=$in_selected_course&fromExercise=$from_exercice'>";
 			$res .= Display::return_icon('cd.gif', get_lang('ReUseACopyInCurrentTest'));
 			$res .= "</a>";
 			break;
@@ -759,9 +788,12 @@ function get_action_icon_for_question($in_action, $from_exercice, $in_questionid
 	return $res;
 }
 
-/* return the icon for the question type
- hubert.borderiou 13-10-2011*/
-function get_question_type_for_question($in_selectedcourse, $in_questionid) {
+/**
+ * Return the icon for the question type
+ * @author hubert.borderiou 13-10-2011
+ */
+function get_question_type_for_question($in_selectedcourse, $in_questionid)
+{
 	$myObjQuestion = Question::read($in_questionid, $in_selectedcourse);
     $questionType = null;
     if (!empty($myObjQuestion)) {
@@ -774,7 +806,8 @@ function get_question_type_for_question($in_selectedcourse, $in_questionid) {
 
 // return the name of the category for the question in a course
 // hubert.borderiou 13-10-2011
-function get_question_categorie_for_question($in_courseid, $in_questionid) {
+function get_question_categorie_for_question($in_courseid, $in_questionid)
+{
 	$cat = Testcategory::getCategoryNameForQuestion($in_questionid, $in_courseid);
 	return $cat;
 }

+ 213 - 89
main/exercice/testcategory.class.php

@@ -2,6 +2,10 @@
 /* For licensing terms, see /license.txt */
 /** @author hubert.borderiou  **/
 
+/**
+ * Class Testcategory
+ * @todo rename to ExerciseCategory
+ */
 class Testcategory
 {
 	public $id;
@@ -14,15 +18,15 @@ 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="") {
+	public function Testcategory($in_id=0, $in_name = '', $in_description="")
+    {
 		if ($in_id != 0 && $in_name == "") {
 			$tmpobj = new Testcategory();
 			$tmpobj->getCategory($in_id);
 			$this->id = $tmpobj->id;
 			$this->name = $tmpobj->name;
 			$this->description = $tmpobj->description;
-		}
-		else {
+		} else {
 			$this->id = $in_id;
 			$this->name = $in_name;
 			$this->description = $in_description;
@@ -31,7 +35,8 @@ class Testcategory
 
 	/** return the Testcategory object with id=in_id
 	 */
-	function getCategory($in_id) {
+    public function getCategory($in_id)
+    {
 		$t_cattable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
 		$in_id = Database::escape_string($in_id);
 		$sql = "SELECT * FROM $t_cattable WHERE id=$in_id AND c_id=".api_get_course_int_id();
@@ -45,32 +50,39 @@ class Testcategory
 		}
 	}
 
-	/** add Testcategory in the database if name doesn't already exists
-		*/
-	function addCategoryInBDD() {
+	/**
+     * add Testcategory in the database if name doesn't already exists
+	 */
+    public function addCategoryInBDD()
+    {
 		$t_cattable = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
 		$v_name = $this->name;
 		$v_name = Database::escape_string($v_name);
 		$v_description = $this->description;
 		$v_description = Database::escape_string($v_description);
 		// check if name already exists
-		$sql_verif = "SELECT count(*) AS nb FROM $t_cattable WHERE title = '$v_name' AND c_id=".api_get_course_int_id();
-		$result_verif = Database::query($sql_verif);
+		$sql = "SELECT count(*) AS nb FROM $t_cattable
+              WHERE title = '$v_name' AND c_id=".api_get_course_int_id();
+		$result_verif = Database::query($sql);
 		$data_verif = Database::fetch_array($result_verif);
 		// lets add in BDD if not the same name
 		if ($data_verif['nb'] <= 0) {
 			$c_id = api_get_course_int_id();
 			$sql = "INSERT INTO $t_cattable VALUES ('$c_id', '', '$v_name', '$v_description')";
-			$res = Database::query($sql);
-//            $id_cat_added = Database::insert_id();
+			Database::query($sql);
             $new_id = Database::insert_id();
             // add test_category in item_property table
             $course_code = api_get_course_id();
             $course_info = api_get_course_info($course_code);
-            api_item_property_update($course_info, TOOL_TEST_CATEGORY, $new_id, 'TestCategoryAdded', api_get_user_id());
+            api_item_property_update(
+                $course_info,
+                TOOL_TEST_CATEGORY,
+                $new_id,
+                'TestCategoryAdded',
+                api_get_user_id()
+            );
 			return $new_id;
-		}
-		else {
+		} else {
 			return false;
 		}
 	}
@@ -79,12 +91,13 @@ class Testcategory
      * Removes the category from the database
      * if there were question in this category, the link between question and category is removed
 	 */
-    function removeCategory() {
+    public function removeCategory()
+    {
 		$t_cattable = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
         $tbl_question_rel_cat = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_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);
+		Database::query($sql);
 		if (Database::affected_rows() <= 0) {
 			return false;
 		} else {
@@ -99,22 +112,21 @@ class Testcategory
 		}
 	}
 
-
 	/**
      * modify category name or description of category with id=in_id
 	 */
 	//function modifyCategory($in_id, $in_name, $in_description) {
-    function modifyCategory() {
+    public 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);
 		$v_description = Database::escape_string($this->description);
 		$sql = "UPDATE $t_cattable SET title='$v_name', description='$v_description' WHERE id='$v_id' AND c_id=".api_get_course_int_id();
-		$res = Database::query($sql);
+		Database::query($sql);
 		if (Database::affected_rows() <= 0) {
 			return false;
-		}
-		else {
+		} else {
             // item_property update
             $course_code = api_get_course_id();
             $course_info = api_get_course_info($course_code);
@@ -126,7 +138,8 @@ class Testcategory
 	/**
      * Gets the number of question of category id=in_id
 	 */
-	function getCategoryQuestionsNumber() {
+    public 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();
@@ -135,19 +148,24 @@ class Testcategory
 		return $row['nb'];
 	}
 
-	function display($in_color="#E0EBF5") {
+    /**
+     * @param string $in_color
+     */
+    public function display($in_color="#E0EBF5")
+    {
 		echo "<textarea style='background-color:$in_color; width:60%; height:100px;'>";
 		print_r($this);
 		echo "</textarea>";
 	}
 
 
-
-	/** return an array of all Category objects in the database
-	If in_field=="" Return an array of all category objects in the database
-	Otherwise, return an array of all in_field value in the database (in_field = id or name or description)
+	/**
+     * Return an array of all Category objects in the database
+	   If in_field=="" Return an array of all category objects in the database
+	   Otherwise, return an array of all in_field value in the database (in_field = id or name or description)
 	 */
-	public static function getCategoryListInfo($in_field="", $in_courseid="") {
+	public static function getCategoryListInfo($in_field="", $in_courseid="")
+    {
 		if (empty($in_courseid) || $in_courseid=="") {
 			$in_courseid = api_get_course_int_id();
 		}
@@ -161,8 +179,7 @@ class Testcategory
 				$tmpcat = new Testcategory($row['id'], $row['title'], $row['description']);
 				$tabres[] = $tmpcat;
 			}
-		}
-		else {
+		} else {
 			$sql = "SELECT $in_field FROM $t_cattable WHERE c_id=$in_courseid ORDER BY $in_field ASC";
 			$res = Database::query($sql);
 			while ($row = Database::fetch_array($res)) {
@@ -172,14 +189,14 @@ class Testcategory
 		return $tabres;
 	}
 
-
 	/**
 	 Return the testcategory id for question with question_id = $in_questionid
 	 In this version, a question has only 1 testcategory.
 	 Return the testcategory id, 0 if none
 	 */
-	public static function getCategoryForQuestion($in_questionid, $in_courseid="") {
-		$result = 0;	// result
+	public static function getCategoryForQuestion($in_questionid, $in_courseid="")
+    {
+		$result = 0;
 		if (empty($in_courseid) || $in_courseid=="") {
 			$in_courseid = api_get_course_int_id();
 		}
@@ -194,24 +211,24 @@ class Testcategory
 		return $result;
 	}
 
-
 	/**
 	 * true if question id has a category
 	 */
-	public static function isQuestionHasCategory($in_questionid) {
+	public static function isQuestionHasCategory($in_questionid)
+    {
 		if (Testcategory::getCategoryForQuestion($in_questionid) > 0) {
 			return true;
 		}
 		return false;
 	}
 
-
 	/**
 	 Return the category name for question with question_id = $in_questionid
 	 In this version, a question has only 1 category.
 	 Return the category id, "" if none
 	 */
-	public static function getCategoryNameForQuestion($in_questionid, $in_courseid="") {
+	public static function getCategoryNameForQuestion($in_questionid, $in_courseid="")
+    {
 		if (empty($in_courseid) || $in_courseid=="") {
 			$in_courseid = api_get_course_int_id();
 		}
@@ -234,7 +251,8 @@ class Testcategory
 	 * return : array of category id (integer)
 	 * hubert.borderiou 07-04-2011
 	 */
-	public static function getListOfCategoriesIDForTest($in_testid) {
+	public static function getListOfCategoriesIDForTest($in_testid)
+    {
 		// parcourir les questions d'un test, recup les categories uniques dans un tableau
 		$tabcat = array();
 		$quiz = new Exercise();
@@ -250,13 +268,14 @@ class Testcategory
 	}
 
 	/**
-	 * return the list of differents categories NAME for a test
+	 * return the list of different categories NAME for a test
 	 * input : test_id
 	 * return : array of string
 	 * hubert.borderiou 07-04-2011
      * @author function rewrote by jmontoya
 	 */
-	public static function getListOfCategoriesNameForTest($in_testid) {
+	public static function getListOfCategoriesNameForTest($in_testid)
+    {
 		$tabcatName = array();
 		$tabcatID = self::getListOfCategoriesIDForTest($in_testid);
 		for ($i=0; $i < count($tabcatID); $i++) {
@@ -265,24 +284,26 @@ class Testcategory
 		}
 		return $tabcatName;
 	}
+
 	/**
 	 * return the number of differents categories for a test
 	 * input : test_id
 	 * return : integer
 	 * hubert.borderiou 07-04-2011
 	 */
-	public static function getNumberOfCategoriesForTest($in_testid) {
+	public static function getNumberOfCategoriesForTest($in_testid)
+    {
 		return count(Testcategory::getListOfCategoriesIDForTest($in_testid));
 	}
 
-
 	/**
 	 * return the number of question of a category id in a test
 	 * input : test_id, category_id
 	 * return : integer
 	 * hubert.borderiou 07-04-2011
 	 */
-	public static function getNumberOfQuestionsInCategoryForTest($in_testid, $in_categoryid) {
+	public static function getNumberOfQuestionsInCategoryForTest($in_testid, $in_categoryid)
+    {
 		$nbCatResult = 0;
 		$quiz = new Exercise();
 		$quiz->read($in_testid);
@@ -300,9 +321,10 @@ class Testcategory
 	 * return the number of question for a test using random by category
 	 * input  : test_id, number of random question (min 1)
 	 * hubert.borderiou 07-04-2011
-	 * question witout categories are not counted
+	 * question without categories are not counted
 	 */
-	public static function getNumberOfQuestionRandomByCategory($in_testid, $in_nbrandom) {
+	public static function getNumberOfQuestionRandomByCategory($in_testid, $in_nbrandom)
+    {
 		$nbquestionresult = 0;
 		$tabcatid = Testcategory::getListOfCategoriesIDForTest($in_testid);
 		for ($i=0; $i < count($tabcatid); $i++) {
@@ -319,13 +341,13 @@ class Testcategory
 		return $nbquestionresult;
 	}
 
-
 	/**
 	 * Return an array (id=>name)
 	 * tabresult[0] = get_lang('NoCategory');
 	 *
 	 */
-	static function getCategoriesIdAndName($in_courseid="") {
+    public static function getCategoriesIdAndName($in_courseid="")
+    {
 		if (empty($in_courseid) || $in_courseid=="") {
 			$in_courseid = api_get_course_int_id();
 		}
@@ -337,19 +359,26 @@ class Testcategory
 	 	return $tabresult;
 	}
 
-	/**
-		* return an array of question_id for each category
-		* tabres[0] = array of question id with category id = 0 (i.e. no category)
-		* tabres[24] = array of question id with category id = 24
-		* In this version, a question has 0 or 1 category
-	 */
-	function getQuestionsByCat($in_exerciceId) {
+    /**
+    * return an array of question_id for each category
+    * tabres[0] = array of question id with category id = 0 (i.e. no category)
+    * tabres[24] = array of question id with category id = 24
+    * In this version, a question has 0 or 1 category
+    */
+    public function getQuestionsByCat($in_exerciceId)
+    {
 		$tabres = array();
 		$TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
 		$TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
         $in_exerciceId = intval($in_exerciceId);
-		$sql = "SELECT qrc.question_id, qrc.category_id FROM $TBL_QUESTION_REL_CATEGORY qrc, $TBL_EXERCICE_QUESTION eq
-                WHERE exercice_id=$in_exerciceId AND eq.question_id=qrc.question_id AND eq.c_id=".api_get_course_int_id()." AND eq.c_id=qrc.c_id ORDER BY category_id, question_id";
+		$sql = "SELECT qrc.question_id, qrc.category_id
+		        FROM $TBL_QUESTION_REL_CATEGORY qrc, $TBL_EXERCICE_QUESTION eq
+                WHERE
+                    exercice_id=$in_exerciceId AND
+                    eq.question_id=qrc.question_id AND
+                    eq.c_id=".api_get_course_int_id()." AND
+                    eq.c_id=qrc.c_id
+                ORDER BY category_id, question_id";
 		$res = Database::query($sql);
 		while ($data = Database::fetch_array($res)) {
 			if (!is_array($tabres[$data['category_id']])) {
@@ -357,14 +386,15 @@ class Testcategory
 			}
 			$tabres[$data['category_id']][] = $data['question_id'];
 		}
+
 		return $tabres;
 	}
 
-
 	/**
 	 * return a tab of $in_number random elements of $in_tab
 	 */
-	function getNElementsFromArray($in_tab, $in_number) {
+    public function getNElementsFromArray($in_tab, $in_number)
+    {
 		$tabres = $in_tab;
 		shuffle($tabres);
 		if ($in_number < count($tabres)) {
@@ -376,10 +406,16 @@ class Testcategory
 	/**
 	 * display the category
 	 */
-	public static function displayCategoryAndTitle($in_questionID, $in_display_category_name = 1) {
+	public static function displayCategoryAndTitle($in_questionID, $in_display_category_name = 1)
+    {
         echo self::returnCategoryAndTitle($in_questionID, $in_display_category_name);
 	}
 
+    /**
+     * @param $in_questionID
+     * @param int $in_display_category_name
+     * @return null|string
+     */
     public static function returnCategoryAndTitle($in_questionID, $in_display_category_name = 1) {
         $is_student = !(api_is_allowed_to_edit(null,true) || api_is_session_admin());
         // @todo fix $_SESSION['objExercise']
@@ -396,12 +432,12 @@ class Testcategory
         return $content;
 	}
 
-
-	/**
-		* Display signs [+] and/or (>0) after question title if question has options
-		* scoreAlwaysPositive and/or uncheckedMayScore
-		*/
-	function displayQuestionOption($in_objQuestion) {
+    /**
+    * Display signs [+] and/or (>0) after question title if question has options
+    * scoreAlwaysPositive and/or uncheckedMayScore
+    */
+    public function displayQuestionOption($in_objQuestion)
+    {
 		if ($in_objQuestion->type == MULTIPLE_ANSWER && $in_objQuestion->scoreAlwaysPositive) {
 			echo "<span style='font-size:75%'> (>0)</span>";
 		}
@@ -412,11 +448,12 @@ class Testcategory
 
 	/**
 	 * sortTabByBracketLabel ($tabCategoryQuestions)
-	 * key of $tabCategoryQuestions are the categopy id (0 for not in a category)
+	 * key of $tabCategoryQuestions are the category id (0 for not in a category)
 	 * value is the array of question id of this category
 	 * Sort question by Category
 	*/
-	function sortTabByBracketLabel($in_tab) {
+    public function sortTabByBracketLabel($in_tab)
+    {
 		$tabResult = array();
 		$tabCatName = array();	// tab of category name
 		while (list($cat_id, $tabquestion) = each($in_tab)) {
@@ -433,18 +470,20 @@ class Testcategory
 		return $tabResult;
 	}
 
-	/**
-		* return total score for test exe_id for all question in the category $in_cat_id for user
-		* If no question for this category, return ""
-	*/
-	public static function getCatScoreForExeidForUserid($in_cat_id, $in_exe_id, $in_user_id) {
+    /**
+    * return total score for test exe_id for all question in the category $in_cat_id for user
+    * If no question for this category, return ""
+    */
+	public static function getCatScoreForExeidForUserid($in_cat_id, $in_exe_id, $in_user_id)
+    {
 		$tbl_track_attempt		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 		$tbl_question_rel_category = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
         $in_cat_id = intval($in_cat_id);
         $in_exe_id = intval($in_exe_id);
         $in_user_id = intval($in_user_id);
 
-		$query = "SELECT DISTINCT marks, exe_id, user_id, ta.question_id, category_id FROM $tbl_track_attempt ta , $tbl_question_rel_category qrc
+		$query = "SELECT DISTINCT marks, exe_id, user_id, ta.question_id, category_id
+                  FROM $tbl_track_attempt ta , $tbl_question_rel_category qrc
                   WHERE ta.question_id=qrc.question_id AND qrc.category_id=$in_cat_id AND exe_id=$in_exe_id AND user_id=$in_user_id";
 		$res = Database::query($query);
 		$totalcatscore = "";
@@ -454,13 +493,13 @@ class Testcategory
 		return $totalcatscore;
 	}
 
-
     /**
      * return the number max of question in a category
      * count the number of questions in all categories, and return the max
      * @author - hubert borderiou
     */
-    public static function getNumberMaxQuestionByCat($in_testid) {
+    public static function getNumberMaxQuestionByCat($in_testid)
+    {
         $res_num_max = 0;
         // foreach question
 		$tabcatid = Testcategory::getListOfCategoriesIDForTest($in_testid);
@@ -480,7 +519,8 @@ class Testcategory
      * @params int exercise id
      * @params array prefilled array with the category_id, score, and weight example: array(1 => array('score' => '10', 'total' => 20));
      */
-    public static function get_stats_table_by_attempt($exercise_id, $category_list = array()) {
+    public static function get_stats_table_by_attempt($exercise_id, $category_list = array())
+    {
         if (empty($category_list)) {
             return null;
         }
@@ -524,35 +564,36 @@ class Testcategory
             }
             return $table->toHtml();
         }
+
         return null;
     }
 
-
     /**
      * Return true if a category already exists with the same name
-     * @param $in_name
+     * @param string $in_name
+     *
+     * @return bool
      */
     public static function category_exists_with_title($in_name)
     {
         $tab_test_category = Testcategory::getCategoryListInfo("title");
-        foreach ($tab_test_category as $title)
-        {
-            if ($title == $in_name)
-            {
+        foreach ($tab_test_category as $title) {
+            if ($title == $in_name) {
                 return true;
-}
+            }
         }
         return false;
     }
 
-
     /**
      * Return the id of the test category with title = $in_title
      * @param $in_title
      * @param int $in_c_id
+     *
      * @return int is id of test category
      */
-    public static function get_category_id_for_title($in_title, $in_c_id = 0) {
+    public static function get_category_id_for_title($in_title, $in_c_id = 0)
+    {
         $out_res = 0;
         if ($in_c_id == 0) {
             $in_c_id = api_get_course_int_id();
@@ -569,16 +610,99 @@ class Testcategory
 
     /**
      * Add a relation between question and category in table c_quiz_question_rel_category
-     * @param $in_category_id
-     * @param $in_question_id
+     * @param int $in_category_id
+     * @param int $in_question_id
+     * @param int $in_course_c_id
      */
-    public static function add_category_for_question_id($in_category_id, $in_question_id, $in_course_c_id) {
+    public static function add_category_for_question_id($in_category_id, $in_question_id, $in_course_c_id)
+    {
         $tbl_reltable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
         // if question doesn't have a category
         // @todo change for 1.10 when a question can have several categories
         if (Testcategory::getCategoryForQuestion($in_question_id, $in_course_c_id) == 0 && $in_question_id > 0 && $in_course_c_id > 0) {
             $sql = "INSERT INTO $tbl_reltable VALUES (".intval($in_course_c_id).", ".intval($in_question_id).", ".intval($in_category_id).")";
-            $res = Database::query($sql);
+            Database::query($sql);
+        }
+    }
+
+    /**
+     * @param int $courseId
+     * @param int $sessionId
+     *
+     * @return array
+     */
+    public function getCategories($courseId, $sessionId = 0)
+    {
+        $table = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
+        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
+        $sessionId = intval($sessionId);
+        $courseId = intval($courseId);
+
+        if (empty($sessionId)) {
+            $sessionCondition = api_get_session_condition($sessionId, true, false, 'i.id_session');
+        } else {
+            $sessionCondition = api_get_session_condition($sessionId, true, true, 'i.id_session');
+        }
+
+        if (empty($courseId)) {
+            return array();
         }
+
+        $sql = "SELECT c.* FROM $table c
+                INNER JOIN $itemProperty i
+                ON c.c_id = i.c_id AND i.ref = c.id
+                WHERE
+                    c.c_id = $courseId AND
+                    i.tool = '".TOOL_TEST_CATEGORY."'
+                    $sessionCondition
+                ORDER BY title";
+        $result = Database::query($sql);
+
+        return Database::store_result($result, 'ASSOC');
+    }
+
+    /**
+     * @param int $courseId
+     * @param int $sessionId
+     * @return string
+     */
+    public function displayCategories($courseId, $sessionId = 0)
+    {
+        $categories = $this->getCategories($courseId, $sessionId);
+        $html = null;
+
+        foreach ($categories as $category) {
+            $tmpobj = new Testcategory($category['id']);
+            $nb_question = $tmpobj->getCategoryQuestionsNumber();
+            $rowname = self::protectJSDialogQuote($category['title']);
+            $nb_question_label = $nb_question == 1 ? $nb_question . ' ' . get_lang('Question') : $nb_question . ' ' . get_lang('Questions');
+
+            $html .= '<div class="sectiontitle" id="id_cat' . $category['id'] . '">';
+            $html .= "<span style='float:right'>" . $nb_question_label . "</span>";
+            $html .= $category['title'];
+            $html .= '</div>';
+            $html .= '<div class="sectioncomment">';
+            $html .= $category['description'];
+            $html .= '</div>';
+            $html .= '<div>';
+            $html .= '<a href="' . api_get_self() . '?action=editcategory&amp;category_id=' . $category['id'] . '">' .
+                Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>';
+            $html .= ' <a href="' . api_get_self() . '?action=deletecategory&amp;category_id=' . $category['id'] . '" ';
+            $html .= 'onclick="return confirmDelete(\'' . self::protectJSDialogQuote(get_lang('DeleteCategoryAreYouSure') . '[' . $rowname) . '] ?\', \'id_cat' . $category['id'] . '\');">';
+            $html .= Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
+            $html .= '</div>';
+        }
+
+        return $html;
+    }
+
+    // To allowed " in javascript dialog box without bad surprises
+    // replace " with two '
+    public function protectJSDialogQuote($in_txt)
+    {
+        $res = $in_txt;
+        $res = str_replace("'", "\'", $res);
+        $res = str_replace('"', "\'\'", $res); // super astuce pour afficher les " dans les boite de dialogue
+        return $res;
     }
 }

+ 22 - 61
main/exercice/tests_category.php

@@ -1,5 +1,4 @@
 <?php
-
 /* For licensing terms, see /license.txt */
 
 /**
@@ -13,14 +12,12 @@ $htmlHeadXtra[] = '
 		document.getElementById(in_id).style.backgroundColor="#AAFFB0";
 		if (confirm(in_txt)) {
 			return true;
-		}
-		else {
+		} else {
 			document.getElementById(in_id).style.backgroundColor = oldbgcolor;
 			return false;
 		}
 	}
-</script>
-';
+</script>';
 
 // name of the language file that needs to be included
 $language_file = 'exercice';
@@ -36,6 +33,9 @@ $this_section = SECTION_COURSES;
 if (!api_is_allowed_to_edit()) {
     api_not_allowed(true);
 }
+$category = new Testcategory();
+$courseId = api_get_course_int_id();
+$sessionId = api_get_session_id();
 
 // breadcrumbs
 $interbreadcrumb[] = array("url" => "exercice.php", "name" => get_lang('Exercices'));
@@ -44,19 +44,25 @@ Display::display_header(get_lang('Category'));
 // Action handling: add, edit and remove
 if (isset($_GET['action']) && $_GET['action'] == 'addcategory') {
     add_category_form($_GET['action']);
+    display_add_category();
 } else if (isset($_GET['action']) && $_GET['action'] == 'editcategory') {
     edit_category_form($_GET['action']);
 } else if (isset($_GET['action']) && $_GET['action'] == 'deletecategory') {
     delete_category_form($_GET['action']);
+    display_add_category();
 } else {
     display_add_category();
-    display_categories();
 }
+echo $category->displayCategories($courseId, $sessionId);
 
 Display::display_footer();
 
 // FUNCTIONS
 // form to edit a category
+/**
+ * @todo move to testcategory.class.php
+ * @param string $in_action
+ */
 function edit_category_form($in_action) {
     $in_action = Security::remove_XSS($in_action);
     if (isset($_GET['category_id']) && is_numeric($_GET['category_id'])) {
@@ -99,15 +105,12 @@ function edit_category_form($in_action) {
                 }
             }
             Security::clear_token();
-            display_add_category();
-            display_categories();
         } else {
             display_goback();
             $token = Security::get_token();
             $form->addElement('hidden', 'sec_token');
             $form->setConstants(array('sec_token' => $token));
             $form->display();
-            display_categories();
         }
     } else {
         Display::display_error_message(get_lang('CannotEditCategory'));
@@ -116,24 +119,24 @@ function edit_category_form($in_action) {
 
 // process to delete a category
 function delete_category_form($in_action) {
-    $in_action = Security::remove_XSS($in_action);
     if (isset($_GET['category_id']) && is_numeric($_GET['category_id'])) {
         $category_id = Security::remove_XSS($_GET['category_id']);
         $catobject = new Testcategory($category_id);
-            if ($catobject->removeCategory()) {
-                Display::display_confirmation_message(get_lang('DeleteCategoryDone'));
-            } else {
-                Display::display_error_message(get_lang('CannotDeleteCategoryError'));
-            }
+        if ($catobject->removeCategory()) {
+            Display::display_confirmation_message(get_lang('DeleteCategoryDone'));
+        } else {
+            Display::display_error_message(get_lang('CannotDeleteCategoryError'));
         }
-    else {
+    } else {
         Display::display_error_message(get_lang('CannotDeleteCategoryError'));
     }
-    display_add_category();
-    display_categories();
 }
 
-// form to add a category
+/**
+ * form to add a category
+ * @todo move to testcategory.class.php
+ * @param string $in_action
+ */
 function add_category_form($in_action) {
     $in_action = Security::remove_XSS($in_action);
     // initiate the object
@@ -160,15 +163,12 @@ function add_category_form($in_action) {
             }
         }
         Security::clear_token();
-        display_add_category();
-        display_categories();
     } else {
         display_goback();
         $token = Security::get_token();
         $form->addElement('hidden', 'sec_token');
         $form->setConstants(array('sec_token' => $token));
         $form->display();
-        display_categories();
     }
 }
 
@@ -183,48 +183,9 @@ function display_add_category() {
     echo "<fieldset><legend>" . get_lang('QuestionCategory') . "</legend></fieldset>";
 }
 
-// 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 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
-        $tmpobj = new Testcategory($row['id']);
-        $nb_question = $tmpobj->getCategoryQuestionsNumber();
-        echo '<div class="sectiontitle" id="id_cat' . $row['id'] . '">';
-        $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">';
-        echo $row['description'];
-        echo '</div>';
-        echo '<div>';
-        echo '<a href="' . api_get_self() . '?action=editcategory&amp;category_id=' . $row['id'] . '">' . Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>';
-            $rowname = protectJSDialogQuote($row['title']);
-            echo ' <a href="' . api_get_self() . '?action=deletecategory&amp;category_id=' . $row['id'] . '" ';
-            echo 'onclick="return confirmDelete(\'' . protectJSDialogQuote(get_lang('DeleteCategoryAreYouSure') . '[' . $rowname) . '] ?\', \'id_cat' . $row['id'] . '\');">';
-            echo Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
-        echo '</div>';
-    }
-}
-
 // display goback to category list page link
 function display_goback() {
     echo '<div class="actions">';
     echo '<a href="' . api_get_self() . '">' . Display::return_icon('back.png', get_lang('BackToCategoryList'), array(), 32) . '</a>';
     echo '</div>';
 }
-
-// To allowed " in javascript dialog box without bad surprises
-// replace " with two '
-function protectJSDialogQuote($in_txt) {
-    $res = $in_txt;
-    $res = str_replace("'", "\'", $res);
-    $res = str_replace('"', "\'\'", $res); // super astuce pour afficher les " dans les boite de dialogue
-    return $res;
-}

+ 26 - 27
main/gradebook/lib/be/evaluation.class.php

@@ -26,7 +26,7 @@ class Evaluation implements GradebookItem
 
     // CONSTRUCTORS
 
-    function __construct() {    	
+    function __construct() {
     }
 
     // GETTERS AND SETTERS
@@ -66,23 +66,23 @@ class Evaluation implements GradebookItem
 	public function get_max() {
 		return $this->eval_max;
 	}
-	
+
 	public function get_type() {
 		return $this->type;
-	}	
+	}
 
 	public function is_visible() {
 		return $this->visible;
 	}
-	
+
 	public function get_locked() {
 		return $this->locked;
 	}
-    
+
     public function is_locked() {
 		return isset($this->locked) && $this->locked == 1 ? true : false ;
-	}  
-    
+	}
+
 	public function set_id ($id) {
 		$this->id = $id;
 	}
@@ -122,16 +122,16 @@ class Evaluation implements GradebookItem
 	public function set_visible ($visible) {
 		$this->visible = $visible;
 	}
-	
+
     public function set_type ($type) {
 		$this->type = $type;
 	}
- 
+
 	public function set_locked ($locked) {
 		$this->locked = $locked;
 	}
-    
-    
+
+
     // CRUD FUNCTIONS
 
 	/**
@@ -179,7 +179,7 @@ class Evaluation implements GradebookItem
 			else $sql .= ' WHERE';
 			$sql .= ' locked = '.intval($locked);
 			$paramcount ++;
-		}		
+		}
 		$result = Database::query($sql);
 		$alleval = Evaluation::create_evaluation_objects_from_sql_result($result);
 		return $alleval;
@@ -202,7 +202,7 @@ class Evaluation implements GradebookItem
     			$eval->set_visible($data['visible']);
     			$eval->set_type($data['type']);
     			$eval->set_locked($data['locked']);
-    			
+
     			$alleval[]=$eval;
     		}
     	}
@@ -244,18 +244,17 @@ class Evaluation implements GradebookItem
 				 $sql .= ','.intval($this->get_category_id());
 			}
 			if (empty($this->type)) {
-				$this->type = 'evaluation';	
+				$this->type = 'evaluation';
 			}
 			$sql .= ", '".api_get_utc_datetime()."'";
-			
+
 			$sql .= ',\''.Database::escape_string($this->type).'\'';
-			
+
 			$sql .= ")";
-			
+
 			Database::query($sql);
 			$this->set_id(Database::insert_id());
-		}
-		else {
+		} else {
 			die('Error in Evaluation add: required field empty');
 		}
 	}
@@ -309,7 +308,7 @@ class Evaluation implements GradebookItem
 				.', visible = '.intval($this->is_visible())
 				.' WHERE id = '.intval($this->id);
 		//recorded history
-        
+
 		$eval_log=new Evaluation();
 		$eval_log->add_evaluation_log($this->id);
 		Database::query($sql);
@@ -585,18 +584,18 @@ class Evaluation implements GradebookItem
 	public function get_icon_name() {
 		return $this->has_results() ? 'evalnotempty' : 'evalempty';
 	}
-    
+
   	/**
-  	 * Locks an evaluation, only one who can unlock it is the platform administrator.  	 
-  	 * @param int locked 1 or unlocked 0 
-  	 * 
+  	 * Locks an evaluation, only one who can unlock it is the platform administrator.
+  	 * @param int locked 1 or unlocked 0
+  	 *
   	 **/
   	function lock($locked) {
   		$table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
   		$sql = "UPDATE $table_evaluation SET locked = '".intval($locked)."' WHERE id='".intval($this->id)."'";
   		Database::query($sql);
   	}
-    
+
     function check_lock_permissions() {
         if (api_is_platform_admin()) {
             return true;
@@ -606,8 +605,8 @@ class Evaluation implements GradebookItem
             }
         }
     }
-    
+
     function delete_linked_data() {
-        
+
     }
 }

+ 5 - 0
main/inc/introductionSection.inc.php

@@ -272,6 +272,11 @@ if ($intro_dispCommand) {
 			$introduction_section .=  "<a href=\"".api_get_self()."?intro_cmdDel=1\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES,$charset))."')) return false;\">".Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL)."</a>";
 		}
 		$introduction_section .=  "</div>";
+        // Fix for chrome XSS filter for videos in iframes - BT#7930
+        $browser = api_get_navigator();
+        if (strpos($introduction_section, '<iframe') !== false && $browser['name'] == 'Chrome') {
+            header('X-XSS-Protection: 0');
+        }
 	}
 }
 $introduction_section .=  '</div>';

+ 6 - 5
main/inc/lib/banner.lib.php

@@ -389,7 +389,7 @@ function return_menu() {
     } else {
         //$errorMsg = get_lang('HomePageFilesNotReadable');
     }
-    
+
     $home_top = api_to_system_encoding($home_top, api_detect_encoding(strip_tags($home_top)));
 
     $open = str_replace('{rel_path}',api_get_path(REL_PATH), $home_top);
@@ -455,15 +455,14 @@ function return_menu() {
     return $menu;
 }
 
-function return_breadcrumb($interbreadcrumb, $language_file, $nameTools) {
-    global $cidReset;
+function return_breadcrumb($interbreadcrumb, $language_file, $nameTools)
+{
     $session_id     = api_get_session_id();
     $session_name   = api_get_session_name($session_id);
     $_course        = api_get_course_info();
     $user_id        = api_get_user_id();
     $course_id      = api_get_course_id();
 
-
     /*  Plugins for banner section */
     $web_course_path = api_get_path(WEB_COURSE_PATH);
 
@@ -507,7 +506,9 @@ function return_breadcrumb($interbreadcrumb, $language_file, $nameTools) {
         $navigation[] = $navigation_item;
     }
 
-    // part 2: Interbreadcrumbs. If there is an array $interbreadcrumb defined then these have to appear before the last breadcrumb (which is the tool itself)
+    /* part 2: Interbreadcrumbs. If there is an array $interbreadcrumb
+    defined then these have to appear before the last breadcrumb
+    (which is the tool itself)*/
     if (isset($interbreadcrumb) && is_array($interbreadcrumb)) {
         foreach ($interbreadcrumb as $breadcrumb_step) {
             if (isset($breadcrumb_step['type']) && $breadcrumb_step['type'] == 'right') {

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

@@ -4255,9 +4255,9 @@ class CourseManager
 
     /**
      * @deprecated seems not to be used
-     * @return ResultSet
      */
-    static function list_inactive_courses($ceiling, $visibility_level = COURSE_VISIBILITY_REGISTERED) {
+    static function list_inactive_courses($ceiling, $visibility_level = COURSE_VISIBILITY_REGISTERED)
+    {
         $ceiling = is_numeric($ceiling) ? (int) $ceiling : strtotime($ceiling);
         $ceiling = date('Y-m-d H:i:s', $ceiling);
         $visibility_level = $visibility_level ? $visibility_level : '0';

+ 3 - 3
main/inc/lib/events.lib.inc.php

@@ -1499,11 +1499,11 @@ function event_course_login($course_code, $user_id, $session_id) {
     global $course_tracking_table;
 
     //@todo use api_get_utc_datetime
-    $time		 = api_get_datetime();
+    $time = api_get_utc_datetime();
 
     $course_code = Database::escape_string($course_code);
-    $user_id	 = Database::escape_string($user_id);
-    $session_id  = Database::escape_string($session_id);
+    $user_id	 = intval($user_id);
+    $session_id  = intval($session_id);
 
     $sql	= "INSERT INTO $course_tracking_table(course_code, user_id, login_course_date, logout_course_date, counter, session_id)
         	  VALUES('".$course_code."', '".$user_id."', '$time', '$time', '1', '".$session_id."')";

+ 0 - 4
main/inc/lib/formvalidator/Element/DateRangePicker.php

@@ -98,7 +98,6 @@ class DateRangePicker extends HTML_QuickForm_text
      */
     function validateDates($dates)
     {
-
         if (empty($dates['start']) || empty($dates['end'])) {
             return false;
         }
@@ -115,7 +114,4 @@ class DateRangePicker extends HTML_QuickForm_text
 
         return true;
     }
-
-
-
 }

+ 1 - 0
main/inc/lib/formvalidator/Element/datepickerdate.php

@@ -8,6 +8,7 @@ class HTML_QuickForm_datepickerdate extends HTML_QuickForm_date
 {
 	/**
 	 * Constructor
+     * @deprecated use class DatePicker
 	 */
 	public function HTML_QuickForm_datepickerdate($elementName = null, $elementLabel = null, $attributes = null)
     {

+ 5 - 0
main/inc/lib/formvalidator/FormValidator.class.php

@@ -143,6 +143,7 @@ class FormValidator extends HTML_QuickForm
         $this->registerElementType('CAPTCHA_Image', 'HTML/QuickForm/CAPTCHA/Image.php', 'HTML_QuickForm_CAPTCHA_Image');
 
         $this->registerRule('date', null, 'HTML_QuickForm_Rule_Date', $dir . 'Rule/Date.php');
+        $this->registerRule('datetime', null, 'DateTimeRule', $dir . 'Rule/DateTimeRule.php');
         $this->registerRule('date_compare', null, 'HTML_QuickForm_Rule_DateCompare', $dir . 'Rule/DateCompare.php');
         $this->registerRule('html', null, 'HTML_QuickForm_Rule_HTML', $dir . 'Rule/HTML.php');
         $this->registerRule('username_available', null, 'HTML_QuickForm_Rule_UsernameAvailable', $dir . 'Rule/UsernameAvailable.php');
@@ -384,6 +385,7 @@ EOT;
      * A rule is added to check if the date is a valid one
      * @param string $label						The label for the form-element
      * @param string $name						The element name
+     * @deprecated
      */
     function add_datepicker($name, $label)
     {
@@ -397,6 +399,7 @@ EOT;
      * A rule is added to check if the date is a valid one
      * @param string $label						The label for the form-element
      * @param string $name						The element name
+     * @deprecated
      */
     function add_datepickerdate($name, $label)
     {
@@ -411,6 +414,7 @@ EOT;
      * before the second one.
      * @param string $label						The label for the form-element
      * @param string $name						The element name
+     * @deprecated
      */
     function add_timewindow($name_1, $name_2, $label_1, $label_2)
     {
@@ -421,6 +425,7 @@ EOT;
 
     /**
      * Adds a button to the form to add resources.
+     * @deprecated
      */
     function add_resource_button()
     {

+ 11 - 28
main/inc/lib/formvalidator/Rule/Date.php

@@ -1,40 +1,23 @@
 <?php
-// $Id: Date.php 6187 2005-09-07 10:23:57Z bmol $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
+/* For licensing terms, see /license.txt */
+/** @author Bart Mollet, Julio Montoya */
+require_once 'HTML/QuickForm/Rule.php';
 
-	Copyright (c) 2004-2005 Dokeos S.A.
-	Copyright (c) Bart Mollet, Hogeschool Gent
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
-require_once ('HTML/QuickForm/Rule.php');
 /**
- * QuickForm rule to check a date
+ * Class HTML_QuickForm_Rule_Date
  */
 class HTML_QuickForm_Rule_Date extends HTML_QuickForm_Rule
 {
 	/**
-	 * Function to check a date
+	 * Check a date
 	 * @see HTML_QuickForm_Rule
-	 * @param array $date An array with keys F (month), d (day) and Y (year)
+	 * @param string $date example 2014-04-30
+     * @param array $options
+     *
 	 * @return boolean True if date is valid
 	 */
-	function validate($date, $options)
+	public function validate($date, $options)
 	{
-		return checkdate($date['F'], $date['d'], $date['Y']);
+        return api_is_valid_date($date, 'Y-m-d');
 	}
-}
+}

+ 8 - 33
main/inc/lib/formvalidator/Rule/DateCompare.php

@@ -1,46 +1,21 @@
 <?php
-// $Id: DateCompare.php 6187 2005-09-07 10:23:57Z bmol $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2005 Dokeos S.A.
-	Copyright (c) Bart Mollet, Hogeschool Gent
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
-	Mail: info@dokeos.com
-==============================================================================
-*/
+/* For licensing terms, see /license.txt */
+/** @author Bart Mollet, Julio Montoya */
 require_once 'HTML/QuickForm/Rule/Compare.php';
 /**
- * QuickForm rule to compare 2 dates
+ * Class HTML_QuickForm_Rule_DateCompare
  */
 class HTML_QuickForm_Rule_DateCompare extends HTML_QuickForm_Rule_Compare
 {
     /**
      * Validate 2 dates
-     * @param array $values Array with the 2 dates. Each element in this array
-     * should be an array width keys  F (month), d (day) and Y (year)
-     * @param string $operator The operator to use (default '==')
-     * @return boolean True if the 2 given dates match the operator
+     * @param array $values Array with the 2 dates.
+     * @param $operator
+     *
+     * @return boolean true if the 2 given dates match the operator
      */
     function validate($values, $operator = null)
     {
-    	$date1 = $values[0];
-    	$date2 = $values[1];
-        $time1 = mktime($date1['H'],$date1['i'],0,$date1['F'],$date1['d'],$date1['Y']);
-        $time2 = mktime($date2['H'],$date2['i'],0,$date2['F'],$date2['d'],$date2['Y']);
-		return parent::validate(array($time1,$time2),$operator);
+        return api_strtotime($values[0]) < api_strtotime($values[1]);
     }
 }
-?>

+ 23 - 0
main/inc/lib/formvalidator/Rule/DateTimeRule.php

@@ -0,0 +1,23 @@
+<?php
+/* For licensing terms, see /license.txt */
+/** @author Bart Mollet, Julio Montoya */
+require_once 'HTML/QuickForm/Rule.php';
+
+/**
+ * Class HTML_QuickForm_Rule_Date
+ */
+class DateTimeRule extends HTML_QuickForm_Rule
+{
+	/**
+	 * Check a date
+	 * @see HTML_QuickForm_Rule
+	 * @param string $date example 2014-04-30
+     * @param array $options
+     *
+	 * @return boolean True if date is valid
+	 */
+	public function validate($date, $options)
+	{
+        return api_is_valid_date($date, 'Y-m-d h:i');
+	}
+}

+ 33 - 23
main/inc/lib/gradebook.lib.php

@@ -1,26 +1,24 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
-*   This class provides methods for the notebook management.
-*   Include/require it in your code to use its features.
-*   @package chamilo.library
-*/
+ *   This class provides methods for the notebook management.
+ *   Include/require it in your code to use its features.
+ *   @package chamilo.library
+ */
 /**
  * Code
  */
-
-class Gradebook extends Model {
-
+class Gradebook extends Model
+{
     public $columns = array('id', 'name', 'description', 'course_code', 'parent_id', 'grade_model_id', 'session_id', 'weight', 'user_id');
 
-
-    public function __construct() {
+    public function __construct()
+    {
         $this->table                        = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
         $this->table_skill                  = Database::get_main_table(TABLE_MAIN_SKILL);
         $this->table_skill_rel_gradebook    = Database::get_main_table(TABLE_MAIN_SKILL_REL_GRADEBOOK);
     }
 
-
     /**
      * Returns true if the gradebook is active and visible in a course, false
      * otherwise.
@@ -32,8 +30,10 @@ class Gradebook extends Model {
     {
         $name = 'gradebook';
         $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
-        $sql = "SELECT * from $table WHERE variable='course_hide_tools' AND subkey='$name'";
-        $setting = ResultSet::create($sql)->first();
+        $sql = "SELECT * from $table WHERE variable='course_hide_tools' AND subkey='$name' LIMIT 1";
+        $result = Database::query($sql);
+        $setting = Database::store_result($result);
+        $setting = isset($setting[0]) ? $setting[0] : null;
         $setting = $setting ? $setting : array();
         $inactive = isset($setting['selected_value']) && $setting['selected_value'] == 'true';
 
@@ -43,17 +43,20 @@ class Gradebook extends Model {
 
         $c_id = $c_id ? intval($c_id) : api_get_course_int_id();
         $table  = Database::get_course_table(TABLE_TOOL_LIST);
-        $sql = "SELECT * from $table WHERE c_id = $c_id and name='$name'";
-        $item = ResultSet::create($sql)->first();
+        $sql = "SELECT * from $table WHERE c_id = $c_id and name='$name' LIMIT 1";
+        $result = Database::query($sql);
+        $item = Database::store_result($result, 'ASSOC');
+        $item = isset($item[0]) ? $item[0] : null;
         if (empty($item)) {
             return true;
         }
         return $item['visibility'] == '1';
     }
 
-    public function get_all($options = array()) {
+    public function get_all($options = array())
+    {
         $gradebooks = parent::get_all($options);
-        foreach($gradebooks as &$gradebook) {
+        foreach ($gradebooks as &$gradebook) {
             if (empty($gradebook['name'])) {
                 $gradebook['name'] = $gradebook['course_code'];
             }
@@ -62,11 +65,13 @@ class Gradebook extends Model {
         return $gradebooks;
     }
 
-    public function update($params) {
+    public function update($params)
+    {
         return parent::update($params);
     }
 
-    public function update_skills_to_gradebook($gradebook_id, $skill_list) {
+    public function update_skills_to_gradebook($gradebook_id, $skill_list)
+    {
 
         if (!empty($skill_list)) {
 
@@ -112,8 +117,8 @@ class Gradebook extends Model {
      * @param   string  action add, edit
      * @return  obj     form validator obj
      */
-    public function show_skill_form($gradebook_id, $url, $header = null) {
-
+    public function show_skill_form($gradebook_id, $url, $header = null)
+    {
         $form = new FormValidator('gradebook_add_skill', 'POST', $url);
         // Setting the form elements
         if (!isset($header)) {
@@ -145,7 +150,12 @@ class Gradebook extends Model {
         return $form;
     }
 
-    function get_skills_by_gradebook($gradebook_id) {
+    /**
+     * @param int $gradebook_id
+     * @return array|resource
+     */
+    function get_skills_by_gradebook($gradebook_id)
+    {
         $gradebook_id = intval($gradebook_id);
         $sql = "SELECT skill.id, skill.name FROM {$this->table_skill} skill INNER JOIN {$this->table_skill_rel_gradebook} skill_rel_gradebook
                     ON skill.id = skill_rel_gradebook.skill_id
@@ -155,11 +165,11 @@ class Gradebook extends Model {
         return $result;
     }
 
-
     /**
      * Displays the title + grid
      */
-    public function display() {
+    public function display()
+    {
         // action links
         echo Display::grid_html('gradebooks');
     }

+ 1 - 0
main/inc/lib/groupmanager.lib.php

@@ -340,6 +340,7 @@ class GroupManager
     /**
      * Create a group for every class subscribed to the current course
      * @param int $category_id The category in which the groups should be created
+     * @return array
      */
     public static function create_class_groups($category_id)
     {

+ 1 - 2
main/inc/lib/htmlpurifier/library/HTMLPurifier/Filter/AllowIframes.php

@@ -46,8 +46,7 @@ class HTMLPurifier_Filter_AllowIframes extends HTMLPurifier_Filter
     protected function postFilterCallback($matches)
     {
         // Domain Whitelist
-
-        $youTubeMatch       = preg_match('#src="https?://www.youtube(-nocookie)?.com/#i', $matches[1]);
+        $youTubeMatch       = preg_match('#src="(https:)?//www.youtube(-nocookie)?.com/#i', $matches[1]);
         $vimeoMatch         = preg_match('#src="http://player.vimeo.com/#i', $matches[1]);
         $googleMapsMatch    = preg_match('#src="https://maps.google.com/#i', $matches[1]);
 

+ 11 - 11
main/inc/lib/main_api.lib.php

@@ -21,7 +21,6 @@ define('REQUIRED_MIN_POST_MAX_SIZE',        '10');
 
 use \ChamiloSession as Session;
 
-
 // USER STATUS CONSTANTS
 /** global status of a user: student */
 define('STUDENT', 5);
@@ -45,7 +44,6 @@ define('COURSE_STUDENT', 14);   //student subscribed in a course
 define('SESSION_STUDENT', 15);  //student subscribed in a session course
 define('COURSE_TUTOR', 16); // student is tutor of a course (NOT in session)
 
-
 // Table of status
 $_status_list[COURSEMANAGER]    = 'teacher';        // 1
 $_status_list[SESSIONADMIN]     = 'session_admin';  // 3
@@ -53,7 +51,6 @@ $_status_list[DRH]              = 'drh';            // 4
 $_status_list[STUDENT]          = 'user';           // 5
 $_status_list[ANONYMOUS]        = 'anonymous';      // 6
 
-
 // COURSE VISIBILITY CONSTANTS
 /** only visible for course admin */
 define('COURSE_VISIBILITY_CLOSED', 0);
@@ -72,7 +69,6 @@ define('SESSION_VISIBLE', 2);
 define('SESSION_INVISIBLE', 3); // not available
 define('SESSION_AVAILABLE', 4);
 
-
 define('SUBSCRIBE_ALLOWED', 1);
 define('SUBSCRIBE_NOT_ALLOWED', 0);
 define('UNSUBSCRIBE_ALLOWED', 1);
@@ -210,13 +206,10 @@ define('LOG_CONFIGURATION_SETTINGS_VARIABLE',   'settings_variable');
 define('LOG_PLATFORM_LANGUAGE',                 'default_platform_language');
 define('LOG_CAREER_ID',                         'career_id');
 define('LOG_PROMOTION_ID',                      'promotion_id');
-
 define('LOG_GRADEBOOK_LOCKED',                   'gradebook_locked');
 define('LOG_GRADEBOOK_UNLOCKED',                 'gradebook_unlocked');
 define('LOG_GRADEBOOK_ID',                       'gradebook_id');
-
 define('LOG_WIKI_PAGE_ID',                       'wiki_page_id');
-
 define('LOG_EXERCISE_ID',                        'exercise_id');
 define('LOG_EXERCISE_AND_USER_ID',               'exercise_and_user_id');
 define('LOG_LP_ID',                              'lp_id');
@@ -344,8 +337,6 @@ define('ICON_SIZE_HUGE',    128);
 
 define('SHOW_TEXT_NEAR_ICONS', false);
 
-
-
 /**
  * Inclusion of internationalization libraries
  */
@@ -3251,6 +3242,15 @@ function api_item_property_update(
     $end_visible = 0,
     $session_id = 0
 ) {
+    if (empty($_course)) {
+        return false;
+    }
+
+    $course_id = $_course['real_id'];
+
+    if (empty($course_id)) {
+        return false;
+    }
 
     // Definition of variables.
     $tool           = Database::escape_string($tool);
@@ -3296,7 +3296,6 @@ function api_item_property_update(
         $condition_session = " AND id_session = '$session_id' ";
     }
 
-    $course_id = $_course['real_id'];
     $filter = " c_id = $course_id AND tool='$tool' AND ref='$item_id' $condition_session ";
 
     if ($item_id == '*') {
@@ -5131,7 +5130,8 @@ function api_is_element_in_the_session($tool, $element_id, $session_id = null) {
             $table_tool = Database::get_course_table(TABLE_GROUP);
             $key_field = 'id';
             break;
-        default: return false;
+        default:
+            return false;
     }
     $course_id = api_get_course_int_id();
 

+ 1 - 0
main/inc/lib/result_set.class.php

@@ -5,6 +5,7 @@
  *
  * @license see /license.txt
  * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
+ * @deprecated
  */
 class ResultSet implements Countable, Iterator
 {

+ 37 - 43
main/inc/lib/surveymanager.lib.php

@@ -12,7 +12,8 @@
  * Manage the "versioning" of a conditional survey
  * @package chamilo.survey
  * */
-class SurveyTree {
+class SurveyTree
+{
 	public $surveylist;
 	public $plainsurveylist;
 	public $numbersurveys;
@@ -20,7 +21,8 @@ class SurveyTree {
 	/**
 	 * Sets the surveylist and the plainsurveylist
 	 */
-	public function __construct() {
+	public function __construct()
+    {
         // Database table definitions
 		$table_survey 			= Database :: get_course_table(TABLE_SURVEY);
 		$table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
@@ -31,16 +33,15 @@ class SurveyTree {
 		if ($search_restriction) {
 			$search_restriction = ' AND '.$search_restriction;
 		}
-		
 		$course_id = api_get_course_int_id();
-		
-
-		$sql = "SELECT survey.survey_id , survey.parent_id, survey_version, survey.code as name
-				FROM $table_survey survey LEFT JOIN $table_survey_question  survey_question
+		$sql = "SELECT
+survey.survey_id , survey.parent_id, survey_version, survey.code as name
+				FROM $table_survey survey
+				LEFT JOIN $table_survey_question  survey_question
 				ON survey.survey_id = survey_question.survey_id , $table_user user
 				WHERE
-					survey.c_id 			=  $course_id AND 
-					survey_question.c_id 	=  $course_id AND 
+					survey.c_id 			=  $course_id AND
+					survey_question.c_id 	=  $course_id AND
 					survey.author 			= user.user_id
 				GROUP BY survey.survey_id";
 
@@ -48,11 +49,10 @@ class SurveyTree {
 		$surveys_parents = array ();
 		$refs = array();
 		$list = array();
-		$last=array();
+		$last = array();
 		$plain_array=array();
 
-		while ($survey = Database::fetch_array($res,'ASSOC'))
-		{
+		while ($survey = Database::fetch_array($res,'ASSOC')) {
 			$plain_array[$survey['survey_id']]=$survey;
 			$surveys_parents[]=$survey['survey_version'];
 			$thisref = &$refs[ $survey['survey_id'] ];
@@ -60,18 +60,16 @@ class SurveyTree {
 			$thisref['name'] = $survey['name'];
 			$thisref['id'] = $survey['survey_id'];
 			$thisref['survey_version'] = $survey['survey_version'];
-			if ($survey['parent_id'] == 0)
-			{
+			if ($survey['parent_id'] == 0) {
 				$list[ $survey['survey_id'] ] = &$thisref;
-			}
-			else
-			{
+			} else {
 				$refs[ $survey['parent_id'] ]['children'][ $survey['survey_id'] ] = &$thisref;
 			}
 		}
         $this->surveylist = $list;
         $this->plainsurveylist = $plain_array;
     }
+
 	/**
 	 * This function gets the parent id of a survey
 	 *
@@ -81,53 +79,49 @@ class SurveyTree {
 	 * @author Julio Montoya <gugli100@gmail.com>, Dokeos
 	 * @version September 2008
 	 */
-	public function getParentId ($id) {
+	public function getParentId($id)
+    {
 		$node = $this->plainsurveylist[$id];
-		if (is_array($node)&& !empty($node['parent_id']))
+		if (is_array($node)&& !empty($node['parent_id'])) {
 			return $node['parent_id'];
-		else
+        } else {
 			return -1;
+        }
 	}
+
 	/**
 	 * This function creates a list of all surveys id
 	 * @param  list of nodes
 	 * @return array with the structure survey_id => survey_name
-	 * @author Julio Montoya <gugli100@gmail.com>, Dokeos
+	 * @author Julio Montoya <gugli100@gmail.com>
 	 * @version September 2008
-	 *
 	 */
-	public function createList ($list) {
-		$result=array();
-		if(is_array($list)) {
+	public function createList ($list)
+    {
+		$result = array();
+		if (is_array($list)) {
 			foreach ($list as $key=>$node) {
-				if (is_array($node['children']))
-				{
+				if (isset($node['children']) && is_array($node['children'])) {
 					//echo $key; echo '--<br>';
 					//print_r($node);
 					//echo '<br>';
 					$result[$key]= $node['name'];
-					$re=self::createList($node['children']);
-					if (!empty($re))
-					{
-						if (is_array($re))
-							foreach ($re as $key=>$r)
-							{
-								$result[$key]=''.$r;
-							}
-						else
-						{
+					$re = self::createList($node['children']);
+					if (!empty($re)) {
+						if (is_array($re)) {
+							foreach ($re as $key=>$r) {
+                                $result[$key]=''.$r;
+                            }
+                        } else {
 							$result[]=$re;
 						}
-
 					}
-				}
-				else
-				{
-					//echo $key; echo '-<br>';
+				} else {
 					$result[$key]=$node['name'];
 				}
 			}
 		}
+
 		return $result;
 	}
-}
+}

+ 177 - 91
main/inc/lib/tracking.lib.php

@@ -13,7 +13,6 @@
 define('SESSION_LINK_TARGET','_self');
 
 require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.lib.php';
-//require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.class.php'; moved to autoload
 require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
 
 /**
@@ -258,7 +257,8 @@ class Tracking
      * @param integer $user_id
      * @param string  $course_code
      * @param int Session id (optional)
-     * @return timestamp     Time in seconds
+     *
+     * @return int Time in seconds
      */
     public static function get_time_spent_on_the_course($user_id, $course_code, $session_id = 0)
     {
@@ -394,8 +394,12 @@ class Tracking
      * @param    int            Session id (optional, default=0)
      * @return    string|bool    Date with format long without day or false if there is no date
      */
-    public static function get_first_connection_date_on_the_course($student_id, $course_code, $session_id = 0, $convert_date = true)
-    {
+    public static function get_first_connection_date_on_the_course(
+        $student_id,
+        $course_code,
+        $session_id = 0,
+        $convert_date = true
+    ) {
     	// protect data
     	$student_id  = intval($student_id);
     	$course_code = Database::escape_string($course_code);
@@ -427,8 +431,12 @@ class Tracking
      * @param    int            Session id (optional, default=0)
      * @return    string|bool    Date with format long without day or false if there is no date
      */
-    public static function get_last_connection_date_on_the_course($student_id, $course_code, $session_id = 0, $convert_date = true)
-    {
+    public static function get_last_connection_date_on_the_course(
+        $student_id,
+        $course_code,
+        $session_id = 0,
+        $convert_date = true
+    ) {
     	// protect data
     	$student_id  = intval($student_id);
     	$course_code = Database::escape_string($course_code);
@@ -485,7 +493,6 @@ class Tracking
      */
     public static function get_course_connections_count($course_code, $session_id = 0, $start = 0, $stop = null)
     {
-
     	if ($start < 0) {
     		$start = 0;
     	}
@@ -637,15 +644,22 @@ class Tracking
 
     /**
      * Get count student's exercise COMPLETED attempts
-     * @param    int     Student id
-     * @param    string    Course code
-     * @param    int        Exercise id
-     * @param    int        Learning path id (optional), for showing attempts inside a learning path $lp_id and $lp_item_id params are required.
-     * @param    int        Learning path item id (optional), for showing attempts inside a learning path $lp_id and $lp_item_id params are required.
-     * @return  int     count of attempts
+     * @param int tudent id
+     * @param string Course code
+     * @param int Exercise id
+     * @param int Learning path id (optional), for showing attempts inside a learning path $lp_id and $lp_item_id params are required.
+     * @param int Learning path item id (optional), for showing attempts inside a learning path $lp_id and $lp_item_id params are required.
+     *
+     * @return int     count of attempts
      */
-    public static function count_student_exercise_attempts($student_id, $course_code, $exercise_id, $lp_id = 0, $lp_item_id = 0, $session_id = 0)
-    {
+    public static function count_student_exercise_attempts(
+        $student_id,
+        $course_code,
+        $exercise_id,
+        $lp_id = 0,
+        $lp_item_id = 0,
+        $session_id = 0
+    ) {
     	$course_code = Database::escape_string($course_code);
     	$student_id  = intval($student_id);
     	$exercise_id = intval($exercise_id);
@@ -679,7 +693,7 @@ class Tracking
      * @param    int       session id
     */
 
-    static function get_exercise_student_progress($exercise_list, $user_id, $course_code, $session_id)
+    public static function get_exercise_student_progress($exercise_list, $user_id, $course_code, $session_id)
     {
         $course_code    = Database::escape_string($course_code);
         $user_id        = intval($user_id);
@@ -716,7 +730,8 @@ class Tracking
      * @param int $session_id
      * @return string
      */
-    static function get_exercise_student_average_best_attempt($exercise_list, $user_id, $course_code, $session_id) {
+    public static function get_exercise_student_average_best_attempt($exercise_list, $user_id, $course_code, $session_id)
+    {
         $result = 0;
         if (!empty($exercise_list)) {
             foreach ($exercise_list as $exercise_data) {
@@ -3487,38 +3502,65 @@ class Tracking
  */
 class TrackingCourseLog
 {
-
-    function count_item_resources()
+    /**
+     * @return mixed
+     */
+    public static function count_item_resources()
     {
-    	global $session_id;
+        $session_id = api_get_session_id();
         $course_id = api_get_course_int_id();
 
     	$table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
     	$table_user = Database :: get_main_table(TABLE_MAIN_USER);
 
-    	$sql = "SELECT count(tool) AS total_number_of_items FROM $table_item_property track_resource, $table_user user" .
-                " WHERE track_resource.c_id = $course_id AND track_resource.insert_user_id = user.user_id AND id_session = $session_id ";
+    	$sql = "SELECT count(tool) AS total_number_of_items
+    	        FROM $table_item_property track_resource, $table_user user
+    	        WHERE
+                    track_resource.c_id = $course_id AND
+                    track_resource.insert_user_id = user.user_id AND
+                    id_session = $session_id ";
 
     	if (isset($_GET['keyword'])) {
     		$keyword = Database::escape_string(trim($_GET['keyword']));
-    		$sql .= " AND (user.username LIKE '%".$keyword."%' OR lastedit_type LIKE '%".$keyword."%' OR tool LIKE '%".$keyword."%')";
+    		$sql .= " AND (
+    		            user.username LIKE '%".$keyword."%' OR
+    		            lastedit_type LIKE '%".$keyword."%' OR
+    		            tool LIKE '%".$keyword."%'
+                    )";
     	}
 
-    	$sql .= " AND tool IN ('document', 'learnpath', 'quiz', 'glossary', 'link', 'course_description', 'announcement', 'thematic', 'thematic_advance', 'thematic_plan')";
+    	$sql .= " AND tool IN (
+    	            'document',
+    	            'learnpath',
+    	            'quiz',
+    	            'glossary',
+    	            'link',
+    	            'course_description',
+    	            'announcement',
+    	            'thematic',
+    	            'thematic_advance',
+    	            'thematic_plan'
+                )";
     	$res = Database::query($sql);
     	$obj = Database::fetch_object($res);
     	return $obj->total_number_of_items;
     }
 
-    function get_item_resources_data($from, $number_of_items, $column, $direction)
+    /**
+     * @param $from
+     * @param $number_of_items
+     * @param $column
+     * @param $direction
+     * @return array
+     */
+    public static function get_item_resources_data($from, $number_of_items, $column, $direction)
     {
-    	global $dateTimeFormatLong, $session_id;
+        $session_id = api_get_session_id();
         $course_id = api_get_course_int_id();
 
     	$table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
     	$table_user = Database :: get_main_table(TABLE_MAIN_USER);
     	$table_session = Database :: get_main_table(TABLE_MAIN_SESSION);
-
     	$session_id = intval($session_id);
 
     	$sql = "SELECT
@@ -3530,16 +3572,32 @@ class TrackingCourseLog
                     visibility as col6,
                     user.user_id as user_id
                 FROM $table_item_property track_resource, $table_user user
-                WHERE   track_resource.c_id = $course_id AND
-                        track_resource.insert_user_id = user.user_id AND
-                        id_session = $session_id ";
+                WHERE
+                  track_resource.c_id = $course_id AND
+                  track_resource.insert_user_id = user.user_id AND
+                  id_session = $session_id ";
 
     	if (isset($_GET['keyword'])) {
     		$keyword = Database::escape_string(trim($_GET['keyword']));
-    		$sql .= " AND (user.username LIKE '%".$keyword."%' OR lastedit_type LIKE '%".$keyword."%' OR tool LIKE '%".$keyword."%') ";
+    		$sql .= " AND (
+    		            user.username LIKE '%".$keyword."%' OR
+    		            lastedit_type LIKE '%".$keyword."%' OR
+    		            tool LIKE '%".$keyword."%'
+                     ) ";
     	}
 
-    	$sql .= " AND tool IN ('document', 'learnpath', 'quiz', 'glossary', 'link', 'course_description', 'announcement', 'thematic', 'thematic_advance', 'thematic_plan')";
+    	$sql .= " AND tool IN (
+    	            'document',
+    	            'learnpath',
+    	            'quiz',
+    	            'glossary',
+    	            'link',
+    	            'course_description',
+    	            'announcement',
+    	            'thematic',
+    	            'thematic_advance',
+    	            'thematic_plan'
+                )";
 
     	if ($column == 0) {
     		$column = '0';
@@ -3552,10 +3610,13 @@ class TrackingCourseLog
     		$sql .= " ORDER BY col5 DESC ";
     	}
 
+        $from = intval($from);
+        $number_of_items = intval($number_of_items);
+
     	$sql .= " LIMIT $from, $number_of_items ";
 
     	$res = Database::query($sql);
-    	$resources = array ();
+    	$resources = array();
     	$thematic_tools = array('thematic', 'thematic_advance', 'thematic_plan');
     	while ($row = Database::fetch_array($res)) {
     		$ref = $row['ref'];
@@ -3573,14 +3634,24 @@ class TrackingCourseLog
     				$row_thematic = Database::fetch_array($rs_thematic);
     				$thematic_id = $row_thematic['thematic_id'];
 
-    				$query = "SELECT session.id, session.name, user.username FROM $tbl_thematic t, $table_session session, $table_user user" .
-                            " WHERE t.c_id = $course_id AND t.session_id = session.id AND session.id_coach = user.user_id AND t.id = $thematic_id";
-    				$recorset = Database::query($query);
+                    $sql = "SELECT session.id, session.name, user.username
+                            FROM $tbl_thematic t, $table_session session, $table_user user
+                            WHERE
+                              t.c_id = $course_id AND
+                              t.session_id = session.id AND
+                              session.id_coach = user.user_id AND
+                              t.id = $thematic_id";
+    				$recorset = Database::query($sql);
     			}
     		} else {
-    			$query = "SELECT session.id, session.name, user.username FROM $table_tool tool, $table_session session, $table_user user
-    			          WHERE tool.c_id = $course_id AND tool.session_id = session.id AND session.id_coach = user.user_id AND tool.$id = $ref";
-    			$recorset = Database::query($query);
+                $sql = "SELECT session.id, session.name, user.username
+                          FROM $table_tool tool, $table_session session, $table_user user
+    			          WHERE
+    			              tool.c_id = $course_id AND
+    			              tool.session_id = session.id AND
+    			              session.id_coach = user.user_id AND
+    			              tool.$id = $ref";
+    			$recorset = Database::query($sql);
     		}
 
     		if (!empty($recorset)) {
@@ -3621,44 +3692,48 @@ class TrackingCourseLog
     			//@todo Improve this code please
     			switch ($table_name['table_name']) {
     				case 'document' :
-    					$query_document = "SELECT tool.title as title FROM $table_tool tool WHERE c_id = $course_id AND id = $ref";
-    					$rs_document = Database::query($query_document);
+    					$sql = "SELECT tool.title as title FROM $table_tool tool
+                                WHERE c_id = $course_id AND id = $ref";
+    					$rs_document = Database::query($sql);
     					$obj_document = Database::fetch_object($rs_document);
     					$row[5] = $obj_document->title;
 
     					break;
     				case 'announcement':
-    					$query_document = "SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref";
-    					$rs_document = Database::query($query_document);
+                        $sql = "SELECT title FROM $table_tool
+                                WHERE c_id = $course_id AND id = $ref";
+    					$rs_document = Database::query($sql);
     					$obj_document = Database::fetch_object($rs_document);
     					$row[5] = $obj_document->title;
     					break;
     				case 'glossary':
-    					$query_document = "SELECT name FROM $table_tool WHERE c_id = $course_id AND glossary_id = $ref";
-    					$rs_document = Database::query($query_document);
+                        $sql = "SELECT name FROM $table_tool
+    					        WHERE c_id = $course_id AND glossary_id = $ref";
+    					$rs_document = Database::query($sql);
     					$obj_document = Database::fetch_object($rs_document);
     					$row[5] = $obj_document->name;
     					break;
     				case 'lp':
-    					$query_document = "SELECT name FROM $table_tool WHERE c_id = $course_id AND id = $ref";
-    					$rs_document = Database::query($query_document);
+                        $sql = "SELECT name
+                                FROM $table_tool WHERE c_id = $course_id AND id = $ref";
+    					$rs_document = Database::query($sql);
     					$obj_document = Database::fetch_object($rs_document);
     					$row[5] = $obj_document->name;
     					break;
     				case 'quiz':
-    					$query_document = "SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref";
-    					$rs_document = Database::query($query_document);
+                        $sql = "SELECT title FROM $table_tool
+                                WHERE c_id = $course_id AND id = $ref";
+    					$rs_document = Database::query($sql);
     					$obj_document = Database::fetch_object($rs_document);
     					$row[5] = $obj_document->title;
     					break;
-
     				case 'course_description':
-    					$query_document = "SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref";
-    					$rs_document = Database::query($query_document);
+                        $sql = "SELECT title FROM $table_tool
+                                WHERE c_id = $course_id AND id = $ref";
+    					$rs_document = Database::query($sql);
     					$obj_document = Database::fetch_object($rs_document);
     					$row[5] = $obj_document->title;
     					break;
-
     				case 'thematic':
     					$rs = Database::query("SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref");
     					if (Database::num_rows($rs) > 0) {
@@ -3680,7 +3755,6 @@ class TrackingCourseLog
     						$row[5] = $obj->title;
     					}
     					break;
-
     				default:
     					break;
     			}
@@ -3690,16 +3764,19 @@ class TrackingCourseLog
     				$row2 .= '<br />'.get_lang('Coach').': '.$coach_name;
     			}
     			$row[2] = $row2;
-                        if (!empty($row['col3'])) {
-                            $row['col3'] = Display::url($row['col3'],api_get_path(WEB_CODE_PATH).'user/userInfo.php?'.api_get_cidreq().'&origin=tracking&uInfo='.$row['user_id']);
-                            $row[3] = $row['col3'];
+                if (!empty($row['col3'])) {
+                    $row['col3'] = Display::url(
+                        $row['col3'],
+                        api_get_path(WEB_CODE_PATH).'user/userInfo.php?'.api_get_cidreq().'&origin=tracking&uInfo='.$row['user_id']
+                    );
+                    $row[3] = $row['col3'];
 
-                            $ip = TrackingUserLog::get_ip_from_user_event($row['user_id'], $row['col5'], true);
-                            if (empty($ip)) {
-                                $ip = get_lang('Unknown');
-                            }
-                            $row[4] = $ip;
-                        }
+                    $ip = TrackingUserLog::get_ip_from_user_event($row['user_id'], $row['col5'], true);
+                    if (empty($ip)) {
+                        $ip = get_lang('Unknown');
+                    }
+                    $row[4] = $ip;
+                }
 
     			$resources[] = $row;
     		}
@@ -3708,7 +3785,13 @@ class TrackingCourseLog
     	return $resources;
     }
 
-    function get_tool_name_table($tool) {
+    /**
+     * @param string $tool
+     *
+     * @return array
+     */
+    public static function get_tool_name_table($tool)
+    {
     	switch ($tool) {
     		case 'document':
     			$table_name = TABLE_DOCUMENT;
@@ -3764,15 +3847,19 @@ class TrackingCourseLog
     			$table_name = $tool;
     		break;
     	}
-    	return array('table_name' => $table_name,'link_tool' => $link_tool,'id_tool' => $id_tool);
+
+    	return array(
+            'table_name' => $table_name,
+            'link_tool' => $link_tool,
+            'id_tool' => $id_tool
+        );
     }
 
-    static function display_additional_profile_fields()
+    public static function display_additional_profile_fields()
     {
     	// getting all the extra profile fields that are defined by the platform administrator
     	$extra_fields = UserManager :: get_extra_fields(0,50,5,'ASC');
 
-
     	// creating the form
     	$return = '<form action="courseLog.php" method="get" name="additional_profile_field_form" id="additional_profile_field_form">';
 
@@ -3819,7 +3906,7 @@ class TrackingCourseLog
      * @since October 2009
      * @version 1.8.7
      */
-    function get_addtional_profile_information_of_field($field_id)
+    public function get_addtional_profile_information_of_field($field_id)
     {
     	// Database table definition
     	$table_user             = Database::get_main_table(TABLE_MAIN_USER);
@@ -3849,7 +3936,7 @@ class TrackingCourseLog
      * @since    Nov 2009
      * @version    1.8.6.2
      */
-    function get_addtional_profile_information_of_field_by_user($field_id, $users)
+    public function get_addtional_profile_information_of_field_by_user($field_id, $users)
     {
     	// Database table definition
     	$table_user                 = Database::get_main_table(TABLE_MAIN_USER);
@@ -3902,18 +3989,18 @@ class TrackingCourseLog
      * count the number of students in this course (used for SortableTable)
      * Deprecated
      */
-    function count_student_in_course()
+    public function count_student_in_course()
     {
     	global $nbStudents;
     	return $nbStudents;
     }
 
-    function sort_users($a, $b)
+    public function sort_users($a, $b)
     {
     	return strcmp(trim(api_strtolower($a[$_SESSION['tracking_column']])), trim(api_strtolower($b[$_SESSION['tracking_column']])));
     }
 
-    function sort_users_desc($a, $b)
+    public function sort_users_desc($a, $b)
     {
     	return strcmp( trim(api_strtolower($b[$_SESSION['tracking_column']])), trim(api_strtolower($a[$_SESSION['tracking_column']])));
     }
@@ -3922,7 +4009,7 @@ class TrackingCourseLog
      * Get number of users for sortable with pagination
      * @return int
      */
-    static function get_number_of_users()
+    public static function get_number_of_users()
     {
     	global $user_ids;
     	return count($user_ids);
@@ -3936,7 +4023,7 @@ class TrackingCourseLog
      * @param $direction
      * @return array
      */
-    static function get_user_data($from, $number_of_items, $column, $direction)
+    public static function get_user_data($from, $number_of_items, $column, $direction)
     {
     	global $user_ids, $course_code, $additional_user_profile_info, $export_csv, $is_western_name_order, $csv_content, $session_id, $_configuration;
 
@@ -4120,7 +4207,7 @@ class TrackingUserLog
     /**
      * Displays the number of logins every month for a specific user in a specific course.
      */
-    function display_login_tracking_info($view, $user_id, $course_id, $session_id = 0)
+    public function display_login_tracking_info($view, $user_id, $course_id, $session_id = 0)
     {
     	$MonthsLong = $GLOBALS['MonthsLong'];
 
@@ -4200,11 +4287,10 @@ class TrackingUserLog
      * Displays the exercise results for a specific user in a specific course.
      * @todo remove globals
      */
-    function display_exercise_tracking_info($view, $user_id, $course_id)
+    public function display_exercise_tracking_info($view, $user_id, $course_id)
     {
-    	global $TABLECOURSE_EXERCICES, $TABLETRACK_EXERCICES, $dateTimeFormatLong;
-    	if(substr($view,1,1) == '1')
-    	{
+    	global $TBL_TRACK_HOTPOTATOES, $TABLECOURSE_EXERCICES, $TABLETRACK_EXERCICES, $dateTimeFormatLong;
+    	if(substr($view,1,1) == '1') {
     		$new_view = substr_replace($view,'0',1,1);
     		echo "<tr>
                     <td valign='top'>
@@ -4302,7 +4388,7 @@ class TrackingUserLog
      * Displays the student publications for a specific user in a specific course.
      * @todo remove globals
      */
-    function display_student_publications_tracking_info($view, $user_id, $course_id)
+    public function display_student_publications_tracking_info($view, $user_id, $course_id)
     {
     	global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK, $dateTimeFormatLong, $_course;
     	if (substr($view,2,1) == '1') {
@@ -4368,10 +4454,10 @@ class TrackingUserLog
      * Displays the links followed for a specific user in a specific course.
      * @todo remove globals
      */
-    function display_links_tracking_info($view, $user_id, $course_id)
+    public function display_links_tracking_info($view, $user_id, $course_id)
     {
     	global $TABLETRACK_LINKS, $TABLECOURSE_LINKS;
-    	if(substr($view,3,1) == '1') {
+    	if (substr($view,3,1) == '1') {
     		$new_view = substr_replace($view,'0',3,1);
     		echo "
                 <tr>
@@ -4428,7 +4514,7 @@ class TrackingUserLog
      * @param    int        Session id (optional, default = 0)
      * @return     void
      */
-    static function display_document_tracking_info($view, $user_id, $course_id, $session_id = 0) {
+    public static function display_document_tracking_info($view, $user_id, $course_id, $session_id = 0) {
 
     	// protect data
     	$user_id     = intval($user_id);
@@ -4436,8 +4522,7 @@ class TrackingUserLog
     	$session_id = intval($session_id);
 
     	$downloads_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
-    	if(substr($view,4,1) == '1')
-    	{
+    	if(substr($view,4,1) == '1') {
     		$new_view = substr_replace($view,'0',4,1);
     		echo "
                 <tr>
@@ -4497,7 +4582,7 @@ class TrackingUserLog
      * @return string IP address (or false on error)
      * @assert (0,0) === false
      */
-    static function get_ip_from_user_event($user_id, $event_date, $return_as_link = false, $body_replace = null) {
+    public static function get_ip_from_user_event($user_id, $event_date, $return_as_link = false, $body_replace = null) {
         if (empty($user_id) or empty($event_date)) {
             return false;
         }
@@ -4526,7 +4611,7 @@ class TrackingUserLogCSV
     /**
      * Displays the number of logins every month for a specific user in a specific course.
      */
-    function display_login_tracking_info($view, $user_id, $course_id, $session_id = 0)
+    public function display_login_tracking_info($view, $user_id, $course_id, $session_id = 0)
     {
     	$MonthsLong = $GLOBALS['MonthsLong'];
     	$track_access_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ACCESS);
@@ -4572,7 +4657,7 @@ class TrackingUserLogCSV
      * Displays the exercise results for a specific user in a specific course.
      * @todo remove globals
      */
-    function display_exercise_tracking_info($view, $user_id, $course_id)
+    public function display_exercise_tracking_info($view, $user_id, $course_id)
     {
     	global $TABLECOURSE_EXERCICES, $TABLETRACK_EXERCICES, $TABLETRACK_HOTPOTATOES, $dateTimeFormatLong;
     	if (substr($view,1,1) == '1') {
@@ -4639,7 +4724,7 @@ class TrackingUserLogCSV
      * Displays the student publications for a specific user in a specific course.
      * @todo remove globals
      */
-    function display_student_publications_tracking_info($view, $user_id, $course_id)
+    public function display_student_publications_tracking_info($view, $user_id, $course_id)
     {
     	global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK, $dateTimeFormatLong, $_course;
     	if (substr($view,2,1) == '1') {
@@ -4676,9 +4761,10 @@ class TrackingUserLogCSV
      * Displays the links followed for a specific user in a specific course.
      * @todo remove globals
      */
-    function display_links_tracking_info($view, $user_id, $course_id)
+    public function display_links_tracking_info($view, $user_id, $course_id)
     {
     	global $TABLETRACK_LINKS, $TABLECOURSE_LINKS;
+        $line = null;
     	if (substr($view,3,1) == '1') {
     		$new_view = substr_replace($view,'0',3,1);
     		$title[1]=get_lang('LinksDetails');
@@ -4711,7 +4797,7 @@ class TrackingUserLogCSV
      * @param    int        Session id (optional, default = 0)
      * @return     void
      */
-    function display_document_tracking_info($view, $user_id, $course_id, $session_id = 0)
+    public function display_document_tracking_info($view, $user_id, $course_id, $session_id = 0)
     {
     	// protect data
     	$user_id     = intval($user_id);

+ 7 - 27
main/inc/lib/usergroup.lib.php

@@ -11,8 +11,7 @@
 require_once 'model.lib.php';
 
 /**
- * Class
- * @package chamilo.library
+ * Class UserGroup
  */
 class UserGroup extends Model
 {
@@ -103,7 +102,6 @@ class UserGroup extends Model
             }
 
             return 0;
-
         } else {
             $row = Database::select(
                 'count(*) as count',
@@ -285,9 +283,7 @@ class UserGroup extends Model
                     LEFT OUTER JOIN {$this->usergroup_rel_course_table} urc
                     ON (u.id = urc.usergroup_id AND course_id = $course_id)
             ";
-
         } else {
-
             $sql = "SELECT DISTINCT u.id, name
                     FROM {$this->table} u
                     LEFT OUTER JOIN {$this->usergroup_rel_course_table} urc
@@ -710,9 +706,9 @@ class UserGroup extends Model
             $urlId = api_get_current_access_url_id();
             $from = $this->table." u INNER JOIN {$this->access_url_rel_usergroup} a ON (u.id = a.usergroup_id)";
             $options = array('where' => array('access_url_id = ? ' => $urlId));
-            return Database::select('name, description', $from, $options);
+            return Database::select('a.id, name, description', $from, $options);
         } else {
-            return Database::select('name, description', $this->table, $options);
+            return Database::select('id, name, description', $this->table, $options);
         }
     }
 
@@ -765,7 +761,7 @@ class UserGroup extends Model
     }
 
     /**
-     * @param $id
+     * @param int $id
      * @return bool|void
      */
     public function delete($id)
@@ -794,8 +790,8 @@ class UserGroup extends Model
     }
 
     /**
-     * @param $id
-     * @param $urlId
+     * @param int $id
+     * @param int $urlId
      */
     public function unsubscribeToUrl($id, $urlId)
     {
@@ -836,24 +832,8 @@ class UserGroup extends Model
             }
         }
         $response->addAssign('ajax_list_courses','innerHTML', api_utf8_encode($return));
-        return $response;
 
+        return $response;
     }
-    /**
-    * Add a user to a class. If the class is subscribed to a course, the new
-    * user will also be subscribed to that course.
-    * @param int $user_id The user id
-    * @param int $class_id The class id
-    */
-    public function addUser($userId, $classId)
-    {   
-        $table_rel_user = Database::get_main_table(TABLE_USERGROUP_REL_USER);
-        $userId  = intval($userId);
-        $classId = intval($classId);
-        $sql = "INSERT INTO $table_rel_user SET user_id = '".$userId."', usergroup_id='".$classId."'";
-	 Database::query($sql);
-    }
-    
-       
 }
 /* CREATE TABLE IF NOT EXISTS access_url_rel_usergroup (access_url_id int unsigned NOT NULL, usergroup_id int unsigned NOT NULL, PRIMARY KEY (access_url_id, usergroup_id));*/

+ 5 - 5
main/inc/lib/usermanager.lib.php

@@ -2177,7 +2177,7 @@ class UserManager
               FROM $tbl_session as session
                   LEFT JOIN $tbl_session_category session_category
                   ON (session_category_id = session_category.id)
-                  INNER JOIN $tbl_session_course_user as session_rel_course_user
+                  LEFT JOIN $tbl_session_course_user as session_rel_course_user
                   ON (session_rel_course_user.id_session = session.id)
               WHERE (
                         session_rel_course_user.id_user = $user_id OR
@@ -4205,8 +4205,8 @@ class UserManager
                     }
                     break;
                 case self::USER_FIELD_TYPE_DATE:
-                    $form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3], array('form_name' => $form_name));
-                    $form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
+                    $form->addElement('date_picker', 'extra_'.$field_details[1], $field_details[3]);
+                    //$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
                     $defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
                     $form->setDefaults($defaults);
                     if (!$admin_permissions) {
@@ -4216,8 +4216,8 @@ class UserManager
                     $form->applyFilter('theme', 'trim');
                     break;
                 case self::USER_FIELD_TYPE_DATETIME:
-                    $form->addElement('datepicker', 'extra_'.$field_details[1], $field_details[3], array('form_name' => $form_name));
-                    $form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
+                    $form->addElement('date_time_picker', 'extra_'.$field_details[1], $field_details[3]);
+                    //$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
                     $defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
                     $form->setDefaults($defaults);
                     if (!$admin_permissions) {

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

@@ -2199,7 +2199,7 @@ class learnpath
         $itemInfo = api_get_item_property_info($course['real_id'], TOOL_LEARNPATH, $lp_id, $sessionId);
 
         // If the item was deleted.
-        if ($itemInfo['visibility'] == 2) {
+        if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
             return false;
         }
 

+ 1 - 3
main/newscorm/lp_view.php

@@ -321,8 +321,6 @@ if ($is_allowed_to_edit) {
     $interbreadcrumb[] = array('url' => 'lp_controller.php?action=list&isStudentView=false', 'name' => get_lang('LearningPaths'));
     $interbreadcrumb[] = array('url' => api_get_self()."?action=add_item&type=step&lp_id=".$_SESSION['oLP']->lp_id."&isStudentView=false", 'name' => $_SESSION['oLP']->get_name());
     $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Preview'));
-    //$interbreadcrumb[] = array('type' => 'right', 'url' => api_get_self()."?action=add_item&type=step&lp_id=".$_SESSION['oLP']->lp_id."&isStudentView=false", 'name' => get_lang('Edit'), 'class' => 'btn btn-mini btn-warning');
-
     echo return_breadcrumb($interbreadcrumb, null, null);
     echo '</div>';
 }
@@ -378,7 +376,7 @@ if ($is_allowed_to_edit) {
         <!-- end image preview Layout -->
 
         <div id="author_name">
-            <?php echo $_SESSION['oLP']->get_author(); ?> 
+            <?php echo $_SESSION['oLP']->get_author(); ?>
         </div>
 
         <!-- media player layout -->

+ 8 - 11
main/newscorm/storageapi.php

@@ -43,7 +43,7 @@ switch ($_REQUEST['action']) {
 		}
 		break;
 	case "stackgetall":
-		if (storage_can_set($_REQUEST['svuser'])) 
+		if (storage_can_set($_REQUEST['svuser']))
 			print storage_stack_getall($_REQUEST['svuser'], $_REQUEST['svcourse'], $_REQUEST['svsco'], $_REQUEST['svkey']);
 		break;
 	case "getposition":
@@ -82,8 +82,7 @@ function storage_get($sv_user, $sv_course, $sv_sco, $sv_key) {
 		$row = Database::fetch_assoc($res);
 		if (get_magic_quotes_gpc()) {
 			return stripslashes($row['sv_value']);
-		}
-		else {
+		} else {
 			return $row['sv_value'];
 		}
 	}
@@ -91,7 +90,7 @@ function storage_get($sv_user, $sv_course, $sv_sco, $sv_key) {
 		return null;
 	}
 }
-			
+
 function storage_get_leaders($sv_user, $sv_course, $sv_sco, $sv_key, $sv_asc, $sv_length) {
 
 	// get leaders
@@ -122,12 +121,12 @@ function storage_get_leaders($sv_user, $sv_course, $sv_sco, $sv_key, $sv_asc, $s
 //				$row["values"][$dataRow["variable"]] = $dataRow["value"];
 //		}
 		$result[] = $row;
-	} 
+	}
 	return json_encode($result);
 }
 
 function storage_get_position($sv_user, $sv_course, $sv_sco, $sv_key, $sv_asc, $sv_length) {
-	$sql = "select count(list.user_id) as position 
+	$sql = "select count(list.user_id) as position
 		from ".Database::get_main_table(TABLE_TRACK_STORED_VALUES)." search,
 			".Database::get_main_table(TABLE_TRACK_STORED_VALUES)." list
 		where search.user_id= '$sv_user'
@@ -179,7 +178,7 @@ function storage_getall($sv_user, $sv_course, $sv_sco) {
 function storage_stack_push($sv_user, $sv_course, $sv_sco, $sv_key, $sv_value) {
 	$sv_value = Database::escape_string($sv_value);
 	Database::query("start transaction");
-	$sqlorder = "select ifnull((select max(stack_order) 
+	$sqlorder = "select ifnull((select max(stack_order)
 		from ".Database::get_main_table(TABLE_TRACK_STORED_VALUES_STACK)."
 		where user_id= '$sv_user'
 		and sco_id='$sv_sco'
@@ -229,12 +228,10 @@ function storage_stack_pop($sv_user, $sv_course, $sv_sco, $sv_key) {
 		Database::query("commit");
 		if (get_magic_quotes_gpc()) {
 			return stripslashes($rowselect['sv_value']);
-		}
-		else {
+		} else {
 			return $rowselect['sv_value'];
 		}
-	}
-	else {
+	} else {
 		Database::query("rollback");
 		return null;
 	}

+ 54 - 45
main/survey/create_new_survey.php

@@ -1,5 +1,4 @@
 <?php
-
 /* For licensing terms, see /license.txt */
 
 /**
@@ -27,24 +26,25 @@ require_once 'survey.lib.php';
 require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/gradebook_functions.inc.php';
 
-$htmlHeadXtra[] = '<script type="text/javascript">
-		function advanced_parameters() {
-			if(document.getElementById(\'options\').style.display == \'none\') {
-					document.getElementById(\'options\').style.display = \'block\';
-					document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_hide.gif', get_lang('Hide'), array('style' => 'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
-			} else {
-					document.getElementById(\'options\').style.display = \'none\';
-					document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_show.gif', get_lang('Show'), array('style' => 'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
-			}
-		}
-
-		function setFocus(){
-		  $("#surveycode_title").focus();
-		}
-		$(document).ready(function () {
-		  setFocus();
-		});
-	</script>';
+$htmlHeadXtra[] = '<script>
+    function advanced_parameters() {
+        if (document.getElementById(\'options\').style.display == \'none\') {
+            document.getElementById(\'options\').style.display = \'block\';
+            document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_hide.gif', get_lang('Hide'), array('style' => 'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+        } else {
+            document.getElementById(\'options\').style.display = \'none\';
+            document.getElementById(\'plus_minus\').innerHTML=\'&nbsp;'.Display::return_icon('div_show.gif', get_lang('Show'), array('style' => 'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'\';
+        }
+    }
+
+    function setFocus(){
+        $("#surveycode_title").focus();
+    }
+
+    $(document).ready(function () {
+      setFocus();
+    });
+</script>';
 
 // Database table definitions
 $table_survey = Database :: get_course_table(TABLE_SURVEY);
@@ -55,39 +55,45 @@ $table_gradebook_link = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 /** @todo this has to be moved to a more appropriate place (after the display_header of the code) */
 // If user is not teacher or if he's a coach trying to access an element out of his session
 if (!api_is_allowed_to_edit()) {
-    if (!api_is_course_coach() || (!empty($_GET['survey_id']) && !api_is_element_in_the_session(TOOL_SURVEY, intval($_GET['survey_id'])))) {
+    if (!api_is_course_coach() ||
+        (!empty($_GET['survey_id']) &&
+        !api_is_element_in_the_session(TOOL_SURVEY, $_GET['survey_id']))
+    ) {
         api_not_allowed(true);
         exit;
     }
 }
 
 // Getting the survey information
-$survey_id = Security::remove_XSS($_GET['survey_id']);
+$survey_id = isset($_GET['survey_id']) ? intval($_GET['survey_id']) : null;
 $survey_data = survey_manager::get_survey($survey_id);
 
 // Additional information
 $course_id = api_get_course_id();
 $session_id = api_get_session_id();
-$gradebook_link_type = 8; // LINK_SURVEY
-
-/* $urlname = strip_tags(api_substr(api_html_entity_decode($survey_data['title'], ENT_QUOTES), 0, 40));
-  if (api_strlen(strip_tags($survey_data['title'])) > 40) {
-  $urlname .= '...';
-  } */
-$urlname = $survey_data['title'];
-
+$gradebook_link_type = 8;
+$urlname = isset($survey_data['title']) ? strip_tags($survey_data['title']) : null;
 
 // Breadcrumbs
 if ($_GET['action'] == 'add') {
-    $interbreadcrumb[] = array('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
+    $interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq(),
+        'name' => get_lang('SurveyList')
+    );
     $tool_name = get_lang('CreateNewSurvey');
 }
 if ($_GET['action'] == 'edit' && is_numeric($survey_id)) {
-    $interbreadcrumb[] = array('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
-    $interbreadcrumb[] = array('url' => 'survey.php?survey_id='.$survey_id, 'name' => strip_tags($urlname));
+    $interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq(),
+        'name' => get_lang('SurveyList')
+    );
+    $interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id.'&'.api_get_cidreq(),
+        'name' => Security::remove_XSS($urlname)
+    );
     $tool_name = get_lang('EditSurvey');
 }
-
+$gradebook_link_id = null;
 // Getting the default values
 if ($_GET['action'] == 'edit' && isset($survey_id) && is_numeric($survey_id)) {
     $defaults = $survey_data;
@@ -105,9 +111,9 @@ if ($_GET['action'] == 'edit' && isset($survey_id) && is_numeric($survey_id)) {
     }
 } else {
     $defaults['survey_language'] = $_course['language'];
-    $defaults['start_date'] = date('d-F-Y H:i');
+    $defaults['start_date'] = date('Y-m-d', api_strtotime(api_get_local_time()));
     $startdateandxdays = time() + 864000; // today + 10 days
-    $defaults['end_date'] = date('d-F-Y H:i', $startdateandxdays);
+    $defaults['end_date'] = date('Y-m-d', $startdateandxdays);
     //$defaults['survey_share']['survey_share'] = 0;
     //$form_share_value = 1;
     $defaults['anonymous'] = 0;
@@ -124,7 +130,6 @@ if ($_GET['action'] == 'edit' && isset($survey_id) && is_numeric($survey_id)) {
 }
 
 $survey_code = $form->addElement('text', 'survey_code', get_lang('SurveyCode'), array('size' => '20', 'maxlength' => '20', 'id' => 'surveycode_title'));
-//$form->applyFilter('survey_code', 'html_filter');
 
 if ($_GET['action'] == 'edit') {
     $survey_code->freeze();
@@ -146,8 +151,8 @@ $form->addElement('html_editor', 'survey_subtitle', get_lang('SurveySubTitle'),
 
 // Pass the language of the survey in the form
 $form->addElement('hidden', 'survey_language');
-$form->addElement('datepickerdate', 'start_date', get_lang('StartDate'), array('form_name' => 'survey'));
-$form->addElement('datepickerdate', 'end_date', get_lang('EndDate'), array('form_name' => 'survey'));
+$form->addElement('date_picker', 'start_date', get_lang('StartDate'));
+$form->addElement('date_picker', 'end_date', get_lang('EndDate'));
 
 //$group = '';
 //$group[] =& HTML_QuickForm::createElement('radio', 'survey_share', null, get_lang('Yes'), $form_share_value);
@@ -159,8 +164,12 @@ $form->addElement('html_editor', 'survey_introduction', get_lang('SurveyIntroduc
 $form->addElement('html_editor', 'survey_thanks', get_lang('SurveyThanks'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '130', 'ToolbarStartExpanded' => false));
 
 // Aditional Parameters
-$form->addElement('advanced_settings', '<a href="javascript: void(0);" onclick="javascript: advanced_parameters();" >
-        <span id="plus_minus">&nbsp;'.Display::return_icon('div_show.gif', null, array('style' => 'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'</span></a>');
+$form->addElement(
+    'advanced_settings',
+    '<a href="javascript: void(0);" onclick="javascript: advanced_parameters();">
+        <span id="plus_minus">&nbsp;'.
+        Display::return_icon('div_show.gif', null, array('style' => 'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedParameters').'</span></a>'
+);
 
 $form->addElement('html', '<div id="options" style="display: none;">');
 
@@ -187,14 +196,13 @@ if ($_GET['action'] == 'add') {
     $defaults['parent_id'] = 0;
 }
 
-if ($survey_data['survey_type'] == 1 || $_GET['action'] == 'add') {
+if (isset($survey_data['survey_type']) && $survey_data['survey_type'] == 1 || $_GET['action'] == 'add') {
     $form->addElement('checkbox', 'one_question_per_page', null, get_lang('OneQuestionPerPage'));
     $form->addElement('checkbox', 'shuffle', null, get_lang('ActivateShuffle'));
 }
-
+$input_name_list = null;
 if ((isset($_GET['action']) && $_GET['action'] == 'edit') && !empty($survey_id)) {
     if ($survey_data['anonymous'] == 0) {
-
         $form->addElement('checkbox', 'show_form_profile', null, get_lang('ShowFormProfile'), 'onclick="javascript: if(this.checked){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"');
 
         if ($survey_data['show_form_profile'] == 1) {
@@ -212,7 +220,8 @@ if ((isset($_GET['action']) && $_GET['action'] == 'edit') && !empty($survey_id))
                     $input_name_list.= 'profile_'.$key.',';
                 }
             }
-            // Necesary to know the fields
+
+            // Necessary to know the fields
             $form->addElement('hidden', 'input_name_list', $input_name_list);
 
             // Set defaults form fields
@@ -309,7 +318,7 @@ if ($form->validate()) {
         Display::display_confirmation_message($return['message'], false);
     } else {
         // Redirecting to the survey page (whilst showing the return message)
-        header('location:survey.php?survey_id='.$return['id'].'&message='.$return['message']);
+        header('location: '.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$return['id'].'&message='.$return['message'].'&'.api_get_cidreq());
         exit;
     }
 } else {

+ 175 - 91
main/survey/fillsurvey.php

@@ -1,18 +1,17 @@
 <?php
-
 /* For licensing terms, see /license.txt */
 
 /**
- *    @package chamilo.survey
- *     @author unknown, the initial survey that did not make it in 1.8 because of bad code
- *     @author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts of the code
- *    @author Julio Montoya Armas <gugli100@gmail.com>, Chamilo: Personality Test modification and rewriting large parts of the code as well
- *     @version $Id: survey_list.php 10680 2007-01-11 21:26:23Z pcool $
- *
- *     @todo use quickforms for the forms
- *     @todo check if the user already filled the survey and if this is the case then the answers have to be updated and not stored again.
- *           alterantively we could not allow people from filling the survey twice.
- *     @todo performance could be improved if not the survey_id was stored with the invitation but the survey_code
+*    @package chamilo.survey
+*     @author unknown, the initial survey that did not make it in 1.8 because of bad code
+*     @author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts of the code
+*    @author Julio Montoya Armas <gugli100@gmail.com>, Chamilo: Personality Test modification and rewriting large parts of the code as well
+*     @version $Id: survey_list.php 10680 2007-01-11 21:26:23Z pcool $
+*
+*     @todo use quickforms for the forms
+*     @todo check if the user already filled the survey and if this is the case then the answers have to be updated and not stored again.
+*           alterantively we could not allow people from filling the survey twice.
+*     @todo performance could be improved if not the survey_id was stored with the invitation but the survey_code
  */
 // Language file that needs to be included
 $language_file = 'survey';
@@ -32,7 +31,10 @@ require_once 'survey.lib.php';
 
 // Breadcrumbs
 if (!empty($_user)) {
-    $interbreadcrumb[] = array('url' => 'survey_list.php?cidReq='.Security::remove_XSS($_GET['course']), 'name' => get_lang('SurveyList'));
+    $interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?cidReq='.Security::remove_XSS($_GET['course']),
+        'name' => get_lang('SurveyList')
+    );
 }
 
 // Database table definitions
@@ -41,7 +43,6 @@ $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_user = Database :: get_main_table(TABLE_MAIN_USER);
 
 // Check if user is anonymous or not
@@ -63,7 +64,7 @@ if (empty($course_info)) {
 }
 
 $course_id = $course_info['real_id'];
-$surveyCode = isset($_GET['scode']) ? Database::escape_string($_GET['scode']) : ''; 
+$surveyCode = isset($_GET['scode']) ? Database::escape_string($_GET['scode']) : '';
 
 if ($surveyCode != "") {
     // Firstly we check if this survey is ready for anonymous use:
@@ -73,11 +74,11 @@ if ($surveyCode != "") {
     // If is anonymous and is not allowed to take the survey to anonymous users, forbid access:
     if (!isset($rowAnonymous['anonymous']) || ($rowAnonymous['anonymous'] == 0 && api_is_anonymous($_user['user_id'], true)) || count($rowAnonymous) == 0) {
         api_not_allowed();
-    } 
+    }
 // If is anonymous and it is allowed to take the survey as anonymous, mark survey as anonymous:
 } else {
     //nothing to do
-} 
+}
 
 // Header
 Display :: display_header(get_lang('ToolSurvey'));
@@ -99,9 +100,9 @@ if ($invitationcode == 'auto' && isset($_GET['scode'])) {
 	      $autoInvitationcode = "auto-ANONY_".md5(time())."-$surveyCode";
     } else {
         // New invitation code from userid
-        $autoInvitationcode = "auto-$userid-$surveyCode"; 				
+        $autoInvitationcode = "auto-$userid-$surveyCode";
     }
-	
+
     // The survey code must exist in this course, or the URL is invalid
     $sql = "SELECT * FROM $table_survey WHERE c_id = $course_id AND code = '".$surveyCode."'";
     $result = Database::query($sql);
@@ -125,7 +126,10 @@ if ($invitationcode == 'auto' && isset($_GET['scode'])) {
 }
 
 // Now we check if the invitationcode is valid
-$sql = "SELECT * FROM $table_survey_invitation WHERE c_id = $course_id AND 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);
@@ -142,11 +146,12 @@ if ($isAnonymous && isset($_SESSION['surveyuser']) || ($survey_invitation['answe
     exit;
 }
 
-
-
 // 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 c_id = $course_id AND 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) {
@@ -177,7 +182,10 @@ $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 c_id = $course_id AND 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')) {
@@ -206,11 +214,13 @@ if (count($_POST) > 0) {
                         }
                         SurveyUtil::store_answer($survey_invitation['user'], $survey_invitation['survey_id'], $survey_question_id, $option_id, $option_value, $survey_data);
                     }
-                }
-                // All the other question types (open question, multiple choice, percentage, ...)
-                else {
+                } else {
+                    // All the other question types (open question, multiple choice, percentage, ...)
                     if ($types[$survey_question_id] == 'percentage') {
-                        $sql = "SELECT * FROM $table_survey_question_option WHERE c_id = $course_id AND 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'];
@@ -236,8 +246,10 @@ if (count($_POST) > 0) {
             $shuffle = ' ORDER BY RAND() ';
         }
         $sql = "SELECT * FROM $table_survey_question
-                WHERE c_id = $course_id AND survey_id = '".Database::escape_string($survey_invitation['survey_id'])."'
-                AND survey_group_pri = '0' $shuffle";
+                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
         while ($row = Database::fetch_array($result, 'ASSOC')) {
@@ -309,8 +321,12 @@ if ($survey_data['form_fields'] != '' && $survey_data['anonymous'] == 0 && is_ar
     }
 
     // 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;'))
+    $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;'))
     );
 
     if (api_is_western_name_order()) {
@@ -519,27 +535,55 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
                 // Get the user into survey answer table (user or anonymus)
                 $my_user_id = ($survey_data['anonymous'] == 1) ? $_SESSION['surveyuser'] : api_get_user_id();
 
-                $sql = "SELECT survey_question.survey_group_sec1, survey_question.survey_group_sec2, survey_question.survey_group_pri,
-                    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 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.c_id =  $course_id
-                    ORDER BY survey_question.sort, survey_question_option.sort ASC";
+                $sql = "SELECT
+                            survey_question.survey_group_sec1,
+                            survey_question.survey_group_sec2,
+                            survey_question.survey_group_pri,
+                            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 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.c_id =  $course_id
+                                ORDER BY survey_question.sort, survey_question_option.sort ASC";
             } else {
-                $sql = "SELECT survey_question.survey_group_sec1, survey_question.survey_group_sec2, survey_question.survey_group_pri,
-                    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 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.c_id =  $course_id
-                    ORDER BY survey_question.sort, survey_question_option.sort ASC";
+                $sql = "SELECT
+                            survey_question.survey_group_sec1,
+                            survey_question.survey_group_sec2,
+                            survey_question.survey_group_pri,
+                            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 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.c_id =  $course_id
+                        ORDER BY survey_question.sort, survey_question_option.sort ASC";
             }
 
             $result = Database::query($sql);
@@ -559,9 +603,8 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
                     $questions[$row['sort']]['type'] = $row['type'];
                     $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
                     $questions[$row['sort']]['maximum_score'] = $row['max_value'];
-                }
-                // If the type is a pagebreak we are finished loading the questions for this page
-                else {
+                } else {
+                    // If the type is a pagebreak we are finished loading the questions for this page
                     break;
                 }
                 $counter++;
@@ -584,12 +627,14 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
             // Get current user results
             $results = array();
             $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."' AND
-                           survey_answer.c_id = $course_id AND
-                           survey_question.c_id = $course_id AND
+                    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."' 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
                     ";
@@ -606,16 +651,20 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
             $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
-                    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_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
+                        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_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
@@ -775,9 +824,11 @@ 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 c_id = $course_id AND survey_id = '".$my_survey_id."'
-                                       AND ($secondary )
-                                     ORDER BY sort ASC";
+                                 WHERE
+                                    c_id = $course_id AND
+                                    survey_id = '".$my_survey_id."' AND
+                                    ($secondary )
+                                 ORDER BY sort ASC";
                         $result = Database::query($sql);
                         $counter = 0;
                         while ($row = Database::fetch_array($result, 'ASSOC')) {
@@ -811,15 +862,28 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
                     //echo '<pre>'; print_r($paged_questions_sec); echo '</pre>';
                     if (is_array($paged_questions_sec)) {
 
-                        $sql = "SELECT survey_question.survey_group_sec1, survey_question.survey_group_sec2, survey_question.survey_group_pri,
-                                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
+                        $sql = "SELECT
+                                    survey_question.survey_group_sec1,
+                                    survey_question.survey_group_sec2,
+                                    survey_question.survey_group_pri,
+                                    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 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]).")
+                                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);
@@ -870,9 +934,12 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 
             if (empty($_SESSION['paged_questions'])) {
                 $sql = "SELECT * FROM $table_survey_question
-                             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." ";
+                        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 />';
                 $result = Database::query($sql);
                 $counter = 0;
@@ -914,15 +981,28 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
                 if ($imploded != '') {
                     // The answers are always in the same order NO shuffle
                     $order_sql = ' BY survey_question.sort, survey_question_option.sort ASC ';
-                    $sql = "SELECT survey_question.survey_group_sec1, survey_question.survey_group_sec2, survey_question.survey_group_pri,
-                            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
+                    $sql = "SELECT
+                                survey_question.survey_group_sec1,
+                                survey_question.survey_group_sec2,
+                                survey_question.survey_group_pri,
+                                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 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.")
+                            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);
@@ -961,7 +1041,11 @@ if (isset($_GET['show']) || isset($_POST['personality'])) {
 }
 
 // Selecting the maximum number of pages
-$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'])."'";
+$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;
 

+ 2 - 3
main/survey/generate_link.php

@@ -1,5 +1,4 @@
 <?php
-
 /* For licensing terms, see /license.txt */
 
 $language_file = 'survey';
@@ -17,8 +16,8 @@ if (empty($survey_id)) {
 
 $survey_data = survey_manager::get_survey($survey_id);
 
-$interbreadcrumb[] = array('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
-$interbreadcrumb[] = array('url' => 'survey.php?survey_id='.$survey_id, 'name' => strip_tags($survey_data['title']));
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php', 'name' => get_lang('SurveyList'));
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id, 'name' => strip_tags($survey_data['title']));
 
 Display::display_header(get_lang('Survey'), 'Survey');
 

+ 2 - 1
main/survey/index.php

@@ -1,3 +1,4 @@
 <?php
 require_once '../inc/global.inc.php';
-header('location: survey_list.php?'.api_get_cidReq());
+header('location: '.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidReq());
+exit;

+ 1 - 6
main/survey/link.php

@@ -3,11 +3,6 @@
 
 require_once '../inc/global.inc.php';
 
-/*
-if (!api_is_allowed_to_edit(false, true)) {
-    api_not_allowed(true);
-}*/
-
 $survey_id = isset($_REQUEST['i']) ? intval($_REQUEST['i']) : null;
 
 if (empty($survey_id)) {
@@ -41,4 +36,4 @@ if ($hash_is_valid && $course_info) {
     }
 } else {
     api_not_allowed(true);
-}
+}

+ 49 - 29
main/survey/preview.php

@@ -34,22 +34,28 @@ $surveyId = Database::escape_string($_GET['survey_id']);
 $userInvited = 0;
 
 //query to ask if logged user is allowed to see the preview (if he is invited of he is a teacher)
-$sql = "SELECT survey_invitation.user FROM $table_survey_invitation survey_invitation LEFT JOIN $table_survey survey
-       ON survey_invitation.survey_code = survey.code WHERE survey_invitation.c_id = $course_id AND survey.survey_id = $surveyId AND survey_invitation.user = $userId";
+$sql = "SELECT survey_invitation.user
+        FROM $table_survey_invitation survey_invitation
+        LEFT JOIN $table_survey survey
+        ON survey_invitation.survey_code = survey.code
+        WHERE
+          survey_invitation.c_id = $course_id AND
+          survey.survey_id = $surveyId AND
+          survey_invitation.user = $userId";
 $result = Database::query($sql);
 if (Database::num_rows($result) > 0) {
-    $userInvited = 1;    
+    $userInvited = 1;
 }
-if($userInvited == 0) {
-    if(!api_is_allowed_to_edit()) {    
+if ($userInvited == 0) {
+    if(!api_is_allowed_to_edit()) {
         api_not_allowed();
-    }                
+    }
 }
 // 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'));
-	Display :: display_error_message(get_lang('InvallidSurvey'), false);
-	Display :: display_footer();
+	Display::display_header(get_lang('SurveyPreview'));
+	Display::display_error_message(get_lang('InvallidSurvey'), false);
+	Display::display_footer();
 	exit;
 }
 
@@ -58,22 +64,17 @@ $survey_id = intval($_GET['survey_id']);
 $survey_data = survey_manager::get_survey($survey_id);
 
 if (empty($survey_data)) {
-	Display :: display_header(get_lang('SurveyPreview'));
-	Display :: display_error_message(get_lang('InvallidSurvey'), false);
-	Display :: display_footer();
+	Display::display_header(get_lang('SurveyPreview'));
+	Display::display_error_message(get_lang('InvallidSurvey'), false);
+	Display::display_footer();
 	exit;
 }
 
-/*$urlname = strip_tags(api_substr(api_html_entity_decode($survey_data['title'], ENT_QUOTES), 0, 40));
-if (api_strlen(strip_tags($survey_data['title'])) > 40) {
-	$urlname .= '...';
-}*/
-
 $urlname = strip_tags($survey_data['title']);
 
 // Breadcrumbs
-$interbreadcrumb[] = array('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
-$interbreadcrumb[] = array('url' => 'survey.php?survey_id='.$survey_id, 'name' => $urlname);
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php', 'name' => get_lang('SurveyList'));
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id, 'name' => $urlname);
 
 // Header
 Display :: display_header(get_lang('SurveyPreview'));
@@ -111,13 +112,15 @@ if (api_is_course_admin() || (api_is_course_admin() && $_GET['isStudentView'] ==
 		exit;
 	}
 
+    $questions = array();
+
 	if (isset($_GET['show'])) {
 		// Getting all the questions for this page and add them to a multidimensional array where the first index is the page.
 		// as long as there is no pagebreak fount we keep adding questions to the page
 		$questions_displayed = array();
 		$paged_questions = array();
 		$counter = 0;
-		$sql = "SELECT * FROM $table_survey_question 
+		$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);
@@ -133,15 +136,26 @@ if (api_is_course_admin() || (api_is_course_admin() && $_GET['isStudentView'] ==
         } 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 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.c_id =  $course_id 
+			$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 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.c_id =  $course_id
 					ORDER BY survey_question.sort, survey_question_option.sort ASC";
 
 			$result = Database::query($sql);
@@ -166,8 +180,13 @@ if (api_is_course_admin() || (api_is_course_admin() && $_GET['isStudentView'] ==
 			}
 		}
 	}
+
 	// Selecting the maximum number of pages
-	$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)."'";
+	$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
@@ -176,6 +195,7 @@ if (api_is_course_admin() || (api_is_course_admin() && $_GET['isStudentView'] ==
 	} else {
 		$show = 0;
 	}
+
 	echo '<form id="question" name="question" method="post" action="'.api_get_self().'?survey_id='.Security::remove_XSS($survey_id).'&show='.$show.'">';
 
 	if (is_array($questions) && count($questions) > 0) {

+ 26 - 16
main/survey/question.php

@@ -17,12 +17,12 @@ require_once '../inc/global.inc.php';
 // Including additional libraries
 require_once 'survey.lib.php';
 
-$htmlHeadXtra[] = '<script type="text/javascript">
-						$(document).ready( function() {
-							$("button").click(function() {
-								$("#is_executable").attr("value",$(this).attr("name"));
-							});
-		 				} ); </script>';
+$htmlHeadXtra[] = '<script>
+$(document).ready( function() {
+    $("button").click(function() {
+        $("#is_executable").attr("value",$(this).attr("name"));
+    });
+} ); </script>';
 
 /** @todo this has to be moved to a more appropriate place (after the display_header of the code)*/
 if (!api_is_allowed_to_edit(false, true)) {
@@ -33,7 +33,7 @@ if (!api_is_allowed_to_edit(false, true)) {
 }
 
 // Is valid request
-$is_valid_request = $_REQUEST['is_executable'];
+$is_valid_request = isset($_REQUEST['is_executable']) ? $_REQUEST['is_executable'] : null;
 if ($request_index != $is_valid_request) {
 	if ($request_index == 'save_question') {
 		unset($_POST[$request_index]);
@@ -70,17 +70,20 @@ 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 c_id = '.$course_id.' AND 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');
+		header('Location: '.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.(int)$_GET['survey_id'].'&message='.'YouNeedToCreateGroups');
 		exit;
 	}
 }
 
 // Breadcrumbs
-$interbreadcrumb[] = array ('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
-$interbreadcrumb[] = array ('url' => 'survey.php?survey_id='.Security::remove_XSS($_GET['survey_id']), 'name' => strip_tags($urlname));
+$interbreadcrumb[] = array ('url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php', 'name' => get_lang('SurveyList'));
+$interbreadcrumb[] = array ('url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.Security::remove_XSS($_GET['survey_id']), 'name' => strip_tags($urlname));
 
 // Tool name
 if ($_GET['action'] == 'add') {
@@ -95,7 +98,7 @@ $possible_types = array('personality', 'yesno', 'multiplechoice', 'multiplerespo
 
 // Actions
 $actions = '<div class="actions">';
-$actions .= '<a href="survey.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">'.Display::return_icon('back.png', get_lang('BackToSurvey'),'',ICON_SIZE_MEDIUM).'</a>';
+$actions .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">'.Display::return_icon('back.png', get_lang('BackToSurvey'),'',ICON_SIZE_MEDIUM).'</a>';
 $actions .= '</div>';
 // Checking if it is a valid type
 if (!in_array($_GET['type'], $possible_types)) {
@@ -116,7 +119,11 @@ if (empty($_POST['save_question']) && in_array($_GET['type'], $possible_types))
 		if (isset($_SESSION['temp_sys_message'])) {
 			$error_message=$_SESSION['temp_sys_message'];
 			unset($_SESSION['temp_sys_message']);
-			if ($error_message == 'PleaseEnterAQuestion' || $error_message == 'PleasFillAllAnswer'|| $error_message == 'PleaseChooseACondition'|| $error_message == 'ChooseDifferentCategories') {
+			if ($error_message == 'PleaseEnterAQuestion' ||
+                $error_message == 'PleasFillAllAnswer'||
+                $error_message == 'PleaseChooseACondition'||
+                $error_message == 'ChooseDifferentCategories'
+            ) {
 				Display::display_error_message(get_lang($error_message), true);
 			}
 		}
@@ -154,7 +161,10 @@ if (empty($_POST['save_question']) && in_array($_GET['type'], $possible_types))
 	// An action has been performed (for instance adding a possible answer, moving an answer, ...)
 	if ($_POST) {
 		$form_content = $_POST;
-		$form_content = $form->handle_action($form_content);
+		$form_content = $form->handle_action(
+            $survey_data,
+            $form_content
+        );
 	}
 
 	if ($error_message != '') {
@@ -169,12 +179,12 @@ if (empty($_POST['save_question']) && in_array($_GET['type'], $possible_types))
 		unset($_SESSION['temp_horizontalvertical']);
 	}
 
-	$form->create_form($form_content);
+	$form->create_form($survey_data, $form_content);
 	$form->render_form();
 } else {
 	$form_content = $_POST;
 	$form = new survey_question();
-	$form->handle_action($form_content);
+	$form->handle_action($survey_data, $form_content);
 }
 
 // Footer

+ 27 - 13
main/survey/reporting.php

@@ -17,7 +17,6 @@ $language_file = 'survey';
 require_once '../inc/global.inc.php';
 require_once 'survey.lib.php';
 $this_section = SECTION_COURSES;
-
 $survey_id = intval($_GET['survey_id']);
 
 // Export
@@ -25,17 +24,17 @@ $survey_id = intval($_GET['survey_id']);
  * @todo use export_table_csv($data, $filename = 'export')
  */
 if (isset($_POST['export_report']) && $_POST['export_report']) {
-	switch($_POST['export_format']) {
+	switch ($_POST['export_format']) {
 		case 'xls':
 			$survey_data = survey_manager::get_survey($survey_id);
 			$filename = 'survey_results_'.$survey_id.'.xls';
-			$data = SurveyUtil::export_complete_report_xls($filename, $_GET['user_id']);
+			$data = SurveyUtil::export_complete_report_xls($survey_data, $filename, $_GET['user_id']);
 			exit;
 			break;
 		case 'csv':
 		default:
 			$survey_data = survey_manager::get_survey($survey_id);
-			$data = SurveyUtil::export_complete_report($_GET['user_id']);
+			$data = SurveyUtil::export_complete_report($survey_data, $_GET['user_id']);
 
 			//$filename = 'fileexport.csv';
 			$filename = 'survey_results_'.$survey_id.'.csv';
@@ -61,8 +60,19 @@ if (isset($_POST['export_report']) && $_POST['export_report']) {
 	}
 }
 
+if ($survey_data['anonymous'] == 0) {
+    $people_filled_full_data = true;
+} else {
+    $people_filled_full_data = false;
+}
+$people_filled = survey_manager::get_people_who_filled_survey(
+    $_GET['survey_id'],
+    $people_filled_full_data
+);
+
 // Checking the parameters
-SurveyUtil::check_parameters();
+SurveyUtil::check_parameters($people_filled);
+
 
 /** @todo this has to be moved to a more appropriate place (after the display_header of the code)*/
 if (!api_is_allowed_to_edit(false, true)) {
@@ -92,12 +102,15 @@ if (api_strlen(strip_tags($survey_data['title'])) > 40) {
 }
 
 // Breadcrumbs
-$interbreadcrumb[] = array('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
-$interbreadcrumb[] = array('url' => 'survey.php?survey_id='.$survey_id, 'name' => $urlname);
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php', 'name' => get_lang('SurveyList'));
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id, 'name' => $urlname);
 if (!$_GET['action'] OR $_GET['action'] == 'overview') {
 	$tool_name = get_lang('Reporting');
 } else {
-	$interbreadcrumb[] = array('url' => 'reporting.php?survey_id='.$survey_id, 'name' => get_lang('Reporting'));
+	$interbreadcrumb[] = array(
+        'url' => api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$survey_id,
+        'name' => get_lang('Reporting')
+    );
 	switch ($_GET['action']) {
 		case 'questionreport':
 			$tool_name = get_lang('DetailedReportByQuestion');
@@ -118,19 +131,20 @@ if (!$_GET['action'] OR $_GET['action'] == 'overview') {
 Display::display_header($tool_name, 'Survey');
 
 // Action handling
-SurveyUtil::handle_reporting_actions();
+SurveyUtil::handle_reporting_actions($people_filled);
 
 // Actions bar
 echo '<div class="actions">';
-echo '<a href="survey.php?survey_id='.$survey_id.'">'.Display::return_icon('back.png', get_lang('BackToSurvey'),'',ICON_SIZE_MEDIUM).'</a>';
+echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id.'">'.
+    Display::return_icon('back.png', get_lang('BackToSurvey'),'',ICON_SIZE_MEDIUM).'</a>';
 echo '</div>';
 
 // Content
 if (!$_GET['action'] || $_GET['action'] == 'overview') {
 	$myweb_survey_id = $survey_id;
-	echo '<div class="sectiontitle"><a href="reporting.php?action=questionreport&amp;survey_id='.$myweb_survey_id.'">'.Display::return_icon('survey_reporting_question.gif',get_lang('DetailedReportByQuestion')).' '.get_lang('DetailedReportByQuestion').'</a></div><div class="sectioncomment">'.get_lang('DetailedReportByQuestionDetail').' </div>';
-	echo '<div class="sectiontitle"><a href="reporting.php?action=userreport&amp;survey_id='.$myweb_survey_id.'">'.Display::return_icon('survey_reporting_user.gif',get_lang('DetailedReportByUser')).' '.get_lang('DetailedReportByUser').'</a></div><div class="sectioncomment">'.get_lang('DetailedReportByUserDetail').'.</div>';
-	echo '<div class="sectiontitle"><a href="reporting.php?action=comparativereport&amp;survey_id='.$myweb_survey_id.'">'.Display::return_icon('survey_reporting_comparative.gif',get_lang('ComparativeReport')).' '.get_lang('ComparativeReport').'</a></div><div class="sectioncomment">'.get_lang('ComparativeReportDetail').'.</div>';
+	echo '<div class="sectiontitle"><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=questionreport&amp;survey_id='.$myweb_survey_id.'">'.Display::return_icon('survey_reporting_question.gif',get_lang('DetailedReportByQuestion')).' '.get_lang('DetailedReportByQuestion').'</a></div><div class="sectioncomment">'.get_lang('DetailedReportByQuestionDetail').' </div>';
+	echo '<div class="sectiontitle"><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&amp;survey_id='.$myweb_survey_id.'">'.Display::return_icon('survey_reporting_user.gif',get_lang('DetailedReportByUser')).' '.get_lang('DetailedReportByUser').'</a></div><div class="sectioncomment">'.get_lang('DetailedReportByUserDetail').'.</div>';
+	echo '<div class="sectiontitle"><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=comparativereport&amp;survey_id='.$myweb_survey_id.'">'.Display::return_icon('survey_reporting_comparative.gif',get_lang('ComparativeReport')).' '.get_lang('ComparativeReport').'</a></div><div class="sectioncomment">'.get_lang('ComparativeReportDetail').'.</div>';
 	echo '<div class="sectiontitle"><a href="reporting.php?action=completereport&amp;survey_id='.$myweb_survey_id.'">'.Display::return_icon('survey_reporting_complete.gif',get_lang('CompleteReport')).' '.get_lang('CompleteReport').'</a></div><div class="sectioncomment">'.get_lang('CompleteReportDetail').'</div>';
 }
 

+ 37 - 20
main/survey/survey.download.inc.php

@@ -22,11 +22,14 @@ function check_download_survey($course, $invitation, $doc_url) {
 	// 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_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
 	$table_survey_invitation 		= Database :: get_course_table(TABLE_SURVEY_INVITATION);
 
 	// Now we check if the invitationcode is valid
-	$sql = "SELECT * FROM $table_survey_invitation WHERE c_id = $course_id AND invitation_code = '".Database::escape_string($invitation)."'";
+	$sql = "SELECT * FROM $table_survey_invitation
+	        WHERE
+	            c_id = $course_id AND
+	            invitation_code = '".Database::escape_string($invitation)."'";
 	$result = Database::query($sql);
 	if (Database::num_rows($result) < 1) {
 		Display :: display_error_message(get_lang('WrongInvitationCode'), false);
@@ -47,7 +50,10 @@ function check_download_survey($course, $invitation, $doc_url) {
 	// Fetch survey ID
 
 	// If this is the case there will be a language choice
-	$sql = "SELECT * FROM $table_survey WHERE c_id = $course_id AND 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) {
 		if ($_POST['language']) {
@@ -69,22 +75,33 @@ function check_download_survey($course, $invitation, $doc_url) {
 		$survey_invitation['survey_id'] = $row['survey_id'];
 	}
 
-	$sql = "SELECT count(*) FROM $table_survey WHERE c_id = $course_id AND survey_id = ".$survey_invitation['survey_id']."
-								and (
-									title LIKE '%$doc_url%'
-									or subtitle LIKE '%$doc_url%'
-									or intro LIKE '%$doc_url%'
-									or surveythanks LIKE '%$doc_url%'
-								)
-		union select count(*) from $table_survey_question  where c_id = $course_id AND survey_id = ".$survey_invitation['survey_id']."
-								and (
-									survey_question LIKE '%$doc_url%'
-									or survey_question_comment LIKE '%$doc_url%'
-								)
-		union select count(*) from $table_survey_question_option where c_id = $course_id AND survey_id = ".$survey_invitation['survey_id']."
-								and (
-									option_text LIKE '%$doc_url%'
-								)";
+	$sql = "SELECT count(*)
+	        FROM $table_survey
+	        WHERE
+	            c_id = $course_id AND
+	            survey_id = ".$survey_invitation['survey_id']." AND (
+                    title LIKE '%$doc_url%'
+                    or subtitle LIKE '%$doc_url%'
+                    or intro LIKE '%$doc_url%'
+                    or surveythanks LIKE '%$doc_url%'
+                )
+		    UNION
+		        SELECT count(*)
+		        FROM $table_survey_question
+		        WHERE
+		            c_id = $course_id AND
+		            survey_id = ".$survey_invitation['survey_id']." AND (
+                        survey_question LIKE '%$doc_url%'
+                        or survey_question_comment LIKE '%$doc_url%'
+                    )
+		    UNION
+		        SELECT count(*)
+		        FROM $table_survey_question_option
+		        WHERE
+		            c_id = $course_id AND
+		            survey_id = ".$survey_invitation['survey_id']." AND (
+                        option_text LIKE '%$doc_url%'
+                    )";
 	$result = Database::query($sql);
 	if (Database::num_rows($result) == 0) {
 		Display :: display_error_message(get_lang('WrongInvitationCode'), false);
@@ -92,4 +109,4 @@ function check_download_survey($course, $invitation, $doc_url) {
 		exit;
 	}
 	return $_course;
-}
+}

File diff suppressed because it is too large
+ 257 - 203
main/survey/survey.lib.php


+ 44 - 43
main/survey/survey.php

@@ -46,7 +46,7 @@ $survey_id = intval($_GET['survey_id']);
 $course_id = api_get_course_int_id();
 
 // Breadcrumbs
-$interbreadcrumb[] = array ('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
+$interbreadcrumb[] = array ('url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php', 'name' => get_lang('SurveyList'));
 
 // Getting the survey information
 if (isset($_GET['survey_id'])) {
@@ -69,10 +69,12 @@ if (api_strlen(strip_tags($survey_data['title'])) > 40) {
 	$tool_name .= '...';
 }
 
-if ($is_survey_type_1 && $_GET['action'] == 'addgroup' || $_GET['action'] == 'deletegroup') {
+if ($is_survey_type_1 &&
+    isset($_GET['action']) &&
+    ($_GET['action'] == 'addgroup' || $_GET['action'] == 'deletegroup')
+) {
 	$_POST['name'] = trim($_POST['name']);
-
-	if (($_GET['action'] == 'addgroup')) {
+	if ($_GET['action'] == 'addgroup') {
 		if (!empty($_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']).'\'');
@@ -89,7 +91,7 @@ if ($is_survey_type_1 && $_GET['action'] == 'addgroup' || $_GET['action'] == 'de
 		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);
+	header('Location: '.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id.'&sendmsg='.$sendmsg);
 	exit;
 }
 
@@ -98,10 +100,10 @@ if ($is_survey_type_1 && $_GET['action'] == 'addgroup' || $_GET['action'] == 'de
 Display::display_header($tool_name, 'Survey');
 
 // Action handling
-$my_action_survey		= Security::remove_XSS($_GET['action']);
-$my_question_id_survey  = Security::remove_XSS($_GET['question_id']);
+$my_action_survey		= isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null;
+$my_question_id_survey  = isset($_GET['question_id']) ? Security::remove_XSS($_GET['question_id']) : null;
 $my_survey_id_survey    = Security::remove_XSS($_GET['survey_id']);
-$message_information    = Security::remove_XSS($_GET['message']);
+$message_information    = isset($_GET['message']) ? Security::remove_XSS($_GET['message']) : null;
 
 if (isset($_GET['action'])) {
 	if (($_GET['action'] == 'moveup' || $_GET['action'] == 'movedown') && isset($_GET['question_id'])) {
@@ -133,30 +135,29 @@ if (!empty($survey_data['survey_version'])) echo '<b>'.get_lang('Version').': '.
 SurveyUtil::check_first_last_question($_GET['survey_id']);
 
 // Action links
-$survey_actions = '<a href="create_new_survey.php?'.api_get_cidreq().'&amp;action=edit&amp;survey_id='.$survey_id.'">'.Display::return_icon('edit.png', get_lang('EditSurvey'),'',ICON_SIZE_MEDIUM).'</a>';
-$survey_actions .= '<a href="survey_list.php?'.api_get_cidreq().'&amp;action=delete&amp;survey_id='.$survey_id.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('DeleteSurvey').'?', ENT_QUOTES)).'\')) return false;">'.Display::return_icon('delete.png', get_lang('DeleteSurvey'),'',ICON_SIZE_MEDIUM).'</a>';
-//$survey_actions .= '<a href="create_survey_in_another_language.php?id_survey='.$survey_id.'">'.Display::return_icon('copy.gif', get_lang('Copy')).'</a>';
-$survey_actions .= '<a href="preview.php?'.api_get_cidreq().'&amp;survey_id='.$survey_id.'">'.Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_MEDIUM).'</a>';
-$survey_actions .= '<a href="survey_invite.php?'.api_get_cidreq().'&amp;survey_id='.$survey_id.'">'.Display::return_icon('mail_send.png', get_lang('Publish'),'',ICON_SIZE_MEDIUM).'</a>';
-$survey_actions .= '<a href="reporting.php?'.api_get_cidreq().'&amp;survey_id='.$survey_id.'">'.Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_MEDIUM).'</a>';
+$survey_actions = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/create_new_survey.php?'.api_get_cidreq().'&amp;action=edit&amp;survey_id='.$survey_id.'">'.Display::return_icon('edit.png', get_lang('EditSurvey'),'',ICON_SIZE_MEDIUM).'</a>';
+$survey_actions .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&amp;action=delete&amp;survey_id='.$survey_id.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('DeleteSurvey').'?', ENT_QUOTES)).'\')) return false;">'.Display::return_icon('delete.png', get_lang('DeleteSurvey'),'',ICON_SIZE_MEDIUM).'</a>';
+//$survey_actions .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/create_survey_in_another_language.php?id_survey='.$survey_id.'">'.Display::return_icon('copy.gif', get_lang('Copy')).'</a>';
+$survey_actions .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/preview.php?'.api_get_cidreq().'&amp;survey_id='.$survey_id.'">'.Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_MEDIUM).'</a>';
+$survey_actions .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?'.api_get_cidreq().'&amp;survey_id='.$survey_id.'">'.Display::return_icon('mail_send.png', get_lang('Publish'),'',ICON_SIZE_MEDIUM).'</a>';
+$survey_actions .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&amp;survey_id='.$survey_id.'">'.Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_MEDIUM).'</a>';
 echo '<div class="actions">'.$survey_actions.'</div>';
 
 if ($survey_data['survey_type'] == 0) {
 	echo '<div class="actionsbig">';
-	echo '<a style="padding-left:0px;" href="question.php?'.api_get_cidreq().'&amp;action=add&type=yesno&amp;survey_id='.$survey_id.'">'.Display::return_icon('yesno.gif', get_lang('YesNo')).'</a>';
-	echo '<a href="question.php?'.api_get_cidreq().'&amp;action=add&type=multiplechoice&amp;survey_id='.$survey_id.'">'.Display::return_icon('mcua.gif', get_lang('UniqueSelect')).'<br /></a>';
-	echo '<a href="question.php?'.api_get_cidreq().'&amp;action=add&type=multipleresponse&amp;survey_id='.$survey_id.'">'.Display::return_icon('mcma.gif', get_lang('MultipleResponse')).'</a>';
-	echo '<a href="question.php?'.api_get_cidreq().'&amp;action=add&type=open&amp;survey_id='.$survey_id.'">'.Display::return_icon('open_answer.gif', get_lang('Open')).'<br /></a>';
-	echo '<a href="question.php?'.api_get_cidreq().'&amp;action=add&type=dropdown&amp;survey_id='.$survey_id.'">'.Display::return_icon('dropdown.gif', get_lang('Dropdown')).'<br /></a>';
-	echo '<a href="question.php?'.api_get_cidreq().'&amp;action=add&type=percentage&amp;survey_id='.$survey_id.'">'.Display::return_icon('percentagequestion.gif', get_lang('Percentage')).'<br /></a>';
-	echo '<a href="question.php?'.api_get_cidreq().'&amp;action=add&type=score&amp;survey_id='.$survey_id.'">'.Display::return_icon('scorequestion.gif', get_lang('Score')).'</a>';
-	echo '<a href="question.php?'.api_get_cidreq().'&amp;action=add&type=comment&amp;survey_id='.$survey_id.'">'.Display::return_icon('commentquestion.gif', get_lang('Comment')).'</a>';
-	echo '<a href="question.php?'.api_get_cidreq().'&amp;action=add&type=pagebreak&amp;survey_id='.$survey_id.'">'.Display::return_icon('page_end.gif', get_lang('Pagebreak')).'</a>';
+	echo '<a style="padding-left:0px;" href="'.api_get_path(WEB_CODE_PATH).'survey/question.php?'.api_get_cidreq().'&amp;action=add&type=yesno&amp;survey_id='.$survey_id.'">'.Display::return_icon('yesno.gif', get_lang('YesNo')).'</a>';
+	echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/question.php?'.api_get_cidreq().'&amp;action=add&type=multiplechoice&amp;survey_id='.$survey_id.'">'.Display::return_icon('mcua.gif', get_lang('UniqueSelect')).'<br /></a>';
+	echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/question.php?'.api_get_cidreq().'&amp;action=add&type=multipleresponse&amp;survey_id='.$survey_id.'">'.Display::return_icon('mcma.gif', get_lang('MultipleResponse')).'</a>';
+	echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/question.php?'.api_get_cidreq().'&amp;action=add&type=open&amp;survey_id='.$survey_id.'">'.Display::return_icon('open_answer.gif', get_lang('Open')).'<br /></a>';
+	echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/question.php?'.api_get_cidreq().'&amp;action=add&type=dropdown&amp;survey_id='.$survey_id.'">'.Display::return_icon('dropdown.gif', get_lang('Dropdown')).'<br /></a>';
+	echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/question.php?'.api_get_cidreq().'&amp;action=add&type=percentage&amp;survey_id='.$survey_id.'">'.Display::return_icon('percentagequestion.gif', get_lang('Percentage')).'<br /></a>';
+	echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/question.php?'.api_get_cidreq().'&amp;action=add&type=score&amp;survey_id='.$survey_id.'">'.Display::return_icon('scorequestion.gif', get_lang('Score')).'</a>';
+	echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/question.php?'.api_get_cidreq().'&amp;action=add&type=comment&amp;survey_id='.$survey_id.'">'.Display::return_icon('commentquestion.gif', get_lang('Comment')).'</a>';
+	echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/question.php?'.api_get_cidreq().'&amp;action=add&type=pagebreak&amp;survey_id='.$survey_id.'">'.Display::return_icon('page_end.gif', get_lang('Pagebreak')).'</a>';
 	echo '</div>';
 } else {
 	echo '<div class="actionsbig">';
-	//echo '<a href="group.php?'.api_get_cidreq().'&amp;action=add&amp;survey_id='.$survey_id.'"><img src="../img/yesno.gif" /><br />'.get_lang('Add groups').'</a></div>';
-	echo '<a style="padding-left:0px;" href="question.php?'.api_get_cidreq().'&amp;action=add&type=personality&amp;survey_id='.$survey_id.'"><img src="../img/yesno.gif" /></a></div>';
+	echo '<a style="padding-left:0px;" href="'.api_get_path(WEB_CODE_PATH).'survey/question.php?'.api_get_cidreq().'&amp;action=add&type=personality&amp;survey_id='.$survey_id.'"><img src="../img/yesno.gif" /></a></div>';
 	echo '</div>';
 }
 
@@ -176,20 +177,22 @@ echo '	</tr>';
 
 // Displaying the table contents with all the questions
 $question_counter = 1;
-$sql = "SELECT * FROM $table_survey_question_group WHERE c_id = '.$course_id.' AND 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)) {
     $groups[$row['id']] = $row['name'];
 }
 $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 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";
+        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 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);
@@ -215,15 +218,15 @@ while ($row = Database::fetch_array($result, 'ASSOC')) {
 	echo '	<td>'.$tool_name.'</td>';
 	echo '	<td>'.$row['number_of_options'].'</td>';
 	echo '	<td>';
-	echo '		<a href="question.php?'.api_get_cidreq().'&amp;action=edit&amp;type='.$row['type'].'&amp;survey_id='.$survey_id.'&amp;question_id='.$row['question_id'].'">'.Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>';
-	echo '		<a href="survey.php?'.api_get_cidreq().'&amp;action=delete&amp;survey_id='.$survey_id.'&amp;question_id='.$row['question_id'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("DeleteSurveyQuestion").'?',ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
+	echo '		<a href="'.api_get_path(WEB_CODE_PATH).'survey/question.php?'.api_get_cidreq().'&amp;action=edit&amp;type='.$row['type'].'&amp;survey_id='.$survey_id.'&amp;question_id='.$row['question_id'].'">'.Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>';
+	echo '		<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey.php?'.api_get_cidreq().'&amp;action=delete&amp;survey_id='.$survey_id.'&amp;question_id='.$row['question_id'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("DeleteSurveyQuestion").'?',ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
 	if ($question_counter > 1) {
-		echo '		<a href="survey.php?'.api_get_cidreq().'&amp;action=moveup&amp;survey_id='.$survey_id.'&amp;question_id='.$row['question_id'].'">'.Display::return_icon('up.png', get_lang('MoveUp'),'',ICON_SIZE_SMALL).'</a>';
+		echo '		<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey.php?'.api_get_cidreq().'&amp;action=moveup&amp;survey_id='.$survey_id.'&amp;question_id='.$row['question_id'].'">'.Display::return_icon('up.png', get_lang('MoveUp'),'',ICON_SIZE_SMALL).'</a>';
 	} else {
 		Display::display_icon('up_na.png','&nbsp;','',ICON_SIZE_SMALL);
 	}
 	if ($question_counter < $question_counter_max) {
-		echo '		<a href="survey.php?'.api_get_cidreq().'&amp;action=movedown&amp;survey_id='.$survey_id.'&amp;question_id='.$row['question_id'].'">'.Display::return_icon('down.png', get_lang('MoveDown'),'',ICON_SIZE_SMALL).'</a>';
+		echo '		<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey.php?'.api_get_cidreq().'&amp;action=movedown&amp;survey_id='.$survey_id.'&amp;question_id='.$row['question_id'].'">'.Display::return_icon('down.png', get_lang('MoveDown'),'',ICON_SIZE_SMALL).'</a>';
 	} else {
 		Display::display_icon('down_na.png','&nbsp;','',ICON_SIZE_SMALL);
 	}
@@ -249,10 +252,8 @@ if ($is_survey_type_1) {
 	if (in_array($_GET['sendmsg'], array('GroupNeedName'))){
 		echo Display::display_warning_message(get_lang($_GET['sendmsg']), false);
 	}
-
 	echo '<table border="0"><tr><td width="100">'.get_lang('Name').'</td><td>'.get_lang('Description').'</td></tr></table>';
-
-	echo '<form action="survey.php?action=addgroup&survey_id='.$survey_id.'" method="post">';
+	echo '<form action="'.api_get_path(WEB_CODE_PATH).'survey/survey.php?action=addgroup&survey_id='.$survey_id.'" method="post">';
 	if ($_GET['action'] == 'editgroup') {
 		$sql = 'SELECT name,description FROM '.$table_survey_question_group.' WHERE id = '.Database::escape_string($_GET['gid']).' AND survey_id = '.Database::escape_string($survey_id).' limit 1';
 		$rs = Database::query($sql);
@@ -280,9 +281,9 @@ if ($is_survey_type_1) {
 	$rs = Database::query($sql);
 	while($row = Database::fetch_array($rs,ASSOC)){
 		$grouplist .= '<tr><td>'.$row['name'].'</td><td>'.$row['description'].'</td><td>'.
-		'<a href="survey.php?survey_id='.$survey_id.'&gid='.$row['id'].'&action=editgroup">'.
+		'<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id.'&gid='.$row['id'].'&action=editgroup">'.
 		Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).'</a> '.
-		'<a href="survey.php?survey_id='.$survey_id.'&gid='.$row['id'].'&action=deletegroup" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('DeleteSurveyGroup'),$row['name']).'?',ENT_QUOTES)).'\')) return false;">'.
+		'<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id.'&gid='.$row['id'].'&action=deletegroup" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('DeleteSurveyGroup'),$row['name']).'?',ENT_QUOTES)).'\')) return false;">'.
 		Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>'.
 		'</td></tr>';
 	}
@@ -290,4 +291,4 @@ if ($is_survey_type_1) {
 }
 
 // Footer
-Display :: display_footer();
+Display :: display_footer();

+ 8 - 22
main/survey/survey_invitation.php

@@ -63,8 +63,8 @@ if (api_strlen(strip_tags($survey_data['title'])) > 40) {
 }
 
 // Breadcrumbs
-$interbreadcrumb[] = array('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
-$interbreadcrumb[] = array('url' => 'survey.php?survey_id='.$survey_id, 'name' => $urlname);
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php', 'name' => get_lang('SurveyList'));
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id, 'name' => $urlname);
 
 
 // Displaying the header
@@ -110,24 +110,24 @@ echo '	</tr>';
 
 $course_id = api_get_course_int_id();
 
-$sql = "SELECT survey_invitation.*, user.firstname, user.lastname, user.email 
-            FROM $table_survey_invitation survey_invitation
-			LEFT JOIN $table_user user ON (survey_invitation.user = user.user_id AND survey_invitation.c_id = $course_id)
-			WHERE survey_invitation.survey_code = '".Database::escape_string($survey_data['code'])."' ";
+$sql = "SELECT survey_invitation.*, user.firstname, user.lastname, user.email
+        FROM $table_survey_invitation survey_invitation
+        LEFT JOIN $table_user user ON (survey_invitation.user = user.user_id AND survey_invitation.c_id = $course_id)
+        WHERE survey_invitation.survey_code = '".Database::escape_string($survey_data['code'])."' ";
 
 $res = Database::query($sql);
 while ($row = Database::fetch_assoc($res)) {
 	if (!$_GET['view'] || $_GET['view'] == 'invited' || ($_GET['view'] == 'answered' && in_array($row['user'], $answered_data)) || ($_GET['view'] == 'unanswered' && !in_array($row['user'], $answered_data))) {
 		echo '<tr>';
 		if (is_numeric($row['user'])) {
-			echo '			<td><a href="../user/userInfo.php?editMainUserInfo='.$row['user'].'">'.api_get_person_name($row['firstname'], $row['lastname']).'</a></td>';
+			echo '			<td><a href="'.api_get_path(WEB_CODE_PATH).'user/userInfo.php?editMainUserInfo='.$row['user'].'">'.api_get_person_name($row['firstname'], $row['lastname']).'</a></td>';
 		} else {
 				echo '	<td>'.$row['user'].'</td>';
 		}
 		echo '	<td>'.$row['invitation_date'].'</td>';
 		echo '	<td>';
 		if (in_array($row['user'], $answered_data)) {
-			echo '<a href="reporting.php?action=userreport&amp;survey_id='.$survey_id.'&amp;user='.$row['user'].'">'.get_lang('ViewAnswers').'</a>';
+			echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&amp;survey_id='.$survey_id.'&amp;user='.$row['user'].'">'.get_lang('ViewAnswers').'</a>';
 		} else {
 			echo '-';
 		}
@@ -141,17 +141,3 @@ echo '</table>';
 
 // Footer
 Display :: display_footer();
-
-/**
- * @todo add the additional parameters
- */
-/*
-$table = new SortableTable('survey_invitations', 'get_number_of_survey_invitations', 'get_survey_invitations_data',2);
-$table->set_additional_parameters($parameters);
-$table->set_header(0, get_lang('User'));
-$table->set_header(1, get_lang('InvitationCode'));
-$table->set_header(2, get_lang('InvitationDate'));
-$table->set_header(3, get_lang('Answered'));
-$table->set_column_filter(3, 'SurveyUtil::modify_filter');
-$table->display();
-*/

+ 15 - 11
main/survey/survey_invite.php

@@ -17,7 +17,7 @@
 $language_file = 'survey';
 
 // Including the global initialization file
-require '../inc/global.inc.php';
+require_once '../inc/global.inc.php';
 
 // Including additional libraries
 require_once 'survey.lib.php';
@@ -57,11 +57,11 @@ if (api_strlen(strip_tags($survey_data['title'])) > 40) {
 }
 
 // Breadcrumbs
-$interbreadcrumb[] = array('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
+$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php', 'name' => get_lang('SurveyList'));
 if (api_is_course_admin()) {
-	$interbreadcrumb[] = array('url' => 'survey.php?survey_id='.$survey_id, 'name' => $urlname);
+	$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id, 'name' => $urlname);
 } else {
-	$interbreadcrumb[] = array('url' => 'survey_invite.php?survey_id='.$survey_id, 'name' => $urlname);
+	$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?survey_id='.$survey_id, 'name' => $urlname);
 }
 $tool_name = get_lang('SurveyPublication');
 
@@ -86,20 +86,24 @@ if (Database::num_rows($result) > 1) {
 
 // Invited / answered message
 if ($survey_data['invited'] > 0 && !isset($_POST['submit'])) {
-	$message  = '<a href="survey_invitation.php?view=answered&amp;survey_id='.$survey_data['survey_id'].'">'.$survey_data['answered'].'</a> ';
+	$message  = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&amp;survey_id='.$survey_data['survey_id'].'">'.$survey_data['answered'].'</a> ';
 	$message .= get_lang('HaveAnswered').' ';
-	$message .= '<a href="survey_invitation.php?view=invited&amp;survey_id='.$survey_data['survey_id'].'">'.$survey_data['invited'].'</a> ';
+	$message .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&amp;survey_id='.$survey_data['survey_id'].'">'.$survey_data['invited'].'</a> ';
 	$message .= get_lang('WereInvited');
 	Display::display_normal_message($message, false);
 }
 
 // Building the form for publishing the survey
 $form = new FormValidator('publish_form', 'post', api_get_self().'?survey_id='.$survey_id.'&'.api_get_cidReq());
-
 $form->addElement('header', '', $tool_name);
 
 // Course users
-$complete_user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), api_get_session_id(), '', api_sort_by_first_name() ? 'ORDER BY firstname' : 'ORDER BY lastname');
+$complete_user_list = CourseManager::get_user_list_from_course_code(
+    api_get_course_id(),
+    api_get_session_id(),
+    '',
+    api_sort_by_first_name() ? 'ORDER BY firstname' : 'ORDER BY lastname'
+);
 $possible_users = array();
 foreach ($complete_user_list as & $user) {
 	$possible_users[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']);
@@ -208,9 +212,9 @@ if ($form->validate()) {
 	$row = Database::fetch_array($result);
 	$total_invited = $row['invited'];
     if ($total_invited > 0) {
-    	$message  = '<a href="survey_invitation.php?view=answered&amp;survey_id='.$survey_data['survey_id'].'">'.$survey_data['answered'].'</a> ';
+    	$message  = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&amp;survey_id='.$survey_data['survey_id'].'">'.$survey_data['answered'].'</a> ';
     	$message .= get_lang('HaveAnswered').' ';
-    	$message .= '<a href="survey_invitation.php?view=invited&amp;survey_id='.$survey_data['survey_id'].'">'.$total_invited.'</a> ';
+    	$message .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&amp;survey_id='.$survey_data['survey_id'].'">'.$total_invited.'</a> ';
     	$message .= get_lang('WereInvited');
     	Display::display_normal_message($message, false);
     	Display::display_confirmation_message($total_count.' '.get_lang('InvitationsSend'));
@@ -231,4 +235,4 @@ if ($form->validate()) {
 	$form->setDefaults($defaults);
     $form->display();
 }
-Display :: display_footer();
+Display :: display_footer();

+ 7 - 7
main/survey/survey_list.php

@@ -49,7 +49,7 @@ $table_user 			= Database :: get_main_table(TABLE_MAIN_USER);
 
 // Language variables
 if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
-    $interbreadcrumb[] = array('url' => 'survey_list.php', 'name' => get_lang('SurveyList'));
+    $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php', 'name' => get_lang('SurveyList'));
     $tool_name = get_lang('SearchASurvey');
 } else {
     $tool_name = get_lang('SurveyList');
@@ -81,16 +81,17 @@ if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['survey
 
     $return = survey_manager :: delete_survey($_GET['survey_id']);
     if ($return) {
-        Display :: display_confirmation_message(get_lang('SurveyDeleted'), false);
+        Display::display_confirmation_message(get_lang('SurveyDeleted'), false);
     } else {
-        Display :: display_error_message(get_lang('ErrorOccurred'), false);
+        Display::display_error_message(get_lang('ErrorOccurred'), false);
     }
 }
 
 if (isset($_GET['action']) && $_GET['action'] == 'empty') {
     $mysession = api_get_session_id();
-    if ( $mysession != 0 ) {
-        if (!((api_is_course_coach() || api_is_platform_admin()) && api_is_element_in_the_session(TOOL_SURVEY,intval($_GET['survey_id'])))) {
+    if ($mysession != 0) {
+        if (!((api_is_course_coach() || api_is_platform_admin()) &&
+            api_is_element_in_the_session(TOOL_SURVEY, $_GET['survey_id']))) {
             // The coach can't empty a survey not belonging to his session
             api_not_allowed();
             exit;
@@ -131,9 +132,8 @@ if (isset($_POST['action']) && $_POST['action']) {
 echo '<div class="actions">';
 if (!api_is_course_coach() || $extend_rights_for_coachs == 'true') {
 	// Action links
-	echo '<a href="create_new_survey.php?'.api_get_cidreq().'&amp;action=add">'.Display::return_icon('new_survey.png', get_lang('CreateNewSurvey'),'',ICON_SIZE_MEDIUM).'</a> ';
+	echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/create_new_survey.php?'.api_get_cidreq().'&amp;action=add">'.Display::return_icon('new_survey.png', get_lang('CreateNewSurvey'),'',ICON_SIZE_MEDIUM).'</a> ';
 }
-//echo '<a href="survey_all_courses.php">'.get_lang('CreateExistingSurvey').'</a> ';
 echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;search=advanced">'.Display::return_icon('search.png', get_lang('Search'),'',ICON_SIZE_MEDIUM).'</a>';
 echo '</div>';
 

+ 50 - 26
main/tracking/course_log_resources.php

@@ -15,19 +15,13 @@ $language_file = array('admin', 'tracking', 'scorm', 'exercice');
 // Including the global initialization file
 require_once '../inc/global.inc.php';
 $current_course_tool = TOOL_TRACKING;
-
 $course_info = api_get_course_info(api_get_course_id());
-
-if (!empty($course_info)) {
-    //api_protect_course_script();
-}
-
 $from_myspace = false;
 $from = isset($_GET['from']) ? $_GET['from'] : null;
 
 if ($from == 'myspace') {
     $from_myspace = true;
-    $this_section = "session_my_space";    
+    $this_section = "session_my_space";
 } else {
     $this_section = SECTION_COURSES;
 }
@@ -35,8 +29,8 @@ if ($from == 'myspace') {
 // Access restrictions.
 $is_allowedToTrack = api_is_platform_admin() || api_is_allowed_to_create_course() || api_is_session_admin() || api_is_drh() || api_is_course_tutor();
 
-if (!$is_allowedToTrack) {    
-    api_not_allowed();    
+if (!$is_allowedToTrack) {
+    api_not_allowed();
     exit;
 }
 
@@ -58,17 +52,18 @@ $export_csv = isset($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
 $session_id = intval($_REQUEST['id_session']);
 
 if ($export_csv) {
-    if (!empty($session_id)) {
-        $_SESSION['id_session'] = $session_id;
-    }
     ob_start();
 }
 
+if (empty($session_id)) {
+    $session_id = api_get_session_id();
+}
+
 // Breadcrumbs.
 if (isset($_GET['origin']) && $_GET['origin'] == 'resume_session') {
-    $interbreadcrumb[] = array('url' => '../admin/index.php','name' => get_lang('PlatformAdmin'));
-    $interbreadcrumb[] = array('url' => '../admin/session_list.php','name' => get_lang('SessionList'));
-    $interbreadcrumb[] = array('url' => '../admin/resume_session.php?id_session='.api_get_session_id(), 'name' => get_lang('SessionOverview'));
+    $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'admin/index.php','name' => get_lang('PlatformAdmin'));
+    $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'admin/session_list.php','name' => get_lang('SessionList'));
+    $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'admin/resume_session.php?id_session='.api_get_session_id(), 'name' => get_lang('SessionOverview'));
 }
 
 $nameTools = get_lang('Tracking');
@@ -79,20 +74,32 @@ Display::display_header($nameTools, 'Tracking');
 /* MAIN CODE */
 
 echo '<div class="actions">';
-echo Display::url(Display::return_icon('user.png', get_lang('StudentsTracking'), array(), 32), 'courseLog.php?'.api_get_cidreq());  
-echo Display::url(Display::return_icon('course.png', get_lang('CourseTracking'), array(), 32), 'course_log_tools.php?'.api_get_cidreq());
-echo Display::return_icon('tools_na.png', get_lang('ResourcesTracking'), array(), 32);
+echo Display::url(
+    Display::return_icon('user.png', get_lang('StudentsTracking'), array(), ICON_SIZE_MEDIUM),
+    api_get_path(WEB_CODE_PATH).'tracking/courseLog.php?'.api_get_cidreq()
+);
+
+echo Display::url(
+    Display::return_icon('course.png', get_lang('CourseTracking'), array(), ICON_SIZE_MEDIUM),
+    api_get_path(WEB_CODE_PATH).'tracking/course_log_tools.php?'.api_get_cidreq()
+);
+
+echo Display::return_icon('tools_na.png', get_lang('ResourcesTracking'), array(), ICON_SIZE_MEDIUM);
 echo '<span style="float:right; padding-top:0px;">';
-echo '<a href="javascript: void(0);" onclick="javascript: window.print();">'.Display::return_icon('printer.png', get_lang('Print'),'',ICON_SIZE_MEDIUM).'</a>';
+echo '<a href="javascript: void(0);" onclick="javascript: window.print();">'.
+    Display::return_icon('printer.png', get_lang('Print'),'',ICON_SIZE_MEDIUM).
+'</a>';
 
 $addional_param = '';
 if (isset($_GET['additional_profile_field'])) {
     $addional_param ='additional_profile_field='.intval($_GET['additional_profile_field']);
 }
+
 $users_tracking_per_page = '';
 if (isset($_GET['users_tracking_per_page'])) {
     $users_tracking_per_page= '&users_tracking_per_page='.intval($_GET['users_tracking_per_page']);
 }
+
 echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&export=csv&'.$addional_param.$users_tracking_per_page.'">
 '.Display::return_icon('export_csv.png', get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a>';
 
@@ -100,21 +107,38 @@ echo '</span>';
 echo '</div>';
 
 // Create a search-box.
-$form = new FormValidator('search_simple', 'GET', api_get_path(WEB_CODE_PATH).'tracking/course_log_resources.php?'.api_get_cidreq(), '', array('class' => 'form-search'), false);
+$form = new FormValidator(
+    'search_simple',
+    'GET',
+    api_get_path(WEB_CODE_PATH).'tracking/course_log_resources.php?'.api_get_cidreq().'&id_session'.$session_id,
+    '',
+    array('class' => 'form-search'),
+    false
+);
 $renderer = $form->defaultRenderer();
 $renderer->setElementTemplate('<span>{element}</span>');
 $form->addElement('text', 'keyword', get_lang('keyword'));
+$form->addElement('hidden', 'cidReq', api_get_course_id());
+$form->addElement('hidden', 'id_session', $session_id);
 $form->addElement('style_submit_button', 'submit', get_lang('SearchUsers'), 'class="search"');
 echo '<div class="actions">';
 $form->display();
 echo '</div>';
 
-$table = new SortableTable('resources', array('TrackingCourseLog', 'count_item_resources'), array('TrackingCourseLog', 'get_item_resources_data'), 5, 20, 'DESC');
-$parameters = array();
-
-if (isset($_GET['keyword'])) {
-    $parameters['keyword'] = Security::remove_XSS($_GET['keyword']);
-}
+$table = new SortableTable(
+    'resources',
+    array('TrackingCourseLog', 'count_item_resources'),
+    array('TrackingCourseLog', 'get_item_resources_data'),
+    5,
+    20,
+    'DESC'
+);
+
+$parameters = array(
+    'keyword' => Security::remove_XSS($_GET['keyword']),
+    'id_session' => $session_id,
+    'cidReq' => api_get_course_id()
+);
 
 $table->set_additional_parameters($parameters);
 $table->set_header(0, get_lang('Tool'));

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