Prechádzať zdrojové kódy

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

Imanol Losada 10 rokov pred
rodič
commit
3c8336e94f
46 zmenil súbory, kde vykonal 1117 pridanie a 674 odobranie
  1. 2 2
      custompages/index-unlogged.php
  2. 32 0
      documentation/optimization.html
  3. 31 37
      main/admin/add_many_session_to_category.php
  4. 25 21
      main/admin/course_import.php
  5. 2 2
      main/admin/example_session.csv
  6. 10 23
      main/admin/resume_session.php
  7. 48 29
      main/admin/session_category_edit.php
  8. 10 21
      main/admin/session_course_user_list.php
  9. 11 5
      main/admin/session_edit.php
  10. 6 6
      main/admin/session_import.php
  11. 2 3
      main/auth/gotocourse.php
  12. 0 1
      main/auth/profile.php
  13. 109 8
      main/cron/import_csv.php
  14. 2 2
      main/exercice/answer.class.php
  15. 1 0
      main/exercice/exercice.php
  16. 1 1
      main/exercice/exercise.lib.php
  17. 0 1
      main/exercice/exercise_result.php
  18. 12 13
      main/exercice/exercise_submit.php
  19. 189 181
      main/exercice/matching.class.php
  20. 0 1
      main/exercice/overview.php
  21. 23 20
      main/exercice/question.class.php
  22. 16 8
      main/exercice/question_pool.php
  23. 2 1
      main/forum/viewforum.php
  24. 8 2
      main/inc/ajax/document.ajax.php
  25. 23 15
      main/inc/lib/add_course.lib.inc.php
  26. 3 2
      main/inc/lib/course.lib.php
  27. 21 11
      main/inc/lib/document.lib.php
  28. 6 2
      main/inc/lib/events.lib.inc.php
  29. 17 0
      main/inc/lib/extra_field.lib.php
  30. 27 14
      main/inc/lib/fileUpload.lib.php
  31. 15 0
      main/inc/lib/formvalidator/FormValidator.class.php
  32. 64 19
      main/inc/lib/sessionmanager.lib.php
  33. 1 1
      main/inc/lib/template.lib.php
  34. 17 1
      main/inc/lib/usermanager.lib.php
  35. 49 41
      main/mySpace/myStudents.php
  36. 12 12
      main/newscorm/learnpath.class.php
  37. 30 21
      main/newscorm/learnpathItem.class.php
  38. 41 20
      main/newscorm/lp_ajax_save_item.php
  39. 1 0
      main/newscorm/lp_controller.php
  40. 5 4
      main/newscorm/lp_view.php
  41. 23 20
      main/survey/create_new_survey.php
  42. 2 2
      main/survey/preview.php
  43. 16 5
      main/survey/question.php
  44. 168 76
      main/survey/survey.lib.php
  45. 9 11
      main/survey/survey.php
  46. 25 9
      main/survey/survey_list.php

+ 2 - 2
custompages/index-unlogged.php

@@ -102,12 +102,12 @@ $rootWeb = api_get_path('WEB_PATH');
 			<div id="links">
 
                 <?php if (api_get_setting('allow_registration') === 'true') { ?>
-                <a href="<?php echo api_get_path(WEB_PATH); ?>main/auth/inscription.php">
+                <a href="<?php echo api_get_path(WEB_PATH); ?>main/auth/inscription.php?language=<?php echo api_get_interface_language(); ?>">
                     <?php echo custompages_get_lang('langReg')?>
                 </a><br />
                 <?php } ?>
 
-                <a href="<?php echo api_get_path(WEB_PATH); ?>main/auth/lostPassword.php">
+                <a href="<?php echo api_get_path(WEB_PATH); ?>main/auth/lostPassword.php?language=<?php echo api_get_interface_language(); ?>">
                     <?php echo custompages_get_lang('langLostPassword')?>
                 </a>
 			</div>

+ 32 - 0
documentation/optimization.html

@@ -245,6 +245,38 @@ If you use php5-memcached (different set of functions than php5-memcache!), then
             ...
         }
 </pre>
+Finally, the Free Campus of Chamilo has a very specific case of slow query: the courses catalog! Because there might be more than 30,000 courses in there, getting the number of "Connections last month" can be a desastrous query in terms of performances. This is why you should try to cache the results as well.<br />
+Obviously, as we are speaking about showing the number of visits this month, it doesn't really matter if the number doesn't refresh for an hour or so...<br />
+Locate the main/inc/lib/course_category.lib.php file, open it and go to the browseCoursesInCategory() function.<br />
+Locate the $count_connections_last_month = Tracking::get_course_connections_count(...) call, and wrap in into something like this:
+<pre>
+    $xc = method_exists('Memcached', 'add');
+    if ($xc) {
+        // Make sure the server is available
+        $xm = new Memcached;
+        $xm->addServer('localhost', 11211);
+        // The following concatenates the name of the database + the id of the
+        // access url to make it a unique variable prefix for the variables to
+        // be stored
+        $xs = $_configuration['main_database'].'_'.$_configuration['access_url'].'_';
+    }
+    $result = Database::query($sql);
+    $courses = array();
+    while ($row = Database::fetch_array($result)) {
+        $row['registration_code'] = !empty($row['registration_code']);
+        $count_users = CourseManager::get_users_count_in_course($row['code']);
+        if ($xc) {
+            if ($xm->get($xs.'cccount_'.$row['code'])) {
+                $number = $xm->get($xs.'cccount_'.$row['code']);
+            } else {
+                $count_connections_last_month = Tracking::get_course_connections_count($row['code'], 0, api_get_utc_datetime(time() - (30 * 86400)));
+                $xm->set($xs.'cccount_'.$row['code'], $count_connections_last_month, 3600);
+            }
+        } else {
+            $count_connections_last_month = Tracking::get_course_connections_count($row['code'], 0, api_get_utc_datetime(time() - (30 * 86400)));
+        }
+   ...
+</pre>
 <hr />
 <h2><a name="2.Slow-queries"></a>2. Slow queries</h2>
 Enable slow_queries in /etc/mysqld/my.cnf, restart MySQL then follow using sudo tail -f /var/log/mysql/mysql-slow.log

+ 31 - 37
main/admin/add_many_session_to_category.php

@@ -15,7 +15,7 @@ require_once api_get_path(LIBRARY_PATH).'add_many_session_to_category_functions.
 require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
 
 $xajax = new xajax();
-$xajax -> registerFunction ('search_courses');
+$xajax->registerFunction('search_courses');
 
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;
@@ -36,12 +36,12 @@ $tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE)
 $tbl_course							= Database::get_main_table(TABLE_MAIN_COURSE);
 
 // setting the name of the tool
-$tool_name= get_lang('SubscribeSessionsToCategory');
-$id_session=intval($_GET['id_session']);
+$tool_name = get_lang('SubscribeSessionsToCategory');
+$id_session = isset($_GET['id_session']) ? intval($_GET['id_session']) : null;
 
 $add_type = 'multiple';
-if(isset($_GET['add_type']) && $_GET['add_type']!=''){
-	$add_type = Security::remove_XSS($_REQUEST['add_type']);
+if (isset($_GET['add_type']) && $_GET['add_type'] != '') {
+    $add_type = Security::remove_XSS($_REQUEST['add_type']);
 }
 
 if (!api_is_platform_admin() && !api_is_session_admin()) {
@@ -90,17 +90,24 @@ $formSent = 0;
 $errorMsg = $firstLetterCourse = $firstLetterSession = '';
 $CourseList = $SessionList = array();
 $courses = $sessions = array();
-$Categoryid = isset($_POST['CategorySessionId']) ? intval($_POST['CategorySessionId']) : null;
+$categoryId = isset($_POST['CategorySessionId']) ? intval($_POST['CategorySessionId']) : null;
 
 if (isset($_POST['formSent']) && $_POST['formSent']) {
     $formSent = $_POST['formSent'];
-    $SessionCategoryList = $_POST['SessionCategoryList'];
+    $sessionCategoryList = $_POST['SessionCategoryList'];
 
-    if ($Categoryid != 0 && count($SessionCategoryList) > 0) {
-        $session_id = join(',', $SessionCategoryList);
-        $sql = "UPDATE $tbl_session SET session_category_id = $Categoryid WHERE id in ($session_id) ";
+
+    if ($categoryId != 0 && count($sessionCategoryList) > 0) {
+        // Removing all
+        $sql = "UPDATE $tbl_session SET session_category_id = '' WHERE session_category_id = $categoryId";
+        Database::query($sql);
+        // Adding new
+        $sessionCategoryList = array_map('intval', $sessionCategoryList);
+        $session_id = join(',', $sessionCategoryList);
+
+        $sql = "UPDATE $tbl_session SET session_category_id = $categoryId WHERE id in ($session_id) ";
         Database::query($sql);
-        header('Location: add_many_session_to_category.php?id_category=' . $Categoryid . '&msg=ok');
+        header('Location: add_many_session_to_category.php?id_category=' . $categoryId . '&msg=ok');
         exit;
     } else {
         header('Location: add_many_session_to_category.php?msg=error');
@@ -109,7 +116,7 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
 }
 
 if (isset($_GET['id_category'])) {
-    $Categoryid = intval($_GET['id_category']);
+    $categoryId = intval($_GET['id_category']);
 }
 
 if (isset($_GET['msg']) && $_GET['msg'] == 'error') {
@@ -121,15 +128,15 @@ if (isset($_GET['msg']) && $_GET['msg'] == 'ok') {
 }
 
 $page = isset($_GET['page']) ? Security::remove_XSS($_GET['page']) : null;
-// display the dokeos header
+
 Display::display_header($tool_name);
 
 $where = '';
 $rows_category_session = array();
 if ((isset($_POST['CategorySessionId']) && $_POST['formSent'] == 0) || isset($_GET['id_category'])) {
 
-    $where = 'WHERE session_category_id !=' . $Categoryid;
-    $sql = 'SELECT id, name  FROM ' . $tbl_session . ' WHERE session_category_id =' . $Categoryid . ' ORDER BY name';
+    $where = 'WHERE session_category_id !=' . $categoryId;
+    $sql = 'SELECT id, name  FROM ' . $tbl_session . ' WHERE session_category_id =' . $categoryId . ' ORDER BY name';
     $result = Database::query($sql);
     $rows_category_session = Database::store_result($result);
 }
@@ -147,7 +154,7 @@ if (api_get_multiple_access_url()) {
     $sql = "SELECT s.id, s.name  FROM $tbl_session s INNER JOIN $table_access_url_rel_session u ON s.id = u.session_id $where AND u.access_url_id = $access_url_id ORDER BY name";
 } else {
     $sql = "SELECT id, name  FROM $tbl_session $where ORDER BY name";
-} 
+}
 $result=Database::query($sql);
 $rows_session = Database::store_result($result);
 ?>
@@ -167,10 +174,10 @@ if(!empty($OkMsg)) {
 	Display::display_confirmation_message($OkMsg); //main API
 }
 
-/* 
- * 
- * The a/b/c Filter is not a priority 
- *  
+/*
+ *
+ * The a/b/c Filter is not a priority
+ *
  * <td width="45%" align="center">
  <?php echo get_lang('FirstLetterCourse'); ?> :
      <select name="firstLetterCourse" onchange = "xajax_search_courses(this.value,'multiple')">
@@ -188,14 +195,14 @@ if(!empty($OkMsg)) {
 <tr>
 	<td align="left"></td>
 	<td align="left"></td>
-	<td  align="center"> 
+	<td  align="center">
 	<b><?php echo get_lang('SessionCategoryName') ?> :</b><br />
 	<select name="CategorySessionId" style="width: 320px;" onchange="javascript:send();" >
 		<option value="0" ></option>
 		<?php
 		if (!empty($rows_session_category)) {
     		foreach($rows_session_category as $category) {
-    			if($category['id'] == $Categoryid)
+    			if($category['id'] == $categoryId)
       				echo '<option value="'.$category['id'].'" selected>'.$category['name'].'</option>';
       			else
       				echo '<option value="'.$category['id'].'">'.$category['name'].'</option>';
@@ -228,19 +235,9 @@ if(!empty($OkMsg)) {
 <?php unset($nosessionCourses); ?>
   </td>
   <td width="10%" valign="middle" align="center">
-  <?php
-  if ($ajax_search) {
-  ?>
-  	<button class="arrowl" type="button" onclick="remove_item(document.getElementById('destination'))"></button>
-  <?php
-  } else {
-  ?>
   	<button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin'), document.getElementById('destination'))" onclick="moveItem(document.getElementById('origin'), document.getElementById('destination'))"></button>
 	<br /><br />
 	<button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination'), document.getElementById('origin'))" onclick="moveItem(document.getElementById('destination'), document.getElementById('origin'))"></button>
-  <?php
-  }
-  ?>
 	<br /><br /><br /><br /><br /><br />
 	<?php
 		echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('SubscribeSessionsToCategory').'</button>';
@@ -258,7 +255,6 @@ if(!empty($OkMsg)) {
 
 </form>
 <script type="text/javascript">
-<!--
 function moveItem(origin , destination) {
 	for(var i = 0 ; i<origin.options.length ; i++) {
 		if(origin.options[i].selected) {
@@ -302,9 +298,7 @@ function valide(){
 
 	document.forms.formulaire.submit();
 }
--->
-
 </script>
 <?php
-/*		FOOTER	*/
-Display::display_footer();
+
+Display::display_footer();

+ 25 - 21
main/admin/course_import.php

@@ -72,6 +72,7 @@ function validate_data($courses)
             }
         }
     }
+
     return $errors;
 }
 
@@ -80,12 +81,13 @@ function getTeacherListInArray($teachers)
     if (!empty($teachers)) {
         return explode('|', $teachers);
     }
+
     return array();
 }
 
 /**
  * Saves imported data.
- * @param array   List of courses
+ * @param array $courses List of courses
  */
 function save_data($courses)
 {
@@ -113,16 +115,23 @@ function save_data($courses)
         $params['course_language']  = $course_language;
         $params['user_id']          = $creatorId;
 
-        $course_info = CourseManager::create_course($params);
+        $addMeAsTeacher = isset($_POST['add_me_as_teacher']) ? $_POST['add_me_as_teacher'] : false;
+        $params['add_user_as_teacher'] = $addMeAsTeacher;
+
+        $courseInfo = CourseManager::create_course($params);
 
-        if (!empty($course_info)) {
+        if (!empty($courseInfo)) {
             if (!empty($teacherList)) {
                 foreach ($teacherList as $teacher) {
-                    CourseManager::add_user_to_course($teacher['user_id'], $course_info['code'], COURSEMANAGER);
+                    CourseManager::add_user_to_course(
+                        $teacher['user_id'],
+                        $courseInfo['code'],
+                        COURSEMANAGER
+                    );
                 }
             }
-            $msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/">
-                    '.$course_info['title'].'</a> '.get_lang('Created').'<br />';
+            $msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$courseInfo['directory'].'/">
+                    '.$courseInfo['title'].'</a> '.get_lang('Created').'<br />';
         }
     }
 
@@ -197,22 +206,17 @@ if (isset($errors) && count($errors) != 0) {
     $error_message .= '</ul>';
     Display :: display_error_message($error_message, false);
 }
+
+$form = new FormValidator('import', 'post', api_get_self(), null, array('enctype' => 'multipart/form-data'));
+$form->add_header($tool_name);
+$form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
+$form->addElement('checkbox', 'add_me_as_teacher', null, get_lang('AddMeAsTeacherInCourses'));
+$form->addElement('button', 'save', get_lang('Import'));
+$form->addElement('hidden', 'formSent', 1);
+//$form->setDefaults(array('add_me_as_teacher' => 0));
+$form->display();
+
 ?>
-<form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" style="margin: 0px;">
-<legend><?php echo $tool_name; ?></legend>
-<div class="control-group">
-    <label><?php echo get_lang('ImportCSVFileLocation'); ?></label>
-    <div class="control">
-        <input type="file" name="import_file"/>
-    </div>
-</div>
-<div class="control-group">
-    <div class="control">
-        <button type="submit" class="save" value="<?php echo get_lang('Import'); ?>"><?php echo get_lang('Import'); ?></button>
-    </div>
-</div>
-<input type="hidden" name="formSent" value="1"/>
-</form>
 <div style="clear: both;"></div>
 <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
 

+ 2 - 2
main/admin/example_session.csv

@@ -1,3 +1,3 @@
 SessionName;Coach;DateStart;DateEnd;Users;Courses
-Session1;jmontoya;2008/08/08;2012/12/12;username1|username2;course1[coach1][username1,username2]|course2[coach1][username1,username2]
-Session2;jmontoya;2008/08/08;2012/12/12;username1|username2;course1[coach1][username1,username2]|course2[coach1][username1,username2]
+Session1;jmontoya;2008/08/08;2020/12/12;username1|username2;course1[coach1][username1,username2]|course2[coach1][username1,username2]
+Session2;jmontoya;2008/08/08;2020/12/12;username1|username2;course1[coach1][username1,username2]|course2[coach1][username1,username2]

+ 10 - 23
main/admin/resume_session.php

@@ -96,39 +96,26 @@ switch ($action) {
         }
         break;
     case 'delete':
-        $idChecked = $_GET['idChecked'];
+        $idChecked = isset($_GET['idChecked']) ? $_GET['idChecked'] : null;
         if (is_array($idChecked)) {
-            $my_temp = array();
-            foreach ($idChecked as $id){
-                $my_temp[]= Database::escape_string($id);// forcing the escape_string
+            $usersToDelete = array();
+            foreach ($idChecked as $id) {
+                // forcing the escape_string
+                SessionManager::unsubscribe_user_from_session($id_session, $id);
             }
-            $idChecked = $my_temp;
-
-            $idChecked="'".implode("','",$idChecked)."'";
-
-            Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND course_code IN($idChecked)");
-            $nbr_affected_rows=Database::affected_rows();
-
-            Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code IN($idChecked)");
-            Database::query("UPDATE $tbl_session SET nbr_courses=nbr_courses-$nbr_affected_rows WHERE id='$id_session'");
         }
 
-        if (!empty($_GET['class'])){
+        if (!empty($_GET['class'])) {
             Database::query("DELETE FROM $tbl_session_rel_class WHERE session_id='$id_session' AND class_id=".Database::escape_string($_GET['class']));
             $nbr_affected_rows=Database::affected_rows();
             Database::query("UPDATE $tbl_session SET nbr_classes=nbr_classes-$nbr_affected_rows WHERE id='$id_session'");
         }
 
         if (!empty($_GET['user'])) {
-            Database::query("DELETE FROM $tbl_session_rel_user WHERE relation_type<>".SESSION_RELATION_TYPE_RRHH." AND id_session='$id_session' AND id_user=".intval($_GET['user']));
-            $nbr_affected_rows=Database::affected_rows();
-
-            Database::query("UPDATE $tbl_session SET nbr_users=nbr_users-$nbr_affected_rows WHERE id='$id_session'");
-
-            Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND id_user=".intval($_GET['user']));
-            $nbr_affected_rows=Database::affected_rows();
-
-            Database::query("UPDATE $tbl_session_rel_course SET nbr_users=nbr_users-$nbr_affected_rows WHERE id_session='$id_session'");
+            SessionManager::unsubscribe_user_from_session(
+                $id_session,
+                $_GET['user']
+            );
         }
         break;
 }

+ 48 - 29
main/admin/session_category_edit.php

@@ -4,27 +4,31 @@
  * Edition script for sessions categories
  * @package chamilo.admin
  */
-/**
- * Code
- */
 
 // name of the language file that needs to be included
 $language_file ='admin';
-$cidReset=true;
+$cidReset = true;
 require_once '../inc/global.inc.php';
 
 // setting the section (for the tabs)
-$this_section=SECTION_PLATFORM_ADMIN;
+$this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script(true);
-$id=intval($_GET['id']);
-$formSent=0;
-$errorMsg='';
+$id = intval($_GET['id']);
+$formSent = 0;
+$errorMsg = '';
 
 // Database Table Definitions
 $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 $tool_name = get_lang('EditSessionCategory');
-$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[]=array('url' => "session_category_list.php","name" => get_lang('ListSessionCategory'));
+$interbreadcrumb[] = array(
+    'url' => 'index.php',
+    "name" => get_lang('PlatformAdmin')
+);
+$interbreadcrumb[] = array(
+    'url' => "session_category_list.php",
+    "name" => get_lang('ListSessionCategory')
+);
+
 $sql = "SELECT * FROM $tbl_session_category WHERE id='".$id."' ORDER BY name";
 $result=Database::query($sql);
 if (!$infos=Database::fetch_array($result)) {
@@ -38,24 +42,38 @@ if (!api_is_platform_admin() && $infos['session_admin_id']!=$_user['user_id'] &&
 	api_not_allowed(true);
 }
 
-if ($_POST['formSent']) {
-	$formSent=1;
-	$name= $_POST['name'];
-	$year_start= $_POST['year_start'];
-	$month_start=$_POST['month_start'];
-	$day_start=$_POST['day_start'];
-	$year_end=$_POST['year_end'];
-	$month_end=$_POST['month_end'];
-	$day_end=$_POST['day_end'];
-	$return = SessionManager::edit_category_session($id, $name, $year_start, $month_start, $day_start, $year_end, $month_end, $day_end);
-	if ($return == strval(intval($return))) {
-		header('Location: session_category_list.php?action=show_message&message='.urlencode(get_lang('SessionCategoryUpdate')));
-		exit();
-	}
+if (isset($_POST['formSent']) && $_POST['formSent']) {
+    $formSent = 1;
+    $name = $_POST['name'];
+    $year_start = $_POST['year_start'];
+    $month_start = $_POST['month_start'];
+    $day_start = $_POST['day_start'];
+    $year_end = $_POST['year_end'];
+    $month_end = $_POST['month_end'];
+    $day_end = $_POST['day_end'];
+    $return = SessionManager::edit_category_session(
+        $id,
+        $name,
+        $year_start,
+        $month_start,
+        $day_start,
+        $year_end,
+        $month_end,
+        $day_end
+    );
+    if ($return == strval(intval($return))) {
+        header(
+            'Location: session_category_list.php?action=show_message&message=' . urlencode(
+                get_lang('SessionCategoryUpdate')
+            )
+        );
+        exit();
+    }
 }
-$thisYear=date('Y');
-$thisMonth=date('m');
-$thisDay=date('d');
+
+$thisYear = date('Y');
+$thisMonth = date('m');
+$thisDay = date('d');
 
 // display the header
 Display::display_header($tool_name);
@@ -63,7 +81,7 @@ if (!empty($return)) {
 	Display::display_error_message($return,false);
 }
 ?>
-<form method="post" name="form" action="<?php echo api_get_self(); ?>?page=<?php echo Security::remove_XSS($_GET['page']) ?>&id=<?php echo $id; ?>" style="margin:0px;">
+<form method="post" name="form" action="<?php echo api_get_self(); ?>?id=<?php echo $id; ?>">
 <input type="hidden" name="formSent" value="1">
 <legend><?php echo $tool_name;?> </legend>
 <table border="0" cellpadding="5" cellspacing="0" width="550">
@@ -216,7 +234,8 @@ for($i=$thisYear-5;$i <= ($thisYear+5);$i++)
 <tr>
   <td>&nbsp;</td>
   <td>
-<button class="save" type="submit" value="<?php echo get_lang('ModifyThisSession') ?>"><?php echo get_lang('ModifyThisSession') ?></button>
+<button class="save" type="submit" value="<?php echo get_lang('ModifyThisSession') ?>">
+    <?php echo get_lang('ModifyThisSession') ?></button>
 
   </td>
 </tr>

+ 10 - 21
main/admin/session_course_user_list.php

@@ -1,11 +1,9 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
 *	@package chamilo.admin
 */
-/**
- * Code
- */
 $language_file = array('admin', 'registration');
 $cidReset = true;
 
@@ -26,22 +24,24 @@ if (empty($id_session )) {
 }
 
 $course_code    = Database::escape_string(trim($_GET['course_code']));
-$page           = intval($_GET['page']);
-$action         = $_REQUEST['action'];
+$page           = isset($_GET['page']) ? intval($_GET['page']) : null;
+$action         = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
 $default_sort   = api_sort_by_first_name() ? 'firstname':'lastname';
-$sort           = in_array($_GET['sort'], array('lastname','firstname','username')) ? $_GET['sort'] : $default_sort;
-$idChecked      = (is_array($_GET['idChecked']) ? $_GET['idChecked'] : (is_array($_POST['idChecked']) ? $_POST['idChecked'] : null));
+$sort           = isset($_GET['sort']) && in_array($_GET['sort'], array('lastname','firstname','username')) ? $_GET['sort'] : $default_sort;
+$idChecked      = isset($_GET['idChecked']) && is_array($_GET['idChecked']) ? $_GET['idChecked'] : (isset($_POST['idChecked']) && is_array($_POST['idChecked']) ? $_POST['idChecked'] : null);
 $direction      = isset($_GET['direction']) && in_array($_GET['direction'], array('desc','asc')) ? $_GET['direction'] : 'desc';
 
 if (is_array($idChecked)) {
     $my_temp = array();
     foreach ($idChecked as $id) {
-        $my_temp[]= intval($id);// forcing the intval
+        // forcing the intval
+        $my_temp[]= intval($id);
     }
     $idChecked = $my_temp;
 }
 
-$sql = "SELECT s.name, c.title  FROM $tbl_session_rel_course src
+$sql = "SELECT s.name, c.title
+        FROM $tbl_session_rel_course src
 		INNER JOIN $tbl_session s ON s.id = src.id_session
 		INNER JOIN $tbl_course c ON c.code = src.course_code
 		WHERE src.id_session='$id_session' AND src.course_code='".Database::escape_string($course_code)."' ";
@@ -52,7 +52,7 @@ if (!list($session_name,$course_title) = Database::fetch_row($result)) {
 	exit();
 }
 
-switch($action) {
+switch ($action) {
     case 'delete':
         if (is_array($idChecked) && count($idChecked)>0) {
             array_map('intval', $idChecked);
@@ -77,17 +77,6 @@ switch($action) {
 $limit  = 20;
 $from   = $page * $limit;
 $is_western_name_order = api_is_western_name_order();
-
-//scru.status<>2  scru.course_code='".$course_code."'
-/*$sql = "SELECT DISTINCT
-         u.user_id,".($is_western_name_order ? 'u.firstname, u.lastname' : 'u.lastname, u.firstname').", u.username, scru.id_user as is_subscribed
-         FROM $tbl_session_rel_user s
-         INNER JOIN $tbl_user u ON (u.user_id=s.id_user)
-         LEFT JOIN $tbl_session_rel_course_rel_user scru ON (u.user_id=scru.id_user AND  scru.course_code = '".$course_code."' )
-         WHERE s.id_session='$id_session'
-         ORDER BY $sort $direction
-         LIMIT $from,".($limit+1);*/
-
 $sql = "SELECT DISTINCT
          u.user_id,".($is_western_name_order ? 'u.firstname, u.lastname' : 'u.lastname, u.firstname').", u.username, scru.id_user as is_subscribed
          FROM $tbl_session_rel_user s

+ 11 - 5
main/admin/session_edit.php

@@ -34,12 +34,18 @@ $interbreadcrumb[] = array('url' => 'index.php',"name" => get_lang('PlatformAdmi
 $interbreadcrumb[] = array('url' => "session_list.php","name" => get_lang('SessionList'));
 $interbreadcrumb[] = array('url' => "resume_session.php?id_session=".$id,"name" => get_lang('SessionOverview'));
 
-list($year_start,$month_start,$day_start)   = explode('-', $infos['date_start']);
-list($year_end,$month_end,$day_end)         = explode('-', $infos['date_end']);
+list($year_start, $month_start, $day_start) = explode('-', $infos['date_start']);
+list($year_end, $month_end, $day_end) = explode('-', $infos['date_end']);
 
-$showDescriptionChecked = null;
-if (isset($infos['show_description']) && !empty($infos['show_description'])) {
-    $showDescriptionChecked = 'checked';
+// Default value
+$showDescriptionChecked = 'checked';
+
+if (isset($infos['show_description'])) {
+    if (!empty($infos['show_description'])) {
+        $showDescriptionChecked = 'checked';
+    } else {
+        $showDescriptionChecked = null;
+    }
 }
 
 $end_year_disabled = $end_month_disabled = $end_day_disabled = '';

+ 6 - 6
main/admin/session_import.php

@@ -47,8 +47,8 @@ global $_configuration;
 if (isset($_POST['formSent']) && $_POST['formSent']) {
     if (isset($_FILES['import_file']['tmp_name']) && !empty($_FILES['import_file']['tmp_name'])) {
         $form_sent = $_POST['formSent'];
-        $file_type = $_POST['file_type'];
-        $send_mail = $_POST['sendMail'] ? 1 : 0;
+        $file_type = isset($_POST['file_type']) ? $_POST['file_type'] : null;
+        $send_mail = isset($_POST['sendMail']) && $_POST['sendMail'] ? 1 : 0;
         $isOverwrite = $_POST['overwrite'] ? true: false;
         $deleteUsersNotInList = isset($_POST['delete_users_not_in_list']) ? true : false;
         $sessions = array();
@@ -551,8 +551,8 @@ $form->display();
 <blockquote>
 <pre>
 <strong>SessionName</strong>;Coach;<strong>DateStart</strong>;<strong>DateEnd</strong>;Users;Courses
-<strong>xxx1</strong>;xxx;<strong>xxx;xxx</strong>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
-<strong>xxx2</strong>;xxx;<strong>xxx;xxx</strong>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
+<strong>xxx1</strong>;xxx;<strong>yyyy/mm/dd;yyyy/mm/dd</strong>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
+<strong>xxx2</strong>;xxx;<strong>yyyy/mm/dd;yyyy/mm/dd</strong>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
 </pre>
 </blockquote>
 
@@ -586,8 +586,8 @@ $form->display();
     &lt;Session&gt;
         <strong>&lt;SessionName&gt;xxx&lt;/SessionName&gt;</strong>
         &lt;Coach&gt;xxx&lt;/Coach&gt;
-        <strong>&lt;DateStart&gt;xxx&lt;/DateStart&gt;</strong>
-        <strong>&lt;DateEnd&gt;xxx&lt;/DateEnd&gt;</strong>
+        <strong>&lt;DateStart&gt;yyyy/mm/dd&lt;/DateStart&gt;</strong>
+        <strong>&lt;DateEnd&gt;yyyy/mm/dd&lt;/DateEnd&gt;</strong>
         &lt;User&gt;xxx&lt;/User&gt;
         &lt;User&gt;xxx&lt;/User&gt;
         &lt;Course&gt;

+ 2 - 3
main/auth/gotocourse.php

@@ -9,10 +9,9 @@
  *
  */
 
-require('../inc/global.inc.php');
+require '../inc/global.inc.php';
 require_once(api_get_path(SYS_PATH).'main/auth/cas/authcas.php');
-
-
+$msg = null;
 if (isset($_GET['firstpage'])) {
     $firstpage = $_GET['firstpage'];
 

+ 0 - 1
main/auth/profile.php

@@ -301,7 +301,6 @@ if (is_profile_editable()) {
 } else {
     $form->freeze();
 }
-
 $user_data = array_merge($user_data, $extra_data);
 $form->setDefaults($user_data);
 

+ 109 - 8
main/cron/import_csv.php

@@ -78,6 +78,7 @@ class ImportCsv
         $path = api_get_path(SYS_CODE_PATH).'cron/incoming/';
         if (!is_dir($path)) {
             echo "The folder! $path does not exits";
+
             return 0;
         }
 
@@ -128,6 +129,7 @@ class ImportCsv
 
             if (empty($fileToProcess)) {
                 echo 'Error - no files to process.';
+
                 return 0;
             }
 
@@ -581,15 +583,19 @@ class ImportCsv
     {
         $data = Import::csv_to_array($file);
 
-        //$language = $this->defaultLanguage;
-
         if (!empty($data)) {
             $this->logger->addInfo(count($data)." records found.");
 
             foreach ($data as $row) {
                 $row = $this->cleanCourseRow($row);
-                $courseCode = CourseManager::get_course_id_from_original_id($row['extra_'.$this->extraFieldIdNameList['course']], $this->extraFieldIdNameList['course']);
+
+                $courseCode = CourseManager::get_course_id_from_original_id(
+                    $row['extra_' . $this->extraFieldIdNameList['course']],
+                    $this->extraFieldIdNameList['course']
+                );
+
                 $courseInfo = api_get_course_info($courseCode);
+
                 if (empty($courseInfo)) {
                     // Create
                     $params = array();
@@ -603,7 +609,12 @@ class ImportCsv
                     $courseInfo = CourseManager::create_course($params);
 
                     if (!empty($courseInfo)) {
-                        CourseManager::update_course_extra_field_value($courseInfo['code'], 'external_course_id', $row['extra_'.$this->extraFieldIdNameList['course']]);
+                        CourseManager::update_course_extra_field_value(
+                            $courseInfo['code'],
+                            'external_course_id',
+                            $row['extra_'.$this->extraFieldIdNameList['course']]
+                        );
+
                         $this->logger->addInfo("Courses - Course created ".$courseInfo['code']);
                     } else {
                         $this->logger->addError("Courses - Can't create course:".$row['title']);
@@ -617,6 +628,7 @@ class ImportCsv
                     $result = CourseManager::update_attributes($courseInfo['real_id'], $params);
 
                     $addTeacherToSession = isset($courseInfo['add_teachers_to_sessions_courses']) && !empty($courseInfo['add_teachers_to_sessions_courses']) ? true : false;
+
                     if ($addTeacherToSession) {
                         CourseManager::updateTeachers($courseInfo['id'], $row['teachers'], false, true, false);
                     } else {
@@ -643,12 +655,97 @@ class ImportCsv
      */
     private function importSessionsStatic($file)
     {
-        $this->importSessions($file, false);
+        //$this->importSessions($file, false);
+        $content = file($file);
+        $sessions = array();
+
+        if (!api_strstr($content[0], ';')) {
+            $error_message = get_lang('NotCSV');
+        } else {
+            $tag_names = array();
+
+            foreach ($content as $key => $enreg) {
+                $enreg = explode(';', trim($enreg));
+                if ($key) {
+                    foreach ($tag_names as $tag_key => $tag_name) {
+                        $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
+                    }
+                } else {
+                    foreach ($enreg as $tag_name) {
+                        $tag_names[] = api_preg_replace(
+                            '/[^a-zA-Z0-9_\-]/',
+                            '',
+                            $tag_name
+                        );
+                    }
+                    if (!in_array('SessionName', $tag_names) || !in_array(
+                            'DateStart',
+                            $tag_names
+                        ) || !in_array('DateEnd', $tag_names)
+                    ) {
+                        $error_message = get_lang('NoNeededData');
+                        break;
+                    }
+                }
+            }
+        }
+
+        if (!empty($sessions)) {
+            // Looping the sessions.
+            foreach ($sessions as $session) {
+                if (!empty($session['SessionID'])) {
+                    $sessionId = SessionManager::get_session_id_from_original_id(
+                        $session['SessionID'],
+                        $this->extraFieldIdNameList['session']
+                    );
+
+                    if (!empty($sessionId)) {
+                        $courses = explode('|', $session['Courses']);
+                        foreach ($courses as $course) {
+                            $courseArray = bracketsToArray($course);
+                            $courseCode = $courseArray[0];
+                            if (CourseManager::course_exists($courseCode)) {
+                                $courseUsers = isset($courseArray[2]) ? $courseArray[2] : null;
+                                $courseUsers = explode(',', $courseUsers);
+                                if (!empty($courseUsers)) {
+                                    $userList = array();
+                                    foreach ($courseUsers as $username) {
+                                        $userInfo = api_get_user_info_from_username(trim($username));
+                                        if (!empty($userInfo)) {
+                                            $userList[] = $userInfo['user_id'];
+                                        }
+                                    }
+                                    if (!empty($userList)) {
+                                        SessionManager::subscribe_users_to_session_course(
+                                            $userList,
+                                            $sessionId,
+                                            $courseCode
+                                        );
+                                    } else {
+                                        $this->logger->addInfo("No users to register.");
+                                    }
+                                } else {
+                                    $this->logger->addInfo("No users to register.");
+                                }
+                            } else {
+                                $this->logger->addInfo("Course does not exists $courseCode");
+                            }
+                        }
+                    } else {
+                        $this->logger->addInfo('SessionID not found in system.');
+                    }
+                } else {
+                    $this->logger->addInfo('SessionID does not exists');
+                }
+            }
+        } else {
+            $this->logger->addInfo($error_message);
+        }
     }
 
     /**
      * @param string $file
-     * @param bool $moveFile
+     * @param bool   $moveFile
      */
     private function importSessions($file, $moveFile = true)
     {
@@ -844,7 +941,9 @@ if (isset($argv[1]) && $argv[1] = '--dump') {
     $dump = true;
 }
 
-if (isset($_configuration['import_csv_disable_dump']) && $_configuration['import_csv_disable_dump'] == true) {
+if (isset($_configuration['import_csv_disable_dump']) &&
+    $_configuration['import_csv_disable_dump'] == true
+) {
     $import->setDumpValues(false);
 } else {
     $import->setDumpValues($dump);
@@ -859,7 +958,9 @@ if (isset($_configuration['import_csv_test'])) {
 
 $import->run();
 
-if (isset($_configuration['import_csv_fix_permissions']) && $_configuration['import_csv_fix_permissions'] == true) {
+if (isset($_configuration['import_csv_fix_permissions']) &&
+    $_configuration['import_csv_fix_permissions'] == true
+) {
     $command = "sudo find ".api_get_path(SYS_COURSE_PATH)." -type d -exec chmod 777 {} \; ";
     echo "Executing: ".$command.PHP_EOL;
     system($command);

+ 2 - 2
main/exercice/answer.class.php

@@ -273,8 +273,8 @@ class Answer
 	 * @return string - answer title
 	 */
 	function selectAnswer($id)
-    {
-        return isset($this->answer[$id]) ? $this->answer[$id] : null;
+        {
+            return isset($this->answer[$id]) ? $this->answer[$id] : null;
 	}
 
 	/**

+ 1 - 0
main/exercice/exercice.php

@@ -493,6 +493,7 @@ if (isset($list_ordered) && !empty($list_ordered)) {
 }
 
 echo '<table class="'.Display::return_default_table_class().'">';
+$_user = api_get_user_info();
 
 /*  Listing exercises  */
 if (!empty($exercise_list)) {

+ 1 - 1
main/exercice/exercise.lib.php

@@ -831,7 +831,7 @@ function exercise_time_control_is_valid($exercise_id, $lp_id = 0 , $lp_item_id =
     $sql 	= "SELECT expired_time FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $exercise_id";
     $result = Database::query($sql);
     $row	= Database::fetch_array($result, 'ASSOC');
-    if (!empty($row['expired_time']) ) {
+    if (!empty($row['expired_time'])) {
     	$current_expired_time_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id);
     	if (isset($_SESSION['expired_time'][$current_expired_time_key])) {
             $current_time = time();

+ 0 - 1
main/exercice/exercise_result.php

@@ -49,7 +49,6 @@ if ($debug) {
     error_log('Entering exercise_result.php: '.print_r($_POST, 1));
 }
 
-// general parameters passed via POST/GET
 // general parameters passed via POST/GET
 if (empty($origin)) {
     $origin = Security::remove_XSS($_REQUEST['origin']);

+ 12 - 13
main/exercice/exercise_submit.php

@@ -792,10 +792,9 @@ if (!empty($error)) {
     }
 
     echo '<script>
-
             $(function() {
-    			//$(".exercise_save_now_button").hide();
-    		    $(".main_question").mouseover(function() {
+		        //$(".exercise_save_now_button").hide();
+                $(".main_question").mouseover(function() {
     		    	//$(this).find(".exercise_save_now_button").show();
     		    	//$(this).addClass("question_highlight");
                 });
@@ -807,17 +806,17 @@ if (!empty($error)) {
 
                 $(".no_remind_highlight").hide();
 
-				// if the users validates the form using return key, prevent form action and simulates click on validation button
-				$("#exercise_form").submit(function(){
-					$(".question-validate-btn").first().trigger("click");
-					return false;
-				});
+                // if the users validates the form using return key, prevent form action and simulates click on validation button
+                /*$("#exercise_form").submit(function(){
+                    $(".question-validate-btn").first().trigger("click");
+                    return false;
+                });*/
     		});
 
-			function previous_question(question_num) {
-				url = "exercise_submit.php?'.$params.'&num="+question_num;
-				window.location = url;
-			}
+		function previous_question(question_num) {
+			url = "exercise_submit.php?'.$params.'&num="+question_num;
+			window.location = url;
+		}
 
             function previous_question_and_save(previous_question_id, question_id_to_save) {
                 url = "exercise_submit.php?'.$params.'&num="+previous_question_id;
@@ -1048,7 +1047,7 @@ if (!empty($error)) {
 
             //BUtton save and continue
             switch ($objExercise->type) {
-				case ONE_PER_PAGE:
+	        case ONE_PER_PAGE:
                     $exercise_actions .= $objExercise->show_button($questionId, $current_question);
                     break;
                 case ALL_ON_ONE_PAGE :

+ 189 - 181
main/exercice/matching.class.php

@@ -1,8 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
-/**
- * Code
- */
+
 /**
  *
  *  Class Matching
@@ -14,76 +12,79 @@
  *	@author Eric Marguin
  *	@package chamilo.exercise
  */
-class Matching extends Question {
-	static $typePicture = 'matching.gif';
-	static $explanationLangVar = 'Matching';
-
-	/**
-	 * Constructor
-	 */
-	function Matching(){
-		parent::question();
-		$this -> type = MATCHING;
-		$this -> isContent = $this-> getIsContent();
-	}
-
-	/**
-	 * function which redifines Question::createAnswersForm
-	 * @param the formvalidator instance
-	 */
-	function createAnswersForm ($form) {
-		$defaults = array();
-		$navigator_info = api_get_navigator();
-
-		$nb_matches = $nb_options = 2;
-		if($form -> isSubmitted()) {
-			$nb_matches = $form -> getSubmitValue('nb_matches');
-			$nb_options = $form -> getSubmitValue('nb_options');
-			if(isset($_POST['lessMatches']))
-				$nb_matches--;
-			if(isset($_POST['moreMatches']))
-				$nb_matches++;
-			if(isset($_POST['lessOptions']))
-				$nb_options--;
-			if(isset($_POST['moreOptions']))
-				$nb_options++;
-
-		} else if(!empty($this -> id)) {
-			$answer = new Answer($this -> id);
-			$answer -> read();
-			if(count($answer->nbrAnswers)>0) {
-				$a_matches = $a_options = array();
-				$nb_matches = $nb_options = 0;
-				for($i=1 ; $i<=$answer->nbrAnswers ; $i++){
-					if ($answer -> isCorrect($i)) {
-						$nb_matches++;
-						$defaults['answer['.$nb_matches.']'] = $answer -> selectAnswer($i);
-						$defaults['weighting['.$nb_matches.']'] = float_format($answer -> selectWeighting($i),1);
-						$defaults['matches['.$nb_matches.']'] = $answer -> correct[$i];
-					} else {
-						$nb_options++;
-						$defaults['option['.$nb_options.']'] = $answer -> selectAnswer($i);
-					}
-				}
-
-			}
-		} else {
-			$defaults['answer[1]'] = get_lang('DefaultMakeCorrespond1');
-			$defaults['answer[2]'] = get_lang('DefaultMakeCorrespond2');
-			$defaults['matches[2]'] = '2';
-			$defaults['option[1]'] = get_lang('DefaultMatchingOptA');
-			$defaults['option[2]'] = get_lang('DefaultMatchingOptB');
-		}
-		$a_matches = array();
-		for($i=1 ; $i<=$nb_options ; ++$i) {
-			$a_matches[$i] = chr(64+$i);  // fill the array with A, B, C.....
-		}
-
-		$form -> addElement('hidden', 'nb_matches', $nb_matches);
-		$form -> addElement('hidden', 'nb_options', $nb_options);
-
-		// DISPLAY MATCHES
-		$html='<table class="data_table">
+class Matching extends Question
+{
+    static $typePicture = 'matching.gif';
+    static $explanationLangVar = 'Matching';
+
+    /**
+     * Constructor
+     */
+    public function Matching()
+    {
+        parent::question();
+        $this->type = MATCHING;
+        $this->isContent = $this-> getIsContent();
+    }
+
+    /**
+     * function which redefines Question::createAnswersForm
+     * @param FormValidator $form
+     */
+    public function createAnswersForm ($form)
+    {
+        $defaults = array();
+        $navigator_info = api_get_navigator();
+
+        $nb_matches = $nb_options = 2;
+        if ($form -> isSubmitted()) {
+            $nb_matches = $form -> getSubmitValue('nb_matches');
+            $nb_options = $form -> getSubmitValue('nb_options');
+            if(isset($_POST['lessMatches']))
+                $nb_matches--;
+            if(isset($_POST['moreMatches']))
+                $nb_matches++;
+            if(isset($_POST['lessOptions']))
+                $nb_options--;
+            if(isset($_POST['moreOptions']))
+                $nb_options++;
+
+        } else if(!empty($this -> id)) {
+            $answer = new Answer($this -> id);
+            $answer -> read();
+            if(count($answer->nbrAnswers)>0) {
+                $a_matches = $a_options = array();
+                $nb_matches = $nb_options = 0;
+                for($i=1 ; $i<=$answer->nbrAnswers ; $i++){
+                    if ($answer -> isCorrect($i)) {
+                        $nb_matches++;
+                        $defaults['answer['.$nb_matches.']'] = $answer -> selectAnswer($i);
+                        $defaults['weighting['.$nb_matches.']'] = float_format($answer -> selectWeighting($i),1);
+                        $defaults['matches['.$nb_matches.']'] = $answer -> correct[$i];
+                    } else {
+                        $nb_options++;
+                        $defaults['option['.$nb_options.']'] = $answer -> selectAnswer($i);
+                    }
+                }
+
+            }
+        } else {
+            $defaults['answer[1]'] = get_lang('DefaultMakeCorrespond1');
+            $defaults['answer[2]'] = get_lang('DefaultMakeCorrespond2');
+            $defaults['matches[2]'] = '2';
+            $defaults['option[1]'] = get_lang('DefaultMatchingOptA');
+            $defaults['option[2]'] = get_lang('DefaultMatchingOptB');
+        }
+        $a_matches = array();
+        for($i=1 ; $i<=$nb_options ; ++$i) {
+            $a_matches[$i] = chr(64+$i);  // fill the array with A, B, C.....
+        }
+
+        $form -> addElement('hidden', 'nb_matches', $nb_matches);
+        $form -> addElement('hidden', 'nb_options', $nb_options);
+
+        // DISPLAY MATCHES
+        $html='<table class="data_table">
 					<tr>
 						<th width="10px">
 							'.get_lang('Number').'
@@ -99,42 +100,42 @@ class Matching extends Question {
 						</th>
 					</tr>';
 
-		$form -> addElement ('label', get_lang('MakeCorrespond').'<br /> <img src="../img/fill_field.png">', $html);
-
-		if ($nb_matches < 1) {
-			$nb_matches = 1;
-			Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
-		}
-
-		for($i = 1 ; $i <= $nb_matches ; ++$i) {
-			$form -> addElement ('html', '<tr><td>');
-			$group = array();
-			$puce = $form->createElement('text', null,null,'value="'.$i.'"');
-			$puce->freeze();
-			$group[] = $puce;
-
-			$group[] = $form->createElement('text', 'answer['.$i.']',null, 'size="60" style="margin-left: 0em;"');
-			$group[] = $form->createElement('select', 'matches['.$i.']',null,$a_matches);
-			$group[] = $form->createElement('text', 'weighting['.$i.']',null, array('class' => 'span1', 'value' => 10));
-			$form -> addGroup($group, null, null, '</td><td>');
-			$form -> addElement ('html', '</td></tr>');
-		}
-
-		$form -> addElement ('html', '</table></div></div>');
-		$group = array();
-
-		if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
-			$group[] = $form->createElement('submit', 'lessMatches', get_lang('DelElem'),'class="btn minus"');
-			$group[] = $form->createElement('submit', 'moreMatches', get_lang('AddElem'),'class="btn plus"');
-		} else {
+        $form -> addElement ('label', get_lang('MakeCorrespond').'<br /> <img src="../img/fill_field.png">', $html);
+
+        if ($nb_matches < 1) {
+            $nb_matches = 1;
+            Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
+        }
+
+        for($i = 1 ; $i <= $nb_matches ; ++$i) {
+            $form -> addElement ('html', '<tr><td>');
+            $group = array();
+            $puce = $form->createElement('text', null,null,'value="'.$i.'"');
+            $puce->freeze();
+            $group[] = $puce;
+
+            $group[] = $form->createElement('text', 'answer['.$i.']',null, 'size="60" style="margin-left: 0em;"');
+            $group[] = $form->createElement('select', 'matches['.$i.']',null,$a_matches);
+            $group[] = $form->createElement('text', 'weighting['.$i.']',null, array('class' => 'span1', 'value' => 10));
+            $form -> addGroup($group, null, null, '</td><td>');
+            $form -> addElement ('html', '</td></tr>');
+        }
+
+        $form -> addElement ('html', '</table></div></div>');
+        $group = array();
+
+        if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
+            $group[] = $form->createElement('submit', 'lessMatches', get_lang('DelElem'),'class="btn minus"');
+            $group[] = $form->createElement('submit', 'moreMatches', get_lang('AddElem'),'class="btn plus"');
+        } else {
             $group[] = $form->createElement('style_submit_button', 'moreMatches', get_lang('AddElem'),'class="btn plus"');
-			$group[] = $form->createElement('style_submit_button', 'lessMatches', get_lang('DelElem'),'class="btn minus"');
-		}
+            $group[] = $form->createElement('style_submit_button', 'lessMatches', get_lang('DelElem'),'class="btn minus"');
+        }
 
-		$form -> addGroup($group);
+        $form -> addGroup($group);
 
-		// DISPLAY OPTIONS
-		$html='<table class="data_table">
+        // DISPLAY OPTIONS
+        $html='<table class="data_table">
 					<tr style="text-align: center;">
 						<th width="10px">
 							'.get_lang('Number').'
@@ -143,95 +144,102 @@ class Matching extends Question {
 							'.get_lang('Answer').'
 						</th>
 					</tr>';
-		//$form -> addElement ('html', $html);
+        //$form -> addElement ('html', $html);
         $form -> addElement ('label', null, $html);
 
-		if ($nb_options < 1) {
-			$nb_options = 1;
-			Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
-		}
-
-		for($i = 1 ; $i <= $nb_options ; ++$i) {
-			$form -> addElement ('html', '<tr><td>');
-			$group = array();
-			$puce = $form->createElement('text', null,null,'value="'.chr(64+$i).'"');
-			$puce->freeze();
-			$group[] = $puce;
-			$group[] = $form->createElement('text', 'option['.$i.']',null, array('class' =>'span6'));
-			$form -> addGroup($group, null, null, '</td><td>');
-			$form -> addElement ('html', '</td></tr>');
-		}
-
-		$form -> addElement ('html', '</table></div></div>');
-		$group = array();
-		global $text, $class;
-
-		if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
+        if ($nb_options < 1) {
+            $nb_options = 1;
+            Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
+        }
+
+        for($i = 1 ; $i <= $nb_options ; ++$i) {
+            $form -> addElement ('html', '<tr><td>');
+            $group = array();
+            $puce = $form->createElement('text', null,null,'value="'.chr(64+$i).'"');
+            $puce->freeze();
+            $group[] = $puce;
+            $group[] = $form->createElement('text', 'option['.$i.']',null, array('class' =>'span6'));
+            $form -> addGroup($group, null, null, '</td><td>');
+            $form -> addElement ('html', '</td></tr>');
+        }
+
+        $form -> addElement ('html', '</table></div></div>');
+        $group = array();
+        global $text, $class;
+
+        if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
             // setting the save button here and not in the question class.php
             $group[] = $form->createElement('submit','submitQuestion',$text, 'class="'.$class.'"');
             $group[] = $form->createElement('submit', 'lessOptions', get_lang('DelElem'),'class="minus"');
             $group[] = $form->createElement('submit', 'moreOptions',get_lang('AddElem'),'class="plus"');
-		} else {
+        } else {
             // setting the save button here and not in the question class.php
             $group[] = $form->createElement('style_submit_button', 'lessOptions', get_lang('DelElem'),'class="minus"');
             $group[] = $form->createElement('style_submit_button', 'moreOptions',get_lang('AddElem'),' class="plus"');
             $group[] = $form->createElement('style_submit_button','submitQuestion',$text, 'class="'.$class.'"');
-		}
-
-		$form -> addGroup($group);
-
-		if (!empty($this -> id)) {
-			$form -> setDefaults($defaults);
-		} else {
-			if ($this -> isContent == 1) {
-				$form -> setDefaults($defaults);
-			}
-		}
-
-		$form->setConstants(array('nb_matches' => $nb_matches,'nb_options' => $nb_options));
-	}
-
-
-	/**
-	 * abstract function which creates the form to create / edit the answers of the question
-	 * @param the formvalidator instance
-	 */
-	function processAnswersCreation($form) {
-
-		$nb_matches = $form -> getSubmitValue('nb_matches');
-		$nb_options = $form -> getSubmitValue('nb_options');
-		$this -> weighting = 0;
-		$objAnswer = new Answer($this->id);
-
-		$position = 0;
-
-		// insert the options
-		for($i=1 ; $i<=$nb_options; ++$i) {
-			$position++;
-			$option = $form -> getSubmitValue('option['.$i.']');
-			$objAnswer->createAnswer($option, 0, '', 0, $position);
-		}
-
-		// insert the answers
-		for($i=1 ; $i<=$nb_matches ; ++$i) {
-			$position++;
-			$answer = $form -> getSubmitValue('answer['.$i.']');
-			$matches = $form -> getSubmitValue('matches['.$i.']');
-			$weighting = $form -> getSubmitValue('weighting['.$i.']');
-			$this -> weighting += $weighting;
-			$objAnswer->createAnswer($answer,$matches,'',$weighting,$position);
-		}
-		$objAnswer->save();
-		$this->save();
-	}
-
-	function return_header($feedback_type = null, $counter = null, $score = null) {
-	    $header = parent::return_header($feedback_type, $counter, $score);
+        }
+
+        $form -> addGroup($group);
+
+        if (!empty($this -> id)) {
+            $form -> setDefaults($defaults);
+        } else {
+            if ($this -> isContent == 1) {
+                $form -> setDefaults($defaults);
+            }
+        }
+
+        $form->setConstants(array('nb_matches' => $nb_matches,'nb_options' => $nb_options));
+    }
+
+
+    /**
+     * abstract function which creates the form to create / edit the answers of the question
+     * @param FormValidator $form
+     */
+    public function processAnswersCreation($form)
+    {
+        $nb_matches = $form -> getSubmitValue('nb_matches');
+        $nb_options = $form -> getSubmitValue('nb_options');
+        $this -> weighting = 0;
+        $objAnswer = new Answer($this->id);
+
+        $position = 0;
+
+        // insert the options
+        for($i=1 ; $i<=$nb_options; ++$i) {
+            $position++;
+            $option = $form -> getSubmitValue('option['.$i.']');
+            $objAnswer->createAnswer($option, 0, '', 0, $position);
+        }
+
+        // insert the answers
+        for($i=1 ; $i<=$nb_matches ; ++$i) {
+            $position++;
+            $answer = $form -> getSubmitValue('answer['.$i.']');
+            $matches = $form -> getSubmitValue('matches['.$i.']');
+            $weighting = $form -> getSubmitValue('weighting['.$i.']');
+            $this -> weighting += $weighting;
+            $objAnswer->createAnswer($answer,$matches,'',$weighting,$position);
+        }
+        $objAnswer->save();
+        $this->save();
+    }
+
+    /**
+     * @param null $feedback_type
+     * @param null $counter
+     * @param null $score
+     * @return string
+     */
+    public function return_header($feedback_type = null, $counter = null, $score = null)
+    {
+        $header = parent::return_header($feedback_type, $counter, $score);
         $header .= '<table class="'.$this->question_table_class .'">';
         $header .= '<tr>
                 <th>'.get_lang('ElementList').'</th>
                 <th>'.get_lang('CorrespondsTo').'</th>
               </tr>';
         return $header;
-	}
+    }
 }

+ 0 - 1
main/exercice/overview.php

@@ -98,7 +98,6 @@ if (isset($exercise_stat_info['exe_id'])) {
 }
 
 //1. Check if this is a new attempt or a previous
-//$countNotFinished = isset($exercise_stat_info['num_exe']) ? $exercise_stat_info['num_exe'] : null;
 $label = get_lang('StartTest');
 if ($time_control && !empty($clock_expired_time) || !empty($attempt_list)) {
 	$label = get_lang('ContinueTest');

+ 23 - 20
main/exercice/question.class.php

@@ -905,36 +905,36 @@ abstract class Question
 
             }
         }
-
     }
 
-	/**
-	 * adds an exercise into the exercise list
-	 *
-	 * @author Olivier Brouckaert
+    /**
+     * adds an exercise into the exercise list
+     *
+     * @author Olivier Brouckaert
      * @param integer $exerciseId - exercise ID
      * @param boolean $fromSave - comming from $this->save() or not
-	 */
-	function addToList($exerciseId, $fromSave = false) {
-		$TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
-		$id = $this->id;
-		// checks if the exercise ID is not in the list
-		if (!in_array($exerciseId,$this->exerciseList)) {
-			$this->exerciseList[]=$exerciseId;
+     */
+    function addToList($exerciseId, $fromSave = false)
+    {
+	    $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
+	    $id = $this->id;
+	    // checks if the exercise ID is not in the list
+	    if (!in_array($exerciseId,$this->exerciseList)) {
+		    $this->exerciseList[]=$exerciseId;
             $new_exercise = new Exercise();
             $new_exercise->read($exerciseId);
             $count = $new_exercise->selectNbrQuestions();
             $count++;
-			$sql="INSERT INTO $TBL_EXERCICE_QUESTION (c_id, question_id, exercice_id, question_order) VALUES
-				 ({$this->course['real_id']}, '".Database::escape_string($id)."','".Database::escape_string($exerciseId)."', '$count' )";
-			Database::query($sql);
+		    $sql="INSERT INTO $TBL_EXERCICE_QUESTION (c_id, question_id, exercice_id, question_order) VALUES
+			     ({$this->course['real_id']}, '".Database::escape_string($id)."','".Database::escape_string($exerciseId)."', '$count' )";
+		    Database::query($sql);
 
             // we do not want to reindex if we had just saved adnd indexed the question
             if (!$fromSave) {
             	$this->search_engine_edit($exerciseId, TRUE);
             }
-		}
-	}
+        }
+    }
 
 	/**
 	 * removes an exercise from the exercise list
@@ -943,7 +943,8 @@ abstract class Question
 	 * @param integer $exerciseId - exercise ID
 	 * @return boolean - true if removed, otherwise false
 	 */
-	function removeFromList($exerciseId) {
+	function removeFromList($exerciseId)
+    {
         $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
 
 		$id = $this->id;
@@ -986,7 +987,8 @@ abstract class Question
 	 * @author Olivier Brouckaert
 	 * @param integer $deleteFromEx - exercise ID if the question is only removed from one exercise
 	 */
-	function delete($deleteFromEx = 0) {
+	function delete($deleteFromEx = 0)
+    {
         $course_id = api_get_course_int_id();
 
 		$TBL_EXERCICE_QUESTION	= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
@@ -1050,7 +1052,8 @@ abstract class Question
 	 * @return int     ID of the new question
     */
 
-	function duplicate($course_info = null) {
+	function duplicate($course_info = null)
+    {
         if (empty($course_info)) {
         	$course_info = $this->course;
         } else {

+ 16 - 8
main/exercice/question_pool.php

@@ -79,6 +79,8 @@ if ($is_allowedToEdit) {
         //Reading the source question
 		$old_question_obj = Question::read($old_question_id, $origin_course_id);
 
+        $courseId = $current_course['real_id'];
+
 		if ($old_question_obj) {
 			$old_question_obj->updateTitle($old_question_obj->selectTitle().' - '.get_lang('Copy'));
             //Duplicating the source question, in the current course
@@ -94,10 +96,9 @@ if ($is_allowedToEdit) {
 			// destruction of the Question object
 			unset($new_question_obj);
 			unset($old_question_obj);
-            if (!$objExercise instanceOf Exercise) {
-                $objExercise = new Exercise();
-                $objExercise->read($fromExercise);
-            }
+
+            $objExercise = new Exercise($courseId);
+            $objExercise->read($fromExercise);
 			Session::write('objExercise', $objExercise);
 		}
 		$displayMessage = get_lang('ItemAdded');
@@ -663,7 +664,12 @@ if (is_array($main_question_list)) {
         $data[] = $row;
     }
 }
-Display :: display_sortable_table($header, $data, '', array('per_page_default'=>999,'per_page'=>999,'page_nr'=>1));
+Display :: display_sortable_table(
+    $header,
+    $data,
+    '',
+    array('per_page_default' => 999, 'per_page' => 999, 'page_nr' => 1)
+);
 
 if (!$nbrQuestions) {
 	echo get_lang('NoQuestion');
@@ -811,9 +817,11 @@ function get_action_icon_for_question(
 			unset($myObjEx);
 			break;
 		case "clone":
-			$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>";
+            $url = api_get_self()."?".api_get_cidreq().$getParams."&amp;copy_question=$in_questionid&amp;course_id=$in_selected_course&amp;fromExercise=$from_exercice";
+            $res = Display::url(
+                Display::return_icon('cd.gif', get_lang('ReUseACopyInCurrentTest')),
+                $url
+            );
 			break;
 		default :
 			$res = $in_action;

+ 2 - 1
main/forum/viewforum.php

@@ -277,7 +277,8 @@ echo '<div class="actions">';
 
 if ($origin != 'learnpath') {
     if ($origin=='group') {
-        echo '<a href='.api_get_path(WEB_CODE_PATH).'"group/group_space.php?'.api_get_cidreq().'&amp;gradebook='.$gradebook.'">'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('Groups'),'',ICON_SIZE_MEDIUM).'</a>';
+        echo '<a href"='.api_get_path(WEB_CODE_PATH).'group/group_space.php?'.api_get_cidreq().'&amp;gradebook='.$gradebook.'">'.
+            Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('Groups'),'',ICON_SIZE_MEDIUM).'</a>';
     } else {
         echo '<span style="float:right;">'.search_link().'</span>';
         echo '<a href="'.$forumUrl.'index.php">'.Display::return_icon('back.png', get_lang('BackToForumOverview'), '', ICON_SIZE_MEDIUM).'</a>';

+ 8 - 2
main/inc/ajax/document.ajax.php

@@ -24,7 +24,7 @@ switch($action) {
             exit;
         }
 
-        $ifExists = isset($_POST['if_exists']) ? $_POST['if_exists'] : null;
+        $ifExists = isset($_POST['if_exists']) ? $_POST['if_exists'] : 'overwrite';
 
         if (!empty($_FILES)) {
             require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php';
@@ -39,8 +39,14 @@ switch($action) {
                 false,
                 false
             );
+
             $json = array();
-            $json['name'] = Display::url(api_htmlentities($file['name']), api_htmlentities($result['url']), array('target'=>'_blank'));
+            $json['name'] = Display::url(
+                api_htmlentities($result['title']),
+                api_htmlentities($result['url']),
+                array('target'=>'_blank')
+            );
+
             $json['type'] = api_htmlentities($file['type']);
             $json['size'] = format_file_size($file['size']);
             if (!empty($result) && is_array($result)) {

+ 23 - 15
main/inc/lib/add_course.lib.inc.php

@@ -2716,7 +2716,8 @@ function string2binary($variable) {
  * @todo use an array called $params instead of lots of params
  * @assert (null) === false
  */
-function register_course($params) {
+function register_course($params)
+{
     global $error_msg, $firstExpirationDelay;
 
     $title              = $params['title'];
@@ -2825,25 +2826,32 @@ function register_course($params) {
                     unsubscribe     = '".intval($unsubscribe) . "',
                     visual_code     = '".Database :: escape_string($visual_code) . "'";
         Database::query($sql);
-
-		$course_id  = Database::get_last_insert_id();
+		$course_id  = Database::insert_id();
 
         if ($course_id) {
-
             $sort = api_max_sort_value('0', api_get_user_id());
+            // Default true
+            $addTeacher = isset($params['add_user_as_teacher']) ? $params['add_user_as_teacher'] : true;
+            if ($addTeacher) {
+
+                $i_course_sort = CourseManager:: userCourseSort(
+                    $user_id,
+                    $code
+                );
 
-            $i_course_sort = CourseManager :: userCourseSort($user_id, $code);
-            if (!empty($user_id)) {
-                $sql = "INSERT INTO ".$TABLECOURSUSER . " SET
-                            course_code     = '".Database :: escape_string($code). "',
-                            user_id         = '".intval($user_id) . "',
-                            status          = '1',
-                            role            = '".lang2db(get_lang('Professor')) . "',
-                            tutor_id        = '0',
-                            sort            = '". ($i_course_sort) . "',
-                            user_course_cat = '0'";
-                Database::query($sql);
+                if (!empty($user_id)) {
+                    $sql = "INSERT INTO " . $TABLECOURSUSER . " SET
+                                course_code     = '" . Database:: escape_string($code) . "',
+                                user_id         = '" . intval($user_id) . "',
+                                status          = '1',
+                                role            = '" . lang2db(get_lang('Professor')) . "',
+                                tutor_id        = '0',
+                                sort            = '" . ($i_course_sort) . "',
+                                user_course_cat = '0'";
+                    Database::query($sql);
+                }
             }
+
             if (!empty($teachers)) {
                 if (!is_array($teachers)) {
                     $teachers = array($teachers);

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

@@ -36,8 +36,9 @@ class CourseManager
 
     /**
      * Creates a course
-     * @param   array   with the columns in the main.course table
-     * @return   mixed   false if the course was not created, array with the course info
+     * @param   array   $params columns in the main.course table
+     *
+     * @return  mixed  false if the course was not created, array with the course info
      */
     public static function create_course($params)
     {

+ 21 - 11
main/inc/lib/document.lib.php

@@ -2635,18 +2635,18 @@ class DocumentManager
                 );
 
                 if ($new_path) {
-                    $docid = DocumentManager::get_document_id($course_info, $new_path);
+                    $documentId = DocumentManager::get_document_id($course_info, $new_path);
 
-                    if (!empty($docid)) {
+                    if (!empty($documentId)) {
                         $table_document = Database::get_course_table(TABLE_DOCUMENT);
                         $params = array();
 
-                        if (!empty($title)) {
-                            $params['title'] = get_document_title($title);
+                        if ($if_exists == 'rename') {
+                            $new_path = basename($new_path);
+                            $params['title'] = get_document_title($new_path);
                         } else {
-                            if ($if_exists == 'rename') {
-                                $new_path = basename($new_path);
-                                $params['title'] = get_document_title($new_path);
+                            if (!empty($title)) {
+                                $params['title'] = get_document_title($title);
                             } else {
                                 $params['title'] = get_document_title($files['file']['name']);
                             }
@@ -2655,7 +2655,16 @@ class DocumentManager
                         if (!empty($comment)) {
                             $params['comment'] = trim($comment);
                         }
-                        Database::update($table_document, $params, array('id = ? AND c_id = ? ' => array($docid, $course_info['real_id'])));
+                        Database::update(
+                            $table_document,
+                            $params,
+                            array(
+                                'id = ? AND c_id = ? ' => array(
+                                    $documentId,
+                                    $course_info['real_id']
+                                )
+                            )
+                        );
                     }
 
                     // Showing message when sending zip files
@@ -2664,10 +2673,11 @@ class DocumentManager
                     }
 
                     if ($index_document) {
-                        self::index_document($docid, $course_info['code'], null, $_POST['language'], $_REQUEST, $if_exists);
+                        self::index_document($documentId, $course_info['code'], null, $_POST['language'], $_REQUEST, $if_exists);
                     }
-                    if (!empty($docid) && is_numeric($docid)) {
-                        $document_data = self::get_document_data_by_id($docid, $course_info['code']);
+
+                    if (!empty($documentId) && is_numeric($documentId)) {
+                        $document_data = self::get_document_data_by_id($documentId, $course_info['code']);
                         return $document_data;
                     }
                 }

+ 6 - 2
main/inc/lib/events.lib.inc.php

@@ -312,10 +312,14 @@ function update_event_exercice(
     if ($debug) error_log('duration:' . $duration);
 
     if ($exeid != '') {
-        // Validation in case of fraud with actived control time
+        /*
+         * Code commented due BT#8423 do not change the score to 0.
+         *
+         * Validation in case of fraud with actived control time
         if (!exercise_time_control_is_valid($exo_id, $learnpath_id, $learnpath_item_id)) {
         	$score = 0;
         }
+        */
 
         if (!isset($status) || empty($status)) {
         	$status = '';
@@ -874,7 +878,7 @@ function get_attempt_count_not_finished($user_id, $exerciseId, $lp_id, $lp_item_
     $exerciseId 	= intval($exerciseId);
     $lp_id 			= intval($lp_id);
     $lp_item_id 	= intval($lp_item_id);
-    $lp_item_view_id= intval($lp_item_view_id);
+    //$lp_item_view_id= intval($lp_item_view_id);
 
     $sql = "SELECT count(*) as count FROM $stat_table WHERE
         		exe_exo_id 			= $exerciseId AND

+ 17 - 0
main/inc/lib/extra_field.lib.php

@@ -51,6 +51,7 @@ class ExtraField extends Model
     const FIELD_TYPE_TIMEZONE        = 11;
     const FIELD_TYPE_SOCIAL_PROFILE  = 12;
     const FIELD_TYPE_CHECKBOX        = 13;
+    const FIELD_TYPE_TELEPHONE       = 14;
 
     public $type = 'user'; //or session or course
     public $handler_id = 'user_id';
@@ -204,6 +205,7 @@ class ExtraField extends Model
         $types[self::FIELD_TYPE_TAG]             = get_lang('FieldTypeTag');
         $types[self::FIELD_TYPE_TIMEZONE]        = get_lang('FieldTypeTimezone');
         $types[self::FIELD_TYPE_SOCIAL_PROFILE]  = get_lang('FieldTypeSocialProfile');
+        $types[self::FIELD_TYPE_TELEPHONE]       = get_lang('FieldTypeTelephone');
 
         switch ($handler) {
             case 'course':
@@ -1036,6 +1038,21 @@ EOF;
                             $form->freeze('extra_'.$field_details['field_variable']);
                         }
                         break;
+                    case ExtraField::FIELD_TYPE_TELEPHONE:
+                        $form->addElement(
+                            'text', 
+                            'extra_'.$field_details['field_variable'], 
+                            $field_details['field_display_text'],
+                            array('placeholder'  => '(xx)xxxxxxxxx')
+                        );
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'stripslashes');
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'trim');
+                        $form->applyFilter('extra_'.$field_details['field_variable'], 'telephone');
+                        $form->addRule('extra_'.$field_details[1], get_lang('TelephoneNumberIsWrong'), 'telephone');
+                        if ($field_details['field_visible'] == 0) {
+                            $form->freeze('extra_'.$field_details['field_variable']);
+                        }
+                        break;
                 }
             }
         }

+ 27 - 14
main/inc/lib/fileUpload.lib.php

@@ -9,9 +9,6 @@
  *	@package chamilo.library
  *	@todo test and reorganise
  */
-/**
- * Code
- */
 require_once api_get_path(LIBRARY_PATH).'document.lib.php';
 
 /**
@@ -51,13 +48,15 @@ function disable_dangerous_file($filename) {
 
 /**
  * This function generates a unique name for a file on a given location
- * filenames are changed to name_#.ext
+ * file names are changed to name_#.ext
  *
  * @param string $path
  * @param string $name
- * @return new unique name
+ *
+ * @return string new unique name
  */
-function unique_name($path, $name) {
+function unique_name($path, $name)
+{
 	$ext = substr(strrchr($name, '.'), 0);
 	$name_no_ext = substr($name, 0, strlen($name) - strlen(strstr($name, $ext)));
 	$n = 0;
@@ -266,8 +265,9 @@ function handle_uploaded_document(
 			$file_size = $uploaded_file['size'];
 
 			$files_perm = api_get_permissions_for_new_files();
-            $doc_path = '/'.$clean_name;
-            $docId = DocumentManager :: get_document_id($_course, $doc_path, $current_session_id);
+            //$doc_path = '/'.$clean_name;
+            $docId = DocumentManager::get_document_id($_course, $file_path, $current_session_id);
+
             // What to do if the target file exists
 			switch ($what_if_file_exists) {
 				// Overwrite the file if it exists
@@ -339,9 +339,11 @@ function handle_uploaded_document(
 				case 'rename':
                     if ($docId) {
                         $new_name = unique_name($where_to_save, $clean_name);
+                        $document_name = $new_name;
                     } else {
                         $new_name = $clean_name;
                     }
+
 					$store_path = $where_to_save.$new_name;
 					$new_file_path = $upload_path.$new_name;
 
@@ -362,7 +364,7 @@ function handle_uploaded_document(
 						item_property_update_on_folder($_course, $upload_path, $user_id);
 
 						// Display success message to user
-						if ($output){
+						if ($output) {
 							Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />'.get_lang('UplFileSavedAs').$new_file_path, false);
 						}
 						return $new_file_path;
@@ -446,8 +448,8 @@ function moveUploadedFile($file, $storePath)
 function enough_size($file_size, $dir, $max_dir_space)
 {
     // If the directory is the archive directory, safely ignore the size limit
-    if (api_get_path(SYS_ARCHIVE_PATH) == $dir) { 
-        return true; 
+    if (api_get_path(SYS_ARCHIVE_PATH) == $dir) {
+        return true;
     }
 
     if ($max_dir_space) {
@@ -613,8 +615,8 @@ function add_ext_on_mime($file_name, $file_type) {
  *
  * @return boolean true if it succeds, false otherwise
  */
-function treat_uploaded_file($uploaded_file, $base_work_dir, $upload_path, $max_filled_space, $uncompress = '') {
-
+function treat_uploaded_file($uploaded_file, $base_work_dir, $upload_path, $max_filled_space, $uncompress = '')
+{
 	$uploaded_file['name'] = stripslashes($uploaded_file['name']);
 
 	if (!enough_size($uploaded_file['size'], $base_work_dir, $max_filled_space)) {
@@ -1216,7 +1218,18 @@ function create_unexisting_directory(
                         $session_id
                     );
 				} else {
-					api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'FolderCreated', $user_id, $to_group_id, $to_user_id, null, null, $session_id);
+                    api_item_property_update(
+                        $_course,
+                        TOOL_DOCUMENT,
+                        $document_id,
+                        'FolderCreated',
+                        $user_id,
+                        $to_group_id,
+                        $to_user_id,
+                        null,
+                        null,
+                        $session_id
+                    );
 				}
 				return $desired_dir_name.$nb;
 			}

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

@@ -150,6 +150,7 @@ class FormValidator extends HTML_QuickForm
         $this->registerRule('filetype', null, 'HTML_QuickForm_Rule_Filetype', $dir . 'Rule/Filetype.php');
         $this->registerRule('multiple_required', 'required', 'HTML_QuickForm_Rule_MultipleRequired', $dir . 'Rule/MultipleRequired.php');
         $this->registerRule('url', null, 'HTML_QuickForm_Rule_Url', $dir . 'Rule/Url.php');
+        $this->registerRule('telephone', null, 'HTML_QuickForm_Rule_Telephone', $dir . 'Rule/Telephone.php');
         $this->registerRule('compare_fields', null, 'HTML_QuickForm_Compare_Fields', $dir . 'Rule/CompareFields.php');
         $this->registerRule('CAPTCHA', 'rule', 'HTML_QuickForm_Rule_CAPTCHA', 'HTML/QuickForm/Rule/CAPTCHA.php');
 
@@ -638,3 +639,17 @@ function html_filter_student_fullpage($html)
 {
     return html_filter($html, STUDENT_HTML_FULLPAGE);
 }
+
+/**
+ * Cleans telephone text
+ * @param string $telephone     Telephone number to clean
+ * @return string               The cleaned telephone number
+ */
+function telephone_filter($telephone)
+{
+    $telephone= trim ($telephone,'(');
+    $telephone= trim ($telephone,')');
+    $telephone= ltrim ($telephone,'+');    
+    $telephone= ltrim ($telephone,'0');
+    return $telephone;
+}

+ 64 - 19
main/inc/lib/sessionmanager.lib.php

@@ -1593,7 +1593,18 @@ class SessionManager
                         $subject = '[' . get_setting('siteName') . '] ' . get_lang('YourReg') . ' ' . get_setting('siteName');
                         $user_info = api_get_user_info($user_id);
                         $content = get_lang('Dear') . " " . stripslashes($user_info['complete_name']) . ",\n\n" . sprintf(get_lang('YouAreRegisterToSessionX'), $session_name) . " \n\n" . get_lang('Address') . " " . get_setting('siteName') . " " . get_lang('Is') . " : " . api_get_path(WEB_PATH) . "\n\n" . get_lang('Problem') . "\n\n" . get_lang('Formula') . ",\n\n" . get_setting('administratorName') . " " . get_setting('administratorSurname') . "\n" . get_lang('Manager') . " " . get_setting('siteName') . "\nT. " . get_setting('administratorTelephone') . "\n" . get_lang('Email') . " : " . get_setting('emailAdministrator');
-                        MessageManager::send_message($user_id, $subject, $content, array(), array(), null, null, null, null, null);
+                        MessageManager::send_message(
+                            $user_id,
+                            $subject,
+                            $content,
+                            array(),
+                            array(),
+                            null,
+                            null,
+                            null,
+                            null,
+                            null
+                        );
                     }
                 }
             }
@@ -1607,7 +1618,8 @@ class SessionManager
             if ($empty_users) {
                 foreach ($existingUsers as $existing_user) {
                     if (!in_array($existing_user, $user_list)) {
-                        $sql = "DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='$enreg_course' AND id_user='$existing_user' AND status = 0";
+                        $sql = "DELETE FROM $tbl_session_rel_course_rel_user
+                                WHERE id_session='$id_session' AND course_code='$enreg_course' AND id_user='$existing_user' AND status = 0";
                         Database::query($sql);
                         if (Database::affected_rows()) {
                             $nbr_users--;
@@ -1621,8 +1633,9 @@ class SessionManager
             foreach ($user_list as $enreg_user) {
                 if (!in_array($enreg_user, $existingUsers)) {
                     $enreg_user = Database::escape_string($enreg_user);
-                    $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session, course_code, id_user, visibility, status) VALUES('$id_session','$enreg_course','$enreg_user','$session_visibility', '0')";
-                    Database::query($insert_sql);
+                    $sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session, course_code, id_user, visibility, status)
+                            VALUES('$id_session','$enreg_course','$enreg_user','$session_visibility', '0')";
+                    Database::query($sql);
                     if (Database::affected_rows()) {
                         $nbr_users++;
                     }
@@ -1678,8 +1691,10 @@ class SessionManager
         $course_code,
         $session_visibility = SESSION_VISIBLE_READ_ONLY
     ) {
+        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
         $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
         $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
 
         if (empty($user_list) || empty($session_id) || empty($course_code)) {
             return false;
@@ -1690,10 +1705,10 @@ class SessionManager
         $session_visibility = intval($session_visibility);
 
         $nbr_users = 0;
-        /* AND
-          visibility = $session_visibility */
+
         foreach ($user_list as $enreg_user) {
             $enreg_user = intval($enreg_user);
+            // Checking if user exists in session - course - user table.
             $sql = "SELECT count(id_user) as count
                     FROM $tbl_session_rel_course_rel_user
                     WHERE id_session = $session_id AND
@@ -1708,13 +1723,34 @@ class SessionManager
             }
 
             if ($count == 0) {
-                $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user,visibility)
+                $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session, course_code, id_user, visibility)
                                VALUES ('$session_id','$course_code','$enreg_user','$session_visibility')";
                 Database::query($insert_sql);
                 if (Database::affected_rows()) {
                     $nbr_users++;
                 }
             }
+
+            // Checking if user exists in session - user table.
+            $sql = "SELECT count(id_user) as count
+                    FROM $tbl_session_rel_user
+                    WHERE id_session = $session_id AND id_user = $enreg_user ";
+            $result = Database::query($sql);
+            $count = 0;
+
+            if (Database::num_rows($result) > 0) {
+                $row = Database::fetch_array($result, 'ASSOC');
+                $count = $row['count'];
+            }
+
+            if (empty($count)) {
+                // If user is not registered to a session then add it.
+                $sql = "INSERT IGNORE INTO $tbl_session_rel_user (id_session, id_user) VALUES ('$session_id', '$enreg_user')";
+                Database::query($sql);
+
+                $sql = "UPDATE $tbl_session SET nbr_users = nbr_users + 1 WHERE id='$session_id' ";
+                Database::query($sql);
+            }
         }
 
         // count users in this session-course relation
@@ -1723,9 +1759,9 @@ class SessionManager
         $rs = Database::query($sql);
         list($nbr_users) = Database::fetch_array($rs);
         // update the session-course relation to add the users total
-        $update_sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users
-                       WHERE id_session='$session_id' AND course_code='$course_code'";
-        Database::query($update_sql);
+        $sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users
+                WHERE id_session='$session_id' AND course_code='$course_code'";
+        Database::query($sql);
     }
 
     /**
@@ -3491,7 +3527,6 @@ class SessionManager
                         $session_id = $my_session_result['id'];
 
                         if ($session_id) {
-
                             if ($session_id) {
                                 foreach ($enreg as $key => $value) {
                                     if (substr($key, 0, 6) == 'extra_') { //an extra field
@@ -3655,9 +3690,10 @@ class SessionManager
                         $courseInfo = api_get_course_info($course_code);
 
                         // Adding the course to a session.
-                        $sql_course = "INSERT IGNORE INTO $tbl_session_course
-                                       SET course_code = '$course_code', id_session='$session_id'";
-                        Database::query($sql_course);
+                        $sql = "INSERT IGNORE INTO $tbl_session_course
+                                SET course_code = '$course_code', id_session='$session_id'";
+                        Database::query($sql);
+
                         $course_info = api_get_course_info($course_code);
                         SessionManager::installCourse($session_id, $course_info['real_id']);
 
@@ -3759,7 +3795,12 @@ class SessionManager
                                         $coach_id = UserManager::get_user_id_from_username($course_coach);
                                         if ($coach_id !== false) {
                                             // Just insert new coaches
-                                            SessionManager::updateCoaches($session_id, $course_code, array($coach_id), false);
+                                            SessionManager::updateCoaches(
+                                                $session_id,
+                                                $course_code,
+                                                array($coach_id),
+                                                false
+                                            );
 
                                             if ($debug) {
                                                 $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
@@ -3774,12 +3815,17 @@ class SessionManager
                         }
 
                         // Adding Students, updating relationship "Session - Course - User".
+                        $course_users = array_filter($course_users);
                         if (!empty($course_users)) {
                             foreach ($course_users as $user) {
                                 $user_id = UserManager::get_user_id_from_username($user);
 
                                 if ($user_id !== false) {
-                                    SessionManager::subscribe_users_to_session_course(array($user_id), $session_id, $course_code);
+                                    SessionManager::subscribe_users_to_session_course(
+                                        array($user_id),
+                                        $session_id,
+                                        $course_code
+                                    );
                                     if ($debug) {
                                         $logger->addInfo("Sessions - Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
                                     }
@@ -3795,8 +3841,8 @@ class SessionManager
                 }
                 $access_url_id = api_get_current_access_url_id();
                 UrlManager::add_session_to_url($session_id, $access_url_id);
-                $sql_update_users = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter' WHERE id = '$session_id'";
-                Database::query($sql_update_users);
+                $sql = "UPDATE $tbl_session SET nbr_users = '$user_counter', nbr_courses = '$course_counter' WHERE id = '$session_id'";
+                Database::query($sql);
             }
         }
 
@@ -4042,7 +4088,6 @@ class SessionManager
                 ";
 
         if ($getCount) {
-            ///var_dump($sql);
             $result = Database::query($sql);
             $count = 0;
             if (Database::num_rows($result)) {

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

@@ -706,7 +706,7 @@ class Template
         //Preparing values for the menu
 
         //Logout link
-        $this->assign('logout_link', api_get_path(WEB_PATH).'index.php?logout=logout&&uid='.api_get_user_id());
+        $this->assign('logout_link', api_get_path(WEB_PATH).'index.php?logout=logout&uid='.api_get_user_id());
 
         //Profile link
         if (api_get_setting('allow_social_tool') == 'true') {

+ 17 - 1
main/inc/lib/usermanager.lib.php

@@ -30,6 +30,7 @@ class UserManager
     const USER_FIELD_TYPE_TIMEZONE = 11;
     const USER_FIELD_TYPE_SOCIAL_PROFILE = 12;
     const USER_FIELD_TYPE_FILE = 13;
+    const USER_FIELD_TYPE_TELEPHONE  = 14;
 
     /**
      * The default constructor only instanciates an empty user object
@@ -3831,7 +3832,7 @@ class UserManager
 
         $userConditions = '';
         if (!empty($userStatus)) {
-            $userConditions .= ' AND u.status = '.$userStatus;
+            $userConditions .= ' AND u.status = '.intval($userStatus);
         }
 
         $select = " SELECT DISTINCT u.user_id, u.username, u.lastname, u.firstname, u.email ";
@@ -4563,6 +4564,20 @@ EOF;
                         $form->freeze($extra_field);
                     }
                     break;
+
+                case self::USER_FIELD_TYPE_TELEPHONE:
+                    $form->addElement('text', 'extra_'.$field_details[1], $field_details[3]." (".get_lang('TelephonePrefix').")", 
+                        array('size' => 40, 'placeholder'  => '(xx)xxxxxxxxx'));
+                    $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
+                    $form->applyFilter('extra_'.$field_details[1], 'trim');
+                    $form->applyFilter('extra_'.$field_details[1], 'telephone_filter');
+                    $form->addRule('extra_'.$field_details[1], get_lang('TelephoneNumberIsWrong'), 'telephone');
+                    if (!$admin_permissions) {
+                        if ($field_details[7] == 0) {
+                            $form->freeze('extra_'.$field_details[1]);
+                        }
+                    }                 
+                    break;
             }
         }
         $return = array();
@@ -4589,6 +4604,7 @@ EOF;
         $types[self::USER_FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
         $types[self::USER_FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
         $types[self::USER_FIELD_TYPE_FILE] = get_lang('FieldTypeFile');
+        $types[self::USER_FIELD_TYPE_TELEPHONE] = get_lang('FieldTypeTelephone');
 
         return $types;
     }

+ 49 - 41
main/mySpace/myStudents.php

@@ -710,12 +710,12 @@ if (empty($_GET['details'])) {
     // csv export headers
     $csv_content[] = array ();
     $csv_content[] = array (
-    	get_lang('Learnpath', ''),
-    	get_lang('Time', ''),
-    	get_lang('AverageScore', ''),
-    	get_lang('LatestScore', ''),
-    	get_lang('Progress', ''),
-    	get_lang('LastConnexion', '')
+    	get_lang('Learnpath'),
+    	get_lang('Time'),
+    	get_lang('AverageScore'),
+    	get_lang('LatestAttemptAverageScore'),
+    	get_lang('Progress'),
+    	get_lang('LastConnexion')
     );
 
     if (empty($session_id)) {
@@ -868,12 +868,13 @@ if (empty($_GET['details'])) {
 			</tr>
 		<?php
 
-		$csv_content[] = array ();
-		$csv_content[] = array (
-			get_lang('Exercices'),
-			get_lang('Score'),
-			get_lang('Attempts')
-		);
+		$csv_content[] = array();
+        $csv_content[] = array(
+            get_lang('Exercices'),
+            get_lang('LearningPath'),
+            get_lang('AvgCourseScore'),
+            get_lang('Attempts')
+        );
 
 		$t_quiz = Database :: get_course_table(TABLE_QUIZ_TEST);
 		$sql_exercices = "SELECT quiz.title, id FROM " . $t_quiz . " AS quiz
@@ -898,11 +899,6 @@ if (empty($_GET['details'])) {
                     $lp_name = '-';
                 }
                 $lp_name = !empty($lp_name) ? $lp_name : get_lang('NoLearnpath');
-				$csv_content[] = array (
-					$exercices['title'],
-					$score_percentage . '%',
-					$count_attempts
-				);
 
                 if ($i % 2) {
                     $css_class = 'row_odd';
@@ -956,6 +952,14 @@ if (empty($_GET['details'])) {
 				$data_exercices[$i][] = $exercices['title'];
 				$data_exercices[$i][] = $score_percentage . '%';
 				$data_exercices[$i][] = $count_attempts;
+
+                $csv_content[] = array (
+                    $exercices['title'],
+                    $lp_name,
+                    $score_percentage,
+                    $count_attempts
+                );
+
 				$i++;
 
 			}
@@ -1020,30 +1024,34 @@ if (empty($_GET['details'])) {
 		$documents				= Tracking::count_student_downloaded_documents($student_id, $course_code, $session_id);
 		$uploaded_documents		= Tracking::count_student_uploaded_documents($student_id, $course_code, $session_id);
 
-		$csv_content[] = array (
-			get_lang('Student_publication'),
-			$nb_assignments
-		);
-		$csv_content[] = array (
-			get_lang('Messages'),
-			$messages
-		);
-		$csv_content[] = array (
-			get_lang('LinksDetails'),
-			$links
-		);
-		$csv_content[] = array (
-			get_lang('DocumentsDetails'),
-			$documents
-		);
-		$csv_content[] = array (
-			get_lang('UploadedDocuments'),
-			$uploaded_documents
-		);
-		$csv_content[] = array (
-			get_lang('ChatLastConnection'),
-			$chat_last_connection
-		);
+        $csv_content[] = array(
+            get_lang('OtherTools')
+        );
+
+        $csv_content[] = array(
+            get_lang('Student_publication'),
+            $nb_assignments
+        );
+        $csv_content[] = array(
+            get_lang('Messages'),
+            $messages
+        );
+        $csv_content[] = array(
+            get_lang('LinksDetails'),
+            $links
+        );
+        $csv_content[] = array(
+            get_lang('DocumentsDetails'),
+            $documents
+        );
+        $csv_content[] = array(
+            get_lang('UploadedDocuments'),
+            $uploaded_documents
+        );
+        $csv_content[] = array(
+            get_lang('ChatLastConnection'),
+            $chat_last_connection
+        );
 ?>
 		<tr>
 			<th colspan="2"><?php echo get_lang('OtherTools'); ?></th>

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

@@ -79,9 +79,9 @@ class learnpath
     /**
     * Class constructor. Needs a database handler, a course code and a learnpath id from the database.
     * Also builds the list of items into $this->items.
-    * @param	string		Course code
-    * @param	integer		Learnpath ID
-    * @param	integer		User ID
+    * @param	string		$course Course code
+    * @param	integer		$lp_id
+    * @param	integer		$user_id
     * @return	boolean		True on success, false on error
     */
     public function __construct($course, $lp_id, $user_id)
@@ -2306,14 +2306,14 @@ class learnpath
         return $output;
     }
 
-
     /**
      * Gets the progress bar info to display inside the progress bar. Also used by scorm_api.php
      * @param	string	Mode of display (can be '%' or 'abs').abs means we display a number of completed elements per total elements
      * @param	integer	Additional steps to fake as completed
      * @return	list	Percentage or number and symbol (% or /xx)
      */
-    public function get_progress_bar_text($mode = '', $add = 0) {
+    public function get_progress_bar_text($mode = '', $add = 0)
+    {
         if ($this->debug > 0) {
             error_log('New LP - In learnpath::get_progress_bar_text()', 0);
         }
@@ -2346,12 +2346,11 @@ class learnpath
             }
             $percentage = number_format($percentage, 0);
             $text = '%';
-        }
-        elseif ($mode == 'abs') {
+        } elseif ($mode == 'abs') {
             $percentage = $i;
             $text = '/' . $total_items;
         }
-        return array (
+        return array(
             $percentage,
             $text
         );
@@ -2557,7 +2556,7 @@ class learnpath
                     ' '
                 );
                 $prereq_mod = str_replace($find, $replace, $prereq);
-                $ids = split(' ', $prereq_mod);
+                $ids = explode(' ', $prereq_mod);
                 foreach ($ids as $id) {
                     $id = trim($id);
                     if (isset ($this->refs_list[$id])) {
@@ -4019,11 +4018,12 @@ class learnpath
 
     /**
      * Saves the given item
-     * @param	integer	Item ID. Optional (will take from $_REQUEST if null)
-     * @param	boolean	Save from url params (true) or from current attributes (false). Optional. Defaults to true
+     * @param	integer	$item_id. Optional (will take from $_REQUEST if null)
+     * @param	boolean	$from_outside Save from url params (true) or from current attributes (false). Optional. Defaults to true
      * @return	boolean
      */
-    public function save_item($item_id = null, $from_outside = true) {
+    public function save_item($item_id = null, $from_outside = true)
+    {
         $debug = $this->debug;
         if ($debug) {
             error_log('In learnpath::save_item(' . $item_id . ',' . intval($from_outside). ')', 0);

+ 30 - 21
main/newscorm/learnpathItem.class.php

@@ -778,9 +778,9 @@ class learnpathItem
             error_log('learnpathItem::get_max()', 0);
         }
         if ($this->type == 'sco') {
-            if (!empty($this->view_max_score) && $this->view_max_score > 0) {
+            if (isset($this->view_max_score) && !empty($this->view_max_score) && $this->view_max_score > 0) {
                 return $this->view_max_score;
-            } elseif ($this->view_max_score === '') {
+            } elseif (isset($this->view_max_score) && $this->view_max_score === '') {
                 return $this->view_max_score;
             } else {
                 if (!empty($this->max_score)) {
@@ -1668,9 +1668,9 @@ class learnpathItem
 
     /**
      * Gets the item status
-     * @param    boolean    Do or don't check into the database for the latest value. Optional. Default is true
-     * @param    boolean    Do or don't update the local attribute value with what's been found in DB
-     * @return    string    Current status or 'Not attempted' if no status set yet
+     * @param    boolean $check_db   Do or don't check into the database for the latest value. Optional. Default is true
+     * @param    boolean $update_local   Do or don't update the local attribute value with what's been found in DB
+     * @return   string  Current status or 'Not attempted' if no status set yet
      */
     public function get_status($check_db = true, $update_local = false)
     {
@@ -1684,8 +1684,11 @@ class learnpathItem
             }
             if (!empty($this->db_item_view_id)) {
                 $table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
-                $sql = "SELECT status FROM $table WHERE c_id = $course_id AND id = '" . $this->db_item_view_id . "' AND view_count = '" . $this->get_attempt_id(
-                    ) . "'";
+                $sql = "SELECT status FROM $table
+                        WHERE
+                            c_id = $course_id AND
+                            id = '" . $this->db_item_view_id . "' AND
+                            view_count = '" . $this->get_attempt_id() . "'";
                 if (self::debug > 2) {
                     error_log(
                         'learnpathItem::get_status() - Checking DB: ' . $sql,
@@ -1768,6 +1771,7 @@ class learnpathItem
         $query_db = false
     ) {
         $h = get_lang('h');
+        $time = null;
         $course_id = api_get_course_int_id();
         if (!isset($given_time)) {
             if (self::debug > 2) {
@@ -2457,7 +2461,7 @@ class learnpathItem
                                     );
                                 }
 
-                                if (isset($items[$refs_list[$prereqs_string]])) {
+                                if (isset($refs_list[$prereqs_string]) && isset($items[$refs_list[$prereqs_string]])) {
                                     if ($items[$refs_list[$prereqs_string]]->type == 'quiz') {
 
                                         // 1. Checking the status in current items.
@@ -3131,8 +3135,9 @@ class learnpathItem
                 TABLE_LP_IV_INTERACTION
             );
             $sql = "SELECT * FROM $item_view_interaction_table
-                WHERE c_id = $course_id
-                    AND lp_iv_id = '" . $this->db_item_view_id . "'";
+                    WHERE
+                        c_id = $course_id AND
+                        lp_iv_id = '" . $this->db_item_view_id . "'";
             //error_log('sql10->'.$sql);
             $res = Database::query($sql);
             if ($res !== false) {
@@ -3145,8 +3150,9 @@ class learnpathItem
                 TABLE_LP_IV_OBJECTIVE
             );
             $sql = "SELECT * FROM $item_view_objective_table
-                WHERE c_id = $course_id
-                    AND lp_iv_id = '" . $this->db_item_view_id . "'";
+                    WHERE
+                        c_id = $course_id AND
+                        lp_iv_id = '" . $this->db_item_view_id . "'";
             //error_log('sql11->'.$sql);
             $res = Database::query($sql);
             if ($res !== false) {
@@ -3265,21 +3271,22 @@ class learnpathItem
 
     /**
      * Sets the status for this item
-     * @param    string    Status - must be one of the values defined in $this->possible_status
-     * @return    boolean    True on success, false on error
+     * @param   string $status must be one of the values defined in $this->possible_status
+     * @return  boolean True on success, false on error
      */
     public function set_status($status)
     {
         if (self::debug > 0) {
             error_log('learnpathItem::set_status(' . $status . ')', 0);
         }
+
         $found = false;
         foreach ($this->possible_status as $possible) {
             if (preg_match('/^' . $possible . '$/i', $status)) {
                 $found = true;
             }
         }
-        //if (in_array($status, $this->possible_status)) {
+
         if ($found) {
             $this->status = Database::escape_string($status);
             if (self::debug > 1) {
@@ -3292,8 +3299,9 @@ class learnpathItem
             }
             return true;
         }
-        //error_log('New LP - '.$status.' was not in the possible status', 0);
+
         $this->status = $this->possible_status[0];
+
         return false;
     }
 
@@ -3319,14 +3327,15 @@ class learnpathItem
         }
         $new_terms = $a_terms;
         $new_terms_string = implode(',', $new_terms);
-        $terms_update_sql = '';
+
         // TODO: Validate csv string.
         $terms = Database::escape_string(api_htmlentities($new_terms_string, ENT_QUOTES, $charset));
-        $terms_update_sql = "UPDATE $lp_item
+        $sql = "UPDATE $lp_item
                 SET terms = '$terms'
-                WHERE c_id = $course_id
-                    AND id=" . $this->get_id();
-        $res = Database::query($terms_update_sql);
+                WHERE
+                    c_id = $course_id AND
+                    id=" . $this->get_id();
+        Database::query($sql);
         // Save it to search engine.
         if (api_get_setting('search_enabled') == 'true') {
             $di = new ChamiloIndexer();

+ 41 - 20
main/newscorm/lp_ajax_save_item.php

@@ -44,8 +44,23 @@ require_once 'aiccItem.class.php';
  * @param   array   Interactions array
  * @param   string  Core exit SCORM string
  */
-function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1, $min = -1, $status = '', $time = 0, $suspend = '', $location = '', $interactions = array(), $core_exit = 'none', $sessionId = null, $courseId = null)
-{
+function save_item(
+    $lp_id,
+    $user_id,
+    $view_id,
+    $item_id,
+    $score = -1,
+    $max = -1,
+    $min = -1,
+    $status = '',
+    $time = 0,
+    $suspend = '',
+    $location = '',
+    $interactions = array(),
+    $core_exit = 'none',
+    $sessionId = null,
+    $courseId = null
+) {
     global $debug;
     $return = null;
 
@@ -58,9 +73,10 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
 
     $mylp = null;
     $lpobject = Session::read('lpobject');
-    if (!is_object($lpobject) && isset($sessionId) && isset($courseId)) {
+    /*if (!is_object($lpobject) && isset($sessionId) && isset($courseId)) {
         $lpobject = new learnpathItem($lp_id, $user_id, $courseId);
-    }
+    }*/
+
     if (isset($lpobject)) {
         if (is_object($lpobject)) {
             $mylp = $lpobject;
@@ -87,6 +103,7 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
         if ($debug) {
             error_log("mylp variable is not an learnpath object");
         }
+
         return null;
     }
 
@@ -99,6 +116,7 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
         if ($debug > 0) {
             error_log("item #$item_id not found in the items array: ".print_r($mylp->items, 1));
         }
+
         return false;
     }
 
@@ -113,6 +131,7 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
         }
 
         return $return;
+
     } else {
         if ($debug > 1) { error_log('Prerequisites are OK'); }
 
@@ -137,17 +156,17 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
             if ($debug > 1) { error_log('Done calling set_score '.$mylpi->get_score(), 0); }
         } else {
             if ($debug > 1) { error_log("Score not updated"); }
+        }
 
-            // Default behaviour
-            if (isset($status) && $status != '' && $status != 'undefined') {
-                if ($debug > 1) { error_log('Calling set_status('.$status.')', 0); }
+        // Default behaviour.
+        if (isset($status) && $status != '' && $status != 'undefined') {
+            if ($debug > 1) { error_log('Calling set_status('.$status.')', 0); }
 
-                $mylpi->set_status($status);
+            $mylpi->set_status($status);
 
-                if ($debug > 1) { error_log('Done calling set_status: checking from memory: '.$mylpi->get_status(false), 0); }
-            } else {
-                if ($debug > 1) { error_log("Status not updated"); }
-            }
+            if ($debug > 1) { error_log('Done calling set_status: checking from memory: '.$mylpi->get_status(false), 0); }
+        } else {
+            if ($debug > 1) { error_log("Status not updated"); }
         }
 
         // Hack to set status to completed for hotpotatoes if score > 80%.
@@ -235,8 +254,6 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
     if ($debug > 1) { error_log("myprogress_mode: $myprogress_mode", 0); }
     if ($debug > 1) { error_log("progress: $mycomplete / $mytotal", 0); }
 
-    //$_SESSION['lpobject'] = serialize($mylp);
-
     if ($mylpi->get_type() != 'sco') {
         // If this object's JS status has not been updated by the SCORM API, update now.
         $return .= "olms.lesson_status='".$mystatus."';";
@@ -245,7 +262,9 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
     $update_list = $mylp->get_update_queue();
 
     foreach ($update_list as $my_upd_id => $my_upd_status)  {
-        if ($my_upd_id != $item_id) { // Only update the status from other items (i.e. parents and brothers), do not update current as we just did it already.
+        if ($my_upd_id != $item_id) {
+            /* Only update the status from other items (i.e. parents and brothers),
+            do not update current as we just did it already. */
             $return .= "update_toc('".$my_upd_status."','".$my_upd_id."');";
         }
     }
@@ -259,18 +278,20 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
         // If $_SESSION['login_as'] is set, then the user is an admin logged as the user.
         $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
 
-        $sql_last_connection = "SELECT login_id, login_date
+        $sql = "SELECT login_id, login_date
             FROM $tbl_track_login
             WHERE login_user_id='".api_get_user_id()."'
             ORDER BY login_date DESC LIMIT 0,1";
 
-        $q_last_connection = Database::query($sql_last_connection);
+        $q_last_connection = Database::query($sql);
         if (Database::num_rows($q_last_connection) > 0) {
             $current_time = api_get_utc_datetime();
             $row = Database::fetch_array($q_last_connection);
             $i_id_last_connection = $row['login_id'];
-            $s_sql_update_logout_date = "UPDATE $tbl_track_login SET logout_date='".$current_time."' WHERE login_id='$i_id_last_connection'";
-            Database::query($s_sql_update_logout_date);
+            $sql = "UPDATE $tbl_track_login
+                    SET logout_date='".$current_time."'
+                    WHERE login_id='$i_id_last_connection'";
+            Database::query($sql);
         }
     }
 
@@ -278,7 +299,7 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
          $return .= "update_stats();";
     }
 
-    //To be sure progress is updated
+    // To be sure progress is updated.
     $mylp->save_last();
 
     Session::write('lpobject', serialize($mylp));

+ 1 - 0
main/newscorm/lp_controller.php

@@ -355,6 +355,7 @@ if (!$lp_found || (!empty($_REQUEST['lp_id']) && $_SESSION['oLP']->get_id() != $
         $_SESSION['oLP'] = $oLP;
     }
 }
+
 if ($debug > 0) error_log('New LP - Passed oLP creation check', 0);
 
 $is_allowed_to_edit = api_is_allowed_to_edit(false, true, false, false);

+ 5 - 4
main/newscorm/lp_view.php

@@ -42,12 +42,13 @@ $lp_id = intval($_GET['lp_id']);
 
 // Check if the learning path is visible for student - (LP requisites)
 
-if (!api_is_allowed_to_edit(null, true) && !learnpath::is_lp_visible_for_student($lp_id, api_get_user_id())) {
-
-    api_not_allowed(true);
+if (!api_is_platform_admin()) {
+    if (!api_is_allowed_to_edit(null, true) && !learnpath::is_lp_visible_for_student($lp_id, api_get_user_id())) {
+        api_not_allowed(true);
+    }
 }
 
-//Checking visibility (eye icon)
+// Checking visibility (eye icon)
 $visibility = api_get_item_visibility(api_get_course_info(), TOOL_LEARNPATH, $lp_id, $action, api_get_user_id(), api_get_session_id());
 if (!api_is_allowed_to_edit(false, true, false, false) && intval($visibility) == 0) {
     api_not_allowed(true);

+ 23 - 20
main/survey/create_new_survey.php

@@ -134,33 +134,18 @@ 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'));
 
 if ($_GET['action'] == 'edit') {
-    $survey_code->freeze();
+    //$survey_code->freeze();
     $form->applyFilter('survey_code', 'api_strtoupper');
 }
 
 $form->addElement('html_editor', 'survey_title', get_lang('SurveyTitle'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '200'));
 $form->addElement('html_editor', 'survey_subtitle', get_lang('SurveySubTitle'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '100', 'ToolbarStartExpanded' => false));
 
-/*
-  //Language selection has been disabled. If you want to re-enable, please
-  //disable the following line (hidden language field).
-  $lang_array = api_get_languages();
-  foreach ($lang_array['name'] as $key => $value) {
-  $languages[$lang_array['folder'][$key]] = $value;
-  }
-  $form->addElement('select', 'survey_language', get_lang('Language'), $languages);
- */
-
 // Pass the language of the survey in the form
 $form->addElement('hidden', 'survey_language');
 $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);
-/** TODO Maybe it is better to change this into false instead see line 95 in survey.lib.php */
-//$group[] =& HTML_QuickForm::createElement('radio', 'survey_share', null, get_lang('No'), 0);
-//$form->addGroup($group, 'survey_share', get_lang('ShareSurvey'), '&nbsp;');
 $form->addElement('checkbox', 'anonymous', null, get_lang('Anonymous'));
 $form->addElement('html_editor', 'survey_introduction', get_lang('SurveyIntroduction'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '130', 'ToolbarStartExpanded' => false));
 $form->addElement('html_editor', 'survey_thanks', get_lang('SurveyThanks'), null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '130', 'ToolbarStartExpanded' => false));
@@ -294,11 +279,14 @@ if ($form->validate()) {
         // Display the form
         $form->display();
     } else {
-        $gradebook_option = $values['survey_qualify_gradebook'] > 0;
+        $gradebook_option = false;
+        if (isset($values['survey_qualify_gradebook'])) {
+            $gradebook_option = $values['survey_qualify_gradebook'] > 0;
+        }
+
         if ($gradebook_option) {
             $survey_id = intval($return['id']);
             if ($survey_id > 0) {
-
                 $title_gradebook = ''; // Not needed here.
                 $description_gradebook = ''; // Not needed here.
                 $survey_weight = floatval($_POST['survey_weight']);
@@ -306,10 +294,25 @@ if ($form->validate()) {
                 $date = time(); // TODO: Maybe time zones implementation is needed here.
                 $visible = 1; // 1 = visible
 
-                $link_info = is_resource_in_course_gradebook($course_id, $gradebook_link_type, $survey_id, $session_id);
+                $link_info = is_resource_in_course_gradebook(
+                    $course_id,
+                    $gradebook_link_type,
+                    $survey_id,
+                    $session_id
+                );
                 $gradebook_link_id = $link_info['id'];
                 if (!$gradebook_link_id) {
-                    add_resource_to_course_gradebook($course_id, $gradebook_link_type, $survey_id, $title_gradebook, $survey_weight, $max_score, $description_gradebook, 1, $session_id);
+                    add_resource_to_course_gradebook(
+                        $course_id,
+                        $gradebook_link_type,
+                        $survey_id,
+                        $title_gradebook,
+                        $survey_weight,
+                        $max_score,
+                        $description_gradebook,
+                        1,
+                        $session_id
+                    );
                 } else {
                     Database::query('UPDATE '.$table_gradebook_link.' SET weight='.$survey_weight.' WHERE id='.$gradebook_link_id);
                 }

+ 2 - 2
main/survey/preview.php

@@ -73,7 +73,7 @@ if (api_is_allowed_to_edit()) {
 	$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);
 }
-$courseCode = $_GET['cidReq'];
+$courseCode = isset($_GET['cidReq']) ? $_GET['cidReq'] : null;
 $surveyAnonymous = survey_manager::get_survey($survey_id, 0, $courseCode);
 $surveyAnonymous = $surveyAnonymous['anonymous'];
 if ($surveyAnonymous == 0 && api_is_anonymous()) {
@@ -215,7 +215,7 @@ if (api_is_course_admin() || (api_is_course_admin() && $_GET['isStudentView'] ==
 
 	if (($show < $numberofpages) || (!$_GET['show'] && count($questions) > 0)) {
         if ($show == 0) {
-            echo '<br /><button type="submit" name="next_survey_page" class="next">'.get_lang('StartSurvey').'   </button>';    
+            echo '<br /><button type="submit" name="next_survey_page" class="next">'.get_lang('StartSurvey').'   </button>';
         } else {
 		    echo '<br /><button type="submit" name="next_survey_page" class="next">'.get_lang('NextQuestion').'   </button>';
         }

+ 16 - 5
main/survey/question.php

@@ -63,7 +63,6 @@ if (empty($survey_data)) {
 	exit;
 }
 
-
 $urlname = api_substr(api_html_entity_decode($survey_data['title'], ENT_QUOTES), 0, 40);
 if (api_strlen(strip_tags($survey_data['title'])) > 40) {
 	$urlname .= '...';
@@ -75,7 +74,7 @@ if ($survey_data['survey_type'] == 1) {
                 c_id = '.$course_id.' AND
                 survey_id = '.(int)$_GET['survey_id'].' LIMIT 1';
 	$rs = Database::query($sql);
-	if(Database::num_rows($rs)===0) {
+	if (Database::num_rows($rs)===0) {
 		header('Location: '.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.(int)$_GET['survey_id'].'&message='.'YouNeedToCreateGroups');
 		exit;
 	}
@@ -94,7 +93,18 @@ if ($_GET['action'] == 'edit') {
 }
 
 // The possible question types
-$possible_types = array('personality', 'yesno', 'multiplechoice', 'multipleresponse', 'open', 'dropdown', 'comment', 'pagebreak', 'percentage', 'score');
+$possible_types = array(
+    'personality',
+    'yesno',
+    'multiplechoice',
+    'multipleresponse',
+    'open',
+    'dropdown',
+    'comment',
+    'pagebreak',
+    'percentage',
+    'score'
+);
 
 // Actions
 $actions = '<div class="actions">';
@@ -108,16 +118,17 @@ if (!in_array($_GET['type'], $possible_types)) {
 	Display :: display_footer();
 }
 
+$error_message = '';
+
 // Displaying the form for adding or editing the question
 if (empty($_POST['save_question']) && in_array($_GET['type'], $possible_types)) {
 	if (!isset($_POST['save_question'])) {
 		// Displaying the header
 		Display::display_header($tool_name, 'Survey');
 		echo $actions;
-		$error_message = '';
 		// Displys message if exists
 		if (isset($_SESSION['temp_sys_message'])) {
-			$error_message=$_SESSION['temp_sys_message'];
+			$error_message = $_SESSION['temp_sys_message'];
 			unset($_SESSION['temp_sys_message']);
 			if ($error_message == 'PleaseEnterAQuestion' ||
                 $error_message == 'PleasFillAllAnswer'||

+ 168 - 76
main/survey/survey.lib.php

@@ -11,9 +11,7 @@
  * @author cfasanando
  *
  */
-/**
- * Code
- */
+
 $config['survey']['debug'] = false;
 
 $htmlHeadXtra[] = '<script>
@@ -32,6 +30,34 @@ $(document).ready(function () {
  */
 class survey_manager
 {
+    /**
+     * @param $code
+     * @return string
+     */
+    public static function generate_unique_code($code)
+    {
+        if (empty($code)) {
+            return false;
+        }
+        $course_id = api_get_course_int_id();
+        $table_survey = Database::get_course_table(TABLE_SURVEY);
+        $code = Database::escape_string($code);
+        $num = 0;
+        $new_code = $code;
+        while (true) {
+            $sql = "SELECT * FROM $table_survey
+                    WHERE code = '$new_code' AND c_id = $course_id";
+            $result = Database::query($sql);
+            if (Database::num_rows($result)) {
+                $num++;
+                $new_code = $code . $num;
+            } else {
+                break;
+            }
+        }
+        return $code.$num;
+    }
+
     /**
      * Deletes all survey invitations of a user
      * @param int $user_id
@@ -102,7 +128,7 @@ class survey_manager
 	 *
 	 * @todo this is the same function as in create_new_survey.php
 	 */
-    public static function get_survey($survey_id, $shared = 0, $course_code = '')
+    public static function get_survey($survey_id, $shared = 0, $course_code = '', $simple_return = false)
     {
 		// Table definition
 		if (!empty($course_code)) {
@@ -131,6 +157,9 @@ class survey_manager
 
 		if (Database::num_rows($result)> 0) {
 			$return = Database::fetch_array($result,'ASSOC');
+            if ($simple_return) {
+                return $return;
+            }
 			// We do this (temporarily) to have the array match the quickform elements immediately
 			// idealiter the fields in the db match the quickform fields
 			$return['survey_code'] 			= $return['code'];
@@ -170,7 +199,7 @@ class survey_manager
 		$table_survey 	= Database :: get_course_table(TABLE_SURVEY);
 		$shared_survey_id = 0;
 
-		if (!$values['survey_id'] || !is_numeric($values['survey_id'])) {
+		if (!isset($values['survey_id'])) {
 			// Check if the code doesn't soon exists in this language
 			$sql = 'SELECT 1 FROM '.$table_survey.'
 			        WHERE
@@ -185,16 +214,19 @@ class survey_manager
 				return $return;
 			}
 
-			if ($values['anonymous'] == '') {
+			if (!isset($values['anonymous'])) {
 				$values['anonymous'] = 0;
 			}
 
+            $values['anonymous'] = intval($values['anonymous']);
+
 			$additional['columns'] = '';
 			$additional['values'] = '';
 
 			if ($values['anonymous'] == 0) {
 				// Input_name_list
 				$additional['columns'] .= ', show_form_profile';
+                $values['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : null;
 				$additional['values'] .= ",'".Database::escape_string($values['show_form_profile'])."'";
 
 				if ($values['show_form_profile'] == 1) {
@@ -262,7 +294,6 @@ class survey_manager
 						$row = Database::fetch_array($rs, 'ASSOC');
 						$pos = api_strpos($row['survey_version']);
 						if ($pos === false) {
-							//$new_version = substr($row['survey_version'],$pos, count())
 							$row['survey_version'] = $row['survey_version'] + 1;
 							$additional['values'] .= ",'".$row['survey_version']."'";
 						} else {
@@ -294,7 +325,7 @@ class survey_manager
 						'".Database::escape_string('template')."',
 						'".Database::escape_string($values['survey_introduction'])."',
 						'".Database::escape_string($values['survey_thanks'])."',
-						'".date('Y-m-d H:i:s')."',
+						'".api_get_utc_datetime()."',
 						'".Database::escape_string($values['anonymous'])."'".$additional['values'].",
 						".api_get_session_id()."
 						)";
@@ -306,7 +337,7 @@ class survey_manager
 			}
 
 			if ($values['survey_type'] == 1 && !empty($values['parent_id'])) {
-				survey_manager::copy_survey($values['parent_id'],$survey_id);
+				survey_manager::copy_survey($values['parent_id'], $survey_id);
 			}
 
 			$return['message'] = 'SurveyCreatedSuccesfully';
@@ -486,11 +517,12 @@ class survey_manager
 	}
 
     /**
-     * @param int $parent_survey
+     * @param int $survey_id
      * @param int $new_survey_id
+     *
      * @return bool
      */
-    public function copy_survey($parent_survey, $new_survey_id)
+    public static function copy_survey($survey_id, $new_survey_id = null)
     {
 	    $course_id = api_get_course_int_id();
 
@@ -499,39 +531,83 @@ class survey_manager
 		$table_survey_question_group 	= Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
 		$table_survey_question 			= Database::get_course_table(TABLE_SURVEY_QUESTION);
 		$table_survey_options 			= Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
-		$parent_survey 					= Database::escape_string($parent_survey);
+        $survey_id                      = Database::escape_string($survey_id);
+
 		// Get groups
-		$sql = "SELECT * from $table_survey_question_group WHERE c_id = $course_id AND survey_id='".$parent_survey."'";
-		$res = Database::query($sql);
-		if (Database::num_rows($res) === 0) {
-			return true;
-		}
-		$new_survey_id = intval($new_survey_id);
-		while($row = Database::fetch_array($res, 'ASSOC')){
-			$sql1 = 'INSERT INTO '.$table_survey_question_group.' (c_id, name,description,survey_id) VALUES
-					('.$course_id.', \''.Database::escape_string($row['name']).'\',\''.Database::escape_string($row['description']).'\',\''.$new_survey_id.'\')';
-			Database::query($sql1);
-			$group_id[$row['id']] = Database::insert_id();
-		}
+        $survey_data = self::get_survey($survey_id, 0, null, true);
+        if (empty($survey_data)) {
+            return true;
+        }
 
-		// Get questions
-		$sql = "SELECT * FROM $table_survey_question WHERE c_id = $course_id AND survey_id='".$parent_survey."'";
-		$res = Database::query($sql);
-		while($row = Database::fetch_array($res, 'ASSOC')){
-			$sql2 = 'INSERT INTO '.$table_survey_question.' (c_id, survey_id,survey_question,survey_question_comment,type,display,sort,shared_question_id,max_value,survey_group_pri,survey_group_sec1,survey_group_sec2) VALUES '.
-			'('.$course_id.', \''.$new_survey_id.'\',\''.Database::escape_string($row['survey_question']).'\',\''.Database::escape_string($row['survey_comment']).'\',\''.$row['type'].'\',\''.$row['display'].'\',\''.$row['sort'].'\',\''.$row['shared_question_id'].'\',\''.$row['max_value'].
-			'\',\''.$group_id[$row['survey_group_pri']].'\',\''.$group_id[$row['survey_group_sec1']].'\',\''.$group_id[$row['survey_group_sec2']].'\')';
-			Database::query($sql2);
-			$question_id[$row['question_id']] = Database::insert_id();
+        if (empty($new_survey_id)) {
+            $params = $survey_data;
+            $params['code'] = self::generate_unique_code($params['code']);
+            $params['c_id'] = $course_id;
+            unset($params['survey_id']);
+            $params['session_id'] = api_get_session_id();
+            $params['title'] = $params['title'] . ' ' . get_lang('Copy');
+            Database::insert($table_survey, $params);
+            $new_survey_id = Database::insert_id();
+
+            // Insert into item_property
+            api_item_property_update(api_get_course_info(), TOOL_SURVEY, $new_survey_id, 'SurveyAdded', api_get_user_id());
+        } else {
+            $new_survey_id = intval($new_survey_id);
+        }
+
+        $sql = "SELECT * FROM $table_survey_question_group
+                WHERE c_id = $course_id AND  survey_id='".$survey_id."'";
+        $res = Database::query($sql);
+        while($row = Database::fetch_array($res, 'ASSOC')) {
+            $params = array(
+                'c_id' =>  $course_id,
+                'name' => $row['name'],
+                'description' => $row['description'],
+                'survey_id' => $new_survey_id
+            );
+            $insertId = Database::insert($table_survey_question_group, $params);
+
+            $group_id[$row['id']] = $insertId;
+        }
+
+        // Get questions
+        $sql = "SELECT * FROM $table_survey_question
+                WHERE c_id = $course_id AND survey_id='".$survey_id."'";
+        $res = Database::query($sql);
+        while ($row = Database::fetch_array($res, 'ASSOC')) {
+            $params = array(
+                'c_id' =>  $course_id,
+                'survey_id' => $new_survey_id,
+                'survey_question' => $row['survey_question'],
+                'survey_question_comment' => $row['survey_question_comment'],
+                'type' => $row['type'],
+                'display' => $row['display'],
+                'sort' => $row['sort'],
+                'shared_question_id' =>  $row['shared_question_id'],
+                'max_value' =>  $row['max_value'],
+                'survey_group_pri' =>  $row['survey_group_pri'],
+                'survey_group_sec1' =>  $row['survey_group_sec1'],
+                'survey_group_sec2' => $row['survey_group_sec2']
+            );
+            $insertId = Database::insert($table_survey_question, $params);
+			$question_id[$row['question_id']] = $insertId;
 		}
 
 		// Get questions options
-		$sql = "SELECT * FROM $table_survey_options WHERE c_id = $course_id AND survey_id='".$parent_survey."'";
+        $sql = "SELECT * FROM $table_survey_options
+                WHERE c_id = $course_id AND survey_id='".$survey_id."'";
+
 		$res = Database::query($sql);
-		while($row = Database::fetch_array($res ,'ASSOC')){
-			$sql3 = 'INSERT INTO '.$table_survey_options.' (c_id, question_id,survey_id,option_text,sort,value) VALUES ('.
-			" $course_id ,    '".$question_id[$row['question_id']]."','".$new_survey_id."','".Database::escape_string($row['option_text'])."','".$row['sort']."','".$row['value']."')";
-			Database::query($sql3);
+		while ($row = Database::fetch_array($res ,'ASSOC')) {
+            $params = array(
+                'c_id' =>  $course_id,
+                'question_id' => $question_id[$row['question_id']],
+                'survey_id' => $new_survey_id,
+                'option_text' => $row['option_text'],
+                'sort' => $row['sort'],
+                'value' => $row['value']
+            );
+            Database::insert($table_survey_options, $params);
 		}
 
 		return true;
@@ -546,7 +622,7 @@ class survey_manager
 	 * @author Eric Marguin <e.marguin@elixir-interactive.com>, Elixir Interactive
 	 * @version October 2007
 	 */
-    public function empty_survey($survey_id)
+    public static function empty_survey($survey_id)
     {
 		// Database table definitions
 		$table_survey_invitation      = Database :: get_course_table(TABLE_SURVEY_INVITATION);
@@ -799,13 +875,13 @@ class survey_manager
 	/**
 	 * This function saves a question in the database.
 	 * This can be either an update of an existing survey or storing a new survey
-	 *
+	 * @param array $survey_data
 	 * @param array $form_content all the information of the form
 	 *
 	 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 	 * @version January 2007
 	 */
-    public function save_question($survey_data, $form_content)
+    public static function save_question($survey_data, $form_content)
     {
 		if (strlen($form_content['question']) > 1) {
 		    // Checks length of the question
@@ -867,14 +943,15 @@ class survey_manager
 					// Some variables defined for survey-test type
 					$additional['column'] = '';
 					$additional['value'] = '';
-
-					if ($_POST['choose'] == 1) {
-						$additional['column'] = ',survey_group_pri';
-						$additional['value'] = ",'".Database::escape_string($_POST['assigned'])."'";
-					} elseif($_POST['choose'] == 2) {
-						$additional['column'] = ',survey_group_sec1, survey_group_sec2';
-						$additional['value'] = ",'".Database::escape_string($_POST['assigned1'])."'".",'".Database::escape_string($_POST['assigned2'])."'";
-					}
+                    if (isset($_POST['choose'])) {
+                        if ($_POST['choose'] == 1) {
+                            $additional['column'] = ',survey_group_pri';
+                            $additional['value'] = ",'" . Database::escape_string($_POST['assigned']) . "'";
+                        } elseif ($_POST['choose'] == 2) {
+                            $additional['column'] = ',survey_group_sec1, survey_group_sec2';
+                            $additional['value'] = ",'" . Database::escape_string($_POST['assigned1']) . "'" . ",'" . Database::escape_string($_POST['assigned2']) . "'";
+                        }
+                    }
 
 					// Adding the question to the survey_question table
 					$sql = "INSERT INTO $tbl_survey_question
@@ -901,13 +978,13 @@ class survey_manager
 
 					$additionalsets = '';
 
-					if ($_POST['choose'] == 1) {
-						$additionalsets = ',survey_group_pri = \''.Database::escape_string($_POST['assigned']).'\', survey_group_sec1 = \'0\', survey_group_sec2 = \'0\' ';
-					}
-					elseif ($_POST['choose'] == 2) {
-						$additionalsets = ',survey_group_pri = \'0\', survey_group_sec1 = \''.Database::escape_string($_POST['assigned1']).'\', survey_group_sec2 = \''.Database::escape_string($_POST['assigned2']).'\' ';
-					}
-
+                    if (isset($_POST['choose'])) {
+                        if ($_POST['choose'] == 1) {
+                            $additionalsets = ',survey_group_pri = \''.Database::escape_string($_POST['assigned']).'\', survey_group_sec1 = \'0\', survey_group_sec2 = \'0\' ';
+                        } elseif ($_POST['choose'] == 2) {
+                            $additionalsets = ',survey_group_pri = \'0\', survey_group_sec1 = \''.Database::escape_string($_POST['assigned1']).'\', survey_group_sec2 = \''.Database::escape_string($_POST['assigned2']).'\' ';
+                        }
+                    }
 					$setadditionals = $additional['set'][1].$additional['set'][2].$additional['set'][3];
 
 					// Adding the question to the survey_question table
@@ -924,11 +1001,17 @@ class survey_manager
 
                 if (!empty($form_content['survey_id'])) {
                     //Updating survey
-                    api_item_property_update(api_get_course_info(), TOOL_SURVEY, $form_content['survey_id'], 'SurveyUpdated', api_get_user_id());
+                    api_item_property_update(
+                        api_get_course_info(),
+                        TOOL_SURVEY,
+                        $form_content['survey_id'],
+                        'SurveyUpdated',
+                        api_get_user_id()
+                    );
                 }
 
 				// Storing the options of the question
-				$message_options = survey_manager::save_question_options($form_content, $survey_data);
+				survey_manager::save_question_options($form_content, $survey_data);
 			} else {
 				$return_message = 'PleasFillAllAnswer';
 			}
@@ -1144,10 +1227,6 @@ class survey_manager
 		Database::query($sql);
 	}
 
-	/**
-	 * SURVEY QUESTION OPTIONS FUNCTIONS
-	 */
-
 	/**
 	 * This function stores the options of the questions in the table
 	 *
@@ -1157,7 +1236,7 @@ class survey_manager
 	 *
 	 * @todo writing the update statement when editing a question
 	 */
-    public function save_question_options($form_content, $survey_data)
+    public static function save_question_options($form_content, $survey_data)
     {
 	    $course_id = api_get_course_int_id();
 		// A percentage question type has options 1 -> 100
@@ -1266,6 +1345,7 @@ class survey_manager
 	 * @param int $survey_id
 	 * @param int $question_id
 	 * @param int $shared
+     *
 	 * @return bool
 	 *
 	 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
@@ -1466,13 +1546,16 @@ class survey_question
 			$tool_name .= ': '.get_lang(api_ucfirst(Security::remove_XSS($_GET['type'])));
 		}
 
+        $formContent = isset($form_content['question']) ? $form_content['question'] : null;
+        $sharedQuestionId = isset($form_content['shared_question_id']) ? $form_content['shared_question_id'] : null;
+
         $url = api_get_self().'?action='.$action.'&type='.Security::remove_XSS($_GET['type']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&question_id='.$questionId;
 
 		$this->html .= '<form class="form-horizontal" id="question_form" name="question_form" method="post" action="'.$url.'">';
         $this->html .= '<legend>'.$tool_name.'</legend>';
 		$this->html .= '		<input type="hidden" name="survey_id" id="survey_id" value="'.Security::remove_XSS($_GET['survey_id']).'"/>';
 		$this->html .= '		<input type="hidden" name="question_id" id="question_id" value="'.$questionId.'"/>';
-		$this->html .= '		<input type="hidden" name="shared_question_id" id="shared_question_id" value="'.Security::remove_XSS($form_content['shared_question_id']).'"/>';
+		$this->html .= '		<input type="hidden" name="shared_question_id" id="shared_question_id" value="'.Security::remove_XSS($sharedQuestionId).'"/>';
 		$this->html .= '		<input type="hidden" name="type" id="type" value="'.Security::remove_XSS($_GET['type']).'"/>';
 
 		// question field
@@ -1481,7 +1564,7 @@ class survey_question
 		$this->html .= '			<span class="form_required">*</span> '.get_lang('Question');
 		$this->html .= '		</label>';
 		$this->html .= '		<div class="controls">';
-		$this->html .= api_return_html_area('question', Security::remove_XSS(stripslashes($form_content['question']), STUDENT), '', '', null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '120'));
+		$this->html .= api_return_html_area('question', Security::remove_XSS(stripslashes($formContent), STUDENT), '', '', null, array('ToolbarSet' => 'Survey', 'Width' => '100%', 'Height' => '120'));
 		$this->html .= '		</div>';
 		$this->html .= '	</div>';
 
@@ -1489,7 +1572,7 @@ class survey_question
 			$table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
 			$sql = 'SELECT id,name FROM '.$table_survey_question_group.' WHERE survey_id = '.(int)$_GET['survey_id'].' ORDER BY name';
 			$rs = Database::query($sql);
-
+            $glist = null;
 			while ($row = Database::fetch_array($rs, 'NUM')) {
 				$glist .= '<option value="'.$row[0].'" >'.$row[1].'</option>';
 			}
@@ -1572,7 +1655,7 @@ class survey_question
 		global $config;
 
 		// Moving an answer up
-		if ($_POST['move_up']) {
+		if (isset($_POST['move_up']) && $_POST['move_up']) {
 			foreach ($_POST['move_up'] as $key => & $value) {
 				$id1		= $key;
 				$content1 	= $form_content['answers'][$id1];
@@ -1584,7 +1667,7 @@ class survey_question
 		}
 
 		// Moving an answer down
-		if ($_POST['move_down']) {
+		if (isset($_POST['move_down']) && $_POST['move_down']) {
 			foreach ($_POST['move_down'] as $key => & $value) {
 				$id1		= $key;
 				$content1 	= $form_content['answers'][$id1];
@@ -1719,7 +1802,7 @@ class ch_yesno extends survey_question
 		}
 		$this->html .= '/>'.get_lang('Horizontal').'<br />';
 		$this->html .= '		  <input name="horizontalvertical" type="radio" value="vertical" ';
-		if ($form_content['horizontalvertical'] == 'vertical') {
+		if (isset($form_content['horizontalvertical']) && $form_content['horizontalvertical'] == 'vertical') {
 			$this->html .= 'checked="checked"';
 		}
 		$this->html .= ' />'.get_lang('Vertical').'';
@@ -1816,7 +1899,7 @@ class ch_multiplechoice extends survey_question
 		}
 		$this->html .= '/>'.get_lang('Horizontal').'</label><br />';
 		$this->html .= '		  <input name="horizontalvertical" type="radio" value="vertical" ';
-		if ($form_content['horizontalvertical'] == 'vertical') {
+		if (isset($form_content['horizontalvertical']) && $form_content['horizontalvertical'] == 'vertical') {
 			$this->html .= 'checked="checked"';
 		}
 		$this->html .= ' />'.get_lang('Vertical').'</label>';
@@ -1902,7 +1985,7 @@ class ch_personality extends survey_question
 		$this->html .= '/>'.get_lang('Horizontal').'</label><br />';
 		$this->html .= '		  <input name="horizontalvertical" type="radio" value="vertical" ';
 
-		if ($form_content['horizontalvertical'] == 'vertical') {
+		if (isset($form_content['horizontalvertical']) && $form_content['horizontalvertical'] == 'vertical') {
 			$this->html .= 'checked="checked"';
 		}
 
@@ -1997,7 +2080,7 @@ class ch_multipleresponse extends survey_question
 		}
 		$this->html .= '/>'.get_lang('Horizontal').'</label><br />';
 		$this->html .= '		  <input name="horizontalvertical" type="radio" value="vertical" ';
-		if ($form_content['horizontalvertical'] == 'vertical') {
+		if (isset($form_content['horizontalvertical']) && $form_content['horizontalvertical'] == 'vertical') {
 			$this->html .= 'checked="checked"';
 		}
 		$this->html .= ' />'.get_lang('Vertical').'</label>';
@@ -4455,7 +4538,9 @@ class SurveyUtil
                     api_get_path(WEB_CODE_PATH).'survey/generate_link.php?survey_id='.$survey_id.'&'.api_get_cidreq()
                 );
             }
-			$return .= ' <a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&amp;action=empty&amp;survey_id='.$survey_id.'" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang("EmptySurvey").'?')).'\')) return false;">'.Display::return_icon('clean.png', get_lang('EmptySurvey'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
+            $return .= Display::url(Display::return_icon('copy.png', get_lang('DuplicateSurvey'), '', ICON_SIZE_SMALL), 'survey_list.php?action=copy_survey&survey_id='.$survey_id.'&'.api_get_cidreq());
+
+            $return .= ' <a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&amp;action=empty&amp;survey_id='.$survey_id.'" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang("EmptySurvey").'?')).'\')) return false;">'.Display::return_icon('clean.png', get_lang('EmptySurvey'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
 		}
 		$return .= '<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_SMALL).'</a>&nbsp;';
 		$return .= '<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_SMALL).'</a>&nbsp;';
@@ -4719,10 +4804,12 @@ class SurveyUtil
 	 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 	 * @version April 2007
 	 */
-	function survey_list_user($user_id)
+	public static function survey_list_user($user_id)
     {
         $_course = api_get_course_info();
         $course_id = api_get_course_int_id();
+        $user_id = intval($user_id);
+        $sessionId = api_get_session_id();
 
 		// Database table definitions
 		$table_survey_question   = Database :: get_course_table(TABLE_SURVEY_QUESTION);
@@ -4745,7 +4832,7 @@ class SurveyUtil
 					WHERE
 					    c_id = '.$course_id.' AND
 					    question_id='.Database::escape_string($all_question_id[$i]['question_id']).' AND
-					    user = '.api_get_user_id();
+					    user = '.$user_id;
 			$result = Database::query($sql);
 			while ($row = Database::fetch_array($result, 'ASSOC')) {
 				if ($row['count'] == 0) {
@@ -4770,6 +4857,7 @@ class SurveyUtil
 				survey.avail_from 		<= '".date('Y-m-d H:i:s')."' AND
 				survey.avail_till 		>= '".date('Y-m-d H:i:s')."' AND
 				survey.c_id 			= $course_id AND
+				survey.session_id = $sessionId AND
 				survey_invitation.c_id = $course_id
 				";
 		$result = Database::query($sql);
@@ -4777,7 +4865,11 @@ class SurveyUtil
 		while ($row = Database::fetch_array($result, 'ASSOC')) {
 			// Get the user into survey answer table (user or anonymus)
 			$sql = "SELECT user FROM $table_survey_answer
-					WHERE c_id = $course_id AND survey_id = (SELECT survey_id from $table_survey WHERE code ='".Database::escape_string($row['code'])." AND c_id = $course_id')";
+					WHERE c_id = $course_id AND survey_id = (
+					    SELECT survey_id from $table_survey
+					    WHERE code ='".Database::escape_string($row['code'])." AND c_id = $course_id'
+                    )
+            ";
 			$result_answer = Database::query($sql);
 			$row_answer = Database::fetch_array($result_answer,'ASSOC');
 			echo '<tr>';

+ 9 - 11
main/survey/survey.php

@@ -42,8 +42,8 @@ $table_course 					= Database :: get_main_table(TABLE_MAIN_COURSE);
 $table_user 					= Database :: get_main_table(TABLE_MAIN_USER);
 
 $survey_id = intval($_GET['survey_id']);
-
 $course_id = api_get_course_int_id();
+$action = isset($_GET['action']) ? $_GET['action'] : null;
 
 // Breadcrumbs
 $interbreadcrumb[] = array ('url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php', 'name' => get_lang('SurveyList'));
@@ -69,12 +69,9 @@ if (api_strlen(strip_tags($survey_data['title'])) > 40) {
 	$tool_name .= '...';
 }
 
-if ($is_survey_type_1 &&
-    isset($_GET['action']) &&
-    ($_GET['action'] == 'addgroup' || $_GET['action'] == 'deletegroup')
-) {
+if ($is_survey_type_1 && ($action == 'addgroup' || $action == 'deletegroup')) {
 	$_POST['name'] = trim($_POST['name']);
-	if ($_GET['action'] == 'addgroup') {
+	if ($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']).'\'');
@@ -87,7 +84,7 @@ if ($is_survey_type_1 &&
 		}
 	}
 
-	if ($_GET['action'] == 'deletegroup'){
+	if ($action == 'deletegroup') {
 		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';
 	}
@@ -100,20 +97,21 @@ if ($is_survey_type_1 &&
 Display::display_header($tool_name, 'Survey');
 
 // Action handling
-$my_action_survey		= isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null;
+$my_action_survey = Security::remove_XSS($action);
 $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    = isset($_GET['message']) ? Security::remove_XSS($_GET['message']) : null;
 
-if (isset($_GET['action'])) {
-	if (($_GET['action'] == 'moveup' || $_GET['action'] == 'movedown') && isset($_GET['question_id'])) {
+if (isset($action)) {
+	if (($action == 'moveup' || $action == 'movedown') && isset($_GET['question_id'])) {
 		survey_manager::move_survey_question($my_action_survey,$my_question_id_survey,$my_survey_id_survey);
 		Display::display_confirmation_message(get_lang('SurveyQuestionMoved'));
 	}
-	if ($_GET['action'] == 'delete' AND is_numeric($_GET['question_id'])) {
+	if ($action == 'delete' AND is_numeric($_GET['question_id'])) {
 		survey_manager::delete_survey_question($my_survey_id_survey, $my_question_id_survey, $survey_data['is_shared']);
 	}
 }
+
 if (isset($_GET['message'])) {
 	// We have created the survey or updated the survey
 	if (in_array($_GET['message'], array('SurveyUpdatedSuccesfully','SurveyCreatedSuccesfully'))) {

+ 25 - 9
main/survey/survey_list.php

@@ -13,7 +13,8 @@
 
 // Language file that needs to be included
 $language_file = 'survey';
-if (!isset ($_GET['cidReq'])){
+
+if (!isset($_GET['cidReq'])) {
     $_GET['cidReq'] = 'none'; // Prevent sql errors
     $cidReset = true;
 }
@@ -21,9 +22,10 @@ if (!isset ($_GET['cidReq'])){
 // Including the global initialization file
 require_once '../inc/global.inc.php';
 $this_section = SECTION_COURSES;
-$current_course_tool  = TOOL_SURVEY;
+$current_course_tool = TOOL_SURVEY;
 
 api_protect_course_script(true);
+$action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null;
 
 // Including additional libraries
 require_once 'survey.lib.php';
@@ -31,10 +33,14 @@ require_once 'survey.lib.php';
 // Tracking
 event_access_tool(TOOL_SURVEY);
 
-/** @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)) { // Coach can see this
+/** @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)) {
+    // Coach can see this
     Display::display_header(get_lang('SurveyList'));
-    SurveyUtil::survey_list_user($_user['user_id']);
+    SurveyUtil::survey_list_user(api_get_user_id());
     Display::display_footer();
     exit;
 }
@@ -55,6 +61,15 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
     $tool_name = get_lang('SurveyList');
 }
 
+if ($action == 'copy_survey') {
+    if (api_is_allowed_to_edit()) {
+        survey_manager::copy_survey($_GET['survey_id']);
+        $message = get_lang('Copied');
+        header('Location: ' . api_get_path(WEB_CODE_PATH) . 'survey/survey_list.php?' . api_get_cidreq());
+        exit;
+    }
+}
+
 // Header
 Display::display_header($tool_name, 'Survey');
 
@@ -62,11 +77,11 @@ Display::display_header($tool_name, 'Survey');
 Display::display_introduction_section('survey', 'left');
 
 // Action handling: searching
-if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
+if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
     SurveyUtil::display_survey_search_form();
 }
 // Action handling: deleting a survey
-if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['survey_id'])) {
+if ($action == 'delete' && isset($_GET['survey_id'])) {
     // Getting the information of the survey (used for when the survey is shared)
     $survey_data = survey_manager::get_survey($_GET['survey_id']);
     if (api_is_course_coach() && intval($_SESSION['id_session']) != $survey_data['session_id']) {
@@ -79,7 +94,8 @@ if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['survey
         survey_manager::delete_survey($survey_data['survey_share'], true);
     }
 
-    $return = survey_manager :: delete_survey($_GET['survey_id']);
+    $return = survey_manager::delete_survey($_GET['survey_id']);
+
     if ($return) {
         Display::display_confirmation_message(get_lang('SurveyDeleted'), false);
     } else {
@@ -87,7 +103,7 @@ if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['survey
     }
 }
 
-if (isset($_GET['action']) && $_GET['action'] == 'empty') {
+if ($action == 'empty') {
     $mysession = api_get_session_id();
     if ($mysession != 0) {
         if (!((api_is_course_coach() || api_is_platform_admin()) &&