Juan Carlos Raña 15 years ago
parent
commit
0fa2d2dd6a
100 changed files with 4232 additions and 4380 deletions
  1. 7 1
      archive/.htaccess
  2. 72 72
      index.php
  3. 20 20
      main/admin/access_url_add_courses_to_url.php
  4. 25 25
      main/admin/access_url_add_sessions_to_url.php
  5. 22 22
      main/admin/access_url_add_users_to_url.php
  6. 26 26
      main/admin/access_url_edit.php
  7. 54 54
      main/admin/access_url_edit_courses_to_url.php
  8. 53 53
      main/admin/access_url_edit_sessions_to_url.php
  9. 50 50
      main/admin/access_url_edit_users_to_url.php
  10. 47 47
      main/admin/access_urls.php
  11. 84 84
      main/admin/add_courses_to_session.php
  12. 118 118
      main/admin/add_users_to_session.php
  13. 135 135
      main/admin/calendar.lib.php
  14. 8 8
      main/admin/calendar.php
  15. 7 7
      main/admin/calendar_ical_export.php
  16. 1 1
      main/admin/calendar_view_print.php
  17. 18 23
      main/admin/class_add.php
  18. 18 24
      main/admin/class_edit.php
  19. 48 59
      main/admin/class_import.php
  20. 29 43
      main/admin/class_information.php
  21. 49 54
      main/admin/class_list.php
  22. 89 93
      main/admin/class_user_import.php
  23. 69 69
      main/admin/configure_extensions.php
  24. 46 46
      main/admin/configure_homepage.php
  25. 7 7
      main/admin/course_add.php
  26. 27 27
      main/admin/course_category.php
  27. 12 12
      main/admin/course_create_content.php
  28. 4 4
      main/admin/course_edit.php
  29. 59 79
      main/admin/course_import.php
  30. 4 4
      main/admin/course_information.php
  31. 28 28
      main/admin/course_list.php
  32. 68 89
      main/admin/course_user_import.php
  33. 1 1
      main/admin/course_user_list.php
  34. 69 69
      main/admin/course_virtual.php
  35. 19 19
      main/admin/index.php
  36. 51 51
      main/admin/languages.php
  37. 1 1
      main/admin/ldap_form_add_users_group.php
  38. 8 8
      main/admin/ldap_import_students.php
  39. 5 5
      main/admin/ldap_import_students_to_session.php
  40. 3 3
      main/admin/ldap_synchro.php
  41. 6 6
      main/admin/ldap_users_list.php
  42. 1 1
      main/admin/ldap_users_synchro.php
  43. 41 41
      main/admin/legal_add.php
  44. 6 6
      main/admin/legal_list.php
  45. 6 6
      main/admin/resume_session.php
  46. 27 27
      main/admin/session_add.php
  47. 3 3
      main/admin/session_course_list.php
  48. 2 2
      main/admin/session_course_user_list.php
  49. 10 10
      main/admin/session_edit.php
  50. 20 20
      main/admin/session_export.php
  51. 910 896
      main/admin/session_import.php
  52. 53 52
      main/admin/session_list.php
  53. 163 163
      main/admin/settings.php
  54. 3 3
      main/admin/statistics.php
  55. 2 2
      main/admin/statistics/index.php
  56. 41 41
      main/admin/statistics/statistics.lib.php
  57. 1 1
      main/admin/style_preview.php
  58. 37 37
      main/admin/sub_language.class.php
  59. 78 78
      main/admin/sub_language.php
  60. 41 41
      main/admin/sub_language_add.php
  61. 5 5
      main/admin/sub_language_ajax.inc.php
  62. 7 7
      main/admin/subscribe_class2course.php
  63. 10 7
      main/admin/subscribe_user2class.php
  64. 65 64
      main/admin/subscribe_user2course.php
  65. 6 6
      main/admin/system_announcements.php
  66. 183 228
      main/admin/user_add.php
  67. 219 283
      main/admin/user_edit.php
  68. 29 29
      main/admin/user_export.php
  69. 41 41
      main/admin/user_fields.php
  70. 35 35
      main/admin/user_fields_add.php
  71. 27 27
      main/admin/user_fields_options.php
  72. 193 188
      main/admin/user_import.php
  73. 26 26
      main/admin/user_information.php
  74. 61 61
      main/admin/user_list.php
  75. 2 2
      main/auth/inscription.php
  76. 253 282
      main/auth/profile.php
  77. 15 3
      main/course_home/activity.php
  78. 12 2
      main/course_home/course_home.php
  79. 13 14
      main/course_info/download.php
  80. 3 1
      main/coursecopy/classes/Announcement.class.php
  81. 5 3
      main/coursecopy/classes/Course.class.php
  82. 8 8
      main/coursecopy/classes/CourseArchiver.class.php
  83. 20 22
      main/coursecopy/classes/CourseBuilder.class.php
  84. 3 1
      main/coursecopy/classes/CourseDescription.class.php
  85. 3 6
      main/coursecopy/classes/CourseRecycler.class.php
  86. 17 21
      main/coursecopy/classes/CourseRestorer.class.php
  87. 3 1
      main/coursecopy/classes/CourseSelectForm.class.php
  88. 4 1
      main/coursecopy/classes/Document.class.php
  89. 20 18
      main/coursecopy/classes/DummyCourseCreator.class.php
  90. 3 1
      main/coursecopy/classes/Event.class.php
  91. 3 1
      main/coursecopy/classes/Forum.class.php
  92. 3 1
      main/coursecopy/classes/ForumCategory.class.php
  93. 3 1
      main/coursecopy/classes/ForumPost.class.php
  94. 3 1
      main/coursecopy/classes/ForumTopic.class.php
  95. 3 1
      main/coursecopy/classes/Glossary.class.php
  96. 3 1
      main/coursecopy/classes/Link.class.php
  97. 3 1
      main/coursecopy/classes/LinkCategory.class.php
  98. 3 1
      main/coursecopy/classes/Quiz.class.php
  99. 3 1
      main/coursecopy/classes/QuizQuestion.class.php
  100. 2 1
      main/coursecopy/classes/ScormDocument.class.php

+ 7 - 1
archive/.htaccess

@@ -1,2 +1,8 @@
 order deny,allow
-deny from all
+deny from all
+
+# pChart generated files should be allowed
+<FilesMatch "^[0-9a-f]+$">
+	order allow,deny
+	allow from all
+</FilesMatch>

+ 72 - 72
index.php

@@ -1,5 +1,5 @@
 <?php // $Id: index.php 22368 2009-07-24 23:25:57Z iflorespaz $
- 
+
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
@@ -181,15 +181,15 @@ if (!api_get_user_id()) {
 
 $home= 'home/';
 if ($_configuration['multiple_access_urls']==true) {
-	$access_url_id = api_get_current_access_url_id();										 
-	if ($access_url_id != -1){						
+	$access_url_id = api_get_current_access_url_id();
+	if ($access_url_id != -1){
 		$url_info = api_get_access_url($access_url_id);
-		// "http://" and the final "/" replaced						
-		$url = substr($url_info['url'],7,strlen($url_info['url'])-8);						
+		// "http://" and the final "/" replaced
+		$url = substr($url_info['url'],7,strlen($url_info['url'])-8);
 		$clean_url = replace_dangerous_char($url);
 		$clean_url = str_replace('/','-',$clean_url);
 		$clean_url = $clean_url.'/';
-		$home_old  = 'home/'; 
+		$home_old  = 'home/';
 		$home= 'home/'.$clean_url;
 	}
 }
@@ -201,7 +201,7 @@ if (!empty ($_GET['include']) && preg_match('/^[a-zA-Z0-9_-]*\.html$/',$_GET['in
 	include ('./'.$home.$_GET['include']);
 	$page_included = true;
 } else {
-	
+
 	if (!empty($_SESSION['user_language_choice'])) {
 		$user_selected_language=$_SESSION['user_language_choice'];
 	} elseif(!empty($_SESSION['_user']['language'])) {
@@ -209,13 +209,13 @@ if (!empty ($_GET['include']) && preg_match('/^[a-zA-Z0-9_-]*\.html$/',$_GET['in
 	} else {
 		$user_selected_language=api_get_setting('platformLanguage');
 	}
-	
+
 	if(!file_exists($home.'home_news_'.$user_selected_language.'.html')) {
 		if (file_exists($home.'home_top.html'))
 			$home_top_temp=file($home.'home_top.html');
 		else {
 			$home_top_temp=file($home_old.'home_top.html');
-		} 
+		}
 		$home_top_temp=implode('',$home_top_temp);
 		$open=str_replace('{rel_path}',api_get_path(REL_PATH),$home_top_temp);
 		echo $open;
@@ -268,7 +268,7 @@ Display :: display_footer();
  *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  */
-function logout() 
+function logout()
 {
 	global $_configuration, $extAuthSource;
 	// variable initialisation
@@ -288,19 +288,19 @@ function logout()
 	if (Database::num_rows($q_last_connection)>0) {
 		$i_id_last_connection=Database::result($q_last_connection,0,"login_id");
 	}
-	
+
 	if (!isset($_SESSION['login_as'])) {
 		$current_date=date('Y-m-d H:i:s',time());
 		$s_sql_update_logout_date="UPDATE $tbl_track_login SET logout_date='".$current_date."' WHERE login_id='$i_id_last_connection'";
 		api_sql_query($s_sql_update_logout_date);
 	}
 	LoginDelete($uid, $_configuration['statistics_database']); //from inc/lib/online.inc.php - removes the "online" status
-	
+
 	//the following code enables the use of an external logout function.
 	//example: define a $extAuthSource['ldap']['logout']="file.php" in configuration.php
-	// then a function called ldap_logout() inside that file 
-	// (using *authent_name*_logout as the function name) and the following code 
-	// will find and execute it 
+	// then a function called ldap_logout() inside that file
+	// (using *authent_name*_logout as the function name) and the following code
+	// will find and execute it
 	$uinfo = api_get_user_info($uid);
 	if (($uinfo['auth_source'] != PLATFORM_AUTH_SOURCE) && is_array($extAuthSource)) {
 		if (is_array($extAuthSource[$uinfo['auth_source']])) {
@@ -328,14 +328,14 @@ function logout()
  */
 function category_has_open_courses($category) {
 	global $setting_show_also_closed_courses;
-	
+
 	$user_identified = (api_get_user_id()>0 && !api_is_anonymous());
 	$main_course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
 	$sql_query = "SELECT * FROM $main_course_table WHERE category_code='$category'";
 	$sql_result = api_sql_query($sql_query, __FILE__, __LINE__);
 	while ($course = Database::fetch_array($sql_result)) {
 		if ($setting_show_also_closed_courses == false) {
-			if ((api_get_user_id()>0 
+			if ((api_get_user_id()>0
 				and $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
 				or ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)) {
 				return true; //at least one open course
@@ -343,7 +343,7 @@ function category_has_open_courses($category) {
 		} else  {
 			if(isset($course['visibility'])){
 				return true; //at least one course (does not matter weither it's open or not because $setting_show_also_closed_courses = true
-			}			
+			}
 		}
 	}
 	return false;
@@ -403,26 +403,26 @@ function display_anonymous_right_menu() {
 
 		$show_menu=false;
 		$show_create_link=false;
-		$show_course_link=false;	
-		
+		$show_course_link=false;
+
 		$display_add_course_link = api_is_allowed_to_create_course() && ($_SESSION["studentview"] != "studentenview");
-		
+
 		if ($display_add_course_link) {
 			//display_create_course_link();
 			$show_menu=true;
-			$show_create_link=true;			
+			$show_create_link=true;
 		}
-				
+
 		if (api_is_platform_admin() || api_is_course_admin() || api_is_allowed_to_create_course()) {
 				$show_menu=true;
-				$show_course_link=true;		
-		} else {	
-			if (api_get_setting('allow_students_to_browse_courses')=='true') {			
+				$show_course_link=true;
+		} else {
+			if (api_get_setting('allow_students_to_browse_courses')=='true') {
 				$show_menu=true;
-				$show_course_link=true;				
-			}	
+				$show_course_link=true;
+			}
 		}
-				
+
 		if ($show_menu){
 			echo "<div class=\"menusection\">";
 			echo "<span class=\"menusectioncaption\">".get_lang("MenuUser")."</span>";
@@ -430,11 +430,11 @@ function display_anonymous_right_menu() {
 			if ($show_create_link)
 				display_create_course_link();
 			if ($show_course_link)
-				display_edit_course_list_links();			
+				display_edit_course_list_links();
 			echo "</ul>";
-			echo "</div>";			
+			echo "</div>";
 		}
-		
+
 		if (!empty($menu_navigation)) {
 			echo "<div class=\"menusection\">";
 			echo "<span class=\"menusectioncaption\">".get_lang("MainNavigation")."</span>";
@@ -450,16 +450,16 @@ function display_anonymous_right_menu() {
 			echo '</div>';
 		}
 	}
-	
+
 	// help section
 	/*** hide right menu "general" and other parts on anonymous right menu  *****/
-	 
+
 	$user_selected_language = api_get_interface_language();
 	global $home, $home_old;
 	if (!isset ($user_selected_language))
 	{
 		$user_selected_language = $platformLanguage;
-	} 
+	}
 
 	if (!file_exists($home.'home_menu_'.$user_selected_language.'.html') && file_exists($home.'home_menu.html') && file_get_contents($home.'home_menu.html')!='')
 	{
@@ -475,22 +475,22 @@ function display_anonymous_right_menu() {
 	}
 
 	elseif(file_exists($home.'home_menu_'.$user_selected_language.'.html') && file_get_contents($home.'home_menu_'.$user_selected_language.'.html')!='')
-	{	
+	{
 		echo "<div class=\"menusection\">", "<span class=\"menusectioncaption\">".get_lang("MenuGeneral")."</span>";
 	 	echo "<ul class=\"menulist\">";
 		include($home.'home_menu_'.$user_selected_language.'.html');
 		echo '</ul>';
 		echo '</div>';
-	}	
-	
+	}
+
 	if ($_user['user_id'] && api_number_of_plugins('campushomepage_menu') > 0) {
 		echo '<div class="note" style="background: none">';
 		api_plugin('campushomepage_menu');
 		echo '</div>';
 	}
-			
+
 	// includes for any files to be displayed below anonymous right menu
-	
+
 	if (!file_exists($home.'home_notice_'.$user_selected_language.'.html') && file_exists($home.'home_notice.html') && file_get_contents($home.'home_notice.html')!='') {
 		echo '<div class="note">';
 		if (file_exists($home.'home_notice.html'))
@@ -501,9 +501,9 @@ function display_anonymous_right_menu() {
 		echo '</div>';
 	} elseif(file_exists($home.'home_notice_'.$user_selected_language.'.html') && file_get_contents($home.'home_notice_'.$user_selected_language.'.html')!='') {
 		echo '<div class="note">';
-		include($home.'home_notice_'.$user_selected_language.'.html'); 
+		include($home.'home_notice_'.$user_selected_language.'.html');
 		echo '</div>';
-	}	
+	}
 }
 
 /**
@@ -548,7 +548,7 @@ function handle_login_failed() {
 *	Adds a form to let users login
 *	@version 1.1
 */
-function display_login_form() 
+function display_login_form()
 {
 	$form = new FormValidator('formLogin');
 	$form->addElement('text','login',get_lang('UserName'),array('size'=>17));
@@ -578,8 +578,8 @@ function display_lost_password_info() {
 */
 function display_anonymous_course_list() {
 	$ctok = $_SESSION['sec_token'];
-	$stok = Security::get_token();	
-	
+	$stok = Security::get_token();
+
 	//init
 	$user_identified = (api_get_user_id()>0 && !api_is_anonymous());
 	$web_course_path = api_get_path(WEB_COURSE_PATH);
@@ -596,19 +596,19 @@ function display_anonymous_course_list() {
 	$sql_get_course_list = "SELECT * FROM $main_course_table cours
 								WHERE category_code = '".Database::escape_string($_GET["category"])."'
 								ORDER BY title, UPPER(visual_code)";
-								
-	//showing only the courses of the current access_url_id								
+
+	//showing only the courses of the current access_url_id
 	global $_configuration;
 	if ($_configuration['multiple_access_urls']==true) {
 		$url_access_id = api_get_current_access_url_id();
 		if ($url_access_id !=-1) {
-			$tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);			
-			$sql_get_course_list="SELECT * FROM $main_course_table as course INNER JOIN $tbl_url_rel_course as url_rel_course 
+			$tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+			$sql_get_course_list="SELECT * FROM $main_course_table as course INNER JOIN $tbl_url_rel_course as url_rel_course
 					ON (url_rel_course.course_code=course.code)
 					WHERE access_url_id = $url_access_id AND category_code = '".Database::escape_string($_GET["category"])."' ORDER BY title, UPPER(visual_code)";
 		}
 	}
-	
+
 	//removed: AND cours.visibility='".COURSE_VISIBILITY_OPEN_WORLD."'
 	$sql_result_courses = api_sql_query($sql_get_course_list, __FILE__, __LINE__);
 
@@ -622,14 +622,14 @@ function display_anonymous_course_list() {
 		if ($setting_show_also_closed_courses) {
 			$platform_visible_courses = '';
 		} else  {
-			$platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' OR t3.visibility='".COURSE_VISIBILITY_OPEN_PLATFORM."' )";	
+			$platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' OR t3.visibility='".COURSE_VISIBILITY_OPEN_PLATFORM."' )";
 		}
 	} else {
 		if ($setting_show_also_closed_courses) {
 			$platform_visible_courses = '';
 		} else  {
-			$platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' )";	
-		}				
+			$platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' )";
+		}
 	}
 	$sqlGetSubCatList = "
 				SELECT t1.name,t1.code,t1.parent_id,t1.children_count,COUNT(DISTINCT t3.code) AS nbCourse
@@ -638,26 +638,26 @@ function display_anonymous_course_list() {
 				LEFT JOIN $main_course_table t3 ON (t3.category_code=t1.code $platform_visible_courses)
 				WHERE t1.parent_id ". (empty ($category) ? "IS NULL" : "='$category'")."
 				GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count ORDER BY t1.tree_pos, t1.name";
-				
-					
-	//showing only the category of courses of the current access_url_id								
+
+
+	//showing only the category of courses of the current access_url_id
 	global $_configuration;
 	if ($_configuration['multiple_access_urls']==true) {
 		$url_access_id = api_get_current_access_url_id();
 		if ($url_access_id !=-1) {
-			$tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);	
+			$tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 			$sqlGetSubCatList = "
 				SELECT t1.name,t1.code,t1.parent_id,t1.children_count,COUNT(DISTINCT t3.code) AS nbCourse
 				FROM $main_category_table t1
 				LEFT JOIN $main_category_table t2 ON t1.code=t2.parent_id
 				LEFT JOIN $main_course_table t3 ON (t3.category_code=t1.code $platform_visible_courses)
-				INNER JOIN $tbl_url_rel_course as url_rel_course 
+				INNER JOIN $tbl_url_rel_course as url_rel_course
 					ON (url_rel_course.course_code=t3.code)
-				WHERE access_url_id = $url_access_id AND t1.parent_id ". (empty ($category) ? "IS NULL" : "='$category'")."				
+				WHERE access_url_id = $url_access_id AND t1.parent_id ". (empty ($category) ? "IS NULL" : "='$category'")."
 				GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count ORDER BY t1.tree_pos, t1.name";
 		}
 	}
-	
+
 	$resCats = api_sql_query($sqlGetSubCatList, __FILE__, __LINE__);
 	$thereIsSubCat = false;
 	if (Database::num_rows($resCats) > 0) {
@@ -724,16 +724,16 @@ function display_anonymous_course_list() {
 			$courses_list_string .= "<hr size=\"1\" noshade=\"noshade\">\n";
 		}
 		$courses_list_string .= "<h4 style=\"margin-top: 0px;\">".get_lang("CourseList")."</h4>\n"."<ul>\n";
-		
+
 		if (api_get_user_id()) {
 			$courses_of_user = get_courses_of_user(api_get_user_id());
 		}
-		
+
 		foreach ($course_list AS $course) {
 			// $setting_show_also_closed_courses
-			
+
 			if ($setting_show_also_closed_courses==false) {
-				// if we do not show the closed courses 
+				// if we do not show the closed courses
 				// we only show the courses that are open to the world (to everybody)
 				// and the courses that are open to the platform (if the current user is a registered user
 				if( ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) OR ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)) {
@@ -748,7 +748,7 @@ function display_anonymous_course_list() {
 				}
 				if (api_get_setting("display_teacher_in_courselist") == "true") {
 					$courses_list_string .= $course['tutor_name'];
-				}				
+				}
 					if (api_get_setting('show_different_course_language') == 'true' && $course['course_language'] <> api_get_setting('platformLanguage')) {
 						$courses_list_string .= ' - '.$course['course_language'];
 					}
@@ -762,21 +762,21 @@ function display_anonymous_course_list() {
 			// 3. the user is logged in and the user is subscribed to the course and the course visibility is not COURSE_VISIBILITY_CLOSED
 			// 4. the user is logged in and the user is course admin of te course (regardless of the course visibility setting)
 			// 5. the user is the platform admin api_is_platform_admin()
-			// 
+			//
 			else {
 				$courses_shown++;
 				$courses_list_string .= "<li>\n";
 					if ( $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
-							OR ($user_identified AND $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) 
-							OR ($user_identified AND key_exists($course['code'],$courses_of_user) AND $course['visibility'] <> COURSE_VISIBILITY_CLOSED) 
+							OR ($user_identified AND $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
+							OR ($user_identified AND key_exists($course['code'],$courses_of_user) AND $course['visibility'] <> COURSE_VISIBILITY_CLOSED)
 							OR $courses_of_user[$course['code']]['status'] == '1'
 							OR api_is_platform_admin()) {
 						$courses_list_string .= "<a href=\"".$web_course_path.$course['directory']."/\">";
 					}
 					$courses_list_string .= $course['title'];
 					if ( $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
-							OR ($user_identified AND $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) 
-							OR ($user_identified AND key_exists($course['code'],$courses_of_user) AND $course['visibility'] <> COURSE_VISIBILITY_CLOSED) 
+							OR ($user_identified AND $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
+							OR ($user_identified AND key_exists($course['code'],$courses_of_user) AND $course['visibility'] <> COURSE_VISIBILITY_CLOSED)
 							OR $courses_of_user[$course['code']]['status'] == '1'
 							OR api_is_platform_admin()) {
 						$courses_list_string .="</a><br />";
@@ -790,14 +790,14 @@ function display_anonymous_course_list() {
 					if (api_get_setting("display_teacher_in_courselist") == "true")
 					{
 						$courses_list_string .= $course['tutor_name'];
-					}				
+					}
 				if (api_get_setting('show_different_course_language') == 'true' && $course['course_language'] <> api_get_setting('platformLanguage')) {
 					$courses_list_string .= ' - '.$course['course_language'];
 				}
 					if (api_get_setting('show_different_course_language') == 'true' && $course['course_language'] <> api_get_setting('platformLanguage')) {
 						$courses_list_string .= ' - '.$course['course_language'];
 					}
-					// We display a subscription link if 
+					// We display a subscription link if
 					// 1. it is allowed to register for the course and if the course is not already in the courselist of the user and if the user is identiefied
 					// 2
 					if ($user_identified AND !key_exists($course['code'],$courses_of_user)) {

+ 20 - 20
main/admin/access_url_add_courses_to_url.php

@@ -2,31 +2,31 @@
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
-	
+
 	Copyright (c) 2009 Dokeos SPRL
 	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
 
 	For a full list of contributors, see "credits.txt".
 	The full license can be read in "license.txt".
-	
+
 	This program is free software; you can redistribute it and/or
 	modify it under the terms of the GNU General Public License
 	as published by the Free Software Foundation; either version 2
 	of the License, or (at your option) any later version.
-	
+
 	See the GNU General Public License for more details.
-	
+
 	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	This script allows platform admins to add users to urls.
 *	It displays a list of users and a list of courses;
 *	you can select multiple users and courses and then click on
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 
 // name of the language file that needs to be included
@@ -39,7 +39,7 @@ require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
 api_protect_admin_script();
 if (!$_configuration['multiple_access_urls'])
 	header('Location: index.php');
-	
+
 /*
 -----------------------------------------------------------
 	Global constants and variables
@@ -75,9 +75,9 @@ $interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('Mult
 Display :: display_header($tool_name);
 
 echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">		
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_courses_to_url.php">'.Display::return_icon('edit.gif',get_lang('AddUserToURL'),'').get_lang('EditCoursesToURL').'</a>												
-	  </div><br />';		  
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_courses_to_url.php">'.Display::return_icon('edit.gif',get_lang('AddUserToURL'),'').get_lang('EditCoursesToURL').'</a>
+	  </div><br />';
 echo '</div>';
 
 api_display_tool_title($tool_name);
@@ -89,7 +89,7 @@ if ($_POST['form_sent']) {
 	$first_letter_course = $_POST['first_letter_course'];
 
 	foreach($users as $key => $value) {
-		$users[$key] = intval($value);	
+		$users[$key] = intval($value);
 	}
 
 	if ($form_sent == 1) {
@@ -99,7 +99,7 @@ if ($_POST['form_sent']) {
 		} else {
 			UrlManager::add_courses_to_urls($courses,$url_list);
 			Display :: display_confirmation_message(get_lang('CourseBelongURL'));
-			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));				
+			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));
 		}
 	}
 }
@@ -116,8 +116,8 @@ if(empty($first_letter_user))
 {
 	$sql = "SELECT count(*) as num_courses FROM $tbl_course";
 	$result = api_sql_query($sql, __FILE__, __LINE__);
-	$num_row = Database::fetch_array($result);	
-	if($num_row['num_courses']>1000) 
+	$num_row = Database::fetch_array($result);
+	if($num_row['num_courses']>1000)
 	{//if there are too much num_courses to gracefully handle with the HTML select list,
 	 // assign a default filter on users names
 		$first_letter_user = 'A';
@@ -129,7 +129,7 @@ $first_letter_course = Database::escape_string($first_letter_course);
 $sql = "SELECT code, title FROM $tbl_course
 		WHERE title LIKE '".$first_letter_course."%' OR title LIKE '".api_strtolower($first_letter_course)."%'
 		ORDER BY title, code DESC ";
-		
+
 $result = api_sql_query($sql, __FILE__, __LINE__);
 $db_courses = api_store_result($result);
 unset($result);
@@ -147,7 +147,7 @@ unset($result);
     <td width="40%" align="center">
      <b><?php echo get_lang('CourseList'); ?></b>
      <br/><br/>
-     <?php echo get_lang('FirstLetterCourse'); ?> : 
+     <?php echo get_lang('FirstLetterCourse'); ?> :
      <select name="first_letter_course" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
       <option value="">--</option>
       <?php
@@ -155,11 +155,11 @@ unset($result);
         echo Display :: get_numeric_options(0,9,$first_letter_course);
       ?>
      </select>
-    </td>    
+    </td>
         <td width="20%">&nbsp;</td>
     <td width="40%" align="center">
-     <b><?php echo get_lang('URLList'); ?> :</b>     
-    </td>       
+     <b><?php echo get_lang('URLList'); ?> :</b>
+    </td>
    </tr>
    <tr>
     <td width="40%" align="center">
@@ -193,7 +193,7 @@ unset($result);
 <?php
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 25 - 25
main/admin/access_url_add_sessions_to_url.php

@@ -2,31 +2,31 @@
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
-	
+
 	Copyright (c) 2009 Dokeos SPRL
 	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
 
 	For a full list of contributors, see "credits.txt".
 	The full license can be read in "license.txt".
-	
+
 	This program is free software; you can redistribute it and/or
 	modify it under the terms of the GNU General Public License
 	as published by the Free Software Foundation; either version 2
 	of the License, or (at your option) any later version.
-	
+
 	See the GNU General Public License for more details.
-	
+
 	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	This script allows platform admins to add users to urls.
 *	It displays a list of users and a list of courses;
 *	you can select multiple users and courses and then click on
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 
 // name of the language file that needs to be included
@@ -39,7 +39,7 @@ require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
 api_protect_admin_script();
 if (!$_configuration['multiple_access_urls'])
 	header('Location: index.php');
-	
+
 /*
 -----------------------------------------------------------
 	Global constants and variables
@@ -74,21 +74,21 @@ $interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('Mult
 
 Display :: display_header($tool_name);
 echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">		
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_sessions_to_url.php">'.Display::return_icon('course_del.gif',get_lang('EditSessionToURL'),'').get_lang('EditSessionToURL').'</a>												
-	  </div><br />';		  
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_sessions_to_url.php">'.Display::return_icon('course_del.gif',get_lang('EditSessionToURL'),'').get_lang('EditSessionToURL').'</a>
+	  </div><br />';
 echo '</div>';
 
 api_display_tool_title($tool_name);
 
 if ($_POST['form_sent']) {
 	$form_sent = $_POST['form_sent'];
-	$sessions = is_array($_POST['session_list']) ? $_POST['session_list'] : array() ;	
+	$sessions = is_array($_POST['session_list']) ? $_POST['session_list'] : array() ;
 	$url_list = is_array($_POST['url_list']) ? $_POST['url_list'] : array() ;
 	$first_letter_session = $_POST['first_letter_session'];
 
 	foreach($users as $key => $value) {
-		$users[$key] = intval($value);	
+		$users[$key] = intval($value);
 	}
 
 	if ($form_sent == 1) {
@@ -98,7 +98,7 @@ if ($_POST['form_sent']) {
 		} else {
 			UrlManager::add_sessions_to_urls($sessions,$url_list);
 			Display :: display_confirmation_message(get_lang('SessionBelongURL'));
-			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));				
+			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));
 		}
 	}
 }
@@ -114,8 +114,8 @@ if ($_POST['form_sent']) {
 if(empty($first_letter_user)) {
 	$sql = "SELECT count(*) as num_courses FROM $tbl_course";
 	$result = api_sql_query($sql, __FILE__, __LINE__);
-	$num_row = Database::fetch_array($result);	
-	if($num_row['num_courses']>1000) 
+	$num_row = Database::fetch_array($result);
+	if($num_row['num_courses']>1000)
 	{//if there are too much num_courses to gracefully handle with the HTML select list,
 	 // assign a default filter on users names
 		$first_letter_user = 'A';
@@ -123,11 +123,11 @@ if(empty($first_letter_user)) {
 	unset($result);
 }
 */
-$first_letter_session = Database::escape_string($first_letter_session); 
+$first_letter_session = Database::escape_string($first_letter_session);
 $sql = "SELECT id, name FROM $tbl_session
 		WHERE name LIKE '".$first_letter_session."%' OR name LIKE '".api_strtolower($first_letter_session)."%'
 		ORDER BY name DESC ";
-		
+
 $result = api_sql_query($sql, __FILE__, __LINE__);
 $db_sessions = api_store_result($result);
 unset($result);
@@ -145,7 +145,7 @@ unset($result);
     <td width="40%" align="center">
      <b><?php echo get_lang('SessionList'); ?></b>
      <br/><br/>
-     <?php echo get_lang('FirstLetterSession'); ?> : 
+     <?php echo get_lang('FirstLetterSession'); ?> :
      <select name="first_letter_session" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
       <option value="">--</option>
       <?php
@@ -153,21 +153,21 @@ unset($result);
         echo Display :: get_numeric_options(0,9,$first_letter_session);
       ?>
      </select>
-    </td>    
+    </td>
         <td width="20%">&nbsp;</td>
     <td width="40%" align="center">
-     <b><?php echo get_lang('URLList'); ?> :</b>     
-    </td>       
+     <b><?php echo get_lang('URLList'); ?> :</b>
+    </td>
    </tr>
    <tr>
     <td width="40%" align="center">
      <select name="session_list[]" multiple="multiple" size="20" style="width:230px;">
 		<?php
-		
+
 		foreach ($db_sessions as $session) {
 			?>
-			<option value="<?php echo $session['id']; ?>" 
-			<?php if(in_array($session['id'],$sessions)) 
+			<option value="<?php echo $session['id']; ?>"
+			<?php if(in_array($session['id'],$sessions))
 			echo 'selected="selected"'; ?>>
 			<?php echo $session['name']; ?></option>
 			<?php
@@ -195,7 +195,7 @@ unset($result);
 <?php
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 22 - 22
main/admin/access_url_add_users_to_url.php

@@ -2,30 +2,30 @@
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
-	
+
 	Copyright (c) 2009 Dokeos SPRL
 	Copyright (c) 2009 Julio Montoya Armas <gugli100@gmail.com>
 
 	For a full list of contributors, see "credits.txt".
 	The full license can be read in "license.txt".
-	
+
 	This program is free software; you can redistribute it and/or
 	modify it under the terms of the GNU General Public License
 	as published by the Free Software Foundation; either version 2
 	of the License, or (at your option) any later version.
-	
+
 	See the GNU General Public License for more details.
-	
+
 	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	This script allows platform admins to add users to urls.
 *	It displays a list of users and a list of courses;
 *	you can select multiple users and courses and then click on
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 
 // name of the language file that needs to be included
@@ -38,7 +38,7 @@ require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
 api_protect_admin_script();
 if (!$_configuration['multiple_access_urls'])
 	header('Location: index.php');
-	
+
 /*
 -----------------------------------------------------------
 	Global constants and variables
@@ -75,10 +75,10 @@ $interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('Mult
 Display :: display_header($tool_name);
 
 echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">		
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php">'.Display::return_icon('edit.gif',get_lang('EditUsersToURL'),'').get_lang('EditUsersToURL').'</a>													
-	  </div><br />';		  
-echo '</div>';	
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php">'.Display::return_icon('edit.gif',get_lang('EditUsersToURL'),'').get_lang('EditUsersToURL').'</a>
+	  </div><br />';
+echo '</div>';
 
 api_display_tool_title($tool_name);
 
@@ -91,7 +91,7 @@ if ($_POST['form_sent']) {
 	$first_letter_user = $_POST['first_letter_user'];
 
 	foreach($users as $key => $value) {
-		$users[$key] = intval($value);	
+		$users[$key] = intval($value);
 	}
 
 	if ($form_sent == 1)
@@ -102,7 +102,7 @@ if ($_POST['form_sent']) {
 		} else {
 			UrlManager::add_users_to_urls($users,$url_list);
 			Display :: display_confirmation_message(get_lang('UsersBelongURL'));
-			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));				
+			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));
 		}
 	}
 }
@@ -119,7 +119,7 @@ if ($_POST['form_sent']) {
 if(empty($first_letter_user)) {
 	$sql = "SELECT count(*) as nb_users FROM $tbl_user";
 	$result = api_sql_query($sql, __FILE__, __LINE__);
-	$num_row = Database::fetch_array($result);	
+	$num_row = Database::fetch_array($result);
 	if($num_row['nb_users']>1000) {
 		//if there are too much users to gracefully handle with the HTML select list,
 	    // assign a default filter on users names
@@ -130,14 +130,14 @@ if(empty($first_letter_user)) {
 $first_letter_user = Database::escape_string($first_letter_user);
 
 $target_name = api_sort_by_first_name() ? 'firstname' : 'lastname';
-$sql = "SELECT user_id,lastname,firstname,username FROM $tbl_user 
-	    WHERE ".$target_name." LIKE '".$first_letter_user."%' OR ".$target_name." LIKE '".api_strtolower($first_letter_user)."%' 
+$sql = "SELECT user_id,lastname,firstname,username FROM $tbl_user
+	    WHERE ".$target_name." LIKE '".$first_letter_user."%' OR ".$target_name." LIKE '".api_strtolower($first_letter_user)."%'
 		ORDER BY ". (count($users) > 0 ? "(user_id IN(".implode(',', $users).")) DESC," : "")." ".$target_name;
 $result = api_sql_query($sql, __FILE__, __LINE__);
 $db_users = api_store_result($result);
 unset($result);
 
-$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url"; 
+$sql = "SELECT id, url FROM $tbl_access_url  WHERE active=1 ORDER BY url";
 $result = api_sql_query($sql, __FILE__, __LINE__);
 $db_urls = api_store_result($result);
 unset($result);
@@ -150,18 +150,18 @@ unset($result);
     <td width="40%" align="center">
      <b><?php echo get_lang('UserList'); ?></b>
      <br/><br/>
-     <?php echo get_lang('FirstLetterUser'); ?> : 
+     <?php echo get_lang('FirstLetterUser'); ?> :
      <select name="first_letter_user" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
       <option value="">--</option>
       <?php
         echo Display :: get_alphabet_options($first_letter_user);
       ?>
      </select>
-    </td>    
+    </td>
         <td width="20%">&nbsp;</td>
     <td width="40%" align="center">
-     <b><?php echo get_lang('URLList'); ?> :</b>     
-    </td>    
+     <b><?php echo get_lang('URLList'); ?> :</b>
+    </td>
    </tr>
    <tr>
     <td width="40%" align="center">
@@ -195,7 +195,7 @@ unset($result);
 <?php
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 26 - 26
main/admin/access_url_edit.php

@@ -23,7 +23,7 @@
 /**
 ==============================================================================
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 
 $language_file = 'admin';
@@ -42,48 +42,48 @@ require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
 // Create the form
 $form = new FormValidator('add_url');
 
-if( $form->validate()) {		
-	$check = Security::check_token('post');	
+if( $form->validate()) {
+	$check = Security::check_token('post');
 	if($check) {
 		$url_array = $form->getSubmitValues();
 		$url = Security::remove_XSS($url_array['url']);
 		$description = Security::remove_XSS($url_array['description']);
-		$active = intval($url_array['active']);				
+		$active = intval($url_array['active']);
 		$url_id = $url_array['id'];
-		$url_to_go='access_urls.php';			
+		$url_to_go='access_urls.php';
 		if ($url_id!='') {
 			//we can't change the status of the url with id=1
 			if ($url_id==1)
-				$active=1;								
+				$active=1;
 			//checking url
 			if (substr($url,strlen($url)-1, strlen($url))=='/') {
-				UrlManager::udpate($url_id, $url, $description, $active);				
-			} else {					
-				UrlManager::udpate($url_id, $url.'/', $description, $active);					
-			}						
+				UrlManager::udpate($url_id, $url, $description, $active);
+			} else {
+				UrlManager::udpate($url_id, $url.'/', $description, $active);
+			}
 			$url_to_go='access_urls.php';
 			$message=get_lang('URLEdited');
-		} else {			
-			$num = UrlManager::url_exist($url);											
+		} else {
+			$num = UrlManager::url_exist($url);
 			if ($num == 0) {
 				//checking url
 				if (substr($url,strlen($url)-1, strlen($url))=='/') {
-					UrlManager::add($url, $description, $active);					
-				} else {					
-					//create		
-					UrlManager::add($url.'/', $description, $active);						
+					UrlManager::add($url, $description, $active);
+				} else {
+					//create
+					UrlManager::add($url.'/', $description, $active);
 				}
 				$message = get_lang('URLAdded');
-				$url_to_go='access_urls.php';		
+				$url_to_go='access_urls.php';
 			} else {
 				$url_to_go='access_url_edit.php';
-				$message = get_lang('URLAlreadyAdded');			
-			}				
+				$message = get_lang('URLAlreadyAdded');
+			}
 		}
 		Security::clear_token();
 		$tok = Security::get_token();
 		header('Location: '.$url_to_go.'?action=show_message&message='.urlencode($message).'&sec_token='.$tok);
-		exit();		
+		exit();
 	}
 }
 else
@@ -109,22 +109,22 @@ $form->setDefaults($defaults);
 $submit_name = get_lang('Add');
 if (isset($_GET['url_id']))
 {
-	$url_id = Database::escape_string($_GET['url_id']);	
-	$num_url_id = UrlManager::url_id_exist($url_id);	
+	$url_id = Database::escape_string($_GET['url_id']);
+	$num_url_id = UrlManager::url_id_exist($url_id);
 	if($num_url_id != 1)
 	{
 		header('Location: access_urls.php');
 		exit();
 	}
-	$url_data = UrlManager::get_url_data_from_id($url_id);	
+	$url_data = UrlManager::get_url_data_from_id($url_id);
 	$form->addElement('hidden','id',$url_data['id']);
 	$form->setDefaults($url_data);
-	$submit_name = get_lang('Edit'); 
+	$submit_name = get_lang('Edit');
 }
 
 if (!$_configuration['multiple_access_urls'])
 	header('Location: index.php');
-	
+
 $tool_name = get_lang('AddUrl');
 $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array ("url" => 'access_urls.php', "name" => get_lang('MultipleAccessURLs'));
@@ -137,7 +137,7 @@ if (isset ($_GET['action']))
 		case 'show_message' :
 			Display :: display_normal_message(stripslashes($_GET['message']));
 			break;
-	}	
+	}
 }
 
 // Submit button

+ 54 - 54
main/admin/access_url_edit_courses_to_url.php

@@ -62,34 +62,34 @@ $interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('Mult
 $add_type = 'multiple';
 if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
 	$add_type = Security::remove_XSS($_REQUEST['add_type']);
-	 
+
 }
 
 $access_url_id=1;
 if(isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
-	$access_url_id = Security::remove_XSS($_REQUEST['access_url_id']); 
+	$access_url_id = Security::remove_XSS($_REQUEST['access_url_id']);
 }
 
 function search_courses($needle, $id)
 {
-	global $tbl_course;	
+	global $tbl_course;
 	$xajax_response = new XajaxResponse();
 	$return = '';
-				
-	if(!empty($needle)) {		
+
+	if(!empty($needle)) {
 		// xajax send utf8 datas... datas in db can be non-utf8 datas
 		$charset = api_get_setting('platform_charset');
 		$needle = api_convert_encoding($needle, $charset, 'utf-8');
 		$needle = Database::escape_string($needle);
 		// search courses where username or firstname or lastname begins likes $needle
-		$sql = 'SELECT code, title FROM '.$tbl_course.' u 
+		$sql = 'SELECT code, title FROM '.$tbl_course.' u
 				WHERE (title LIKE "'.$needle.'%"
 				OR code LIKE "'.$needle.'%"
-				) 
+				)
 				ORDER BY title, code
-				LIMIT 11';				
-		$rs = api_sql_query($sql, __FILE__, __LINE__);		
-        $i=0;        
+				LIMIT 11';
+		$rs = api_sql_query($sql, __FILE__, __LINE__);
+        $i=0;
 		while ($course = Database :: fetch_array($rs)) {
 			$i++;
             if ($i<=10) {
@@ -111,23 +111,23 @@ function add_user_to_url(code, content) {
 
 	document.getElementById("course_to_add").value = "";
 	document.getElementById("ajax_list_courses").innerHTML = "";
-	
+
 	destination = document.getElementById("destination_users");
 	destination.options[destination.length] = new Option(content,code);
-	
+
 	destination.selectedIndex = -1;
-	sortOptions(destination.options);	
+	sortOptions(destination.options);
 }
-	
+
 function send() {
-	
-	if (document.formulaire.access_url_id.value!=0) {	
-		document.formulaire.form_sent.value=0; 
-		document.formulaire.add_type.value=\''.$add_type.'\';		
+
+	if (document.formulaire.access_url_id.value!=0) {
+		document.formulaire.form_sent.value=0;
+		document.formulaire.add_type.value=\''.$add_type.'\';
 		document.formulaire.submit();
-	}	
+	}
 }
-	
+
 function remove_item(origin)
 {
 	for(var i = 0 ; i<origin.options.length ; i++) {
@@ -144,32 +144,32 @@ $errorMsg='';
 $UserList=$SessionList=array();
 $users=$sessions=array();
 
-if($_POST['form_sent']) {	
+if($_POST['form_sent']) {
 	$form_sent=$_POST['form_sent'];
-	$course_list=$_POST['course_list'];	
-	
+	$course_list=$_POST['course_list'];
+
 	if(!is_array($course_list)) {
 		$course_list=array();
 	}
-	
-	if($form_sent == 1) { 
-		if ($access_url_id==0) {						
+
+	if($form_sent == 1) {
+		if ($access_url_id==0) {
 			header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
 		}
-		elseif(is_array($course_list) ) {									
+		elseif(is_array($course_list) ) {
 			UrlManager::update_urls_rel_course($course_list,$access_url_id);
 			header('Location: access_urls.php?action=show_message&message='.get_lang('CoursesWereEdited'));
-		}		
+		}
 	}
 }
 
 Display::display_header($tool_name);
 
 echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">		
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_courses_to_url.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddUserToURL'),'').get_lang('AddCoursesToURL').'</a>												
-	  </div><br />';		  
-echo '</div>';	
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_courses_to_url.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddUserToURL'),'').get_lang('AddCoursesToURL').'</a>
+	  </div><br />';
+echo '</div>';
 
 api_display_tool_title($tool_name);
 
@@ -179,31 +179,31 @@ if ($_GET['action'] == 'show_message')
 $no_course_list = $course_list = array();
 $ajax_search = $add_type == 'unique' ? true : false;
 
-if($ajax_search) {		
+if($ajax_search) {
 	$courses=UrlManager::get_url_rel_course_data($access_url_id);
 	foreach($courses as $course) {
 		$course_list[$course['course_code']] = $course ;
-	}	
-} else {	
+	}
+} else {
 	$courses=UrlManager::get_url_rel_course_data();
-		
+
 	foreach($courses as $course) {
 		if($course['access_url_id'] == $access_url_id) {
 			$course_list[$course['course_code']] = $course ;
 		}
 	}
-		
+
 	$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
 	$sql="SELECT code, title
-	  	  	FROM $tbl_course u	
-			ORDER BY title, code";	
-	$result=api_sql_query($sql,__FILE__,__LINE__);	
+	  	  	FROM $tbl_course u
+			ORDER BY title, code";
+	$result=api_sql_query($sql,__FILE__,__LINE__);
 	$courses=api_store_result($result);
 	$course_list_leys = array_keys($course_list);
-	foreach($courses as $course) {	
+	foreach($courses as $course) {
 		if (!in_array($course['code'],$course_list_leys))
 			$no_course_list[$course['code']] = $course ;
-	}	
+	}
 }
 
 
@@ -217,7 +217,7 @@ if($add_type == 'multiple') {
 
 $url_list = UrlManager::get_url_data();
 
-?>	
+?>
 
 <div style="text-align: left;">
 	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
@@ -227,7 +227,7 @@ $url_list = UrlManager::get_url_data();
 <?php echo get_lang('SelectUrl').' : '; ?>
 <select name="access_url_id" onchange="javascript:send();">
 <option value="0"> <?php echo get_lang('SelectUrl')?></option>
-	<?php	
+	<?php
 	$url_selected='';
 	foreach ($url_list as $url_obj) {
 		$checked = '';
@@ -237,17 +237,17 @@ $url_list = UrlManager::get_url_data();
 			$url_selected=$url_obj[1];
 			}
 		}
-		if ($url_obj['active']==1) {						
+		if ($url_obj['active']==1) {
 			?>
 				<option <?php echo $checked;?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?></option>
 			<?php
 		}
 	}
-	?>		
+	?>
 </select>
 <br /><br />
 <input type="hidden" name="form_sent" value="1" />
-<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" /> 
+<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
 
 <?php
 if(!empty($errorMsg)) {
@@ -261,7 +261,7 @@ if(!empty($errorMsg)) {
 <tr>
   <td align="center"><b><?php echo get_lang('CourseListInPlatform') ?> :</b>
   </td>
-  <td></td>  
+  <td></td>
   <td align="center"><b><?php echo get_lang('CourseListIn').' '.$url_selected; ?></b></td>
 </tr>
 
@@ -275,7 +275,7 @@ if(!empty($errorMsg)) {
 		<div id="ajax_list_courses"></div>
 		<?php
   	  } else {
-  	  ?>  	  
+  	  ?>
 	  <select id="origin_users" name="no_course_list[]" multiple="multiple" size="15" style="width:300px;">
 		<?php
 		foreach($no_course_list as $no_course) {
@@ -291,13 +291,13 @@ function add_user_to_url (code, content) {
 
 	document.getElementById("course_to_add").value = "";
 	document.getElementById("ajax_list_courses").innerHTML = "";
-	
+
 	destination = document.getElementById("destination_users");
 	destination.options[destination.length] = new Option(content,code);
-	
+
 	destination.selectedIndex = -1;
 	sortOptions(destination.options);
-	
+
 }
 function remove_item(origin)
 {
@@ -331,8 +331,8 @@ function remove_item(origin)
 	<input type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" value=">>" />
 	<br /><br />
 	<input type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" value="<<" />
-	<?php 
-  } 
+	<?php
+  }
   ?>
 	<br /><br /><br /><br /><br /><br />
   </td>

+ 53 - 53
main/admin/access_url_edit_sessions_to_url.php

@@ -66,27 +66,27 @@ if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
 
 $access_url_id=1;
 if(isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
-	$access_url_id = Security::remove_XSS(intval($_REQUEST['access_url_id'])); 
+	$access_url_id = Security::remove_XSS(intval($_REQUEST['access_url_id']));
 }
 
 function search_sessions($needle, $id)
 {
-	global $tbl_session;	
+	global $tbl_session;
 	$xajax_response = new XajaxResponse();
 	$return = '';
-				
-	if(!empty($needle)) {		
+
+	if(!empty($needle)) {
 		// xajax send utf8 datas... datas in db can be non-utf8 datas
 		$charset = api_get_setting('platform_charset');
 		$needle = api_convert_encoding($needle, $charset, 'utf-8');
 		$needle = Database::escape_string($needle);
 		// search sessiones where username or firstname or lastname begins likes $needle
-		$sql = 'SELECT id, name FROM '.$tbl_session.' u 
-				WHERE (name LIKE "'.$needle.'%") 
+		$sql = 'SELECT id, name FROM '.$tbl_session.' u
+				WHERE (name LIKE "'.$needle.'%")
 				ORDER BY name, id
-				LIMIT 11';				
-		$rs = api_sql_query($sql, __FILE__, __LINE__);		
-        $i=0;        
+				LIMIT 11';
+		$rs = api_sql_query($sql, __FILE__, __LINE__);
+        $i=0;
 		while ($session = Database :: fetch_array($rs)) {
 			$i++;
             if ($i<=10) {
@@ -108,23 +108,23 @@ function add_user_to_url(code, content) {
 
 	document.getElementById("course_to_add").value = "";
 	document.getElementById("ajax_list_courses").innerHTML = "";
-	
+
 	destination = document.getElementById("destination_users");
 	destination.options[destination.length] = new Option(content,code);
-	
+
 	destination.selectedIndex = -1;
-	sortOptions(destination.options);	
+	sortOptions(destination.options);
 }
-	
+
 function send() {
-	
-	if (document.formulaire.access_url_id.value!=0) {	
-		document.formulaire.form_sent.value=0; 
-		document.formulaire.add_type.value=\''.$add_type.'\';		
+
+	if (document.formulaire.access_url_id.value!=0) {
+		document.formulaire.form_sent.value=0;
+		document.formulaire.add_type.value=\''.$add_type.'\';
 		document.formulaire.submit();
-	}	
+	}
 }
-	
+
 function remove_item(origin)
 {
 	for(var i = 0 ; i<origin.options.length ; i++) {
@@ -141,32 +141,32 @@ $errorMsg='';
 $UserList=$SessionList=array();
 $users=$sessions=array();
 
-if($_POST['form_sent']) {	
+if($_POST['form_sent']) {
 	$form_sent=$_POST['form_sent'];
-	$session_list=$_POST['session_list'];	
-		
+	$session_list=$_POST['session_list'];
+
 	if(!is_array($session_list)) {
 		$session_list=array();
 	}
-	
-	if($form_sent == 1) { 
-		if ($access_url_id==0) {						
+
+	if($form_sent == 1) {
+		if ($access_url_id==0) {
 			header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
 		}
-		elseif(is_array($session_list) ) {									
+		elseif(is_array($session_list) ) {
 			UrlManager::update_urls_rel_session($session_list,$access_url_id);
 			header('Location: access_urls.php?action=show_message&message='.get_lang('SessionsWereEdited'));
-		}		
+		}
 	}
 }
 
 Display::display_header($tool_name);
 
 echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">		
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_sessions_to_url.php">'.Display::return_icon('course_add.gif',get_lang('AddSessionsToURL'),'').get_lang('AddSessionsToURL').'</a>												
-	  </div><br />';		  
-echo '</div>';	
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_sessions_to_url.php">'.Display::return_icon('course_add.gif',get_lang('AddSessionsToURL'),'').get_lang('AddSessionsToURL').'</a>
+	  </div><br />';
+echo '</div>';
 
 api_display_tool_title($tool_name);
 
@@ -176,30 +176,30 @@ if ($_GET['action'] == 'show_message')
 $no_session_list = $session_list = array();
 $ajax_search = $add_type == 'unique' ? true : false;
 
-if($ajax_search) {		
+if($ajax_search) {
 	$sessions=UrlManager::get_url_rel_session_data($access_url_id);
 	foreach($sessions as $session) {
 		$session_list[$session['id']] = $session ;
-	}	
-} else {	
-	$sessions=UrlManager::get_url_rel_session_data();		
+	}
+} else {
+	$sessions=UrlManager::get_url_rel_session_data();
 	foreach($sessions as $session) {
 		if($session['access_url_id'] == $access_url_id) {
 			$session_list[$session['id']] = $session ;
 		}
 	}
-		
+
 	$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
 	$sql="SELECT id, name
-	  	  	FROM $tbl_session u	
-			ORDER BY name, id";	
-	$result=api_sql_query($sql,__FILE__,__LINE__);	
+	  	  	FROM $tbl_session u
+			ORDER BY name, id";
+	$result=api_sql_query($sql,__FILE__,__LINE__);
 	$sessions=api_store_result($result);
 	$session_list_leys = array_keys($session_list);
-	foreach($sessions as $session) {	
+	foreach($sessions as $session) {
 		if (!in_array($session['id'],$session_list_leys))
 			$no_session_list[$session['id']] = $session ;
-	}	
+	}
 }
 
 
@@ -213,7 +213,7 @@ if($add_type == 'multiple') {
 
 $url_list = UrlManager::get_url_data();
 
-?>	
+?>
 
 <div style="text-align: left;">
 	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
@@ -223,7 +223,7 @@ $url_list = UrlManager::get_url_data();
 <?php echo get_lang('SelectUrl').' : '; ?>
 <select name="access_url_id" onchange="javascript:send();">
 <option value="0"> <?php echo get_lang('SelectUrl')?></option>
-	<?php	
+	<?php
 	$url_selected='';
 	foreach ($url_list as $url_obj) {
 		$checked = '';
@@ -233,17 +233,17 @@ $url_list = UrlManager::get_url_data();
 			$url_selected=$url_obj[1];
 			}
 		}
-		if ($url_obj['active']==1) {						
+		if ($url_obj['active']==1) {
 			?>
 				<option <?php echo $checked;?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?></option>
 			<?php
 		}
 	}
-	?>		
+	?>
 </select>
 <br /><br />
 <input type="hidden" name="form_sent" value="1" />
-<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" /> 
+<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
 
 <?php
 if(!empty($errorMsg)) {
@@ -257,7 +257,7 @@ if(!empty($errorMsg)) {
 <tr>
   <td align="center"><b><?php echo get_lang('SessionListInPlatform') ?> :</b>
   </td>
-  <td></td>  
+  <td></td>
   <td align="center"><b><?php echo get_lang('SessionListIn').' '.$url_selected; ?></b></td>
 </tr>
 
@@ -271,7 +271,7 @@ if(!empty($errorMsg)) {
 		<div id="ajax_list_courses"></div>
 		<?php
   	  } else {
-  	  ?>  	  
+  	  ?>
 	  <select id="origin_users" name="no_session_list[]" multiple="multiple" size="15" style="width:300px;">
 		<?php
 		foreach($no_session_list as $no_session) {
@@ -287,13 +287,13 @@ function add_user_to_url (code, content) {
 
 	document.getElementById("course_to_add").value = "";
 	document.getElementById("ajax_list_courses").innerHTML = "";
-	
+
 	destination = document.getElementById("destination_users");
 	destination.options[destination.length] = new Option(content,code);
-	
+
 	destination.selectedIndex = -1;
 	sortOptions(destination.options);
-	
+
 }
 function remove_item(origin)
 {
@@ -327,8 +327,8 @@ function remove_item(origin)
 	<input type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" value=">>" />
 	<br /><br />
 	<input type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" value="<<" />
-	<?php 
-  } 
+	<?php
+  }
   ?>
 	<br /><br /><br /><br /><br /><br />
   </td>

+ 50 - 50
main/admin/access_url_edit_users_to_url.php

@@ -66,32 +66,32 @@ if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
 
 $access_url_id=1;
 if(isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id']!=''){
-	$access_url_id = Security::remove_XSS($_REQUEST['access_url_id']); 
+	$access_url_id = Security::remove_XSS($_REQUEST['access_url_id']);
 }
 
 function search_users($needle, $id)
 {
-	global $tbl_user, $tbl_access_url_rel_user;	
+	global $tbl_user, $tbl_access_url_rel_user;
 	$xajax_response = new XajaxResponse();
 	$return = '';
-				
-	if(!empty($needle)) {		
+
+	if(!empty($needle)) {
 		// xajax send utf8 datas... datas in db can be non-utf8 datas
 		$charset = api_get_setting('platform_charset');
 		$needle = api_convert_encoding($needle, $charset, 'utf-8');
 		$needle = Database::escape_string($needle);
 		// search users where username or firstname or lastname begins likes $needle
 		$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-		$sql = 'SELECT u.user_id, username, lastname, firstname FROM '.$tbl_user.' u 
+		$sql = 'SELECT u.user_id, username, lastname, firstname FROM '.$tbl_user.' u
 				WHERE (username LIKE "'.$needle.'%"
 				OR firstname LIKE "'.$needle.'%"
 				OR lastname LIKE "'.$needle.'%")'.
 				$order_clause.
 				' LIMIT 11';
-				
-		$rs = api_sql_query($sql, __FILE__, __LINE__);		
+
+		$rs = api_sql_query($sql, __FILE__, __LINE__);
         $i=0;
-        
+
 		while ($user = Database :: fetch_array($rs)) {
 			$i++;
             if ($i<=10) {
@@ -113,23 +113,23 @@ function add_user_to_url(code, content) {
 
 	document.getElementById("user_to_add").value = "";
 	document.getElementById("ajax_list_users").innerHTML = "";
-	
+
 	destination = document.getElementById("destination_users");
 	destination.options[destination.length] = new Option(content,code);
-	
+
 	destination.selectedIndex = -1;
-	sortOptions(destination.options);	
+	sortOptions(destination.options);
 }
-	
+
 function send() {
-	
-	if (document.formulaire.access_url_id.value!=0) {	
-		document.formulaire.form_sent.value=0; 
-		document.formulaire.add_type.value=\''.$add_type.'\';		
+
+	if (document.formulaire.access_url_id.value!=0) {
+		document.formulaire.form_sent.value=0;
+		document.formulaire.add_type.value=\''.$add_type.'\';
 		document.formulaire.submit();
-	}	
+	}
 }
-	
+
 function remove_item(origin)
 {
 	for(var i = 0 ; i<origin.options.length ; i++) {
@@ -146,30 +146,30 @@ $errorMsg='';
 $UserList=$SessionList=array();
 $users=$sessions=array();
 
-if($_POST['form_sent']) {	
+if($_POST['form_sent']) {
 	$form_sent=$_POST['form_sent'];
-	$UserList=$_POST['sessionUsersList'];	
+	$UserList=$_POST['sessionUsersList'];
 	if(!is_array($UserList)) {
 		$UserList=array();
 	}
-	if($form_sent == 1) { 
-		if ($access_url_id==0) {						
+	if($form_sent == 1) {
+		if ($access_url_id==0) {
 			header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
 		}
-		elseif(is_array($UserList) ) {						
+		elseif(is_array($UserList) ) {
 			UrlManager::update_urls_rel_user($UserList,$access_url_id);
 			header('Location: access_urls.php?action=show_message&message='.get_lang('UsersWereEdited'));
-		}		
+		}
 	}
 }
 
 Display::display_header($tool_name);
 
 echo '<div class="actions" style="height:22px;">';
-echo '<div style="float:right;">		
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_users_to_url.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddUserToURL'),'').get_lang('AddUsersToURL').'</a>												
-	  </div><br />';		  
-echo '</div>';	
+echo '<div style="float:right;">
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_add_users_to_url.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddUserToURL'),'').get_lang('AddUsersToURL').'</a>
+	  </div><br />';
+echo '</div>';
 
 api_display_tool_title($tool_name);
 
@@ -179,29 +179,29 @@ if ($_GET['action'] == 'show_message')
 $nosessionUsersList = $sessionUsersList = array();
 $ajax_search = $add_type == 'unique' ? true : false;
 
-if($ajax_search) {		
+if($ajax_search) {
 	$Users=UrlManager::get_url_rel_user_data($access_url_id);
 	foreach($Users as $user) {
 		$sessionUsersList[$user['user_id']] = $user ;
-	}	
-} else {	
-	$Users=UrlManager::get_url_rel_user_data();	
+	}
+} else {
+	$Users=UrlManager::get_url_rel_user_data();
 	foreach($Users as $user) {
 		if($user['access_url_id'] == $access_url_id) {
 			$sessionUsersList[$user['user_id']] = $user ;
 		}
-	}	
+	}
 	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
 	$sql="SELECT u.user_id, lastname, firstname, username
-	  	  	FROM $tbl_user u".	
-			$order_clause;	
-	$result=api_sql_query($sql,__FILE__,__LINE__);	
+	  	  	FROM $tbl_user u".
+			$order_clause;
+	$result=api_sql_query($sql,__FILE__,__LINE__);
 	$Users=api_store_result($result);
 	$user_list_leys = array_keys($sessionUsersList);
-	foreach($Users as $user) {	
+	foreach($Users as $user) {
 		if (!in_array($user['user_id'],$user_list_leys))
 			$nosessionUsersList[$user['user_id']] = $user ;
-	}	
+	}
 }
 
 
@@ -215,7 +215,7 @@ if($add_type == 'multiple') {
 
 $url_list = UrlManager::get_url_data();
 
-?>	
+?>
 
 <div style="text-align: left;">
 	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
@@ -225,8 +225,8 @@ $url_list = UrlManager::get_url_data();
 <?php echo get_lang('SelectUrl').' : '; ?>
 <select name="access_url_id" onchange="javascript:send();">
 <option value="0"> <?php echo get_lang('SelectUrl')?></option>
-	<?php	
-	$url_selected='';	
+	<?php
+	$url_selected='';
 	foreach ($url_list as $url_obj) {
 		$checked = '';
 		if (!empty($access_url_id)) {
@@ -235,17 +235,17 @@ $url_list = UrlManager::get_url_data();
 			$url_selected=	$url_obj[1];
 			}
 		}
-		if ($url_obj['active']==1) {				
+		if ($url_obj['active']==1) {
 	?>
 		<option <?php echo $checked;?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?></option>
 	<?php
 		}
 	}
-	?>		
+	?>
 </select>
 <br /><br />
 <input type="hidden" name="form_sent" value="1" />
-<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" /> 
+<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
 
 <?php
 if(!empty($errorMsg)) {
@@ -273,7 +273,7 @@ if(!empty($errorMsg)) {
 		<div id="ajax_list_users"></div>
 		<?php
   	  } else {
-  	  ?>  	  
+  	  ?>
 	  <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:300px;">
 		<?php
 		foreach($nosessionUsersList as $enreg) {
@@ -289,13 +289,13 @@ function add_user_to_url (code, content) {
 
 	document.getElementById("user_to_add").value = "";
 	document.getElementById("ajax_list_users").innerHTML = "";
-	
+
 	destination = document.getElementById("destination_users");
 	destination.options[destination.length] = new Option(content,code);
-	
+
 	destination.selectedIndex = -1;
 	sortOptions(destination.options);
-	
+
 }
 function remove_item(origin)
 {
@@ -329,8 +329,8 @@ function remove_item(origin)
 	<input type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" value=">>" />
 	<br /><br />
 	<input type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" value="<<" />
-	<?php 
-  } 
+	<?php
+  }
   ?>
 	<br /><br /><br /><br /><br /><br />
   </td>

+ 47 - 47
main/admin/access_urls.php

@@ -23,10 +23,10 @@
 /**
 ==============================================================================
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file = 'admin';
 $cidReset = true;
 require ('../inc/global.inc.php');
@@ -35,7 +35,7 @@ $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
 if (!$_configuration['multiple_access_urls'])
 	header('Location: index.php');
-	
+
 $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 $tool_name = get_lang('MultipleAccessURLs');
 Display :: display_header($tool_name);
@@ -50,17 +50,17 @@ $current_access_url_id = api_get_current_access_url_id();
 $url_list = UrlManager::get_url_data();
 
 // Actions
-if (isset ($_GET['action'])) {	
+if (isset ($_GET['action'])) {
 	if ($_GET['action'] == 'show_message')
-		Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));	
-		
-	$check = Security::check_token('get');		
+		Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
+
+	$check = Security::check_token('get');
 	if ($check) {
 		$url_id=Database::escape_string($_GET['url_id']);
-	
-		switch ($_GET['action']) {		
-			case 'delete_url' :		
-				$result = UrlManager::delete($url_id);					
+
+		switch ($_GET['action']) {
+			case 'delete_url' :
+				$result = UrlManager::delete($url_id);
 				if ($result) {
 					Display :: display_normal_message(get_lang('URLDeleted'));
 				} else {
@@ -68,30 +68,30 @@ if (isset ($_GET['action'])) {
 				}
 				break;
 			case 'lock' :
-				UrlManager::set_url_status('lock',$url_id);				
+				UrlManager::set_url_status('lock',$url_id);
 				Display :: display_normal_message(get_lang('URLInactive'));
 				break;
 			case 'unlock';
 				UrlManager::set_url_status('unlock',$url_id);
 				Display :: display_normal_message(get_lang('URLActive'));
-				break;			
-			case 'register';			
+				break;
+			case 'register';
 				// we are going to register the admin
-				if(api_is_platform_admin()) {					
+				if(api_is_platform_admin()) {
 					if($current_access_url_id!=-1) {
 						$url_str = '';
-						foreach($url_list as $my_url) {	
-							if (!in_array($my_url['id'],$my_user_url_list)){								
-								UrlManager::add_user_to_url(api_get_user_id(),$my_url['id']);	
-									$url_str.=$my_url['url'].' '; 
+						foreach($url_list as $my_url) {
+							if (!in_array($my_url['id'],$my_user_url_list)){
+								UrlManager::add_user_to_url(api_get_user_id(),$my_url['id']);
+									$url_str.=$my_url['url'].' ';
 							}
-						}						
+						}
 						Display :: display_normal_message(get_lang('AdminUserRegisteredToThisURL').': '.$url_str.'<br />',false);
 					}
-				}						
-				break;	
+				}
+				break;
 			}
-			
+
 		}
 		Security::clear_token();
 }
@@ -102,23 +102,23 @@ $parameters['sec_token'] = Security::get_token();
 
 $url_string='';
 $my_user_url_list = api_get_access_url_from_user(api_get_user_id());
-foreach($url_list as $my_url) {	
+foreach($url_list as $my_url) {
 	if (!in_array($my_url['id'],$my_user_url_list)){
-		$url_string.=$my_url['url'].' ';		
-	}	
+		$url_string.=$my_url['url'].' ';
+	}
 }
 if(!empty($url_string)) {
 	Display :: display_warning_message(get_lang('AdminShouldBeRegisterInSite').':<br />'.$url_string,false);
 }
 
 // checking the current installation
-if ($current_access_url_id==-1) {	
-	Display :: display_warning_message(get_lang('URLNotConfiguredPleaseChangedTo').': '.api_get_path(WEB_PATH));	
-} elseif(api_is_platform_admin()) {			
+if ($current_access_url_id==-1) {
+	Display :: display_warning_message(get_lang('URLNotConfiguredPleaseChangedTo').': '.api_get_path(WEB_PATH));
+} elseif(api_is_platform_admin()) {
 	$quant= UrlManager::relation_url_user_exist(api_get_user_id(),$current_access_url_id);
 	if ($quant==0) {
-		Display :: display_warning_message('<a href="'.api_get_self().'?action=register&sec_token='.$parameters['sec_token'].'">'.get_lang('ClickToRegisterAdmin').'</a>',false);	
-	} 
+		Display :: display_warning_message('<a href="'.api_get_self().'?action=register&sec_token='.$parameters['sec_token'].'">'.get_lang('ClickToRegisterAdmin').'</a>',false);
+	}
 }
 
 //<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_sessions_to_url.php">'.Display::return_icon('sessions.gif',get_lang('ManageSessions'),'').get_lang('ManageSessions').'</a>
@@ -126,12 +126,12 @@ if ($current_access_url_id==-1) {
 echo '<div class="actions" style="height:22px;">';
 echo '<div style="float:right;">
 		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddUrl'),'').get_lang('AddUrl').'</a>&nbsp;&nbsp;
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php">'.Display::return_icon('members.gif',get_lang('ManageUsers'),'').get_lang('ManageUsers').'</a>															
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php">'.Display::return_icon('members.gif',get_lang('ManageUsers'),'').get_lang('ManageUsers').'</a>
 	    <a href="'.api_get_path(WEB_CODE_PATH).'admin/access_url_edit_courses_to_url.php">'.Display::return_icon('courses.gif',get_lang('ManageCourses'),'').get_lang('ManageCourses').'</a>
-	  </div><br />';		  
+	  </div><br />';
 echo '</div>';
 
-$table = new SortableTable('urls', 'url_count_mask', 'get_url_data_mask',2); 
+$table = new SortableTable('urls', 'url_count_mask', 'get_url_data_mask',2);
 $table->set_additional_parameters($parameters);
 $table->set_header(0, '', false);
 
@@ -146,33 +146,33 @@ $table->set_column_filter(3, 'active_filter');
 $table->set_column_filter(4, 'modify_filter');
 
 //$table->set_form_actions(array ('delete' => get_lang('DeleteFromPlatform')));
-$table->display(); 
+$table->display();
 /*
-function status_filter($active, $url_params, $row) {	
-	$url_id =UrlManager::get_url_id($row[1]);	
-	if ($row[0] == $url_id ) { 	
+function status_filter($active, $url_params, $row) {
+	$url_id =UrlManager::get_url_id($row[1]);
+	if ($row[0] == $url_id ) {
 		$action='lock';
 		$image='right';
 	} else {
 		$image='wrong';
 	}
-	// you cannot lock the default	
-	$result = Display::return_icon($image.'.gif', get_lang(ucfirst($action)));		
+	// you cannot lock the default
+	$result = Display::return_icon($image.'.gif', get_lang(ucfirst($action)));
 
 	return $result;
 }
 */
 function modify_filter($active, $url_params, $row) {
-	global $charset;	
+	global $charset;
 	$url_id = $row['0'];
 	$result .= '<a href="access_url_edit.php?url_id='.$url_id.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>&nbsp;';
-	if ($url_id != '1') {	
+	if ($url_id != '1') {
 		$result .= '<a href="access_urls.php?action=delete_url&amp;url_id='.$url_id.'&amp;sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
 	}
 	return $result;
 }
 
-function active_filter($active, $url_params, $row) {	
+function active_filter($active, $url_params, $row) {
 	$active = $row['3'];
 	if ($active=='1') {
 		$action='lock';
@@ -183,10 +183,10 @@ function active_filter($active, $url_params, $row) {
 		$image='wrong';
 	}
 	// you cannot lock the default
-	if ($row['0']=='1') { 
+	if ($row['0']=='1') {
 		$result = Display::return_icon($image.'.gif', get_lang(ucfirst($action)));
 	} else {
-		$result = '<a href="access_urls.php?action='.$action.'&amp;url_id='.$row['0'].'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon($image.'.gif', get_lang(ucfirst($action))).'</a>';		
+		$result = '<a href="access_urls.php?action='.$action.'&amp;url_id='.$row['0'].'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon($image.'.gif', get_lang(ucfirst($action))).'</a>';
 	}
 	return $result;
 }
@@ -196,12 +196,12 @@ function get_url_data_mask($id, $url_params=null, $row=null) {
 	return UrlManager::get_url_data();
 }
 function url_count_mask() {
-	return UrlManager::url_count();				
+	return UrlManager::url_count();
 }
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 84 - 84
main/admin/add_courses_to_session.php

@@ -60,14 +60,14 @@ if (!api_is_platform_admin()) {
 function search_courses($needle,$type)
 {
 	global $tbl_course, $tbl_session_rel_course, $id_session;
-	
+
 	$xajax_response = new XajaxResponse();
-	$return = '';	
+	$return = '';
 	if(!empty($needle) && !empty($type)) {
 		// xajax send utf8 datas... datas in db can be non-utf8 datas
 		$charset = api_get_setting('platform_charset');
 		$needle = api_convert_encoding($needle, $charset, 'utf-8');
-		
+
 		$cond_course_code = '';
 		if (!empty($id_session)) {
 		$id_session = Database::escape_string($id_session);
@@ -77,14 +77,14 @@ function search_courses($needle,$type)
 			$course_codes = '';
 			if (Database::num_rows($res) > 0) {
 				while ($row = Database::fetch_row($res)) {
-					$course_codes .= '\''.$row[0].'\',';					
+					$course_codes .= '\''.$row[0].'\',';
 				}
 				$course_codes = substr($course_codes,0,(strlen($course_codes)-1));
-											
+
 				$cond_course_code = ' AND course.code NOT IN('.$course_codes.') ';
-			}				
+			}
 		}
-		
+
 		if ($type=='single') {
 		// search users where username or firstname or lastname begins likes $needle
 		$sql = 'SELECT course.code, course.visual_code, course.title, session_rel_course.id_session
@@ -94,63 +94,63 @@ function search_courses($needle,$type)
 					AND session_rel_course.id_session = '.intval($id_session).'
 				WHERE course.visual_code LIKE "'.$needle.'%"
 				OR course.title LIKE "'.$needle.'%"';
-		} else {			
-						
+		} else {
+
 		$sql = 'SELECT course.code, course.visual_code, course.title
-				FROM '.$tbl_course.' course				
-				WHERE course.visual_code LIKE "'.$needle.'%" '.$cond_course_code.' ORDER BY course.code ';	
+				FROM '.$tbl_course.' course
+				WHERE course.visual_code LIKE "'.$needle.'%" '.$cond_course_code.' ORDER BY course.code ';
 		}
-				
+
 		global $_configuration;
-		if ($_configuration['multiple_access_urls']==true) {		
-			$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);	
+		if ($_configuration['multiple_access_urls']==true) {
+			$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 			$access_url_id = api_get_current_access_url_id();
 			if ($access_url_id != -1){
-				
-				if ($type=='single') { 
+
+				if ($type=='single') {
 					$sql = 'SELECT course.code, course.visual_code, course.title, session_rel_course.id_session
 							FROM '.$tbl_course.' course
 							LEFT JOIN '.$tbl_session_rel_course.' session_rel_course
 								ON course.code = session_rel_course.course_code
-								AND session_rel_course.id_session = '.intval($id_session).' 	
-							INNER JOIN '.$tbl_course_rel_access_url.' url_course ON (url_course.course_code=course.code)					
+								AND session_rel_course.id_session = '.intval($id_session).'
+							INNER JOIN '.$tbl_course_rel_access_url.' url_course ON (url_course.course_code=course.code)
 							WHERE access_url_id = '.$access_url_id.' AND (course.visual_code LIKE "'.$needle.'%"
 							OR course.title LIKE "'.$needle.'%" )';
 				} else {
 					$sql = 'SELECT course.code, course.visual_code, course.title
-							FROM '.$tbl_course.' course, '.$tbl_course_rel_access_url.' url_course							 													
-							WHERE url_course.course_code=course.code AND access_url_id = '.$access_url_id.' 
+							FROM '.$tbl_course.' course, '.$tbl_course_rel_access_url.' url_course
+							WHERE url_course.course_code=course.code AND access_url_id = '.$access_url_id.'
 							AND course.visual_code LIKE "'.$needle.'%" '.$cond_course_code.' ORDER BY course.code ';
-				}					
+				}
 			}
 		}
-					
-		$rs = api_sql_query($sql, __FILE__, __LINE__);		
+
+		$rs = api_sql_query($sql, __FILE__, __LINE__);
 		$course_list = array();
 		if ($type=='single') {
-			
-			while($course = Database :: fetch_array($rs)) {	
+
+			while($course = Database :: fetch_array($rs)) {
 				$course_list[] = $course['code'];
-				$course_title=str_replace("'","\'",$course_title);					
+				$course_title=str_replace("'","\'",$course_title);
 				$return .= '<a href="javascript: void(0);" onclick="javascript: add_course_to_session(\''.$course['code'].'\',\''.$course_title.' ('.$course['visual_code'].')'.'\')">'.$course['title'].' ('.$course['visual_code'].')</a><br />';
 			}
-			
+
 			$xajax_response -> addAssign('ajax_list_courses_single','innerHTML',api_utf8_encode($return));
-			
+
 		} else {
-	
+
 			$return .= '<select id="origin" name="NoSessionCoursesList[]" multiple="multiple" size="20" style="width:340px;">';
-			while($course = Database :: fetch_array($rs)) {	
+			while($course = Database :: fetch_array($rs)) {
 				$course_list[] = $course['code'];
-				$course_title=str_replace("'","\'",$course_title);				
-				$return .= '<option value="'.$course['code'].'" title="'.htmlspecialchars($course['title'].' ('.$course['visual_code'].')',ENT_QUOTES).'">'.$course['title'].' ('.$course['visual_code'].')</option>';				
+				$course_title=str_replace("'","\'",$course_title);
+				$return .= '<option value="'.$course['code'].'" title="'.htmlspecialchars($course['title'].' ('.$course['visual_code'].')',ENT_QUOTES).'">'.$course['title'].' ('.$course['visual_code'].')</option>';
 			}
 			$return .= '</select>';
-			
-			$xajax_response -> addAssign('ajax_list_courses_multiple','innerHTML',api_utf8_encode($return));			
+
+			$xajax_response -> addAssign('ajax_list_courses_multiple','innerHTML',api_utf8_encode($return));
 		}
-	}	
-	$_SESSION['course_list'] = $course_list;	
+	}
+	$_SESSION['course_list'] = $course_list;
 	return $xajax_response;
 }
 $xajax -> processRequests();
@@ -162,20 +162,20 @@ function add_course_to_session (code, content) {
 
 	document.getElementById("course_to_add").value = "";
 	document.getElementById("ajax_list_courses_single").innerHTML = "";
-	
+
 	destination = document.getElementById("destination");
-	
+
 	for (i=0;i<destination.length;i++) {
 		if(destination.options[i].text == content) {
 				return false;
-		} 
-	}			
-			
-	destination.options[destination.length] = new Option(content,code);	
-	
+		}
+	}
+
+	destination.options[destination.length] = new Option(content,code);
+
 	destination.selectedIndex = -1;
-	sortOptions(destination.options);	
-}		
+	sortOptions(destination.options);
+}
 function remove_item(origin)
 {
 	for(var i = 0 ; i<origin.options.length ; i++) {
@@ -195,7 +195,7 @@ $courses=$sessions=array();
 $noPHP_SELF=true;
 
 if ($_POST['formSent']) {
-		
+
 	$formSent=$_POST['formSent'];
 	$firstLetterCourse=$_POST['firstLetterCourse'];
 	$firstLetterSession=$_POST['firstLetterSession'];
@@ -227,13 +227,13 @@ if ($_POST['formSent']) {
 				$exists=true;
 			}
 		}
-		if(!$exists) {			
+		if(!$exists) {
 			$sql_insert_rel_course= "INSERT INTO $tbl_session_rel_course(id_session,course_code, id_coach) VALUES('$id_session','$enreg_course','$id_coach')";
-			api_sql_query($sql_insert_rel_course ,__FILE__,__LINE__);			
+			api_sql_query($sql_insert_rel_course ,__FILE__,__LINE__);
 			//We add in the existing courses table the current course, to not try to add another time the current course
 			$existingCourses[]=array('course_code'=>$enreg_course);
 			$nbr_users=0;
-			foreach ($UserList as $enreg_user) {				
+			foreach ($UserList as $enreg_user) {
 				$enreg_user = Database::escape_string($enreg_user['id_user']);
 				$sql_insert = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$enreg_user')";
 				api_sql_query($sql_insert,__FILE__,__LINE__);
@@ -295,34 +295,34 @@ $count_courses = mysql_result($rs, 0, 0);*/
 $ajax_search = $add_type == 'unique' ? true : false;
 $nosessionCourses = $sessionCourses = array();
 if ($ajax_search) {
-	
+
 	$sql="SELECT code, title, visual_code, id_session
 			FROM $tbl_course course
 			INNER JOIN $tbl_session_rel_course session_rel_course
 				ON course.code = session_rel_course.course_code
 				AND session_rel_course.id_session = ".intval($id_session)."
 			ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
-	
+
 	global $_configuration;
-	if ($_configuration['multiple_access_urls']==true) {		
-		$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);	
+	if ($_configuration['multiple_access_urls']==true) {
+		$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 		$access_url_id = api_get_current_access_url_id();
 		if ($access_url_id != -1){
 			$sql="SELECT code, title, visual_code, id_session
 			FROM $tbl_course course
 			INNER JOIN $tbl_session_rel_course session_rel_course
 				ON course.code = session_rel_course.course_code
-				AND session_rel_course.id_session = ".intval($id_session)." 
+				AND session_rel_course.id_session = ".intval($id_session)."
 				INNER JOIN $tbl_course_rel_access_url url_course ON (url_course.course_code=course.code)
 				WHERE access_url_id = $access_url_id
 			ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
-						
-		}	
+
+		}
 	}
-							
-	$result=api_sql_query($sql,__FILE__,__LINE__);	
-	$Courses=api_store_result($result);	
-	
+
+	$result=api_sql_query($sql,__FILE__,__LINE__);
+	$Courses=api_store_result($result);
+
 	foreach($Courses as $course) {
 		$sessionCourses[$course['code']] = $course ;
 	}
@@ -333,10 +333,10 @@ if ($ajax_search) {
 				ON course.code = session_rel_course.course_code
 				AND session_rel_course.id_session = ".intval($id_session)."
 			ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
-						
+
 	global $_configuration;
-	if ($_configuration['multiple_access_urls']==true) {		
-		$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);	
+	if ($_configuration['multiple_access_urls']==true) {
+		$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 		$access_url_id = api_get_current_access_url_id();
 		if ($access_url_id != -1){
 			$sql="SELECT code, title, visual_code, id_session
@@ -345,12 +345,12 @@ if ($ajax_search) {
 					ON course.code = session_rel_course.course_code
 					AND session_rel_course.id_session = ".intval($id_session)."
 				INNER JOIN $tbl_course_rel_access_url url_course ON (url_course.course_code=course.code)
-				WHERE access_url_id = $access_url_id 
+				WHERE access_url_id = $access_url_id
 				ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
-		}	
+		}
 	}
 
-	$result=api_sql_query($sql,__FILE__,__LINE__);	
+	$result=api_sql_query($sql,__FILE__,__LINE__);
 	$Courses=api_store_result($result);
 	foreach($Courses as $course) {
 		if ($course['id_session'] == $id_session) {
@@ -358,8 +358,8 @@ if ($ajax_search) {
 		} else {
 			$nosessionCourses[$course['code']] = $course ;
 		}
-	}	
-}		
+	}
+}
 
 unset($Courses);
 
@@ -389,13 +389,13 @@ if(!empty($errorMsg))
 
 <?php if($add_type == 'multiple') { ?>
 <tr><td width="45%" align="center">
- <?php echo get_lang('FirstLetterCourse'); ?> : 
+ <?php echo get_lang('FirstLetterCourse'); ?> :
      <select name="firstLetterCourse" onchange = "xajax_search_courses(this.value,'multiple')">
       <option value="%">--</option>
       <?php
       echo Display :: get_alphabet_options();
       echo Display :: get_numeric_options(0,9,'');
-      ?> 
+      ?>
      </select>
 </td>
 <td>&nbsp;</td></tr>
@@ -406,14 +406,14 @@ if(!empty($errorMsg))
 
 <?php
 if(!($add_type == 'multiple')){
-	?>	
+	?>
 	<input type="text" id="course_to_add" onkeyup="xajax_search_courses(this.value,'single')" />
 	<div id="ajax_list_courses_single"></div>
 	<?php
 }
 else
 {
-	?> 
+	?>
 	<div id="ajax_list_courses_multiple">
 	<select id="origin" name="NoSessionCoursesList[]" multiple="multiple" size="20" style="width:320px;"> <?php
 	foreach($nosessionCourses as $enreg)
@@ -423,7 +423,7 @@ else
 		<?php
 	}
 	?>  </select></div> <?php
-}	
+}
 unset($nosessionCourses);
 ?>
 
@@ -441,8 +441,8 @@ unset($nosessionCourses);
   	<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 
-  } 
+  <?php
+  }
   ?>
 	<br /><br /><br /><br /><br /><br />
 	<?php
@@ -460,11 +460,11 @@ unset($nosessionCourses);
 
 <?php
 foreach($sessionCourses as $enreg)
-{	
-?>	
+{
+?>
 	<option value="<?php echo $enreg['code']; ?>" title="<?php echo htmlspecialchars($enreg['title'].' ('.$enreg['visual_code'].')',ENT_QUOTES); ?>"><?php echo $enreg['title'].' ('.$enreg['visual_code'].')'; ?></option>
 
-<?php 
+<?php
 }
 unset($sessionCourses);
 ?>
@@ -487,25 +487,25 @@ function moveItem(origin , destination){
 	}
 	destination.selectedIndex = -1;
 	sortOptions(destination.options);
-	
+
 
 }
 
 function sortOptions(options) {
 
 	newOptions = new Array();
-	
+
 	for (i = 0 ; i<options.length ; i++) {
-		newOptions[i] = options[i];							
+		newOptions[i] = options[i];
 	}
 
 	newOptions = newOptions.sort(mysort);
 	options.length = 0;
 
-	for(i = 0 ; i < newOptions.length ; i++){		
-		options[i] = newOptions[i];			
+	for(i = 0 ; i < newOptions.length ; i++){
+		options[i] = newOptions[i];
 	}
-	
+
 }
 
 function mysort(a, b){

+ 118 - 118
main/admin/add_users_to_session.php

@@ -71,22 +71,22 @@ if (is_array($extra_field_list)) {
 			$new_field_list[] = array('name'=> $extra_field[3], 'variable'=>$extra_field[1], 'data'=> $extra_field[9]);
 		}
 	}
-}	
-	
+}
+
 function search_users($needle,$type)
 {
 	global $tbl_user,$tbl_session_rel_user,$id_session;
 	$xajax_response = new XajaxResponse();
 	$return = '';
-		
+
 	if (!empty($needle) && !empty($type)) {
-		
+
 		// xajax send utf8 datas... datas in db can be non-utf8 datas
 		$charset = api_get_setting('platform_charset');
 		$needle = Database::escape_string($needle);
 		$needle = api_convert_encoding($needle, $charset, 'utf-8');
 		$user_anonymous=api_get_anonymous_id();
-		
+
 		$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
 		$cond_user_id = '';
 		if (!empty($id_session)) {
@@ -97,14 +97,14 @@ function search_users($needle,$type)
 			$user_ids = array();
 			if (Database::num_rows($res) > 0) {
 				while ($row = Database::fetch_row($res)) {
-					$user_ids[] = (int)$row[0];  
+					$user_ids[] = (int)$row[0];
 				}
 			}
-			if (count($user_ids) > 0){	
+			if (count($user_ids) > 0){
 				$cond_user_id = ' AND user_id NOT IN('.implode(",",$user_ids).')';
-			}				
-		} 
-		
+			}
+		}
+
 		if ($type == 'single') {
 			// search users where username or firstname or lastname begins likes $needle
 			$sql = 'SELECT user_id, username, lastname, firstname FROM '.$tbl_user.' user
@@ -113,19 +113,19 @@ function search_users($needle,$type)
 				OR lastname LIKE "'.$needle.'%") AND user_id<>"'.$user_anonymous.'"'.
 				$order_clause.
 				' LIMIT 11';
-		} else {						
+		} else {
 			$sql = 'SELECT user_id, username, lastname, firstname FROM '.$tbl_user.' user
 					WHERE '.(api_sort_by_first_name() ? 'firstname' : 'lastname').' LIKE "'.$needle.'%" AND user_id<>"'.$user_anonymous.'"'.$cond_user_id.
 					$order_clause;
 		}
-				
-		global $_configuration;	
-		if ($_configuration['multiple_access_urls']==true) {		
-			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+
+		global $_configuration;
+		if ($_configuration['multiple_access_urls']==true) {
+			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 			$access_url_id = api_get_current_access_url_id();
 			if ($access_url_id != -1){
-				if ($type == 'single') {		
-					$sql = 'SELECT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user 
+				if ($type == 'single') {
+					$sql = 'SELECT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user
 					INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
 					WHERE access_url_id = '.$access_url_id.'  AND (username LIKE "'.$needle.'%"
 					OR firstname LIKE "'.$needle.'%"
@@ -133,19 +133,19 @@ function search_users($needle,$type)
 					$order_clause.
 					' LIMIT 11';
 				} else {
-					$sql = 'SELECT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user 
+					$sql = 'SELECT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user
 					INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
-					WHERE access_url_id = '.$access_url_id.'  
+					WHERE access_url_id = '.$access_url_id.'
 					AND '.(api_sort_by_first_name() ? 'firstname' : 'lastname').' LIKE "'.$needle.'%" AND user.user_id<>"'.$user_anonymous.'"'.$cond_user_id.
-					$order_clause;					
-				}				
-				
+					$order_clause;
+				}
+
 			}
 		}
-				
-		$rs = api_sql_query($sql, __FILE__, __LINE__);		
-        $i=0;		
-		if ($type=='single') {			
+
+		$rs = api_sql_query($sql, __FILE__, __LINE__);
+        $i=0;
+		if ($type=='single') {
 			while ($user = Database :: fetch_array($rs)) {
 	            $i++;
 	            if ($i<=10) {
@@ -155,15 +155,15 @@ function search_users($needle,$type)
 	            	$return .= '...<br />';
 	            }
 			}
-			
+
 			$xajax_response -> addAssign('ajax_list_users_single','innerHTML',api_utf8_encode($return));
-				
+
 		} else {
 			global $nosessionUsersList;
 			$return .= '<select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;">';
-			while ($user = Database :: fetch_array($rs)) {				
+			while ($user = Database :: fetch_array($rs)) {
 				$person_name = api_get_person_name($user['firstname'], $user['lastname']);
-	            $return .= '<option value="'.$user['user_id'].'">'.$person_name.' ('.$user['username'].')</option>';				     	            
+	            $return .= '<option value="'.$user['user_id'].'">'.$person_name.' ('.$user['username'].')</option>';
 			}
 			$return .= '</select>';
 			$xajax_response -> addAssign('ajax_list_users_multiple','innerHTML',api_utf8_encode($return));
@@ -182,19 +182,19 @@ function add_user_to_session (code, content) {
 
 	document.getElementById("user_to_add").value = "";
 	document.getElementById("ajax_list_users_single").innerHTML = "";
-	
+
 	destination = document.getElementById("destination_users");
-			
+
 	for (i=0;i<destination.length;i++) {
 		if(destination.options[i].text == content) {
 				return false;
-		} 
-	}		
-			
-	destination.options[destination.length] = new Option(content,code);	
+		}
+	}
+
+	destination.options[destination.length] = new Option(content,code);
 	destination.selectedIndex = -1;
 	sortOptions(destination.options);
-	
+
 }
 function remove_item(origin)
 {
@@ -207,15 +207,15 @@ function remove_item(origin)
 }
 
 function validate_filter() {
-	
+
 		document.formulaire.add_type.value = \''.$add_type.'\';
-		document.formulaire.form_sent.value=0;				
+		document.formulaire.form_sent.value=0;
 		document.formulaire.submit();
-		
+
 }
-			
 
-	
+
+
 </script>';
 
 
@@ -236,18 +236,18 @@ if($_POST['form_sent']) {
 	}
 
 	if ($form_sent == 1) {
-		
+
 		SessionManager::suscribe_users_to_session($id_session,$UserList,true);
-		
+
 		//adding the session to the access_url_rel_session table
 		global $_configuration;
-		require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');	
-		if ($_configuration['multiple_access_urls']==true) {			
-			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
-			$access_url_id = api_get_current_access_url_id();			
-			UrlManager::add_session_to_url($id_session,$access_url_id);			
+		require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
+		if ($_configuration['multiple_access_urls']==true) {
+			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+			$access_url_id = api_get_current_access_url_id();
+			UrlManager::add_session_to_url($id_session,$access_url_id);
 		} else {
-			// we are filling by default the access_url_rel_session table 
+			// we are filling by default the access_url_rel_session table
 			UrlManager::add_session_to_url($id_session,1);
 		}
 		//if(empty($_GET['add']))
@@ -267,7 +267,7 @@ $nosessionUsersList = $sessionUsersList = array();
 $rs = api_sql_query($sql, __FILE__, __LINE__);
 $count_courses = Database::result($rs, 0, 0);*/
 $ajax_search = $add_type == 'unique' ? true : false;
-global $_configuration;	
+global $_configuration;
 
 $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
 if ($ajax_search) {
@@ -278,107 +278,107 @@ if ($ajax_search) {
 				AND $tbl_session_rel_user.id_session = ".intval($id_session).
 			$order_clause;
 
-	if ($_configuration['multiple_access_urls']==true) {		
-		$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+	if ($_configuration['multiple_access_urls']==true) {
+		$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1){				
+		if ($access_url_id != -1){
 			$sql="SELECT u.user_id, lastname, firstname, username, id_session
-			FROM $tbl_user u 
+			FROM $tbl_user u
 			INNER JOIN $tbl_session_rel_user
 				ON $tbl_session_rel_user.id_user = u.user_id
 				AND $tbl_session_rel_user.id_session = ".intval($id_session)."
-				INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id) 
-				WHERE access_url_id = $access_url_id  
+				INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id)
+				WHERE access_url_id = $access_url_id
 				$order_clause";
 		}
-	}		
-	$result=api_sql_query($sql,__FILE__,__LINE__);	
-	$Users=api_store_result($result);	
+	}
+	$result=api_sql_query($sql,__FILE__,__LINE__);
+	$Users=api_store_result($result);
 	foreach ($Users as $user) {
 		$sessionUsersList[$user['user_id']] = $user ;
 	}
 
 } else {
 		//Filter by Extra Fields
-		$use_extra_fields = false;		
+		$use_extra_fields = false;
 		if (is_array($extra_field_list)) {
-			if (is_array($new_field_list) && count($new_field_list)>0 ) {			
+			if (is_array($new_field_list) && count($new_field_list)>0 ) {
 				$result_list=array();
 				foreach ($new_field_list as $new_field) {
-					$varname = 'field_'.$new_field['variable'];				
+					$varname = 'field_'.$new_field['variable'];
 					if (Usermanager::is_extra_field_available($new_field['variable'])) {
-						if (isset($_POST[$varname]) && $_POST[$varname]!='0') {		
-							$use_extra_fields = true;																	
+						if (isset($_POST[$varname]) && $_POST[$varname]!='0') {
+							$use_extra_fields = true;
 							$extra_field_result[]= Usermanager::get_extra_user_data_by_value($new_field['variable'], $_POST[$varname]);
-						}								
+						}
 					}
-				}									
+				}
 			}
-		}	
+		}
 		if ($use_extra_fields) {
 			$final_result = array();
 			if (count($extra_field_result)>1) {
 				for($i=0;$i<count($extra_field_result)-1;$i++) {
 					if (is_array($extra_field_result[$i+1])) {
-						$final_result  = array_intersect($extra_field_result[$i],$extra_field_result[$i+1]);				
+						$final_result  = array_intersect($extra_field_result[$i],$extra_field_result[$i+1]);
 					}
 				}
-			} else {				
+			} else {
 				$final_result = $extra_field_result[0];
 			}
-					
+
 			$where_filter ='';
 			if ($_configuration['multiple_access_urls']==true) {
 				if (is_array($final_result) && count($final_result)>0) {
 					$where_filter = " AND u.user_id IN  ('".implode("','",$final_result)."') ";
 				} else {
 					//no results
-					$where_filter = " AND u.user_id  = -1"; 
+					$where_filter = " AND u.user_id  = -1";
 				}
-			} else {			
+			} else {
 				if (is_array($final_result) && count($final_result)>0) {
 					$where_filter = " WHERE u.user_id IN  ('".implode("','",$final_result)."') ";
 				} else {
 					//no results
-					$where_filter = " WHERE u.user_id  = -1"; 
+					$where_filter = " WHERE u.user_id  = -1";
 				}
-			}		
+			}
 		}
-		
-		if ($use_extra_fields) {		
+
+		if ($use_extra_fields) {
 			$sql="SELECT  user_id, lastname, firstname, username, id_session
 				FROM $tbl_user u
 				LEFT JOIN $tbl_session_rel_user
 				ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'
 				$where_filter
 			$order_clause";
-				
+
 		} else {
 			$sql="SELECT  user_id, lastname, firstname, username, id_session
 				FROM $tbl_user u
 				LEFT JOIN $tbl_session_rel_user
-				ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session' 
+				ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'
 			$order_clause";
-		}			
-		if ($_configuration['multiple_access_urls']==true) {		
-			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+		}
+		if ($_configuration['multiple_access_urls']==true) {
+			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1){				
+			if ($access_url_id != -1){
 				$sql="SELECT  u.user_id, lastname, firstname, username, id_session
 				FROM $tbl_user u
 				LEFT JOIN $tbl_session_rel_user
-					ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'			 
-				INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id) 
+					ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'
+				INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id)
 				WHERE access_url_id = $access_url_id  $where_filter
-			$order_clause";			
+			$order_clause";
 			}
 		}
-		
-		$result=api_sql_query($sql,__FILE__,__LINE__);	
+
+		$result=api_sql_query($sql,__FILE__,__LINE__);
 		$Users=api_store_result($result);
 		//var_dump($_REQUEST['id_session']);
 		foreach ($Users as $user) {
-			if($user['id_session'] != $id_session)			
+			if($user['id_session'] != $id_session)
 				$nosessionUsersList[$user['user_id']] = $user ;
 		}
 		$user_anonymous=api_get_anonymous_id();
@@ -391,23 +391,23 @@ if ($ajax_search) {
 		$sql="SELECT  user_id, lastname, firstname, username, id_session
 			FROM $tbl_user u
 			LEFT JOIN $tbl_session_rel_user
-			ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session' 
+			ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'
 			$order_clause";
-		
-		if ($_configuration['multiple_access_urls']==true) {		
-			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+
+		if ($_configuration['multiple_access_urls']==true) {
+			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1){				
+			if ($access_url_id != -1){
 				$sql="SELECT  u.user_id, lastname, firstname, username, id_session
 				FROM $tbl_user u
 				LEFT JOIN $tbl_session_rel_user
-					ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'			 
-				INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id) 
+					ON $tbl_session_rel_user.id_user = u.user_id AND id_session = '$id_session'
+				INNER JOIN $tbl_user_rel_access_url url_user ON (url_user.user_id=u.user_id)
 				WHERE access_url_id = $access_url_id
-				$order_clause";			
+				$order_clause";
 			}
-		}		
-	$result=api_sql_query($sql,__FILE__,__LINE__);	
+		}
+	$result=api_sql_query($sql,__FILE__,__LINE__);
 	$Users=api_store_result($result);
 
 	foreach($Users as $key_user_list =>$value_user_list) {
@@ -415,7 +415,7 @@ if ($ajax_search) {
 			unset($Users[$key_user_list]);
 			}
 		}
-		
+
 	foreach ($Users as $user) {
 		if($user['id_session'] == $id_session){
 			$sessionUsersList[$user['user_id']] = $user;
@@ -446,30 +446,30 @@ if ($add_type == 'multiple') {
 <form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?page=<?php echo Security::remove_XSS($_GET['page']); ?>&id_session=<?php echo $id_session; ?><?php if(!empty($_GET['add'])) echo '&add=true' ; ?>" style="margin:0px;" <?php if($ajax_search){echo ' onsubmit="valide();"';}?>>
 
 <?php
-if ($add_type=='multiple') {	
+if ($add_type=='multiple') {
 	if (is_array($extra_field_list)) {
 		if (is_array($new_field_list) && count($new_field_list)>0 ) {
 			echo '<h3>'.get_lang('FilterUsers').'</h3>';
 			foreach ($new_field_list as $new_field) {
 				echo $new_field['name'];
-				$varname = 'field_'.$new_field['variable'];						
+				$varname = 'field_'.$new_field['variable'];
 				echo '&nbsp;<select name="'.$varname.'">';
-				echo '<option value="0">--'.get_lang('Select').'--</option>';	
+				echo '<option value="0">--'.get_lang('Select').'--</option>';
 				foreach	($new_field['data'] as $option) {
 					$checked='';
 					if (isset($_POST[$varname])) {
 						if ($_POST[$varname]==$option[1]) {
-							$checked = 'selected="true"'; 
+							$checked = 'selected="true"';
 						}
-					}							
-					echo '<option value="'.$option[1].'" '.$checked.'>'.$option[1].'</option>';		
+					}
+					echo '<option value="'.$option[1].'" '.$checked.'>'.$option[1].'</option>';
 				}
-				echo '</select>';	
+				echo '</select>';
 				echo '&nbsp;&nbsp;';
 			}
 			echo '<input type="button" value="'.get_lang('Filter').'" onclick="validate_filter()" />';
 			echo '<br /><br />';
-		}	
+		}
 	}
 }
 ?>
@@ -496,11 +496,11 @@ if(!empty($errorMsg)) {
 <tr>
 <td align="center">
 
-<?php echo get_lang('FirstLetterUser'); ?> : 
+<?php echo get_lang('FirstLetterUser'); ?> :
      <select name="firstLetterUser" onchange = "xajax_search_users(this.value,'multiple')" >
       <option value = "%">--</option>
       <?php
-        echo Display :: get_alphabet_options();        
+        echo Display :: get_alphabet_options();
       ?>
      </select>
 </td>
@@ -519,15 +519,15 @@ if(!empty($errorMsg)) {
 		<div id="ajax_list_users_single"></div>
 		<?php
   	  } else {
-  	  ?>  	
-  	  <div id="ajax_list_users_multiple">    	 	  
+  	  ?>
+  	  <div id="ajax_list_users_multiple">
 	  <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;">
 		<?php
 		foreach($nosessionUsersList as $enreg) {
-		?>			
+		?>
 			<option value="<?php echo $enreg['user_id']; ?>" <?php if(in_array($enreg['user_id'],$UserList)) echo 'selected="selected"'; ?>><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']).' ('.$enreg['username'].')'; ?></option>
 		<?php
-		}	
+		}
 		?>
 	  </select>
 	  </div>
@@ -548,8 +548,8 @@ if(!empty($errorMsg)) {
   	<button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))"></button>
 	<br /><br />
 	<button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))"></button>
-	<?php 
-  } 
+	<?php
+  }
   ?>
 	<br /><br /><br /><br /><br /><br />
   </td>
@@ -577,8 +577,8 @@ unset($sessionUsersList);
 			echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('FinishSessionCreation').'</button>';
         } else {
             //@todo see that the call to "valide()" doesn't duplicate the onsubmit of the form (necessary to avoid delete on "enter" key pressed)
-			echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('SubscribeUsersToSession').'</button>'; 
-			
+			echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('SubscribeUsersToSession').'</button>';
+
         }
 		?>
 	</td>

+ 135 - 135
main/admin/calendar.lib.php

@@ -4,7 +4,7 @@
 ==============================================================================
 *	@package dokeos.admin
 *	@author Carlos Vargas
-*	This file is the calendar/agenda.inc.php 
+*	This file is the calendar/agenda.inc.php
 ==============================================================================
 */
 
@@ -187,7 +187,7 @@ function move(fbox,	tbox)
 
 function checkDate(month, day, year)
 {
-  var monthLength = 
+  var monthLength =
     new Array(31,28,31,30,31,30,31,31,30,31,30,31);
 
   if (!day || !month || !year)
@@ -202,14 +202,14 @@ function checkDate(month, day, year)
 
   if (day > monthLength[month-1])
     return false;
-  
+
   return true;
-}		
+}
 
-function mktime() 
-{		    
+function mktime()
+{
     var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
-    d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972); 
+    d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);
     var dateManip = {
         0: function(tt){ return d.setHours(tt); },
         1: function(tt){ return d.setMinutes(tt); },
@@ -217,7 +217,7 @@ function mktime()
         3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
         4: function(tt){ return d.setDate(tt+mb); },
         5: function(tt){ return d.setYear(tt+ma); }
-    };    
+    };
     for( i = 0; i < argc; i++ ){
         no = parseInt(argv[i]*1);
         if (isNaN(no)) {
@@ -229,10 +229,10 @@ function mktime()
                 return false;
             }
         }
-    } 
+    }
     return Math.floor(d.getTime()/1000);
-}		
-		
+}
+
 function validate()
 {
 	var	f =	document.new_calendar_item;
@@ -241,45 +241,45 @@ function validate()
 }
 
 function validate_date()
-{		
+{
 		var start_day = document.new_calendar_item.fday.value;
 		var start_month = document.new_calendar_item.fmonth.value;
-		var start_year = document.new_calendar_item.fyear.value;		
-		var start_hour = document.new_calendar_item.fhour.value;		
+		var start_year = document.new_calendar_item.fyear.value;
+		var start_hour = document.new_calendar_item.fhour.value;
 		var start_minute = document.new_calendar_item.fminute.value;
 		var start_date = mktime(start_hour,start_minute,0,start_month,start_day,start_year)
-				
+
 		var ends_day = document.new_calendar_item.end_fday.value;
 		var ends_month = document.new_calendar_item.end_fmonth.value;
-		var ends_year = document.new_calendar_item.end_fyear.value;		
-		var ends_hour = document.new_calendar_item.end_fhour.value;		
+		var ends_year = document.new_calendar_item.end_fyear.value;
+		var ends_hour = document.new_calendar_item.end_fhour.value;
 		var ends_minute = document.new_calendar_item.end_fminute.value;
-		var ends_date = mktime(ends_hour,ends_minute,0,ends_month,ends_day,ends_year)		
-		
+		var ends_date = mktime(ends_hour,ends_minute,0,ends_month,ends_day,ends_year)
+
 		msg_err1 = document.getElementById(\"err_date\");
 		msg_err2 = document.getElementById(\"err_start_date\");
 		msg_err3 = document.getElementById(\"err_end_date\");
 		msg_err4 = document.getElementById(\"err_title\");
-											
-		if (start_date > ends_date) {			 
-			msg_err1.style.display =\"block\"; 
+
+		if (start_date > ends_date) {
+			msg_err1.style.display =\"block\";
 			msg_err1.innerHTML=\"".get_lang('EndDateCannotBeBeforeTheStartDate')."\";
-			msg_err2.innerHTML=\"\";msg_err3.innerHTML=\"\";												
+			msg_err2.innerHTML=\"\";msg_err3.innerHTML=\"\";
 		} else if (checkDate(start_month,start_day,start_year) == false) {
 			msg_err2.style.display =\"block\";
 			msg_err2.innerHTML=\"".get_lang('InvalidDate')."\";
-			msg_err1.innerHTML=\"\";msg_err3.innerHTML=\"\";			 					
+			msg_err1.innerHTML=\"\";msg_err3.innerHTML=\"\";
 		} else if (checkDate(ends_month,ends_day,ends_year) == false) {
 			msg_err3.style.display =\"block\";
 			msg_err3.innerHTML=\"".get_lang('InvalidDate')."\";
-			msg_err1.innerHTML=\"\";msg_err2.innerHTML=\"\";			 					
+			msg_err1.innerHTML=\"\";msg_err2.innerHTML=\"\";
 		} else if (document.new_calendar_item.title.value == '') {
 			msg_err4.style.display =\"block\";
 			msg_err4.innerHTML=\"".get_lang('FieldRequired')."\";
-			msg_err1.innerHTML=\"\";msg_err2.innerHTML=\"\";msg_err3.innerHTML=\"\";			 					
+			msg_err1.innerHTML=\"\";msg_err2.innerHTML=\"\";msg_err3.innerHTML=\"\";
 		}  else {
 			document.new_calendar_item.submit();
-		}			
+		}
 
 }
 //	End	-->
@@ -412,22 +412,22 @@ function store_new_agenda_item()
 	global $_user /*, $_course*/;
 	$TABLEAGENDA = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
     //$t_agenda_repeat = Database::get_course_Table(TABLE_AGENDA_REPEAT);
-	
+
 	// some filtering of the input data
 	$title=strip_tags(trim($_POST['title'])); // no html allowed in the title
 	$content=trim($_POST['content']);
 	$start_date=(int)$_POST['fyear']."-".(int)$_POST['fmonth']."-".(int)$_POST['fday']." ".(int)$_POST['fhour'].":".(int)$_POST['fminute'].":00";
     $end_date=(int)$_POST['end_fyear']."-".(int)$_POST['end_fmonth']."-".(int)$_POST['end_fday']." ".(int)$_POST['end_fhour'].":".(int)$_POST['end_fminute'].":00";
-	 
+
 	// store in the table calendar_event
 	 $sql = "INSERT INTO ".$TABLEAGENDA."
 					        (title,content, start_date, end_date)
 					        VALUES
 					        ('".$title."','".$content."', '".$start_date."','".$end_date."')";
-	
+
 	$result = api_sql_query($sql,__FILE__,__LINE__) or die (Database::error());
 	$last_id=Database::insert_id();
-	
+
 	// store in last_tooledit (first the groups, then the users
 	$to=$_POST['selectedform'];
 	/*	if ((!is_null($to))or (!empty($_SESSION['toolgroup']))) // !is_null($to): when no user is selected we send it to everyone
@@ -454,10 +454,10 @@ function store_new_agenda_item()
 	{
 		api_item_property_update($_course, TOOL_CALENDAR_EVENT, $last_id,"AgendaAdded", $_user['user_id'], '','',$start_date,$end_date);
 	}*/
-	
+
 // storing the resources
 	//store_resources($_SESSION['source_type'],$last_id);
-    
+
     //if repetitive, insert element into agenda_repeat table
 /*    if(!empty($_POST['repeat']) && !empty($_POST['repeat_type']))
     {
@@ -469,8 +469,8 @@ function store_new_agenda_item()
             $end = mktime((int)$_POST['fhour'],(int)$_POST['fminute'],0,$end_m,$end_d,$end_y);
             $now = time();
             $type = Database::escape_string($_POST['repeat_type']);
-        
-        	if($end > $now 
+
+        	if($end > $now
                 && in_array($type,array('daily','weekly','monthlyByDate','monthlyByDay','monthlyByDayR','yearly')))
             {
         	   $sql = "INSERT INTO $t_agenda_repeat (cal_id, cal_type, cal_end)" .
@@ -500,12 +500,12 @@ function display_student_links()
 	else
 	{
 		echo "<a href='".api_get_self()."?sort=desc&amp;origin=".$_GET['origin']."'>".Display::return_icon('calendar_down.gif',get_lang('AgendaSortChronologicallyDown')).' '.get_lang("AgendaSortChronologicallyDown")."</a>";
-	}	
+	}
 	if ($_SESSION['view'] <> 'month')
 	{
 		echo "\t<a href=\"".api_get_self()."?action=view&amp;view=month\"><img src=\"../img/calendar_month.gif\" border=\"0\" alt=\"".get_lang('MonthView')."\" /> ".get_lang('MonthView')."</a>\n";
 	}
-	else 
+	else
 	{
 		echo "\t<a href=\"".api_get_self()."?action=view&amp;view=list\"><img src=\"../img/calendar_select.gif\" border=\"0\" alt=\"".get_lang('ListView')."\" /> ".get_lang('ListView')."</a>\n";
 	}
@@ -588,7 +588,7 @@ function save_edit_agenda_item($id,$title,$content,$start_date,$end_date)
 		$content=Database::escape_string($content);
 		$start_date=Database::escape_string($start_date);
 		$end_date=Database::escape_string($end_date);
-					
+
 
 	// store the modifications in the table calendar_event
 	$sql = "UPDATE ".$TABLEAGENDA."
@@ -632,7 +632,7 @@ function delete_agenda_item($id)
 			echo '<br />';
 			Display::display_normal_message(get_lang("AgendaDeleteSuccess"));
 		}
-	} 
+	}
 
 }
 /**
@@ -709,14 +709,14 @@ function display_agenda_items()
 	}
 
 	// by default we use the id of the current user. The course administrator can see the agenda of other users by using the user / group filter
-    
+
     $repeats = array(); //placeholder for repeated events
 
 	if (is_allowed_to_edit() && !api_is_anonymous()) {
 		$sql="SELECT * FROM ".$TABLEAGENDA.' ORDER BY start_date '.$_SESSION['sort'];
 		//echo "<pre>".$sql."</pre>";
 		$result=api_sql_query($sql,__FILE__,__LINE__) or die(Database::error());
-		$number_items=Database::num_rows($result);		
+		$number_items=Database::num_rows($result);
 	} else {
 		$number_items = 0;
 	}
@@ -901,8 +901,8 @@ function display_agenda_items()
 				echo ' "> '.$user_filename.' </a>';
 				echo '<span class="forum_attach_comment" >'.$attachment_list['comment'].'</span>';
 				if (api_is_allowed_to_edit()) {
-					echo '&nbsp;&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;origin='.Security::remove_XSS($_GET['origin']).'&amp;action=delete_attach&amp;id_attach='.$attachment_list['id'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.gif',get_lang('Delete')).'</a><br />';	
-				}				
+					echo '&nbsp;&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;origin='.Security::remove_XSS($_GET['origin']).'&amp;action=delete_attach&amp;id_attach='.$attachment_list['id'].'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset)).'\')) return false;">'.Display::return_icon('delete.gif',get_lang('Delete')).'</a><br />';
+				}
 
 			}
 
@@ -984,7 +984,7 @@ function display_one_agenda_item($agenda_id)
 	$result=api_sql_query($sql,__FILE__,__LINE__) or die(Database::error());
 	$number_items=Database::num_rows($result);
 	$myrow=Database::fetch_array($result); // there should be only one item so no need for a while loop
-    
+
     $sql_rep = "SELECT * FROM $TABLEAGENDA WHERE id = $agenda_id";
     $res_rep = Database::query($sql_rep,__FILE__,__LINE__);
     $repeat = false;
@@ -993,9 +993,9 @@ function display_one_agenda_item($agenda_id)
     {
         $repeat=true;
         $row_rep = Database::fetch_array($res_rep);
-        //$repeat_id = $row_rep['parent_event_id']; 
+        //$repeat_id = $row_rep['parent_event_id'];
     }
-    
+
 	/*--------------------------------------------------
 			DISPLAY: NO ITEMS
 	  --------------------------------------------------*/
@@ -1322,7 +1322,7 @@ function show_add_form($id = '')
 <input type="hidden" name="action" value="<?php if (isset($_GET['action'])) echo $_GET['action']; ?>" />
 <input type="hidden" name="sort" value="asc" />
 <input type="hidden" name="submit_event" value="ok" />
-<?php 
+<?php
 	echo '<div class="row"><div class="form_header">';
 	echo (isset($id) AND $id<>'')?get_lang('ModifyCalendarItem'):get_lang("AddCalendarItem");
 	echo '</div></div>';
@@ -1334,10 +1334,10 @@ function show_add_form($id = '')
 <table border="0" width="80%">
 				<tr><td colspan="4">
 					<div id="err_date" style="display:none;color:red"></div>
-					<div id="err_start_date" style="display:none;color:red"></div>					
+					<div id="err_start_date" style="display:none;color:red"></div>
 				</td></tr>
-				<td width="10%">	
-					<!-- date: 1 -> 31 -->					
+				<td width="10%">
+					<!-- date: 1 -> 31 -->
 					<nobr><?php echo get_lang('StartDate').": \n"; ?></nobr>
 				</td>
 				<td width="35%">
@@ -1400,10 +1400,10 @@ function show_add_form($id = '')
 					</select>
 					<a href="javascript:openCalendar('new_calendar_item','f')"><?php Display::display_icon('calendar_select.gif', get_lang('Select'), array ('style' => 'vertical-align: middle;')); ?></a>
 					</td>
-					<td width="10%">	
+					<td width="10%">
 						<nobr><?php echo get_lang('StartTime').": \n"; ?></nobr>
 					</td>
-					<td>					
+					<td>
 						<select name="fhour" onchange="javascript:document.new_calendar_item.end_fhour.value=this.value;">
 							<!-- <option value="--">--</option> -->
 							<?php
@@ -1423,7 +1423,7 @@ function show_add_form($id = '')
 									}
 								} ?>
 						</select>
-						
+
 						<select name="fminute" onchange="javascript:document.new_calendar_item.end_fminute.value=this.value;">
 							<!-- <option value="<?php echo $minutes ?>"><?php echo $minutes; ?></option> -->
 							<!-- <option value="--">--</option> -->
@@ -1443,8 +1443,8 @@ function show_add_form($id = '')
 <tr>
 <div>
 					<tr><td colspan="4"><div id="err_end_date" style="display:none;color:red"></div></td></tr>
-					<td >			
-							<!-- date: 1 -> 31 -->							
+					<td >
+							<!-- date: 1 -> 31 -->
 							<nobr><?php echo get_lang('EndDate').": "; ?></nobr>
 					</td>
 					<td  >
@@ -1477,7 +1477,7 @@ function show_add_form($id = '')
 									else
 										{ echo "\t\t\t\t <option value=\"".$value."\">".$MonthsLong[$i-1]."</option>\n"; }
 									}?>
-						</select>			
+						</select>
 						<select name="end_fyear">
 								<option value="<?php echo ($end_year-1) ?>"><?php echo ($end_year-1) ?></option>
 								<option value="<?php echo $end_year ?>" selected> <?php echo $end_year ?> </option>
@@ -1510,7 +1510,7 @@ function show_add_form($id = '')
 										{ echo "\t\t\t\t<option value=\"".$value."\"> ".$value." </option>\n"; }
 								} ?>
 						</select>
-						
+
 						<select name="end_fminute">
 							<!-- <option value="<?php echo $end_minutes; ?>"><?php echo $end_minutes; ?></option> -->
 							<!-- <option value="--">--</option> -->
@@ -1528,7 +1528,7 @@ function show_add_form($id = '')
 </tr>
 <tr><td colspan="4">
 <hr noshade="noshade" color="#cccccc" />
-	<div id="err_title" style="display:none;color:red"></div>										
+	<div id="err_title" style="display:none;color:red"></div>
 </td></tr>
 <tr class="subtitle">
 		<td colspan="4" valign="top"><?php echo get_lang('ItemTitle'); ?> :
@@ -1545,7 +1545,7 @@ function show_add_form($id = '')
 
 			$oFCKeditor = new FCKeditor('content') ;
 
-			$oFCKeditor->ToolbarSet = 'GlobalAgenda';		
+			$oFCKeditor->ToolbarSet = 'GlobalAgenda';
 			$oFCKeditor->Width		= '100%';
 			$oFCKeditor->Height		= '175';
 			$oFCKeditor->Value		= $content;
@@ -1579,27 +1579,27 @@ function show_add_form($id = '')
     if(empty($id)) //only show repeat fields when adding the first time
     {
 	?>
-    
+
     <tr>
-      <td colspan="4" />      
+      <td colspan="4" />
     </tr>
     <?php
     }//only show repeat fields if adding, not if editing
     ?>
 	<tr>
 		<td colspan="4">
-		<?php 
+		<?php
 		if ($_GET['action']=='edit'){
 			$class='save';
 			$text=get_lang('ModifyEvent');
-			
+
 		}else{
 			$class='add';
 			$text=get_lang('AddEvent');
 		}
 		?>
 		<button type="button" class="add" value="<?php echo get_lang('Ok'); ?>" onclick="validate_date()" ><?php echo $text;  ?></button>
-		
+
 		</td>
 	</tr>
 </table>
@@ -1627,8 +1627,8 @@ function get_agendaitems($month, $year)
 		//echo "course admin";
 		$sqlquery = "SELECT
 						DISTINCT *
-						FROM ".$TABLEAGENDA."							 
-						WHERE 
+						FROM ".$TABLEAGENDA."
+						WHERE
 						MONTH(start_date)='".$month."'
 						AND YEAR(start_date)='".$year."'
 						GROUP BY id
@@ -1653,7 +1653,7 @@ function get_agendaitems($month, $year)
 			$sqlquery = "SELECT
 							agenda.*, item_property.*
 							FROM ".$TABLEAGENDA."
-							WHERE 
+							WHERE
 							MONTH(agenda.start_date)='".$month."'
 							AND YEAR(agenda.start_date)='".$year."'
 							ORDER BY start_date ";
@@ -1663,22 +1663,22 @@ function get_agendaitems($month, $year)
 	//$mycourse = api_get_course_info();
 	$portal_url = $_configuration['root_web'];
 	if ($_configuration['multiple_access_urls']==true) {
-		$access_url_id = api_get_current_access_url_id();				
+		$access_url_id = api_get_current_access_url_id();
 		if ($access_url_id != -1 ){
 			$url = api_get_access_url($access_url_id);
 			$portal_url = $url['url'];
 		}
 	}
-			
+
     $result = api_sql_query($sqlquery, __FILE__, __LINE__);
 	while ($item = Database::fetch_array($result))
 	{
 		$agendaday = date('j',strtotime($item['start_date']));
-		$time= date('H:i',strtotime($item['start_date']));		
+		$time= date('H:i',strtotime($item['start_date']));
 		$URL = $portal_url.'main/admin/agenda.php?day='.$agendaday."&amp;month=".$month."&amp;year=".$year; // RH  //Patrick Cool: to highlight the relevant agenda item
 		$items[$agendaday][$item['start_time']] .= '<i>'.$time.'</i> <a href="'.$URL.'" title="'.$item['title'].'<br />';
 	}
-		
+
 	// sorting by hour for every day
 	$agendaitems = array ();
 	while (list ($agendaday, $tmpitems) = each($items))
@@ -1696,7 +1696,7 @@ function display_upcoming_events()
 {
 	echo '<b>'.get_lang('UpcomingEvent').'</b><br />';
 	$number_of_items_to_show = (int)api_get_setting('number_of_upcoming_events');
-	
+
 	//databases of the courses
 	$TABLEAGENDA = Database :: get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
 	//$TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
@@ -1716,7 +1716,7 @@ function display_upcoming_events()
 	// if the user is not an administrator of that course
 	$result = api_sql_query($sqlquery, __FILE__, __LINE__);
 	$counter = 0;
-	while ($item = Database::fetch_array($result,'ASSOC'))	
+	while ($item = Database::fetch_array($result,'ASSOC'))
 	{
 		if ($counter < $number_of_items_to_show)
 		{
@@ -1837,7 +1837,7 @@ function display_daycalendar($agendaitems, $day, $month, $year, $weekdaynames, $
 }
 /**
  *	Display the weekly view of the calendar
- */ 
+ */
 function display_weekcalendar($agendaitems, $month, $year, $weekdaynames, $monthName)
 {
 	global $DaysShort,$course_path;
@@ -1948,8 +1948,8 @@ function get_day_agendaitems($courses_dbs, $month, $year, $day)
 		{
 			//echo "course admin";
 			$sqlquery = "SELECT DISTINCT *
-										FROM ".$TABLEAGENDA." 
-										WHERE 
+										FROM ".$TABLEAGENDA."
+										WHERE
 										DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
 										GROUP BY agenda.id
 										ORDER BY start_date ";
@@ -1962,8 +1962,8 @@ function get_day_agendaitems($courses_dbs, $month, $year, $day)
 			{
 				$sqlquery = "SELECT
 													agenda.*
-													FROM ".$TABLEAGENDA." 
-													WHERE 
+													FROM ".$TABLEAGENDA."
+													WHERE
 													DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
 													ORDER BY start_date ";
 			}
@@ -1971,8 +1971,8 @@ function get_day_agendaitems($courses_dbs, $month, $year, $day)
 			{
 				$sqlquery = "SELECT
 													agenda.*
-													FROM ".$TABLEAGENDA." 
-													WHERE 
+													FROM ".$TABLEAGENDA."
+													WHERE
 													DAYOFMONTH(start_date)='".$day."' AND MONTH(start_date)='".$month."' AND YEAR(start_date)='".$year."'
 													ORDER BY start_date ";
 			}
@@ -1983,13 +1983,13 @@ function get_day_agendaitems($courses_dbs, $month, $year, $day)
 		$result = api_sql_query($sqlquery, __FILE__, __LINE__);
 		$portal_url = $_configuration['root_web'];
 		if ($_configuration['multiple_access_urls']==true) {
-			$access_url_id = api_get_current_access_url_id();				
+			$access_url_id = api_get_current_access_url_id();
 			if ($access_url_id != -1 ){
 				$url = api_get_access_url($access_url_id);
 				$portal_url = $url['url'];
 			}
-		} 
-			
+		}
+
 		//echo Database::num_rows($result);
 		while ($item = Database::fetch_array($result))
 		{
@@ -2010,11 +2010,11 @@ function get_day_agendaitems($courses_dbs, $month, $year, $day)
 				$title=$array_course_info['title'];
 				$agenda_link = api_substr($title, 0, 14);
 			}
-			else 
+			else
 			{
 				$agenda_link = Display::return_icon('course_home.gif');
-			}			
-			
+			}
+
 			//$URL = $_configuration['root_web'].$mycours["dir"]."/";
 			$URL = $portal_url.'main/admin/agenda.php?cidReq='."&amp;day=$day&amp;month=$month&amp;year=$year#$day"; // RH  //Patrick Cool: to highlight the relevant agenda item
 			$items[$halfhour][] .= "<i>".$hours.":".$minutes."</i> <a href=\"$URL\" title=\"".$array_course_info['name']."\">".$agenda_link."</a>  ".$item['title']."<br />";
@@ -2092,31 +2092,31 @@ function get_week_agendaitems($courses_dbs, $month, $year, $week = '')
 		//				AND (MONTH(day)>='$start_month' AND MONTH(day)<='$end_month')
 		//				AND (YEAR(day)>='$start_year' AND YEAR(day)<='$end_year')";
 		$result = api_sql_query($sqlquery, __FILE__, __LINE__);
-		
+
 		$portal_url = $_configuration['root_web'];
 		if ($_configuration['multiple_access_urls']==true) {
-			$access_url_id = api_get_current_access_url_id();				
+			$access_url_id = api_get_current_access_url_id();
 			if ($access_url_id != -1 ){
 				$url = api_get_access_url($access_url_id);
 				$portal_url = $url['url'];
 			}
-		} 
-			
+		}
+
 		while ($item = Database::fetch_array($result))
 		{
 			$agendaday = date("j",strtotime($item['start_date']));
 			$time= date("H:i",strtotime($item['start_date']));
 
 			if ($setting_agenda_link == 'coursecode')
-			{				
+			{
 				$title=$array_course_info['title'];
 				$agenda_link = api_substr($title, 0, 14);
 			}
-			else 
+			else
 			{
 				$agenda_link = Display::return_icon('course_home.gif');
-			}			 
-			
+			}
+
 			$URL = $portal_url."main/admin/agenda.php?cidReq=".urlencode($array_course_info["code"])."&amp;day=$agendaday&amp;month=$month&amp;year=$year#$agendaday"; // RH  //Patrick Cool: to highlight the relevant agenda item
 			$items[$agendaday][$item['start_time']] .= "<i>$time</i> <a href=\"$URL\" title=\"".$array_course_info["name"]."\">".$agenda_link."</a>  ".$item['title']."<br />";
 		}
@@ -2153,7 +2153,7 @@ function get_repeated_events_day_view($course_info,$start=0,$end=0,$params)
     //block $end if higher than 2038 -- PHP doesn't go past that
     if($end>2145934800){$end = 2145934800;}
 	if($start == 0 or $end == 0)
-	{	
+	{
 		$y=date('Y');
 		$m=date('m');
 		$d=date('j');
@@ -2168,7 +2168,7 @@ function get_repeated_events_day_view($course_info,$start=0,$end=0,$params)
 		$end = mktime(23,59,59,$m,$d,$y);
 	}
 	//$db_end = date('Y-m-d H:i:s',$end);
-	
+
 	$t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR,$course_info['dbName']);
 	//$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
     $t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
@@ -2203,7 +2203,7 @@ function get_repeated_events_day_view($course_info,$start=0,$end=0,$params)
 					$time_orig_s = date('s',$orig_start);
 					$int_time = (($time_orig_h*60)+$time_orig_m)*60+$time_orig_s; //time in seconds since 00:00:00
 					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
-					$current_start =$start + $int_time; //unixtimestamp start of today's event 
+					$current_start =$start + $int_time; //unixtimestamp start of today's event
 					$current_stop = $start+$int_time+$span; //unixtimestamp stop of today's event
 					$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
 					break;
@@ -2294,7 +2294,7 @@ function get_repeated_events_week_view($course_info,$start=0,$end=0,$params)
 		$end = $start+(86400*7)-1; //start of week, more 7 days, minus 1 second to get back to the previoyus day
 	}
 	//$db_end = date('Y-m-d H:i:s',$end);
-	
+
 	$t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
 	//$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
     //$t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
@@ -2323,7 +2323,7 @@ function get_repeated_events_week_view($course_info,$start=0,$end=0,$params)
 					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
 					for($i=0;$i<7;$i++)
 					{
-						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event 
+						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event
 						$current_stop = $start + ($i*86400) + $int_time + $span; //unixtimestamp stop of today's event
 						$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
 					}
@@ -2345,7 +2345,7 @@ function get_repeated_events_week_view($course_info,$start=0,$end=0,$params)
 					list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
 					$time_now = date('Y/n/W/j/G/i/s',$end);
 					list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now); 
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
 					if((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($start<$event_repetition_time && $event_repetition_time<$end))
 					{ //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
 					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
@@ -2364,7 +2364,7 @@ function get_repeated_events_week_view($course_info,$start=0,$end=0,$params)
 					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
 					$time_now = date('Y/n/j/z/G/i/s',$end);
 					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now); 
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
 					if((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end)))
 					{
 					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
@@ -2420,7 +2420,7 @@ function get_repeated_events_month_view($course_info,$start=0,$end=0,$params)
 		}
 	}
 	//$db_end = date('Y-m-d H:i:s',$end);
-	
+
 	$t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
 	//$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
     //$t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
@@ -2455,7 +2455,7 @@ function get_repeated_events_month_view($course_info,$start=0,$end=0,$params)
 					$span = $orig_end - $orig_start; //total seconds between start and stop of original event
 					for($i=0;$i<$month_last_day;$i++)
 					{
-						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event 
+						$current_start = $start + ($i*86400) + $int_time; //unixtimestamp start of today's event
 						$current_stop = $start + ($i*86400) + $int_time + $span; //unixtimestamp stop of today's event
 						$events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
 					}
@@ -2466,7 +2466,7 @@ function get_repeated_events_month_view($course_info,$start=0,$end=0,$params)
 					//The same can be said for the end of the month.
 					// The idea is thus to get all possible events by enlarging the scope of
 					// the month to get complete weeks covering the complete month, and then take out
-					// the events that start before the 1st ($start) or after the last day of the month ($end) 
+					// the events that start before the 1st ($start) or after the last day of the month ($end)
 					$time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
 					list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
                     $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
@@ -2491,14 +2491,14 @@ function get_repeated_events_month_view($course_info,$start=0,$end=0,$params)
                           // This means the event occurs on 29/4, 6/5, 13/5, 20/5 and 27/5.
                           // We want to get all of these, and then reject 29/4 because it is out
                           // of the month itself.
-                          
+
                           //First, to get the start time of the first day of the month view (even if
                           // the day is from the past month), we get the month start date (1/5) and
                           // see which day of the week it is, and subtract the number of days necessary
                           // to get back to the first day of the week.
                           $month_first_day_weekday = date('N',$start);
-                          $first_week_start = $start - (($month_first_day_weekday-1)*86400); 
-                          
+                          $first_week_start = $start - (($month_first_day_weekday-1)*86400);
+
                           //Second, we add the week day of the original event, so that we have an
                           // absolute time that represents the first repetition of the event in
                           // our 4- or 5-weeks timespan
@@ -2522,7 +2522,7 @@ function get_repeated_events_month_view($course_info,$start=0,$end=0,$params)
 					list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
 					$time_now = date('Y/n/W/j/G/i/s',$end);
 					list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now); 
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
 					if(($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig)))
 					{ //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
 					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
@@ -2541,7 +2541,7 @@ function get_repeated_events_month_view($course_info,$start=0,$end=0,$params)
 					list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
 					$time_now = date('Y/n/j/z/G/i/s',$end);
 					list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now); 
+					$event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
 					if((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end)))
 					{
 					  $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
@@ -2591,7 +2591,7 @@ function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
         $end = mktime(0, 0, 0, 1, 1, 2037);
     }
     //$db_end = date('Y-m-d H:i:s',$end);
-    
+
     $t_cal = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR,$course_info['dbName']);
     //$t_cal_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course_info['dbName']);
     //$t_ip = Database::get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
@@ -2625,7 +2625,7 @@ function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
                     $span = $orig_end - $orig_start; //total seconds between start and stop of original event
                     for($i=$orig_start+86400;($i<$end && $i<=$repeat_end);$i+=86400)
                     {
-                        $current_start = $i; //unixtimestamp start of today's event 
+                        $current_start = $i; //unixtimestamp start of today's event
                         $current_stop = $i + $span; //unixtimestamp stop of today's event
                         $events[] = array($course_info['id'],$row['id'],$current_start,$current_stop,$row['title'],$row['content']);
                     }
@@ -2636,7 +2636,7 @@ function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
                     //The same can be said for the end of the month.
                     // The idea is thus to get all possible events by enlarging the scope of
                     // the month to get complete weeks covering the complete month, and then take out
-                    // the events that start before the 1st ($start) or after the last day of the month ($end) 
+                    // the events that start before the 1st ($start) or after the last day of the month ($end)
                     $time_orig = date('Y/n/W/j/N/G/i/s',$orig_start);
                     list($y_orig,$m_orig,$w_orig,$d_orig,$dw_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
                     $time_orig_end = date('Y/n/W/j/N/G/i/s',$orig_end);
@@ -2647,7 +2647,7 @@ function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
                     if($w_now==52)
                     {
                         ++$y_now;
-                        $w_now=1;	
+                        $w_now=1;
                     }
                     else
                     {
@@ -2661,8 +2661,8 @@ function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
                     { //if the event is after the original (at least one week) and the day of the week is the same
                         //for($i=$month_first_week;($i<=$month_last_week && $i<1000);$i++)
                         //{
-                        	
-                        
+
+
                           /*
                            The "day of the week" of repetition is the same as the $dw_orig,
                            so to get the "day of the month" from the "day of the week", we have
@@ -2679,8 +2679,8 @@ function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
                            to get back to the first day of the week.
                           */
                           $month_first_day_weekday = date('N',$start);
-                          $first_week_start = $start - (($month_first_day_weekday-1)*86400); 
-                          
+                          $first_week_start = $start - (($month_first_day_weekday-1)*86400);
+
                           //Second, we add the week day of the original event, so that we have an
                           // absolute time that represents the first repetition of the event in
                           // our 4- or 5-weeks timespan
@@ -2706,7 +2706,7 @@ function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
                 case 'monthlyByDate':
                     $time_orig = date('Y/n/W/j/G/i/s',$orig_start);
                     list($y_orig,$m_orig,$w_orig,$d_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
-                    
+
                     $time_now = date('Y/n/W/j/G/i/s',$start);
                     list($y_now,$m_now,$w_now,$d_now,$h_now,$n_now,$s_now) = split('/',$time_now);
                     //make sure we are one month ahead (to avoid being the same month as the original event)
@@ -2719,11 +2719,11 @@ function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
                     {
                         ++$m_now;
                     }
-                    
+
                     $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
                     list($y_orig_e,$m_orig_e,$d_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
- 
-                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now); 
+
+                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
                     $diff = $orig_end - $orig_start;
                     while((($y_now>$y_orig) OR (($y_now == $y_orig) && ($m_now>$m_orig))) && ($event_repetition_time < $end) && ($event_repetition_time < $repeat_end))
                     { //if the event is after the original (at least one month) and the original event's day is between the first day of the week and the last day of the week
@@ -2739,7 +2739,7 @@ function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
                       {
                         ++$m_now;
                       }
-                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now); 
+                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now);
                     }
                     break;
                 case 'monthlyByDayR':
@@ -2753,14 +2753,14 @@ function get_repeated_events_list_view($course_info,$start=0,$end=0,$params)
                     list($y_orig,$m_orig,$d_orig,$dy_orig,$h_orig,$n_orig,$s_orig) = split('/',$time_orig);
                     $time_now = date('Y/n/j/z/G/i/s',$end);
                     list($y_now,$m_now,$d_now,$dy_now,$h_now,$n_now,$s_now) = split('/',$time_now);
-                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now); 
+                    $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
                     while((($y_now>$y_orig) && ($start<$event_repetition_time && $event_repetition_time<$end && $event_repetition_time<$repeat_end)))
                     {
                       $time_orig_end = date('Y/n/j/G/i/s',$orig_end);
                       list($y_orig_e,$m_orig_e,$d_orig_e,$dy_orig_e,$h_orig_e,$n_orig_e,$s_orig_e) = split('/',$time_orig_end);
                       $events[] = array($course_info['id'],$row['id'],mktime($h_orig,$n_orig,$s_orig,$m_now,$d_orig,$y_now),mktime($h_orig_e,$n_orig_e,$s_orig_e,$m_now,$d_orig_e,$y_now),$row['title'],$row['content']);
                       ++$y_now;
-                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now); 
+                      $event_repetition_time = mktime($h_orig,$n_orig,$s_orig,$m_orig,$d_orig,$y_now);
                     }
                     break;
                 default:
@@ -2781,7 +2781,7 @@ function is_repeated_event($id,$course=null)
 	if(empty($course))
     {
     	$course_info = api_get_course_info();
-        $course = $course_info['dbName']; 
+        $course = $course_info['dbName'];
     }
     $id = (int) $id;
 	//$t_agenda_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT,$course);
@@ -2850,13 +2850,13 @@ function agenda_add_item($course_info, $title, $content, $db_start_date, $db_end
   global $_course;
     $user_id    = api_get_user_id();
     $t_agenda   = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
-    
+
     // some filtering of the input data
     $title      = Database::escape_string($title); // no html allowed in the title
     $content    = Database::escape_string($content);
     $start_date = Database::escape_string($db_start_date);
     $end_date   = Database::escape_string($db_end_date);
-     
+
      isset($_SESSION['id_session'])?$id_session=intval($_SESSION['id_session']):$id_session=null;
     // store in the table calendar_event
 
@@ -2929,7 +2929,7 @@ function agenda_add_item($course_info, $title, $content, $db_start_date, $db_end
 {
 	global $_user, $_course;
 	global $is_allowed_to_edit;
-	
+
 	$month=Database::escape_string($month);
 	$year=Database::escape_string($year);
 
@@ -2952,15 +2952,15 @@ function agenda_add_item($course_info, $title, $content, $db_start_date, $db_end
 			GROUP BY id ".
 			"ORDER BY  start_date ";
 		$result=api_sql_query($sql,__FILE__,__LINE__);
-	
+
 		while ($row=Database::fetch_array($result)) {
 			$datum_item=(int)substr($row["start_date"],8,2);
 			$data[$datum_item][intval($datum_item)][] = $row;
 		}
-	}	
+	}
 	return $data;
 }
- 
+
 function agenda_add_repeat_item($course_info,$orig_id,$type,$end,$orig_dest)
 {/*
 	$t_agenda   = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR,$course_info['dbName']);
@@ -3006,7 +3006,7 @@ function agenda_add_repeat_item($course_info,$orig_id,$type,$end,$orig_dest)
                 break;
         }
     }
-    if($end > $now 
+    if($end > $now
         && in_array($type,array('daily','weekly','monthlyByDate','monthlyByDay','monthlyByDayR','yearly')))
     {
        $sql = "INSERT INTO $t_agenda_r (cal_id, cal_type, cal_end)" .
@@ -3073,7 +3073,7 @@ function agenda_import_ical($course_info,$file)
     $ical->setConfig( 'directory', dirname($filepath) );
     $ical->setConfig( 'filename', basename($filepath) );
     $ical->parse();
-    //we need to recover: summary, description, dtstart, dtend, organizer, attendee, location (=course name), 
+    //we need to recover: summary, description, dtstart, dtend, organizer, attendee, location (=course name),
     // rrule
     $ve = $ical->getComponent(0);
     //print_r($ve);
@@ -3092,7 +3092,7 @@ function agenda_import_ical($course_info,$file)
     $course_name = $ve->getProperty('location');
     //insert the event in our database
     $id = agenda_add_item($course_info,$title,$desc,$start_date,$end_date,$_POST['selectedform']);
-    
+
     $repeat = $ve->getProperty('rrule');
     if(is_array($repeat) && !empty($repeat['FREQ']))
     {
@@ -3108,7 +3108,7 @@ function agenda_import_ical($course_info,$file)
         if(!empty($repeat['COUNT']))
         {
             $count = $repeat['COUNT'];
-            $res = agenda_add_repeat_item($course_info,$id,$freq,$count,$_POST['selectedform']);            
+            $res = agenda_add_repeat_item($course_info,$id,$freq,$count,$_POST['selectedform']);
         }
     }
     return true;

+ 8 - 8
main/admin/calendar.php

@@ -22,7 +22,7 @@
 ==============================================================================
 *	@package dokeos.admin
 *	@author Carlos Vargas
-*	This file is the calendar/agenda.php 
+*	This file is the calendar/agenda.php
 ==============================================================================
 */
 
@@ -266,23 +266,23 @@ if (api_is_allowed_to_edit(false,true))
 				}
                 display_agenda_items();
             } elseif ($_POST['submit_event']) {
-			
+
 		     $course_info = api_get_course_info();
 			    $event_start    = (int) $_POST['fyear'].'-'.(int) $_POST['fmonth'].'-'.(int) $_POST['fday'].' '.(int) $_POST['fhour'].':'.(int) $_POST['fminute'].':00';
                 $event_stop     = (int) $_POST['end_fyear'].'-'.(int) $_POST['end_fmonth'].'-'.(int) $_POST['end_fday'].' '.(int) $_POST['end_fhour'].':'.(int) $_POST['end_fminute'].':00';
-                
+
 				$id = agenda_add_item($course_info,$_POST['title'],$_POST['content'],$event_start,$event_stop,$_POST['selectedform'],false,$_POST['file_comment']);
-				
+
                 if(!empty($_POST['repeat'])) {
                 	$end_y = intval($_POST['repeat_end_year']);
                     $end_m = intval($_POST['repeat_end_month']);
                     $end_d = intval($_POST['repeat_end_day']);
                     $end   = mktime(23, 59, 59, $end_m, $end_d, $end_y);
                     $res = agenda_add_repeat_item($course_info,$id,$_POST['repeat_type'],$end,null,$_POST['file_comment']);
-                } 
+                }
                 if (api_get_setting('display_upcoming_events') == 'true') {
 					display_upcoming_events();
-				}           
+				}
 				display_agenda_items();
 			} else {
 				show_add_form();
@@ -376,7 +376,7 @@ if (!$_GET['action'] OR $_GET['action']=="showall"  OR $_GET['action']=="showcur
 		{
             if(!empty($_GET['agenda_id']))
             {
-                 display_one_agenda_item((int)$_GET['agenda_id']);   
+                 display_one_agenda_item((int)$_GET['agenda_id']);
             }
             else
             {
@@ -403,7 +403,7 @@ echo "&nbsp;</td></tr></table>";
 // The footer is displayed only if we are not in the learnpath
 if ($_GET['origin'] != 'learnpath')
 {
-	 
+
 	Display::display_footer();
 
 }

+ 7 - 7
main/admin/calendar_ical_export.php

@@ -4,7 +4,7 @@
 ==============================================================================
 *	@package dokeos.admin
 *	@author Carlos Vargas
-*	This file is the calendar/ical_export.php 
+*	This file is the calendar/ical_export.php
 ==============================================================================
 */
 /**
@@ -51,7 +51,7 @@ if(!empty($_GET['id']) && $_GET['id']==strval(intval($_GET['id'])))
 		switch($_GET['class'])
 		{
 			case 'public':
-				$vevent->setClass('PUBLIC');			
+				$vevent->setClass('PUBLIC');
 				break;
 			case 'private':
 				$vevent->setClass('PRIVATE');
@@ -60,7 +60,7 @@ if(!empty($_GET['id']) && $_GET['id']==strval(intval($_GET['id'])))
 				$vevent->setClass('CONFIDENTIAL');
 				break;
 			default:
-				$vevent->setClass('PRIVATE');				
+				$vevent->setClass('PRIVATE');
 				break;
 		}
 
@@ -74,7 +74,7 @@ if(!empty($_GET['id']) && $_GET['id']==strval(intval($_GET['id'])))
 				list($y,$m,$d,$h,$M,$s) = preg_split('/[\s:-]/',$ai['date']);
 				$vevent->setProperty('dtstart',array('year'=>$y,'month'=>$m,'day'=>$d,'hour'=>$h,'min'=>$M,'sec'=>$s));
 				if(empty($ai['enddate']))
-				{	
+				{
 					$y2=$y;$m2=$m;$d2=$d;$h2=$h;$M2=$M+15;$s2=$s;
 					if($M2>60){$M2=$M2-60;$h2+=1;}
 				}
@@ -104,7 +104,7 @@ if(!empty($_GET['id']) && $_GET['id']==strval(intval($_GET['id'])))
 				list($y,$m,$d,$h,$M,$s) = preg_split('/[\s:-]/',$ai['start_date']);
 				$vevent->setProperty('dtstart',array('year'=>$y,'month'=>$m,'day'=>$d,'hour'=>$h,'min'=>$M,'sec'=>$s));
 				if(empty($ai['end_date']))
-				{	
+				{
 					$y2=$y;$m2=$m;$d2=$d;$h2=$h;$M2=$M+15;$s2=$s;
 					if($M2>60){$M2=$M2-60;$h2+=1;}
 				}
@@ -134,13 +134,13 @@ if(!empty($_GET['id']) && $_GET['id']==strval(intval($_GET['id'])))
 				break;
 			default:
 				header('location:'.$_SERVER['REFERER_URI']);
-				die();	
+				die();
 		}
 	}
 }
 else
 {
 	header('location:'.$_SERVER['REFERER_URI']);
-	die();	
+	die();
 }
 ?>

+ 1 - 1
main/admin/calendar_view_print.php

@@ -22,7 +22,7 @@
 ==============================================================================
 *	@package dokeos.admin
 *	@author Carlos Vargas
-*	This file is the calendar/print.php 
+*	This file is the calendar/print.php
 ==============================================================================
 */
 // name of the language file that needs to be included

+ 18 - 23
main/admin/class_add.php

@@ -29,48 +29,43 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// Language files that should be included.
 $language_file = 'admin';
 
-// resetting the course id
+// Resetting the course id.
 $cidReset = true;
 
-// including some necessary dokeos files
-require_once('../inc/global.inc.php');
-require_once (api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+// Including some necessary dokeos files.
+require_once '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
-// setting the section (for the tabs)
+// Setting the section (for the tabs).
 $this_section = SECTION_PLATFORM_ADMIN;
 
-// Access restrictions
+// Access restrictions.
 api_protect_admin_script();
 
-// setting breadcrumbs
+// Setting breadcrumbs.
 $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 
-// setting the name of the tool
+// Setting the name of the tool.
 $tool_name = get_lang("AddClasses");
 
 $form = new FormValidator('add_class');
-$form->add_textfield('name',get_lang('ClassName'));
-$form->addElement('submit','submit',get_lang('Ok'));
-if($form->validate())
-{
+$form->add_textfield('name', get_lang('ClassName'));
+$form->addElement('style_submit_button', 'submit', get_lang('Ok'), 'class="add"');
+if ($form->validate()) {
 	$values = $form->exportValues();
-	ClassManager :: create_class($values['name']);
+	ClassManager::create_class($values['name']);
 	header('Location: class_list.php');
 }
 
-// Displaying the header
+// Displaying the header.
 Display :: display_header($tool_name);
 
-// Displaying the form
+// Displaying the form.
 $form->display();
-/*
-==============================================================================
-		FOOTER 
-==============================================================================
-*/
+
+// Displaying the footer.
 Display :: display_footer();
-?>

+ 18 - 24
main/admin/class_edit.php

@@ -29,37 +29,36 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// Language files that should be included.
 $language_file = 'admin';
 
-// resetting the course id
+// Resetting the course id.
 $cidReset = true;
 
-// including some necessary dokeos files
-include ('../inc/global.inc.php');
-require_once(api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+// Including some necessary dokeos files.
+include '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
-// setting the section (for the tabs)
-$this_section=SECTION_PLATFORM_ADMIN;
+// Setting the section (for the tabs).
+$this_section = SECTION_PLATFORM_ADMIN;
 
-// Access restrictions
+// Access restrictions.
 api_protect_admin_script();
 
-// setting breadcrumbs
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ("url" => "class_list.php", "name" => get_lang('AdminClasses'));
-
-// setting the name of the tool
-$tool_name = get_lang("AddClasses");
+// Setting breadcrumbs.
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'class_list.php', 'name' => get_lang('AdminClasses'));
 
+// Setting the name of the tool.
+$tool_name = get_lang('AddClasses');
 
 $tool_name = get_lang('ModifyClassInfo');
 $class_id = intval($_GET['idclass']);
 $class = ClassManager :: get_class_info($class_id);
-$form = new FormValidator('edit_class','post','class_edit.php?idclass='.$class_id);
+$form = new FormValidator('edit_class', 'post', 'class_edit.php?idclass='.$class_id);
 $form->add_textfield('name',get_lang('ClassName'));
-$form->addElement('submit','submit',get_lang('Ok'));
+$form->addElement('style_submit_button', 'submit', get_lang('Ok'), 'class="add"');
 $form->setDefaults(array('name'=>$class['name']));
 if($form->validate())
 {
@@ -68,14 +67,9 @@ if($form->validate())
 	header('Location: class_list.php');
 }
 
-
 Display :: display_header($tool_name);
 //api_display_tool_title($tool_name);
 $form->display();
-/*
-==============================================================================
-		FOOTER 
-==============================================================================
-*/
+
+// Displaying the footer.
 Display :: display_footer();
-?>

+ 48 - 59
main/admin/class_import.php

@@ -30,100 +30,91 @@
 *	@package dokeos.admin
 ==============================================================================
 */
+
 /**
- * Validate the imported data
+ * Validates imported data.
  */
-function validate_data($classes)
-{
+function validate_data($classes) {
 	$errors = array();
-	foreach($classes as $index => $class)
-	{
-		//1. Check if ClassName is available
-		if(!isset($class['ClassName']) || strlen(trim($class['ClassName'])) == 0)
-		{
-			$class['line'] = $index+2;
+	foreach ($classes as $index => $class) {
+		// 1. Check wheter ClassName is available.
+		if (!isset($class['ClassName']) || strlen(trim($class['ClassName'])) == 0) {
+			$class['line'] = $index + 2;
 			$class['error'] = get_lang('MissingClassName');
 			$errors[] = $class;
-		}	
-		//2. Check if class doesn't exist yet
-		else
-		{
-			if(ClassManager::class_name_exists($class['ClassName']))
-			{
-				$class['line'] = $index+2;
-				$class['error'] = get_lang('ClassNameExists');
-				$errors[] = $class;					
-			}	
+		}
+		// 2. Check whether class doesn't exist yet.
+		else {
+			if (ClassManager::class_name_exists($class['ClassName'])) {
+				$class['line'] = $index + 2;
+				$class['error'] = get_lang('ClassNameExists').' <strong>'.$class['ClassName'].'</strong>';
+				$errors[] = $class;
+			}
 		}
 	}
 	return $errors;
 }
+
 /**
  * Save imported class data to database
  */
-function save_data($classes)
-{
+function save_data($classes) {
 	$number_of_added_classes = 0;
-	foreach($classes as $index => $class)
-	{
-		if(ClassManager::create_class($class['ClassName']))
-		{
-			$number_of_added_classes++;	
-		}	
+	foreach ($classes as $index => $class) {
+		if (ClassManager::create_class($class['ClassName'])) {
+			$number_of_added_classes++;
+		}
 	}
 	return $number_of_added_classes;
 }
 
-
-
-// name of the language file that needs to be included 
+// Language files that should be included.
 $language_file = array ('admin', 'registration');
 
-// resetting the course id
+// Resetting the course id.
 $cidReset = true;
 
-// including some necessary dokeos files
-include ('../inc/global.inc.php');
-require_once (api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'import.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+// Including some necessary dokeos files.
+include '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'import.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
-// setting the section (for the tabs)
+// Setting the section (for the tabs).
 $this_section = SECTION_PLATFORM_ADMIN;
 
-// Access restrictions
+// Access restrictions.
 api_protect_admin_script();
 
 // setting breadcrumbs
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 
 // Database Table Definitions
 
-// setting the name of the tool
+// Setting the name of the tool.
 $tool_name = get_lang('ImportClassListCSV');
 
-// Displaying the header
+// Displaying the header.
 Display :: display_header($tool_name);
 //api_display_tool_title($tool_name);
+
+set_time_limit(0);
+
 $form = new FormValidator('import_classes');
-$form->addElement('file','import_file',get_lang('ImportCSVFileLocation'));
-$form->addElement('submit','submit',get_lang('Ok'));
-if( $form->validate())
-{
+$form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
+$form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
+
+if ($form->validate()) {
 	$classes = Import::csv_to_array($_FILES['import_file']['tmp_name']);
 	$errors = validate_data($classes);
-	if (count($errors) == 0)
-	{
+	if (count($errors) == 0) {
 		$number_of_added_classes = save_data($classes);
 		Display::display_normal_message($number_of_added_classes.' '.get_lang('ClassesCreated'));
-	}		
-	else
-	{
+	} else {
 		$error_message = get_lang('ErrorsWhenImportingFile');
 		$error_message .= '<ul>';
-		foreach ($errors as $index => $error_class)
-		{
+		foreach ($errors as $index => $error_class) {
 			$error_message .= '<li>'.$error_class['error'].' ('.get_lang('Line').' '.$error_class['line'].')';
 			$error_message .= '</li>';
 		}
@@ -132,7 +123,9 @@ if( $form->validate())
 		Display :: display_error_message($error_message);
 	}
 }
+
 $form->display();
+
 ?>
 <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
 <blockquote>
@@ -145,10 +138,6 @@ $form->display();
  </pre>
 </blockquote>
 <?php
-/*
-==============================================================================
-		FOOTER 
-==============================================================================
-*/
+
+// Displaying the footer.
 Display :: display_footer();
-?>

+ 29 - 43
main/admin/class_information.php

@@ -22,49 +22,45 @@
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	@author	 Bart Mollet
 *	@package dokeos.admin
-============================================================================== 
-*/
-
-/*
-==============================================================================
-		INIT SECTION
 ==============================================================================
-*/ 
+*/
 
-// name of the language file that needs to be included 
-$language_file='admin';
+// Language files that should be included.
+$language_file = 'admin';
 
-$cidReset=true;
+$cidReset = true;
 
-require('../inc/global.inc.php');
-$this_section=SECTION_PLATFORM_ADMIN;
+require '../inc/global.inc.php';
+$this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
-require(api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-if( !isset($_GET['id']))
-{
-	api_not_allowed();	
+
+require api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+
+if (!isset($_GET['id'])) {
+	api_not_allowed();
 }
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ("url" => 'class_list.php', "name" => get_lang('AdminClasses'));
+
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'class_list.php', 'name' => get_lang('AdminClasses'));
+
 $class_id = $_GET['id'];
 $class = ClassManager::get_class_info($class_id);
 
 $tool_name = $class['name'];
 Display::display_header($tool_name);
 //api_display_tool_title($tool_name);
+
 /**
- * Show all users subscribed in this class
+ * Show all users subscribed in this class.
  */
 echo '<h4>'.get_lang('Users').'</h4>';
 echo '<blockquote>';
-
 $users = ClassManager::get_users($class_id);
-if (count($users) > 0)
-{
+if (count($users) > 0) {
 	$is_western_name_order = api_is_western_name_order();
 	$table_header[] = array (get_lang('OfficialCode'), true);
 	if ($is_western_name_order) {
@@ -78,8 +74,7 @@ if (count($users) > 0)
 	$table_header[] = array (get_lang('Status'), true);
 	$table_header[] = array ('', false);
 	$data = array();
-	foreach($users as $index => $user)
-	{
+	foreach($users as $index => $user) {
 		$row = array ();
 		$row[] = $user['official_code'];
 		if ($is_western_name_order) {
@@ -95,24 +90,21 @@ if (count($users) > 0)
 		$data[] = $row;
 	}
 	Display::display_sortable_table($table_header,$data,array(),array(),array('id'=>$_GET['id']));
-}
-else
-{
-	echo get_lang('NoUsersInClass');	
+} else {
+	echo get_lang('NoUsersInClass');
 }
 echo '</blockquote>';
+
 /**
- * Show all courses in which this class is subscribed
+ * Show all courses in which this class is subscribed.
  */
 $courses = ClassManager::get_courses($class_id);
-if (count($courses) > 0)
-{
+if (count($courses) > 0) {
 	$header[] = array (get_lang('Code'), true);
 	$header[] = array (get_lang('Title'), true);
 	$header[] = array ('', false);
 	$data = array ();
-	foreach( $courses as $index=>$course)
-	{
+	foreach( $courses as $index => $course) {
 		$row = array ();
 		$row[] = $course['visual_code'];
 		$row[] = $course['title'];
@@ -125,15 +117,9 @@ if (count($courses) > 0)
 	echo '<blockquote>';
 	Display :: display_sortable_table($header, $data, array (), array (), array('id'=>$_GET['id']));
 	echo '</blockquote>';
-}
-else
-{
+} else {
 	echo '<p>'.get_lang('NoCoursesForThisClass').'</p>';
 }
-/*
-==============================================================================
-		FOOTER 
-==============================================================================
-*/ 
+
+// Displaying the footer.
 Display::display_footer();
-?> 

+ 49 - 54
main/admin/class_list.php

@@ -28,92 +28,86 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
 $language_file = 'admin';
+
 $cidReset = true;
-require ('../inc/global.inc.php');
+require '../inc/global.inc.php';
+
 $this_section = SECTION_PLATFORM_ADMIN;
+api_protect_admin_script();
 
 /**
- * Gets the total number of classes
+ * Gets the total number of classes.
  */
-function get_number_of_classes()
-{
+function get_number_of_classes() {
 	$tbl_class = Database :: get_main_table(TABLE_MAIN_CLASS);
 	$sql = "SELECT COUNT(*) AS number_of_classes FROM $tbl_class";
-	if (isset ($_GET['keyword']))
-	{
+	if (isset ($_GET['keyword'])) {
 		$sql .= " WHERE (name LIKE '%".Database::escape_string(trim($_GET['keyword']))."%')";
 	}
-	$res = api_sql_query($sql, __FILE__, __LINE__);
+	$res = Database::query($sql, __FILE__, __LINE__);
 	$obj = Database::fetch_object($res);
 	return $obj->number_of_classes;
 }
+
 /**
- * Gets the information about some classes
+ * Gets the information about some classes.
  * @param int $from
  * @param int $number_of_items
  * @param string $direction
  */
-function get_class_data($from, $number_of_items, $column, $direction)
-{
-	$tbl_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
+function get_class_data($from, $number_of_items, $column, $direction) {
+	$tbl_class_user = Database::get_main_table(TABLE_MAIN_CLASS_USER);
 	$tbl_class = Database :: get_main_table(TABLE_MAIN_CLASS);
 	$from 				= Database::escape_string($from);
 	$number_of_items 	= Database::escape_string($number_of_items);
 	$column 			= Database::escape_string($column);
 	$direction 			= Database::escape_string($direction);
-	
+
 	$sql = "SELECT 	id AS col0, name AS col1, COUNT(user_id) AS col2, id AS col3
-				FROM $tbl_class
-				LEFT JOIN $tbl_class_user ON id=class_id ";
-	if (isset ($_GET['keyword']))
-	{
+		FROM $tbl_class
+			LEFT JOIN $tbl_class_user ON id=class_id ";
+	if (isset ($_GET['keyword'])) {
 		$sql .= " WHERE (name LIKE '%".Database::escape_string(trim($_GET['keyword']))."%')";
 	}
-	$sql .= "GROUP BY id,name ORDER BY col$column $direction LIMIT $from,$number_of_items";
-	$res = api_sql_query($sql, __FILE__, __LINE__);
+	$sql .= " GROUP BY id,name ORDER BY col$column $direction LIMIT $from,$number_of_items";
+	$res = Database::query($sql, __FILE__, __LINE__);
 	$classes = array ();
-	while ($class = Database::fetch_row($res))
-	{
+	while ($class = Database::fetch_row($res)) {
 		$classes[] = $class;
 	}
 	return $classes;
 }
+
 /**
  * Filter for sortable table to display edit icons for class
  */
-function modify_filter($class_id)
-{
-	global $charset;
+function modify_filter($class_id) {
 	$class_id = Security::remove_XSS($class_id);
 	$result = '<a href="class_information.php?id='.$class_id.'">'.Display::return_icon('synthese_view.gif', get_lang('Info')).'</a>';
 	$result .= '<a href="class_edit.php?idclass='.$class_id.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
-	$result .= '<a href="class_list.php?action=delete_class&amp;class_id='.$class_id.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
+	$result .= '<a href="class_list.php?action=delete_class&amp;class_id='.$class_id.'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"), ENT_QUOTES))."'".')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
 	$result .= '<a href="subscribe_user2class.php?idclass='.$class_id.'">'.Display::return_icon('add_multiple_users.gif', get_lang('AddUsersToAClass')).'</a>';
 	return $result;
 }
 
-api_protect_admin_script();
-require (api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require (api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
+require api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+
 $tool_name = get_lang('ClassList');
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 
 Display :: display_header($tool_name);
 //api_display_tool_title($tool_name);
-if (isset ($_POST['action']))
-{
-	switch ($_POST['action'])
-	{
+
+if (isset($_POST['action'])) {
+	switch ($_POST['action']) {
 		// Delete selected classes
 		case 'delete_classes' :
 			$classes = $_POST['class'];
-			if (count($classes) > 0)
-			{
-				foreach ($classes as $index => $class_id)
-				{
+			if (count($classes) > 0) {
+				foreach ($classes as $index => $class_id) {
 					ClassManager :: delete_class($class_id);
 				}
 				Display :: display_normal_message(get_lang('ClassesDeleted'));
@@ -121,36 +115,37 @@ if (isset ($_POST['action']))
 			break;
 	}
 }
-if (isset ($_GET['action']))
-{
-	switch ($_GET['action'])
-	{
-		case 'delete_class' :
+
+if (isset($_GET['action'])) {
+	switch ($_GET['action']) {
+		case 'delete_class':
 			ClassManager :: delete_class($_GET['class_id']);
 			Display :: display_normal_message(get_lang('ClassDeleted'));
+			break;
+		case 'show_message':
+			Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
+			break;
 	}
 }
+
 // Create a search-box
-$form = new FormValidator('search_simple','get','','',null,false);
+$form = new FormValidator('search_simple', 'get', '', '', null, false);
 $renderer =& $form->defaultRenderer();
 $renderer->setElementTemplate('<span>{element}</span> ');
-$form->addElement('text','keyword',get_lang('keyword'));
-$form->addElement('submit','submit',get_lang('Search'));
+$form->addElement('text', 'keyword', get_lang('keyword'));
+$form->addElement('submit', 'submit', get_lang('Search'));
 $form->display();
+
 // Create the sortable table with class information
 $table = new SortableTable('classes', 'get_number_of_classes', 'get_class_data', 1);
-$table->set_additional_parameters(array('keyword'=>$_GET['keyword']));
+$table->set_additional_parameters(array('keyword' => $_GET['keyword']));
 $table->set_header(0, '', false);
 $table->set_header(1, get_lang('ClassName'));
 $table->set_header(2, get_lang('NumberOfUsers'));
 $table->set_header(3, '', false);
 $table->set_column_filter(3, 'modify_filter');
-$table->set_form_actions(array ('delete_classes' => get_lang('DeleteSelectedClasses')),'class');
+$table->set_form_actions(array ('delete_classes' => get_lang('DeleteSelectedClasses')), 'class');
 $table->display();
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
+
+// Displaying the footer.
 Display :: display_footer();
-?>

+ 89 - 93
main/admin/class_user_import.php

@@ -22,58 +22,56 @@
 */
 /**
 ==============================================================================
-* This tool allows platform admins to update class-user relations by uploading a
-* CSVfile
+* This tool allows platform admins to update class-user relations by uploading
+* a CSVfile
 * @package dokeos.admin
 ==============================================================================
 */
+
 /**
- * validate the imported data
+ * Validates imported data.
  */
-function validate_data($user_classes)
-{
+function validate_data($user_classes) {
+	global $purification_option_for_usernames;
 	$errors = array ();
 	$classcodes = array ();
-	foreach ($user_classes as $index => $user_class)
-	{
-		$user_class['line'] = $index +1;
-		//1. check if mandatory fields are set
+	foreach ($user_classes as $index => $user_class) {
+		$user_class['line'] = $index + 1;
+		// 1. Check whether mandatory fields are set.
 		$mandatory_fields = array ('UserName', 'ClassName');
-		foreach ($mandatory_fields as $key => $field)
-		{
-			if (!isset ($user_class[$field]) || strlen($user_class[$field]) == 0)
-			{
+		foreach ($mandatory_fields as $key => $field) {
+			if (!isset ($user_class[$field]) || strlen($user_class[$field]) == 0) {
 				$user_class['error'] = get_lang($field.'Mandatory');
 				$errors[] = $user_class;
 			}
 		}
-		//2. check if classcode exists
-		if (isset ($user_class['ClassName']) && strlen($user_class['ClassName']) != 0)
-		{
-			//2.1 check if code allready used in this CVS-file
-			if (!isset ($classcodes[$user_class['ClassName']]))
-			{
-				//2.1.1 check if code exists in DB
+		// 2. Check whether classcode exists.
+		if (isset ($user_class['ClassName']) && strlen($user_class['ClassName']) != 0) {
+			// 2.1 Check whether code has been allready used in this CVS-file.
+			if (!isset ($classcodes[$user_class['ClassName']])) {
+				// 2.1.1 Check whether code exists in DB.
 				$class_table = Database :: get_main_table(TABLE_MAIN_CLASS);
 				$sql = "SELECT * FROM $class_table WHERE name = '".Database::escape_string($user_class['ClassName'])."'";
-				$res = api_sql_query($sql, __FILE__, __LINE__);
-				if (Database::num_rows($res) == 0)
-				{
+				$res = Database::query($sql, __FILE__, __LINE__);
+				if (Database::num_rows($res) == 0) {
 					$user_class['error'] = get_lang('CodeDoesNotExists');
 					$errors[] = $user_class;
-				}
-				else
-				{
+				} else {
 					$classcodes[$user_class['CourseCode']] = 1;
 				}
 			}
 		}
-		//3. check if username exists
-		if (isset ($user_class['UserName']) && strlen($user_class['UserName']) != 0)
-		{
-			if (UserManager :: is_username_available($user_class['UserName']))
-			{
-				$user_class['error'] = get_lang('UnknownUser').":".$user_class['UserName'];
+		// 3. Check username, first, check whether it is empty.
+		if (!UserManager::is_username_empty($user_class['UserName'])) {
+			// 3.1. Check whether username is too long.
+			if (UserManager::is_username_too_long($user_class['UserName'])) {
+				$user_class['error'] = get_lang('UserNameTooLong').': '.$user_class['UserName'];
+				$errors[] = $user_class;
+			}
+			$username = UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames);
+			// 3.2. Check whether username exists.
+			if (UserManager::is_username_available($username)) {
+				$user_class['error'] = get_lang('UnknownUser').': '.$username;
 				$errors[] = $user_class;
 			}
 		}
@@ -82,112 +80,111 @@ function validate_data($user_classes)
 }
 
 /**
- * Save the imported data
+ * Saves imported data.
  */
-function save_data($users_classes)
-{
-	// table definitions
+function save_data($users_classes) {
+
+	global $purification_option_for_usernames;
+
+	// Table definitions.
 	$user_table 		= Database :: get_main_table(TABLE_MAIN_USER);
 	$class_user_table 	= Database :: get_main_table(TABLE_MAIN_CLASS_USER);
 	$class_table 		= Database :: get_main_table(TABLE_MAIN_CLASS);
-	
+
+	// Data parsing: purification + conversion (UserName, ClassName) --> (user_is, class_id)
 	$csv_data = array ();
-	foreach ($users_classes as $index => $user_class)
-	{
-		$sql = "SELECT * FROM $class_table WHERE name = '".mysql_real_escape_string($user_class['ClassName'])."'";
-		$res = api_sql_query($sql, __FILE__, __LINE__);
-		$obj = mysql_fetch_object($res);
-		$csv_data[$user_class['UserName']][$obj->id] = 1;
+	foreach ($users_classes as $index => $user_class) {
+		$sql1 = "SELECT user_id FROM $user_table WHERE username = '".Database::escape_string(UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames))."'";
+		$res1 = Database::query($sql1, __FILE__, __LINE__);
+		$obj1 = Database::fetch_object($res1);
+		$sql2 = "SELECT id FROM $class_table WHERE name = '".Database::escape_string(trim($user_class['ClassName']))."'";
+		$res2 = Database::query($sql2, __FILE__, __LINE__);
+		$obj2 = Database::fetch_object($res2);
+		if ($obj1 && $obj2) {
+			$csv_data[$obj1->user_id][$obj2->id] = 1;
+		}
 	}
-	foreach ($csv_data as $username => $csv_subscriptions)
-	{
-		$user_id = 0;
-		$sql = "SELECT * FROM $user_table u WHERE u.username = '".mysql_real_escape_string($username)."'";
-		$res = api_sql_query($sql, __FILE__, __LINE__);
-		$obj = mysql_fetch_object($res);
-		$user_id = $obj->user_id;
-		$sql = "SELECT * FROM $class_user_table cu WHERE cu.user_id = $user_id";
-		$res = api_sql_query($sql, __FILE__, __LINE__);
-		$db_subscriptions = array ();
-		while ($obj = mysql_fetch_object($res))
-		{
+
+	// Logic for processing the request (data + UI options).
+	$db_subscriptions = array();
+	foreach ($csv_data as $user_id => $csv_subscriptions) {
+		$sql = "SELECT class_id FROM $class_user_table cu WHERE cu.user_id = $user_id";
+		$res = Database::query($sql, __FILE__, __LINE__);
+		while ($obj = Database::fetch_object($res)) {
 			$db_subscriptions[$obj->class_id] = 1;
 		}
 		$to_subscribe = array_diff(array_keys($csv_subscriptions), array_keys($db_subscriptions));
 		$to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csv_subscriptions));
-		if ($_POST['subscribe'])
-		{
-			foreach ($to_subscribe as $index => $class_id)
-			{
-				ClassManager :: add_user($user_id, $class_id);
-				//echo get_lang('Subscription').' : '.$course_code.'<br />';
+		// Subscriptions for new classes.
+		if ($_POST['subscribe']) {
+			foreach ($to_subscribe as $class_id) {
+				ClassManager::add_user($user_id, $class_id);
 			}
 		}
-		if ($_POST['unsubscribe'])
-		{
-			foreach ($to_unsubscribe as $index => $class_id)
-			{
-				ClassManager :: unsubscribe_user($user_id, $class_id);
-				//echo get_lang('Unsubscription').' : '.$course_code.'<br />';
+		// Unsubscription from previous classes.
+		if ($_POST['unsubscribe']) {
+			foreach ($to_unsubscribe as $class_id) {
+				ClassManager::unsubscribe_user($user_id, $class_id);
 			}
 		}
 	}
 }
+
 /**
- * Read the CSV-file
+ * Reads a CSV-file.
  * @param string $file Path to the CSV-file
  * @return array All course-information read from the file
  */
-function parse_csv_data($file)
-{
-	$courses = Import :: csv_to_array($file);
+function parse_csv_data($file) {
+	$courses = Import::csv_to_array($file);
 	return $courses;
 }
 
-// name of the language file that needs to be included 
-$language_file = array ('admin', 'registration');
+$language_file = array('admin', 'registration');
 
 $cidReset = true;
 
-include ('../inc/global.inc.php');
+include '../inc/global.inc.php';
 
+$this_section = SECTION_PLATFORM_ADMIN;
+api_protect_admin_script(true);
 
-require_once (api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'import.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-$formSent = 0;
-$errorMsg = '';
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'import.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
 $tool_name = get_lang('AddUsersToAClass').' CSV';
 
 $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 
+// Set this option to true to enforce strict purification for usenames.
+$purification_option_for_usernames = false;
+
 set_time_limit(0);
+
 $form = new FormValidator('class_user_import');
 $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
 $form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
 $form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
-$form->addElement('submit', 'submit', get_lang('Ok'));
-if ($form->validate())
-{
+$form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
+if ($form->validate()) {
 	$users_classes = parse_csv_data($_FILES['import_file']['tmp_name']);
 	$errors = validate_data($users_classes);
-	if (count($errors) == 0)
-	{
+	if (count($errors) == 0) {
 		save_data($users_classes);
 		header('Location: class_list.php?action=show_message&message='.urlencode(get_lang('FileImported')));
-		exit ();
+		exit();
 	}
 }
+
 Display :: display_header($tool_name);
 api_display_tool_title($tool_name);
-if (count($errors) != 0)
-{
+
+if (count($errors) != 0) {
 	$error_message = "\n";
-	foreach ($errors as $index => $error_class_user)
-	{
+	foreach ($errors as $index => $error_class_user) {
 		$error_message .= get_lang('Line').' '.$error_class_user['line'].': '.$error_class_user['error'].'</b>: ';
 		$error_message .= "\n";
 	}
@@ -202,7 +199,7 @@ $form->display();
 <pre>
 <b>UserName</b>;<b>ClassName</b>
 jdoe;class01
-a.dam;class01
+adam;class01
 </pre>
 </blockquote>
 <?php
@@ -213,4 +210,3 @@ a.dam;class01
 ==============================================================================
 */
 Display :: display_footer();
-?>

+ 69 - 69
main/admin/configure_extensions.php

@@ -20,7 +20,7 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file='admin';
 
 $cidReset=true;
@@ -45,8 +45,8 @@ require api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
 if(isset($_POST['activeExtension'])){
 
-	switch ($_POST['extension_code']){		
-		
+	switch ($_POST['extension_code']){
+
 		case 'visio' :
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="true"
@@ -55,7 +55,7 @@ if(isset($_POST['activeExtension'])){
 			$rs = api_sql_query($sql, __FILE__, __LINE__);
 			if(Database::affected_rows()>0)
 			{
-				
+
 				// select all the courses and insert the tool inside
 				$sql = 'SELECT db_name FROM '.Database::get_main_table(TABLE_MAIN_COURSE);
 				$rs = api_sql_query($sql, __FILE__, __LINE__);
@@ -67,7 +67,7 @@ if(isset($_POST['activeExtension'])){
 						$selectres = api_sql_query($select,__FILE__, __LINE__);
 						if(Database::num_rows($selectres)<1)
 						{
-							$sql = 'INSERT INTO '.$tool_table.' SET 
+							$sql = 'INSERT INTO '.$tool_table.' SET
 									name="'.TOOL_VISIO_CONFERENCE.'",
 									link="conference/index.php?type=conference",
 									image="visio.gif",
@@ -76,13 +76,13 @@ if(isset($_POST['activeExtension'])){
 									address="squaregrey.gif",
 									target="_self",
 									category="interaction"';
-							api_sql_query($sql, __FILE__, __LINE__);		
+							api_sql_query($sql, __FILE__, __LINE__);
 						}
 						$select = "SELECT id FROM $tool_table WHERE name='".TOOL_VISIO_CLASSROOM."'";
 						$selectres = api_sql_query($select,__FILE__, __LINE__);
 						if(Database::num_rows($selectres)<1)
 						{
-							$sql = 'INSERT INTO '.$tool_table.' SET 
+							$sql = 'INSERT INTO '.$tool_table.' SET
 									name="'.TOOL_VISIO_CLASSROOM.'",
 									link="conference/index.php?type=classroom",
 									image="visio.gif",
@@ -93,96 +93,96 @@ if(isset($_POST['activeExtension'])){
 									category="authoring"';
 							api_sql_query($sql, __FILE__, __LINE__);
 						}
-					}					
+					}
 				}
 				$message = get_lang('ServiceActivated');
-				
+
 			}
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="'.Database::escape_string($_POST['visio_host']).'"
 					WHERE variable="service_visio"
 					AND subkey="visio_host"';
 			$rs = api_sql_query($sql, __FILE__, __LINE__);
-			
+
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="'.Database::escape_string($_POST['visio_port']).'"
 					WHERE variable="service_visio"
 					AND subkey="visio_port"';
-			$rs = api_sql_query($sql, __FILE__, __LINE__);	
+			$rs = api_sql_query($sql, __FILE__, __LINE__);
 
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="'.Database::escape_string($_POST['visio_pass']).'"
 					WHERE variable="service_visio"
 					AND subkey="visio_pass"';
-			$rs = api_sql_query($sql, __FILE__, __LINE__);	
+			$rs = api_sql_query($sql, __FILE__, __LINE__);
 
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="'.($_POST['visio_use_rtmpt']=='true'?'true':'false').'"
 					WHERE variable="service_visio"
 					AND subkey="visio_use_rtmpt"';
-			$rs = api_sql_query($sql, __FILE__, __LINE__);	
-			
+			$rs = api_sql_query($sql, __FILE__, __LINE__);
+
 			if(empty($message))
 			{
 				$message = get_lang('ServiceReconfigured');
 			}
-			
-			
-			
-			
-			break;	
-			
+
+
+
+
+			break;
+
 		case 'ppt2lp' :
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="true"
 					WHERE variable="service_ppt2lp"
 					AND subkey="active"';
-					
+
 			$rs = api_sql_query($sql, __FILE__, __LINE__);
-			
+
 			if(Database::affected_rows()>0){
 				$message = get_lang('ServiceActivated');
 			}
-			
+
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="'.addslashes($_POST['host']).'"
 					WHERE variable="service_ppt2lp"
 					AND subkey="host"';
 			api_sql_query($sql, __FILE__, __LINE__);
-			
+
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="'.addslashes($_POST['port']).'"
 					WHERE variable="service_ppt2lp"
 					AND subkey="port"';
 			api_sql_query($sql, __FILE__, __LINE__);
-			
+
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="'.addslashes($_POST['ftp_password']).'"
 					WHERE variable="service_ppt2lp"
 					AND subkey="ftp_password"';
 			api_sql_query($sql, __FILE__, __LINE__);
-			
+
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="'.addslashes($_POST['user']).'"
 					WHERE variable="service_ppt2lp"
 					AND subkey="user"';
 			api_sql_query($sql, __FILE__, __LINE__);
-			
+
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="'.addslashes($_POST['path_to_lzx']).'"
 					WHERE variable="service_ppt2lp"
 					AND subkey="path_to_lzx"';
 			api_sql_query($sql, __FILE__, __LINE__);
-			
+
 			$sql = 'UPDATE '.$tbl_settings_current.' SET
 					selected_value="'.addslashes($_POST['size']).'"
 					WHERE variable="service_ppt2lp"
 					AND subkey="size"';
 			api_sql_query($sql, __FILE__, __LINE__);
-				
-			break;		
+
+			break;
 	}
-	
+
 }
 
 
@@ -204,7 +204,7 @@ if(isset($_GET['display'])){
 // javascript to handle accordion behaviour
 $javascript_message = '';
 if(!empty($message)){
-	$javascript_message = 
+	$javascript_message =
 	'
 	document.getElementById("message").style.display = "block";
 	var timer = setTimeout(hideMessage,5000);
@@ -219,12 +219,12 @@ window.onload = loadTables;
 function loadTables(){
 	'.$javascript_message.'
 	var listeDiv = document.getElementsByTagName("div");
-	
+
 	// fill extensionsHeader and extensionsContent
 	for(var i=0 ; i < listeDiv.length ; i++){
 		if(listeDiv[i].id.indexOf(\'extension_header\')!=-1){
 			listeDiv[i].onclick = afficheContent;
-			extensionsHeader.push(listeDiv[i]);		
+			extensionsHeader.push(listeDiv[i]);
 		}
 		if(listeDiv[i].id.indexOf("extension_content")!=-1){
 			extensionsContent.push(listeDiv[i]);
@@ -237,17 +237,17 @@ function hideMessage(){
 	document.getElementById("message").style.display = "none";
 }
 
-function afficheContent(event){	
+function afficheContent(event){
 	var id = this.id.replace("header","content");
 	switch(document.getElementById(id).style.display){
-		case "block" : 			
+		case "block" :
 			document.getElementById(id).style.display = "none";
 			break;
 		case "none" :
 			document.getElementById(id).style.display = "block";
 			for(var i=0 ; i < extensionsContent.length ; i++){
 				if(extensionsContent[i].id != id)
-					extensionsContent[i].style.display = "none";				
+					extensionsContent[i].style.display = "none";
 			}
 			break;
 	}
@@ -261,9 +261,9 @@ Display::display_header($nameTool);
 
 
 <div id="message" style="display: none">
-	<?php 
+	<?php
 	if(!empty($message))
-		Display::display_normal_message($message) 
+		Display::display_normal_message($message)
 	?>
 </div>
 
@@ -272,7 +272,7 @@ Display::display_header($nameTool);
 
 
 <!-- INSTRUCTIONS TO ADD AN EXTENSION HERE
-- copy paste a "main_*" div 
+- copy paste a "main_*" div
 - set the names of the subdiv to extension_header_yourextension and extension_content_yourextension
 - extension_content_yourextension is the hidden div where you have to put your form / activation process
 - extension_header_yourextension is the name of your extension
@@ -284,7 +284,7 @@ Display::display_header($nameTool);
 		<div id="extension_header_visio" class="accordion_header">
 			<a href="#"><?php echo get_lang('Visioconf') ?></a>
 		</div>
-		<div id="extension_content_visio" style="display:none" class="accordion_content">		
+		<div id="extension_content_visio" style="display:none" class="accordion_content">
 			<?php echo get_lang('VisioconfDescription') ?><br /><br />
 			<table width="100%">
 				<tr>
@@ -292,8 +292,8 @@ Display::display_header($nameTool);
 						<?php Display::display_icon('screenshot_conf.jpg', get_lang('Visioconf')); ?>
 					</td>
 					<!--td align="center" width="50%">
-						<?php 
-						$form = new FormValidator('visio');						
+						<?php
+						$form = new FormValidator('visio');
 						$form -> addElement('text', 'visio_host', get_lang('VisioHost'));
 						$form -> addElement('html','<br /><br />');
 						$form -> addElement('text', 'visio_port', get_lang('VisioPort'));
@@ -313,13 +313,13 @@ Display::display_header($nameTool);
 						$form -> addElement('html','<br /><br />');
 						if(in_array('service_visio',$listActiveServices))
 						{
-							$sql = 'SELECT subkey, selected_value FROM '.$tbl_settings_current.' 
+							$sql = 'SELECT subkey, selected_value FROM '.$tbl_settings_current.'
 									WHERE variable = "service_visio"';
 							$rs = api_sql_query($sql, __FILE__, __LINE__);
 							while($row = Database::fetch_array($rs,'ASSOC'))
 							{
 								$defaults[$row['subkey']] = $row['selected_value'];
-							}							
+							}
 							$form -> addElement('style_submit_button', 'activeExtension', get_lang('ReconfigureExtension'),'class="save"');
 						}
 						else {
@@ -333,13 +333,13 @@ Display::display_header($nameTool);
 			</table>
 		</div>
 	</div>
-	
+
 	<!-- PPT2LP -->
 	<div id="main_ppt2lp">
 		<div id="extension_header_ppt2lp" class="accordion_header">
 			<a href="#"><?php echo get_lang('Ppt2lp') ?></a>
 		</div>
-		<div id="extension_content_ppt2lp" style="display:none" class="accordion_content">		
+		<div id="extension_content_ppt2lp" style="display:none" class="accordion_content">
 			<?php echo get_lang('Ppt2lpDescription').' '.get_lang('Ppt2lpVoiceRecordingNeedsRed5') ?><br /><br />
 			<table width="100%">
 				<tr>
@@ -348,9 +348,9 @@ Display::display_header($nameTool);
 					</td>
 					<!--td align="center" width="50%">
 						<form method="POST" action="<?php echo api_get_self(); ?>">
-						<?php 
-						
-						$form = new FormValidator('ppt2lp');						
+						<?php
+
+						$form = new FormValidator('ppt2lp');
 						$form -> addElement('text', 'host', get_lang('Host'));
 						$form -> addElement('html','<br /><br />');
 						$form -> addElement('text', 'port', get_lang('Port'));
@@ -369,24 +369,24 @@ Display::display_header($nameTool);
 									'1000x750'=>'1000x750'
 									);
 						$form -> addElement('select', 'size', get_lang('SlideSize'), $options);
-						
-						
+
+
 						$form -> addElement('hidden', 'extension_code', 'ppt2lp');
-						
+
 						$defaults = array();
 						$renderer = $form -> defaultRenderer();
 						$renderer -> setElementTemplate('<div style="text-align:left">{label}</div><div style="text-align:left">{element}</div>');
 						$form -> addElement('html','<br /><br />');
 						if(in_array('service_ppt2lp',$listActiveServices))
 						{
-							$sql = 'SELECT subkey, selected_value FROM '.$tbl_settings_current.' 
+							$sql = 'SELECT subkey, selected_value FROM '.$tbl_settings_current.'
 									WHERE variable = "service_ppt2lp"
 									AND subkey <> "active"';
 							$rs = api_sql_query($sql, __FILE__, __LINE__);
 							while($row = Database::fetch_array($rs,'ASSOC'))
 							{
 								$defaults[$row['subkey']] = $row['selected_value'];
-							}							
+							}
 							$form -> addElement('style_submit_button', 'activeExtension', get_lang('ReconfigureExtension'),'class="save"');
 						}
 						else {
@@ -395,9 +395,9 @@ Display::display_header($nameTool);
 							$defaults['size'] = '720x540';
 							$form -> addElement('style_submit_button', 'activeExtension', get_lang('ActivateExtension'),'class="save"');
 						}
-						
+
 						$form -> setDefaults($defaults);
-						$form -> display();						
+						$form -> display();
 						echo '<br />';
 						?>
 						</form>
@@ -406,7 +406,7 @@ Display::display_header($nameTool);
 			</table>
 		</div>
 	</div>
-	<?php 
+	<?php
 	/*
 	<!-- EPHORUS -->
 	<div id="main_ephorus">
@@ -425,7 +425,7 @@ Display::display_header($nameTool);
 									<TBODY>
 										<TR>
 											<TD>
-												&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
+												&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 												<a title="http://www.ephorus.com/dokeos_activate.html" href="http://www.ephorus.com/dokeos_activate.html" target="_blank">
 												<?php Display::display_icon('ephorus.gif','Ephorus'); ?>
 												</a>
@@ -447,7 +447,7 @@ Display::display_header($nameTool);
 										<TBODY>
 											<TR>
 												<TD width="50">&nbsp;
-													 
+
 												</TD>
 												<TD>
 													<P>
@@ -467,7 +467,7 @@ Display::display_header($nameTool);
 								</TD>
 							</TR>
 						</TBODY>
-						</TABLE>						
+						</TABLE>
                     </td>
 				</tr>
 			</table>
@@ -480,7 +480,7 @@ Display::display_header($nameTool);
 		<div id="extension_header_search" class="accordion_header">
 			<a href="#"><?php echo get_lang('SearchEngine') ?></a>
 		</div>
-		<div id="extension_content_search" style="display:none" class="accordion_content">		
+		<div id="extension_content_search" style="display:none" class="accordion_content">
 			<?php echo get_lang('SearchEngineDescription') ?><br /><br />
 			<table width="100%">
 				<tr>
@@ -497,13 +497,13 @@ Display::display_header($nameTool);
 			</table>
 		</div>
 	</div>
-	
+
 	<!-- SERVER STATS -->
 	<div id="main_serverstats">
 		<div id="extension_header_serverstats" class="accordion_header">
 			<a href="#"><?php echo get_lang('ServerStatistics') ?></a>
 		</div>
-		<div id="extension_content_serverstats" style="display:none" class="accordion_content">		
+		<div id="extension_content_serverstats" style="display:none" class="accordion_content">
 			<?php echo get_lang('ServerStatisticsDescription') ?><br /><br />
 			<table width="100%">
 				<tr>
@@ -520,13 +520,13 @@ Display::display_header($nameTool);
 			</table>
 		</div>
 	</div>
-	
+
 	<!-- BANDWIDTH STATS -->
 	<div id="main_bandwidthstats">
 		<div id="extension_header_bandwidthstats" class="accordion_header">
 			<a href="#"><?php echo get_lang('BandWidthStatistics') ?></a>
 		</div>
-		<div id="extension_content_bandwidthstats" style="display:none" class="accordion_content">		
+		<div id="extension_content_bandwidthstats" style="display:none" class="accordion_content">
 			<?php echo get_lang('BandWidthStatisticsDescription') ?><br /><br />
 			<table width="100%">
 				<tr>
@@ -538,15 +538,15 @@ Display::display_header($nameTool);
 						<input type="hidden" name="extension_code" value="bandwidthstats" />
 						<button type="submit" class="save" name="activeExtension" value="<?php echo get_lang('ActivateExtension') ?>" ><?php echo get_lang('ActivateExtension') ?></button>
 						</form>
-						
+
 					</td>
 				</tr>
 			</table>
 		</div>
 	</div>
-	
+
 </div><!-- /content -->
-	
+
 
 <?php
 

+ 46 - 46
main/admin/configure_homepage.php

@@ -1,6 +1,6 @@
 <?php // $Id: configure_homepage.php 22243 2009-07-20 15:08:31Z ivantcholakov $
 /*
-===== =========================================================================
+==============================================================================
 	Dokeos - elearning and course management software
 
 	Copyright (c) 2004-2009 Dokeos SPRL
@@ -96,28 +96,28 @@ if(!empty($_SESSION['user_language_choice'])) {
 // ----- Ensuring availability of main files in the corresponding language -----
 
 if ($_configuration['multiple_access_urls']==true) {
-	$access_url_id = api_get_current_access_url_id();										 
-	if ($access_url_id != -1){						
+	$access_url_id = api_get_current_access_url_id();
+	if ($access_url_id != -1){
 		$url_info = api_get_access_url($access_url_id);
-		// "http://" and the final "/" replaced						
-		$url = substr($url_info['url'],7,strlen($url_info['url'])-8);						
+		// "http://" and the final "/" replaced
+		$url = substr($url_info['url'],7,strlen($url_info['url'])-8);
 		$clean_url = replace_dangerous_char($url);
 		$clean_url = str_replace('/','-',$clean_url);
 		$clean_url = $clean_url.'/';
-		
-		$homep = '../../home/'; //homep for Home Path			
-		$homep_new = '../../home/'.$clean_url; //homep for Home Path added the url				
+
+		$homep = '../../home/'; //homep for Home Path
+		$homep_new = '../../home/'.$clean_url; //homep for Home Path added the url
 		$new_url_dir = api_get_path(SYS_PATH).'home/'.$clean_url;
 		//we create the new dir for the new sites
-		if (!is_dir($new_url_dir)){		
+		if (!is_dir($new_url_dir)){
 			umask(0);
 			$perm = api_get_setting('permissions_for_new_directories');
 			$perm = octdec(!empty($perm)?$perm:'0755');
 			mkdir($new_url_dir, $perm);
-		}							
+		}
 	}
-} else {			
-	$homep_new ='';		
+} else {
+	$homep_new ='';
 	$homep = '../../home/'; //homep for Home Path
 }
 
@@ -135,15 +135,15 @@ foreach($homef as $my_file) {
 	if ($_configuration['multiple_access_urls']==true) {
 		if (!file_exists($homep_new.$my_file.'_'.$lang.$ext)) {
 			copy($homep.$my_file.$ext,$homep_new.$my_file.'_'.$lang.$ext);
-		}		
-	} else {	
+		}
+	} else {
 		if (!file_exists($homep.$my_file.'_'.$lang.$ext)) {
 			copy($homep.$my_file.$ext,$homep.$my_file.'_'.$lang.$ext);
 		}
 	}
 }
 if ($_configuration['multiple_access_urls']==true) {
-	$homep = $homep_new; 
+	$homep = $homep_new;
 }
 
 // Check WCAG settings and prepare edition using WCAG
@@ -179,11 +179,11 @@ if(!empty($action)) {
 					$home_top=WCAG_Rendering::prepareXHTML();
 				} else {
 					$home_top=trim(stripslashes($_POST['home_top']));
-				}				
-					
+				}
+
 				// Write
 				if (file_exists($homep.$topf.'_'.$lang.$ext)) {
-					if(is_writable($homep.$topf.'_'.$lang.$ext)) {						
+					if(is_writable($homep.$topf.'_'.$lang.$ext)) {
 						$fp=fopen($homep.$topf.'_'.$lang.$ext,"w");
 						fputs($fp,$home_top);
 						fclose($fp);
@@ -191,12 +191,12 @@ if(!empty($action)) {
 						$errorMsg=get_lang('HomePageFilesNotWritable');
 					}
 				} else {
-					//File does not exist					
+					//File does not exist
 					$fp=fopen($homep.$topf.'_'.$lang.$ext,"w");
 					fputs($fp,$home_top);
 					fclose($fp);
-				}				
-				
+				}
+
 				break;
 			case 'edit_notice':
 				// Filter
@@ -398,7 +398,7 @@ if(!empty($action)) {
 									fclose($fpo);
 								}
 							}
-								
+
 						} else {
 							$errorMsg=get_lang('HomePageFilesNotWritable');
 						}
@@ -454,14 +454,14 @@ if(!empty($action)) {
 				break;
 			case 'edit_top':
 				// This request is only the preparation for the update of the home_top
-				$home_top = '';			
+				$home_top = '';
 				if(is_file($homep.$topf.'_'.$lang.$ext) && is_readable($homep.$topf.'_'.$lang.$ext)) {
 					$home_top=file_get_contents($homep.$topf.'_'.$lang.$ext);
 				} elseif(is_file($homep.$topf.$lang.$ext) && is_readable($homep.$topf.$lang.$ext)) {
 					$home_top=file_get_contents($homep.$topf.$lang.$ext);
 				} else {
 					$errorMsg=get_lang('HomePageFilesNotReadable');
-				}		
+				}
 				break;
 			case 'edit_notice':
 				// This request is only the preparation for the update of the home_notice
@@ -622,7 +622,7 @@ switch($action){
 		}
 
 		?>
-		
+
 		<table border="0" cellpadding="5" cellspacing="0">
 		<tr><td colspan="2"><?php echo '<span style="font-style: italic;">'.get_lang('LetThoseFieldsEmptyToHideTheNotice').'</span>'; ?></tr>
 		<tr>
@@ -663,12 +663,12 @@ switch($action){
 		$default['link_name'] = api_htmlentities($link_name, ENT_QUOTES, $charset);
 		$form->addElement('text', 'link_name', get_lang('LinkName'), array('size' => '30', 'maxlength' => '50'));
 		$form->addElement('html', '</td></tr>');
-		
+
 		$form->addElement('html', '<tr><td nowrap="nowrap">'.get_lang('LinkURL').' ('.get_lang('Optional').') :</td><td>');
-		$default['link_url'] = empty($link_url) ? 'http://' : api_htmlentities($link_url, ENT_QUOTES, $charset); 
+		$default['link_url'] = empty($link_url) ? 'http://' : api_htmlentities($link_url, ENT_QUOTES, $charset);
 		$form->addElement('text', 'link_url', get_lang('LinkName'), array('size' => '30', 'maxlength' => '100', 'style' => 'width: 350px;'));
 		$form->addElement('html', '</td></tr>');
-		
+
 		if($action == 'insert_link') {
 			$form->addElement('html', '<tr><td nowrap="nowrap">'.get_lang('InsertThisLink').' :</td>');
 			$form->addElement('html', '<td><select name="insert_where"><option value="-1">'.get_lang('FirstPlace').'</option>');
@@ -729,7 +729,7 @@ switch($action){
 		$renderer->setElementTemplate('<tr><td>{element}</td></tr>');
 		$renderer->setRequiredNoteTemplate('');
 		$form->addElement('hidden', 'formSent', '1');
-		
+
 		if($action == 'edit_news'){
 			$_languages=api_get_languages();
 			$html = '<tr><td>'.get_lang('ChooseNewsLanguage').' : ';
@@ -764,14 +764,14 @@ switch($action){
 		break;
 	default: // When no action applies, default page to update campus homepage
 		?>
-		<table border="0" cellpadding="5" cellspacing="0" width="100%">	
+		<table border="0" cellpadding="5" cellspacing="0" width="100%">
 		<tr>
 		  <td width="80%" colspan="2" valign="top">
 		  	<div class="actions">
 			<a href="<?php echo api_get_self(); ?>?action=edit_top"><?php Display::display_icon('edit.gif', get_lang('EditHomePage')); ?></a>
 			<a href="<?php echo api_get_self(); ?>?action=edit_top"><?php echo get_lang('EditHomePage'); ?></a>
 		  	</div>
-		  	
+
 			<table border="0" cellpadding="5" cellspacing="0" width="100%">
 			<tr>
 			  <td colspan="2">
@@ -788,26 +788,26 @@ switch($action){
 			  </td>
 			</tr>
 			<tr>
-			<?php 
+			<?php
 			$access_url_id =1;
 			// we only show the category options for the main Dokeos installation
-			if ($_configuration['multiple_access_urls']==true) {					
-				$access_url_id = api_get_current_access_url_id();					
-			}			
-			echo '<td width="50%">';				
+			if ($_configuration['multiple_access_urls']==true) {
+				$access_url_id = api_get_current_access_url_id();
+			}
+			echo '<td width="50%">';
 			if ($access_url_id ==1) {
 				echo '<div class="actions">';
 				echo '<a href="course_category.php">'.Display::display_icon('edit.gif', get_lang('Edit')).'</a>
 					  <a href="course_category.php">'.get_lang('EditCategories').'</a>';
 				echo '</div>';
-			}			
+			}
 			echo '</td>
 				  <td width="50%">
-				  <br />';								
+				  <br />';
 			/* <!--<a href="<?php echo api_get_self(); ?>?action=edit_news"><?php Display::display_icon('edit.gif', get_lang('Edit')); ?></a> <a href="<?php echo api_get_self(); ?>?action=edit_news"><?php echo get_lang('EditNews'); ?></a>--> */
 			echo '</td></tr>
 				<tr>
-				<td width="50%" valign="top">				  	
+				<td width="50%" valign="top">
 				<table border="0" cellpadding="5" cellspacing="0" width="100%">';
 				if ($access_url_id ==1) {
 					if(sizeof($Categories)) {
@@ -818,19 +818,19 @@ switch($action){
 					} else {
 						echo get_lang('NoCategories');
 					}
-				}				
-				
+				}
+
 				echo '</table>';
 				?>
 			  </td>
 			  <!--<td width="50%" valign="top">
-				<?php				
+				<?php
 				if(file_exists($homep.$newsf.'_'.$lang.$ext)) {
 					include ($homep.$newsf.'_'.$lang.$ext);
 				} else {
 					include ($homep.$newsf.$ext);
 				}
-				
+
 			?>
 			  </td>-->
 			</tr>
@@ -861,12 +861,12 @@ switch($action){
 				<li><span style="color: #9D9DA1; font-weight: bold;"><?php echo api_ucfirst(get_lang('LostPassword')); ?></span></li>
 				</ul>
 			</div>
-			
-			
+
+
 			<br />
 			<a href="<?php echo api_get_self(); ?>?action=insert_link"><?php Display::display_icon('insert_row.png', get_lang('InsertLink')); ?></a>
 			<a href="<?php echo api_get_self(); ?>?action=insert_link"/><?php echo get_lang('InsertLink'); ?></a>
-			
+
 			<div class="menusection">
 				<span class="menusectioncaption"><?php echo api_ucfirst(get_lang('General')); ?></span>
 				<ul class="menulist">

+ 7 - 7
main/admin/course_add.php

@@ -35,7 +35,7 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file = array('admin','create_course');
 $cidReset = true;
 require_once ('../inc/global.inc.php');
@@ -65,10 +65,10 @@ $table_user = Database :: get_main_table(TABLE_MAIN_USER);
 $sql = "SELECT user_id,lastname,firstname FROM $table_user WHERE status=1".$order_clause;
 //filtering teachers when creating a course
 if ($_configuration['multiple_access_urls']==true){
-	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);   	
+	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 	$sql = "SELECT u.user_id,lastname,firstname FROM $table_user as u
-			INNER JOIN $access_url_rel_user_table url_rel_user 
-			ON (u.user_id=url_rel_user.user_id) WHERE url_rel_user.access_url_id=".api_get_current_access_url_id()." AND status=1".$order_clause;  
+			INNER JOIN $access_url_rel_user_table url_rel_user
+			ON (u.user_id=url_rel_user.user_id) WHERE url_rel_user.access_url_id=".api_get_current_access_url_id()." AND status=1".$order_clause;
 }
 
 $res = api_sql_query($sql,__FILE__,__LINE__);
@@ -85,7 +85,7 @@ $dbnamelength = strlen($_configuration['db_prefix']);
 $maxlength = 40 - $dbnamelength;
 
 // Build the form
-$form = new FormValidator('update_course'); 
+$form = new FormValidator('update_course');
 $form->addElement('header', '', $tool_name);
 $form->add_textfield( 'visual_code', get_lang('CourseCode'),false,array('size'=>'20','maxlength'=>20));
 $form->applyFilter('visual_code','api_strtoupper');
@@ -111,7 +111,7 @@ $form->add_textfield('department_name', get_lang('CourseDepartment'),false, arra
 $form->applyFilter('department_name','html_filter');
 $form->applyFilter('department_name','trim');
 
-//Department URL 
+//Department URL
 $form->add_textfield('department_url', get_lang('CourseDepartmentURL'),false, array ('size' => '60'));
 $form->applyFilter('department_url','html_filter');
 
@@ -148,7 +148,7 @@ if( $form->validate()) {
 	$teacher_id = $course['tutor_id'];
 	$course_teachers = $course['course_teachers'];
 	$test=false;
-	
+
 	//The course tutor has been selected in the teachers list so we must remove him to avoid double records in the database
 	foreach($course_teachers as $key=>$value){
 		if($value==$teacher_id){

+ 27 - 27
main/admin/course_category.php

@@ -28,7 +28,7 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file='admin';
 
 $cidReset=true;
@@ -132,54 +132,54 @@ if(empty($action))
 	$Categories=api_store_result($result);
 }
 
-	
-	
+
+
 
 if($action == 'add' || $action == 'edit')
 {
 	?>
 	<div class="actions">
 	<a href="<?php echo api_get_self(); ?>?category=<?php echo Security::remove_XSS($category); ?>"><?php echo Display::return_icon('folder_up.gif').get_lang("Back"); if(!empty($category)) echo ' ('.Security::remove_XSS($category).')'; ?></a>
-	</div>	
-	
-	
+	</div>
+
 
-	<?php 
-	$form_title = ($action == 'add')?get_lang('AddACategory'):get_lang('EditNode'); 
+
+	<?php
+	$form_title = ($action == 'add')?get_lang('AddACategory'):get_lang('EditNode');
 	if(!empty($category))
 	{
-		$form_title .= ' '.get_lang('Into').' '.Security::remove_XSS($category); 
+		$form_title .= ' '.get_lang('Into').' '.Security::remove_XSS($category);
 	}
-	
+
 	$form = new FormValidator('course_category');
 	$form->addElement('header', '', $form_title);
 	$form->display();
-	
+
 	?>
-	
+
 	<form method="post" action="<?php echo api_get_self(); ?>?action=<?php echo Security::remove_XSS($action); ?>&category=<?php echo Security::remove_XSS($category); ?>&amp;id=<?php echo Security::remove_XSS($_GET['id']); ?>">
 	<input type="hidden" name="formSent" value="1" />
 	<table border="0" cellpadding="5" cellspacing="0">
-	
+
 	<?php
 	if(!empty($errorMsg))
 	{
 	?>
-	
+
 	<tr>
 	  <td colspan="2">
-	
+
 	<?php
 		Display::display_normal_message($errorMsg); //main API
 	?>
-	
+
 	  </td>
 	</tr>
-	
+
 	<?php
 	}
 	?>
-	
+
 	<tr>
 	  <td nowrap="nowrap"><?php echo get_lang("CategoryCode"); ?> :</td>
 	  <td><input type="text" name="categoryCode" size="20" maxlength="20" value="<?php echo api_htmlentities(stripslashes($categoryCode),ENT_QUOTES,$charset); ?>" /></td>
@@ -203,21 +203,21 @@ if($action == 'add' || $action == 'edit')
 			$text=get_lang('CategoryMod');
 		} else {
 			$class="add";
-			$text=get_lang('AddCategory'); 
+			$text=get_lang('AddCategory');
 		}
 	  ?>
 	  <td><button type="submit" class="<?php echo $class; ?>" value="<?php echo $text; ?>" ><?php echo $text; ?></button></td>
 	</tr>
 	</table>
 	</form>
-	
+
 	<?php
 }
 else
 {
 ?>
 <div class="actions">
-<?php 
+<?php
 if(!empty($category) && empty($action))
 {
 	$myquery = "SELECT parent_id FROM $tbl_category WHERE code='$category'";
@@ -226,13 +226,13 @@ if(!empty($category) && empty($action))
 	if(Database::num_rows($result)>0){
 		$parent_id=Database::fetch_array($result);
 	}
-	
+
 	$parent_id['parent_id']?$link=' ('.$parent_id['parent_id'].')':$link='';
 	?>
 
 	<a href="<?php echo api_get_self(); ?>?category=<?php echo $parent_id['parent_id']; ?>"><?php echo Display::return_icon('folder_up.gif').get_lang("Back"); if(!empty($parent_id)) echo $link ?></a>
 
-	<?php 
+	<?php
 }
 ?>
 <a href="<?php echo api_get_self(); ?>?category=<?php echo Security::remove_XSS($category); ?>&amp;action=add"><?php echo Display::return_icon('folder_new.gif').get_lang("AddACategory"); if(!empty($category)) echo ' '.get_lang('Into').' '.Security::remove_XSS($category); ?></a>
@@ -271,9 +271,9 @@ else
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
-*/ 
+*/
 Display::display_footer();
 
 /******** Functions ********/
@@ -315,7 +315,7 @@ function addNode($code,$name,$canHaveCourses,$parent_id)
 	$canHaveCourses=$canHaveCourses?'TRUE':'FALSE';
 	$code 			= Database::escape_string($code);
 	$name 			= Database::escape_string($name);
-	$parent_id		= Database::escape_string($parent_id);	
+	$parent_id		= Database::escape_string($parent_id);
 
 	$result=api_sql_query("SELECT 1 FROM $tbl_category WHERE code='$code'",__FILE__,__LINE__);
 
@@ -367,7 +367,7 @@ function moveNodeUp($code,$tree_pos,$parent_id)
 	$code 		= Database::escape_string($code);
 	$tree_pos 	= Database::escape_string($tree_pos);
 	$parent_id	= Database::escape_string($parent_id);
-	
+
 	$result=api_sql_query("SELECT code,tree_pos FROM $tbl_category WHERE parent_id ".(empty($parent_id)?"IS NULL":"='$parent_id'")." AND tree_pos<'$tree_pos' ORDER BY tree_pos DESC LIMIT 0,1",__FILE__,__LINE__);
 
 	if(!$row=Database::fetch_array($result))

+ 12 - 12
main/admin/course_create_content.php

@@ -1,32 +1,32 @@
 <?php
 // $Id: course_create_content.php 10811 2007-01-22 08:26:40Z elixir_julian $
 /*
-============================================================================== 
+==============================================================================
 	Dokeos - elearning and course management software
-	
+
 	Copyright (c) 2004 Dokeos S.A.
 	Copyright (c) 2003 Ghent University (UGent)
 	Copyright (c) 2001 Universite catholique de Louvain (UCL)
 	Copyright (c) Bart Mollet (bart.mollet@hogent.be)
-	
+
 	For a full list of contributors, see "credits.txt".
 	The full license can be read in "license.txt".
-	
+
 	This program is free software; you can redistribute it and/or
 	modify it under the terms of the GNU General Public License
 	as published by the Free Software Foundation; either version 2
 	of the License, or (at your option) any later version.
-	
+
 	See the GNU General Public License for more details.
-	
+
 	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
-============================================================================== 
+==============================================================================
 */
 /**
  * ==============================================================================
  * This script allows a platform admin to add dummy content to a course.
- * 
+ *
  * @author Bart Mollet <bart.mollet@hogent.be>
  * @package dokeos.admin
  * ==============================================================================
@@ -35,9 +35,9 @@
 ==============================================================================
 		INIT SECTION
 ==============================================================================
-*/ 
+*/
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file = 'admin';
 include ('../inc/global.inc.php');
 $this_section=SECTION_PLATFORM_ADMIN;
@@ -49,7 +49,7 @@ Display::display_header($tool_name);
 //api_display_tool_title($tool_name);
 if(api_get_setting('server_type') != 'test')
 {
-	echo get_lang('DummyCourseOnlyOnTestServer');	
+	echo get_lang('DummyCourseOnlyOnTestServer');
 }
 elseif( isset($_POST['action']))
 {
@@ -65,7 +65,7 @@ else
 }
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display::display_footer();

+ 4 - 4
main/admin/course_edit.php

@@ -132,7 +132,7 @@ EOT;
 $renderer = $form->defaultRenderer();
 $renderer -> setElementTemplate($element_template, 'group');
 $form -> addGroup($group,'group',get_lang('CourseTeachers'),'</td><td width="50" align="center"><input type="button" onclick="moveItem(document.getElementById(\'platform_teachers\'), document.getElementById(\'course_teachers\'))" value=">>"><br><br><input type="button" onclick="moveItem(document.getElementById(\'course_teachers\'), document.getElementById(\'platform_teachers\'))" value="<<"></td><td>');
-//title 
+//title
 $form->add_textfield( 'title', get_lang('Title'),true, array ('size' => '60'));
 $form->applyFilter('title','html_filter');
 $form->applyFilter('title','trim');
@@ -228,14 +228,14 @@ if( $form->validate())
 	$cond='';
 	if(count($teachers)>0){
 		foreach($teachers as $key) $cond.=" AND user_id<>'".$key."'";
-	}	
+	}
 	$sql='DELETE FROM '.$course_user_table.' WHERE course_code="'.Database::escape_string($course_code).'" AND status="1"'.$cond;
 	api_sql_query($sql, __FILE__, __LINE__);
 
 	if(count($teachers)>0){
 		foreach($teachers as $key){
 
-			//We check if the teacher is already subscribed in this course 
+			//We check if the teacher is already subscribed in this course
 			$sql_select_teacher = 'SELECT 1 FROM '.$course_user_table.' WHERE user_id = "'.$key.'" AND course_code = "'.$course_code.'"';
 			$result = api_sql_query($sql_select_teacher, __FILE__, __LINE__);
 
@@ -271,7 +271,7 @@ if( $form->validate())
 	$forum_config_table = Database::get_course_table(TOOL_FORUM_CONFIG_TABLE,$course_db_name);
 	$sql = "UPDATE ".$forum_config_table." SET default_lang='".Database::escape_string($course_language)."'";
 	if ($visual_code_is_used == true) {
-	    header('Location: course_list.php?action=show_msg&warn='.urlencode($warn));	
+	    header('Location: course_list.php?action=show_msg&warn='.urlencode($warn));
 	} else {
         header('Location: course_list.php');
 	}

+ 59 - 79
main/admin/course_import.php

@@ -26,11 +26,13 @@
 * @package dokeos.admin
 ==============================================================================
 */
+
 /**
- * validate the imported data
+ * Validates imported data.
  */
 function validate_data($courses) {
-	global $_configuration;	
+	global $_configuration;
+	global $purification_option_for_usernames;
 	$dbnamelength = strlen($_configuration['db_prefix']);
 	//Ensure the prefix + database name do not get over 40 characters
 	$maxlength = 40 - $dbnamelength;
@@ -39,30 +41,31 @@ function validate_data($courses) {
 	$coursecodes = array ();
 	foreach ($courses as $index => $course) {
 		$course['line'] = $index +1;
-		//1. check if mandatory fields are set
+		// 1. Check whether mandatory fields are set.
 		$mandatory_fields = array ('Code', 'Title', 'CourseCategory', 'Teacher');
 		foreach ($mandatory_fields as $key => $field) {
-			if (!isset ($course[$field]) || strlen($course[$field]) == 0)
-			{
+			if (!isset($course[$field]) || strlen($course[$field]) == 0) {
 				$course['error'] = get_lang($field.'Mandatory');
 				$errors[] = $course;
 			}
 		}
-		//2. check if code isn't in use
+		// 2. Check current course code.
 		if (isset ($course['Code']) && strlen($course['Code']) != 0) {
-			//2.1 check if code allready used in this CVS-file
+			// 2.1 Check whether code has been allready used by this CVS-file.
 			if (isset ($coursecodes[$course['Code']])) {
 				$course['error'] = get_lang('CodeTwiceInFile');
 				$errors[] = $course;
-			} elseif (api_strlen($course['Code']) > $maxlength) {
+			}
+			// 2.2 Check course code length.
+			elseif (api_strlen($course['Code']) > $maxlength) {
 				$course['error'] = get_lang('Max');
 				$errors[] = $course;
 			}
-			//2.3 check if code allready used in DB
+			// 2.3 Check whether course code has been occupied.
 			else {
 				$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
 				$sql = "SELECT * FROM $course_table WHERE code = '".Database::escape_string($course['Code'])."'";
-				$res = api_sql_query($sql, __FILE__, __LINE__);
+				$res = Database::query($sql, __FILE__, __LINE__);
 				if (Database::num_rows($res) > 0) {
 					$course['error'] = get_lang('CodeExists');
 					$errors[] = $course;
@@ -70,23 +73,20 @@ function validate_data($courses) {
 			}
 			$coursecodes[$course['Code']] = 1;
 		}
-		//3. check if teacher exists
-		if (isset ($course['Teacher']) && strlen($course['Teacher']) != 0)
-		{
-			if (UserManager :: is_username_available($course['Teacher']))
-			{
-				$course['error'] = get_lang('UnknownTeacher').' ('.$course['Teacher'].')';
+		// 3. Check whether teacher exists.
+		if (!UserManager::is_username_empty($course['Teacher'])) {
+			$teacher = UserManager::purify_username($course['Teacher'], $purification_option_for_usernames);
+			if (UserManager::is_username_available($teacher)) {
+				$course['error'] = get_lang('UnknownTeacher').' ('.$teacher.')';
 				$errors[] = $course;
 			}
 		}
-		//4. check if category exists
-		if (isset ($course['CourseCategory']) && strlen($course['CourseCategory']) != 0)
-		{
+		// 4. Check whether course category exists.
+		if (isset ($course['CourseCategory']) && strlen($course['CourseCategory']) != 0) {
 			$category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
-			$sql = "SELECT * FROM $category_table WHERE code = '".mysql_real_escape_string($course['CourseCategory'])."'";
-			$res = api_sql_query($sql, __FILE__, __LINE__);
-			if (mysql_num_rows($res) == 0)
-			{
+			$sql = "SELECT * FROM $category_table WHERE code = '".Database::escape_string($course['CourseCategory'])."'";
+			$res = Database::query($sql, __FILE__, __LINE__);
+			if (Database::num_rows($res) == 0) {
 				$course['error'] = get_lang('UnkownCategory').' ('.$course['CourseCategory'].')';
 				$errors[] = $course;
 			}
@@ -96,31 +96,24 @@ function validate_data($courses) {
 }
 
 /**
- * Save the imported data
- * @param   array   List of courses info
+ * Saves imported data.
+ * @param   array   List of courses
  */
-function save_data($courses)
-{
+function save_data($courses) {
 	global $_configuration, $firstExpirationDelay;
+	global $purification_option_for_usernames;
 	$msg = '';
-	$enabled_languages = api_get_languages();
-	$enabled_languages = $enabled_languages["folder"];
-	foreach($courses as $index => $course)
-	{
-		$course_language = $course['Language'];
-		if (empty($course_language) || !in_array($course_language, $enabled_languages))
-		{
-			$course_language = api_get_setting('platformLanguage');
-		}
-		$keys = define_course_keys($course['Code'], "", $_configuration['db_prefix']);
+	foreach ($courses as $index => $course) {
+		$course_language = api_validate_language($course['Language']);
+		$keys = define_course_keys($course['Code'], '', $_configuration['db_prefix']);
 		$user_table = Database::get_main_table(TABLE_MAIN_USER);
-		$sql = "SELECT user_id, ".(api_is_western_name_order(null, $course_language) ? "CONCAT(firstname,' ',lastname)" : "CONCAT(lastname,' ',firstname)")." AS name FROM $user_table WHERE username = '".Database::escape_string($course['Teacher'])."'";
-		$res = api_sql_query($sql,__FILE__,__LINE__);
-		$teacher = mysql_fetch_object($res);
-		$visual_code = $keys["currentCourseCode"];
-		$code = $keys["currentCourseId"];
-		$db_name = $keys["currentCourseDbName"];
-		$directory = $keys["currentCourseRepository"];
+		$sql = "SELECT user_id, ".(api_is_western_name_order(null, $course_language) ? "CONCAT(firstname,' ',lastname)" : "CONCAT(lastname,' ',firstname)")." AS name FROM $user_table WHERE username = '".Database::escape_string(UserManager::purify_username($course['Teacher'], $purification_option_for_usernames))."'";
+		$res = Database::query($sql,__FILE__,__LINE__);
+		$teacher = Database::fetch_object($res);
+		$visual_code = $keys['currentCourseCode'];
+		$code = $keys['currentCourseId'];
+		$db_name = $keys['currentCourseDbName'];
+		$directory = $keys['currentCourseRepository'];
 		$expiration_date = time() + $firstExpirationDelay;
 		prepare_course_repository($directory, $code);
 		update_Db_course($db_name);
@@ -130,16 +123,16 @@ function save_data($courses)
 		$msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$directory.'/">'.$code.'</a> '.get_lang('Created').'<br />';
 	}
     if (!empty($msg)) {
-        Display::display_normal_message($msg,false);    	
+        Display::display_normal_message($msg,false);
     }
 }
+
 /**
  * Read the CSV-file
  * @param string $file Path to the CSV-file
  * @return array All course-information read from the file
  */
-function parse_csv_data($file)
-{
+function parse_csv_data($file) {
 	$courses = Import :: csv_to_array($file);
 	return $courses;
 }
@@ -148,43 +141,39 @@ $language_file = array ('admin', 'registration','create_course', 'document');
 
 $cidReset = true;
 
-include ('../inc/global.inc.php');
+include '../inc/global.inc.php';
+
+$this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
-require_once (api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'import.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-require_once (api_get_path(CONFIGURATION_PATH).'add_course.conf.php');
-require_once (api_get_path(LIBRARY_PATH).'add_course.lib.inc.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-$formSent = 0;
-$errorMsg = '';
+
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'import.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
+require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+
 $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
-if (is_array($extAuthSource))
-{
+if (is_array($extAuthSource)) {
 	$defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
 }
 
 $tool_name = get_lang('ImportCourses').' CSV';
 
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 
 set_time_limit(0);
 Display :: display_header($tool_name);
 
-if ($_POST['formSent'])
-{
-	if(empty($_FILES['import_file']['tmp_name']))
-	{
+if ($_POST['formSent']) {
+	if (empty($_FILES['import_file']['tmp_name'])) {
 		$error_message = get_lang('UplUploadFailed');
 		Display :: display_error_message($error_message, false);
-	}
-	else
-	{
+	} else {
 		$file_type = $_POST['file_type'];
 		$courses = parse_csv_data($_FILES['import_file']['tmp_name']);
 		$errors = validate_data($courses);
-		if (count($errors) == 0)
-		{
+		if (count($errors) == 0) {
 			//$users = complete_missing_data($courses);
 			save_data($courses);
 			//header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('FileImported')));
@@ -193,11 +182,9 @@ if ($_POST['formSent'])
 	}
 }
 
-if (count($errors) != 0)
-{
+if (count($errors) != 0) {
 	$error_message = '<ul>';
-	foreach ($errors as $index => $error_course)
-	{
+	foreach ($errors as $index => $error_course) {
 		$error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <b>'.$error_course['error'].'</b>: ';
 		$error_message .= $error_course['Code'].' '.$error_course['Title'];
 		$error_message .= '</li>';
@@ -239,11 +226,4 @@ BIO0015;Biology;BIO;username;english
 
 <?php
 
-
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
 Display :: display_footer();
-?>

+ 4 - 4
main/admin/course_information.php

@@ -11,7 +11,7 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file = 'admin';
 $cidReset = true;
 require ('../inc/global.inc.php');
@@ -20,7 +20,7 @@ $this_section=SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 /**
- * 
+ *
  */
 function get_course_usage($course_code)
 {
@@ -183,8 +183,8 @@ else
 }
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
-*/ 
+*/
 Display::display_footer();
 ?>

+ 28 - 28
main/admin/course_list.php

@@ -11,7 +11,7 @@
 ==============================================================================
 */
 
-// name of the language file that needs to be included 
+// name of the language file that needs to be included
 $language_file = array('admin','courses');
 $cidReset = true;
 require ('../inc/global.inc.php');
@@ -25,18 +25,18 @@ require_once '../gradebook/lib/be/gradebookitem.class.php';
 require_once '../gradebook/lib/be/category.class.php';
 /**
  * Get the number of courses which will be displayed
- */ 
+ */
 function get_number_of_courses()
 {
 	$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
 	$sql = "SELECT COUNT(code) AS total_number_of_items FROM $course_table";
-	
+
 	global $_configuration;
     if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
     	$access_url_rel_course_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-    	$sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (code=url_rel_course.course_code)";    		
+    	$sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (code=url_rel_course.course_code)";
     }
-    
+
 	if (isset ($_GET['keyword']))
 	{
 		$keyword = Database::escape_string($_GET['keyword']);
@@ -53,12 +53,12 @@ function get_number_of_courses()
 		$keyword_unsubscribe = Database::escape_string($_GET['keyword_unsubscribe']);
 		$sql .= " WHERE (code LIKE '%".$keyword_code."%' OR visual_code LIKE '%".$keyword_code."%') AND title LIKE '%".$keyword_title."%' AND category_code LIKE '%".$keyword_category."%'  AND course_language LIKE '%".$keyword_language."%'   AND visibility LIKE '%".$keyword_visibility."%'    AND subscribe LIKE '".$keyword_subscribe."'AND unsubscribe LIKE '".$keyword_unsubscribe."'";
 	}
-	
+
 	 // adding the filter to see the user's only of the current access_url
-	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {		
-    		$sql.= " AND url_rel_course.access_url_id=".api_get_current_access_url_id();   	  
+	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
+    		$sql.= " AND url_rel_course.access_url_id=".api_get_current_access_url_id();
     }
-    
+
 	$res = api_sql_query($sql, __FILE__, __LINE__);
 	$obj = Database::fetch_object($res);
 	return $obj->total_number_of_items;
@@ -71,15 +71,15 @@ function get_course_data($from, $number_of_items, $column, $direction)
 	$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
 	$users_table = Database :: get_main_table(TABLE_MAIN_USER);
 	$course_users_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-	
+
 	$sql = "SELECT code AS col0, visual_code AS col1, title AS col2, course_language AS col3, category_code AS col4, subscribe AS col5, unsubscribe AS col6, code AS col7, tutor_name as col8, code AS col9, visibility AS col10,directory as col11 FROM $course_table";
-	
+
 	global $_configuration;
     if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
     	$access_url_rel_course_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-    	$sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (code=url_rel_course.course_code)";    		
-    }    
-    
+    	$sql.= " INNER JOIN $access_url_rel_course_table url_rel_course ON (code=url_rel_course.course_code)";
+    }
+
 	if (isset ($_GET['keyword']))
 	{
 		$keyword = Database::escape_string($_GET['keyword']);
@@ -96,10 +96,10 @@ function get_course_data($from, $number_of_items, $column, $direction)
 		$keyword_unsubscribe = Database::escape_string($_GET['keyword_unsubscribe']);
 		$sql .= " WHERE (code LIKE '%".$keyword_code."%' OR visual_code LIKE '%".$keyword_code."%') AND title LIKE '%".$keyword_title."%' AND category_code LIKE '%".$keyword_category."%'  AND course_language LIKE '%".$keyword_language."%'   AND visibility LIKE '%".$keyword_visibility."%'    AND subscribe LIKE '".$keyword_subscribe."'AND unsubscribe LIKE '".$keyword_unsubscribe."'";
 	}
-	
+
 	 // adding the filter to see the user's only of the current access_url
-	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {		
-    		$sql.= " AND url_rel_course.access_url_id=".api_get_current_access_url_id();   	  
+	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
+    		$sql.= " AND url_rel_course.access_url_id=".api_get_current_access_url_id();
     }
 
 	$sql .= " ORDER BY col$column $direction ";
@@ -241,10 +241,10 @@ else
 	{
 
 		CourseManager :: delete_course($_GET['delete_course']);
-		
+
 		$obj_cat=new Category();
 		$obj_cat->update_category_delete($_GET['delete_course']);
-		
+
 	}
 	// Create a search-box
 	$form = new FormValidator('search_simple','get','','','width=200px',false);
@@ -254,16 +254,16 @@ else
 	$form->addElement('style_submit_button', 'submit', get_lang('SearchCourse'),'class="search"');
 	$form->addElement('static','search_advanced_link',null,'<a href="course_list.php?search=advanced">'.get_lang('AdvancedSearch').'</a>');
 	echo '<div style="float:right;margin-top:5px;margin-right:5px;">
-			  <a href="'.api_get_path(WEB_CODE_PATH).'admin/course_add.php">'.Display::return_icon('course_add.gif',get_lang('AddSession')).get_lang('AddCourse').'</a>									
+			  <a href="'.api_get_path(WEB_CODE_PATH).'admin/course_add.php">'.Display::return_icon('course_add.gif',get_lang('AddSession')).get_lang('AddCourse').'</a>
 		 </div>';
-		 
-	echo '<div class="actions">';		
-		$form->display();				
+
+	echo '<div class="actions">';
+		$form->display();
 	echo '</div>';
 	// Create a sortable table with the course data
 	$table = new SortableTable('courses', 'get_number_of_courses', 'get_course_data',2);
 	$parameters=array();
-	
+
 	if (isset ($_GET['keyword'])) {
 		$parameters = array ('keyword' => Security::remove_XSS($_GET['keyword']));
 	} elseif (isset ($_GET['keyword_code'])) {
@@ -275,7 +275,7 @@ else
 		$parameters['keyword_subscribe'] = Security::remove_XSS($_GET['keyword_subscribe']);
 		$parameters['keyword_unsubscribe'] = Security::remove_XSS($_GET['keyword_unsubscribe']);
 	}
-		
+
 	$table->set_additional_parameters($parameters);
 	$table->set_header(0, '', false);
 	$table->set_header(1, get_lang('Code'));
@@ -286,14 +286,14 @@ else
 	$table->set_header(6, get_lang('UnsubscriptionAllowed'));
 	$table->set_header(7, get_lang('IsVirtualCourse'));
 	$table->set_header(8, get_lang('Teacher'));
-	$table->set_header(9, get_lang('Modify'), false,'width="120px"');	
-	$table->set_column_filter(9,'modify_filter');	
+	$table->set_header(9, get_lang('Modify'), false,'width="120px"');
+	$table->set_column_filter(9,'modify_filter');
 	$table->set_form_actions(array ('delete_courses' => get_lang('DeleteCourse')),'course');
 	$table->display();
 }
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 68 - 89
main/admin/course_user_import.php

@@ -7,61 +7,50 @@
 * @package dokeos.admin
 ==============================================================================
 */
+
 /**
- * validate the imported data
+ * Validates the imported data.
  */
-function validate_data($users_courses)
-{
+function validate_data($users_courses) {
 	$errors = array ();
 	$coursecodes = array ();
-	foreach ($users_courses as $index => $user_course)
-	{
+	foreach ($users_courses as $index => $user_course) {
 		$user_course['line'] = $index +1;
-		//1. check if mandatory fields are set
+		// 1. Check whether mandatory fields are set.
 		$mandatory_fields = array ('UserName', 'CourseCode', 'Status');
-		foreach ($mandatory_fields as $key => $field)
-		{
-			if (!isset ($user_course[$field]) || strlen($user_course[$field]) == 0)
-			{
+		foreach ($mandatory_fields as $key => $field) {
+			if (!isset($user_course[$field]) || strlen($user_course[$field]) == 0) {
 				$user_course['error'] = get_lang($field.'Mandatory');
 				$errors[] = $user_course;
 			}
 		}
-		//2. check if coursecode exists
-		if (isset ($user_course['CourseCode']) && strlen($user_course['CourseCode']) != 0)
-		{
-			//2.1 check if code allready used in this CVS-file
-			if (!isset ($coursecodes[$user_course['CourseCode']]))
-			{
-				//2.1.1 check if code exists in DB
+		// 2. Check whether coursecode exists.
+		if (isset ($user_course['CourseCode']) && strlen($user_course['CourseCode']) != 0) {
+			// 2.1 Check whethher code has been allready used by this CVS-file.
+			if (!isset($coursecodes[$user_course['CourseCode']])) {
+				// 2.1.1 Check whether course with this code exists in the system.
 				$course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
-				$sql = "SELECT * FROM $course_table WHERE code = '".mysql_real_escape_string($user_course['CourseCode'])."'";
-				$res = api_sql_query($sql, __FILE__, __LINE__);
-				if (mysql_num_rows($res) == 0)
-				{
+				$sql = "SELECT * FROM $course_table WHERE code = '".Database::escape_string($user_course['CourseCode'])."'";
+				$res = Database::query($sql, __FILE__, __LINE__);
+				if (Database::num_rows($res) == 0) {
 					$user_course['error'] = get_lang('CodeDoesNotExists');
 					$errors[] = $user_course;
-				}
-				else
-				{
+				} else {
 					$coursecodes[$user_course['CourseCode']] = 1;
 				}
 			}
 		}
-		//3. check if username exists
+		// 3. Check whether username exists.
 		if (isset ($user_course['UserName']) && strlen($user_course['UserName']) != 0)
 		{
-			if (UserManager :: is_username_available($user_course['UserName']))
-			{
+			if (UserManager::is_username_available($user_course['UserName'])) {
 				$user_course['error'] = get_lang('UnknownUser');
 				$errors[] = $user_course;
 			}
 		}
-		//4. check if status is valid
-		if (isset ($user_course['Status']) && strlen($user_course['Status']) != 0)
-		{
-			if ($user_course['Status'] != COURSEMANAGER && $user_course['Status'] != STUDENT)
-			{
+		// 4. Check whether status is valid.
+		if (isset ($user_course['Status']) && strlen($user_course['Status']) != 0) {
+			if ($user_course['Status'] != COURSEMANAGER && $user_course['Status'] != STUDENT) {
 				$user_course['error'] = get_lang('UnknownStatus');
 				$errors[] = $user_course;
 			}
@@ -71,7 +60,7 @@ function validate_data($users_courses)
 }
 
 /**
- * Save the imported data
+ * Saves imported data.
  */
 function save_data($users_courses) {
 	$user_table= Database::get_main_table(TABLE_MAIN_USER);
@@ -82,80 +71,71 @@ function save_data($users_courses) {
 	}
 	foreach($csv_data as $username => $csv_subscriptions) {
 		$user_id = 0;
-		$sql = "SELECT * FROM $user_table u WHERE u.username = '".mysql_real_escape_string($username)."'";
-		$res = api_sql_query($sql,__FILE__,__LINE__);
-		$obj = mysql_fetch_object($res);
+		$sql = "SELECT * FROM $user_table u WHERE u.username = '".Database::escape_string($username)."'";
+		$res = Database::query($sql, __FILE__, __LINE__);
+		$obj = Database::fetch_object($res);
 		$user_id = $obj->user_id;
 		$sql = "SELECT * FROM $course_user_table cu WHERE cu.user_id = $user_id";
-		$res = api_sql_query($sql,__FILE__,__LINE__);
+		$res = Database::query($sql, __FILE__, __LINE__);
 		$db_subscriptions = array();
 		while($obj = Database::fetch_object($res)) {
 			$db_subscriptions[$obj->course_code] = $obj->status;
 		}
-		//echo '<b>User '.$username.'</b><br />';
+
 		$to_subscribe = array_diff(array_keys($csv_subscriptions),array_keys($db_subscriptions));
 		$to_unsubscribe = array_diff(array_keys($db_subscriptions),array_keys($csv_subscriptions));
-//		echo '<pre>';
-//		echo "CSV SUBSCRIPTION\n";
-//		print_r($csv_subscriptions);
-//		echo "DB SUBSCRIPTION\n";
-//		print_r($db_subscriptions);
-//		echo "TO SUBSCRIBE\n";
-//		print_r($to_subscribe);
-//		echo "TO UNSUBSCRIBE\n";
-//		print_r($to_unsubscribe);
-//		echo '</pre>';
 
         global $inserted_in_course;
-        if (!isset($inserted_in_course)) { $inserted_in_course = array(); }
+        if (!isset($inserted_in_course)) {
+        	$inserted_in_course = array();
+        }
 		if($_POST['subscribe'])	{
 			foreach($to_subscribe as $index => $course_code) {
                 if(CourseManager :: course_exists($course_code)) {
                     CourseManager::add_user_to_course($user_id,$course_code,$csv_subscriptions[$course_code]);
-                    $c_info = CourseManager::get_course_information($course_code); 
-                    $inserted_in_course[$course_code] = $c_info['title'];
-                } 
+                    $course_info = CourseManager::get_course_information($course_code);
+                    $inserted_in_course[$course_code] = $course_info['title'];
+                }
                 if (CourseManager :: course_exists($course_code,true)) {
-                    // also subscribe to virtual courses through check on visual code
+                    // Also subscribe to virtual courses through check on visual code.
                     $list = CourseManager :: get_courses_info_from_visual_code($course_code);
                     foreach ($list as $vcourse) {
                         if ($vcourse['code'] == $course_code) {
-                            //ignore, this has already been inserted
+                            // Ignore, this has already been inserted.
                         } else {
                             CourseManager::add_user_to_course($user_id,$vcourse['code'],$csv_subscriptions[$course_code]);
                             $inserted_in_course[$vcourse['code']] = $vcourse['title'];
                         }
                     }
                 }
-				//echo get_lang('Subscription').' : '.$course_code.'<br />';
 			}
 		}
 		if($_POST['unsubscribe']) {
 			foreach($to_unsubscribe as $index => $course_code) {
                 if(CourseManager :: course_exists($course_code)) {
                     CourseManager::unsubscribe_user($user_id,$course_code);
-                    $c_info = CourseManager::get_course_information($course_code); 
-                    $inserted_in_course[$course_code] = $c_info['title'];
-                } 
+                    $course_info = CourseManager::get_course_information($course_code);
+                    $inserted_in_course[$course_code] = $course_info['title'];
+                }
                 if (CourseManager :: course_exists($course_code,true)) {
                     // also subscribe to virtual courses through check on visual code
                     $list = CourseManager :: get_courses_info_from_visual_code($course_code);
                     foreach ($list as $vcourse) {
                         if ($vcourse['code'] == $course_code) {
-                            //ignore, this has already been inserted
+                            // Ignore, this has already been inserted.
                         } else {
                             CourseManager::unsubscribe_user($user_id,$vcourse['code']);
                             $inserted_in_course[$vcourse['code']] = $vcourse['title'];
                         }
                     }
                 }
-				//echo get_lang('Unsubscription').' : '.$course_code.'<br />';
 			}
 		}
 	}
 }
+
 /**
- * Read the CSV-file
+ * Reads CSV-file.
  * @param string $file Path to the CSV-file
  * @return array All course-information read from the file
  */
@@ -163,25 +143,27 @@ function parse_csv_data($file) {
 	$courses = Import :: csv_to_array($file);
 	return $courses;
 }
-// name of the language file that needs to be included 
+
+// Language files that should be included,
 $language_file = array ('admin', 'registration');
 
 $cidReset = true;
 
-// including the global Dokeos file
-include ('../inc/global.inc.php');
+// Including the global Dokeos file.
+include '../inc/global.inc.php';
 
-// protecting the admin section
+// Setting the section (for the tabs).
+$this_section = SECTION_PLATFORM_ADMIN;
+
+// Protecting the admin section.
 api_protect_admin_script();
 
-// including additional libraries
-require_once (api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'import.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'course.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-$formSent = 0;
-$errorMsg = '';
+// Including additional libraries.
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'import.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
 $tool_name = get_lang('AddUsersToACourse').' CSV';
 
@@ -189,12 +171,12 @@ $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAd
 
 set_time_limit(0);
 
-// creating the form
+// Creating the form.
 $form = new FormValidator('course_user_import');
 $form->addElement('header', '', $tool_name);
-$form->addElement('file','import_file', get_lang('ImportFileLocation'));
-$form->addElement('checkbox','subscribe',get_lang('Action'),get_lang('SubscribeUserIfNotAllreadySubscribed'));
-$form->addElement('checkbox','unsubscribe','',get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
+$form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
+$form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
+$form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
 $form->addElement('style_submit_button', 'submit',get_lang('Import'),'class="save"');
 if ($form->validate()) {
 	$users_courses = parse_csv_data($_FILES['import_file']['tmp_name']);
@@ -202,38 +184,36 @@ if ($form->validate()) {
 	if (count($errors) == 0) {
         $inserted_in_course = array();
 		save_data($users_courses);
-        // Build the alert message in case there were visual codes subscribed to
+        // Build the alert message in case there were visual codes subscribed to.
         if ($_POST['subscribe']) {
             $warn = get_lang('UsersSubscribedToBecauseVisualCode').': ';
         } else {
             $warn = get_lang('UsersUnsubscribedFromBecauseVisualCode').': ';
         }
-        
         if (count($inserted_in_course) > 1) {
-        	// The users have been inserted in more than one course
+        	// The users have been inserted in more than one course.
             foreach ($inserted_in_course as $code => $info) {
             	$warn .= ' '.$info.' ('.$code.'),';
             }
             $warn = substr($warn,0,-1);
         }
         Security::clear_token();
-        $tok = Security::get_token();       
+        $tok = Security::get_token();
 		header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('FileImported')).'&warn='.urlencode($warn).'&sec_token='.$tok);
 		exit ();
 	}
 }
 
-// displaying the header
+// Displaying the header.
 Display :: display_header($tool_name);
 
-// displaying the tool title
+// Displaying the tool title.
 // api_display_tool_title($tool_name);
 
-
 if (count($errors) != 0) {
 	$error_message = '<ul>';
 	foreach ($errors as $index => $error_course) {
-		$error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <b>'.$error_course['error'].'</b>: ';
+		$error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
 		$error_message .= $error_course['Code'].' '.$error_course['Title'];
 		$error_message .= '</li>';
 	}
@@ -241,7 +221,7 @@ if (count($errors) != 0) {
 	Display :: display_error_message($error_message);
 }
 
-// displaying the form
+// Displaying the form.
 $form->display();
 ?>
 <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
@@ -250,7 +230,7 @@ $form->display();
 <b>UserName</b>;<b>CourseCode</b>;<b>Status</b>
 jdoe;course01;<?php echo COURSEMANAGER; ?>
 
-a.dam;course01;<?php echo STUDENT; ?>
+adam;course01;<?php echo STUDENT; ?>
 </pre>
 <?php
 echo COURSEMANAGER.': '.get_lang('Teacher').'<br />';
@@ -258,6 +238,5 @@ echo STUDENT.': '.get_lang('Student').'<br />';
 ?>
 </blockquote>
 <?php
-// footer
+// Footer.
 Display :: display_footer();
-?>

+ 1 - 1
main/admin/course_user_list.php

@@ -24,5 +24,5 @@ if (count($list_course)==0) {
     <tr>
         <td><?php echo api_convert_encoding($list_course[$k],'UTF-8',$charset);?></td>
     </tr>
-<?php }?>	
+<?php }?>
 </table>

+ 69 - 69
main/admin/course_virtual.php

@@ -1,47 +1,47 @@
-<?php // $Id: course_virtual.php 20441 2009-05-10 07:39:15Z ivantcholakov $ 
+<?php // $Id: course_virtual.php 20441 2009-05-10 07:39:15Z ivantcholakov $
 /*
-============================================================================== 
+==============================================================================
 	Dokeos - elearning and course management software
-	
+
 	Copyright (c) 2004-2005 Dokeos S.A.
 	Copyright (c) 2003 Ghent University (UGent)
 	Copyright (c) 2001 Universite catholique de Louvain (UCL)
 	Copyright (c) Roan Embrechts (Vrije Universiteit Brussel)
-	
+
 	For a full list of contributors, see "credits.txt".
 	The full license can be read in "license.txt".
-	
+
 	This program is free software; you can redistribute it and/or
 	modify it under the terms of the GNU General Public License
 	as published by the Free Software Foundation; either version 2
 	of the License, or (at your option) any later version.
-	
+
 	See the GNU General Public License for more details.
-	
+
 	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
-============================================================================== 
+==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	@author Roan Embrechts - initial admin interface
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 
 /*
-============================================================================== 
+==============================================================================
 		INIT SECTION
-============================================================================== 
-*/ 
+==============================================================================
+*/
 
-// name of the language file that needs to be included 
-$language_file = 'admin'; 
+// name of the language file that needs to be included
+$language_file = 'admin';
 $extra_lang_file = "create_course";
 
-// global settings initialisation 
+// global settings initialisation
 // also provides access to main api (inc/lib/main_api.lib.php)
-include("../inc/global.inc.php"); 
+include("../inc/global.inc.php");
 $this_section=SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
@@ -53,7 +53,7 @@ if (isset($extra_lang_file)) include(api_get_path(INCLUDE_PATH)."../lang/".$lang
 -----------------------------------------------------------
 	Libraries
 -----------------------------------------------------------
-*/ 
+*/
 
 include_once(api_get_path(LIBRARY_PATH) . 'course.lib.php');
 
@@ -61,7 +61,7 @@ include_once(api_get_path(LIBRARY_PATH) . 'course.lib.php');
 -----------------------------------------------------------
 	Constants
 -----------------------------------------------------------
-*/ 
+*/
 
 define ("CREATE_VIRTUAL_COURSE_OPTION", "create_virtual_course");
 define ("DISPLAY_VIRTUAL_COURSE_LIST_OPTION", "display_virtual_course_list");
@@ -80,19 +80,19 @@ define ("COURSE_CATEGORY_FORM_NAME" , "course_category");
 -----------------------------------------------------------
 	Header
 -----------------------------------------------------------
-*/ 
+*/
 
-$tool_name = get_lang('AdminManageVirtualCourses'); // title of the page (should come from the language file) 
+$tool_name = get_lang('AdminManageVirtualCourses'); // title of the page (should come from the language file)
 
 $interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
 
 Display::display_header($tool_name);
 
 /*
-============================================================================== 
+==============================================================================
 		DISPLAY FUNCTIONS
-============================================================================== 
-*/ 
+==============================================================================
+*/
 
 function make_strong($text)
 {
@@ -122,7 +122,7 @@ function get_language_folder_list($dirname)
 }
 
 /**
-* Displays a select element (drop down menu) so the user can select 
+* Displays a select element (drop down menu) so the user can select
 * the course language.
 * @todo function does not belong here, move to (display?) library,
 * @todo language display used apparently no longer existing array, converted to english for now.
@@ -131,25 +131,25 @@ function get_language_folder_list($dirname)
 function display_language_select($element_name)
 {
 	global $platformLanguage;
-	
+
 	//get language list
 	$dirname = api_get_path(SYS_PATH)."main/lang/";
 	$language_list = get_language_folder_list($dirname);
 	sort($language_list);
-	
+
 	//build array with strings to display
 	foreach ($language_list as $this_language)
-	{	
+	{
 		$language_to_display[$this_language] = $this_language;
 	}
-	
+
 	//sort alphabetically
 	//warning: key,value association needs to be maintained --> asort instead of sort
 	asort($language_to_display);
-			 
+
 	$user_selected_language = $_SESSION["user_language_choice"];
 	if (! isset($user_selected_language) ) $user_selected_language = $platformLanguage;
-	
+
 	//display
 	echo "<select name=\"$element_name\">";
 	foreach ($language_to_display as $key => $value)
@@ -171,9 +171,9 @@ function display_language_select($element_name)
 *	We display the course code, but internally store the course id.
 */
 function display_real_course_code_select($element_name)
-{	
+{
 	$real_course_list = CourseManager::get_real_course_list();
-			
+
 	echo "<select name=\"$element_name\" size=\"".SELECT_BOX_SIZE."\" >\n";
 	foreach($real_course_list as $real_course)
 	{
@@ -200,10 +200,10 @@ function display_create_virtual_course_form()
 	<table>
 	<tr valign="top">
 	<td colspan="2">
-	
+
 	</td>
 	</tr>
-	
+
 	<tr valign="top">
 	<td align="right">
 		<?php
@@ -214,19 +214,19 @@ function display_create_virtual_course_form()
 		?>
 	</td>
 	</tr>
-	
+
 	<tr valign="top">
 	<td align="right"><?php echo make_strong(get_lang('CourseFaculty')) . "&nbsp;"; ?> </td>
 	<td>
 		<?php
 			echo "<select name=\"".COURSE_CATEGORY_FORM_NAME."\">";
-			
+
 			$sql_query = "SELECT code, name
 									FROM $category_table
 									WHERE auth_course_child ='TRUE'
 									ORDER BY tree_pos";
 			$category_result = api_sql_query($sql_query, __FILE__, __LINE__);
-		
+
 			while ($current_category = mysql_fetch_array($category_result))
 			{
 				echo "<option value=\"", $current_category["code"], "\"";
@@ -238,7 +238,7 @@ function display_create_virtual_course_form()
 	<br /><?php echo make_strong(get_lang('TargetFac'))  . "&nbsp;" ?>
 	</td>
 	</tr>
-	
+
 	<tr valign="top">
 	<td align="right"><?php echo make_strong(get_lang('Code'))  . "&nbsp;" ?> </td>
 	<td>
@@ -248,10 +248,10 @@ function display_create_virtual_course_form()
 	?>
 	</td>
 	</tr>
-	
+
 	<tr valign="top">
 	<td align="right">
-	<?php echo make_strong(get_lang('RealCourseCode'))  . "&nbsp;" ?> 
+	<?php echo make_strong(get_lang('RealCourseCode'))  . "&nbsp;" ?>
 	</td>
 	<td>
 		<?php
@@ -260,12 +260,12 @@ function display_create_virtual_course_form()
 		?>
 	</td>
 	</tr>
-	
+
 	<tr valign="top">
 	<td align="right">
-		<?php 
+		<?php
 			echo make_strong(get_lang('CourseLanguage')) . "&nbsp;";
-		?> 
+		?>
 	</td>
 	<td> <?php  display_language_select(LANGUAGE_SELECT_FORM_NAME); ?>
 
@@ -299,19 +299,19 @@ function display_virtual_course_list()
 		echo "<i>".get_lang('ThereAreNoVirtualCourses')."</i>";
 		return;
 	}
-	
-	$column_header[] = array(get_lang('Title'),true);					
-	$column_header[] = array(get_lang('Code'),true);				
-	$column_header[] = array(get_lang('VisualCode'),true);				
-	$column_header[] = array(get_lang('LinkedCourseTitle'),true);	
-	$column_header[] = array(get_lang('LinkedCourseCode'),true);		
+
+	$column_header[] = array(get_lang('Title'),true);
+	$column_header[] = array(get_lang('Code'),true);
+	$column_header[] = array(get_lang('VisualCode'),true);
+	$column_header[] = array(get_lang('LinkedCourseTitle'),true);
+	$column_header[] = array(get_lang('LinkedCourseCode'),true);
 	$table_data = array();
 	for($i = 0; $i < count($course_list); $i++)
 	{
 		$course_list[$i] = Database::generate_abstract_course_field_names($course_list[$i]);
 		$target_course_code = $course_list[$i]["target_course_code"];
 		$real_course_info = Database::get_course_info($target_course_code);
-		
+
 		$row = array();
 		$row[] = $course_list[$i]["title"];
 		$row[] = $course_list[$i]["system_code"];
@@ -325,9 +325,9 @@ function display_virtual_course_list()
 
 
 /*
-============================================================================== 
+==============================================================================
 		TOOL LOGIC FUNCTIONS
-============================================================================== 
+==============================================================================
 */
 
 /**
@@ -336,25 +336,25 @@ function display_virtual_course_list()
 *	Call this function instead of create_virtual_course
 */
 function attempt_create_virtual_course($real_course_code, $course_title, $wanted_course_code, $course_language, $course_category)
-{		
-	//better: create parameter list, check the entire list, when false display errormessage	
+{
+	//better: create parameter list, check the entire list, when false display errormessage
 	CourseManager::check_parameter_or_fail($real_course_code, "Unspecified parameter: real course id.");
 	CourseManager::check_parameter_or_fail($course_title, "Unspecified parameter: course title.");
 	CourseManager::check_parameter_or_fail($wanted_course_code, "Unspecified parameter: wanted course code.");
 	CourseManager::check_parameter_or_fail($course_language, "Unspecified parameter: course language.");
 	CourseManager::check_parameter_or_fail($course_category, "Unspecified parameter: course category.");
-	
+
 	$message = get_lang('AttemptedCreationVirtualCourse') . "<br/>";
 	$message .= get_lang('CourseTitle') . " " . $course_title . "<br/>";
 	$message .= get_lang('WantedCourseCode') . " " . $wanted_course_code . "<br/>";
 	$message .= get_lang('CourseLanguage') . " " . $course_language . "<br/>";
 	$message .= get_lang('CourseFaculty') . " " . $course_category . "<br/>";
 	$message .= get_lang('LinkedToRealCourseCode') . " " . $real_course_code . "<br/>";
-	
+
 	Display::display_normal_message($message);
-	
+
 	$creation_success = CourseManager::create_virtual_course( $real_course_code, $course_title, $wanted_course_code, $course_language, $course_category );
-	
+
 	if ($creation_success == true)
 	{
 		Display::display_normal_message( $course_title . " - " . get_lang('CourseCreationSucceeded') );
@@ -362,12 +362,12 @@ function attempt_create_virtual_course($real_course_code, $course_title, $wanted
 	}
 	return false;
 }
-	
+
 /*
-============================================================================== 
+==============================================================================
 		MAIN CODE
-============================================================================== 
-*/ 
+==============================================================================
+*/
 
 $action = $_GET["action"];
 $attempt_create_virtual_course = $_POST["submit_create_virtual_course"];
@@ -381,18 +381,18 @@ if ( isset($attempt_create_virtual_course) && $attempt_create_virtual_course )
 	$wanted_course_code = $_POST[WANTED_COURSE_CODE_FORM_NAME];
 	$course_language = $_POST[LANGUAGE_SELECT_FORM_NAME];
 	$course_category = $_POST[COURSE_CATEGORY_FORM_NAME];
-	
+
 	$message = get_lang('AttemptedCreationVirtualCourse') . "<br/>";
 	$message .= get_lang('CourseTitle') . " " . $course_title . "<br/>";
 	$message .= get_lang('WantedCourseCode') . " " . $wanted_course_code . "<br/>";
 	$message .= get_lang('CourseLanguage') . " " . $course_language . "<br/>";
 	$message .= get_lang('CourseFaculty') . " " . $course_category . "<br/>";
 	$message .= get_lang('LinkedToRealCourseCode') . " " . $real_course_code . "<br/>";
-	
+
 	Display::display_normal_message($message);
-	
+
 	$creation_success = CourseManager::attempt_create_virtual_course($real_course_code, $course_title, $wanted_course_code, $course_language, $course_category);
-	
+
 	if ($creation_success == true)
 	{
 		Display::display_normal_message( $course_title . " - " . get_lang('CourseCreationSucceeded') );
@@ -419,8 +419,8 @@ switch($action)
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
-*/ 
+*/
 Display::display_footer();
 ?>

+ 19 - 19
main/admin/index.php

@@ -55,7 +55,7 @@ $tool_name=get_lang('PlatformAdmin');
 Display::display_header($nameTools);
 
 
-if(api_is_platform_admin()) 
+if(api_is_platform_admin())
 {
 	if(is_dir(api_get_path(SYS_CODE_PATH).'install/') && is_readable(api_get_path(SYS_CODE_PATH).'install/index.php'))
 	{
@@ -71,13 +71,13 @@ if(api_is_platform_admin())
 		register_site();
 		Display :: display_confirmation_message(get_lang('VersionCheckEnabled'));
 	}
-	
+
 	/*
 	==============================================================================
 			MAIN SECTION
 	==============================================================================
 	*/
-	$keyword_url = Security::remove_XSS((empty($_GET['keyword'])?'':$_GET['keyword']));	
+	$keyword_url = Security::remove_XSS((empty($_GET['keyword'])?'':$_GET['keyword']));
 }
 
 if (api_is_platform_admin()) {
@@ -85,7 +85,7 @@ if (api_is_platform_admin()) {
 		<div class="admin_section">
 	<h4><?php Display::display_icon('members.gif', get_lang('Users')); ?> <?php echo api_ucfirst(get_lang('Users')); ?></h4>
 	<ul>
-		<li style="list-style-type:none"><form method="get" action="user_list.php">	
+		<li style="list-style-type:none"><form method="get" action="user_list.php">
 			<input type="text" name="keyword" value="<?php echo $keyword_url; ?>"/>
 			<button class="search" type="submit"> <?php echo get_lang('Search');?>
 			</button>
@@ -106,7 +106,7 @@ else
 	?>
 	<div class="admin_section">
 	<h4><?php Display::display_icon('members.gif', get_lang('Users')); ?> <?php echo api_ucfirst(get_lang('Users')); ?></h4>
-	<ul>		
+	<ul>
 		<li><a href="user_list.php">	<?php echo get_lang('UserList') ?></a></li>
 		<li><a href="../mySpace/user_add.php">		<?php echo get_lang('AddUsers') ?></a></li>
 
@@ -120,14 +120,14 @@ if(api_is_platform_admin()) {
 ?>
 	<div class="admin_section">
 <h4><?php Display::display_icon('course.gif', get_lang('Courses')); ?> <?php echo api_ucfirst(get_lang('Courses')); ?></h4>
-		<ul><li style="list-style-type:none"><form method="get" action="course_list.php">	
+		<ul><li style="list-style-type:none"><form method="get" action="course_list.php">
 		<input type="text" name="keyword" value="<?php echo $keyword_url; ?>"/>
 		<button class="search" type="submit"> <?php echo get_lang('Search');?>
 			</button>
 		</form></li>
 		<li>
 		<a href="course_list.php?search=advanced"><?php echo api_ucfirst(get_lang('AdvancedSearch')); ?></a>
-	
+
 	</li>
 	<li><a href="course_list.php"><?php echo get_lang('CourseList') ?></a></li>
 	<li><a href="course_add.php"><?php echo get_lang('AddCourse') ?></a></li>
@@ -141,7 +141,7 @@ if(api_is_platform_admin()) {
 	<?php } ?>
 	</ul>
 	</div>
-	
+
 	<div class="admin_section">
 	 <h4><?php Display::display_icon('settings.gif', get_lang('Platform')); ?> <?php echo api_ucfirst(get_lang('Platform')); ?></h4>
 	 <ul>
@@ -154,24 +154,24 @@ if(api_is_platform_admin()) {
 	  <?php if(!empty($phpMyAdminPath)) { ?>
 	  <li><a href="<?php echo $phpMyAdminPath; ?>" target="_blank"><?php echo get_lang("AdminDatabases"); ?></a><br />(<?php echo get_lang("DBManagementOnlyForServerAdmin"); ?>)</li>
 	  <?php } ?>
-	  <?php 
+	  <?php
 	  if(!empty($_configuration['multiple_access_urls']))
 	  {
 	    echo '<li><a href="access_urls.php">'.get_lang('ConfigureMultipleAccessURLs').'</a></li>';
 	  }
-	  
+
 	  if (api_get_setting('allow_reservation')=='true') {
 		  	echo '<li><a href="../reservation/m_category.php">'.get_lang('BookingSystem').'</a></li>';
 	  }
-	  
+
   	  if (api_get_setting('allow_terms_conditions')=='true') {
 		  	echo '<li><a href="legal_add.php">'.get_lang('TermsAndConditions').'</a></li>';
 	  }
-		
+
 	  ?>
 	 </ul>
 	</div>
-	
+
 	<?php
 }
 
@@ -241,7 +241,7 @@ if(api_is_platform_admin()){
 <?php
 	if(isset($extAuthSource) && isset($extAuthSource['ldap']) && count($extAuthSource['ldap'])>0){
 	?>
-	<!-- dynamic ldap code --> 
+	<!-- dynamic ldap code -->
 	<div class="admin_section">
 	 <h4><?php Display::display_icon('members.gif', 'LDAP'); ?> LDAP</h4>
 	 <ul>
@@ -252,14 +252,14 @@ if(api_is_platform_admin()){
 	 </ul>
 	</div>
 	<!-- dynamic ldap code -->
-	<?php 
+	<?php
 	}
 ?>
 <div class="admin_section">
  <h4><?php Display::display_icon('dokeos.gif', 'Dokeos'); ?> Dokeos.com</h4>
  <ul>
   <li><a href="http://www.dokeos.com/" target="_blank"><?php echo get_lang('DokeosHomepage'); ?></a></li>
-  <li><a href="http://www.dokeos.com/forum/" target="_blank"><?php echo get_lang('DokeosForum'); ?></a></li>  
+  <li><a href="http://www.dokeos.com/forum/" target="_blank"><?php echo get_lang('DokeosForum'); ?></a></li>
   <li><a href="http://www.dokeos.com/extensions/" target="_blank"><?php echo get_lang('DokeosExtensions'); ?></a></li>
   <li>
   <?php
@@ -289,13 +289,13 @@ function version_check()
 	$sql = 'SELECT selected_value FROM  '.$tbl_settings.' WHERE variable="registered" ';
 	$result = api_sql_query($sql,__FILE__,__LINE__);
 	$row=Database::fetch_array($result,'ASSOC');
-								
+
 	// The site has not been registered yet
 	//if (api_get_setting('registered')=='false')
-	
+
 	$return = '';
 	if ($row['selected_value']=='false')
-	{	
+	{
 		$return .= '<form action="'.api_get_self().'" id="VersionCheck" name="VersionCheck" method="post">';
 		$return .= get_lang('VersionCheckExplanation');
 		$return .= '<input type="checkbox" name="donotlistcampus" value="1" id="checkbox" />'.get_lang('HideCampusFromPublicDokeosPlatformsList');

+ 51 - 51
main/admin/languages.php

@@ -1,13 +1,13 @@
-<?php 
+<?php
 /* For licensing terms, see /dokeos_license.txt */
 /**
 ==============================================================================
 * This page allows the platform admin to decide which languages should
 * be available in the language selection menu in the login page. This can be
-* useful for countries with more than one official language (like Belgium: 
-* Dutch, French and German) or international organisations that are active in	
-* a limited number of countries. 
-* 
+* useful for countries with more than one official language (like Belgium:
+* Dutch, French and German) or international organisations that are active in
+* a limited number of countries.
+*
 * @author Patrick Cool, main author
 * @author Roan EMbrechts, code cleaning
 * @since Dokeos 1.6
@@ -15,9 +15,9 @@
 ==============================================================================
 */
 /*
-============================================================================== 
+==============================================================================
 	   INIT SECTION
-============================================================================== 
+==============================================================================
 */
 // name of the language file that needs to be included
 $language_file = 'admin';
@@ -37,26 +37,26 @@ if (isset($_POST['sent_http_request'])) {
 	if (isset($_POST['visibility']) && $_POST['visibility']==strval(intval($_POST['visibility'])) && $_POST['visibility']==0) {
 		if (isset($_POST['id'])&& $_POST['id']==strval(intval($_POST['id']))) {
 			SubLanguageManager::make_unavailable_language($_POST['id']);
-			echo 'set_hidden';	
+			echo 'set_hidden';
 		}
-	} 
+	}
 	if (isset($_POST['visibility']) && $_POST['visibility']==strval(intval($_POST['visibility'])) && $_POST['visibility']==1) {
 		if (isset($_POST['id'])&& $_POST['id']==strval(intval($_POST['id']))) {
 			SubLanguageManager::make_available_language($_POST['id']);
-			echo 'set_visible';			
+			echo 'set_visible';
 		}
-	} 	
+	}
 	exit;
 }
 $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
 $htmlHeadXtra[] ='<script type="text/javascript">
  $(document).ready(function() {
 
- 	//$(window).load(function () { 
+ 	//$(window).load(function () {
       $(".make_visible_and_invisible").attr("href","javascript:void(0)");
 	//});
- 		
- 	$("td .make_visible_and_invisible").click(function () { 
+
+ 	$("td .make_visible_and_invisible").click(function () {
 		make_visible="visible.gif";
 		make_invisible="invisible.gif";
 		id_link_tool=$(this).attr("id");
@@ -64,10 +64,10 @@ $htmlHeadXtra[] ='<script type="text/javascript">
 		path_name_of_imglinktool=$("#"+id_img_link_tool).attr("src");
 		link_info_id=id_link_tool.split("linktool_");
 		link_id=link_info_id[1];
-				
+
 		link_tool_info=path_name_of_imglinktool.split("/");
 		my_image_tool=link_tool_info[link_tool_info.length-1];
-    
+
 
 		if (my_image_tool=="visible.gif") {
 			path_name_of_imglinktool=path_name_of_imglinktool.replace(make_visible,make_invisible);
@@ -76,48 +76,48 @@ $htmlHeadXtra[] ='<script type="text/javascript">
 			path_name_of_imglinktool=path_name_of_imglinktool.replace(make_invisible,make_visible);
 			my_visibility=1;
 		}
-		
+
 		$.ajax({
 			contentType: "application/x-www-form-urlencoded",
 			beforeSend: function(objeto) {
 				$("#id_content_message").html("<div class=\"normal-message\"><img src=\'/main/inc/lib/javascript/indicator.gif\' /></div>");
-			
+
 			},
 			type: "POST",
 			url: "../admin/languages.php",
 			data: "id="+link_id+"&visibility="+my_visibility+"&sent_http_request=1",
 			success: function(datos) {
-				
+
 				$("#"+id_img_link_tool).attr("src",path_name_of_imglinktool);
-				
+
 				if (my_image_tool=="visible.gif") {
-					$("#"+id_img_link_tool).attr("alt","'.get_lang('MakeAvailable').'");
-					$("#"+id_img_link_tool).attr("title","'.get_lang('MakeAvailable').'");
+					$("#"+id_img_link_tool).attr("alt","'.get_lang('MakeAvailable', '').'");
+					$("#"+id_img_link_tool).attr("title","'.get_lang('MakeAvailable', '').'");
 				} else {
-					$("#"+id_img_link_tool).attr("alt","'.get_lang('MakeUnavailable').'");
-					$("#"+id_img_link_tool).attr("title","'.get_lang('MakeUnavailable').'");							
+					$("#"+id_img_link_tool).attr("alt","'.get_lang('MakeUnavailable', '').'");
+					$("#"+id_img_link_tool).attr("title","'.get_lang('MakeUnavailable', '').'");
 				}
 
 				if (datos=="set_visible") {
-					$("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowVisible').'</div>");
+					$("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowVisible', '').'</div>");
 				} else {
-					$("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowHidden').'</div>");					
+					$("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowHidden', '').'</div>");
 				}
-				
-		} }); 		
-				
-	}); 	
+
+		} });
+
+	});
 
  });
-</script>';	
+</script>';
 // setting the table that is needed for the styles management (there is a check if it exists later in this code)
 $tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 $tbl_settings_current 	= Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
 
 /*
-============================================================================== 
+==============================================================================
 		STORING THE CHANGES
-============================================================================== 
+==============================================================================
 */
 
 // we change the availability
@@ -136,7 +136,7 @@ if ($_GET['action'] == 'makeavailable') {
 if ($_GET['action'] == 'setplatformlanguage') {
 
 	if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
-		SubLanguageManager::set_platform_language($_GET['id']);		
+		SubLanguageManager::set_platform_language($_GET['id']);
 	}
 
 }
@@ -188,9 +188,9 @@ elseif (isset($_POST['action']))
 
 
 /*
-============================================================================== 
+==============================================================================
 		MAIN CODE
-============================================================================== 
+==============================================================================
 */
 // setting the name of the tool
 $tool_name = get_lang('PlatformLanguages');
@@ -201,20 +201,20 @@ $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAd
 // including the header file (which includes the banner itself)
 Display :: display_header($tool_name);
 
-// displaying the naam of the tool 
+// displaying the naam of the tool
 //api_display_tool_title($tool_name);
 
 // displaying the explanation for this tool
 echo '<p>'.get_lang('PlatformLanguagesExplanation').'</p>';
 
-// selecting all the languages	
+// selecting all the languages
 $sql_select = "SELECT * FROM $tbl_admin_languages";
 $result_select = api_sql_query($sql_select);
 
 $sql_select_lang = "SELECT * FROM $tbl_settings_current WHERE  category='Languages'";
 $result_select_lang = api_sql_query($sql_select_lang,__FILE__,__LINE__);
 $row_lang=Database::fetch_array($result_select_lang);
- 
+
 /*
 --------------------------------------
 		DISPLAY THE TABLE
@@ -224,8 +224,8 @@ $row_lang=Database::fetch_array($result_select_lang);
 // the table data
 $language_data = array ();
 while ($row = Database::fetch_array($result_select)) {
-	
-	$row_td = array ();	
+
+	$row_td = array ();
 	$row_td[] = $row['id'];
 	// the first column is the original name of the language OR a form containing the original name
 	if ($_GET['action'] == 'edit' and $row['id'] == $_GET['id']) {
@@ -242,21 +242,21 @@ while ($row = Database::fetch_array($result_select)) {
 	$row_td[] = $row['english_name'];
 	// the third column
 	$row_td[] = $row['dokeos_folder'];
-	
+
 	if ($row['english_name'] == $row_lang['selected_value']){
 		$setplatformlanguage = Display::return_icon('links.gif', get_lang('CurrentLanguagesPortal'));
-	} else {		
+	} else {
 		$setplatformlanguage = "<a href=\"javascript:if (confirm('".addslashes(get_lang('AreYouSureYouWantToSetThisLanguageAsThePortalDefault'))."')) { location.href='".api_get_self()."?action=setplatformlanguage&id=".$row['id']."'; }\">".Display::return_icon('link_na.gif',get_lang('SetLanguageAsDefault'))."</a>";
-	}	
+	}
 	if (api_get_setting('allow_use_sub_language')=='true') {
 
 		$verified_if_is_sub_language=SubLanguageManager::check_if_language_is_sub_language($row['id']);
 
 		if ($verified_if_is_sub_language===false) {
 			$verified_if_is_father=SubLanguageManager::check_if_language_is_father($row['id']);
-			$allow_use_sub_language = "&nbsp;<a href='sub_language_add.php?action=definenewsublanguage&id=".$row['id']."'>".Display::return_icon('mas.gif', get_lang('CreateSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";		
+			$allow_use_sub_language = "&nbsp;<a href='sub_language_add.php?action=definenewsublanguage&id=".$row['id']."'>".Display::return_icon('mas.gif', get_lang('CreateSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";
 			if ($verified_if_is_father===true) {
-				//$allow_add_term_sub_language = "&nbsp;<a href='sub_language.php?action=registersublanguage&id=".$row['id']."'>".Display::return_icon('2rightarrow.gif', get_lang('AddWordForTheSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";						
+				//$allow_add_term_sub_language = "&nbsp;<a href='sub_language.php?action=registersublanguage&id=".$row['id']."'>".Display::return_icon('2rightarrow.gif', get_lang('AddWordForTheSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";
 				$allow_add_term_sub_language='';
 			} else {
 				$allow_add_term_sub_language='';
@@ -264,14 +264,14 @@ while ($row = Database::fetch_array($result_select)) {
 		} else {
 				$allow_use_sub_language='';
 				$all_information_of_sub_language=SubLanguageManager::get_all_information_of_language($row['id']);
-				$allow_add_term_sub_language = "&nbsp;<a href='sub_language.php?action=registersublanguage&id=".Security::remove_XSS($all_information_of_sub_language['parent_id'])."&sub_language_id=".Security::remove_XSS($row['id'])."'>".Display::return_icon('2rightarrow.gif', get_lang('AddWordForTheSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";									
-				$allow_delete_sub_language = "&nbsp;<a href='sub_language_add.php?action=deletesublanguage&id=".Security::remove_XSS($all_information_of_sub_language['parent_id'])."&sub_language_id=".Security::remove_XSS($row['id'])."'>".Display::return_icon('delete_data.gif', get_lang('DeleteSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";		
+				$allow_add_term_sub_language = "&nbsp;<a href='sub_language.php?action=registersublanguage&id=".Security::remove_XSS($all_information_of_sub_language['parent_id'])."&sub_language_id=".Security::remove_XSS($row['id'])."'>".Display::return_icon('2rightarrow.gif', get_lang('AddWordForTheSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";
+				$allow_delete_sub_language = "&nbsp;<a href='sub_language_add.php?action=deletesublanguage&id=".Security::remove_XSS($all_information_of_sub_language['parent_id'])."&sub_language_id=".Security::remove_XSS($row['id'])."'>".Display::return_icon('delete_data.gif', get_lang('DeleteSubLanguage'),array('width'=>'22','height'=>'22'))."</a>";
 		}
-		
+
 	} else {
 		$allow_use_sub_language='';
 		$allow_add_term_sub_language='';
-	}	
+	}
 	if ($row['available'] == 1) {
 		$row_td[] = "<a class=\"make_visible_and_invisible\" id=\"linktool_".$row['id']."\" href='".api_get_self()."?action=makeunavailable&id=".$row['id']."'>".Display::return_icon('visible.gif', get_lang('MakeUnavailable'),array('id'=>'imglinktool_'.$row['id']))."</a> <a href='".api_get_self()."?action=edit&id=".$row['id']."#value'>".Display::return_icon('edit.gif', get_lang('Edit'))."</a>&nbsp;".$setplatformlanguage.$allow_use_sub_language.$allow_add_term_sub_language.$allow_delete_sub_language;
 		//$row_td[] = "<a class=\"make_visible_and_invisible\" id=\"linktool_".$row['id']."\" href='javascript:void(0)'>".Display::return_icon('visible.gif', get_lang('MakeUnavailable'),array('id'=>'imglinktool_'.$row['id']))."</a> <a href='".api_get_self()."?action=edit&id=".$row['id']."#value'>".Display::return_icon('edit.gif', get_lang('Edit'))."</a>&nbsp;".$setplatformlanguage.$allow_use_sub_language.$allow_add_term_sub_language;
@@ -298,7 +298,7 @@ $table->display();
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 1 - 1
main/admin/ldap_form_add_users_group.php

@@ -52,7 +52,7 @@ echo '<tr align="center" id="header3">' .
 			: '<td width="15%"><b>'.get_lang('Name').'</b></td>' .
 			'<td width="15%"><b>'.get_lang('FirstName').'</b></td>') .
 		'<td width="15%"><b>'.get_lang('Login').'</b></td>' .
-	  '</tr>'."\n";																																																					   
+	  '</tr>'."\n";
 while (list ($key, $val) = each($nom_form)) {
 	$nbre=$nbre+1;
 	if($nbre & 1) $ndiv=2; else $ndiv=3;

+ 8 - 8
main/admin/ldap_import_students.php

@@ -39,7 +39,7 @@ $tool_name = get_lang('LDAPImport');
 // setting breadcrumbs
 $interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
 
-$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">	
+$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
 var buttoncheck = 1;
 function checkAll() {
 	//var boxes = document.form.elements[\'checkboxes[]\'];
@@ -77,23 +77,23 @@ if (empty($annee) && empty($course))
 		echo get_lang('LDAPSelectFilterOnUsersOU');
 		//echo '<em>'.get_lang('ToDoThisYouMustEnterYearComponentAndComponentStep').'</em><br />';
 		///echo get_lang('FollowEachOfTheseStepsStepByStep').'<br />';
-		
+
 		echo '<form method="get" action="'.api_get_self().'"><br />';
 		echo '<em>'.get_lang('LDAPOUAttributeFilter').' :</em> ';
 		echo '<input  type="text" name="annee" size="4" maxlength="30" value="'.$annee_base.'"><br />';
 		echo '<input type="submit" value="'.get_lang('Submit').'">';
 		echo '</form>';
 		echo '</div>';
-	
+
 }
 /*
-elseif ($annee <> "" && $composante == "" && $etape == "") // form 2 annee != 0; composante= 0 etape = 0 
+elseif ($annee <> "" && $composante == "" && $etape == "") // form 2 annee != 0; composante= 0 etape = 0
 {
 		Display::display_header($tool_name);
 
 	$ds = ldap_connect($ldap_host, $ldap_port) or die(get_lang('LDAPConnectionError'));
 	ldap_set_version($ds);
-	
+
 	if ($ds) {
 		$r = false;
 		$res = ldap_handle_bind($ds, $r);
@@ -139,7 +139,7 @@ elseif ($annee <> "" && $composante == "" && $etape == "") // form 2 annee != 0;
 	echo '<br />';
 	echo '</div>';
 }
-elseif ($annee <> "" && $composante <> "" && $etape == "") // form3 :annee!=0composante=0etape=0 
+elseif ($annee <> "" && $composante <> "" && $etape == "") // form3 :annee!=0composante=0etape=0
 {
 
 		Display::display_header($tool_name);
@@ -274,7 +274,7 @@ elseif (!empty($annee) && !empty($course) && empty($_POST['confirmed']))
 		asort($nom_form);
 		reset($nom_form);
 
-		$statut=5;	
+		$statut=5;
 		include ('ldap_form_add_users_group.php');
 	} else {
 		echo '<h4>'.get_lang('UnableToConnectTo').' '.$host.'</h4>';
@@ -331,7 +331,7 @@ elseif (!empty($annee) && !empty($course) && ($_POST['confirmed']=='yes'))
 		Display::display_header($tool_name);
 		$message=get_lang('NoUserAdded');
 		Display :: display_normal_message($message,false);
-	}	
+	}
 	echo '<br /><br />';
     echo '<a href="ldap_import_students.php?annee=&composante=&etape=">'.get_lang('BackToNewSearch').'</a>';
     echo '<br /><br />';

+ 5 - 5
main/admin/ldap_import_students_to_session.php

@@ -39,7 +39,7 @@ $tool_name = get_lang('LDAPImport');
 // setting breadcrumbs
 $interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
 
-$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">	
+$htmlHeadXtra[] = '<script language="JavaScript" type="text/javascript">
 var buttoncheck = 1;
 function checkAll() {
 	//var boxes = document.form.elements[\'checkboxes[]\'];
@@ -78,7 +78,7 @@ if (empty($annee) && empty($id_session))
 		echo '<input type="submit" value="'.get_lang('Submit').'">';
 		echo '</form>';
 		echo '</div>';
-	
+
 }
 elseif(!empty($annee) && empty($id_session))
 {
@@ -149,7 +149,7 @@ elseif (!empty($annee) && !empty($id_session) && empty($_POST['confirmed']))
 		asort($nom_form);
 		reset($nom_form);
 
-		$statut=5;	
+		$statut=5;
 		include ('ldap_form_add_users_group.php');
 	} else {
 		echo '<h4>'.get_lang('UnableToConnectTo').' '.$host.'</h4>';
@@ -193,7 +193,7 @@ elseif (!empty($annee) && !empty($id_session) && ($_POST['confirmed']=='yes'))
 		if($num>0)
 		{
 			$sql = 'UPDATE '.$tbl_session.' SET nbr_users = (nbr_users + '.$num.') WHERE id = '.intval($id_session);
-			$res = api_sql_query($sql,__FILE__,__LINE__);			 
+			$res = api_sql_query($sql,__FILE__,__LINE__);
 		}
 		header('Location: resume_session.php?id_session='.Security::remove_XSS($_POST['id_session']));
 	}
@@ -221,7 +221,7 @@ elseif (!empty($annee) && !empty($id_session) && ($_POST['confirmed']=='yes'))
 		Display::display_header($tool_name);
 		$message=get_lang('NoUserAdded');
 		Display :: display_normal_message($message,false);
-	}	
+	}
 	echo '<br /><br />';
     echo '<a href="ldap_import_students.php?annee=&composante=&etape=">'.get_lang('BackToNewSearch').'</a>';
     echo '<br /><br />';

+ 3 - 3
main/admin/ldap_synchro.php

@@ -72,10 +72,10 @@ foreach($Sessions as $session){
 	$UserList=array();
 	$UserUpdate=array();
 	$UserAdd=array();
-	
+
 	// Parse des code etape de la session
 	/*
-	$sql = "SELECT  id_session, code_etape, etape_description, code_ufr, annee 
+	$sql = "SELECT  id_session, code_etape, etape_description, code_ufr, annee
 		FROM $tbl_session_rel_etape
 		WHERE id_session='$id_session'
 		ORDER BY code_ufr, code_etape";
@@ -149,7 +149,7 @@ foreach($Sessions as $session){
 		{
 			print "> $name_session: ".count($UserAdd).get_lang('Added').' '.get_lang('And').' '.count($UserUpdate).' '.get_lang('Modified')."\n";
 		}
-		
+
 		// Une fois les utilisateurs importer dans la base des utilisateurs, on peux les affecter a� la session
 		$result=api_sql_query("SELECT course_code FROM $tbl_session_rel_course " .
 				"WHERE id_session='$id_session'",__FILE__,__LINE__);

+ 6 - 6
main/admin/ldap_users_list.php

@@ -47,7 +47,7 @@ api_protect_admin_script();
 require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
 $action = $_GET["action"];
 $login_as_user_id = $_GET["user_id"];
-	
+
 // Login as ...
 if ($_GET['action'] == "login_as" && isset ($login_as_user_id))
 {
@@ -127,7 +127,7 @@ if (isset ($_GET['action']))
 					Display :: display_normal_message($message,false);
 				}
 				break;
-			default : 
+			default :
 				Display :: display_header($tool_name);
 		}
 		Security::clear_token();
@@ -190,9 +190,9 @@ if (isset ($_POST['action']))
 				else
 				{
 					Display :: display_normal_message(get_lang('NoUserAdded'));
-				}				
+				}
 				break;
-				
+
 		}
 		Security::clear_token();
 	}
@@ -210,7 +210,7 @@ else
 	$form->add_textfield('keyword_lastname',get_lang('LastName'),false);
 	$form->add_textfield('keyword_firstname',get_lang('FirstName'),false);
 }
-if (isset($_GET['id_session'])) 
+if (isset($_GET['id_session']))
 	$form->addElement('hidden','id_session',$_GET['id_session']);
 
 $type = array();
@@ -232,7 +232,7 @@ $parameters['keyword_username'] = $_GET['keyword_username'];
 $parameters['keyword_firstname'] = $_GET['keyword_firstname'];
 $parameters['keyword_lastname'] = $_GET['keyword_lastname'];
 $parameters['keyword_email'] = $_GET['keyword_email'];
-if (isset($_GET['id_session'])) 
+if (isset($_GET['id_session']))
 	$parameters['id_session'] = $_GET['id_session'];
 // Create a sortable table with user-data
 

+ 1 - 1
main/admin/ldap_users_synchro.php

@@ -86,6 +86,6 @@ if (isset($action) && ($action=="synchro")) {
 	$included=true;
 	require('ldap_synchro.php');
 	Display :: display_normal_message($message,false);
-}	
+}
 Display::display_footer();
 ?>

+ 41 - 41
main/admin/legal_add.php

@@ -10,24 +10,24 @@ api_protect_admin_script();
 require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 require_once api_get_path(LIBRARY_PATH).'security.lib.php';
 require_once api_get_path(LIBRARY_PATH).'legal.lib.php';
-//var_dump($_POST);	
+//var_dump($_POST);
 // Create the form
 $form = new FormValidator('addlegal');
-//var_dump($_POST);// var_dump($_GET); 
+//var_dump($_POST);// var_dump($_GET);
 $defaults=array();
 if( $form->validate()) {
-	$check = Security::check_token('post');			
+	$check = Security::check_token('post');
 		if ($check) {
-			$values  = $form->getSubmitValues();						
+			$values  = $form->getSubmitValues();
 			$lang 	 = $values['language'];
 			//language id
 			$lang = api_get_language_id($lang);
-			 
+
 			$type 	 = $values['type'];
 			$content = $values['content'];
 			$changes = $values['changes'];
 			$navigator_info = api_get_navigator();
-			
+
 			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
 				if (isset($values['preview'])) {
 					$submit	='preview';
@@ -37,68 +37,68 @@ if( $form->validate()) {
 					$submit	='back';
 				}
 			}else {
-				$submit  = $values['send'];	
-			
-			}		
+				$submit  = $values['send'];
+
+			}
 
 			$default[content]=$content;
 			if (isset($values['language'])){
 				if($submit=='back') {
 					header('Location: legal_add.php');
 					exit;
-				} elseif($submit=='save') {					
-					$insert_result = LegalManager::add($lang,$content,$type,$changes);					
+				} elseif($submit=='save') {
+					$insert_result = LegalManager::add($lang,$content,$type,$changes);
 					if ($insert_result )
 						$message = get_lang('TermAndConditionSaved');
-					else 
-						$message = get_lang('TermAndConditionNotSaved');				
+					else
+						$message = get_lang('TermAndConditionNotSaved');
 					Security::clear_token();
-					$tok = Security::get_token();			
+					$tok = Security::get_token();
 					header('Location: legal_list.php?action=show_message&message='.urlencode($message).'&sec_token='.$tok);
-					exit();		
-				} elseif($submit=='preview') {		
+					exit();
+				} elseif($submit=='preview') {
 					$defaults['type']=$type;
 					$defaults['content']=$content;
 					$defaults['changes']=$changes;
 					$term_preview = $defaults;
-					$term_preview['type'] = intval($_POST['type']);						
-				} else {				
+					$term_preview['type'] = intval($_POST['type']);
+				} else {
 					$my_lang = $_POST['language'];
 					if (isset($_POST['language'])){
-						$all_langs = api_get_languages();						
+						$all_langs = api_get_languages();
 						if (in_array($my_lang, $all_langs['folder'])){
-							$language = api_get_language_id($my_lang);					
+							$language = api_get_language_id($my_lang);
 							$term_preview = LegalManager::get_last_condition($language);
 							$defaults = $term_preview;
 							if ($term_preview==false) {
 								// there are not terms and conditions
 								$term_preview['type']=-1;
 								$defaults['type']=0;
-							}						
+							}
 						}
-					}		
+					}
 				}
 			}
 		}
-} else {	
+} else {
 	/*
 	if (!isset($_POST['language'])) {
 		$language = api_get_setting('platformLanguage');
 		$language = api_get_language_id($language);
-		$term_preview = LegalManager::get_last_condition($language);	
+		$term_preview = LegalManager::get_last_condition($language);
 		$defaults['type']=$term_preview['type'];
 		if ($term_preview==false) {
 			// there are not terms and conditions
 			$term_preview['type']=-1;
 			$defaults['type']=0;
-		}			
+		}
 		$defaults['content']=$term_preview['content'];
 		$defaults['changes']=$term_preview['changes'];
 	}*/
 }
 $form->setDefaults($default);
 //var_dump($term_preview);
-if(isset($_POST['send'])) { 
+if(isset($_POST['send'])) {
 	Security::clear_token();
 }
 $token = Security::get_token();
@@ -118,12 +118,12 @@ $form->addElement('html',$text);
 //$form->addElement('select_language', 'language', get_lang('Language'),null,array('id'=>'language','onchange'=>'sendlang();'));
 
 
-if (isset($_POST['language'])) {	
+if (isset($_POST['language'])) {
 //$form->addElement('html_editor', 'content', null, null, array('ToolbarSet' => 'Basic', 'Width' => '100%', 'Height' => '250'));
 	$form->addElement('static', $_POST['language']);
 	$form->addElement('hidden', 'language',$_POST['language']);
 	$form->add_html_editor('content', get_lang('Content'), true, false, array('ToolbarSet' => 'simple', 'Width' => '100%', 'Height' => '250'));
-	//$form->addElement('textarea', 'content', get_lang('Content'),array('cols'=>'120','rows'=>'10'));	
+	//$form->addElement('textarea', 'content', get_lang('Content'),array('cols'=>'120','rows'=>'10'));
 	$form->addElement('radio', 'type', '', get_lang('HTMLText') ,'0');
 	$form->addElement('radio', 'type', '', get_lang('PageLink') ,'1');
 	$form->addElement('textarea', 'changes', get_lang('ExplainChanges'),array('width'=>'20'));
@@ -135,15 +135,15 @@ if (isset($_POST['language'])) {
 				<div class="formw">
 				'.$preview.'
 				</div>
-				</div>';	
+				</div>';
 		$form->addElement('html',$term_preview);
 	}
 	// Submit & preview button
-	
+
 		$navigator_info = api_get_navigator();
 		//ie6 fix
 	if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
-		
+
 	$buttons = '<div class="row" align="center">
 			<div class="formw">
 			<input type="submit" name="back"  value="'.get_lang('Back').'"/>
@@ -152,7 +152,7 @@ if (isset($_POST['language'])) {
 			</div>
 		</div>';
 		$form->addElement('html',$buttons);
-	} else {				
+	} else {
 	$buttons = '<div class="row" align="center">
 					<div class="formw">
 					<button type="submit" class="back" 	 name="send" value="back">'.get_lang('Back').'</button>
@@ -162,7 +162,7 @@ if (isset($_POST['language'])) {
 				</div>';
 		$form->addElement('html',$buttons);
 	}
-	
+
 /*	$buttons = '<div class="row">
 					<div class="formw">
 					<button type="submit" class="back" 	 name="send" value="back">'.get_lang('Back').'</button>
@@ -170,16 +170,16 @@ if (isset($_POST['language'])) {
 					<button type="submit" class="save" 	 name="send" value="save">'.get_lang('Save').'</button>
 					</div>
 				</div>';	*/
-	
+
 } else {
 	$form->addElement('select_language', 'language', get_lang('Language'),null,array());
 	$buttons = '<div class="row">
-					<div class="formw">					
+					<div class="formw">
 					<button type="submit" class="save" 	 name="send" value="load">'.get_lang('Load').'</button>
 					</div>
-				</div>';	
+				</div>';
 	$form->addElement('html',$buttons);
-	
+
 }
 //var_dump($defaults);
 
@@ -191,7 +191,7 @@ Display :: display_header($tool_name);
 echo '<script>
 function sendlang(){
 	//document.addlegal.send.value=\'load\';
-//	alert(document.addlegal.send.value);	
+//	alert(document.addlegal.send.value);
 	document.addlegal.sec_token.value=\''.$token.'\';
 	document.addlegal.submit();
 }
@@ -201,7 +201,7 @@ function sendlang(){
 echo '<div class="actions" style="height:22px;">';
 echo '<div style="float:right;">
 		<a href="'.api_get_path(WEB_CODE_PATH).'admin/legal_list.php">'.Display::return_icon('search.gif',get_lang('EditTermsAndConditions'),'').get_lang('AllVersions').'</a>&nbsp;&nbsp;
-	  </div><br />';		  
+	  </div><br />';
 echo '</div>';
 
 if (isset ($_GET['action'])) {
@@ -209,9 +209,9 @@ if (isset ($_GET['action'])) {
 		case 'show_message' :
 			Display :: display_normal_message(stripslashes($_GET['message']));
 			break;
-	}	
+	}
 }
-		
+
 
 //var_dump($defaults);
 

+ 6 - 6
main/admin/legal_list.php

@@ -5,7 +5,7 @@ $language_file = 'admin';
 $cidReset = true;
 require ('../inc/global.inc.php');
 $this_section = SECTION_PLATFORM_ADMIN;
-api_protect_admin_script();	
+api_protect_admin_script();
 $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 $tool_name = get_lang('TermsAndConditions');
 Display :: display_header($tool_name);
@@ -21,7 +21,7 @@ $parameters['sec_token'] = Security::get_token();
 echo '<div class="actions" style="height:22px;">';
 echo '<div style="float:right;">
 		<a href="'.api_get_path(WEB_CODE_PATH).'admin/legal_add.php">'.Display::return_icon('edit.gif',get_lang('EditTermsAndConditions'),'').get_lang('EditTermsAndConditions').'</a>&nbsp;&nbsp;
-	  </div><br />';		  
+	  </div><br />';
 echo '</div>';
 
 // Actions
@@ -31,7 +31,7 @@ if (isset ($_GET['action'])) {
 	Security::clear_token();
 }
 
-$table = new SortableTable('conditions', 'count_mask', 'get_legal_data_mask',2); 
+$table = new SortableTable('conditions', 'count_mask', 'get_legal_data_mask',2);
 $table->set_additional_parameters($parameters);
 $table->set_header(0, get_lang('Version'), false, 'width="15px"');
 $table->set_header(1, get_lang('Language'), false, 'width="30px"');
@@ -39,19 +39,19 @@ $table->set_header(2, get_lang('Content'),false);
 $table->set_header(3, get_lang('Changes'), false, 'width="60px"');
 $table->set_header(4, get_lang('Type'), false, 'width="60px"');
 $table->set_header(5, get_lang('Date'), false, 'width="50px"');
-$table->display(); 
+$table->display();
 
 // this 2 "mask" function are here just because the SortableTable
 function get_legal_data_mask($id, $params=null, $row=null) {
 	return LegalManager::get_legal_data($id, $params, $row);
 }
 function count_mask() {
-	return LegalManager::count();				
+	return LegalManager::count();
 }
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 6 - 6
main/admin/resume_session.php

@@ -57,13 +57,13 @@ if(!api_is_platform_admin() && $session['session_admin_id']!=$_user['user_id'])
 if($_GET['action'] == 'delete')
 {
 	$idChecked = $_GET['idChecked'];
-	if(is_array($idChecked)) {		
-		$my_temp = array(); 
+	if(is_array($idChecked)) {
+		$my_temp = array();
 		foreach ($idChecked as $id){
 			$my_temp[]= Database::escape_string($id);// forcing the escape_string
 		}
-		$idChecked = $my_temp;		
-		
+		$idChecked = $my_temp;
+
 		$idChecked="'".implode("','",$idChecked)."'";
 
 		api_sql_query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
@@ -100,7 +100,7 @@ if($_GET['action'] == 'delete')
 
 Display::display_header($tool_name);
 if (!empty($_GET['warn'])) {
-    Display::display_warning_message(urldecode($_GET['warn']));    
+    Display::display_warning_message(urldecode($_GET['warn']));
 }
 
 api_display_tool_title($tool_name);
@@ -197,7 +197,7 @@ else {
 			$coach = api_get_person_name($course['firstname'], $course['lastname']).' ('.$course['username'].')';
 		}
 
-		$orig_param = '&origin=resume_session';	
+		$orig_param = '&origin=resume_session';
 		//hide_course_breadcrumb the parameter has been added to hide the name of the course, that appeared in the default $interbreadcrumb
 		echo '
 		<tr>

+ 27 - 27
main/admin/session_add.php

@@ -2,10 +2,10 @@
 /* For licensing terms, see /dokeos_license.txt */
 
 /**
-============================================================================== 
+==============================================================================
 *	@package dokeos.admin
 * 	@todo use formvalidator for the form
-============================================================================== 
+==============================================================================
 */
 
 // name of the language file that needs to be included
@@ -62,12 +62,12 @@ function search_coachs($needle)
 				$order_clause.
 				' LIMIT 10';
 
-		global $_configuration;	
-		if ($_configuration['multiple_access_urls']==true) {		
-			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+		global $_configuration;
+		if ($_configuration['multiple_access_urls']==true) {
+			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 			$access_url_id = api_get_current_access_url_id();
-			if ($access_url_id != -1){			
-				
+			if ($access_url_id != -1){
+
 				$sql = 'SELECT username, lastname, firstname FROM '.$tbl_user.' user
 				INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
 				WHERE access_url_id = '.$access_url_id.'  AND (username LIKE "'.$needle.'%"
@@ -75,11 +75,11 @@ function search_coachs($needle)
 				OR lastname LIKE "'.$needle.'%")
 				AND status=1'.
 				$order_clause.
-				' LIMIT 10';			
-				
+				' LIMIT 10';
+
 			}
-		}		
-				
+		}
+
 		$rs = api_sql_query($sql, __FILE__, __LINE__);
 		while ($user = Database :: fetch_array($rs)) {
 			$return .= '<a href="javascript: void(0);" onclick="javascript: fill_coach_field(\''.$user['username'].'\')">'.api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')</a><br />';
@@ -106,14 +106,14 @@ function fill_coach_field (username) {
 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']; 
-	$nb_days_acess_before = $_POST['nb_days_acess_before']; 
-	$nb_days_acess_after = $_POST['nb_days_acess_after']; 
+	$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'];
+	$nb_days_acess_before = $_POST['nb_days_acess_before'];
+	$nb_days_acess_after = $_POST['nb_days_acess_after'];
 	$nolimit=$_POST['nolimit'];
 	$coach_username=$_POST['coach_username'];
 	$return = SessionManager::create_session($name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nb_days_acess_before,$nb_days_acess_after,$nolimit,$coach_username);
@@ -164,18 +164,18 @@ $count_users = Database::result($rs, 0, 0);
 
 if (intval($count_users)<50) {
 	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
-	$sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1'".$order_clause;	
-	global $_configuration;	
-	if ($_configuration['multiple_access_urls']==true) {		
-		$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+	$sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1'".$order_clause;
+	global $_configuration;
+	if ($_configuration['multiple_access_urls']==true) {
+		$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1){					
+		if ($access_url_id != -1){
 			$sql = 'SELECT username, lastname, firstname FROM '.$tbl_user.' user
 			INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
-			WHERE access_url_id = '.$access_url_id.'  AND status=1'.$order_clause;			
+			WHERE access_url_id = '.$access_url_id.'  AND status=1'.$order_clause;
 		}
-	}	
-	
+	}
+
 	$result=api_sql_query($sql,__FILE__,__LINE__);
 	$Coaches=api_store_result($result);
 	?>

+ 3 - 3
main/admin/session_course_list.php

@@ -38,12 +38,12 @@ if(!list($session_name)=mysql_fetch_row($result))
 
 if($action == 'delete') {
 	$idChecked = $_REQUEST['idChecked'];
-	if(is_array($idChecked) && count($idChecked)>0) {		
-		$my_temp = array(); 
+	if(is_array($idChecked) && count($idChecked)>0) {
+		$my_temp = array();
 		foreach ($idChecked as $id){
 			$my_temp[]= Database::escape_string($id);// forcing the escape_string
 		}
-		$idChecked = $my_temp;		
+		$idChecked = $my_temp;
 		$idChecked="'".implode("','",$idChecked)."'";
 		api_sql_query("DELETE FROM $tbl_session_rel_course WHERE id_session='$id_session' AND course_code IN($idChecked)",__FILE__,__LINE__);
 		$nbr_affected_rows=mysql_affected_rows();

+ 2 - 2
main/admin/session_course_user_list.php

@@ -23,7 +23,7 @@ $action=$_REQUEST['action'];
 $sort=in_array($_GET['sort'],array('lastname','firstname','username'))?$_GET['sort']:api_sort_by_first_name()?'firstname':'lastname';
 $idChecked = (is_array($_GET['idChecked']) ? $_GET['idChecked'] : (is_array($_POST['idChecked']) ? $_POST['idChecked'] : null));
 if (is_array($idChecked)) {
-	$my_temp = array(); 
+	$my_temp = array();
 	foreach ($idChecked as $id){
 		$my_temp[]= intval($id);// forcing the intval
 	}
@@ -37,7 +37,7 @@ if(!list($session_name,$course_title)=mysql_fetch_row($result))
 	exit();
 }
 
-if($action == 'delete') {	
+if($action == 'delete') {
 	if(is_array($idChecked) && count($idChecked)>0 ) {
 		$idChecked=implode(',',$idChecked);
 		api_sql_query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='".addslashes($course_code)."' AND id_user IN($idChecked)",__FILE__,__LINE__);

+ 10 - 10
main/admin/session_edit.php

@@ -43,14 +43,14 @@ if (!api_is_platform_admin() && $infos['session_admin_id']!=$_user['user_id']) {
 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']; 
-	$nb_days_acess_before = $_POST['nb_days_access_before']; 
-	$nb_days_acess_after = $_POST['nb_days_access_after']; 
+	$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'];
+	$nb_days_acess_before = $_POST['nb_days_access_before'];
+	$nb_days_acess_after = $_POST['nb_days_access_after'];
 	$nolimit=$_POST['nolimit'];
 	$id_coach=$_POST['id_coach'];
 	$return = SessionManager::edit_session($id,$name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nb_days_acess_before,$nb_days_acess_after,$nolimit,$id_coach);
@@ -64,7 +64,7 @@ $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, usern
 $sql="SELECT user_id,lastname,firstname,username FROM $tbl_user WHERE status='1'".$order_clause;
 
 if ($_configuration['multiple_access_urls']==true){
-	$table_access_url_rel_user= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+	$table_access_url_rel_user= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 	$access_url_id = api_get_current_access_url_id();
 	if ($access_url_id != -1) {
 		$sql="SELECT DISTINCT u.user_id,lastname,firstname,username FROM $tbl_user u INNER JOIN $table_access_url_rel_user url_rel_user
@@ -293,7 +293,7 @@ for($i=$thisYear-5;$i <= ($thisYear+5);$i++)
   <td>&nbsp;</td>
   <td>
 <button class="save" type="submit" value="<?php echo get_lang('ModifyThisSession') ?>"><?php echo get_lang('ModifyThisSession') ?></button>
-  
+
   </td>
 </tr>
 

+ 20 - 20
main/admin/session_export.php

@@ -70,20 +70,20 @@ if($_POST['formSent'] )
 	if(empty($session_id))
 	{
 		$sql = "SELECT id,name,id_coach,username,date_start,date_end FROM $tbl_session INNER JOIN $tbl_user
-					ON $tbl_user.user_id = $tbl_session.id_coach ORDER BY id";	
-			
-		global $_configuration;	
-		if ($_configuration['multiple_access_urls']==true) {	
-			$tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);	
+					ON $tbl_user.user_id = $tbl_session.id_coach ORDER BY id";
+
+		global $_configuration;
+		if ($_configuration['multiple_access_urls']==true) {
+			$tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 			$access_url_id = api_get_current_access_url_id();
 			if ($access_url_id != -1){
-			$sql = "SELECT id, name,id_coach,username,date_start,date_end FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url 		
-				ON (s.id= session_rel_url.session_id) INNER JOIN $tbl_user u ON (u.user_id = s.id_coach)		
+			$sql = "SELECT id, name,id_coach,username,date_start,date_end FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url
+				ON (s.id= session_rel_url.session_id) INNER JOIN $tbl_user u ON (u.user_id = s.id_coach)
 				WHERE access_url_id = $access_url_id
-				ORDER BY id";								
-						
+				ORDER BY id";
+
 			}
-		}				 		
+		}
 		$result=api_sql_query($sql,__FILE__,__LINE__);
 	}
 	else
@@ -95,7 +95,7 @@ if($_POST['formSent'] )
 				WHERE id='$session_id'";
 
 		$result = api_sql_query($sql,__FILE__,__LINE__);
-		
+
 	}
 
 	if(Database::num_rows($result))
@@ -228,9 +228,9 @@ if($_POST['formSent'] )
 				$courses = api_substr($courses , 0, api_strlen($courses)-1);
 			$add .= $courses;
 
-			
 
-			if($cvs) {				
+
+			if($cvs) {
 				$breakline = api_is_windows_os()?"\r\n":"\n";
 				$add .= ";$breakline";
 			} else {
@@ -257,17 +257,17 @@ Display::display_header($tool_name);
 
 //select of sessions
 $sql = "SELECT id, name FROM $tbl_session ORDER BY name";
-global $_configuration;	
-if ($_configuration['multiple_access_urls']==true) {		
-	$tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);	
+global $_configuration;
+if ($_configuration['multiple_access_urls']==true) {
+	$tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 	$access_url_id = api_get_current_access_url_id();
 	if ($access_url_id != -1){
-	$sql = "SELECT id, name FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url 		
-		ON (s.id= session_rel_url.session_id)		
+	$sql = "SELECT id, name FROM $tbl_session s INNER JOIN $tbl_session_rel_access_url as session_rel_url
+		ON (s.id= session_rel_url.session_id)
 		WHERE access_url_id = $access_url_id
-		ORDER BY name";		
+		ORDER BY name";
 	}
-} 
+}
 
 
 $result=api_sql_query($sql,__FILE__,__LINE__);

+ 910 - 896
main/admin/session_import.php

@@ -1,898 +1,912 @@
-<?php // $Id: session_import.php 20699 2009-05-15 16:32:03Z ivantcholakov $
-/* For licensing terms, see /dokeos_license.txt */
-/**
-==============================================================================
-*	@package dokeos.admin
-==============================================================================
-*/
-$language_file = array('admin','registration');
-$cidReset=true;
-require('../inc/global.inc.php');
-if (empty($charset)) {
-	$charset = 'ISO-8859-15';
-}
-api_protect_admin_script(true);
-
-require_once(api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require_once(api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-require(api_get_path(CONFIGURATION_PATH).'add_course.conf.php');
-require_once(api_get_path(LIBRARY_PATH).'add_course.lib.inc.php');
-require_once(api_get_path(LIBRARY_PATH).'sessionmanager.lib.php');
-require_once(api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php');
-require_once(api_get_path(INCLUDE_PATH).'lib/course.lib.php');
-$formSent=0;
-$errorMsg='';
-
-$tbl_user					= Database::get_main_table(TABLE_MAIN_USER);
-$tbl_course					= Database::get_main_table(TABLE_MAIN_COURSE);
-$tbl_course_user			= Database::get_main_table(TABLE_MAIN_COURSE_USER);
-$tbl_session				= Database::get_main_table(TABLE_MAIN_SESSION);
-$tbl_session_user			= Database::get_main_table(TABLE_MAIN_SESSION_USER);
-$tbl_session_course			= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
-$tbl_session_course_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-
-$tool_name=get_lang('ImportSessionListXMLCSV');
-
-$interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('AdministrationTools'));
-
-set_time_limit(0);
-$inserted_in_course = array();
-
-if ($_POST['formSent']) {
-	if (isset($_FILES['import_file']['tmp_name'])) {
-		$formSent=$_POST['formSent'];
-		$file_type=$_POST['file_type'];
-		$sendMail=$_POST['sendMail']?1:0;		
-		//$updatesession=$_POST['updatesession']?1:0;
-		$updatesession = 0;
-		$sessions=array();
-
-		///////////////////////
-		//XML/////////////////
-		/////////////////////
-		
-		$countSessions = 0;
-		
-		if ($file_type == 'xml') {
-			$racine = @simplexml_load_file($_FILES['import_file']['tmp_name']);	
-			if (is_object($racine)) {																				
-				if (count($racine->Users->User) > 0) {
-					
-					//Creating - updating users
-					// from the <Sessions> <User> racine 		
-					foreach($racine->Users->User as $userNode) {
-						$username = api_convert_encoding($userNode->Username,$charset,'utf-8');
-						$isCut = 0; // if the username given is too long
-						if(api_strlen($username)>20) {
-							$user_name_dist = $username;
-							$username = api_substr($username,0,20);
-							$isCut = 1;
-						}						
-						$user_exist = UserManager::is_username_available($username);												
-						if ($user_exist == true) {
-							if ($isCut) {
-								$errorMsg .= get_lang('UsernameTooLongWasCut').' '.get_lang('From').' '.$user_name_dist.' '.get_lang('To').' '.$username.' <br />';
-							}	
-							$lastname = api_convert_encoding($userNode->Lastname,$charset,'utf-8');
-							$firstname = api_convert_encoding($userNode->Firstname,$charset,'utf-8');
-							$password = api_convert_encoding($userNode->Password,$charset,'utf-8');
-							if(empty($password)) {
-								$password = base64_encode(rand(1000,10000));
-	                        }
-							$email = api_convert_encoding($userNode->Email,$charset,'utf-8');
-							$official_code = api_convert_encoding($userNode->OfficialCode,$charset,'utf-8');
-							$phone = api_convert_encoding($userNode->Phone,$charset,'utf-8');
-							$status = api_convert_encoding($userNode->Status,$charset,'utf-8');
-							switch ($status) {
-								case 'student' : $status = 5; break;
-								case 'teacher' : $status = 1; break;
-								default : $status = 5; 
-								$errorMsg = get_lang('StudentStatusWasGivenTo').' : '.$username.'<br />';
-							}
-							
-							//adding user to the platform 
-							$sql = "INSERT INTO $tbl_user SET
-									username = '".Database::escape_string($username)."',
-									lastname = '".Database::escape_string($lastname)."',
-									firstname = '".Database::escape_string($firstname)."',
-									password = '".(api_get_encrypted_password($password))."',
-									email = '".Database::escape_string($email)."',
-									official_code = '".Database::escape_string($official_code)."',
-									phone = '".Database::escape_string($phone)."',
-									status = '".Database::escape_string($status)."'";
-							
-							//if available adding also the access_url rel user relationship
-							api_sql_query($sql, __FILE__, __LINE__);
-							$return=Database::get_last_insert_id();						
-							global $_configuration;
-							require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-							if ($_configuration['multiple_access_urls']==true) {										
-								if (api_get_current_access_url_id()!=-1)
-									UrlManager::add_user_to_url($return, api_get_current_access_url_id());
-								else
-									UrlManager::add_user_to_url($return, 1);
-							} else {
-								//we are adding by default the access_url_user table with access_url_id = 1
-								UrlManager::add_user_to_url($return, 1);				
-							}
-							// send an email to users
-							if($sendMail) {														
+<?php // $Id: session_import.php 20699 2009-05-15 16:32:03Z ivantcholakov $
+/* For licensing terms, see /dokeos_license.txt */
+/**
+==============================================================================
+*	@package dokeos.admin
+==============================================================================
+*/
+
+$language_file = array('admin', 'registration');
+$cidReset = true;
+
+require '../inc/global.inc.php';
+
+$this_section = SECTION_PLATFORM_ADMIN;
+api_protect_admin_script(true);
+
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+require api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
+require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+
+$form_sent = 0;
+$error_message = ''; // Avoid conflict with the global variable $error_msg (array type) in add_course.conf.php.
+
+$tbl_user					= Database::get_main_table(TABLE_MAIN_USER);
+$tbl_course					= Database::get_main_table(TABLE_MAIN_COURSE);
+$tbl_course_user			= Database::get_main_table(TABLE_MAIN_COURSE_USER);
+$tbl_session				= Database::get_main_table(TABLE_MAIN_SESSION);
+$tbl_session_user			= Database::get_main_table(TABLE_MAIN_SESSION_USER);
+$tbl_session_course			= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+$tbl_session_course_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+
+$tool_name = get_lang('ImportSessionListXMLCSV');
+
+$interbreadcrumb[] = array('url' => 'index.php','name' => get_lang('AdministrationTools'));
+
+set_time_limit(0);
+
+// Set this option to true to enforce strict purification for usenames.
+$purification_option_for_usernames = false;
+
+$inserted_in_course = array();
+
+if ($_POST['formSent']) {
+	if (isset($_FILES['import_file']['tmp_name'])) {
+		$form_sent = $_POST['formSent'];
+		$file_type = $_POST['file_type'];
+		$send_mail = $_POST['sendMail'] ? 1 : 0;
+		//$updatesession = $_POST['updatesession'] ? 1 : 0;
+		$updatesession = 0;
+		$sessions = array();
+
+		$session_counter = 0;
+
+		if ($file_type == 'xml') {
+
+			///////////////////////
+			//XML/////////////////
+			/////////////////////
+
+			// SimpleXML for PHP5 deals with various encodings, but how many they are, what are version issues, do we need to waste time with configuration options?
+			// For avoiding complications we go some sort of "PHP4 way" - we convert the input xml-file into UTF-8 before passing it to the parser.
+			// Instead of:
+			// $root = @simplexml_load_file($_FILES['import_file']['tmp_name']);
+			// we may use the following construct:
+			// $root = @simplexml_load_string(api_utf8_encode_xml(file_get_contents($_FILES['import_file']['tmp_name'])));
+			// To ease debugging let us use:
+			$content = file_get_contents($_FILES['import_file']['tmp_name']);
+			$content = api_utf8_encode_xml($content);
+			$root = @simplexml_load_string($content);
+			unset($content);
+
+			if (is_object($root)) {
+				if (count($root->Users->User) > 0) {
+
+					// Creating/updating users from <Sessions> <Users> base node.
+					foreach ($root->Users->User as $node_user) {
+						$username = $username_old = trim(api_utf8_decode($node_user->Username));
+							$username = UserManager::purify_username($username, $purification_option_for_usernames);
+						if (UserManager::is_username_available($username)) {
+							if (UserManager::is_username_too_long($username_old)) {
+								$error_message .= get_lang('UsernameTooLongWasCut').' '.get_lang('From').' '.$username_old.' '.get_lang('To').' '.$username.' <br />';
+							}
+							$lastname = trim(api_utf8_decode($node_user->Lastname));
+							$firstname = trim(api_utf8_decode($node_user->Firstname));
+							$password = api_utf8_decode($node_user->Password);
+							if (empty($password)) {
+								$password = api_generate_password();
+							}
+							$email = trim(api_utf8_decode($node_user->Email));
+							$official_code = trim(api_utf8_decode($node_user->OfficialCode));
+							$phone = trim(api_utf8_decode($node_user->Phone));
+							$status = trim(api_utf8_decode($node_user->Status));
+							switch ($status) {
+								case 'student' : $status = 5; break;
+								case 'teacher' : $status = 1; break;
+								default : $status = 5; $error_message .= get_lang('StudentStatusWasGivenTo').' : '.$username.'<br />';
+							}
+
+							// Adding the current user to the platform.
+							$sql = "INSERT INTO $tbl_user SET
+									username = '".Database::escape_string($username)."',
+									lastname = '".Database::escape_string($lastname)."',
+									firstname = '".Database::escape_string($firstname)."',
+									password = '".(api_get_encrypted_password($password))."',
+									email = '".Database::escape_string($email)."',
+									official_code = '".Database::escape_string($official_code)."',
+									phone = '".Database::escape_string($phone)."',
+									status = '".Database::escape_string($status)."'";
+
+							// When it is applicable, adding the access_url rel user relationship too.
+							Database::query($sql, __FILE__, __LINE__);
+							$return = Database::get_last_insert_id();
+							global $_configuration;
+							require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
+							if ($_configuration['multiple_access_urls']) {
+								if (api_get_current_access_url_id() != -1) {
+									UrlManager::add_user_to_url($return, api_get_current_access_url_id());
+								} else {
+									UrlManager::add_user_to_url($return, 1);
+								}
+							} else {
+								// We add by default in the access_url_user table with access_url_id = 1.
+								UrlManager::add_user_to_url($return, 1);
+							}
+							// Sending email to the current user.
+							if ($send_mail) {
 								$recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
-								$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');			
-								$emailbody="[NOTE:] ".get_lang('ThisIsAutomaticEmailNoReply').".\n\n".get_lang('langDear')." ".api_get_person_name($firstname, $lastname).",\n\n".get_lang('langYouAreReg')." ".api_get_setting('siteName') ." ".get_lang('langSettings')." $username\n". get_lang('langPass')." : $password\n\n".get_lang('langAddress') ." ". get_lang('langIs') ." ". $serverAddress ."\n\n".get_lang('YouWillSoonReceiveMailFromCoach')."\n\n". get_lang('langProblem'). "\n\n". get_lang('langFormula');						
+								$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
+								$emailbody = "[NOTE:] ".get_lang('ThisIsAutomaticEmailNoReply').".\n\n".get_lang('langDear')." ".api_get_person_name($firstname, $lastname).",\n\n".get_lang('langYouAreReg')." ".api_get_setting('siteName') ." ".get_lang('langSettings')." $username\n". get_lang('langPass')." : $password\n\n".get_lang('langAddress') ." ". get_lang('langIs') ." ". $serverAddress ."\n\n".get_lang('YouWillSoonReceiveMailFromCoach')."\n\n". get_lang('langProblem'). "\n\n". get_lang('langFormula');
 								$sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-							    $email_admin = api_get_setting('emailAdministrator');							
-								@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name,$email_admin);
-							}
-						} else {
-							$lastname = api_convert_encoding($userNode->Lastname,$charset,'utf-8');
-							$firstname = api_convert_encoding($userNode->Firstname,$charset,'utf-8');
-							$password = api_convert_encoding($userNode->Password,$charset,'utf-8');
-							$email = api_convert_encoding($userNode->Email,$charset,'utf-8');
-							$official_code = api_convert_encoding($userNode->OfficialCode,$charset,'utf-8');
-							$phone = api_convert_encoding($userNode->Phone,$charset,'utf-8');
-							$status = api_convert_encoding($userNode->Status,$charset,'utf-8');
-							switch($status) {
-								case 'student' : $status = 5; break;
-								case 'teacher' : $status = 1; break;
-								default : $status = 5; $errorMsg = get_lang('StudentStatusWasGivenTo').' : '.$username.'<br />';
-							}
-							
-							$sql = "UPDATE $tbl_user SET
-										lastname = '".Database::escape_string($lastname)."',
-										firstname = '".Database::escape_string($firstname)."',
-										".(empty($password) ? "" : "password = '".(api_get_encrypted_password($password))."',")."
-										email = '".Database::escape_string($email)."',
-										official_code = '".Database::escape_string($official_code)."',
-										phone = '".Database::escape_string($phone)."',
-										status = '".Database::escape_string($status)."'
-									WHERE username = '".Database::escape_string($username)."'";
-	
-							api_sql_query($sql, __FILE__, __LINE__);						
-						}
-					}
-				}
-				
-				// Creating - editing courses
-				// from the <Sessions> <Courses> racine
-				if (count($racine->Courses->Course) > 0) {			
-					foreach($racine->Courses->Course as $courseNode) {
-						$course_code = api_convert_encoding($courseNode->CourseCode,$charset,'utf-8');
-						$title = api_convert_encoding($courseNode->CourseTitle,$charset,'utf-8');
-						$description = api_convert_encoding($courseNode->CourseDescription,$charset,'utf-8');
-						$language = api_convert_encoding($courseNode->CourseLanguage,$charset,'utf-8');
-						$username = api_convert_encoding($courseNode->CourseTeacher,$charset,'utf-8');
-						
-						//looking for the teacher
-						$sql = "SELECT user_id, lastname, firstname FROM $tbl_user WHERE username='$username'";
-						$rs = api_sql_query($sql, __FILE__, __LINE__);	
-						list($user_id, $lastname, $firstname) = Database::fetch_array($rs);						
-						global $_configuration;
-						$keys = define_course_keys($course_code, "", $_configuration['db_prefix']);		
-											
-						if (sizeof($keys)) {	
-							$currentCourseCode = $keys['visual_code'];
-							$currentCourseId = $keys['currentCourseId'];
-							if(empty($currentCourseCode))
-								$currentCourseCode = $currentCourseId;
-							$currentCourseDbName = $keys['currentCourseDbName'];
-							$currentCourseRepository = $keys['currentCourseRepository'];
-							//creating a course
-							
-							if($currentCourseId == api_strtoupper($course_code)) {
-								if (empty ($title)) {
-									$title = $keys['currentCourseCode'];
-								}																									
-								prepare_course_repository($currentCourseRepository, $currentCourseId);
-								update_Db_course($currentCourseDbName);								
-								$pictures_array=fill_course_repository($currentCourseRepository); 
-								fill_Db_course($currentCourseDbName, $currentCourseRepository, 'english',$pictures_array);								
-								register_course($currentCourseId, $currentCourseCode, $currentCourseRepository, $currentCourseDbName, "$lastname $firstname", $course['unit_code'], addslashes($course['FR']['title']), $language, $user_id);
-								$sql = "INSERT INTO ".$tbl_course." SET
-											code = '".$currentCourseId."',
-											db_name = '".$currentCourseDbName."',
-											directory = '".$currentCourseRepository."',
-											course_language = '".$language."',
-											title = '".$title."',
-											description = '".lang2db($description)."',
-											category_code = '',
-											visibility = '".$defaultVisibilityForANewCourse."',
-											show_score = '',
-											disk_quota = NULL,
-											creation_date = now(),
-											expiration_date = NULL,
-											last_edit = now(),
-											last_visit = NULL,
-											tutor_name = '".api_get_person_name($firstname, $lastname, null, null, $language)."',
-											visual_code = '".$currentCourseCode."'";
-	
-								api_sql_query($sql, __FILE__, __LINE__);
-	
-								$sql = "INSERT INTO ".$tbl_course_user." SET
-											course_code = '".$currentCourseId."',
-											user_id = '".$user_id."',
-											status = '1',
-											role = '".lang2db('Professor')."',
-											tutor_id='1',
-											sort='". ($sort +1)."',
-											user_course_cat='0'";
-	
-								api_sql_query($sql, __FILE__, __LINE__);
-							}
-	
-						}
-					}                    
-				}
-				
-				// Creating sessions
-				// from the <Sessions><Session> racine
-				if (count($racine->Session) > 0) {
-					foreach ($racine->Session as $sessionNode) {						 
-						// foreach session						
-						$countCourses = 0;
-						$countUsers = 0;
-	
-						$SessionName = api_convert_encoding($sessionNode->SessionName,$charset,'utf-8');
-						$Coach = api_convert_encoding($sessionNode->Coach,$charset,'utf-8');
-	
-						if (!empty($Coach)) {													
-							$coach_id = UserManager::get_user_id_from_username($Coach);
-							if($coach_id === false) {
-								$errorMsg .= get_lang('UserDoesNotExist').' : '.$Coach.'<br />';
-								//forcing the coach id if user does not exist
-								$coach_id = api_get_user_id();
-							}
-						} else {
-							//forcing the coach id 
-							$coach_id = api_get_user_id();
-						}
-						
-						$DateStart = $sessionNode->DateStart;
-						
-						if(!empty($DateStart)) {
-							list($YearStart,$MonthStart, $DayStart) = explode('-',$DateStart);
-							if(empty($YearStart) || empty($MonthStart) || empty($DayStart)) {
-								$errorMsg .= get_lang('WrongDate').' : '.$DateStart.'<br />';
-								break;
-							} else {
-								$timeStart = mktime(0,0,0,$MonthStart,$DayStart,$YearStart);
-							}
-	
-							$DateEnd = $sessionNode->DateEnd;
-							if(!empty($DateStart)) {
-								list($YearEnd,$MonthEnd, $DayEnd) = explode('-',$DateEnd);
-								if(empty($YearEnd) || empty($MonthEnd) || empty($DayEnd)) {
-									$errorMsg .= get_lang('WrongDate').' : '.$DateEnd.'<br />';
-									break;
-								} else {
-									$timeEnd = mktime(0,0,0,$MonthEnd,$DayEnd,$YearEnd);
-								}
-							}
-							if($timeEnd - $timeStart < 0) {
-								$errorMsg .= get_lang('StartDateShouldBeBeforeEndDate').' : '.$DateEnd.'<br />';
-							}
-						}
-						
-						//						
-						if (!$updatesession) {
-							// Always create a session
-							$uniqueName = false; // this MUST be initializead
-							$i = 0;
-							//change session name												
-							// verify that session doesn't exist
-							while(!$uniqueName) {
-								if($i>1)
-									$suffix = ' - '.$i;
-								$sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.Database::escape_string($SessionName.$suffix).'"';
-								$rs = api_sql_query($sql, __FILE__, __LINE__);		
-								if(Database::result($rs,0,0)) {
-									$i++;
-								} else {
-									$uniqueName = true;
-									$SessionName .= $suffix;
-								}
-							}							
-							// Creating the session	
-							$sqlSession = "INSERT IGNORE INTO $tbl_session SET
-											name = '".Database::escape_string($SessionName)."',
-											id_coach = '$coach_id',
-											date_start = '$DateStart',
-											date_end = '$DateEnd',
-											session_admin_id=".intval($_user['user_id']);					
-							$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);					
-							$session_id = Database::get_last_insert_id();					
-							$countSessions++;					
-								
-						} else {
-							// update the session if needed it						
-							$my_session_result = SessionManager::get_session_by_name($SessionName);
-							if ($my_session_result == false) {							
-								// Creating the session	
-									$sqlSession = "INSERT IGNORE INTO $tbl_session SET
-													name = '".Database::escape_string($SessionName)."',
-													id_coach = '$coach_id',
-													date_start = '$DateStart',
-													date_end = '$DateEnd',
-													session_admin_id=".intval($_user['user_id']);					
-									$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);					
-									$session_id = Database::get_last_insert_id();					
-									$countSessions++;					
-							} else {
-								//if already exists we update the session						
-								$sqlSession = "UPDATE $tbl_session SET
-												id_coach = '$coach_id',
-												date_start = '$DateStart',
-												date_end = '$DateEnd'
-												WHERE name = '$SessionName'";
-								$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);
-								$session_id = api_sql_query("SELECT id FROM $tbl_session WHERE name='$SessionName'",__FILE__,__LINE__);
-								list($session_id) = Database::fetch_array($session_id);
-								api_sql_query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'",__FILE__,__LINE__);
-								api_sql_query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'",__FILE__,__LINE__);
-								api_sql_query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'",__FILE__,__LINE__);
-							}
-						}												
-					
-						//adding the session to an access_url 
-						global $_configuration;	
-	                    require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-						if ($_configuration['multiple_access_urls']==true) {			
-							$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
-							$access_url_id = api_get_current_access_url_id();			
-							UrlManager::add_session_to_url($session_id,$access_url_id);			
-						} else {
-							// we are filling by default the access_url_rel_session table 
-							UrlManager::add_session_to_url($session_id,1);
-						}
-						
-						// Adding users to the new session 
-						foreach ($sessionNode->User as $userNode){		
-							$username = api_convert_encoding(api_substr($userNode,0,20),$charset,'utf-8');
-							$user_id = UserManager::get_user_id_from_username($username);					
-							if($user_id!==false){						
-								$sql = "INSERT IGNORE INTO $tbl_session_user SET
-										id_user='$user_id',
-										id_session = '$session_id'";								
-								$rsUser = api_sql_query($sql,__FILE__,__LINE__);							
-								$countUsers++;							
-							}
-						}
-						// Adding courses to a session
-						//var_dump($sessionNode->Course);
-						
-						foreach ($sessionNode->Course as $courseNode) {	
-							$CourseCode = Database::escape_string($courseNode->CourseCode);	
-							// Verify that the course pointed by the course code node exists
-	                        if (CourseManager::course_exists($CourseCode)) {
-							    // If the course exists we continue
-	                            $c_info = CourseManager::get_course_information($CourseCode);
-							$Coach = api_substr($courseNode->Coach,0,20);
-								// finding the user coach
-								if(!empty($Coach)){
-									$coach_id = UserManager::get_user_id_from_username($Coach);													
-									if($coach_id===false) {
-										$errorMsg .= get_lang('UserDoesNotExist').' : '.$Coach.'<br />';
-										$coach_id = '';
-									}
-								} else {
-									$coach_id = '';
-								}
-								$session_course_relation = SessionManager::relation_session_course_exist($session_id, $CourseCode);								
-								if ($session_course_relation==false) {
-									$sqlCourse = "INSERT INTO $tbl_session_course SET
-												  course_code = '$CourseCode',
-												  id_coach='$coach_id',
-												  id_session='$session_id'";
-									$rsCourse = api_sql_query($sqlCourse,__FILE__,__LINE__);
-								}
-								if (Database::affected_rows()) {
-									$countCourses++;
-									$countUsersCourses = 0;								
-									foreach ($courseNode->User as $userNode) {
-										$username = api_substr($userNode,0,20);
-										$user_id = UserManager::get_user_id_from_username($username);																		
-										if ($user_id!==false) {
-											// adding to session_rel_user table
-											$sql = "INSERT IGNORE INTO $tbl_session_user SET
-												id_user='$user_id',
-												id_session = '$session_id'";										                                    
-											$rsUser = api_sql_query($sql,__FILE__,__LINE__);
-											$countUsers++;
-											// adding to session_rel_user_rel_course table			
-											$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-													id_user='$user_id',
-													course_code='$CourseCode',
-													id_session = '$session_id'";
-											$rsUsers = api_sql_query($sql,__FILE__,__LINE__);										
-											$countUsersCourses++;                                       
-										} else {
-											$errorMsg .= get_lang('UserDoesNotExist').' : '.$username.'<br />';
-										}
-									}
-									$update_session_course = "UPDATE $tbl_session_course SET nbr_users='$countUsersCourses' WHERE course_code='$CourseCode'";
-									api_sql_query($update_session_course,__FILE__,__LINE__);
-	                                $inserted_in_course[$CourseCode] = $c_info['title'];
-								}
-							}
-							
-	                        if (CourseManager::course_exists($CourseCode,true)) {
-	                            // if the course exists we continue
-	                            // also subscribe to virtual courses through check on visual code
-	                            $list = CourseManager :: get_courses_info_from_visual_code($CourseCode);
-	                            foreach ($list as $vcourse) {
-	                                if ($vcourse['code'] == $CourseCode) {
-	                                    //ignore, this has already been inserted
-	                                } else {
-	                                    $Coach = substr($courseNode->Coach,0,20);
-	                                    if(!empty($Coach)){
-	                                    	$CoachId = UserManager::get_user_id_from_username($Coach);																		
-											if ($user_id===false) {
-												$errorMsg .= get_lang('UserDoesNotExist').' : '.$Coach.'<br />';
-												$CoachId = '';
-											}	                                     
-	                                    } else {
-	                                        $CoachId = '';
-	                                    }
-	                                    	        
-	                                    $sqlCourse = "INSERT INTO $tbl_session_course SET
-	                                                  course_code = '".$vcourse['code']."',
-	                                                  id_coach='$CoachId',
-	                                                  id_session='$session_id'";
-	                                    $rsCourse = api_sql_query($sqlCourse,__FILE__,__LINE__);
-	                                    if (Database::affected_rows()) {
-	                                        $countCourses++;	        
-	                                        $countUsersCourses = 0;
-	                                        foreach ($courseNode->User as $userNode) {
-	                                            $username = substr($userNode,0,20);	                                            
-	                                            $user_id = UserManager::get_user_id_from_username($username);
-	                                            if ($user_id !==false) {	                                           
-	                                                $sql = "INSERT IGNORE INTO $tbl_session_user SET
-	                                                    id_user='$user_id',
-	                                                    id_session = '$session_id'";
-	                                                $rsUser = api_sql_query($sql,__FILE__,__LINE__);
-	                                                if (Database::affected_rows()) {
-	                                                    $countUsers++;
-	                                                }	                                                
-	                                                $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-	                                                        id_user='$user_id',
-	                                                        course_code='".$vcourse['code']."',
-	                                                        id_session = '$session_id'";
-	                                                $rsUsers = api_sql_query($sql,__FILE__,__LINE__);
-	                                                if(Database::affected_rows())
-	                                                    $countUsersCourses++;
-	                                            } else {
-	                                                $errorMsg .= get_lang('UserDoesNotExist').' : '.$username.'<br />';
-	                                            }
-	                                        }
-	                                        api_sql_query("UPDATE $tbl_session_course SET nbr_users='$countUsersCourses' WHERE course_code='$CourseCode'",__FILE__,__LINE__);
-	                                    }
-	                                }
-	                                $inserted_in_course[$vcourse['code']] = $vcourse['title'];
-	                            }                         
-	                        } else { // if the course does not exists
-								$errorMsg .= get_lang('CourseDoesNotExist').' : '.$CourseCode.'<br />';
-							}
-						}
-						api_sql_query("UPDATE $tbl_session SET nbr_users='$countUsers', nbr_courses='$countCourses' WHERE id='$session_id'",__FILE__,__LINE__);
-				}
-
-				}
-				if(empty($racine->Users->User) && empty($racine->Courses->Course) && empty($racine->Session)) {
-					$errorMsg=get_lang('NoNeededData');
-				}
-			} else {
-				$errorMsg .= get_lang('XMLNotValid');
-			}
-		} else {
-			/////////////////////
-			// CSV /////////////
-			///////////////////
-						
-			$content=file($_FILES['import_file']['tmp_name']);
-			if(!api_strstr($content[0],';')) {
-				$errorMsg=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_eregi_replace('[^a-z0-9_-]','',$tag_name);
-						}
-						if(!in_array('SessionName',$tag_names) || !in_array('DateStart',$tag_names) || !in_array('DateEnd',$tag_names)) {
-							$errorMsg=get_lang('NoNeededData');
-							break;
-						}
-					}
-				}
-				// looping the sessions
-				foreach($sessions as $enreg) {			
-					$countUsers = 0;
-					$countCourses = 0;
-					
-					$SessionName = $enreg['SessionName'];
-					$DateStart = $enreg['DateStart'];
-					$DateEnd = $enreg['DateEnd'];
-					
-					// searching a coach	
-					if (!empty($enreg['Coach'])) {
-						$coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
-	                    if ($coach_id === false) {	                                            	
-							// if the user does not exist I'm the coach
-							$coach_id = api_get_user_id();	
-						}
-					} else {
-						$coach_id = api_get_user_id();
-					}
-										
-					if (!$updatesession) {
-						// Always create a session
-						$uniqueName = false; // this MUST be initializead
-						$i = 0;
-						//change session name												
-						// verify that session doesn't exist
-						while(!$uniqueName) {
-							if($i>1)
-								$suffix = ' - '.$i;
-							$sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.Database::escape_string($SessionName.$suffix).'"';
-							$rs = api_sql_query($sql, __FILE__, __LINE__);
-	
-							if(Database::result($rs,0,0)) {
-								$i++;
-							} else {
-								$uniqueName = true;
-								$SessionName .= $suffix;
-							}
-						}
-						
-						// Creating the session	
-						$sqlSession = "INSERT IGNORE INTO $tbl_session SET
-										name = '".Database::escape_string($SessionName)."',
-										id_coach = '$coach_id',
-										date_start = '$DateStart',
-										date_end = '$DateEnd',
-										session_admin_id=".intval($_user['user_id']);					
-						$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);					
-						$session_id = Database::get_last_insert_id();					
-						$countSessions++;								
-					} else {										
-						$my_session_result = SessionManager::get_session_by_name($SessionName);
-						if ($my_session_result == false) {
-							
-							// creating a session
-							$sqlSession = "INSERT IGNORE INTO $tbl_session SET
-									name = '$SessionName',
-									id_coach = '$coach_id',
-									date_start = '$DateStart',
-									date_end = '$DateEnd'";
-							$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);
-							// we get the last insert id
-							$my_session_result = SessionManager::get_session_by_name($SessionName);
-							$session_id = $my_session_result['id'];
-							//echo '<br>';				
-						} else {
-							//if already exists we update the session						
-							$sqlSession = "UPDATE $tbl_session SET
-											id_coach = '$coach_id',
-											date_start = '$DateStart',
-											date_end = '$DateEnd'
-											WHERE name = '$SessionName'";
-							$rsSession = api_sql_query($sqlSession, __FILE__, __LINE__);
-							$session_id = api_sql_query("SELECT id FROM $tbl_session WHERE name='$SessionName'",__FILE__,__LINE__);
-							list($session_id) = Database::fetch_array($session_id);
-							api_sql_query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'",__FILE__,__LINE__);
-							api_sql_query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'",__FILE__,__LINE__);
-							api_sql_query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'",__FILE__,__LINE__);
-						} 		
-						$countSessions++;					
-					}				
-					
-					$users = explode('|',$enreg['Users']);
-					//var_dump($users );
-					//Adding the relationship  Session - User
-					if (is_array($users)) {
-						foreach ($users as $user) {									
-							$user_id = UserManager::get_user_id_from_username($user);							
-							if ($user_id!==false) {					
-							// insert new users							
-								$sql = "INSERT IGNORE INTO $tbl_session_user SET
-									id_user='$user_id',
-									id_session = '$session_id'";
-								$rsUser = api_sql_query($sql,__FILE__,__LINE__);
-								$countUsers++;
-							}
-						}
-					}
-					
-					$courses = explode('|',$enreg['Courses']);
-					//var_dump($courses);
-					
-					foreach ($courses as $course) {			
-                        $CourseCode = api_strtoupper(api_substr($course,0,api_strpos($course,'[')));
-                        if (CourseManager::course_exists($CourseCode)) {
-                        	       	
-                            // If the course exists we continue
-                            $c_info = CourseManager::get_course_information($CourseCode);
-							
-    						$Coach = api_strstr($course,'[');
-    						$Coach = api_substr($Coach,1,api_strpos($Coach,']')-1);
-    
-    						if(!empty($Coach)) {
-    								$coach_id = UserManager::get_user_id_from_username($Coach);
-	                    		if ($coach_id === false) {	
-	                    			$coach_id = '';
-	                    		}    							
-    						} else {
-    							$Coach = '';
-    						}
-    						// Adding the course to a session		
-    						$sqlCourse = "INSERT IGNORE INTO $tbl_session_course SET
-    									  course_code = '$CourseCode',
-    									  id_coach='$coach_id',
-    									  id_session='$session_id'";    						
-    						$rsCourse = api_sql_query($sqlCourse,__FILE__,__LINE__);    						
-    						$countCourses++;
-    						
-    						$users = api_substr($course , api_strpos($course,'[',1)+1 , api_strpos($course,']',1));
-    						$users = explode('|',$enreg['Users']);
-    						$countUsersCourses = 0;    						
-    						
-    						//Adding the relationship  Session - Course - User 
-    						foreach ($users as $user) {    								
-    							$user_id = UserManager::get_user_id_from_username($user);    											
-								if ($user_id!==false) {	    									    								
-	    							$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-	    									id_user='$user_id',
-	    									course_code='$CourseCode',
-	    									id_session = '$session_id'";
-	    							$rsUsers = api_sql_query($sql,__FILE__,__LINE__);
-	    							$countUsersCourses++;
-    							} else {
-    								$errorMsg .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
-    							}
-    						}
-    						api_sql_query("UPDATE $tbl_session_course SET nbr_users='$countUsersCourses' WHERE course_code='$CourseCode'",__FILE__,__LINE__);
-    					
-                            $c_info = CourseManager::get_course_information($CourseCode);
-                            $inserted_in_course[$CourseCode] = $c_info['title'];                        
-                     	} else {
-                     		//we should create the course as in the XML import                     		
-                     	}
-                        
-	                    if (CourseManager::course_exists($CourseCode,true)) {
-	                        $list = CourseManager :: get_courses_info_from_visual_code($CourseCode);
-	                        foreach ($list as $vcourse) {
-	                            if ($vcourse['code'] == $CourseCode) {
-	                                //ignore, this has already been inserted
-	                            } else {
-                                    $Coach = api_strstr($course,'[');
-                                    $Coach = api_substr($Coach,1,api_strpos($Coach,']')-1);
-	        
-	                                if(!empty($Coach)){
-	                                    $sqlCoach = "SELECT user_id FROM $tbl_user WHERE username='$Coach'";
-	                                    $rsCoach = api_sql_query($sqlCoach,__FILE__,__LINE__);
-	                                    list($Coach) = (Database::fetch_array($rsCoach));
-	                                } else {
-	                                    $Coach = '';
-	                                }
-            						//Adding the relationship  Session - Course
-	                                $sqlCourse = "INSERT IGNORE INTO $tbl_session_course SET
-	                                              course_code = '".$vcourse['code']."',
-	                                              id_coach='$Coach',
-	                                              id_session='$session_id'";
-	        
-	                                $rsCourse = api_sql_query($sqlCourse,__FILE__,__LINE__);
-	                                if(Database::affected_rows()){
-	                                    $countCourses++;
-                                        $users = api_substr($course , api_strpos($course,'[',1)+1 , api_strpos($course,']',1));
-	                                    $users = explode('|',$enreg['Users']);
-	                                    $countUsersCourses = 0;
-	                                    foreach ($users as $user){
-	                                        $sqlUser = "SELECT user_id FROM $tbl_user WHERE username='".$user."'";
-	                                        $rsUser = api_sql_query($sqlUser);
-	                                        list($user_id) = (Database::fetch_array($rsUser));
-	                                        $sql = "INSERT INTO $tbl_session_course_user SET
-	                                                id_user='$user_id',
-	                                                course_code='".$vcourse['code']."',
-	                                                id_session = '$session_id'";
-	                                        $rsUsers = api_sql_query($sql,__FILE__,__LINE__);
-	                                        if(Database::affected_rows())
-	                                            $countUsersCourses++;
-	                                    }
-	                                    api_sql_query("UPDATE $tbl_session_course SET nbr_users='$countUsersCourses' WHERE course_code='".$vcourse['code']."'",__FILE__,__LINE__);
-	                                }
-	                            }
-	                        }
-                        	$inserted_in_course[$vcourse['code']] = $vcourse['title'];                        
-                   		}
-					}
-					
-					$sql_update_users = "UPDATE $tbl_session SET nbr_users='$countUsers', nbr_courses='$countCourses' WHERE id='$session_id'";
-					api_sql_query($sql_update_users,__FILE__,__LINE__);
-				}
-			}
-		}
-		if(!empty($errorMsg)) {
-			$errorMsg = get_lang('ButProblemsOccured').' :<br />'.$errorMsg;
-		}
-
-        if (count($inserted_in_course)>1) {
-        	$warn = get_lang('SeveralCoursesSubscribedToSessionBecauseOfSameVisualCode').': ';
-            foreach ($inserted_in_course as $code => $title) {
-            	$warn .= ' '.$title.' ('.$code.'),';
-            }
-            $warn = substr($warn,0,-1);
-        }
-		if($countSessions == 1) {
-			header('Location: resume_session.php?id_session='.$session_id.'&warn='.urlencode($warn));
-			exit;
-		} else {
-			header('Location: session_list.php?action=show_message&message='.urlencode(get_lang('FileImported').' '.$errorMsg).'&warn='.urlencode($warn));
-			exit;
-		}
-	} else {
-		$errorMsg = get_lang('NoInputFile');
-	}
-}
-
-// display the header
-Display::display_header($tool_name);
-
-// display the tool title
-// api_display_tool_title($tool_name);
-
-if (count($inserted_in_course) > 1) {
-	$msg = get_lang('SeveralCoursesSubscribedToSessionBecauseOfSameVisualCode').': ';
-    foreach ($inserted_in_course as $code => $title) {
-    	$msg .= ' '.$title.' ('.$title.'),';
-    }
-    $msg = substr($msg,0,-1);
-    Display::display_warning_message($msg);
-}
-
-/*
- 
- update session by default is true
- <tr>
-  <td nowrap="nowrap" valign="top"><?php echo get_lang('UpdateSession'); ?> :</td>
-  <td>
-	<input class="checkbox" type="checkbox" name="updatesession" id="updatesession" value="true" />
-  </td>
-</tr>
-
- 
-  */
-?>
-
-<form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" style="margin:0px;">
-<input type="hidden" name="formSent" value="1">
-<div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
-<table border="0" cellpadding="5" cellspacing="0">
-
-<?php
-if(!empty($errorMsg)) {
-?>
-<tr>
-  <td colspan="2">
-<?php
-	Display::display_normal_message($errorMsg,false); //main API
-?>
-  </td>
-</tr>
-<?php
-}
-?>
-<tr>
-  <td nowrap="nowrap"><?php echo get_lang('ImportFileLocation'); ?> :</td>
-  <td><input type="file" name="import_file" size="30"></td>
-</tr>
-<tr>
-  <td nowrap="nowrap" valign="top"><?php echo get_lang('FileType'); ?> :</td>
-  <td>
-	<input class="checkbox" type="radio" name="file_type" id="file_type_xml" value="xml" checked="checked" /> <label for="file_type_xml">XML</label> (<a href="example_session.xml" target="_blank"><?php echo get_lang('ExampleXMLFile'); ?></a>)<br>
-	<input class="checkbox" type="radio" name="file_type" id="file_type_csv"  value="csv" <?php if($formSent && $file_type == 'csv') echo 'checked="checked"'; ?>> <label for="file_type_csv">CSV</label> (<a href="example_session.csv" target="_blank"><?php echo get_lang('ExampleCSVFile'); ?></a>)<br>
-  </td>
-</tr>
-<tr>
-  <td nowrap="nowrap" valign="top"><?php echo get_lang('SendMailToUsers'); ?> :</td>
-  <td>
-	<input class="checkbox" type="checkbox" name="sendMail" id="sendMail" value="true" />
-  </td>
-</tr>
-
-
-
-
-<tr>
-  <td>&nbsp;</td>
-  <td>
-  <button class="save" type="submit" name="name" value="<?php echo get_lang('ImportSession') ?>"><?php echo get_lang('ImportSession') ?></button>
-  </td>
-</tr>
-</table>
-</form>
-
-<font color="gray">
-<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
-
-<blockquote>
-<pre>
-<b>SessionName</b>;Coach;<b>DateStart</b>;<b>DateEnd</b>;Users;Courses
-<b>xxx1</b>;xxx;<b>xxx;xxx</b>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
-<b>xxx2</b>;xxx;<b>xxx;xxx</b>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
-</pre>
-</blockquote>
-
-<p><?php echo get_lang('XMLMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
-
-<blockquote>
-<pre>
-&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
-&lt;Sessions&gt;
-    &lt;Users&gt;
-        &lt;User&gt;
-            &lt;Username&gt;<b>username1</b>&lt;/Username&gt;
-            &lt;Lastname&gt;xxx&lt;/Lastname&gt;
-            &lt;Firstname&gt;xxx&lt;/Firstname&gt;
-            &lt;Password&gt;xxx&lt;/Password&gt;
-            &lt;Email&gt;xxx@xx.xx&lt;/Email&gt;
-            &lt;OfficialCode&gt;xxx&lt;/OfficialCode&gt;
-            &lt;Phone&gt;xxx&lt;/Phone&gt;
-            &lt;Status&gt;student|teacher&lt;/Status&gt;
-        &lt;/User&gt;
-    &lt;/Users&gt;
-    &lt;Courses&gt;
-        &lt;Course&gt;
-            &lt;CourseCode&gt;<b>xxx</b>&lt;/CourseCode&gt;
-            &lt;CourseTeacher&gt;xxx&lt;/CourseTeacher&gt;
-            &lt;CourseLanguage&gt;xxx&lt;/CourseLanguage&gt;
-            &lt;CourseTitle&gt;xxx&lt;/CourseTitle&gt;
-            &lt;CourseDescription&gt;xxx&lt;/CourseDescription&gt;
-        &lt;/Course&gt;
-    &lt;/Courses&gt;
-    &lt;Session&gt;
-        <b>&lt;SessionName&gt;xxx&lt;/SessionName&gt;</b>
-        &lt;Coach&gt;xxx&lt;/Coach&gt;
-        <b>&lt;DateStart&gt;xxx&lt;/DateStart&gt;</b>
-        <b>&lt;DateEnd&gt;xxx&lt;/DateEnd&gt;</b>
-        &lt;User&gt;xxx&lt;/User&gt;
-        &lt;User&gt;xxx&lt;/User&gt;
-    	&lt;Course&gt;
-    		&lt;CourseCode&gt;coursecode1&lt;/CourseCode&gt;
-    		&lt;Coach&gt;coach1&lt;/Coach&gt;
-		&lt;User&gt;username1&lt;/User&gt;
-		&lt;User&gt;username2&lt;/User&gt;
-    	&lt;/Course&gt;
-    &lt;/Session&gt;
-    
-    &lt;Session&gt;
-        <b>&lt;SessionName&gt;xxx&lt;/SessionName&gt;</b>
-        &lt;Coach&gt;xxx&lt;/Coach&gt;
-        <b>&lt;DateStart&gt;xxx&lt;/DateStart&gt;</b>
-        <b>&lt;DateEnd&gt;xxx&lt;/DateEnd&gt;</b>
-        &lt;User&gt;xxx&lt;/User&gt;
-        &lt;User&gt;xxx&lt;/User&gt;
-    	&lt;Course&gt;
-    		&lt;CourseCode&gt;coursecode1&lt;/CourseCode&gt;
-    		&lt;Coach&gt;coach1&lt;/Coach&gt;
-		&lt;User&gt;username1&lt;/User&gt;
-		&lt;User&gt;username2&lt;/User&gt;
-    	&lt;/Course&gt;
-    &lt;/Session&gt;
-&lt;/Sessions&gt;
-</pre>
-</blockquote>
-</font>
-<?php
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
-Display::display_footer();
-?>
+								$email_admin = api_get_setting('emailAdministrator');
+								@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
+							}
+						} else {
+							$lastname = trim(api_utf8_decode($node_user->Lastname));
+							$firstname = trim(api_utf8_decode($node_user->Firstname));
+							$password = api_utf8_decode($node_user->Password);
+							$email = trim(api_utf8_decode($node_user->Email));
+							$official_code = trim(api_utf8_decode($node_user->OfficialCode));
+							$phone = trim(api_utf8_decode($node_user->Phone));
+							$status = trim(api_utf8_decode($node_user->Status));
+							switch ($status) {
+								case 'student' : $status = 5; break;
+								case 'teacher' : $status = 1; break;
+								default : $status = 5; $error_message .= get_lang('StudentStatusWasGivenTo').' : '.$username.'<br />';
+							}
+
+							$sql = "UPDATE $tbl_user SET
+									lastname = '".Database::escape_string($lastname)."',
+									firstname = '".Database::escape_string($firstname)."',
+									".(empty($password) ? "" : "password = '".(api_get_encrypted_password($password))."',")."
+									email = '".Database::escape_string($email)."',
+									official_code = '".Database::escape_string($official_code)."',
+									phone = '".Database::escape_string($phone)."',
+									status = '".Database::escape_string($status)."'
+								WHERE username = '".Database::escape_string($username)."'";
+
+							Database::query($sql, __FILE__, __LINE__);
+						}
+					}
+				}
+
+				// Creating  courses from <Sessions> <Courses> base node.
+				if (count($root->Courses->Course) > 0) {
+					foreach ($root->Courses->Course as $courseNode) {
+						$course_code = trim(api_utf8_decode($courseNode->CourseCode));
+						$title = trim(api_utf8_decode($courseNode->CourseTitle));
+						$description = trim(api_utf8_decode($courseNode->CourseDescription));
+						$language = api_validate_language(api_utf8_decode($courseNode->CourseLanguage));
+						$username = trim(api_utf8_decode($courseNode->CourseTeacher));
+
+						// Looking up for the teacher.
+						$sql = "SELECT user_id, lastname, firstname FROM $tbl_user WHERE username='$username'";
+						$rs = Database::query($sql, __FILE__, __LINE__);
+						list($user_id, $lastname, $firstname) = Database::fetch_array($rs);
+						global $_configuration;
+						$keys = define_course_keys($course_code, '', $_configuration['db_prefix']);
+
+						if (sizeof($keys)) {
+							$current_course_code = $keys['visual_code'];
+							$current_course_id = $keys['currentCourseId'];
+							if (empty($current_course_code)) {
+								$current_course_code = $current_course_id;
+							}
+							$current_course_db_name = $keys['currentCourseDbName'];
+							$current_course_repository = $keys['currentCourseRepository'];
+
+							// Course creation.
+							if ($current_course_id == api_strtoupper($course_code)) {
+								if (empty ($title)) {
+									$title = $keys['currentCourseCode'];
+								}
+
+								prepare_course_repository($current_course_repository, $current_course_id);
+								update_Db_course($current_course_db_name);
+								$pictures_array = fill_course_repository($current_course_repository);
+
+								//fill_Db_course($current_course_db_name, $current_course_repository, 'english', $pictures_array);
+								//register_course($current_course_id, $current_course_code, $current_course_repository, $current_course_db_name, "$lastname $firstname", $course['unit_code'], addslashes($course['FR']['title']), $language, $user_id);
+								fill_Db_course($current_course_db_name, $current_course_repository, $language, $pictures_array);
+								register_course($current_course_id, $current_course_code, $current_course_repository, $current_course_db_name, api_get_person_name($firstname, $lastname, null, null, $language), null, addslashes($title), $language, $user_id);
+
+								$sql = "INSERT INTO ".$tbl_course." SET
+										code = '".$current_course_id."',
+										db_name = '".$current_course_db_name."',
+										directory = '".$current_course_repository."',
+										course_language = '".$language."',
+										title = '".$title."',
+										description = '".lang2db($description)."',
+										category_code = '',
+										visibility = '".$defaultVisibilityForANewCourse."',
+										show_score = '',
+										disk_quota = NULL,
+										creation_date = now(),
+										expiration_date = NULL,
+										last_edit = now(),
+										last_visit = NULL,
+										tutor_name = '".api_get_person_name($firstname, $lastname, null, null, $language)."',
+										visual_code = '".$current_course_code."'";
+
+								Database::query($sql, __FILE__, __LINE__);
+
+								$sql = "INSERT INTO ".$tbl_course_user." SET
+										course_code = '".$current_course_id."',
+										user_id = '".$user_id."',
+										status = '1',
+										role = '".lang2db('Professor')."',
+										tutor_id='1',
+										sort='". ($sort + 1)."',
+										user_course_cat='0'";
+
+								Database::query($sql, __FILE__, __LINE__);
+							}
+						}
+					}
+				}
+
+				// Creating sessions from <Sessions> base node.
+				if (count($root->Session) > 0) {
+					foreach ($root->Session as $node_session) {
+
+						$course_counter = 0;
+						$user_counter = 0;
+
+						$session_name = trim(api_utf8_decode($node_session->SessionName));
+						$coach = UserManager::purify_username(api_utf8_decode($node_session->Coach), $purification_option_for_usernames);
+
+						if (!empty($coach)) {
+							$coach_id = UserManager::get_user_id_from_username($coach);
+							if ($coach_id === false) {
+								$error_message .= get_lang('UserDoesNotExist').' : '.$coach.'<br />';
+								// Forcing the coach id if user does not exist.
+								$coach_id = api_get_user_id();
+							}
+						} else {
+							// Forcing the coach id.
+							$coach_id = api_get_user_id();
+						}
+
+						$date_start = trim(api_utf8_decode($node_session->DateStart)); // Just in case - encoding conversion.
+
+						if (!empty($date_start)) {
+							list($year_start, $month_start, $day_start) = explode('-', $date_start);
+							if(empty($year_start) || empty($month_start) || empty($day_start)) {
+								$error_message .= get_lang('WrongDate').' : '.$date_start.'<br />';
+								break;
+							} else {
+								$time_start = mktime(0, 0, 0, $month_start, $day_start, $year_start);
+							}
+
+							$date_end = trim(api_utf8_decode($node_session->DateEnd));
+							if (!empty($date_start)) {
+								list($year_end, $month_end, $day_end) = explode('-', $date_end);
+								if (empty($year_end) || empty($month_end) || empty($day_end)) {
+									$error_message .= get_lang('WrongDate').' : '.$date_end.'<br />';
+									break;
+								} else {
+									$time_end = mktime(0, 0, 0, $month_end, $day_end, $year_end);
+								}
+							}
+							if ($time_end - $time_start < 0) {
+								$error_message .= get_lang('StartDateShouldBeBeforeEndDate').' : '.$date_end.'<br />';
+							}
+						}
+
+						if (!$updatesession) {
+							// Always create a session.
+							$unique_name = false; // This MUST be initializead.
+							$i = 0;
+							// Change session name, verify that session doesn't exist.
+							while (!$unique_name) {
+								if ($i > 1) {
+									$suffix = ' - '.$i;
+								}
+								$sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.Database::escape_string($session_name.$suffix).'"';
+								$rs = Database::query($sql, __FILE__, __LINE__);
+								if (Database::result($rs, 0, 0)) {
+									$i++;
+								} else {
+									$unique_name = true;
+									$session_name .= $suffix;
+								}
+							}
+							// Creating the session.
+							$sql_session = "INSERT IGNORE INTO $tbl_session SET
+									name = '".Database::escape_string($session_name)."',
+									id_coach = '$coach_id',
+									date_start = '$date_start',
+									date_end = '$date_end',
+									session_admin_id=".intval($_user['user_id']);
+							$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+							$session_id = Database::get_last_insert_id();
+							$session_counter++;
+
+						} else {
+							// Update the session if it is needed.
+							$my_session_result = SessionManager::get_session_by_name($session_name);
+							if ($my_session_result === false) {
+								// Creating the session.
+								$sql_session = "INSERT IGNORE INTO $tbl_session SET
+										name = '".Database::escape_string($session_name)."',
+										id_coach = '$coach_id',
+										date_start = '$date_start',
+										date_end = '$date_end',
+										session_admin_id=".intval($_user['user_id']);
+								$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+								$session_id = Database::get_last_insert_id();
+								$session_counter++;
+							} else {
+								// if the session already exists - update it.
+								$sql_session = "UPDATE $tbl_session SET
+										id_coach = '$coach_id',
+										date_start = '$date_start',
+										date_end = '$date_end'
+									WHERE name = '$session_name'";
+								$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+								$session_id = Database::query("SELECT id FROM $tbl_session WHERE name='$session_name'", __FILE__, __LINE__);
+								list($session_id) = Database::fetch_array($session_id);
+								Database::query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'", __FILE__, __LINE__);
+								Database::query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'", __FILE__, __LINE__);
+								Database::query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'", __FILE__, __LINE__);
+							}
+						}
+
+						// Associate the session with access_url.
+						global $_configuration;
+						require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
+						if ($_configuration['multiple_access_urls']) {
+							$tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+							$access_url_id = api_get_current_access_url_id();
+							UrlManager::add_session_to_url($session_id, $access_url_id);
+						} else {
+							// We fill by default the access_url_rel_session table.
+							UrlManager::add_session_to_url($session_id, 1);
+						}
+
+						// Adding users to the new session.
+						foreach ($node_session->User as $node_user) {
+							$username = UserManager::purify_username(api_utf8_decode($node_user), $purification_option_for_usernames);
+							$user_id = UserManager::get_user_id_from_username($username);
+							if ($user_id !== false) {
+								$sql = "INSERT IGNORE INTO $tbl_session_user SET
+										id_user='$user_id',
+										id_session = '$session_id'";
+								$rs_user = Database::query($sql, __FILE__, __LINE__);
+								$user_counter++;
+							}
+						}
+
+						// Adding courses to a session.
+						foreach ($node_session->Course as $node_course) {
+							$course_code = Database::escape_string(trim(api_utf8_decode($node_course->CourseCode)));
+							// Verify that the course pointed by the course code node exists.
+							if (CourseManager::course_exists($course_code)) {
+								// If the course exists we continue.
+								$course_info = CourseManager::get_course_information($course_code);
+								// Searching the coach.
+								$coach = UserManager::purify_username(api_utf8_decode($node_course->Coach), $purification_option_for_usernames);
+								if (!empty($coach)) {
+									$coach_id = UserManager::get_user_id_from_username($coach);
+									if ($coach_id === false) {
+										$error_message .= get_lang('UserDoesNotExist').' : '.$coach.'<br />';
+										$coach_id = '';
+									}
+								} else {
+									$coach_id = '';
+								}
+								$session_course_relation = SessionManager::relation_session_course_exist($session_id, $course_code);
+								if (!$session_course_relation) {
+									$sql_course = "INSERT INTO $tbl_session_course SET
+											course_code = '$course_code',
+											id_coach='$coach_id',
+											id_session='$session_id'";
+									$rs_course = Database::query($sql_course, __FILE__, __LINE__);
+								}
+								if (Database::affected_rows()) {
+									$course_counter++;
+									$users_in_course_counter = 0;
+									foreach ($node_course->User as $node_user) {
+										$username = UserManager::purify_username(api_utf8_decode($node_user), $purification_option_for_usernames);
+										$user_id = UserManager::get_user_id_from_username($username);
+										if ($user_id !== false) {
+											// Adding to session_rel_user table.
+											$sql = "INSERT IGNORE INTO $tbl_session_user SET
+													id_user='$user_id',
+													id_session = '$session_id'";
+											$rs_user = Database::query($sql, __FILE__, __LINE__);
+											$user_counter++;
+											// Adding to session_rel_user_rel_course table.
+											$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
+													id_user='$user_id',
+													course_code='$course_code',
+													id_session = '$session_id'";
+											$rs_users = Database::query($sql, __FILE__, __LINE__);
+											$users_in_course_counter++;
+										} else {
+											$error_message .= get_lang('UserDoesNotExist').' : '.$username.'<br />';
+										}
+									}
+									$update_session_course = "UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='$course_code'";
+									Database::query($update_session_course, __FILE__, __LINE__);
+									$inserted_in_course[$course_code] = $course_info['title'];
+								}
+							}
+
+							if (CourseManager::course_exists($course_code, true)) {
+								// If the course exists we continue.
+								// Also subscribe to virtual courses through check on visual code.
+								$list = CourseManager :: get_courses_info_from_visual_code($course_code);
+								foreach ($list as $vcourse) {
+									if ($vcourse['code'] == $course_code) {
+										// Ignore, this has already been inserted.
+									} else {
+										$coach = UserManager::purify_username(api_utf8_decode($node_course->Coach), $purification_option_for_usernames);
+										if (!empty($coach)) {
+											$coach_id = UserManager::get_user_id_from_username($coach);
+											if ($user_id === false) {
+												$error_message .= get_lang('UserDoesNotExist').' : '.$coach.'<br />';
+												$coach_id = '';
+											}
+										} else {
+											$coach_id = '';
+										}
+
+										$sql_course = "INSERT INTO $tbl_session_course SET
+												course_code = '".$vcourse['code']."',
+												id_coach='$coach_id',
+												id_session='$session_id'";
+										$rs_course = Database::query($sql_course, __FILE__, __LINE__);
+										if (Database::affected_rows()) {
+											$course_counter++;
+											$users_in_course_counter = 0;
+											foreach ($node_course->User as $node_user) {
+												$username = UserManager::purify_username(api_utf8_decode($node_user), $purification_option_for_usernames);
+												$user_id = UserManager::get_user_id_from_username($username);
+												if ($user_id !== false) {
+													$sql = "INSERT IGNORE INTO $tbl_session_user SET
+															id_user='$user_id',
+															id_session = '$session_id'";
+													$rs_user = Database::query($sql, __FILE__, __LINE__);
+													if (Database::affected_rows()) {
+														$user_counter++;
+													}
+													$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
+															id_user='$user_id',
+															course_code='".$vcourse['code']."',
+															id_session = '$session_id'";
+													$rs_users = Database::query($sql, __FILE__, __LINE__);
+													if (Database::affected_rows()) {
+														$users_in_course_counter++;
+													}
+												} else {
+													$error_message .= get_lang('UserDoesNotExist').' : '.$username.'<br />';
+												}
+											}
+											Database::query("UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='$course_code'",__FILE__,__LINE__);
+										}
+									}
+									$inserted_in_course[$vcourse['code']] = $vcourse['title'];
+								}
+							} else {
+								// Tthe course does not exist.
+								$error_message .= get_lang('CourseDoesNotExist').' : '.$course_code.'<br />';
+							}
+						}
+						Database::query("UPDATE $tbl_session SET nbr_users='$user_counter', nbr_courses='$course_counter' WHERE id='$session_id'", __FILE__, __LINE__);
+					}
+
+				}
+				if (empty($root->Users->User) && empty($root->Courses->Course) && empty($root->Session)) {
+					$error_message = get_lang('NoNeededData');
+				}
+			} else {
+				$error_message .= get_lang('XMLNotValid');
+			}
+		} else {
+
+			/////////////////////
+			// CSV /////////////
+			///////////////////
+
+			$content = file($_FILES['import_file']['tmp_name']);
+			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_eregi_replace('[^a-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;
+						}
+					}
+				}
+				// looping the sessions
+				foreach ($sessions as $enreg) {
+					$user_counter = 0;
+					$course_counter = 0;
+
+					$session_name = $enreg['SessionName'];
+					$date_start = $enreg['DateStart'];
+					$date_end = $enreg['DateEnd'];
+
+					// searching a coach
+					if (!empty($enreg['Coach'])) {
+						$coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
+						if ($coach_id === false) {
+							// If the coach-user does not exist - I'm the coach.
+							$coach_id = api_get_user_id();
+						}
+					} else {
+						$coach_id = api_get_user_id();
+					}
+
+					if (!$updatesession) {
+						// Always create a session.
+						$unique_name = false; // This MUST be initializead.
+						$i = 0;
+						// Change session name, verify that session doesn't exist
+						while (!$unique_name) {
+							if ($i > 1) {
+								$suffix = ' - '.$i;
+							}
+							$sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.Database::escape_string($session_name.$suffix).'"';
+							$rs = Database::query($sql, __FILE__, __LINE__);
+
+							if (Database::result($rs, 0, 0)) {
+								$i++;
+							} else {
+								$unique_name = true;
+								$session_name .= $suffix;
+							}
+						}
+
+						// Creating the session.
+						$sql_session = "INSERT IGNORE INTO $tbl_session SET
+								name = '".Database::escape_string($session_name)."',
+								id_coach = '$coach_id',
+								date_start = '$date_start',
+								date_end = '$date_end',
+								session_admin_id=".intval($_user['user_id']);
+						$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+						$session_id = Database::get_last_insert_id();
+						$session_counter++;
+					} else {
+						$my_session_result = SessionManager::get_session_by_name($session_name);
+						if ($my_session_result === false) {
+
+							// Creating a session.
+							$sql_session = "INSERT IGNORE INTO $tbl_session SET
+									name = '$session_name',
+									id_coach = '$coach_id',
+									date_start = '$date_start',
+									date_end = '$date_end'";
+							$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+							// We get the last insert id.
+							$my_session_result = SessionManager::get_session_by_name($session_name);
+							$session_id = $my_session_result['id'];
+							//echo '<br>';
+						} else {
+							// The session already exists, update it then.
+							$sql_session = "UPDATE $tbl_session SET
+									id_coach = '$coach_id',
+									date_start = '$date_start',
+									date_end = '$date_end'
+								WHERE name = '$session_name'";
+							$rs_session = Database::query($sql_session, __FILE__, __LINE__);
+							$session_id = Database::query("SELECT id FROM $tbl_session WHERE name='$session_name'", __FILE__, __LINE__);
+							list($session_id) = Database::fetch_array($session_id);
+							Database::query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'", __FILE__, __LINE__);
+							Database::query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'", __FILE__, __LINE__);
+							Database::query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'", __FILE__, __LINE__);
+						}
+						$session_counter++;
+					}
+
+					$users = explode('|', $enreg['Users']);
+
+					// Adding the relationship "Session - User".
+					if (is_array($users)) {
+						foreach ($users as $user) {
+							$user_id = UserManager::get_user_id_from_username($user);
+							if ($user_id !== false) {
+								// Insert new users.
+								$sql = "INSERT IGNORE INTO $tbl_session_user SET
+										id_user='$user_id',
+										id_session = '$session_id'";
+								$rs_user = Database::query($sql, __FILE__, __LINE__);
+								$user_counter++;
+							}
+						}
+					}
+
+					$courses = explode('|', $enreg['Courses']);
+
+					foreach ($courses as $course) {
+						$course_code = api_strtoupper(api_substr($course, 0, api_strpos($course, '[')));
+						if (CourseManager::course_exists($course_code)) {
+
+							// If the course exists we continue
+							$course_info = CourseManager::get_course_information($course_code);
+
+							$coach = api_strstr($course, '[');
+							$coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
+
+							if (!empty($coach)) {
+								$coach_id = UserManager::get_user_id_from_username($coach);
+								if ($coach_id === false) {
+									$coach_id = '';
+								}
+							} else {
+								$coach = '';
+							}
+							// Adding the course to a session
+							$sql_course = "INSERT IGNORE INTO $tbl_session_course SET
+									course_code = '$course_code',
+									id_coach='$coach_id',
+									id_session='$session_id'";
+							$rs_course = Database::query($sql_course, __FILE__, __LINE__);
+							$course_counter++;
+
+							$users = api_substr($course, api_strpos($course, '[', 1) + 1 , api_strpos($course, ']', 1));
+							$users = explode('|', $enreg['Users']);
+							$users_in_course_counter = 0;
+
+							// Adding the relationship "Session - Course - User".
+							foreach ($users as $user) {
+								$user_id = UserManager::get_user_id_from_username($user);
+								if ($user_id !== false) {
+									$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
+											id_user='$user_id',
+											course_code='$course_code',
+											id_session = '$session_id'";
+									$rs_users = Database::query($sql, __FILE__, __LINE__);
+									$users_in_course_counter++;
+								} else {
+									$error_message .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
+								}
+							}
+							Database::query("UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='$course_code'", __FILE__, __LINE__);
+
+							$course_info = CourseManager::get_course_information($course_code);
+							$inserted_in_course[$course_code] = $course_info['title'];
+						} else {
+							// TODO: We should create the course as in the XML import.
+						}
+
+						if (CourseManager::course_exists($course_code, true)) {
+							$list = CourseManager :: get_courses_info_from_visual_code($course_code);
+							foreach ($list as $vcourse) {
+								if ($vcourse['code'] == $course_code) {
+									// Ignore, this has already been inserted.
+								} else {
+									$coach = api_strstr($course, '[');
+									$coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
+
+									if (!empty($coach)) {
+										$sql_coach = "SELECT user_id FROM $tbl_user WHERE username='$coach'";
+										$rs_coach = Database::query($sql_coach,__FILE__,__LINE__);
+										list($coach) = (Database::fetch_array($rs_coach));
+									} else {
+										$coach = '';
+									}
+									// Adding the relationship "Session - Course".
+									$sql_course = "INSERT IGNORE INTO $tbl_session_course SET
+											course_code = '".$vcourse['code']."',
+											id_coach='$coach',
+											id_session='$session_id'";
+
+									$rs_course = Database::query($sql_course, __FILE__, __LINE__);
+									if (Database::affected_rows()) {
+										$course_counter++;
+										$users = api_substr($course , api_strpos($course,'[', 1) + 1, api_strpos($course,']', 1));
+										$users = explode('|', $enreg['Users']);
+										$users_in_course_counter = 0;
+										foreach ($users as $user) {
+											$sqlUser = "SELECT user_id FROM $tbl_user WHERE username='".$user."'";
+											$rs_user = Database::query($sqlUser);
+											list($user_id) = (Database::fetch_array($rs_user));
+											$sql = "INSERT INTO $tbl_session_course_user SET
+													id_user='$user_id',
+													course_code='".$vcourse['code']."',
+													id_session = '$session_id'";
+											$rs_users = Database::query($sql, __FILE__, __LINE__);
+											if (Database::affected_rows()) {
+												$users_in_course_counter++;
+											}
+										}
+										Database::query("UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='".$vcourse['code']."'", __FILE__, __LINE__);
+									}
+								}
+							}
+							$inserted_in_course[$vcourse['code']] = $vcourse['title'];
+						}
+					}
+
+					$sql_update_users = "UPDATE $tbl_session SET nbr_users='$user_counter', nbr_courses='$course_counter' WHERE id='$session_id'";
+					Database::query($sql_update_users, __FILE__, __LINE__);
+				}
+			}
+		}
+		if (!empty($error_message)) {
+			$error_message = get_lang('ButProblemsOccured').' :<br />'.$error_message;
+		}
+
+		if (count($inserted_in_course) > 1) {
+			$warn = get_lang('SeveralCoursesSubscribedToSessionBecauseOfSameVisualCode').': ';
+			foreach ($inserted_in_course as $code => $title) {
+				$warn .= ' '.$title.' ('.$code.'),';
+			}
+			$warn = substr($warn, 0, -1);
+		}
+		if ($session_counter == 1) {
+			header('Location: resume_session.php?id_session='.$session_id.'&warn='.urlencode($warn));
+			exit;
+		} else {
+			header('Location: session_list.php?action=show_message&message='.urlencode(get_lang('FileImported').' '.$error_message).'&warn='.urlencode($warn));
+			exit;
+		}
+	} else {
+		$error_message = get_lang('NoInputFile');
+	}
+}
+
+// display the header
+Display::display_header($tool_name);
+
+// display the tool title
+// api_display_tool_title($tool_name);
+
+if (count($inserted_in_course) > 1) {
+	$msg = get_lang('SeveralCoursesSubscribedToSessionBecauseOfSameVisualCode').': ';
+	foreach ($inserted_in_course as $code => $title) {
+		$msg .= ' '.$title.' ('.$title.'),';
+	}
+	$msg = substr($msg, 0, -1);
+	Display::display_warning_message($msg);
+}
+
+/*
+
+ update session by default is true
+ <tr>
+  <td nowrap="nowrap" valign="top"><?php echo get_lang('UpdateSession'); ?> :</td>
+  <td>
+	<input class="checkbox" type="checkbox" name="updatesession" id="updatesession" value="true" />
+  </td>
+</tr>
+
+
+  */
+?>
+
+<form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" style="margin: 0px;">
+<input type="hidden" name="formSent" value="1">
+<div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
+<table border="0" cellpadding="5" cellspacing="0">
+
+<?php
+if (!empty($error_message)) {
+?>
+<tr>
+  <td colspan="2">
+<?php
+	Display::display_normal_message($error_message, false);
+?>
+  </td>
+</tr>
+<?php
+}
+?>
+<tr>
+  <td nowrap="nowrap"><?php echo get_lang('ImportFileLocation'); ?> :</td>
+  <td><input type="file" name="import_file" size="30"></td>
+</tr>
+<tr>
+  <td nowrap="nowrap" valign="top"><?php echo get_lang('FileType'); ?> :</td>
+  <td>
+	<input class="checkbox" type="radio" name="file_type" id="file_type_xml" value="xml" checked="checked" /> <label for="file_type_xml">XML</label> (<a href="example_session.xml" target="_blank"><?php echo get_lang('ExampleXMLFile'); ?></a>)<br>
+	<input class="checkbox" type="radio" name="file_type" id="file_type_csv"  value="csv" <?php if ($form_sent && $file_type == 'csv') echo 'checked="checked"'; ?>> <label for="file_type_csv">CSV</label> (<a href="example_session.csv" target="_blank"><?php echo get_lang('ExampleCSVFile'); ?></a>)<br>
+  </td>
+</tr>
+<tr>
+  <td nowrap="nowrap" valign="top"><?php echo get_lang('SendMailToUsers'); ?> :</td>
+  <td>
+	<input class="checkbox" type="checkbox" name="sendMail" id="sendMail" value="true" />
+  </td>
+</tr>
+
+
+
+
+<tr>
+  <td>&nbsp;</td>
+  <td>
+  <button class="save" type="submit" name="name" value="<?php echo get_lang('ImportSession'); ?>"><?php echo get_lang('ImportSession'); ?></button>
+  </td>
+</tr>
+</table>
+</form>
+
+<font color="gray">
+<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
+
+<blockquote>
+<pre>
+<b>SessionName</b>;Coach;<b>DateStart</b>;<b>DateEnd</b>;Users;Courses
+<b>xxx1</b>;xxx;<b>xxx;xxx</b>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
+<b>xxx2</b>;xxx;<b>xxx;xxx</b>;username1|username2;course1[coach1][username1,username2,...]|course2[coach1][username1,username2,...]
+</pre>
+</blockquote>
+
+<p><?php echo get_lang('XMLMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
+
+<blockquote>
+<pre>
+&lt;?xml version=&quot;1.0&quot; encoding=&quot;<?php echo api_refine_encoding_id(api_get_system_encoding()); ?>&quot;?&gt;
+&lt;Sessions&gt;
+    &lt;Users&gt;
+        &lt;User&gt;
+            &lt;Username&gt;<b>username1</b>&lt;/Username&gt;
+            &lt;Lastname&gt;xxx&lt;/Lastname&gt;
+            &lt;Firstname&gt;xxx&lt;/Firstname&gt;
+            &lt;Password&gt;xxx&lt;/Password&gt;
+            &lt;Email&gt;xxx@xx.xx&lt;/Email&gt;
+            &lt;OfficialCode&gt;xxx&lt;/OfficialCode&gt;
+            &lt;Phone&gt;xxx&lt;/Phone&gt;
+            &lt;Status&gt;student|teacher&lt;/Status&gt;
+        &lt;/User&gt;
+    &lt;/Users&gt;
+    &lt;Courses&gt;
+        &lt;Course&gt;
+            &lt;CourseCode&gt;<b>xxx</b>&lt;/CourseCode&gt;
+            &lt;CourseTeacher&gt;xxx&lt;/CourseTeacher&gt;
+            &lt;CourseLanguage&gt;xxx&lt;/CourseLanguage&gt;
+            &lt;CourseTitle&gt;xxx&lt;/CourseTitle&gt;
+            &lt;CourseDescription&gt;xxx&lt;/CourseDescription&gt;
+        &lt;/Course&gt;
+    &lt;/Courses&gt;
+    &lt;Session&gt;
+        <b>&lt;SessionName&gt;xxx&lt;/SessionName&gt;</b>
+        &lt;Coach&gt;xxx&lt;/Coach&gt;
+        <b>&lt;DateStart&gt;xxx&lt;/DateStart&gt;</b>
+        <b>&lt;DateEnd&gt;xxx&lt;/DateEnd&gt;</b>
+        &lt;User&gt;xxx&lt;/User&gt;
+        &lt;User&gt;xxx&lt;/User&gt;
+    	&lt;Course&gt;
+    		&lt;CourseCode&gt;coursecode1&lt;/CourseCode&gt;
+    		&lt;Coach&gt;coach1&lt;/Coach&gt;
+		&lt;User&gt;username1&lt;/User&gt;
+		&lt;User&gt;username2&lt;/User&gt;
+    	&lt;/Course&gt;
+    &lt;/Session&gt;
+
+    &lt;Session&gt;
+        <b>&lt;SessionName&gt;xxx&lt;/SessionName&gt;</b>
+        &lt;Coach&gt;xxx&lt;/Coach&gt;
+        <b>&lt;DateStart&gt;xxx&lt;/DateStart&gt;</b>
+        <b>&lt;DateEnd&gt;xxx&lt;/DateEnd&gt;</b>
+        &lt;User&gt;xxx&lt;/User&gt;
+        &lt;User&gt;xxx&lt;/User&gt;
+    	&lt;Course&gt;
+    		&lt;CourseCode&gt;coursecode1&lt;/CourseCode&gt;
+    		&lt;Coach&gt;coach1&lt;/Coach&gt;
+		&lt;User&gt;username1&lt;/User&gt;
+		&lt;User&gt;username2&lt;/User&gt;
+    	&lt;/Course&gt;
+    &lt;/Session&gt;
+&lt;/Sessions&gt;
+</pre>
+</blockquote>
+</font>
+<?php
+/*
+==============================================================================
+		FOOTER
+==============================================================================
+*/
+Display::display_footer();

+ 53 - 52
main/admin/session_list.php

@@ -7,6 +7,7 @@ include('../inc/global.inc.php');
 require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
 require_once (api_get_path(LIBRARY_PATH).'sessionmanager.lib.php');
 
+$this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script(true);
 
 $htmlHeadXtra[] = '<script language="javascript">
@@ -66,10 +67,10 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
 	$form->display();
 
 } else {
-	
+
 	$limit=20;
 	$from=$page * $limit;
-	
+
 	//if user is crfp admin only list its sessions
 	if(!api_is_platform_admin()) {
 		$where = 'WHERE session_admin_id='.intval($_user['user_id']);
@@ -78,13 +79,13 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
 	else {
 		$where .= (empty($_REQUEST['keyword']) ? " " : " WHERE name LIKE '%".addslashes($_REQUEST['keyword'])."%'");
 	}
-	
+
 	if(trim($where) == ''){
 		$and=" WHERE id_coach=user_id";
 	} else {
 		$and=" AND id_coach=user_id";
 	}
-	
+
 	if(isset($_REQUEST['active']) && !isset($_REQUEST['inactive']) ){
 		$and .= ' AND ( (session.date_start <= CURDATE() AND session.date_end >= CURDATE()) OR session.date_start="0000-00-00" ) ';
 		$cond_url = '&amp;active='.Security::remove_XSS($_REQUEST['active']);
@@ -93,35 +94,35 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
 		$and .= ' AND ( (session.date_start > CURDATE() OR session.date_end < CURDATE()) AND session.date_start<>"0000-00-00" ) ';
 		$cond_url = '&amp;inactive='.Security::remove_XSS($_REQUEST['inactive']);
 	}
-	
-	$query= "SELECT id,name,nbr_courses,date_start,date_end, firstname, lastname 
+
+	$query= "SELECT id,name,nbr_courses,date_start,date_end, firstname, lastname
 			FROM $tbl_session, $tbl_user
 			$where
 			$and
-			ORDER BY $sort 
+			ORDER BY $sort
 			LIMIT $from,".($limit+1);
-			
+
 	//query which allows me to get a record without taking into account the page
 	$query_rows= "SELECT count(*) as total_rows
 				FROM $tbl_session, $tbl_user
 				$where
 				$and
 				ORDER BY $sort";
-				
+
 
 	//filtering the session list by access_url
 	if ($_configuration['multiple_access_urls']==true){
-		$table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);	
+		$table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 		$access_url_id = api_get_current_access_url_id();
 		if ($access_url_id != -1) {
 			$and.= " AND access_url_id = $access_url_id AND $table_access_url_rel_session.session_id = $tbl_session.id";
-			$query= "SELECT id,name,nbr_courses,date_start,date_end, firstname, lastname 
+			$query= "SELECT id,name,nbr_courses,date_start,date_end, firstname, lastname
 				FROM $tbl_session, $tbl_user, $table_access_url_rel_session
 				$where
 				$and
-				ORDER BY $sort 
+				ORDER BY $sort
 				LIMIT $from,".($limit+1);
-				
+
 			$query_rows= "SELECT count(*) as total_rows
 				FROM $tbl_session, $tbl_user,$table_access_url_rel_session
 				$where
@@ -129,18 +130,18 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
 				ORDER BY $sort";
 		}
 	}
-	
 
-	
+
+
 	$result_rows = api_sql_query($query_rows,__FILE__,__LINE__);
 	$recorset = Database::fetch_array($result_rows);
 	$num = $recorset['total_rows'];
-	
-	$result=api_sql_query($query,__FILE__,__LINE__);	
-	$Sessions=api_store_result($result);	
-	$nbr_results=sizeof($Sessions);	
-	$tool_name = get_lang('SessionList');	
-	Display::display_header($tool_name);	
+
+	$result=api_sql_query($query,__FILE__,__LINE__);
+	$Sessions=api_store_result($result);
+	$nbr_results=sizeof($Sessions);
+	$tool_name = get_lang('SessionList');
+	Display::display_header($tool_name);
 	//api_display_tool_title($tool_name);
 
     if (!empty($_GET['warn'])) {
@@ -149,13 +150,13 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
     if(isset($_GET['action'])) {
         Display::display_normal_message(stripslashes($_GET['message']),false);
     }
-	?>	
-	<div class="actions">		
+	?>
+	<div class="actions">
 	<?php
 
 	echo '<div style="float:right;">
-		<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_add.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddSession')).get_lang('AddSession').'</a>									
-	  </div>'; 
+		<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_add.php">'.Display::return_icon('view_more_stats.gif',get_lang('AddSession')).get_lang('AddSession').'</a>
+	  </div>';
 	?>
 	<form method="POST" action="session_list.php">
 		<input type="text" name="keyword" value="<?php echo Security::remove_XSS($_GET['keyword']); ?>"/>
@@ -164,7 +165,7 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
 		</form>
 	<form method="post" action="<?php echo api_get_self(); ?>?action=delete&sort=<?php echo $sort; ?>" onsubmit="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;">
 	 </div><br />
-	
+
 	<div align="left">
 	<?php
 	if(count($Sessions)==0 && isset($_POST['keyword'])) {
@@ -173,25 +174,25 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
 	} else {
 		if($num>$limit){
 			if($page) {
-			?>	
-			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Previous'); ?></a>	
+			?>
+			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Previous'); ?></a>
 			<?php
 			} else {
 				echo get_lang('Previous');
 			}
-			?>	
-			|	
+			?>
+			|
 			<?php
 			if($nbr_results > $limit) {
-				?>	
-				<a href="<?php echo api_get_self(); ?>?page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Next'); ?></a>	
+				?>
+				<a href="<?php echo api_get_self(); ?>?page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Next'); ?></a>
 				<?php
 			} else {
 				echo get_lang('Next');
 			}
 		}
 		?>
-	</div>	
+	</div>
 		<br />
 		<table class="data_table" width="100%">
 		<tr>
@@ -203,7 +204,7 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
 		  <th><a href="<?php echo api_get_self(); ?>?sort=coach_name"><?php echo get_lang('Coach'); ?></a></th>
 		  <th><?php echo get_lang('Actions'); ?></th>
 		</tr>
-	
+
 		<?php
 		$i=0;
 		$x=0;
@@ -212,12 +213,12 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
 				break;
 			}
 			$sql = 'SELECT COUNT(course_code) FROM '.$tbl_session_rel_course.' WHERE id_session='.intval($enreg['id']);
-	
+
 		  	$rs = api_sql_query($sql, __FILE__, __LINE__);
 		  	list($nb_courses) = Database::fetch_array($rs);
-	
+
 		?>
-	
+
 		<tr class="<?php echo $i?'row_odd':'row_even'; ?>">
 		  <td><input type="checkbox" id="idChecked_<?php echo $x; ?>" name="idChecked[]" value="<?php echo $enreg['id']; ?>"></td>
 	      <td><a href="resume_session.php?id_session=<?php echo $enreg['id']; ?>"><?php echo api_htmlentities($enreg['name'],ENT_QUOTES,$charset); ?></a></td>
@@ -232,31 +233,31 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
 			<a href="<?php echo api_get_self(); ?>?sort=<?php echo $sort; ?>&action=delete&idChecked=<?php echo $enreg['id']; ?>" onclick="javascript:if(!confirm('<?php echo get_lang('ConfirmYourChoice'); ?>')) return false;"><?php Display::display_icon('delete.gif', get_lang('Delete')); ?></a>
 		  </td>
 		</tr>
-	
+
 		<?php
 			$i=$i ? 0 : 1;
 			$x++;
 		}
-	
+
 		unset($Sessions);
-	
+
 		?>
-	
+
 		</table>
-	
+
 		<br />
-	
+
 		<div align="left">
-	
+
 		<?php
 
 		if($num>$limit) {
 		if($page)
 			{
 			?>
-		
+
 			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page-1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Previous'); ?></a>
-		
+
 			<?php
 			}
 			else
@@ -264,16 +265,16 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
 				echo get_lang('Previous');
 			}
 			?>
-		
+
 			|
-		
+
 			<?php
 			if($nbr_results > $limit)
 			{
 			?>
-		
+
 			<a href="<?php echo api_get_self(); ?>?page=<?php echo $page+1; ?>&sort=<?php echo $sort; ?>&keyword=<?php echo $_REQUEST['keyword']; ?><?php echo @$cond_url; ?>"><?php echo get_lang('Next'); ?></a>
-		
+
 			<?php
 			}
 			else
@@ -282,9 +283,9 @@ if (isset ($_GET['search']) && $_GET['search'] == 'advanced') {
 			}
 		}
 		?>
-	
+
 		</div>
-	
+
 		<br />
 		<a href="javascript: void(0);" onclick="javascript: selectAll('idChecked',<?php echo $x; ?>,'true');return false;"><?php echo get_lang('SelectAll') ?></a>&nbsp;-&nbsp;
 		<a href="javascript: void(0);" onclick="javascript: selectAll('idChecked',<?php echo $x; ?>,'false');return false;"><?php echo get_lang('UnSelectAll') ?></a>

+ 163 - 163
main/admin/settings.php

@@ -87,11 +87,11 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 	$renderer->setHeaderTemplate('<div class="sectiontitle">{header}</div>'."\n");
 	$renderer->setElementTemplate('<div class="sectioncomment">{label}</div>'."\n".'<div class="sectionvalue">{element}</div>'."\n");
 	$my_category = mysql_real_escape_string($_GET['category']);
-	
+
 	$sqlcountsettings = "SELECT COUNT(*) FROM $table_settings_current WHERE category='".$my_category."' AND type<>'checkbox'";
 	$resultcountsettings = api_sql_query($sqlcountsettings, __FILE__, __LINE__);
 	$countsetting = mysql_fetch_array($resultcountsettings);
-	 
+
 	if ($_configuration['access_url']==1)
 	{
 		$settings = api_get_settings($my_category,'group',$_configuration['access_url']);
@@ -102,9 +102,9 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 		if ($url_info['active']==1)
 		{
 			//the default settings of Dokeos
-			$settings = api_get_settings($my_category,'group',1,0);		
-			//the settings that are changeable from a particular site 
-			$settings_by_access = api_get_settings($my_category,'group',$_configuration['access_url'],1);			
+			$settings = api_get_settings($my_category,'group',1,0);
+			//the settings that are changeable from a particular site
+			$settings_by_access = api_get_settings($my_category,'group',$_configuration['access_url'],1);
 			//echo '<pre>';
 			//print_r($settings_by_access);
 			$settings_by_access_list=array();
@@ -121,7 +121,7 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 					$settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]  = $row;
 				else
 					$settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]  = array();
-			}	
+			}
 		}
 	}
 
@@ -130,27 +130,27 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 	//$resultsettings = api_sql_query($sqlsettings, __FILE__, __LINE__);
 	//while ($row = mysql_fetch_array($resultsettings))
 	$default_values = array();
-	foreach($settings as $row) {			
+	foreach($settings as $row) {
 		if ($row['variable'] == 'search_enabled') { continue; }
 		$anchor_name = $row['variable'].(!empty($row['subkey']) ? '_'.$row['subkey'] : '');
 		$form->addElement('html',"\n<a name=\"$anchor_name\"></a>\n");
 
-		($countsetting['0']%10) < 5 ?$b=$countsetting['0']-10:$b=$countsetting['0'];		
+		($countsetting['0']%10) < 5 ?$b=$countsetting['0']-10:$b=$countsetting['0'];
 		if ($i % 10 == 0 and $i<$b){
 			if ($_GET['category'] <> "Languages"){
 				$form->addElement('html','<div align="right">');
 				$form->addElement('style_submit_button', null,get_lang('SaveSettings'), 'class="save"');
 				$form->addElement('html','</div>');
-			}		
+			}
 		}
 		$i++;
 
 		$form->addElement('header', null, get_lang($row['title']));
-		
+
 		if ($row['access_url_changeable']=='1' && $_configuration['multiple_access_urls']==true) {
-			$form->addElement('html', '<div style="float:right;">'.Display::return_icon('shared_setting.png',get_lang('SharedSettingIconComment')).'</div>');						
-		}	
-		
+			$form->addElement('html', '<div style="float:right;">'.Display::return_icon('shared_setting.png',get_lang('SharedSettingIconComment')).'</div>');
+		}
+
 		$hideme=array();
 		$hide_element=false;
 		if ($_configuration['access_url']!=1)
@@ -163,35 +163,35 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 			}
 			elseif($url_info['active']==1)
 			{
-				// we show the elements 
+				// we show the elements
 				if (empty($row['variable']))
 					$row['variable']=0;
 				if (empty($row['subkey']))
 					$row['subkey']=0;
 				if (empty($row['category']))
 					$row['category']=0;
-					
+
 				if (is_array ($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]))
 				{
-					// we are sure that the other site have a selected value 
-					if ($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]['selected_value']!='')											
+					// we are sure that the other site have a selected value
+					if ($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]['selected_value']!='')
 						$row['selected_value']	=$settings_by_access_list[$row['variable']] [$row['subkey']]	[ $row['category'] ]['selected_value'];
 				}
 				// there is no else because we load the default $row['selected_value'] of the main Dokeos site
-			}	
-		}	
-				
+			}
+		}
+
 		switch ($row['type']) {
-			case 'textfield' :	
+			case 'textfield' :
 				if ($row['variable']=='account_valid_duration') {
 					$form->addElement('text', $row['variable'], get_lang($row['comment']),array('maxlength'=>'5'));
-					$form->applyFilter($row['variable'],'html_filter');					
-					$default_values[$row['variable']] = $row['selected_value'];	
+					$form->applyFilter($row['variable'],'html_filter');
+					$default_values[$row['variable']] = $row['selected_value'];
 				} else {
 					$form->addElement('text', $row['variable'], get_lang($row['comment']),$hideme);
 					$form->applyFilter($row['variable'],'html_filter');
-					$default_values[$row['variable']] = $row['selected_value'];		
-				}					
+					$default_values[$row['variable']] = $row['selected_value'];
+				}
 
 				break;
 			case 'textarea' :
@@ -207,7 +207,7 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 						if ($hide_element) {
 							$element->freeze();
 						}
-						$group[] = $element; 
+						$group[] = $element;
 					}
 				}
 				$form->addGroup($group, $row['variable'], get_lang($row['comment']), '<br />', false);
@@ -216,27 +216,27 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 			case 'checkbox';
 				//1. we collect all the options of this variable
 				$sql = "SELECT * FROM settings_current WHERE variable='".$row['variable']."' AND access_url =  1";
-				
+
 				$result = api_sql_query($sql, __FILE__, __LINE__);
-				$group = array ();	
+				$group = array ();
 				while ($rowkeys = Database::fetch_array($result)) {
  					if ($rowkeys['variable'] == 'course_create_active_tools' && $rowkeys['subkey'] == 'enable_search') {continue;}
 					$element = & $form->createElement('checkbox', $rowkeys['subkey'], '', get_lang($rowkeys['subkeytext']));
-					if ($row['access_url_changeable']==1) {						
+					if ($row['access_url_changeable']==1) {
 						//2. we look into the DB if there is a setting for a specific access_url
 						$access_url = $_configuration['access_url'];
 						if(empty($access_url )) $access_url =1;
-						$sql = "SELECT selected_value FROM settings_current WHERE variable='".$rowkeys['variable']."' AND subkey='".$rowkeys['subkey']."'  AND  subkeytext='".$rowkeys['subkeytext']."' AND access_url =  $access_url";						
+						$sql = "SELECT selected_value FROM settings_current WHERE variable='".$rowkeys['variable']."' AND subkey='".$rowkeys['subkey']."'  AND  subkeytext='".$rowkeys['subkeytext']."' AND access_url =  $access_url";
 						$result_access = api_sql_query($sql, __FILE__, __LINE__);
 						$row_access = Database::fetch_array($result_access);
 						if ($row_access['selected_value'] == 'true' && ! $form->isSubmitted()) {
-							$element->setChecked(true); 
+							$element->setChecked(true);
 						}
-					} else {											
+					} else {
 						if ($rowkeys['selected_value'] == 'true' && ! $form->isSubmitted()) {
-							$element->setChecked(true); 
+							$element->setChecked(true);
 						}
-					}					
+					}
 					if ($hide_element) {
 						$element->freeze();
 					}
@@ -273,25 +273,25 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 			{
 				//$sql = "UPDATE $table_settings_current SET selected_value='".mysql_real_escape_string($value)."' WHERE variable='$key'";
 				//$result = api_sql_query($sql, __FILE__, __LINE__);
-				
-				if (api_get_setting($key) != $value) $keys[] = $key;	
-																
-				$result = api_set_setting($key,$value,null,null,$_configuration['access_url']);												
+
+				if (api_get_setting($key) != $value) $keys[] = $key;
+
+				$result = api_set_setting($key,$value,null,null,$_configuration['access_url']);
 
 			}
 			else
 			{
-				
+
 				$sql = "SELECT subkey FROM $table_settings_current WHERE variable = '$key'";
 				$res = api_sql_query($sql,__FILE__,__LINE__);
 				$subkeys = array();
 				while ($row_subkeys = Database::fetch_array($res)) {
-					// if subkey is changed					
+					// if subkey is changed
 					if ( (isset($value[$row_subkeys['subkey']]) && api_get_setting($key,$row_subkeys['subkey']) == 'false') ||
 						 (!isset($value[$row_subkeys['subkey']]) && api_get_setting($key,$row_subkeys['subkey']) == 'true')) {
 						$keys[] = $key;
-						break;	
-					} 																		
+						break;
+					}
 				}
 
 				foreach ($value as $subkey => $subvalue)
@@ -306,19 +306,19 @@ if (!empty($_GET['category']) and !in_array($_GET['category'], array('Plugins',
 			}
 		}
 
-		// add event configuration settings category to system log		
+		// add event configuration settings category to system log
 		$time = time();
-		$user_id = api_get_user_id();		
-		$category = $_GET['category']; 		
+		$user_id = api_get_user_id();
+		$category = $_GET['category'];
 		event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
-		
 
-		// add event configuration settings variable to system log				
-		if (is_array($keys) && count($keys) > 0) {			
-			foreach($keys as $variable) {																	
-					event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_VARIABLE, $variable, $time, $user_id);				
+
+		// add event configuration settings variable to system log
+		if (is_array($keys) && count($keys) > 0) {
+			foreach($keys as $variable) {
+					event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_VARIABLE, $variable, $time, $user_id);
 			}
-		}			
+		}
 
 		header('Location: settings.php?action=stored&category='.Security::remove_XSS($_GET['category']));
 		exit;
@@ -385,7 +385,7 @@ if (isset ($_GET['category']))
             break;
 		case 'Templates' :
 			handle_templates();
-			break;            
+			break;
 		default :
 			$form->display();
 	}
@@ -435,11 +435,11 @@ function handle_plugins()
 
 	if (isset($_POST['submit_plugins']))
 	{
-		store_plugins();		
-		// add event to system log		
+		store_plugins();
+		// add event to system log
 		$time = time();
-		$user_id = api_get_user_id();		
-		$category = $_GET['category']; 		
+		$user_id = api_get_user_id();
+		$category = $_GET['category'];
 		event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
 
 		Display :: display_normal_message(get_lang('SettingsStored'));
@@ -566,7 +566,7 @@ function display_plugin_cell($location, $plugin_info, $current_plugin, $active_p
 	echo "\t\t<td align=\"center\">\n";
 	if (in_array($location, $plugin_info['location']))
 	{
-		if (isset($active_plugins[$location]) && is_array($active_plugins[$location]) 
+		if (isset($active_plugins[$location]) && is_array($active_plugins[$location])
 			&& in_array($current_plugin, $active_plugins[$location]))
 		{
 			$checked = "checked";
@@ -590,32 +590,32 @@ function handle_stylesheets()
 	// Current style
 	$currentstyle = api_get_setting('stylesheets');
 	$is_style_changeable=false;
-	
-	
+
+
 	if ($_configuration['access_url']!=1)
 	{
 		$style_info = api_get_settings('stylesheets','',1,0);
-		$url_info = api_get_access_url($_configuration['access_url']);	 
+		$url_info = api_get_access_url($_configuration['access_url']);
 		if ($style_info[0]['access_url_changeable']==1 && $url_info['active']==1)
 		{
-			$is_style_changeable=true;	
-			echo '<div class="actions" id="stylesheetuploadlink">';	
-			Display::display_icon('theme_add.gif');	
+			$is_style_changeable=true;
+			echo '<div class="actions" id="stylesheetuploadlink">';
+			Display::display_icon('theme_add.gif');
 			echo '<a href="" onclick="document.getElementById(\'newstylesheetform\').style.display = \'block\'; document.getElementById(\'stylesheetuploadlink\').style.display = \'none\';return false; ">'.get_lang('UploadNewStylesheet').'</a>';
 			echo '</div>';
-		} 
+		}
 	}
 	else
 	{
 		$is_style_changeable=true;
-		echo '<div class="actions" id="stylesheetuploadlink">';	
+		echo '<div class="actions" id="stylesheetuploadlink">';
 		Display::display_icon('theme_add.gif');
 		echo '<a href="" onclick="document.getElementById(\'newstylesheetform\').style.display = \'block\'; document.getElementById(\'stylesheetuploadlink\').style.display = \'none\';return false; ">'.get_lang('UploadNewStylesheet').'</a>';
 		echo '</div>';
-	}	
-		
+	}
+
 	$form = new FormValidator('stylesheet_upload','post','settings.php?category=stylesheets&showuploadform=true');
-	$form->addElement('text','name_stylesheet',get_lang('NameStylesheet'),array('size' => '40', 'maxlength' => '40'));	
+	$form->addElement('text','name_stylesheet',get_lang('NameStylesheet'),array('size' => '40', 'maxlength' => '40'));
 	$form->addRule('name_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
 	$form->addElement('file', 'new_stylesheet', get_lang('UploadNewStylesheet'));
 	$allowed_file_types = array ('css');
@@ -628,41 +628,41 @@ function handle_stylesheets()
 		$picture_element = & $form->getElement('new_stylesheet');
 		$picture = $picture_element->getValue();
 		upload_stylesheet($values, $picture);
-		
-		// add event to system log		
+
+		// add event to system log
 		$time = time();
-		$user_id = api_get_user_id();		
-		$category = $_GET['category']; 		
+		$user_id = api_get_user_id();
+		$category = $_GET['category'];
 		event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
-		
+
 		Display::display_confirmation_message(get_lang('StylesheetAdded'));
 	}
-	else 
+	else
 	{
 		if (!is_writable(api_get_path(SYS_CODE_PATH).'css/'))
 		{
 			Display::display_error_message(api_get_path(SYS_CODE_PATH).'css/'.get_lang('IsNotWritable'));
 		}
-		else 
+		else
 		{
 			if ($_GET['showuploadform'] == 'true')
 			{
 				echo '<div id="newstylesheetform">';
 			}
-			else 
+			else
 			{
 				echo '<div id="newstylesheetform" style="display: none;">';
 			}
 				// uploading a new stylesheet
 			if ($_configuration['access_url']==1)
 			{
-				$form->display();	
+				$form->display();
 			}
 			else
 			{
 				if ($is_style_changeable)
 				{
-					$form->display();				
+					$form->display();
 				}
 			}
 			echo '</div>';
@@ -696,9 +696,9 @@ function handle_stylesheets()
 						$selected = '';
 					}
 					$show_name=get_lang(str_replace(' ','', ucwords(str_replace('_',' ', $style_dir))), '');
-					
+
 					if ($is_style_changeable)
-					{					
+					{
 						echo "<input type=\"radio\" name=\"style\" value=\"".$style_dir."\" ".$selected." onClick=\"parent.preview.location='style_preview.php?style=".$style_dir."';\"/>";
 						echo '<a href="style_preview.php?style='.$style_dir.'" target="preview">'.$show_name.'</a>';
 					}
@@ -715,7 +715,7 @@ function handle_stylesheets()
 		@closedir($handle);
 	}
 	if ($is_style_changeable)
-	{	
+	{
 		echo '<button class="save" type="submit" name="submit_stylesheets"> '.get_lang('SaveSettings').' </button></form>';
 	}
 }
@@ -725,7 +725,7 @@ function handle_stylesheets()
  *
  * @param array $values the values of the form
  * @param array $picture the values of the uploaded file
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version May 2008
  * @since Dokeos 1.8.5
@@ -734,7 +734,7 @@ function upload_stylesheet($values,$picture)
 {
 	// valid name for the stylesheet folder
 	$style_name = api_ereg_replace("[^A-Za-z0-9]", "", $values['name_stylesheet'] );
-	
+
 	// create the folder if needed
 	if(!is_dir(api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/'))
 	{
@@ -743,9 +743,9 @@ function upload_stylesheet($values,$picture)
 			$perm = api_get_setting('permissions_for_new_directories');
 			$perm = octdec(!empty($perm)?$perm:'0770');
 			chmod(api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/', $perm);
-		}		
+		}
 	}
-	
+
 	// move the file in the folder
 	move_uploaded_file($picture['tmp_name'], api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/'.$picture['name']);
 }
@@ -773,7 +773,7 @@ function store_plugins()
 		{
 			//$sql = "INSERT into $table_settings_current (variable,category,selected_value) VALUES ('".$form_name_elements['1']."','Plugins','".$form_name_elements['0']."')";
 			//api_sql_query($sql, __LINE__, __FILE__);
-			api_add_setting($form_name_elements['0'],$form_name_elements['1'],$form_name_elements['0'],null,'Plugins',$form_name_elements['0'],null,null,null,$_configuration['access_url'],1);			
+			api_add_setting($form_name_elements['0'],$form_name_elements['1'],$form_name_elements['0'],null,'Plugins',$form_name_elements['0'],null,null,null,$_configuration['access_url'],1);
 		}
 	}
 }
@@ -818,7 +818,7 @@ function store_stylesheets()
 
 		api_sql_query($sql, __LINE__, __FILE__);
 		*/
-		
+
 		api_set_setting('stylesheets',$style,null,'stylesheets',$_configuration['access_url']);
 	}
 
@@ -913,7 +913,7 @@ function handle_search() {
 
 /**
  * wrapper for the templates
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -928,21 +928,21 @@ function handle_templates()
 
 	if ($_GET['action'] == 'add' OR ( $_GET['action'] == 'edit' AND is_numeric($_GET['id']))) {
 		add_edit_template();
-		
-		// add event to system log		
+
+		// add event to system log
 		$time = time();
-		$user_id = api_get_user_id();		
-		$category = $_GET['category']; 		
+		$user_id = api_get_user_id();
+		$category = $_GET['category'];
 		event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
-		
+
 	} else {
 		if ($_GET['action'] == 'delete' and is_numeric($_GET['id'])) {
 			delete_template($_GET['id']);
-			
-			// add event to system log		
+
+			// add event to system log
 			$time = time();
-			$user_id = api_get_user_id();		
-			$category = $_GET['category']; 		
+			$user_id = api_get_user_id();
+			$category = $_GET['category'];
 			event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
 		}
 		display_templates();
@@ -962,17 +962,17 @@ function display_templates()
 	$table->set_additional_parameters(array('category'=>Security::remove_XSS($_GET['category'])));
 	$table->set_header(0, get_lang('Image'), true, array ('style' => 'width:101px;'));
 	$table->set_header(1, get_lang('Title'));
-	$table->set_header(2, get_lang('Actions'), false, array ('style' => 'width:50px;'));	
+	$table->set_header(2, get_lang('Actions'), false, array ('style' => 'width:50px;'));
 	$table->set_column_filter(2,'actions_filter');
 	$table->set_column_filter(0,'image_filter');
-	$table->display();	
+	$table->display();
 }
 
 /**
- * Get the number of templates that are defined by the platform admin. 
+ * Get the number of templates that are defined by the platform admin.
+ *
+ * @return integer
  *
- * @return integer 
- * 
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -981,12 +981,12 @@ function get_number_of_templates()
 {
 	// Database table definition
 	$table_system_template = Database :: get_main_table('system_template');
-	
+
 	// The sql statement
 	$sql = "SELECT COUNT(id) AS total FROM $table_system_template";
 	$result = api_sql_query($sql, __FILE__, __LINE__);
 	$row = Database::fetch_array($result);
-	
+
 	// returning the number of templates
 	return $row['total'];
 }
@@ -996,10 +996,10 @@ function get_number_of_templates()
  *
  * @param integer $from the start of the limit statement
  * @param integer $number_of_items the number of elements that have to be retrieved from the database
- * @param integer $column the column that is 
+ * @param integer $column the column that is
  * @param string $direction the sorting direction (ASC or DESC�
- * @return array 
- * 
+ * @return array
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -1008,11 +1008,11 @@ function get_template_data($from, $number_of_items, $column, $direction)
 {
 	// Database table definition
 	$table_system_template = Database :: get_main_table('system_template');
-	
+
 	// the sql statement
 	$sql = "SELECT image as col0, title as col1, id as col2 FROM $table_system_template";
 	$sql .= " ORDER BY col$column $direction ";
-	$sql .= " LIMIT $from,$number_of_items";	
+	$sql .= " LIMIT $from,$number_of_items";
 	$result = api_sql_query($sql, __FILE__, __LINE__);
 	while ($row = Database::fetch_array($result)) {
 		$row['1'] = get_lang($row['1']);
@@ -1027,7 +1027,7 @@ function get_template_data($from, $number_of_items, $column, $direction)
  *
  * @param integer $id the id of the template
  * @return html code for the link to edit and delete the template
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -1044,7 +1044,7 @@ function actions_filter($id)
  *
  * @param string $image the image
  * @return html code for the image
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -1072,134 +1072,134 @@ function add_edit_template()
 {
 	// initiate the object
 	$form = new FormValidator('template', 'post', 'settings.php?category=Templates&action='.$_GET['action'].'&id='.$_GET['id']);
-	
+
 	// settting the form elements: the header
 	if ($_GET['action'] == 'add') {
 		$title = get_lang('AddTemplate');
 	}
-	else 
+	else
 	{
 		$title = get_lang('EditTemplate');
 	}
 	$form->addElement('header', '', $title);
-	
+
 	// settting the form elements: the title of the template
 	$form->add_textfield('title', get_lang('Title'), false);
-	
+
 	// settting the form elements: the content of the template (wysiwyg editor)
 	$form->addElement('html_editor', 'template_text', get_lang('Text'), null, array('ToolbarSet' => 'AdminTemplates', 'Width' => '100%', 'Height' => '400'));
-	
+
 	// settting the form elements: the form to upload an image to be used with the template
 	$form->addElement('file','template_image',get_lang('Image'),'');
-	
+
 	// settting the form elements: a little bit information about the template image
 	$form->addElement('static', 'file_comment', '', get_lang('TemplateImageComment100x70'));
-	
-	// getting all the information of the template when editing a template 
+
+	// getting all the information of the template when editing a template
 	if ($_GET['action'] == 'edit') {
-		// Database table definition		
+		// Database table definition
 		$table_system_template = Database :: get_main_table('system_template');
 		$sql = "SELECT * FROM $table_system_template WHERE id = '".Database::escape_string($_GET['id'])."'";
 		$result = api_sql_query($sql, __FILE__, __LINE__);
 		$row = Database::fetch_array($result);
-		
+
 		$defaults['template_id'] 	= intval($_GET['id']);
 		$defaults['template_text'] 	= $row['content'];
 		//forcing a get_lang
 		$defaults['title'] 			= get_lang($row['title']);
-		
+
 		// adding an extra field: a hidden field with the id of the template we are editing
 		$form->addElement('hidden','template_id');
-		
+
 		// adding an extra field: a preview of the image that is currently used
 		if (!empty($row['image']))
-		{		
+		{
 			$form->addElement('static','template_image_preview', '', '<img src="'.api_get_path(WEB_PATH).'home/default_platform_document/template_thumb/'.$row['image'].'" alt="'.get_lang('TemplatePreview').'"/>');
 		}
 		else
 		{
 			$form->addElement('static','template_image_preview', '', '<img src="'.api_get_path(WEB_PATH).'home/default_platform_document/template_thumb/noimage.gif" alt="'.get_lang('NoTemplatePreview').'"/>');
 		}
-		
-		// setting the information of the template that we are editing 
+
+		// setting the information of the template that we are editing
 		$form->setDefaults($defaults);
-	}	
+	}
 		// settting the form elements: the submit button
 	$form->addElement('style_submit_button' , 'submit', get_lang('Ok') ,'class="save"');
-	
+
 	// setting the rules: the required fields
-	$form->addRule('title', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');	
-	$form->addRule('template_text', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');	
-	
+	$form->addRule('title', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
+	$form->addRule('template_text', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
+
 	// if the form validates (complies to all rules) we save the information, else we display the form again (with error message if needed)
 	if( $form->validate() )
 	{
 
-		$check = Security::check_token('post');	
-		if ($check) {		
+		$check = Security::check_token('post');
+		if ($check) {
 			// exporting the values
 			$values = $form->exportValues();
-	
+
 			// upload the file
 			if (!empty($_FILES['template_image']['name']))
 			{
 				include_once (api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
 				$upload_ok = process_uploaded_file($_FILES['template_image']);
-				
+
 				if ($upload_ok)
 				{
 					// Try to add an extension to the file if it hasn't one
-					$new_file_name = add_ext_on_mime(stripslashes($_FILES['template_image']['name']), $_FILES['template_image']['type']);	
-					
+					$new_file_name = add_ext_on_mime(stripslashes($_FILES['template_image']['name']), $_FILES['template_image']['type']);
+
 					// upload dir
 					$upload_dir = api_get_path(SYS_PATH).'home/default_platform_document/template_thumb/';
-					
+
 					// create dir if not exists
 	                if (!is_dir($upload_dir)) {
 	                    $perm = api_get_setting('permissions_for_new_directories');
 	                    $perm = octdec(!empty($perm)?$perm:'0770');
 	                	$res = @mkdir($upload_dir,$perm);
 	                }
-					
+
 					// resize image to max default and upload
 					require_once (api_get_path(LIBRARY_PATH).'image.lib.php');
-					$temp = new image($_FILES['template_image']['tmp_name']);	
+					$temp = new image($_FILES['template_image']['tmp_name']);
 					$picture_infos=@getimagesize($_FILES['template_image']['tmp_name']);
-					
+
 					$max_width_for_picture = 100;
-					
+
 					if ($picture_infos[0]>$max_width_for_picture)
-					{		
+					{
 						$thumbwidth = $max_width_for_picture;
 						if (empty($thumbwidth) or $thumbwidth==0) {
 						  $thumbwidth=$max_width_for_picture;
 						}
 						$new_height = round(($thumbwidth/$picture_infos[0])*$picture_infos[1]);
-						
+
 						$temp->resize($thumbwidth,$new_height,0);
 					}
-					
+
 					$type=$picture_infos[2];
-							  
+
 					switch (!empty($type))
 					{
-						case 2 : $temp->send_image('JPG',$upload_dir.$new_file_name);							 
+						case 2 : $temp->send_image('JPG',$upload_dir.$new_file_name);
 								 break;
-						case 3 : $temp->send_image('PNG',$upload_dir.$new_file_name);							
+						case 3 : $temp->send_image('PNG',$upload_dir.$new_file_name);
 								 break;
-						case 1 : $temp->send_image('GIF',$upload_dir.$new_file_name);							 
+						case 1 : $temp->send_image('GIF',$upload_dir.$new_file_name);
 								 break;
 					}
 				}
 		   }
-		   
+
 		   // store the information in the database (as insert or as update)
 		   $table_system_template = Database :: get_main_table('system_template');
 		   if ($_GET['action'] == 'add') {
 		   		$content_template = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body>'.Database::escape_string($values['template_text']).'</body>';
 			   	$sql = "INSERT INTO $table_system_template (title, content, image) VALUES ('".Database::escape_string($values['title'])."','".$content_template."','".Database::escape_string($new_file_name)."')";
 			   	$result = api_sql_query($sql, __FILE__, __LINE__);
-			   	
+
 			   	// display a feedback message
 			   	Display::display_confirmation_message(get_lang('TemplateAdded'));
 			   	echo '<a href="settings.php?category=Templates&amp;action=add">'.Display::return_icon('template_add.gif', get_lang('AddTemplate')).get_lang('AddTemplate').'</a>';
@@ -1213,25 +1213,25 @@ function add_edit_template()
 			   	}
 			   	$sql .= " WHERE id='".Database::escape_string($_GET['id'])."'";
 			   	$result = api_sql_query($sql, __FILE__, __LINE__);
-			   	
+
 			   	// display a feedback message
-			   	Display::display_confirmation_message(get_lang('TemplateEdited'));		   	
+			   	Display::display_confirmation_message(get_lang('TemplateEdited'));
 		   }
-	   
+
 		}
 	   Security::clear_token();
 	   display_templates();
-	   
-	   
-	   
+
+
+
 	}
-	else 
+	else
 	{
 		$token = Security::get_token();
 		$form->addElement('hidden','sec_token');
 		$form->setConstants(array('sec_token' => $token));
 		// display the form
-		$form->display();		
+		$form->display();
 	}
 }
 
@@ -1239,7 +1239,7 @@ function add_edit_template()
  * Delete a template
  *
  * @param integer $id the id of the template that has to be deleted
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version August 2008
  * @since Dokeos 1.8.6
@@ -1250,16 +1250,16 @@ function delete_template($id)
 	$table_system_template = Database :: get_main_table('system_template');
 	$sql = "SELECT * FROM $table_system_template WHERE id = '".Database::escape_string($id)."'";
 	$result = api_sql_query($sql, __FILE__, __LINE__);
-	$row = Database::fetch_array($result);	
+	$row = Database::fetch_array($result);
 	if (!empty($row['image']))
 	{
 		unlink(api_get_path(SYS_PATH).'home/default_platform_document/template_thumb/'.$row['image']);
 	}
-	
+
 	// now we remove it from the database
 	$sql = "DELETE FROM $table_system_template WHERE id = '".Database::escape_string($id)."'";
 	$result = api_sql_query($sql, __FILE__, __LINE__);
-	
+
 	// display a feedback message
 	Display::display_confirmation_message(get_lang('TemplateDeleted'));
 }

+ 3 - 3
main/admin/statistics.php

@@ -52,12 +52,12 @@ Display::display_header($tool_name);
 ==============================================================================
 		MAIN CODE
 ==============================================================================
-*/ 
+*/
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
-*/ 
+*/
 Display::display_footer();
 ?>

+ 2 - 2
main/admin/statistics/index.php

@@ -135,8 +135,8 @@ switch($_GET['action'])
 	case 'pictures':
 		statistics::print_user_pictures_stats();
 		break;
-	case 'activities':	 		
-		statistics::print_activities_stats();		
+	case 'activities':
+		statistics::print_activities_stats();
 		break;
 }
 

+ 41 - 41
main/admin/statistics/statistics.lib.php

@@ -70,7 +70,7 @@ class Statistics
 		$course_user_table 	= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 		$course_table 		= Database :: get_main_table(TABLE_MAIN_COURSE);
 		$user_table 		= Database :: get_main_table(TABLE_MAIN_USER);
-		
+
 		$sql = "SELECT COUNT(DISTINCT(user_id)) AS number FROM $user_table WHERE status = ".intval(Database::escape_string($status))." ";
 		if (isset ($category_code))
 		{
@@ -80,23 +80,23 @@ class Statistics
 		$obj = Database::fetch_object($res);
 		return $obj->number;
 	}
-	
+
 	/**
-	 * Count activities from track_e_default_table 
+	 * Count activities from track_e_default_table
 	 * @return int Number of activities counted
 	 */
 	function get_number_of_activities()
-	{  
+	{
 		// Database table definitions
-		$track_e_default  = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);  
-		  
-		$sql = "SELECT count(default_id) AS total_number_of_items FROM $track_e_default, $table_user user WHERE default_user_id = user.user_id ";  
-		  
+		$track_e_default  = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
+
+		$sql = "SELECT count(default_id) AS total_number_of_items FROM $track_e_default, $table_user user WHERE default_user_id = user.user_id ";
+
 		if (isset($_GET['keyword'])) {
 		$keyword = Database::escape_string($_GET['keyword']);
 		$sql .= " AND (user.username LIKE '%".$keyword."%' OR default_event_type LIKE '%".$keyword."%' OR default_value_type LIKE '%".$keyword."%' OR default_value LIKE '%".$keyword."%') ";
 		}
-		   
+
 		$res = api_sql_query($sql, __FILE__, __LINE__);
 		$obj = Database::fetch_object($res);
 		return $obj->total_number_of_items;
@@ -110,37 +110,37 @@ class Statistics
 		$track_e_default 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
 		$table_user = Database::get_main_table(TABLE_MAIN_USER);
 		$table_course = Database::get_main_table(TABLE_MAIN_COURSE);
-		
+
 		$sql = "SELECT
 				 	default_event_type  as col0,
 					default_value_type	as col1,
-					default_value		as col2,																
-					user.username 	as col3, 					
-					default_date 	as col4									
+					default_value		as col2,
+					user.username 	as col3,
+					default_date 	as col4
 				FROM $track_e_default track_default, $table_user user
 				WHERE track_default.default_user_id = user.user_id ";
-				
+
 		if (isset($_GET['keyword'])) {
 		$keyword = Database::escape_string($_GET['keyword']);
 		$sql .= " AND (user.username LIKE '%".$keyword."%' OR default_event_type LIKE '%".$keyword."%' OR default_value_type LIKE '%".$keyword."%' OR default_value LIKE '%".$keyword."%') ";
-		}		
-						 				 
-		if (!empty($column) && !empty($direction)) {						 				 
-			$sql .=	" ORDER BY col$column $direction"; 
+		}
+
+		if (!empty($column) && !empty($direction)) {
+			$sql .=	" ORDER BY col$column $direction";
 		} else {
 			$sql .=	" ORDER BY col4 DESC ";
 		}
-		$sql .=	" LIMIT $from,$number_of_items ";				
-											
+		$sql .=	" LIMIT $from,$number_of_items ";
+
 		$res = api_sql_query($sql, __FILE__, __LINE__);
 		$activities = array ();
 		while ($row = Database::fetch_row($res)) {
 			$row[4] = api_format_date(DATE_TIME_FORMAT_LONG, strtotime($row[4]));
 			$activities[] = $row;
-		}		
+		}
 		return $activities;
 	}
-		
+
 	/**
 	 * Get all course categories
 	 * @return array All course categories (code => name)
@@ -353,43 +353,43 @@ class Statistics
 		$result[get_lang('Yes')] = $count2->n; // #users with picture
 		Statistics::print_stats(get_lang('CountUsers').' ('.get_lang('UserPicture').')',$result,true);
 	}
-	
-	function print_activities_stats() {				
-		
+
+	function print_activities_stats() {
+
 		echo '<h4>'.get_lang('ImportantActivities').'</h4>';
-				
+
 		// Create a search-box
 		$form = new FormValidator('search_simple','get',api_get_path(WEB_CODE_PATH).'admin/statistics/index.php?action=activities','','width=200px',false);
 		$renderer =& $form->defaultRenderer();
 		$renderer->setElementTemplate('<span>{element}</span> ');
 		$form->addElement('hidden','action','activities');
 		$form->addElement('hidden','activities_direction','DESC');
-		$form->addElement('hidden','activities_column','4');		
+		$form->addElement('hidden','activities_column','4');
 		$form->addElement('text','keyword',get_lang('keyword'));
-		$form->addElement('style_submit_button', 'submit', get_lang('SearchActivities'),'class="search"');							 
-		echo '<div class="actions">';		
-			$form->display();				
+		$form->addElement('style_submit_button', 'submit', get_lang('SearchActivities'),'class="search"');
+		echo '<div class="actions">';
+			$form->display();
 		echo '</div>';
-		
-				
+
+
 		$table = new SortableTable('activities', array('Statistics','get_number_of_activities'), array('Statistics','get_activities_data'),4,50,'DESC');
 		$parameters = array();
-		
-		$parameters['action'] = 'activities';		
+
+		$parameters['action'] = 'activities';
 		if (isset($_GET['keyword'])) {
 			$parameters['keyword'] = Security::remove_XSS($_GET['keyword']);
 		}
-		
-		$table->set_additional_parameters($parameters);											
+
+		$table->set_additional_parameters($parameters);
 		$table->set_header(0, get_lang('EventType'));
 		$table->set_header(1, get_lang('DataType'));
-		$table->set_header(2, get_lang('Value'));		
+		$table->set_header(2, get_lang('Value'));
 		$table->set_header(3, get_lang('UserName'));
-		$table->set_header(4, get_lang('Date'));		
+		$table->set_header(4, get_lang('Date'));
 		$table->display();
-		
+
 	}
-	
+
 	/**
 	 * Shows statistics about the time of last visit to each course.
 	 */
@@ -407,7 +407,7 @@ class Statistics
 	    	$direction = SORT_ASC;
 	    } else {
 	    	$direction = isset($_GET['direction']) ? $_GET['direction'] : SORT_ASC;
-	    }		
+	    }
 		$form = new FormValidator('courselastvisit','get');
 		$form->addElement('hidden','action','courselastvisit');
 		$form->add_textfield('date_diff',get_lang('Days'),true);

+ 1 - 1
main/admin/style_preview.php

@@ -33,7 +33,7 @@ include(api_get_path(INCLUDE_PATH).'banner.inc.php');
         <td>
         <table>
             <tr>
-              <td width="220">              
+              <td width="220">
               <table id="smallcalendar">
                   <tr id="title">
                     <td width="10%"><a href="#"><<</a></td>

+ 37 - 37
main/admin/sub_language.class.php

@@ -20,14 +20,14 @@ class SubLanguageManager {
      * @param String The dokeos path folder  (/var/www/my_dokeos/main/lang/spanish)
      * @param bool true if we only want the "subname" trad4all instead of  trad4all.inc.php
      * @return Array All file of dokeos folder
-     * 
+     *
      */
     public static function get_all_data_of_dokeos_folder ($dokeos_path_folder,$only_main_name=false) {
 	   $content_dir=array();
 	    if (is_dir($dokeos_path_folder)) {
 		    if ($dh = opendir($dokeos_path_folder)) {
 		        while (($file = readdir($dh)) !== false) {
-		           if ($file[0]<>'.' && substr($file,-4,strlen($file))=='.php') {		           	
+		           if ($file[0]<>'.' && substr($file,-4,strlen($file))=='.php') {
 		           		if ($only_main_name) {
 		           			if ($file!='' && strpos($file, '.inc.php'))
 		           				$content_dir[]=substr($file, 0, strpos($file, '.inc.php'));
@@ -35,13 +35,13 @@ class SubLanguageManager {
 		           	  		$content_dir[]=$file;
 		           		}
 		           }
-		           
+
 		        }
-		       
+
 		    }
  			closedir($dh);
-		    return $content_dir; 
-		}	
+		    return $content_dir;
+		}
     }
     /**
      * Get all information of sub-language
@@ -50,7 +50,7 @@ class SubLanguageManager {
      * @return Array All information about sub-language
      */
 	public static function get_all_information_of_sub_language ($parent_id,$sub_language_id) {
-		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
+		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 	 	$sql='SELECT * FROM '.$tbl_admin_languages.' WHERE parent_id="'.Database::escape_string($parent_id).'" AND id="'.Database::escape_string($sub_language_id).'"';
 		$rs=Database::query($sql,__FILE__,__LINE__);
 		$all_information=array();
@@ -58,27 +58,27 @@ class SubLanguageManager {
 			$all_information=$row;
 		}
 		return $all_information;
-	} 
+	}
     /**
      * Get all information of language
      * @param Integer The parent id(Language father id)
      * @return Array All information about language
-     */	
+     */
    public static function get_all_information_of_language ($parent_id) {
- 		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
+ 		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql='SELECT * FROM '.$tbl_admin_languages.' WHERE id="'.Database::escape_string($parent_id).'"';
 		$rs=Database::query($sql,__FILE__,__LINE__);
 		$all_information=array();
 		while ($row=Database::fetch_array($rs,'ASSOC')) {
 			$all_information=$row;
 		}
-		return $all_information;  	
+		return $all_information;
    }
      /**
-     * Get all information of dokeos file 
+     * Get all information of dokeos file
      * @param String The dokeos path file (/var/www/my_dokeos/main/lang/spanish/gradebook.inc.php)
      * @return Array Contains all information of dokeos file
-     */	  
+     */
    public static function get_all_language_variable_in_file ($dokeos_path_file) {
 	   	$info_file=file($dokeos_path_file);
 	   	foreach ($info_file as $line) {
@@ -89,35 +89,35 @@ class SubLanguageManager {
 	    }
 			return $res_list;
    }
-   
+
      /**
-     * Add file in sub-language directory and add header(tag php) 
+     * Add file in sub-language directory and add header(tag php)
      * @param String The dokeos path file (/var/www/my_dokeos/main/lang/spanish/gradebook.inc.php)
      * @return void()
-     */	   
+     */
    public static function add_file_in_language_directory ($dokeos_path_file) {
    		file_put_contents($dokeos_path_file,'<?php'.PHP_EOL);
    }
      /**
-     * Write in file of sub-language 
+     * Write in file of sub-language
      * @param String The path file (/var/www/my_dokeos/main/lang/spanish/gradebook.inc.php)
      * @param String The new sub-language
      * @param String The language variable
      * @return void()
-     */	    
+     */
    public static function write_data_in_file ($path_file,$new_sub_language,$variable_sub_language) {
    		$new_data=$variable_sub_language.'='.$new_sub_language;
    		$g_open_file = fopen($path_file, "a");
    		if (fwrite($g_open_file, $new_data.PHP_EOL) === false) {
    			//not allow to write
-   		} 
+   		}
    		fclose($g_open_file);
    }
      /**
-     * Add directory for sub-language 
+     * Add directory for sub-language
      * @param String The sub-language path directory ( /var/www/my_dokeos/main/lang/spanish_corporate )
      * @return boolean
-     */	      
+     */
    public static function add_directory_of_sub_language($path_sub_language) {
    		$rs=@mkdir($path_sub_language,0777);
 		if ($rs) {
@@ -130,9 +130,9 @@ class SubLanguageManager {
 	 * Delete sub-language
 	 * @param Integer The parent id
 	 * @return void()
-	 */   
+	 */
    public static function removed_sub_language ($parent_id,$sub_language_id) {
-   		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);		
+   		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql='DELETE FROM '.$tbl_admin_languages.' WHERE parent_id="'.Database::escape_string($parent_id).'" AND id="'.Database::escape_string($sub_language_id).'" ';
     	$rs=Database::query($sql,__FILE__,__LINE__);
    }
@@ -142,7 +142,7 @@ class SubLanguageManager {
 	 * @return Boolean
 	 */
 	public static function check_if_exist_language_by_id ($language_id) {
-		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
+		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql='SELECT count(*) as count FROM '.$tbl_admin_languages.' WHERE id="'.Database::escape_string($language_id).'"';
 		$rs=Database::query($sql,__FILE__,__LINE__);
 		if (Database::num_rows($rs)>0) {
@@ -153,32 +153,32 @@ class SubLanguageManager {
 			}
 		} else {
 			return false;;
-		}	
+		}
 	}
 
 	/**
 	 * Get name of language by id
 	 * @param Integer The language id
 	 * @return String The original name of language
-	 */	
+	 */
 	public static function get_name_of_language_by_id ($language_id) {
-		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
+		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql='SELECT original_name FROM '.$tbl_admin_languages.' WHERE id="'.Database::escape_string($language_id).'"';
 		$rs=Database::query($sql,__FILE__,__LINE__);
 		if (Database::num_rows($rs)>0) {
-			return Database::result($rs,0,'original_name');	
+			return Database::result($rs,0,'original_name');
 		} else {
 			return '';
 		}
-	
+
 	}
 	/**
 	 * Verified if language is sub-language
 	 * @param Integer The language id
-	 * @return Boolean 
+	 * @return Boolean
 	 */
 	public static function check_if_language_is_sub_language ($language_id) {
-	$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
+	$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 	$sql='SELECT count(*) AS count FROM '.$tbl_admin_languages.' WHERE id="'.Database::escape_string($language_id).'" AND NOT ISNULL(parent_id)';
     $rs=Database::query($sql,__FILE__,__LINE__);
 
@@ -194,10 +194,10 @@ class SubLanguageManager {
 	 * @return Boolean
 	 */
 	public static function check_if_language_is_father ($language_id) {
-		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);	
+		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql='SELECT count(*) AS count FROM '.$tbl_admin_languages.' WHERE parent_id="'.Database::escape_string($language_id).'" AND NOT ISNULL(parent_id);';
 	    $rs=Database::query($sql,__FILE__,__LINE__);
-	
+
 	    if (Database::num_rows($rs)>0 && Database::result($rs,'0','count')==1) {
 	    	return true;
 	    } else {
@@ -210,9 +210,9 @@ class SubLanguageManager {
 	 * @return void()
 	 */
 	public static function make_unavailable_language ($language_id) {
-		$tbl_admin_languages= Database :: get_main_table(TABLE_MAIN_LANGUAGE);		
+		$tbl_admin_languages= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
 		$sql_make_unavailable = "UPDATE $tbl_admin_languages SET available='0' WHERE id='".Database::escape_string($language_id)."'";
-		$result = Database::query($sql_make_unavailable,__FILE__,__LINE__);		
+		$result = Database::query($sql_make_unavailable,__FILE__,__LINE__);
 	}
 	/**
 	 * Make available the language
@@ -231,12 +231,12 @@ class SubLanguageManager {
 	  */
 	  public static function set_platform_language ($language_id) {
 		$tbl_admin_languages= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-		$tbl_settings_current 	= Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);	
+		$tbl_settings_current 	= Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
 		$sql_update = "SELECT english_name FROM ". $tbl_admin_languages." WHERE id='".Database::escape_string($language_id)."'";
 		$result = Database::query($sql_update,__FILE__,__LINE__);
 		$lang=Database::fetch_array($result);
 		$sql_update_2 = "UPDATE ".$tbl_settings_current." SET selected_value='".$lang['english_name']."' WHERE variable='platformLanguage'";
-		$result_2 = Database::query($sql_update_2);	  	
+		$result_2 = Database::query($sql_update_2);
 	  }
 }
 ?>

+ 78 - 78
main/admin/sub_language.php

@@ -8,7 +8,7 @@
 // name of the language file that needs to be included
 $language_file = 'admin';
 $cidReset = true;
-require_once '../inc/global.inc.php'; 
+require_once '../inc/global.inc.php';
 require_once 'sub_language.class.php';
 require_once api_get_path(LIBRARY_PATH).'array.lib.php';
 $this_section=SECTION_PLATFORM_ADMIN;
@@ -18,46 +18,46 @@ $htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/java
 $htmlHeadXtra[] ='<script type="text/javascript">
  $(document).ready(function() {
 
-	$(".save").click(function() {		
-		button_name=$(this).attr("name");	
+	$(".save").click(function() {
+		button_name=$(this).attr("name");
 		button_array=button_name.split("|");
-		button_name=button_array[1];	
-		file_id=button_array[2];		
+		button_name=button_array[1];
+		file_id=button_array[2];
 		is_variable_language="$"+button_name;
 
 		is_new_language=$("#txtid_"+button_name).attr("value");
    		if (is_new_language=="undefined") {
      			is_new_language="_";
-    	}	
-		
+    	}
+
 		if (is_new_language.length>0 && is_new_language!="_" && file_id!="" && button_name!="") {
 			$.ajax({
 				contentType: "application/x-www-form-urlencoded",
 				beforeSend: function(objeto) {
 					$("#div_message_information_id").html("<div class=\"normal-message\"><img src=\'../inc/lib/javascript/indicator.gif\' /></div>");
-				
+
 				},
 				type: "POST",
 				url: "../admin/sub_language_ajax.inc.php",
 				data: "new_language="+is_new_language+"&variable_language="+is_variable_language+"&file_id="+file_id+"&id="+'.intval($_REQUEST['id']).'+"&sub="+'.intval($_REQUEST['sub_language_id']).',
 				success: function(datos) {
 					$("#div_message_information_id").html("<div class=\"confirmation-message\">'.get_lang('TheNewWordHasBeenAdded').'</div>");
-				
-			} }); 
+
+			} });
 		} else {
 			$("#div_message_information_id").html("<div class=\"error-message\">'.get_lang('FormHasErrorsPleaseComplete').'</div>");
 		}
 	});
  		});
-</script>';	
+</script>';
 /*
-============================================================================== 
+==============================================================================
 		MAIN CODE
-============================================================================== 
+==============================================================================
 */
 // setting the name of the tool
 $tool_name = get_lang('CreateSubLanguage');
-// setting breadcrumbs  
+// setting breadcrumbs
 $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array ('url' => 'languages.php', 'name' => get_lang('PlatformLanguages'));
 
@@ -66,7 +66,7 @@ require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 
 if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
 	$language_name=SubLanguageManager::get_name_of_language_by_id ($_GET['id']);
-	$all_data_of_language=SubLanguageManager::get_all_information_of_language($_GET['id']);	
+	$all_data_of_language=SubLanguageManager::get_all_information_of_language($_GET['id']);
 	$my_language=$language_name;
 	if (SubLanguageManager::check_if_exist_language_by_id($_GET['id'])===true) {
 		$parent_id=intval($_GET['id']);
@@ -76,7 +76,7 @@ if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
 	}
 } else {
 	$language_name='';
-	$language_id_exist=false;	
+	$language_id_exist=false;
 }
 
 $language_name=get_lang('RegisterTermsOfSubLanguageForLanguage').' ( '.strtolower($language_name).' )';
@@ -110,31 +110,31 @@ echo '<br /><br /><br /><br />';
 echo '<div id="div_message_information_id">&nbsp;</div>';
 
 /**
- * Search a term in the language 
+ * Search a term in the language
  * @param string the term to search
  * @param bool the search will include the variable definition of the term
  * @param bool the search will include the english language variables
  * @param bool the search will include the parent language variables of the sub language
  * @param bool the search will include the sub language variables
- * @author Julio Montoya 
- *   
+ * @author Julio Montoya
+ *
  */
-function search_language_term($term, $search_in_variable = true , $search_in_english = true, $search_in_parent = true, $search_in_sub_language= true) {	
-	//These the $_REQUEST['id'] and the $_REQUEST['sub_language_id'] variables are process in global.inc.php (LOAD LANGUAGE FILES SECTION)		
+function search_language_term($term, $search_in_variable = true , $search_in_english = true, $search_in_parent = true, $search_in_sub_language= true) {
+	//These the $_REQUEST['id'] and the $_REQUEST['sub_language_id'] variables are process in global.inc.php (LOAD LANGUAGE FILES SECTION)
 	/*
 		These 4 arrays are set in global.inc.php with the condition that will be load from sub_language.php or sub_language_ajax.inc.php
 		$english_language_array
-		$parent_language_array 
-		$sub_language_array 
-		$language_files_to_load  
-	*/	
+		$parent_language_array
+		$sub_language_array
+		$language_files_to_load
+	*/
 	//echo '<pre>';
 	// array with the list of files to load i.e trad4fall, notification, etc set in global.inc.php
 
-	global $language_files_to_load, $sub_language_array, $english_language_array, $parent_language_array;	
-	$language_files_to_load_keys = array_flip($language_files_to_load);	
-	$array_to_search = $parent_language_array;	
-	$list_info = array();	
+	global $language_files_to_load, $sub_language_array, $english_language_array, $parent_language_array;
+	$language_files_to_load_keys = array_flip($language_files_to_load);
+	$array_to_search = $parent_language_array;
+	$list_info = array();
 	//echo '<pre>';
 	//print_r($language_files_to_load);
 	$term='/'.Security::remove_XSS(trim($_REQUEST['txt_search_word'])).'/i';
@@ -147,48 +147,48 @@ function search_language_term($term, $search_in_variable = true , $search_in_eng
 				//arrays are avoided
 				if (is_array($parent_variable_value)) {
 					continue;
-				}			
+				}
 				$founded = false;
-				// searching the item in the parent tool			
+				// searching the item in the parent tool
 				if (preg_match($term,$parent_variable_value)!==0) {
 					$founded = true;
-				}							
+				}
 				if ($founded) {
 					//loading variable from the english array
-					$sub_language_name_variable = $sub_language_array[$lang_file][$parent_name_variable];					
+					$sub_language_name_variable = $sub_language_array[$lang_file][$parent_name_variable];
 					//loading variable from the english array
-					$english_name_variable = $english_language_array[$lang_file][$parent_name_variable];	
-					
-					//config buttons					
-					/*if (strlen($english_name_variable)>1500) {			
+					$english_name_variable = $english_language_array[$lang_file][$parent_name_variable];
+
+					//config buttons
+					/*if (strlen($english_name_variable)>1500) {
 						$size =20;
 					} else {
 						$size =4;
 					}*/
-          
-					$obj_text='<textarea rows="10" cols="40" name="txt|'.$parent_name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$parent_name_variable.'" >'.$sub_language_name_variable.'</textarea>';			
-					$obj_button='<button class="save" type="button" name="btn|'.$parent_name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$parent_name_variable.'"  />'.get_lang('Save').'</button>';		
-							
-					$list_info[]=array($lang_file.'.inc.php', 
+
+					$obj_text='<textarea rows="10" cols="40" name="txt|'.$parent_name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$parent_name_variable.'" >'.$sub_language_name_variable.'</textarea>';
+					$obj_button='<button class="save" type="button" name="btn|'.$parent_name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$parent_name_variable.'"  />'.get_lang('Save').'</button>';
+
+					$list_info[]=array($lang_file.'.inc.php',
 									   $parent_name_variable,
 									   $english_name_variable,
 									   $parent_variable_value,$obj_text,$obj_button);
-				}				
+				}
 			}
-		}		
-		
+		}
+
 		//search in english
 		if ($search_in_english || $search_in_variable) {
 			$variables = $english_language_array[$lang_file];
-			foreach ($variables as $name_variable =>$variable_value) {	
+			foreach ($variables as $name_variable =>$variable_value) {
 				if (is_array($variable_value)) {
 					continue;
 				}
-				if (is_array($variable_value))	
-					echo $lang_file;	
-				$founded = false;	
+				if (is_array($variable_value))
+					echo $lang_file;
+				$founded = false;
 				if ($search_in_english && $search_in_variable) {
-					// searching the item in the parent tool			
+					// searching the item in the parent tool
 					if (preg_match($term,$variable_value)!==0 || preg_match($term,$name_variable)!==0 ) {
 						$founded = true;
 					}
@@ -203,67 +203,67 @@ function search_language_term($term, $search_in_variable = true , $search_in_eng
 						}
 					}
 				}
-											
-				if ($founded) {					
+
+				if ($founded) {
 					//loading variable from the english array
 					$sub_language_name_variable = $sub_language_array[$lang_file][$name_variable];
 					$parent_variable_value 		= $parent_language_array[$lang_file][$name_variable];
-					//config buttons			
-					$obj_text='<textarea rows="10" cols="40" name="txt|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$name_variable.'" >'.$sub_language_name_variable.'</textarea>';			
-					$obj_button='<button class="save" type="button" name="btn|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$name_variable.'"  />'.get_lang('Save').'</button>';		
-							
+					//config buttons
+					$obj_text='<textarea rows="10" cols="40" name="txt|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$name_variable.'" >'.$sub_language_name_variable.'</textarea>';
+					$obj_button='<button class="save" type="button" name="btn|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$name_variable.'"  />'.get_lang('Save').'</button>';
+
 					//loading variable from the english array
 					$english_name_variable = $english_language_array[$lang_file][$name_variable];
-					
-					$list_info[]=array($lang_file.'.inc.php', 
+
+					$list_info[]=array($lang_file.'.inc.php',
 									   $name_variable,
 									   $english_name_variable,
 									   $parent_variable_value,$obj_text,$obj_button);
-				}				
+				}
 			}
 		}
-		
-		
+
+
 		//search in sub language
 		if ($search_in_sub_language) {
 			$variables = $sub_language_array[$lang_file];
 			foreach ($variables as $name_variable =>$variable_value) {
 				if (is_array($parent_variable_value)) {
 					continue;
-				}			
-							
+				}
+
 				$founded = false;
-				// searching the item in the parent tool			
+				// searching the item in the parent tool
 				if (preg_match($term,$variable_value)!==0) {
 					$founded = true;
-				}							
+				}
 				if ($founded) {
 					//loading variable from the english array
 					$sub_language_name_variable = $sub_language_array[$lang_file][$name_variable];
 					$parent_variable_value 		= $parent_language_array[$lang_file][$name_variable];
-					//config buttons			
-					$obj_text='<textarea rows="10" cols="40" name="txt|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$name_variable.'" >'.$sub_language_name_variable.'</textarea>';			
-					$obj_button='<button class="save" type="button" name="btn|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$name_variable.'"  />'.get_lang('Save').'</button>';		
-							
+					//config buttons
+					$obj_text='<textarea rows="10" cols="40" name="txt|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="txtid_'.$name_variable.'" >'.$sub_language_name_variable.'</textarea>';
+					$obj_button='<button class="save" type="button" name="btn|'.$name_variable.'|'.$language_files_to_load_keys[$lang_file].'" id="btnid_'.$name_variable.'"  />'.get_lang('Save').'</button>';
+
 					//loading variable from the english array
-					$english_name_variable = $english_language_array[$lang_file][$name_variable];		
-					$list_info[]=array($lang_file.'.inc.php', 
+					$english_name_variable = $english_language_array[$lang_file][$name_variable];
+					$list_info[]=array($lang_file.'.inc.php',
 									   $name_variable,
 									   $english_name_variable,
 									   $parent_variable_value,$obj_text,$obj_button);
-				}				
+				}
 			}
 		}
 	}
 
 	$list_info = array_unique_dimensional($list_info);
-	return $list_info;	
+	return $list_info;
 }
 
 //allow see data in sortetable
-if (isset($_REQUEST['txt_search_word'])) {	
+if (isset($_REQUEST['txt_search_word'])) {
 	//@todo fix to accept a char with 1 char
-	if (strlen(trim($_REQUEST['txt_search_word']))>2) {	
+	if (strlen(trim($_REQUEST['txt_search_word']))>2) {
 		$list_info = search_language_term($_REQUEST['txt_search_word'],true, true, true,true);
 	}
 }
@@ -272,7 +272,7 @@ $parameters=array('id'=>intval($_GET['id']),'sub_language_id'=>intval($_GET['sub
 $table = new SortableTableFromArrayConfig($list_info, 1,20,'data_info');
 $table->set_additional_parameters($parameters);
 //$table->set_header(0, '');
-$table->set_header(0, get_lang('LanguageFile'));	
+$table->set_header(0, get_lang('LanguageFile'));
 $table->set_header(1, get_lang('LanguageVariable'));
 $table->set_header(2, get_lang('EnglishName'));
 $table->set_header(3, get_lang('OriginalName'));
@@ -283,9 +283,9 @@ $table->display();
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
-		
+
 Display :: display_footer();
 ?>

+ 41 - 41
main/admin/sub_language_add.php

@@ -15,14 +15,14 @@ $this_section=SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
 
 /*
-============================================================================== 
+==============================================================================
 		MAIN CODE
-============================================================================== 
+==============================================================================
 */
 // setting the name of the tool
 $tool_name = get_lang('CreateSubLanguage');
 
-// setting breadcrumbs  
+// setting breadcrumbs
 $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array ('url' => 'languages.php', 'name' => get_lang('PlatformLanguages'));
 
@@ -58,18 +58,18 @@ function check_if_language_exist ($original_name,$english_name,$isocode,$sublang
 	if ($count_original_name==1) {
 		$has_error=true;
 		$message_information['original_name']=true;
-	} 
+	}
 	if ($count_english_name==1) {
 		$has_error=true;
 		$message_information['english_name']=true;
-	} 
+	}
 	if ($count_isocode==1) {
 		$has_error=true;
 		$message_information['isocode']=true;
-	} 
+	}
 	if ($has_error===true) {
 		$message_information['execute_add']=false;
-	} 
+	}
 	if ($has_error===false) {
 		$message_information['execute_add']=true;
 	}
@@ -87,7 +87,7 @@ function get_name_of_language_by_id ($language_id) {
  * check if language exist by id
  */
 function check_if_exist_language_by_id ($language_id) {
-	return SubLanguageManager::check_if_exist_language_by_id($language_id); 
+	return SubLanguageManager::check_if_exist_language_by_id($language_id);
 }
 /**
  * check if is parent of sub-language
@@ -96,20 +96,20 @@ function ckeck_if_is_parent_of_sub_language ($parent_id) {
 	$sql='SELECT count(*) AS count FROM language WHERE parent_id="'.Database::escape_string($parent_id).'"';
 	$rs=Database::query($sql,__FILE__,__LINE__);
 	if (Database::num_rows($rs)>0 && Database::result($rs,0,'count')==1) {
-		return true;	
+		return true;
 	} else {
 		return false;
-	}	
+	}
 }
 /**
  * Get all information of sub-language
  */
 function allow_get_all_information_of_sub_language ($parent_id,$sub_language_id) {
-	return SubLanguageManager::get_all_information_of_sub_language($parent_id,$sub_language_id); 
+	return SubLanguageManager::get_all_information_of_sub_language($parent_id,$sub_language_id);
 }
 
 /**
- * Add directory for sub-language 
+ * Add directory for sub-language
  */
 function add_directory_of_sub_language ($path_sub_language) {
 	return SubLanguageManager::add_directory_of_sub_language($path_sub_language);
@@ -139,7 +139,7 @@ function remove_directory_of_sub_language ($path) {
 			return false;
 		}
 	}
-		
+
 }
 /*end declare functions*/
 
@@ -153,7 +153,7 @@ if (isset($_GET['sub_language_id']) && $_GET['sub_language_id']==strval(intval($
 		} else {
 			$sub_language_id_exist=false;
 		}
-		
+
 }
 
 if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
@@ -164,10 +164,10 @@ if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
 		} else {
 			$language_id_exist=false;
 		}
-		
+
 } else {
 	$language_name='';
-	$language_id_exist=false;	
+	$language_id_exist=false;
 }
 
 //removed and register
@@ -178,8 +178,8 @@ if ((isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) && (isset($
 		$original_name=$get_all_information['original_name'];
 		$english_name=$get_all_information['english_name'];
 		$isocode=$get_all_information['isocode'];
-		
-	} 
+
+	}
 }
 
 $language_name=get_lang('CreateSubLanguageForLanguage').' ( '.strtolower($language_name).' )';
@@ -196,9 +196,9 @@ if (isset($_POST['SubmitAddNewLanguage'])) {
 	$isocode=$_POST['isocode'];
 	$english_name=str_replace(' ','_',$english_name);
 	$isocode=str_replace(' ','_',$isocode);
-			
+
 	$sublanguage_available=$_POST['sub_language_is_visible'];
-	$check_information=array();	
+	$check_information=array();
 	$check_information=check_if_language_exist($original_name,$english_name,$isocode,$sublanguage_available);
 	foreach ($check_information as $index_information => $value_information) {
 		$allow_insert_info=false;
@@ -206,38 +206,38 @@ if (isset($_POST['SubmitAddNewLanguage'])) {
 			Display::display_error_message(get_lang('AlreadyExists').' "'.get_lang('OriginalName').'" '.'('.$original_name.')');
 		}
 		if ($index_information=='english_name') {
-			Display::display_error_message(get_lang('AlreadyExists').' "'.get_lang('EnglishName').'" '.'('.$english_name.')');			
+			Display::display_error_message(get_lang('AlreadyExists').' "'.get_lang('EnglishName').'" '.'('.$english_name.')');
 		}
 		if ($index_information=='isocode') {
-			Display::display_error_message(get_lang('AlreadyExists').' "'.get_lang('PlatformCharsetTitle').'" '.'('.$isocode.')');			
-		}	
+			Display::display_error_message(get_lang('AlreadyExists').' "'.get_lang('PlatformCharsetTitle').'" '.'('.$isocode.')');
+		}
 		if ($index_information=='execute_add' && $value_information===true) {
 			$allow_insert_info=true;
 		}
 
 	}
-	
+
 	if (strlen($original_name)>0 && strlen($english_name)>0 && strlen($isocode)>0) {
 		if ($allow_insert_info===true && $language_id_exist===true) {
 			$english_name=str_replace(' ','_',$english_name);
-			$isocode=str_replace(' ','_',$isocode);			
+			$isocode=str_replace(' ','_',$isocode);
 			$str_info='<br/>'.get_lang('OriginalName').' : '.$original_name.'<br/>'.get_lang('EnglishName').' : '.$english_name.'<br/>'.get_lang('PlatformCharsetTitle').' : '.$isocode;
 			$path=api_get_path('SYS_LANG_PATH').$english_name;
-			
+
 			$mkdir_result=add_directory_of_sub_language($path);
 			if ($mkdir_result===true) {
 			  	add_sub_language($original_name,$english_name,$isocode,$sublanguage_available,$parent_id);
 			  	Display::display_confirmation_message(get_lang('TheNewSubLanguageHasBeenAdd').$str_info,false);
 			} else {
-				  Display::display_error_message(get_lang('LanguageDirectoryNotWriteableContactAdmin'));			
+				  Display::display_error_message(get_lang('LanguageDirectoryNotWriteableContactAdmin'));
 			}
 		} else {
 			if ($language_id_exist===false) {
-				Display::display_error_message(get_lang('LanguageParentNotExist'));	
-			}	
+				Display::display_error_message(get_lang('LanguageParentNotExist'));
+			}
 		}
 	} else {
-			Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));		
+			Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'));
 	}
 }
 if (isset($_POST['SubmitAddDeleteLanguage'])) {
@@ -248,7 +248,7 @@ if (isset($_POST['SubmitAddDeleteLanguage'])) {
 			SubLanguageManager::removed_sub_language($parent_id,$sub_language_id);
 			Display::display_confirmation_message(get_lang('TheSubLanguageHasBeenRemoved'));
 		}
-		
+
 	}
 }
      // ckeck_if_is_parent_of_sub_language($parent_id)===false
@@ -257,14 +257,14 @@ if (isset($_POST['SubmitAddDeleteLanguage'])) {
 		$text=$language_name;
 		$form = new FormValidator('addsublanguage', 'post', 'sub_language_add.php?id='.Security::remove_XSS($_GET['id']).'&action=definenewsublanguage');
 		$class='add';
-		$form->addElement('header', '', $text);			
+		$form->addElement('header', '', $text);
 		$form->addElement('text', 'original_name', get_lang('OriginalName'),'class="input_titles"');
-		$form->addRule('original_name', get_lang('ThisFieldIsRequired'), 'required');	
+		$form->addRule('original_name', get_lang('ThisFieldIsRequired'), 'required');
 		$form->addElement('text', 'english_name', get_lang('EnglishName'),'class="input_titles"');
-		$form->addRule('english_name', get_lang('ThisFieldIsRequired'), 'required');	
+		$form->addRule('english_name', get_lang('ThisFieldIsRequired'), 'required');
 		$form->addElement('text', 'isocode', get_lang('PlatformCharsetTitle'),'class="input_titles"');
-		$form->addRule('isocode', get_lang('ThisFieldIsRequired'), 'required');	
-		$form->addElement('checkbox', 'sub_language_is_visible', '', get_lang('Visibility'));	
+		$form->addRule('isocode', get_lang('ThisFieldIsRequired'), 'required');
+		$form->addElement('checkbox', 'sub_language_is_visible', '', get_lang('Visibility'));
 		$form->addElement('style_submit_button', 'SubmitAddNewLanguage', get_lang('CreateSubLanguage'), 'class="'.$class.'"');
 		$form->display();
 	} else {
@@ -275,19 +275,19 @@ if (isset($_POST['SubmitAddDeleteLanguage'])) {
 			$form->addElement('header', '', $text);
 			$form->addElement('static', '', get_lang('OriginalName'),$original_name);
 			$form->addElement('static', '', get_lang('EnglishName'),$english_name);
-			$form->addElement('static', '', get_lang('PlatformCharsetTitle'),$isocode);				
+			$form->addElement('static', '', get_lang('PlatformCharsetTitle'),$isocode);
 			$form->addElement('style_submit_button', 'SubmitAddDeleteLanguage', get_lang('DeleteSubLanguage'), 'class="'.$class.'"');
-			$form->display();		
+			$form->display();
 		}
 		if (isset($_GET['action']) && $_GET['action']=='definenewsublanguage') {
 			Display::display_normal_message(get_lang('TheSubLanguageForThisLanguageHasBeenAdd'));
 		}
 	}
-	
+
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
-*/	
+*/
 Display :: display_footer();
 ?>

+ 5 - 5
main/admin/sub_language_ajax.inc.php

@@ -8,22 +8,22 @@ require_once 'sub_language.class.php';
  */
 global $charset;
 
-$new_language		= Security::remove_XSS($_REQUEST['new_language']); 
+$new_language		= Security::remove_XSS($_REQUEST['new_language']);
 $language_variable	= Security::remove_XSS($_REQUEST['variable_language']);
 $file_id			= Security::remove_XSS($_REQUEST['file_id']);
 
 if (isset($new_language) && isset($language_variable) && isset($file_id)) {
-	$file_language = $language_files_to_load[$file_id].'.inc.php';	
+	$file_language = $language_files_to_load[$file_id].'.inc.php';
 	$id_language = intval($_REQUEST['id']);
-	$sub_language_id = intval($_REQUEST['sub']);	 
+	$sub_language_id = intval($_REQUEST['sub']);
 	$all_data_of_language=SubLanguageManager::get_all_information_of_sub_language($id_language,$sub_language_id);
 	$dokeos_path_folder=api_get_path('SYS_LANG_PATH').$all_data_of_language['dokeos_folder'].'/'.$file_language;
 	$all_file_of_directory=SubLanguageManager::get_all_language_variable_in_file($dokeos_path_folder);
 	SubLanguageManager::add_file_in_language_directory ($dokeos_path_folder);
-	
+
 	//update variable language
 	$all_file_of_directory[$language_variable]="\"".mb_convert_encoding($new_language,$charset,'UTF-8')."\";";
-	
+
 	foreach ($all_file_of_directory as $key_value=>$value_info) {
 		SubLanguageManager::write_data_in_file ($dokeos_path_folder,$value_info,$key_value);
 	}

+ 7 - 7
main/admin/subscribe_class2course.php

@@ -24,9 +24,9 @@
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 // name of the language file that needs to be included
 $language_file = 'admin';
@@ -73,7 +73,7 @@ if ($_POST['formSent'])
 		{
 			Display::display_error_message(get_lang('AtLeastOneClassAndOneCourse'));
 		}
-		elseif (api_substr($_POST['formSubmit'], -2) == '>>') // add classes to courses 
+		elseif (api_substr($_POST['formSubmit'], -2) == '>>') // add classes to courses
 		{
 			foreach ($courses as $course_code)
 			{
@@ -106,7 +106,7 @@ $result = api_sql_query($sql, __FILE__, __LINE__);
 $db_courses = api_store_result($result);
 if (!empty ($error_message))
 {
-	Display :: display_normal_message($error_message); 
+	Display :: display_normal_message($error_message);
 }
 ?>
 <form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
@@ -116,7 +116,7 @@ if (!empty ($error_message))
    <td width="40%" align="center">
     <b><?php echo get_lang('ClassList'); ?></b>
     <br/><br/>
-    <?php echo get_lang('FirstLetterClass'); ?> : 
+    <?php echo get_lang('FirstLetterClass'); ?> :
     <select name="firstLetterClass" onchange="javascript:document.formulaire.formSent.value='2'; document.formulaire.submit();">
      <option value="">--</option>
      <?php
@@ -128,7 +128,7 @@ if (!empty ($error_message))
    <td width="40%" align="center">
     <b><?php echo get_lang('CourseList'); ?> :</b>
     <br/><br/>
-    <?php echo get_lang('FirstLetterCourse'); ?> : 
+    <?php echo get_lang('FirstLetterCourse'); ?> :
     <select name="firstLetterCourse" onchange="javascript:document.formulaire.formSent.value='2'; document.formulaire.submit();">
      <option value="">--</option>
      <?php
@@ -173,7 +173,7 @@ foreach ($db_courses as $course)
 <?php
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 10 - 7
main/admin/subscribe_user2class.php

@@ -23,9 +23,9 @@
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 // name of the language file that needs to be included
 $language_file = 'admin';
@@ -34,7 +34,10 @@ $cidReset = true;
 
 require ('../inc/global.inc.php');
 require_once (api_get_path(LIBRARY_PATH).'classmanager.lib.php');
+
+$this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
+
 $course = $_GET['course'];
 $class_id = intval($_GET['idclass']);
 $form_sent = 0;
@@ -119,7 +122,7 @@ $result = api_sql_query($sql, __FILE__, __LINE__);
 $right_users = api_store_result($result);
 if (!empty ($error_message))
 {
-	Display :: display_normal_message($error_message); 
+	Display :: display_normal_message($error_message);
 }
 ?>
 <form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?course=<?php echo urlencode($course); ?>&amp;idclass=<?php echo $class_id; ?>" style="margin:0px;">
@@ -129,19 +132,19 @@ if (!empty ($error_message))
    <td width="40%" align="center">
     <b><?php echo get_lang('UsersOutsideClass'); ?> :</b>
     <br/><br/>
-    <?php echo get_lang('FirstLetterUser'); ?> : 
+    <?php echo get_lang('FirstLetterUser'); ?> :
     <select name="firstLetterLeft" onchange="javascript:document.formulaire.formSent.value='2'; document.formulaire.submit();">
      <option value="">--</option>
       <?php
       echo Display :: get_alphabet_options($first_letter_left);
-      ?>  
+      ?>
     </select>
    </td>
    <td width="20%">&nbsp;</td>
    <td width="40%" align="center">
     <b><?php echo get_lang('UsersInsideClass'); ?> :</b>
     <br/><br/>
-    <?php echo get_lang('FirstLetterUser'); ?> : 
+    <?php echo get_lang('FirstLetterUser'); ?> :
     <select name="firstLetterRight" onchange="javascript:document.formulaire.formSent.value='2'; document.formulaire.submit();">
      <option value="">--</option>
 <?php
@@ -186,7 +189,7 @@ foreach ($right_users as $user)
 <?php
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 65 - 64
main/admin/subscribe_user2course.php

@@ -3,28 +3,28 @@
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
-	
+
 	Copyright (c) 2004-2009 Dokeos SPRL
 	Copyright (c) 2003 Ghent University (UGent)
 	Copyright (c) 2001 Universite catholique de Louvain (UCL)
 	Copyright (c) Olivier Brouckaert
-	
+
 	For a full list of contributors, see "credits.txt".
 	The full license can be read in "license.txt".
-	
+
 	This program is free software; you can redistribute it and/or
 	modify it under the terms of the GNU General Public License
 	as published by the Free Software Foundation; either version 2
 	of the License, or (at your option) any later version.
-	
+
 	See the GNU General Public License for more details.
-	
+
 	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 *	This script allows platform admins to add users to courses.
 *	It displays a list of users and a list of courses;
 *	you can select multiple users and courses and then click on
@@ -32,7 +32,7 @@
 *
 *	@package dokeos.admin
 * 	@todo use formvalidator for the form
-============================================================================== 
+==============================================================================
 */
 
 /*
@@ -53,8 +53,9 @@ require_once(api_get_path(LIBRARY_PATH).'course.lib.php');
 require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
 include_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
 
-// security
+$this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
+
 /*
 -----------------------------------------------------------
 	Global constants and variables
@@ -84,14 +85,14 @@ $htmlHeadXtra[] = '
 <script type="text/javascript">
 
 function validate_filter() {
-	
-		document.formulaire.form_sent.value=0;				
+
+		document.formulaire.form_sent.value=0;
 		document.formulaire.submit();
-		
+
 }
-			
 
-	
+
+
 </script>';
 
 // displaying the header
@@ -121,7 +122,7 @@ if (is_array($extra_field_list)) {
 			$new_field_list[] = array('name'=> $extra_field[3], 'variable'=>$extra_field[1], 'data'=> $extra_field[9]);
 		}
 	}
-}	
+}
 
 
 /*
@@ -137,7 +138,7 @@ if ($_POST['form_sent']) {
 	$first_letter_course = $_POST['firstLetterCourse'];
 
 	foreach ($users as $key => $value) {
-		$users[$key] = intval($value);	
+		$users[$key] = intval($value);
 	}
 
 	if ($form_sent == 1) {
@@ -163,7 +164,7 @@ if(empty($first_letter_user)) {
 	$sql = "SELECT count(*) as nb_users FROM $tbl_user";
 	$result = api_sql_query($sql, __FILE__, __LINE__);
 	$num_row = Database::fetch_array($result);
-	if($num_row['nb_users']>1000) 
+	if($num_row['nb_users']>1000)
 	{//if there are too much users to gracefully handle with the HTML select list,
 	 // assign a default filter on users names
 		$first_letter_user = 'A';
@@ -172,50 +173,50 @@ if(empty($first_letter_user)) {
 }
 
 //Filter by Extra Fields
-$use_extra_fields = false;		
+$use_extra_fields = false;
 if (is_array($extra_field_list)) {
-	if (is_array($new_field_list) && count($new_field_list)>0 ) {			
+	if (is_array($new_field_list) && count($new_field_list)>0 ) {
 		$result_list=array();
 		foreach ($new_field_list as $new_field) {
-			$varname = 'field_'.$new_field['variable'];				
+			$varname = 'field_'.$new_field['variable'];
 			if (Usermanager::is_extra_field_available($new_field['variable'])) {
-				if (isset($_POST[$varname]) && $_POST[$varname]!='0') {		
-					$use_extra_fields = true;																	
+				if (isset($_POST[$varname]) && $_POST[$varname]!='0') {
+					$use_extra_fields = true;
 					$extra_field_result[]= Usermanager::get_extra_user_data_by_value($new_field['variable'], $_POST[$varname]);
-				}								
+				}
 			}
-		}									
+		}
 	}
-}	
+}
 
 if ($use_extra_fields) {
 	$final_result = array();
 	if (count($extra_field_result)>1) {
 		for($i=0;$i<count($extra_field_result)-1;$i++) {
 			if (is_array($extra_field_result[$i+1])) {
-				$final_result  = array_intersect($extra_field_result[$i],$extra_field_result[$i+1]);				
+				$final_result  = array_intersect($extra_field_result[$i],$extra_field_result[$i+1]);
 			}
 		}
-	} else {				
+	} else {
 		$final_result = $extra_field_result[0];
 	}
-			
+
 	$where_filter ='';
 	if ($_configuration['multiple_access_urls']==true) {
 		if (is_array($final_result) && count($final_result)>0) {
 			$where_filter = " AND u.user_id IN  ('".implode("','",$final_result)."') ";
 		} else {
 			//no results
-			$where_filter = " AND u.user_id  = -1"; 
+			$where_filter = " AND u.user_id  = -1";
 		}
-	} else {			
+	} else {
 		if (is_array($final_result) && count($final_result)>0) {
 			$where_filter = " AND user_id IN  ('".implode("','",$final_result)."') ";
 		} else {
 			//no results
-			$where_filter = " AND user_id  = -1"; 
+			$where_filter = " AND user_id  = -1";
 		}
-	}		
+	}
 }
 
 $target_name = api_sort_by_first_name() ? 'firstname' : 'lastname';
@@ -224,16 +225,16 @@ $sql = "SELECT user_id,lastname,firstname,username
 		WHERE user_id<>2 AND ".$target_name." LIKE '".$first_letter_user."%' $where_filter
 		ORDER BY ". (count($users) > 0 ? "(user_id IN(".implode(',', $users).")) DESC," : "")." ".$target_name;
 
-global $_configuration;	
-if ($_configuration['multiple_access_urls']==true) {	
-	$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+global $_configuration;
+if ($_configuration['multiple_access_urls']==true) {
+	$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 	$access_url_id = api_get_current_access_url_id();
-	if ($access_url_id != -1){		
-		$sql = "SELECT u.user_id,lastname,firstname,username  FROM ".$tbl_user ." u 			
-		INNER JOIN $tbl_user_rel_access_url user_rel_url 
-		ON (user_rel_url.user_id = u.user_id)						
+	if ($access_url_id != -1){
+		$sql = "SELECT u.user_id,lastname,firstname,username  FROM ".$tbl_user ." u
+		INNER JOIN $tbl_user_rel_access_url user_rel_url
+		ON (user_rel_url.user_id = u.user_id)
 		WHERE u.user_id<>2 AND access_url_id =  $access_url_id AND (".$target_name." LIKE '".$first_letter_user."%' ) $where_filter
-		ORDER BY ". (count($users) > 0 ? "(u.user_id IN(".implode(',', $users).")) DESC," : "")." ".$target_name;			
+		ORDER BY ". (count($users) > 0 ? "(u.user_id IN(".implode(',', $users).")) DESC," : "")." ".$target_name;
 	}
 }
 
@@ -243,38 +244,38 @@ unset($result);
 
 $sql = "SELECT code,visual_code,title FROM $tbl_course WHERE visual_code LIKE '".$first_letter_course."%' ORDER BY ". (count($courses) > 0 ? "(code IN('".implode("','", $courses)."')) DESC," : "")." visual_code";
 
-if ($_configuration['multiple_access_urls']==true) {	
-	$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);	
+if ($_configuration['multiple_access_urls']==true) {
+	$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 	$access_url_id = api_get_current_access_url_id();
-	if ($access_url_id != -1){			
-		$sql = "SELECT code, visual_code, title 
-				FROM $tbl_course as course			
+	if ($access_url_id != -1){
+		$sql = "SELECT code, visual_code, title
+				FROM $tbl_course as course
 		  		INNER JOIN $tbl_course_rel_access_url course_rel_url
-				ON (course_rel_url.course_code= course.code)	  	
-		  		WHERE access_url_id =  $access_url_id  AND (visual_code LIKE '".$first_letter_course."%' ) ORDER BY ". (count($courses) > 0 ? "(code IN('".implode("','", $courses)."')) DESC," : "")." visual_code";		  				  			
+				ON (course_rel_url.course_code= course.code)
+		  		WHERE access_url_id =  $access_url_id  AND (visual_code LIKE '".$first_letter_course."%' ) ORDER BY ". (count($courses) > 0 ? "(code IN('".implode("','", $courses)."')) DESC," : "")." visual_code";
 	}
 }
-	
+
 $result = api_sql_query($sql, __FILE__, __LINE__);
 $db_courses = api_store_result($result);
 unset($result);
 
-if ($_configuration['multiple_access_urls']==true) {	
-	$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);	
+if ($_configuration['multiple_access_urls']==true) {
+	$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 	$access_url_id = api_get_current_access_url_id();
-	if ($access_url_id != -1){			
+	if ($access_url_id != -1){
 		$sqlNbCours = "	SELECT course_rel_user.course_code, course.title
 			FROM $tbl_course_user as course_rel_user
 			INNER JOIN $tbl_course as course
 			ON course.code = course_rel_user.course_code
 		  	INNER JOIN $tbl_course_rel_access_url course_rel_url
-			ON (course_rel_url.course_code= course.code)	  	
+			ON (course_rel_url.course_code= course.code)
 		  	WHERE access_url_id =  $access_url_id  AND course_rel_user.user_id='".$_user['user_id']."' AND course_rel_user.status='1'
-		  	ORDER BY course.title";		  			
+		  	ORDER BY course.title";
 	}
 }
 
-	
+
 ?>
 
 <form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
@@ -285,24 +286,24 @@ if (is_array($extra_field_list)) {
 		echo '<h3>'.get_lang('FilterUsers').'</h3>';
 		foreach ($new_field_list as $new_field) {
 			echo $new_field['name'];
-			$varname = 'field_'.$new_field['variable'];						
+			$varname = 'field_'.$new_field['variable'];
 			echo '&nbsp;<select name="'.$varname.'">';
-			echo '<option value="0">--'.get_lang('Select').'--</option>';	
+			echo '<option value="0">--'.get_lang('Select').'--</option>';
 			foreach	($new_field['data'] as $option) {
 				$checked='';
 				if (isset($_POST[$varname])) {
 					if ($_POST[$varname]==$option[1]) {
-						$checked = 'selected="true"'; 
+						$checked = 'selected="true"';
 					}
-				}							
-				echo '<option value="'.$option[1].'" '.$checked.'>'.$option[1].'</option>';		
+				}
+				echo '<option value="'.$option[1].'" '.$checked.'>'.$option[1].'</option>';
 			}
-			echo '</select>';	
+			echo '</select>';
 			echo '&nbsp;&nbsp;';
 		}
 		echo '<input type="button" value="'.get_lang('Filter').'" onclick="validate_filter()" />';
 		echo '<br /><br />';
-	}	
+	}
 }
 
 ?>
@@ -314,7 +315,7 @@ if (is_array($extra_field_list)) {
     <td width="40%" align="center">
      <b><?php echo get_lang('UserList'); ?></b>
      <br/><br/>
-     <?php echo get_lang('FirstLetterUser'); ?> : 
+     <?php echo get_lang('FirstLetterUser'); ?> :
      <select name="firstLetterUser" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
       <option value="">--</option>
       <?php
@@ -326,12 +327,12 @@ if (is_array($extra_field_list)) {
     <td width="40%" align="center">
      <b><?php echo get_lang('CourseList'); ?> :</b>
      <br/><br/>
-     <?php echo get_lang('FirstLetterCourse'); ?> : 
+     <?php echo get_lang('FirstLetterCourse'); ?> :
      <select name="firstLetterCourse" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
       <option value="">--</option>
       <?php
       echo Display :: get_alphabet_options($first_letter_course);
-      ?> 
+      ?>
      </select>
     </td>
    </tr>
@@ -367,7 +368,7 @@ if (is_array($extra_field_list)) {
 <?php
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
 */
 Display :: display_footer();

+ 6 - 6
main/admin/system_announcements.php

@@ -168,7 +168,7 @@ if ($action_todo)
 	} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
 		$form_title = get_lang('EditNews');
 	}
-	
+
 	$form = new FormValidator('system_announcement');
 	$form->addElement('header', '', $form_title);
 	$form->add_textfield('title', get_lang('Title'));
@@ -188,21 +188,21 @@ if ($action_todo)
 	$form->add_timewindow('start','end',get_lang('StartTimeWindow'),get_lang('EndTimeWindow'));
 	$form->addElement('checkbox', 'visible_teacher', get_lang('Visible'), get_lang('Teacher'));
 	$form->addElement('checkbox', 'visible_student', null, get_lang('Student'));
-	$form->addElement('checkbox', 'visible_guest', null, get_lang('Guest'));	
+	$form->addElement('checkbox', 'visible_guest', null, get_lang('Guest'));
 	$form->addElement('hidden', 'id');
 	$form->addElement('checkbox', 'send_mail', get_lang('SendMail'));
-	
+
 	if (isset($_REQUEST['action']) && $_REQUEST['action']=='add') {
 		$text=get_lang('AddNews');
 		$class='add';
 		$form->addElement('hidden', 'action','add');
-		
+
 	} elseif (isset($_REQUEST['action']) && $_REQUEST['action']=='edit') {
 		$text=get_lang('EditNews');
 		$class='save';
 		$form->addElement('hidden', 'action','edit');
 	}
-	
+
 	$form->addElement('style_submit_button', 'submit', $text,'class="'.$class.'"');
 	if (api_get_setting('wcag_anysurfer_public_pages')=='true')
 	{
@@ -239,7 +239,7 @@ if ($action_todo)
 				{
 					Display :: display_normal_message(get_lang('AnnouncementAdded'));
 				}
-				else 
+				else
 				{
 					$show_announcement_list = false;
 					$form->display();

+ 183 - 228
main/admin/user_add.php

@@ -5,24 +5,26 @@
 *	@package dokeos.admin
 ==============================================================================
 */
-// name of the language file that needs to be included
-$language_file = array('admin','registration');
+
+// Language files that should be included
+$language_file = array('admin', 'registration');
+
 $cidReset = true;
 
-// including necessary libraries
+// Including necessary libraries.
 require '../inc/global.inc.php';
 $libpath = api_get_path(LIBRARY_PATH);
 require_once $libpath.'fileManage.lib.php';
 require_once $libpath.'fileUpload.lib.php';
 require_once $libpath.'usermanager.lib.php';
 require_once $libpath.'formvalidator/FormValidator.class.php';
-require_once api_get_path(LIBRARY_PATH).'image.lib.php';
-require_once api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php';
+require_once $libpath.'image.lib.php';
+require_once $libpath.'mail.lib.inc.php';
 
-// section for the tabs
-$this_section=SECTION_PLATFORM_ADMIN;
+// Section for the tabs
+$this_section = SECTION_PLATFORM_ADMIN;
 
-// user permissions
+// User permissions
 api_protect_admin_script();
 
 // Database table definitions
@@ -31,18 +33,18 @@ $table_user 	= Database :: get_main_table(TABLE_MAIN_USER);
 $database 		= Database::get_main_database();
 
 $htmlHeadXtra[] = '
-<script language="JavaScript" type="text/JavaScript">
+<script type="text/javascript">
 <!--
 function enable_expiration_date() { //v2.0
 	document.user_add.radio_expiration_date[0].checked=false;
 	document.user_add.radio_expiration_date[1].checked=true;
 }
 
-function password_switch_radio_button(form, input){
-	var NodeList = document.getElementsByTagName("input");
-	for(var i=0; i< NodeList.length; i++){
-		if(NodeList.item(i).name=="password[password_auto]" && NodeList.item(i).value=="0"){
-			NodeList.item(i).checked=true;
+function password_switch_radio_button() {
+	var input_elements = document.getElementsByTagName("input");
+	for (var i = 0; i < input_elements.length; i++) {
+		if (input_elements.item(i).name == "password[password_auto]" && input_elements.item(i).value == "0") {
+			input_elements.item(i).checked = true;
 		}
 	}
 }
@@ -54,7 +56,7 @@ function display_drh_list(){
 		document.getElementById("id_platform_admin").style.display="none";
 	}
 	else
-	{ 
+	{
 		document.getElementById("drh_list").style.display="none";
 		document.getElementById("id_platform_admin").style.display="block";
 		document.getElementById("drh_select").options[0].selected="selected";
@@ -64,104 +66,99 @@ function display_drh_list(){
 //-->
 </script>';
 
-if(!empty($_GET['message'])){
+if (!empty($_GET['message'])) {
 	$message = urldecode($_GET['message']);
-}	
+}
 
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $tool_name = get_lang('AddUsers');
+
 // Create the form
 $form = new FormValidator('user_add');
 $form->addElement('header', '', $tool_name);
-if (api_is_western_name_order())
-{
+if (api_is_western_name_order()) {
 	// Firstname
-	$form->addElement('text','firstname',get_lang('FirstName'));
-	$form->applyFilter('firstname','html_filter');
-	$form->applyFilter('firstname','trim');
+	$form->addElement('text', 'firstname', get_lang('FirstName'));
+	$form->applyFilter('firstname', 'html_filter');
+	$form->applyFilter('firstname', 'trim');
 	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 	// Lastname
-	$form->addElement('text','lastname',get_lang('LastName'));
-	$form->applyFilter('lastname','html_filter');
-	$form->applyFilter('lastname','trim');
+	$form->addElement('text', 'lastname', get_lang('LastName'));
+	$form->applyFilter('lastname', 'html_filter');
+	$form->applyFilter('lastname', 'trim');
 	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
-}
-else
-{
+} else {
 	// Lastname
-	$form->addElement('text','lastname',get_lang('LastName'));
-	$form->applyFilter('lastname','html_filter');
-	$form->applyFilter('lastname','trim');
+	$form->addElement('text', 'lastname', get_lang('LastName'));
+	$form->applyFilter('lastname', 'html_filter');
+	$form->applyFilter('lastname', 'trim');
 	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
 	// Firstname
-	$form->addElement('text','firstname',get_lang('FirstName'));
-	$form->applyFilter('firstname','html_filter');
-	$form->applyFilter('firstname','trim');
+	$form->addElement('text', 'firstname', get_lang('FirstName'));
+	$form->applyFilter('firstname', 'html_filter');
+	$form->applyFilter('firstname', 'trim');
 	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 }
 // Official code
-$form->addElement('text', 'official_code', get_lang('OfficialCode'),array('size' => '40'));
-$form->applyFilter('official_code','html_filter');
-$form->applyFilter('official_code','trim');
+$form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => '40'));
+$form->applyFilter('official_code', 'html_filter');
+$form->applyFilter('official_code', 'trim');
 // Email
-$form->addElement('text', 'email', get_lang('Email'),array('size' => '40'));
+$form->addElement('text', 'email', get_lang('Email'), array('size' => '40'));
 $form->addRule('email', get_lang('EmailWrong'), 'email');
 $form->addRule('email', get_lang('EmailWrong'), 'required');
 // Phone
-$form->addElement('text','phone',get_lang('PhoneNumber'));
+$form->addElement('text', 'phone', get_lang('PhoneNumber'));
 // Picture
 $form->addElement('file', 'picture', get_lang('AddPicture'));
 $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
+
 $form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
 // Username
-$form->addElement('text', 'username', get_lang('LoginName'),array('maxlength'=>20));
+$form->addElement('text', 'username', get_lang('LoginName'), array('maxlength' => USERNAME_MAX_LENGTH));
 $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
 $form->addRule('username', get_lang('OnlyLettersAndNumbersAllowed'), 'username');
-$form->addRule('username', '', 'maxlength',20);
 $form->addRule('username', get_lang('UserTaken'), 'username_available', $user_data['username']);
 // Password
 $group = array();
 $auth_sources = 0; //make available wider as we need it in case of form reset (see below)
-if(count($extAuthSource) > 0)
-{
-	$group[] =& HTML_QuickForm::createElement('radio','password_auto',null,get_lang('ExternalAuthentication').' ',2);
+if (count($extAuthSource) > 0) {
+	$group[] =& HTML_QuickForm::createElement('radio', 'password_auto', null, get_lang('ExternalAuthentication').' ', 2);
 	$auth_sources = array();
-	foreach($extAuthSource as $key => $info)
-	{
+	foreach($extAuthSource as $key => $info) {
 		$auth_sources[$key] = $key;
 	}
-	$group[] =& HTML_QuickForm::createElement('select','auth_source',null,$auth_sources);
-	$group[] =& HTML_QuickForm::createElement('static','','','<br />');
+	$group[] =& HTML_QuickForm::createElement('select', 'auth_source', null, $auth_sources);
+	$group[] =& HTML_QuickForm::createElement('static', '', '', '<br />');
 }
-$group[] =& HTML_QuickForm::createElement('radio','password_auto',get_lang('Password'),get_lang('AutoGeneratePassword').'<br />',1);
-$group[] =& HTML_QuickForm::createElement('radio', 'password_auto','id="radio_user_password"',null,0);
-$group[] =& HTML_QuickForm::createElement('password', 'password',null,'onkeydown=password_switch_radio_button(document.user_add,"password[password_auto]")');
+$group[] =& HTML_QuickForm::createElement('radio', 'password_auto', get_lang('Password'), get_lang('AutoGeneratePassword').'<br />', 1);
+$group[] =& HTML_QuickForm::createElement('radio', 'password_auto', 'id="radio_user_password"', null, 0);
+$group[] =& HTML_QuickForm::createElement('password', 'password', null, array('onkeydown' => 'javascript: password_switch_radio_button();'));
 $form->addGroup($group, 'password', get_lang('Password'), '');
 
 // Status
 $status = array();
-$status[COURSEMANAGER]  = get_lang('Teacher');
+$status[COURSEMANAGER] = get_lang('Teacher');
 $status[STUDENT] = get_lang('Learner');
 $status[DRH] = get_lang('Drh');
 $status[SESSIONADMIN] = get_lang('SessionsAdmin');
 
-$form->addElement('select','status',get_lang('Status'),$status,'id="status_select" onchange="display_drh_list()"');
+$form->addElement('select', 'status', get_lang('Status'), $status, array('id' => 'status_select', 'onchange' => 'javascript: display_drh_list();'));
 $form->addElement('select_language', 'language', get_lang('Language'));
 //drh list (display only if student)
 $display = ($_POST['status'] == STUDENT || !isset($_POST['status'])) ? 'block' : 'none';
-$form->addElement('html','<div id="drh_list" style="display:'.$display.';">');
-$drh_select = $form->addElement('select','hr_dept_id',get_lang('Drh'),array(),'id="drh_select"');
-$drh_list = UserManager :: get_user_list(array('status'=>DRH),array('lastname','firstname'));
+$form->addElement('html', '<div id="drh_list" style="display:'.$display.';">');
+$drh_select = $form->addElement('select', 'hr_dept_id', get_lang('Drh'), array(), 'id="drh_select"');
+$drh_list = UserManager :: get_user_list(array('status' => DRH), api_sort_by_first_name() ? array('firstname', 'lastname') : array('lastname', 'firstname'));
 if (count($drh_list) == 0) {
-	$drh_select->addOption('- '.get_lang('ThereIsNotStillAResponsible').' -',0);	
+	$drh_select->addOption('- '.get_lang('ThereIsNotStillAResponsible', '').' -', 0);
 } else {
-	$drh_select->addOption('- '.get_lang('SelectAResponsible').' -',0);
+	$drh_select->addOption('- '.get_lang('SelectAResponsible').' -', 0);
 }
 
-if(is_array($drh_list))
-{
-	foreach($drh_list as $drh)
-	{
+if (is_array($drh_list)) {
+	foreach ($drh_list as $drh) {
 		$drh_select->addOption(api_get_person_name($drh['firstname'], $drh['lastname']), $drh['user_id']);
 	}
 }
@@ -169,36 +166,34 @@ $form->addElement('html', '</div>');
 
 // Platform admin
 $group = array();
-$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin','id="id_platform_admin"',get_lang('Yes'),1);
-$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin','id="id_platform_admin"',get_lang('No'),0);
+$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin', 'id="id_platform_admin"', get_lang('Yes'), 1);
+$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin', 'id="id_platform_admin"', get_lang('No'), 0);
 $display = ($_POST['status'] == STUDENT || !isset($_POST['status'])) ? 'none' : 'block';
-$form->addElement('html','<div id="id_platform_admin" style="display:'.$display.';">');
+$form->addElement('html', '<div id="id_platform_admin" style="display:'.$display.';">');
 $form->addGroup($group, 'admin', get_lang('PlatformAdmin'), '&nbsp;');
 $form->addElement('html', '</div>');
 // Send email
 $group = array();
-$group[] =& HTML_QuickForm::createElement('radio', 'send_mail',null,get_lang('Yes'),1);
-$group[] =& HTML_QuickForm::createElement('radio', 'send_mail',null,get_lang('No'),0);
+$group[] =& HTML_QuickForm::createElement('radio', 'send_mail', null, get_lang('Yes'), 1);
+$group[] =& HTML_QuickForm::createElement('radio', 'send_mail', null, get_lang('No'), 0);
 $form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;');
 // Expiration Date
 $form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
 $group = array ();
 $group[] = & $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
-$group[] = & $form->createElement('datepicker','expiration_date', null, array ('form_name' => $form->getAttribute('name'), 'onChange'=>'enable_expiration_date()'));
+$group[] = & $form->createElement('datepicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
 $form->addGroup($group, 'max_member_group', null, '', false);
 // Active account or inactive account
-$form->addElement('radio','active',get_lang('ActiveAccount'),get_lang('Active'),1);
-$form->addElement('radio','active','',get_lang('Inactive'),0);
+$form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);
+$form->addElement('radio', 'active', '', get_lang('Inactive'), 0);
 
 // EXTRA FIELDS
-$extra = UserManager::get_extra_fields(0,50,5,'ASC');
-$extra_data = UserManager::get_extra_user_data(0,true);
-
-foreach($extra as $id => $field_details)
-{	
-	if ($field_details[6]==1) { // only show extra fields that are visible
-		switch($field_details[2])
-		{
+$extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
+$extra_data = UserManager::get_extra_user_data(0, true);
+
+foreach($extra as $id => $field_details) {
+	if ($field_details[6] == 1) { // only show extra fields that are visible
+		switch ($field_details[2]) {
 			case USER_FIELD_TYPE_TEXT:
 				$form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 40));
 				$form->applyFilter('extra_'.$field_details[1], 'stripslashes');
@@ -212,129 +207,115 @@ foreach($extra as $id => $field_details)
 				break;
 			case USER_FIELD_TYPE_RADIO:
 				$group = array();
-				foreach($field_details[9] as $option_id => $option_details)
-				{
+				foreach ($field_details[9] as $option_id => $option_details) {
 					$options[$option_details[1]] = $option_details[2];
-					$group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1],$option_details[2].'<br />',$option_details[1]);
+					$group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1], $option_details[2].'<br />', $option_details[1]);
 				}
 				$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '');
 				break;
 			case USER_FIELD_TYPE_SELECT:
 				$options = array();
-				foreach($field_details[9] as $option_id => $option_details)
-				{
+				foreach($field_details[9] as $option_id => $option_details) {
 					$options[$option_details[1]] = $option_details[2];
 				}
-				$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,'');			
+				$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,'');
 				break;
 			case USER_FIELD_TYPE_SELECT_MULTIPLE:
 				$options = array();
-				foreach($field_details[9] as $option_id => $option_details)
-				{
+				foreach($field_details[9] as $option_id => $option_details) {
 					$options[$option_details[1]] = $option_details[2];
 				}
-				$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,array('multiple' => 'multiple'));
+				$form->addElement('select', 'extra_'.$field_details[1], $field_details[3], $options, array('multiple' => 'multiple'));
 				break;
 			case USER_FIELD_TYPE_DATE:
-				$form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3],array('form_name'=>'user_add'));
-				$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);
+				$form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3], array('form_name' => 'user_add'));
+				$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
 				$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
 				$form -> setDefaults($defaults);
 				$form->applyFilter('theme', 'trim');
 				break;
 			case USER_FIELD_TYPE_DATETIME:
-				$form->addElement('datepicker', 'extra_'.$field_details[1], $field_details[3],array('form_name'=>'user_add'));
-				$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);
+				$form->addElement('datepicker', 'extra_'.$field_details[1], $field_details[3], array('form_name' => 'user_add'));
+				$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
 				$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
 				$form -> setDefaults($defaults);
 				$form->applyFilter('theme', 'trim');
 				break;
 			case USER_FIELD_TYPE_DOUBLE_SELECT:
-				foreach ($field_details[9] as $key=>$element)
-				{
-					if ($element[2][0] == '*')
-					{
+				foreach ($field_details[9] as $key => $element) {
+					if ($element[2][0] == '*') {
 						$values['*'][$element[0]] = str_replace('*','',$element[2]);
-					}
-					else 
-					{
+					} else {
 						$values[0][$element[0]] = $element[2];
 					}
 				}
-				
-				$group='';
-				$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1],'',$values[0],'');
-				$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1].'*','',$values['*'],'');
+
+				$group = '';
+				$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1], '', $values[0], '');
+				$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1].'*', '', $values['*'], '');
 				$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '&nbsp;');
 				if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
-	
+
 				// recoding the selected values for double : if the user has selected certain values, we have to assign them to the correct select form
-				if (key_exists('extra_'.$field_details[1], $extra_data))
-				{
+				if (key_exists('extra_'.$field_details[1], $extra_data)) {
 					// exploding all the selected values (of both select forms)
-					$selected_values = explode(';',$extra_data['extra_'.$field_details[1]]);
-					$extra_data['extra_'.$field_details[1]]  =array();
-					
+					$selected_values = explode(';', $extra_data['extra_'.$field_details[1]]);
+					$extra_data['extra_'.$field_details[1]] = array();
+
 					// looping through the selected values and assigning the selected values to either the first or second select form
-					foreach ($selected_values as $key=>$selected_value)
-					{
-						if (key_exists($selected_value,$values[0]))
-						{
+					foreach ($selected_values as $key => $selected_value) {
+						if (key_exists($selected_value, $values[0])) {
 							$extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1]] = $selected_value;
-						}
-						else 
-						{
+						} else {
 							$extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1].'*'] = $selected_value;
 						}
 					}
 				}
 				break;
 			case USER_FIELD_TYPE_DIVIDER:
-				$form->addElement('static',$field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
+				$form->addElement('static', $field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
 				break;
 		}
 	}
 }
 
-
 // Set default values
 $defaults['admin']['platform_admin'] = 0;
 $defaults['mail']['send_mail'] = 1;
 $defaults['password']['password_auto'] = 1;
 $defaults['active'] = 1;
-$defaults['expiration_date']=array();
+$defaults['expiration_date'] = array();
 $days = api_get_setting('account_valid_duration');
 $time = strtotime('+'.$days.' day');
-$defaults['expiration_date']['d']=date('d',$time);
-$defaults['expiration_date']['F']=date('m',$time);
-$defaults['expiration_date']['Y']=date('Y',$time);
+$defaults['expiration_date']['d'] = date('d', $time);
+$defaults['expiration_date']['F'] = date('m', $time);
+$defaults['expiration_date']['Y'] = date('Y', $time);
 $defaults['radio_expiration_date'] = 0;
 $defaults['status'] = STUDENT;
-$defaults = array_merge($defaults,$extra_data);
+$defaults = array_merge($defaults, $extra_data);
 $form->setDefaults($defaults);
+
 // Submit button
 /*
-$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="add"') ;
+$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="add"');
 $form->addElement('style_submit_button', 'submit_plus', get_lang('Add').'+', 'class="add"');
 */
-$select_level = array (); 	
+$select_level = array ();
 $html_results_enabled[] = FormValidator :: createElement ('style_submit_button', 'submit_plus', get_lang('Add').'+', 'class="add"');
 $html_results_enabled[] = FormValidator :: createElement ('style_submit_button', 'submit', get_lang('Add'), 'class="add"');
 $form->addGroup($html_results_enabled);
 
 // Validate form
-if( $form->validate())
-{
+if( $form->validate()) {
 	$check = Security::check_token('post');
-	if($check)
-	{
+	if ($check) {
 		$user = $form->exportValues();
+
 		$picture_element = & $form->getElement('picture');
 		$picture = $picture_element->getValue();
+
 		$picture_uri = '';
-		if (strlen($picture['name']) > 0 ) {
-		$picture_uri = uniqid('').'_'.replace_dangerous_char($picture['name']);
-		}
+
 		$lastname = $user['lastname'];
 		$firstname = $user['firstname'];
 		$official_code = $user['official_code'];
@@ -347,130 +328,108 @@ if( $form->validate())
 		$platform_admin = intval($user['admin']['platform_admin']);
 		$send_mail = intval($user['mail']['send_mail']);
 		$hr_dept_id = intval($user['hr_dept_id']);
-		if(count($extAuthSource) > 0 && $user['password']['password_auto'] == '2')
-		{
+		if (count($extAuthSource) > 0 && $user['password']['password_auto'] == '2') {
 			$auth_source = $user['password']['auth_source'];
 			$password = 'PLACEHOLDER';
-		}
-		else
-		{
+		} else {
 			$auth_source = PLATFORM_AUTH_SOURCE;
 			$password = $user['password']['password_auto'] == '1' ? api_generate_password() : $user['password']['password'];
 		}
-		if ($user['radio_expiration_date']=='1' )
-		{
-			$expiration_date=$user['expiration_date'];
-		}
-		else
-		{
-			$expiration_date='0000-00-00 00:00:00';
+		if ($user['radio_expiration_date'] == '1') {
+			$expiration_date = $user['expiration_date'];
+		} else {
+			$expiration_date = '0000-00-00 00:00:00';
 		}
 		$active = intval($user['active']);
-	
-		$user_id = UserManager::create_user($firstname,$lastname,$status,$email,$username,$password,$official_code,$language,$phone,$picture_uri,$auth_source,$expiration_date,$active, $hr_dept_id);
-
-		// picture path
-		$picture_path = api_get_path(SYS_CODE_PATH).'upload/users/'.$user_id.'/';		
-
-		if (strlen($picture['name']) > 0 ) {			
-			if (!is_dir($picture_path)) {
-				if (mkdir($picture_path)) {
-					$perm = api_get_setting('permissions_for_new_directories');
-					$perm = octdec(!empty($perm)?$perm:'0770');					
-					chmod($picture_path,$perm);
-				}
+
+		$user_id = UserManager::create_user($firstname, $lastname, $status, $email, $username, $password, $official_code, $language, $phone, $picture_uri, $auth_source, $expiration_date, $active, $hr_dept_id);
+
+		if (!empty($picture['name'])) {
+
+			// picture path
+			if (api_get_setting('split_users_upload_directory') === 'true') {
+				$picture_path = api_get_path(SYS_CODE_PATH).'upload/users/'.substr((string)$user_id, 0, 1).'/'.$user_id.'/';
+			} else {
+				$picture_path = api_get_path(SYS_CODE_PATH).'upload/users/'.$user_id.'/';
+			}
+
+			$picture_uri = $user_id.'_'.uniqid('').'_'.replace_dangerous_char($picture['name']);
+
+			UserManager::update_user($user_id, $firstname, $lastname, $username, $password, $auth_source, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active, null, $hr_dept_id, null, $language);
+
+			$perm = api_get_setting('permissions_for_new_directories');
+			$perm = octdec(!empty($perm) ? $perm : '0770');
+			if (!file_exists($picture_path)) {
+				@mkdir($picture_path, $perm, true);
+			}
+
+			$picture_info = @getimagesize($_FILES['picture']['tmp_name']);
+			$type=$picture_info[2];
+			$small_picture = UserManager::resize_picture($_FILES['picture']['tmp_name'], 22);
+			$medium_picture = UserManager::resize_picture($_FILES['picture']['tmp_name'], 85);
+			$normal_picture = UserManager::resize_picture($_FILES['picture']['tmp_name'], 200);
+			$big_picture = new image($_FILES['picture']['tmp_name']); // This is the original picture.
+
+			$picture_types = array(1 => 'GIF', 2 => 'JPG', 3 => 'PNG');
+			if (in_array($type, array_keys($picture_types))) {
+				$small_picture->send_image($picture_types[$type], $picture_path.'small_'.$picture_uri);
+				$medium_picture->send_image($picture_types[$type], $picture_path.'medium_'.$picture_uri);
+				$normal_picture->send_image($picture_types[$type], $picture_path.$picture_uri);
+				$big_picture->send_image($picture_types[$type], $picture_path.'big_'.$picture_uri);
 			}
-			$picture_infos=@getimagesize($_FILES['picture']['tmp_name']);
-			$type=$picture_infos[2];
-			$small_temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 22); //small picture
-			$medium_temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 85); //medium picture
-			$temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 200); // normal picture
-			$big_temp = new image($_FILES['picture']['tmp_name']); // original picture
-			
-		    switch (!empty($type)) {
-			    case 2 :
-			    	$small_temp->send_image('JPG',$picture_path.'small_'.$picture_uri); 
-			    	$medium_temp->send_image('JPG',$picture_path.'medium_'.$picture_uri);
-			    	$temp->send_image('JPG',$picture_path.$picture_uri);
-			    	$big_temp->send_image('JPG',$picture_path.'big_'.$picture_uri);	    		 
-			    	break;
-			    case 3 :
-			    	$small_temp->send_image('PNG',$picture_path.'small_'.$picture_uri);
-			    	$medium_temp->send_image('PNG',$picture_path.'medium_'.$picture_uri);
-			    	$temp->send_image('PNG',$picture_path.$picture_uri);
-			    	$big_temp->send_image('PNG',$picture_path.'big_'.$picture_uri);
-			    	break;
-			    case 1 :
-			    	$small_temp->send_image('GIF',$picture_path.'small_'.$picture_uri);
-			    	$medium_temp->send_image('GIF',$picture_path.'medium_'.$picture_uri);
-			    	$temp->send_image('GIF',$picture_path.$picture_uri);
-			    	$big_temp->send_image('GIF',$picture_path.'big_'.$picture_uri);	    		 
-			    	break;
-		    }
 		}
-		
+
 		$extras = array();
-		foreach($user as $key => $value)
-		{
-			if(substr($key,0,6)=='extra_') //an extra field
-			{
-				$myres = UserManager::update_extra_field_value($user_id,substr($key,6),$value);
+		foreach($user as $key => $value) {
+			if (substr($key, 0, 6) == 'extra_') { //an extra field
+				$myres = UserManager::update_extra_field_value($user_id, substr($key, 6), $value);
 			}
 		}
-		
-		if ($platform_admin)
-		{
+
+		if ($platform_admin) {
 			$sql = "INSERT INTO $table_admin SET user_id = '".$user_id."'";
-			api_sql_query($sql,__FILE__,__LINE__);
+			Database::query($sql,__FILE__,__LINE__);
 		}
-		if (!empty ($email) && $send_mail)
-		{
+		if (!empty($email) && $send_mail) {
 			$recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
-			$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');			
-									
+			$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
+
 			$sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-		    $email_admin = api_get_setting('emailAdministrator');
-		    
-		    if ($_configuration['multiple_access_urls']==true) {
-				$access_url_id = api_get_current_access_url_id();				
-				if ($access_url_id != -1 ){
-					$url = api_get_access_url($access_url_id);					
-					$emailbody=get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
-				}		
+			$email_admin = api_get_setting('emailAdministrator');
+
+			if ($_configuration['multiple_access_urls'] == true) {
+				$access_url_id = api_get_current_access_url_id();
+				if ($access_url_id != -1) {
+					$url = api_get_access_url($access_url_id);
+					$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
+				}
 			}
 			else {
-				$emailbody=get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
+				$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
 			}
-					
-		    	
-			@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name,$email_admin);
+			@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
 		}
 		Security::clear_token();
-		if(isset($user['submit_plus']))
-		{
+		if (isset($user['submit_plus'])) {
 			//we want to add more. Prepare report message and redirect to the same page (to clean the form)
 			$tok = Security::get_token();
 			header('Location: user_add.php?message='.urlencode(get_lang('UserAdded')).'&sec_token='.$tok);
 			exit ();
-		}
-		else
-		{
-			$tok = Security::get_token();		
+		} else {
+			$tok = Security::get_token();
 			header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('UserAdded')).'&sec_token='.$tok);
 			exit ();
 		}
 	}
-}
-else
-{
-	if(isset($_POST['submit']))
-	{
+} else {
+	if (isset($_POST['submit'])) {
 		Security::clear_token();
 	}
 	$token = Security::get_token();
-	$form->addElement('hidden','sec_token');
+	$form->addElement('hidden', 'sec_token');
 	$form->setConstants(array('sec_token' => $token));
 }
+
 // Display form
 Display::display_header($tool_name);
 //api_display_tool_title($tool_name);
@@ -478,10 +437,6 @@ if(!empty($message)){
 	Display::display_normal_message(stripslashes($message));
 }
 $form->display();
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
+
+// Footer
 Display::display_footer();
-?>

+ 219 - 283
main/admin/user_edit.php

@@ -1,46 +1,37 @@
 <?php // $Id: user_edit.php 22233 2009-07-20 09:54:05Z ivantcholakov $
-/*
-==============================================================================
-	Dokeos - elearning and course management software
-
-	Copyright (c) 2004-2008 Dokeos SPRL
-	Copyright (c) 2003 Ghent University (UGent)
-	Copyright (c) 2001 Universite catholique de Louvain (UCL)
-	Copyright (c) Olivier Brouckaert
-	Copyright (c) Bart Mollet, Hogeschool Gent
-
-	For a full list of contributors, see "credits.txt".
-	The full license can be read in "license.txt".
-
-	This program is free software; you can redistribute it and/or
-	modify it under the terms of the GNU General Public License
-	as published by the Free Software Foundation; either version 2
-	of the License, or (at your option) any later version.
-
-	See the GNU General Public License for more details.
-
-	Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
-==============================================================================
-*/
+/* For licensing terms, see /dokeos_license.txt */
 /**
 ==============================================================================
 *	@package dokeos.admin
 ==============================================================================
 */
-// name of the language file that needs to be included
-$language_file=array('admin','registration');
-$cidReset=true;
-include('../inc/global.inc.php');
-$this_section=SECTION_PLATFORM_ADMIN;
+
+// Language files that should be included
+$language_file = array('admin', 'registration');
+
+$cidReset = true;
+
+include '../inc/global.inc.php';
+
+$this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 
 $htmlHeadXtra[] = '
-<script language="JavaScript" type="text/JavaScript">
+<script type="text/javascript">
 <!--
 function enable_expiration_date() { //v2.0
-	document.user_add.radio_expiration_date[0].checked=false;
-	document.user_add.radio_expiration_date[1].checked=true;
+	document.user_edit.radio_expiration_date[0].checked=false;
+	document.user_edit.radio_expiration_date[1].checked=true;
+}
+
+function password_switch_radio_button(){
+	var input_elements = document.getElementsByTagName("input");
+	for (var i = 0; i < input_elements.length; i++) {
+		if(input_elements.item(i).name == "reset_password" && input_elements.item(i).value == "2") {
+			input_elements.item(i).checked = true;
+		}
+	}
 }
 
 function display_drh_list(){
@@ -49,209 +40,197 @@ function display_drh_list(){
 		document.getElementById("drh_list").style.display="block";
 	}
 	else
-	{ 
+	{
 		document.getElementById("drh_list").style.display="none";
 		document.getElementById("drh_select").options[0].selected="selected";
 	}
 }
-		
+
 function show_image(image,width,height) {
 	width = parseInt(width) + 20;
-	height = parseInt(height) + 20;			
-	window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \' , resizable=0\');		
-}		
+	height = parseInt(height) + 20;
+	window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \' , resizable=0\');
+}
 //-->
 </script>';
 
+$libpath = api_get_path(LIBRARY_PATH);
+require_once $libpath.'fileManage.lib.php';
+require_once $libpath.'fileUpload.lib.php';
+require_once $libpath.'usermanager.lib.php';
+require_once $libpath.'formvalidator/FormValidator.class.php';
+require_once $libpath.'image.lib.php';
+require_once $libpath.'mail.lib.inc.php';
 
-require_once(api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require_once(api_get_path(LIBRARY_PATH).'fileUpload.lib.php');
-require_once(api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-require_once (api_get_path(LIBRARY_PATH).'image.lib.php');
-require_once(api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php');
-$user_id=isset($_GET['user_id']) ? intval($_GET['user_id']) : intval($_POST['user_id']);
-$noPHP_SELF=true;
-$tool_name=get_lang('ModifyUserInfo');
+$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : intval($_POST['user_id']);
+$noPHP_SELF = true;
+$tool_name = get_lang('ModifyUserInfo');
 
-$interbreadcrumb[]=array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[]=array('url' => "user_list.php","name" => get_lang('UserList'));
+$interbreadcrumb[] = array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array('url' => "user_list.php","name" => get_lang('UserList'));
 
 $table_user = Database::get_main_table(TABLE_MAIN_USER);
 $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
 $sql = "SELECT u.*, a.user_id AS is_admin FROM $table_user u LEFT JOIN $table_admin a ON a.user_id = u.user_id WHERE u.user_id = '".$user_id."'";
-$res = api_sql_query($sql,__FILE__,__LINE__);
-if(mysql_num_rows($res) != 1)
-{
+$res = Database::query($sql, __FILE__, __LINE__);
+if (Database::num_rows($res) != 1) {
 	header('Location: user_list.php');
 	exit;
 }
-$user_data = mysql_fetch_array($res,MYSQL_ASSOC);
+
+$user_data = Database::fetch_array($res, 'ASSOC');
 $user_data['platform_admin'] = is_null($user_data['is_admin']) ? 0 : 1;
 $user_data['send_mail'] = 0;
 $user_data['old_password'] = $user_data['password'];
 unset($user_data['password']);
 
-$user_data = array_merge($user_data, Usermanager :: get_extra_user_data($user_id,true));
+$user_data = array_merge($user_data, Usermanager :: get_extra_user_data($user_id, true));
 
 // Create the form
-$form = new FormValidator('user_add','post','','',array('style' => 'width: 60%; float: '.($text_dir=='rtl'?'right;':'left;')));
+$form = new FormValidator('user_edit', 'post', '', '', array('style' => 'width: 60%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;')));
 $form->addElement('header', '', $tool_name);
-$form->addElement('hidden','user_id',$user_id);
+$form->addElement('hidden', 'user_id', $user_id);
 
-if (api_is_western_name_order())
-{
+if (api_is_western_name_order()) {
 	// Firstname
-	$form->addElement('text','firstname',get_lang('FirstName'));
-	$form->applyFilter('firstname','html_filter');
-	$form->applyFilter('firstname','trim');
+	$form->addElement('text', 'firstname', get_lang('FirstName'));
+	$form->applyFilter('firstname', 'html_filter');
+	$form->applyFilter('firstname', 'trim');
 	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 	// Lastname
-	$form->addElement('text','lastname',get_lang('LastName'));
-	$form->applyFilter('lastname','html_filter');
-	$form->applyFilter('lastname','trim');
+	$form->addElement('text', 'lastname', get_lang('LastName'));
+	$form->applyFilter('lastname', 'html_filter');
+	$form->applyFilter('lastname', 'trim');
 	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
-}
-else
-{
+} else {
 	// Lastname
-	$form->addElement('text','lastname',get_lang('LastName'));
-	$form->applyFilter('lastname','html_filter');
-	$form->applyFilter('lastname','trim');
+	$form->addElement('text', 'lastname', get_lang('LastName'));
+	$form->applyFilter('lastname', 'html_filter');
+	$form->applyFilter('lastname', 'trim');
 	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
 	// Firstname
-	$form->addElement('text','firstname',get_lang('FirstName'));
-	$form->applyFilter('firstname','html_filter');
-	$form->applyFilter('firstname','trim');
+	$form->addElement('text', 'firstname', get_lang('FirstName'));
+	$form->applyFilter('firstname', 'html_filter');
+	$form->applyFilter('firstname', 'trim');
 	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 }
 
 // Official code
-$form->addElement('text', 'official_code', get_lang('OfficialCode'),array('size' => '40'));
-$form->applyFilter('official_code','html_filter');
-$form->applyFilter('official_code','trim');
+$form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => '40'));
+$form->applyFilter('official_code', 'html_filter');
+$form->applyFilter('official_code', 'trim');
 
 // Email
-$form->addElement('text', 'email', get_lang('Email'),array('size' => '40'));
+$form->addElement('text', 'email', get_lang('Email'), array('size' => '40'));
 $form->addRule('email', get_lang('EmailWrong'), 'email');
 $form->addRule('email', get_lang('EmailWrong'), 'required');
 
 // OpenID
-if(api_get_setting('openid_authentication')=='true')
-{
-	$form->addElement('text', 'openid', get_lang('OpenIDURL'),array('size' => '40'));
+if (api_get_setting('openid_authentication') == 'true') {
+	$form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => '40'));
 }
 
 // Phone
-$form->addElement('text','phone',get_lang('PhoneNumber'));
+$form->addElement('text', 'phone', get_lang('PhoneNumber'));
 
 // Picture
 $form->addElement('file', 'picture', get_lang('AddPicture'));
 $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
 $form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
-if (strlen($user_data['picture_uri']) > 0 )
-{
+if (strlen($user_data['picture_uri']) > 0) {
 	$form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
 }
 
 // Username
-$form->addElement('text', 'username', get_lang('LoginName'),array('maxlength'=>20));
+$form->addElement('text', 'username', get_lang('LoginName'), array('maxlength' => USERNAME_MAX_LENGTH));
 $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
 $form->addRule('username', get_lang('OnlyLettersAndNumbersAllowed'), 'username');
-$form->addRule('username', '', 'maxlength',20);
 $form->addRule('username', get_lang('UserTaken'), 'username_available', $user_data['username']);
 
 // Password
-$form->addElement('radio','reset_password',get_lang('Password'),get_lang('DontResetPassword'),0);
-if(count($extAuthSource) > 0)
+$form->addElement('radio', 'reset_password', get_lang('Password'), get_lang('DontResetPassword'), 0);
+if (count($extAuthSource) > 0)
 {
-	$group[] =& HTML_QuickForm::createElement('radio','reset_password',null,get_lang('ExternalAuthentication').' ',3);
+	$group[] =& HTML_QuickForm::createElement('radio', 'reset_password', null, get_lang('ExternalAuthentication').' ', 3);
 	$auth_sources = array();
-	foreach($extAuthSource as $key => $info)
-	{
+	foreach($extAuthSource as $key => $info) {
 		$auth_sources[$key] = $key;
 	}
-	$group[] =& HTML_QuickForm::createElement('select','auth_source',null,$auth_sources);
-	$group[] =& HTML_QuickForm::createElement('static','','','<br />');
-	$form->addGroup($group, 'password', null, '',false);
+	$group[] =& HTML_QuickForm::createElement('select', 'auth_source', null, $auth_sources);
+	$group[] =& HTML_QuickForm::createElement('static', '', '', '<br />');
+	$form->addGroup($group, 'password', null, '', false);
 }
-$form->addElement('radio','reset_password',null,get_lang('AutoGeneratePassword'),1);
+$form->addElement('radio', 'reset_password', null, get_lang('AutoGeneratePassword'), 1);
 $group = array();
-$group[] =& HTML_QuickForm::createElement('radio', 'reset_password',null,null,2);
-$group[] =& HTML_QuickForm::createElement('password', 'password',null,null);
-$form->addGroup($group, 'password', null, '',false);
+$group[] =& HTML_QuickForm::createElement('radio', 'reset_password', null, null, 2);
+$group[] =& HTML_QuickForm::createElement('password', 'password', null, array('onkeydown' => 'javascript: password_switch_radio_button();'));
+$form->addGroup($group, 'password', null, '', false);
 
 // Status
 $status = api_get_status_langvars();
-$form->addElement('select','status',get_lang('Status'),$status,'id="status_select" onchange="display_drh_list()"');
+$form->addElement('select', 'status', get_lang('Status'), $status, array('id' => 'status_select', 'onchange' => 'javascript: display_drh_list();'));
 
 //Language
 $form->addElement('select_language', 'language', get_lang('Language'));
 
 $display = $user_data['status'] == STUDENT || $_POST['status'] == STUDENT ? 'block' : 'none';
-$form->addElement('html','<div id="drh_list" style="display:'.$display.';">');
-$drh_select = $form->addElement('select','hr_dept_id',get_lang('Drh'),array(),'id="drh_select"');
-$drh_list = UserManager :: get_user_list(array('status'=>DRH),array('lastname','firstname'));
+$form->addElement('html', '<div id="drh_list" style="display:'.$display.';">');
+$drh_select = $form->addElement('select', 'hr_dept_id', get_lang('Drh'), array(), 'id="drh_select"');
+$drh_list = UserManager :: get_user_list(array('status' => DRH), api_sort_by_first_name() ? array('firstname', 'lastname') : array('lastname', 'firstname'));
 
 if (count($drh_list) == 0) {
-	$drh_select->addOption('- '.get_lang('ThereIsNotStillAResponsible').' -',0);	
+	$drh_select->addOption('- '.get_lang('ThereIsNotStillAResponsible', '').' -', 0);
 } else {
-	$drh_select->addOption('- '.get_lang('SelectAResponsible').' -',0);
+	$drh_select->addOption('- '.get_lang('SelectAResponsible').' -', 0);
 }
 
-foreach($drh_list as $drh)
-{
+foreach($drh_list as $drh) {
 	$drh_select->addOption(api_get_person_name($drh['firstname'], $drh['lastname']), $drh['user_id']);
 }
 $form->addElement('html', '</div>');
 
 // Platform admin
 // Only when changing another user!
-if($user_id != $_SESSION['_uid'])
-{
+if ($user_id != $_SESSION['_uid']) {
 	$group = array();
-	$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin',null,get_lang('Yes'),1);
-	$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin',null,get_lang('No'),0);
-	if ($user_data['status']<>5) {
-		$form->addGroup($group, 'admin', get_lang('PlatformAdmin'), '&nbsp;',false);	
-	} 
-	
+	$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin', null, get_lang('Yes'), 1);
+	$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin', null, get_lang('No'), 0);
+	if ($user_data['status'] <> 5) {
+		$form->addGroup($group, 'admin', get_lang('PlatformAdmin'), '&nbsp;', false);
+	}
 }
 
 // Send email
 $group = array();
-$group[] =& HTML_QuickForm::createElement('radio', 'send_mail',null,get_lang('Yes'),1);
-$group[] =& HTML_QuickForm::createElement('radio', 'send_mail',null,get_lang('No'),0);
-$form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;',false);
+$group[] =& HTML_QuickForm::createElement('radio', 'send_mail', null, get_lang('Yes'), 1);
+$group[] =& HTML_QuickForm::createElement('radio', 'send_mail', null, get_lang('No'), 0);
+$form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;', false);
 
 // Registration Date
-$form->addElement('static','registration_date', get_lang('RegistrationDate'), $user_data['registration_date']);
+$form->addElement('static', 'registration_date', get_lang('RegistrationDate'), $user_data['registration_date']);
 
-if(! $user_data['platform_admin'] )
-{
+if (!$user_data['platform_admin']) {
 	// Expiration Date
 	$form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
 	$group = array ();
 	$group[] = & $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
-	$group[] = & $form->createElement('datepicker', 'expiration_date',null, array ('form_name' => $form->getAttribute('name'), 'onChange'=>'enable_expiration_date()'));
+	$group[] = & $form->createElement('datepicker', 'expiration_date', null, array('form_name' => $form->getAttribute('name'), 'onchange' => 'javascript: enable_expiration_date();'));
 	$form->addGroup($group, 'max_member_group', null, '', false);
 
 	// Active account or inactive account
-	$form->addElement('radio','active',get_lang('ActiveAccount'),get_lang('Active'),1);
-	$form->addElement('radio','active','',get_lang('Inactive'),0);
+	$form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active'), 1);
+	$form->addElement('radio', 'active', '', get_lang('Inactive'), 0);
 }
 
 
 // EXTRA FIELDS
-$extra = UserManager::get_extra_fields(0,50,5,'ASC');
-foreach($extra as $id => $field_details)
-{
-    if($field_details[6] == 0)
-    {
-        continue;
-    }
-    switch($field_details[2])
-	{
+$extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
+foreach ($extra as $id => $field_details) {
+	if ($field_details[6] == 0) {
+		continue;
+	}
+	switch ($field_details[2]) {
 		case USER_FIELD_TYPE_TEXT:
 			$form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 40));
 			$form->applyFilter('extra_'.$field_details[1], 'stripslashes');
@@ -265,39 +244,36 @@ foreach($extra as $id => $field_details)
 			break;
 		case USER_FIELD_TYPE_RADIO:
 			$group = array();
-			foreach($field_details[9] as $option_id => $option_details)
-			{
+			foreach ($field_details[9] as $option_id => $option_details) {
 				$options[$option_details[1]] = $option_details[2];
-				$group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1],$option_details[2].'<br />',$option_details[1]);
+				$group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1], $option_details[2].'<br />', $option_details[1]);
 			}
 			$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '');
 			break;
 		case USER_FIELD_TYPE_SELECT:
 			$options = array();
-			foreach($field_details[9] as $option_id => $option_details)
-			{
+			foreach ($field_details[9] as $option_id => $option_details) {
 				$options[$option_details[1]] = $option_details[2];
 			}
-			$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,'');			
+			$form->addElement('select', 'extra_'.$field_details[1], $field_details[3], $options, '');
 			break;
 		case USER_FIELD_TYPE_SELECT_MULTIPLE:
 			$options = array();
-			foreach($field_details[9] as $option_id => $option_details)
-			{
+			foreach ($field_details[9] as $option_id => $option_details) {
 				$options[$option_details[1]] = $option_details[2];
 			}
-			$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,array('multiple' => 'multiple'));
+			$form->addElement('select', 'extra_'.$field_details[1], $field_details[3], $options, array('multiple' => 'multiple'));
 			break;
 		case USER_FIELD_TYPE_DATE:
-			$form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3],array('form_name'=>'user_add'));
-			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);
+			$form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3], array('form_name' => 'user_edit'));
+			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
 			$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
 			$form -> setDefaults($defaults);
 			$form->applyFilter('theme', 'trim');
 			break;
 		case USER_FIELD_TYPE_DATETIME:
-			$form->addElement('datepicker', 'extra_'.$field_details[1], $field_details[3],array('form_name'=>'user_add'));
-			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);
+			$form->addElement('datepicker', 'extra_'.$field_details[1], $field_details[3], array('form_name' => 'user_edit'));
+			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
 			$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
 			$form -> setDefaults($defaults);
 			$form->applyFilter('theme', 'trim');
@@ -305,89 +281,71 @@ foreach($extra as $id => $field_details)
 	}
 }
 
-
 // Submit button
-$form->addElement('style_submit_button', 'submit',get_lang('ModifyInformation'),'class="save"');
-
+$form->addElement('style_submit_button', 'submit', get_lang('ModifyInformation'), 'class="save"');
 
 // Set default values
-$expiration_date=$user_data['expiration_date'];
-if ($expiration_date=='0000-00-00 00:00:00')
-{
-	$user_data['radio_expiration_date']=0;
-	$user_data['expiration_date']=array();
-	$user_data['expiration_date']['d']=date('d');
-	$user_data['expiration_date']['F']=date('m');
-	$user_data['expiration_date']['Y']=date('Y');
-}
-else
-{
-	$user_data['radio_expiration_date']=1;
-	$user_data['expiration_date']=array();
-	$user_data['expiration_date']['d']=substr($expiration_date,8,2);
-	$user_data['expiration_date']['F']=substr($expiration_date,5,2);
-	$user_data['expiration_date']['Y']=substr($expiration_date,0,4);
+$user_data['reset_password'] = 0;
+$expiration_date = $user_data['expiration_date'];
+if ($expiration_date == '0000-00-00 00:00:00') {
+	$user_data['radio_expiration_date'] = 0;
+	$user_data['expiration_date'] = array();
+	$user_data['expiration_date']['d'] = date('d');
+	$user_data['expiration_date']['F'] = date('m');
+	$user_data['expiration_date']['Y'] = date('Y');
+} else {
+	$user_data['radio_expiration_date'] = 1;
+	$user_data['expiration_date'] = array();
+	$user_data['expiration_date']['d'] = substr($expiration_date, 8, 2);
+	$user_data['expiration_date']['F'] = substr($expiration_date, 5, 2);
+	$user_data['expiration_date']['Y'] = substr($expiration_date, 0, 4);
 }
 $form->setDefaults($user_data);
 
-
 // Validate form
-if( $form->validate())
-{
+if ( $form->validate()) {
 	$user = $form->exportValues();
+
 	$picture_element = & $form->getElement('picture');
 	$picture = $picture_element->getValue();
-	$picture_uri = '';
-	
-    //get the picture directory
-    $picture_paths = UserManager::get_user_picture_path_by_id($user_id,'system',true);
-    $picture_location = $picture_paths['dir'];
-    $big_picture_location = $picture_paths['dir'];
-	if (strlen($picture['name']) > 0)
-	{
-		$picture_uri = uniqid('').'_'.replace_dangerous_char($picture['name']);
-        if(!file_exists($picture_location))
-        {
-        	mkpath($picture_location);
-        }
-		$picture_infos=@getimagesize($_FILES['picture']['tmp_name']);
-		$type=$picture_infos[2];
-		$small_temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 22); //small picture
-		$medium_temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 85); //medium picture
-		$temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 200); // normal picture
-		$big_temp = new image($_FILES['picture']['tmp_name']); // original picture
-		
-	    switch (!empty($type)) {
-		    case 2 : 
-		    	$small_temp->send_image('JPG',$picture_location.'small_'.$picture_uri); 
-				$medium_temp->send_image('JPG',$picture_location.'medium_'.$picture_uri);
-	    		$temp->send_image('JPG',$picture_location.$picture_uri);
-	    		$big_temp->send_image('JPG',$picture_location.'big_'.$picture_uri);	    		 
-		    	break;
-		    case 3 :
-		    	$small_temp->send_image('PNG',$picture_location.'small_'.$picture_uri);
-		    	$medium_temp->send_image('PNG',$picture_location.'medium_'.$picture_uri);
-		    	$temp->send_image('PNG',$picture_location.$picture_uri);
-		    	$big_temp->send_image('PNG',$picture_location.'big_'.$picture_uri);
-		    	break;
-		    case 1 :
-		    	$small_temp->send_image('GIF',$picture_location.'small_'.$picture_uri);
-		    	$medium_temp->send_image('GIF',$picture_location.'medium_'.$picture_uri);
-		    	$temp->send_image('GIF',$picture_location.$picture_uri);
-		    	$big_temp->send_image('GIF',$picture_location.'big_'.$picture_uri);	    		 
-		    	break;
-	    }
 
+	$picture_uri = $user_data['picture_uri'];
+
+	//get the picture directory
+	$picture_path_info = UserManager::get_user_picture_path_by_id($user_id, 'system', true);
+	$picture_path = $picture_path_info['dir'];
+
+	if ($user['delete_picture'] || !empty($picture['name'])) {
+		@unlink($picture_path.'small_'.$picture_uri);
+		@unlink($picture_path.'medium_'.$picture_uri);
+		@unlink($picture_path.'big_'.$picture_uri);
+		@unlink($picture_path.$picture_uri);
+		$picture_uri = '';
 	}
-	elseif(isset($user['delete_picture']))
-	{
-		@unlink($picture_location.$user_data['picture_uri']);
-	}
-	
-	if (strlen($picture['name']) == 0){
-		$picture_uri = $user_data['picture_uri'];
+
+	if (!empty($picture['name'])) {
+		$picture_uri = $user_id.'_'.uniqid('').'_'.replace_dangerous_char($picture['name']);
+		$perm = api_get_setting('permissions_for_new_directories');
+		$perm = octdec(!empty($perm) ? $perm : '0770');
+		if (!file_exists($picture_path)) {
+			@mkdir($picture_path, $perm, true);
+		}
+		$picture_info = @getimagesize($_FILES['picture']['tmp_name']);
+		$type = $picture_info[2];
+		$small_picture = UserManager::resize_picture($_FILES['picture']['tmp_name'], 22);
+		$medium_picture = UserManager::resize_picture($_FILES['picture']['tmp_name'], 85);
+		$normal_picture = UserManager::resize_picture($_FILES['picture']['tmp_name'], 200);
+		$big_picture = new image($_FILES['picture']['tmp_name']); // This is the original picture.
+
+		$picture_types = array(1 => 'GIF', 2 => 'JPG', 3 => 'PNG');
+		if (in_array($type, array_keys($picture_types))) {
+			$small_picture->send_image($picture_types[$type], $picture_path.'small_'.$picture_uri);
+			$medium_picture->send_image($picture_types[$type], $picture_path.'medium_'.$picture_uri);
+			$normal_picture->send_image($picture_types[$type], $picture_path.$picture_uri);
+			$big_picture->send_image($picture_types[$type], $picture_path.'big_'.$picture_uri);
+		}
 	}
-	
+
 	$lastname = $user['lastname'];
 	$firstname = $user['firstname'];
 	$official_code = $user['official_code'];
@@ -395,138 +353,116 @@ if( $form->validate())
 	$phone = $user['phone'];
 	$username = $user['username'];
 	$status = intval($user['status']);
-	$picture = $_FILES['picture'];
 	$platform_admin = intval($user['platform_admin']);
 	$send_mail = intval($user['send_mail']);
 	$reset_password = intval($user['reset_password']);
 	$hr_dept_id = intval($user['hr_dept_id']);
-	$language=$user['language'];
-	if ($user['radio_expiration_date']=='1' && ! $user_data['platform_admin'] )
-	{
+	$language = $user['language'];
+	if ($user['radio_expiration_date'] == '1' && !$user_data['platform_admin']) {
 		$expiration_date=$user['expiration_date'];
-	}
-	else
-	{
+	} else {
 		$expiration_date='0000-00-00 00:00:00';
 	}
 	$active = $user_data['platform_admin'] ? 1 : intval($user['active']);
 
-	if( $reset_password == 0)
-	{
+	if ($reset_password == 0) {
 		$password = null;
 		$auth_source = $user_data['auth_source'];
 	}
-	elseif($reset_password == 1)
-	{
+	elseif($reset_password == 1) {
 		$password = api_generate_password();
 		$auth_source = PLATFORM_AUTH_SOURCE;
 	}
-	elseif($reset_password == 2)
-	{
+	elseif($reset_password == 2) {
 		$password = $user['password'];
 		$auth_source = PLATFORM_AUTH_SOURCE;
 	}
-	elseif($reset_password == 3)
-	{
+	elseif($reset_password == 3) {
 		$password = $user['password'];
-		$auth_source = $user['auth_source'];		
+		$auth_source = $user['auth_source'];
 	}
-	UserManager::update_user($user_id,$firstname,$lastname,$username,$password,$auth_source,$email,$status,$official_code,$phone,$picture_uri,$expiration_date, $active, null, $hr_dept_id,null,$language);
-	if(api_get_setting('openid_authentication')=='true' && !empty($user['openid']))
-	{
+	UserManager::update_user($user_id, $firstname, $lastname, $username, $password, $auth_source, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active, null, $hr_dept_id, null, $language);
+	if (api_get_setting('openid_authentication') == 'true' && !empty($user['openid'])) {
 		$up = UserManager::update_openid($user_id,$user['openid']);
 	}
-	if($user_id != $_SESSION['_uid'])
-	{
-		if($platform_admin == 1)
-		{
+	if ($user_id != $_SESSION['_uid']) {
+		if ($platform_admin == 1) {
 			$sql = "INSERT IGNORE INTO $table_admin SET user_id = '".$user_id."'";
-			api_sql_query($sql,__FILE__,__LINE__);
-		}
-		else
-		{
+			Database::query($sql, __FILE__, __LINE__);
+		} else {
 			$sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
-			api_sql_query($sql,__FILE__,__LINE__);
+			Database::query($sql, __FILE__, __LINE__);
 		}
 	}
-	
+
 	$extras = array();
-	foreach($user as $key => $value)
-	{
-		if(substr($key,0,6)=='extra_') //an extra field
-		{
-			$myres = UserManager::update_extra_field_value($user_id,substr($key,6),$value);
+	foreach($user as $key => $value) {
+		if(substr($key, 0, 6) == 'extra_') { //an extra field
+			$myres = UserManager::update_extra_field_value($user_id, substr($key, 6), $value);
 		}
 	}
-	
-	if (!empty ($email) && $send_mail)
-	{
+
+	if (!empty ($email) && $send_mail) {
 		$recipient_name = api_get_person_name($firstname, $lastname, null, PERSON_NAME_EMAIL_ADDRESS);
-		$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');												
+		$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
 		$sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-	    $email_admin = api_get_setting('emailAdministrator');
-	    
-	    if ($_configuration['multiple_access_urls']==true) {
-			$access_url_id = api_get_current_access_url_id();				
-			if ($access_url_id != -1 ){
-				$url = api_get_access_url($access_url_id);					
-				$emailbody=get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ". api_get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
-			}		
+		$email_admin = api_get_setting('emailAdministrator');
+
+		if ($_configuration['multiple_access_urls'] == true) {
+			$access_url_id = api_get_current_access_url_id();
+			if ($access_url_id != -1) {
+				$url = api_get_access_url($access_url_id);
+				$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ". api_get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
+			}
 		}
 		else {
 			$emailbody=get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreReg')." ". api_get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". api_get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n". get_lang('Manager'). " ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".api_get_setting('emailAdministrator');
 		}
-			
-					
+
 		$emailbody = get_lang('Dear')." ".stripslashes("$firstname $lastname").",\n\n".get_lang('YouAreReg')." ". api_get_setting('siteName') ." ".get_lang('Settings')." ". $username;
 		// Send password by e-mail if it has been modified, even if encrypted in DB (it doesn't make sense to send an e-mail with login info without the password, even if the password is encrypted)
-		if($reset_password > 0)
-		{
+		if ($reset_password > 0) {
 			$emailbody .= "\n".get_lang('Pass')." : ".stripslashes($password);
 		}
-		@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name,$email_admin);
-			
+		@api_mail($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin);
 	}
-	$tok = Security::get_token();		
+	$tok = Security::get_token();
 	header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('UserUpdated')).'&sec_token='.$tok);
 	exit();
 }
 
 Display::display_header($tool_name);
 
-//  USER PICTURE
+// USER PICTURE
 $image_path = UserManager::get_user_picture_path_by_id($user_id,'web');
 $image_dir = $image_path['dir'];
 $image = $image_path['file'];
 $image_file = ($image != '' ? $image_dir.$image : api_get_path(WEB_CODE_PATH).'img/unknown.jpg');
-$image_size = @getimagesize(api_url_to_local_path($image_file));
+$image_size = api_getimagesize($image_file);
 
 $img_attributes = 'src="'.$image_file.'?rand='.time().'" '
-    .'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
-    .'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; padding:5px;" ';
+	.'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
+	.'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; padding:5px;" ';
 
-if ($image_size[0] > 300) //limit display width to 300px
-    $img_attributes .= 'width="300" ';
+if ($image_size[0] > 300) { //limit display width to 300px
+	$img_attributes .= 'width="300" ';
+}
 
 // get the path,width and height from original picture
 $big_image = $image_dir.'big_'.$image;
-$big_image_size = @getimagesize(api_url_to_local_path($big_image));
-$big_image_width= $big_image_size[0];
-$big_image_height= $big_image_size[1];
+$big_image_size = api_getimagesize($big_image);
+$big_image_width = $big_image_size[0];
+$big_image_height = $big_image_size[1];
 $url_big_image = $big_image.'?rnd='.time();
-if ($image=='') {
+
+if ($image == '') {
 	echo '<img '.$img_attributes.' />';
 } else {
-	echo '<input type="image" '.$img_attributes.' onclick="return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
+	echo '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
 }
 
-
 // Display form
 $form->display();
-/*
-==============================================================================
-		FOOTER
-==============================================================================
-*/
+
+// Footer
 Display::display_footer();
-?>

+ 29 - 29
main/admin/user_export.php

@@ -56,15 +56,15 @@ $courses = array ();
 $courses[''] = '--';
 $sql = "SELECT code,visual_code,title FROM $course_table ORDER BY visual_code";
 
-global $_configuration;	
-if ($_configuration['multiple_access_urls']==true) {		
-	$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);	
+global $_configuration;
+if ($_configuration['multiple_access_urls']==true) {
+	$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 	$access_url_id = api_get_current_access_url_id();
 	if ($access_url_id != -1){
-	$sql = "SELECT code,visual_code,title FROM $course_table as c INNER JOIN $tbl_course_rel_access_url as course_rel_url 		
-		ON (c.code = course_rel_url.course_code)		
+	$sql = "SELECT code,visual_code,title FROM $course_table as c INNER JOIN $tbl_course_rel_access_url as course_rel_url
+		ON (c.code = course_rel_url.course_code)
 		WHERE access_url_id = $access_url_id
-		ORDER BY visual_code";		
+		ORDER BY visual_code";
 	}
 }
 $result = api_sql_query($sql, __FILE__, __LINE__);
@@ -84,10 +84,10 @@ $form->setDefaults(array('file_type'=>'csv'));
 if ($form->validate())
 {
 	global $userPasswordCrypted;
-	
+
 	$export = $form->exportValues();
 	$file_type = $export['file_type'];
-	$course_code = $export['course_code'];	
+	$course_code = $export['course_code'];
 	$userPasswordCrypted =
 	$sql = "SELECT  u.user_id 	AS UserId,
 					u.lastname 	AS LastName,
@@ -102,52 +102,52 @@ if ($form->validate())
 	if (strlen($course_code) > 0) {
 		$sql .= " FROM $user_table u, $course_user_table cu WHERE u.user_id = cu.user_id AND course_code = '$course_code' ORDER BY lastname,firstname";
 		$filename = 'export_users_'.$course_code.'_'.date('Y-m-d_H-i-s');
-	} else {		
-		global $_configuration;	
-		if ($_configuration['multiple_access_urls']==true) {		
-			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);	
+	} else {
+		global $_configuration;
+		if ($_configuration['multiple_access_urls']==true) {
+			$tbl_user_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 			$access_url_id = api_get_current_access_url_id();
 			if ($access_url_id != -1) {
-			$sql.= " FROM $user_table u INNER JOIN $tbl_user_rel_access_url as user_rel_url 		
-				ON (u.user_id= user_rel_url.user_id)		
+			$sql.= " FROM $user_table u INNER JOIN $tbl_user_rel_access_url as user_rel_url
+				ON (u.user_id= user_rel_url.user_id)
 				WHERE access_url_id = $access_url_id
-				ORDER BY lastname,firstname";		
+				ORDER BY lastname,firstname";
 			}
 		} else {
 			$sql .= " FROM $user_table u ORDER BY lastname,firstname";
-		}		
+		}
 		$filename = 'export_users_'.date('Y-m-d_H-i-s');
 	}
-	require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');	
-	$data = array();	
+	require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
+	$data = array();
 	$extra_fields = Usermanager::get_extra_fields(0, 0, 5, 'ASC',false);
 	if ($export['addcsvheader']=='1' AND $export['file_type']=='csv')
 	{
 		if($userPasswordCrypted!='none') {
 			$data[] = array('UserId', 'LastName', 'FirstName', 'Email', 'UserName', 'AuthSource', 'Status', 'OfficialCode', 'Phone');
 		} else {
-			$data[] = array('UserId', 'LastName', 'FirstName', 'Email', 'UserName','Password',  'AuthSource', 'Status', 'OfficialCode', 'Phone');	
+			$data[] = array('UserId', 'LastName', 'FirstName', 'Email', 'UserName','Password',  'AuthSource', 'Status', 'OfficialCode', 'Phone');
 		}
-		
+
 		foreach($extra_fields as $extra) {
 			$data[0][]=$extra[1];
-		}	
-		
+		}
+
 	}
-	$res = api_sql_query($sql,__FILE__,__LINE__);	
-	while($user = Database::fetch_array($res,'ASSOC')) {		
-		$student_data= UserManager :: get_extra_user_data($user['UserId'],true,false);		
+	$res = api_sql_query($sql,__FILE__,__LINE__);
+	while($user = Database::fetch_array($res,'ASSOC')) {
+		$student_data= UserManager :: get_extra_user_data($user['UserId'],true,false);
 		foreach($student_data as $key=>$value) {
 			$key= substr($key,6);
-			if (is_array($value)) 
+			if (is_array($value))
 				$user[$key]= $value[$key];
 			else {
 				$user[$key]= $value;
-			}			
+			}
 		}
-		$data[] = $user	;							
+		$data[] = $user	;
 	}
-	
+
 	switch($file_type)
 	{
 		case 'xml':

+ 41 - 41
main/admin/user_fields.php

@@ -61,7 +61,7 @@ if(1)
 			switch ($_GET['action']) {
 				case 'show_message' :
 					Display :: display_normal_message($_GET['message']);
-					break;			
+					break;
 				case 'show_field' :
 					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_visible'=>'1'))) {
 						Display :: display_confirmation_message(get_lang('FieldShown'));
@@ -75,14 +75,14 @@ if(1)
 					} else {
 						Display :: display_error_message(get_lang('CannotHideField'));
 					}
-					break;	
+					break;
 				case 'thaw_field' :
 					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_changeable'=>'1'))) {
 						Display :: display_confirmation_message(get_lang('FieldMadeChangeable'));
 					} else {
 						Display :: display_error_message(get_lang('CannotMakeFieldChangeable'));
 					}
-					break;	
+					break;
 				case 'freeze_field' :
 					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_changeable'=>'0'))) {
 						Display :: display_confirmation_message(get_lang('FieldMadeUnchangeable'));
@@ -100,13 +100,13 @@ if(1)
 					}
 					break;
 				case 'movedown' :
-					if (api_is_platform_admin() && !empty($_GET['field_id'])) {					
+					if (api_is_platform_admin() && !empty($_GET['field_id'])) {
 						if (move_user_field('movedown', $_GET['field_id'])) {
 							Display :: display_confirmation_message(get_lang('FieldMovedDown'));
 						} else {
 							Display :: display_error_message(get_lang('CannotMoveField'));
-						}					
-					}				
+						}
+					}
 					break;
 				case 'filter_on' :
 					if (api_is_platform_admin() && !empty($_GET['field_id']) && UserManager :: update_extra_field($_GET['field_id'],array('field_filter'=>'1'))) {
@@ -122,7 +122,7 @@ if(1)
 						Display :: display_error_message(get_lang('CannotShowField'));
 					}
 					break;
-							
+
 				case 'delete':
 					if (api_is_platform_admin() && !empty($_GET['field_id'])) {
 						if (delete_user_fields($_GET['field_id'])) {
@@ -146,7 +146,7 @@ if(1)
 			Security::clear_token();
 		}
 	}
-	
+
 	// Create an add-field box
 	$form = new FormValidator('add_field','post','','',null,false);
 	$renderer =& $form->defaultRenderer();
@@ -166,9 +166,9 @@ if(1)
 	$column_show  = array(1,1,1,1,1,1,1,1,1,0,0);
 	$column_order = array(1,2,3,4,5,6,7,8,9,10,11);
 	$extra_fields = UserManager::get_extra_fields(0,100,5,'ASC');
-	
+
 	$number_of_extra_fields = count($extra_fields);
- 
+
 	$table = new SortableTableFromArrayConfig($extra_fields, 5, 50, '', $column_show, $column_order, 'ASC');
 	$table->set_additional_parameters($parameters);
 	$table->set_header(0, '', false);
@@ -179,7 +179,7 @@ if(1)
 	$table->set_header(5, get_lang('FieldOrder'), false);
 	$table->set_header(6, get_lang('FieldVisibility'), false);
 	$table->set_header(7, get_lang('FieldChangeability'), false);
-	$table->set_header(8, get_lang('FieldFilter'), false);	
+	$table->set_header(8, get_lang('FieldFilter'), false);
 	$table->set_header(9, get_lang('Modify'), false);
 	$table->set_column_filter(5, 'order_filter');
 	$table->set_column_filter(6, 'modify_visibility');
@@ -213,7 +213,7 @@ function get_extra_fields($f,$n,$o,$d)
  *
  * @param integer $type the id of the form type
  * @return string the huma readable description of the field type (text, date, select drop-down, ...)
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version July 2008
  * @since Dokeos 1.8.6
@@ -228,8 +228,8 @@ function type_filter($type)
 	$types[USER_FIELD_TYPE_DATE] 				= get_lang('FieldTypeDate');
 	$types[USER_FIELD_TYPE_DATETIME] 			= get_lang('FieldTypeDatetime');
 	$types[USER_FIELD_TYPE_DOUBLE_SELECT] 		= get_lang('FieldTypeDoubleSelect');
-	$types[USER_FIELD_TYPE_DIVIDER] 			= get_lang('FieldTypeDivider');	
-	
+	$types[USER_FIELD_TYPE_DIVIDER] 			= get_lang('FieldTypeDivider');
+
 	return $types[$type];
 }
 
@@ -240,7 +240,7 @@ function type_filter($type)
  * @param	array	Url parameters
  * @param	array	The results row
  * @return	string	The link
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version July 2008
  * @since Dokeos 1.8.6
@@ -248,24 +248,24 @@ function type_filter($type)
 function order_filter($field_order,$url_params,$row)
 {
 	global $number_of_extra_fields;
-	
+
 	// the up icon only has to appear when the row can be moved up (all but the first row)
 	if ($row[5]<>1)
 	{
 		$return .= '<a href="'.api_get_self().'?action=moveup&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('up.gif', get_lang('Up')).'</a>';
 	}
-	else 
+	else
 	{
 		$return .= Display::return_icon('blank.gif','',array('width'=>'21px'));
 	}
-	
+
 	// the down icon only has to appear when the row can be moved down (all but the last row)
 	if ($row[5]<>$number_of_extra_fields)
 	{
 		$return .= '<a href="'.api_get_self().'?action=movedown&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('down.gif', get_lang('Down')).'</a>';
 	}
-	
-	return $return; 
+
+	return $return;
 }
 /**
  * Modify the visible field to show links and icons
@@ -301,14 +301,14 @@ function edit_filter($id,$url_params,$row)
 	global $charset;
 	$return = '<a href="user_fields_add.php?action=edit&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('edit.gif',get_lang('Edit')).'</a>';
 	$return .= ' <a href="'.api_get_self().'?action=delete&field_id='.$row[0].'&sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.gif',get_lang('Delete')).'</a>';
-	return $return; 
+	return $return;
 }
 /**
  * Move a user defined field up or down
  *
  * @param string $direction the direction we have to move the field to (up or down)
  * @param unknown_type $field_id
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version July 2008
  * @since Dokeos 1.8.6
@@ -317,25 +317,25 @@ function move_user_field($direction,$field_id)
 {
 	// Databse table definitions
 	$table_user_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
-	
+
 	// check the parameters
 	if (!in_array($direction,array('moveup','movedown')) OR !is_numeric($field_id))
 	{
-		return false; 
+		return false;
 	}
-	
+
 	// determine the SQL sort direction
 	if ($direction == 'moveup')
 	{
 		$sortdirection = 'DESC';
 	}
-	else 
+	else
 	{
 		$sortdirection = 'ASC';
 	}
-	
-	$found = false; 
-	
+
+	$found = false;
+
 	$sql = "SELECT id, field_order FROM $table_user_field ORDER BY field_order $sortdirection";
 	$result = api_sql_query($sql,__FILE__,__LINE__);
 	while($row = Database::fetch_array($result))
@@ -343,10 +343,10 @@ function move_user_field($direction,$field_id)
 		if ($found)
 		{
 			$next_id = $row['id'];
-			$next_order = $row['field_order'];	
+			$next_order = $row['field_order'];
 			break;
 		}
-		
+
 		if ($field_id == $row['id'])
 		{
 			$this_id = $row['id'];
@@ -354,12 +354,12 @@ function move_user_field($direction,$field_id)
 			$found = true;
 		}
 	}
-	
+
 	$sql1 = "UPDATE ".$table_user_field." SET field_order = '".Database::escape_string($next_order)."' WHERE id =  '".Database::escape_string($this_id)."'";
 	$sql2 = "UPDATE ".$table_user_field." SET field_order = '".Database::escape_string($this_order)."' WHERE id =  '".Database::escape_string($next_id)."'";
 	api_sql_query($sql1,__FILE__,__LINE__);
 	api_sql_query($sql2,__FILE__,__LINE__);
-	
+
 	return true;
 }
 
@@ -368,7 +368,7 @@ function move_user_field($direction,$field_id)
  *
  * @param integer $field_id the id of the field that has to be deleted
  * @return boolean true if the field has been deleted, false if the field could not be deleted (for whatever reason)
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version July 2008
  * @since Dokeos 1.8.6
@@ -379,7 +379,7 @@ function delete_user_fields($field_id)
 	$table_user_field 			= Database::get_main_table(TABLE_MAIN_USER_FIELD);
 	$table_user_field_options	= Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
 	$table_user_field_values 	= Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-		
+
 	// delete the fields
 	$sql = "DELETE FROM $table_user_field WHERE id = '".Database::escape_string($field_id)."'";
 	$result = api_sql_query($sql,__FILE__,__LINE__);
@@ -388,11 +388,11 @@ function delete_user_fields($field_id)
 		// delete the field options
 		$sql = "DELETE FROM $table_user_field_options WHERE field_id = '".Database::escape_string($field_id)."'";
 		$result = api_sql_query($sql,__FILE__,__LINE__);
-		
+
 		// delete the field values
 		$sql = "DELETE FROM $table_user_field_values WHERE field_id = '".Database::escape_string($field_id)."'";
-		$result = api_sql_query($sql,__FILE__,__LINE__);	
-		
+		$result = api_sql_query($sql,__FILE__,__LINE__);
+
 		// recalculate the field_order because the value is used to show/hide the up/down icon
 		// and the field_order value cannot be bigger than the number of fields
 		$sql = "SELECT * FROM $table_user_field ORDER BY field_order ASC";
@@ -404,14 +404,14 @@ function delete_user_fields($field_id)
 			$result_reorder = api_sql_query($sql_reorder,__FILE__,__LINE__);
 			$i++;
 		}
-		
+
 		// field was deleted so we return true
 		return true;
 	}
-	else 
+	else
 	{
 		// the field was not deleted so we return false
-		return false; 
+		return false;
 	}
 }
 ?>

+ 35 - 35
main/admin/user_fields_add.php

@@ -44,44 +44,44 @@ function change_image_user_field (image_value) {
 	if (image_value==1) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_text.png', get_lang('AddUserFields'))."'".');
-			
+
 	} else if (image_value==2) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_text_area.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==3) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('add_user_field_howto.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==4) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_drop_down.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==5) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_multidropdown.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==6) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_data.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==7) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_date_time.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==8) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_doubleselect.png', get_lang('AddUserFields'))."'".');
-				
+
 	} else if (image_value==9) {
 		$("div#id_image_user_field").html("&nbsp;");
 		$("div#id_image_user_field").html('."'<br />".Display::return_icon('userfield_divider.png', get_lang('AddUserFields'))."'".');
-				
+
 	}
-}		
-	
-		
-		
+}
+
+
+
 </script>';
 // Database table definitions
 $table_admin	= Database :: get_main_table(TABLE_MAIN_ADMIN);
@@ -96,7 +96,7 @@ if ($_GET['action']<>'edit')
 {
 	$tool_name = get_lang('AddUserFields');
 }
-else 
+else
 {
 	$tool_name = get_lang('EditUserFields');
 }
@@ -149,8 +149,8 @@ if (is_numeric($_GET['field_id']))
 	$defaults['fieldtitle'] = $form_information['field_display_text'];
 	$defaults['fieldlabel'] = $form_information['field_variable'];
 	$defaults['fieldtype'] = $form_information['field_type'];
-	$defaults['fielddefaultvalue'] = $form_information['field_default_value'];									
-	
+	$defaults['fielddefaultvalue'] = $form_information['field_default_value'];
+
 	$count = 0;
 	// we have to concatenate the options
 	if (count($form_information['options'])>0) {
@@ -160,7 +160,7 @@ if (is_numeric($_GET['field_id']))
 			{
 				$defaults['fieldoptions'] = $defaults['fieldoptions'].'; '.$option['option_display_text'];
 			}
-			else 
+			else
 			{
 				$defaults['fieldoptions'] = $option['option_display_text'];
 			}
@@ -174,7 +174,7 @@ $form->setDefaults($defaults);
 		$text=get_lang('buttonEditUserField');
 	} else {
 		$class="add";
-		$text=get_lang('buttonAddUserField'); 
+		$text=get_lang('buttonAddUserField');
 	}
 // Submit button
 $form->addElement('style_submit_button', 'submit',$text, 'class='.$class.'');
@@ -190,13 +190,13 @@ if( $form->validate())
 		$fieldtitle = $field['fieldtitle'];
 		$fielddefault = $field['fielddefaultvalue'];
 		$fieldoptions = $field['fieldoptions']; //comma-separated list of options
-		
+
 		if (is_numeric($field['fieldid']) AND !empty($field['fieldid']))
 		{
 			UserManager:: save_extra_field_changes($field['fieldid'],$fieldlabel,$fieldtype,$fieldtitle,$fielddefault,$fieldoptions);
 			$message = get_lang('FieldEdited');
 		}
-		else 
+		else
 		{
 			$field_id = UserManager::create_extra_field($fieldlabel,$fieldtype,$fieldtitle,$fielddefault,$fieldoptions);
 			$message = get_lang('FieldAdded');
@@ -230,32 +230,32 @@ echo '<div id="id_image_user_field">';
 if(!empty($defaults['fieldtype'])) {
 	$image_value = $defaults['fieldtype'];
 	if ($image_value==1) {
-		echo '<br />'.Display::return_icon('userfield_text.png', get_lang('AddUserFields'));					
+		echo '<br />'.Display::return_icon('userfield_text.png', get_lang('AddUserFields'));
 	} else if ($image_value==2) {
-		echo '<br />'.Display::return_icon('userfield_text_area.png', get_lang('AddUserFields'));						
+		echo '<br />'.Display::return_icon('userfield_text_area.png', get_lang('AddUserFields'));
 	} else if ($image_value==3) {
-		echo '<br />'.Display::return_icon('add_user_field_howto.png', get_lang('AddUserFields'));						
+		echo '<br />'.Display::return_icon('add_user_field_howto.png', get_lang('AddUserFields'));
 	} else if ($image_value==4) {
-		echo '<br />'.Display::return_icon('userfield_drop_down.png', get_lang('AddUserFields'));						
+		echo '<br />'.Display::return_icon('userfield_drop_down.png', get_lang('AddUserFields'));
 	} else if ($image_value==5) {
-		echo '<br />'.Display::return_icon('userfield_multidropdown.png', get_lang('AddUserFields'));								
+		echo '<br />'.Display::return_icon('userfield_multidropdown.png', get_lang('AddUserFields'));
 	} else if ($image_value==6) {
-		echo '<br />'.Display::return_icon('userfield_data.png', get_lang('AddUserFields'));						
+		echo '<br />'.Display::return_icon('userfield_data.png', get_lang('AddUserFields'));
 	} else if ($image_value==7) {
-		echo '<br />'.Display::return_icon('userfield_date_time.png', get_lang('AddUserFields'));								
+		echo '<br />'.Display::return_icon('userfield_date_time.png', get_lang('AddUserFields'));
 	} else if ($image_value==8) {
-		echo '<br />'.Display::return_icon('userfield_doubleselect.png', get_lang('AddUserFields'));									
+		echo '<br />'.Display::return_icon('userfield_doubleselect.png', get_lang('AddUserFields'));
 	} else if ($image_value==9) {
-		echo '<br />'.Display::return_icon('userfield_divider.png', get_lang('AddUserFields'));						
+		echo '<br />'.Display::return_icon('userfield_divider.png', get_lang('AddUserFields'));
 	}
 } else {
-	echo '<br />'.Display::return_icon('userfield_text.png', get_lang('AddUserFields'));	
-}	
-echo '</div>';	
-			
-			
+	echo '<br />'.Display::return_icon('userfield_text.png', get_lang('AddUserFields'));
+}
+echo '</div>';
+
+
+
 
-		
 
 
 // footer

+ 27 - 27
main/admin/user_fields_options.php

@@ -75,7 +75,7 @@ if (isset ($_GET['action']))
 					{
 						Display :: display_confirmation_message(get_lang('FieldOptionMovedUp'));
 					}
-					else 
+					else
 					{
 						Display :: display_error_message(get_lang('CannotMoveFieldOption'));
 					}
@@ -83,17 +83,17 @@ if (isset ($_GET['action']))
 				break;
 			case 'movedown' :
 				if (api_is_platform_admin() && !empty($_GET['option_id']))
-				{					
+				{
 					if (move_user_field_option('movedown', $_GET['option_id']))
 					{
 						Display :: display_confirmation_message(get_lang('FieldOptionMovedDown'));
 					}
-					else 
+					else
 					{
 						Display :: display_error_message(get_lang('CannotMoveFieldOption'));
 					}
-				}				
-				break;			
+				}
+				break;
 		}
 	}
 }
@@ -124,11 +124,11 @@ function get_options_data($from, $number_of_items, $column, $direction)
 {
 	// Database table definition
 	$table_userfields_options 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-	
+
 	// The sql statement
-	$sql = "SELECT 
+	$sql = "SELECT
 				option_order 		AS col0,
-				option_display_text	AS col1,	
+				option_display_text	AS col1,
 				id 					AS col2
 			FROM $table_userfields_options WHERE field_id='".Database::escape_string($_GET['field_id'])."' ORDER BY option_order ASC";
 	$sql .= " LIMIT $from,$number_of_items";
@@ -138,39 +138,39 @@ function get_options_data($from, $number_of_items, $column, $direction)
 	{
 		$return[] = $option;
 	}
-	return $return;	
+	return $return;
 }
 
 function get_number_of_options($from=null, $number_of_items=null, $column=null, $direction=null)
 {
 	// Database table definition
 	$table_userfields_options 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-	
+
 	// The sql statement
 	$sql = "SELECT count(id) as total FROM $table_userfields_options WHERE field_id='".Database::escape_string($_GET['field_id'])."' ";
 	$res = api_sql_query($sql, __FILE__, __LINE__);
 	$row = Database::fetch_row($res);
-	return $row[0];	
+	return $row[0];
 }
 
 function actions_filter($option_id,$url_params,$row)
 {
-	global $number_of_options; 
+	global $number_of_options;
 
 	if ($row[0]<>1)
 	{
 		$return .= '<a href="'.api_get_self().'?action=moveup&amp;option_id='.$option_id.'&amp;field_id='.Security::remove_XSS($_GET['field_id']).'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('up.gif', get_lang('Up')).'</a>';
 	}
-	else 
+	else
 	{
 		$return .= Display::return_icon('blank.gif','',array('width'=>'21px'));
 	}
-	
+
 	// the down icon only has to appear when the row can be moved down (all but the last row)
 	if ($row[0]<>$number_of_options)
 	{
 		$return .= '<a href="'.api_get_self().'?action=movedown&amp;option_id='.$option_id.'&amp;field_id='.Security::remove_XSS($_GET['field_id']).'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('down.gif', get_lang('Down')).'</a>';
-	}	
+	}
 	return $return;
 }
 
@@ -179,7 +179,7 @@ function actions_filter($option_id,$url_params,$row)
  *
  * @param string $direction the direction we have to move the field to (up or down)
  * @param unknown_type $field_id
- * 
+ *
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  * @version July 2008
  * @since Dokeos 1.8.6
@@ -188,25 +188,25 @@ function move_user_field_option($direction,$option_id)
 {
 	// Database table definition
 	$table_userfields_options 	= Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
-	
+
 	// check the parameters
 	if (!in_array($direction,array('moveup','movedown')) OR !is_numeric($option_id))
 	{
-		return false; 
+		return false;
 	}
-	
+
 	// determine the SQL sort direction
 	if ($direction == 'moveup')
 	{
 		$sortdirection = 'DESC';
 	}
-	else 
+	else
 	{
 		$sortdirection = 'ASC';
 	}
-	
-	$found = false; 
-	
+
+	$found = false;
+
 	$sql = "SELECT id, option_order FROM $table_userfields_options  WHERE field_id='".Database::escape_string($_GET['field_id'])."' ORDER BY option_order $sortdirection";
 	$result = api_sql_query($sql,__FILE__,__LINE__);
 	while($row = Database::fetch_array($result))
@@ -214,10 +214,10 @@ function move_user_field_option($direction,$option_id)
 		if ($found)
 		{
 			$next_id = $row['id'];
-			$next_order = $row['option_order'];	
+			$next_order = $row['option_order'];
 			break;
 		}
-		
+
 		if ($option_id == $row['id'])
 		{
 			$this_id = $row['id'];
@@ -225,12 +225,12 @@ function move_user_field_option($direction,$option_id)
 			$found = true;
 		}
 	}
-	
+
 	$sql1 = "UPDATE ".$table_userfields_options." SET option_order = '".Database::escape_string($next_order)."' WHERE id =  '".Database::escape_string($this_id)."'";
 	$sql2 = "UPDATE ".$table_userfields_options." SET option_order = '".Database::escape_string($this_order)."' WHERE id =  '".Database::escape_string($next_id)."'";
 	api_sql_query($sql1,__FILE__,__LINE__);
 	api_sql_query($sql2,__FILE__,__LINE__);
-	
+
 	return true;
 }
 ?>

+ 193 - 188
main/admin/user_import.php

@@ -2,68 +2,73 @@
 /* For licensing terms, see /dokeos_license.txt */
 /**
 ==============================================================================
-*   This tool allows platform admins to add users by uploading a CSV or XML file
+* This tool allows platform admins to add users by uploading a CSV or XML file
 * @todo Add some langvars to DLTT
-*	@package dokeos.admin
+* @package dokeos.admin
 ==============================================================================
 */
+
 /**
- * validate the imported data
+ * Validate the imported data.
  */
- 
+
 $language_file = array ('admin', 'registration');
+
 require '../inc/global.inc.php';
-require_once api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php'; 
+require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
+
+// Set this option to true to enforce strict purification for usenames.
+$purification_option_for_usernames = false;
 
 function validate_data($users) {
 	global $defined_auth_sources;
-	$errors = array ();
-	$usernames = array ();
+	$errors = array();
+	$usernames = array();
 	foreach ($users as $index => $user) {
-		//1. check if mandatory fields are set	
-		$mandatory_fields = array ('LastName', 'FirstName');
+		// 1. Check if mandatory fields are set.
+		$mandatory_fields = array('LastName', 'FirstName');
 		if (api_get_setting('registration', 'email') == 'true') {
-			$mandatory_fields[] = 'Email';	
+			$mandatory_fields[] = 'Email';
 		}
 		foreach ($mandatory_fields as $key => $field) {
-			if (!isset ($user[$field]) || strlen($user[$field]) == 0) {
+			if (empty($user[$field])) {
 				$user['error'] = get_lang($field.'Mandatory');
 				$errors[] = $user;
 			}
 		}
-		//2. check username
-		if (isset ($user['UserName']) && strlen($user['UserName']) != 0) {
-			//2.1. check if no username was used twice in import file
-			if (isset ($usernames[$user['UserName']])) {
+		// 2. Check username, first, check whether it is empty.
+		if (!UserManager::is_username_empty($user['UserName'])) {
+			// 2.1. Check whether username is too long.
+			if (UserManager::is_username_too_long($user['UserName'])) {
+				$user['error'] = get_lang('UserNameTooLong');
+				$errors[] = $user;
+			}
+			// 2.2. Check whether the username was used twice in import file.
+			if (isset($usernames[$user['UserName']])) {
 				$user['error'] = get_lang('UserNameUsedTwice');
 				$errors[] = $user;
 			}
 			$usernames[$user['UserName']] = 1;
-			//2.2. check if username isn't allready in use in database
-			if (!UserManager :: is_username_available($user['UserName'])) {
+			// 2.3. Check whether username is allready occupied.
+			if (!UserManager::is_username_available($user['UserName'])) {
 				$user['error'] = get_lang('UserNameNotAvailable');
 				$errors[] = $user;
 			}
-			//2.3. check if username isn't longer than the 20 allowed characters
-			if (api_strlen($user['UserName']) > 20) {
-				$user['error'] = get_lang('UserNameTooLong');
-				$errors[] = $user;
-			}
 		}
-		//3. check status
-		if (isset ($user['Status']) && !api_status_exists($user['Status'])) {
+		// 3. Check status.
+		if (isset($user['Status']) && !api_status_exists($user['Status'])) {
 			$user['error'] = get_lang('WrongStatus');
 			$errors[] = $user;
 		}
-		//4. Check classname
-		if (isset ($user['ClassName']) && strlen($user['ClassName']) != 0) {
+		// 4. Check classname
+		if (!empty($user['ClassName'])) {
 			if (!ClassManager :: class_name_exists($user['ClassName'])) {
 				$user['error'] = get_lang('ClassNameNotAvailable');
 				$errors[] = $user;
 			}
 		}
-		//5. Check authentication source
-		if (isset ($user['AuthSource']) && strlen($user['AuthSource']) != 0) {
+		// 5. Check authentication source
+		if (!empty($user['AuthSource'])) {
 			if (!in_array($user['AuthSource'], $defined_auth_sources)) {
 				$user['error'] = get_lang('AuthSourceNotAvailable');
 				$errors[] = $user;
@@ -72,38 +77,33 @@ function validate_data($users) {
 	}
 	return $errors;
 }
+
 /**
- * Add missing user-information (which isn't required, like password, username
- * etc)
+ * Add missing user-information (which isn't required, like password, username etc).
  */
 function complete_missing_data($user) {
-	//1. Create a username if necessary
-	if (!isset ($user['UserName']) || strlen($user['UserName']) == 0) {
-		$username = api_strtolower(api_ereg_replace('[^a-zA-Z]', '', api_substr($user['FirstName'], 0, 3).' '.api_substr($user['LastName'], 0, 4)));
-		if (!UserManager :: is_username_available($username)) {
-			$i = 0;
-			$temp_username = $username.$i;
-			while (!UserManager :: is_username_available($temp_username)) {
-				$temp_username = $username.++$i;
-			}
-			$username = $temp_username;
-		}
-		$user['UserName'] = $username;
+	global $purification_option_for_usernames;
+	// 1. Create a username if necessary.
+	if (UserManager::is_username_empty($user['UserName'])) {
+		$user['UserName'] = UserManager::create_unique_username($user['FirstName'], $user['LastName']);
+	} else {
+		$user['UserName'] = UserManager::purify_username($user['UserName'], $purification_option_for_usernames);
 	}
-	//2. generate a password if necessary
-	if (!isset ($user['Password']) || strlen($user['Password']) == 0) {
+	// 2. Generate a password if necessary.
+	if (empty($user['Password'])) {
 		$user['Password'] = api_generate_password();
 	}
-	//3. set status if not allready set
-	if (!isset ($user['Status']) || strlen($user['Status']) == 0) {
+	// 3. Set status if not allready set.
+	if (empty($user['Status'])) {
 		$user['Status'] = 'user';
 	}
-	//4. set authsource if not allready set
-	if (!isset ($user['AuthSource']) || strlen($user['AuthSource']) == 0) {
+	// 4. Set authsource if not allready set.
+	if (empty($user['AuthSource'])) {
 		$user['AuthSource'] = PLATFORM_AUTH_SOURCE;
 	}
 	return $user;
 }
+
 /**
  * Save the imported data
  * @param   array   List of users
@@ -111,74 +111,76 @@ function complete_missing_data($user) {
  * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in
  */
 function save_data($users) {
-    global $inserted_in_course;
-    // not all scripts declare the $inserted_in_course array (although they should)
-    if (!isset($inserted_in_course)) { $inserted_in_course = array(); }
-	require_once(api_get_path(INCLUDE_PATH).'lib/mail.lib.inc.php');
+	global $inserted_in_course;
+	// Not all scripts declare the $inserted_in_course array (although they should).
+	if (!isset($inserted_in_course)) {
+		$inserted_in_course = array();
+	}
+	require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
 	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
-	$sendMail = $_POST['sendMail'] ? 1 : 0;
+	$send_mail = $_POST['sendMail'] ? 1 : 0;
 	if (is_array($users)) {
-        foreach ($users as $index => $user)	{
-    		$user = complete_missing_data($user);
-    		
-    		$user['Status'] = api_status_key($user['Status']);
-    		
-    		$user_id = UserManager :: create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], api_get_setting('PlatformLanguage'), $user['PhoneNumber'], '', $user['AuthSource']);
-            if (!is_array($user['Courses']) && !empty($user['Courses'])) {
-            	$user['Courses'] = array($user['Courses']);
-            }
-            if (is_array($user['Courses'])) {
-        		foreach ($user['Courses'] as $index => $course) {
-        			if (CourseManager :: course_exists($course)) {
-        				CourseManager :: subscribe_user($user_id, $course,$user['Status']);
-                        $c_info = CourseManager::get_course_information($course); 
-                        $inserted_in_course[$course] = $c_info['title'];
-                    } 
-                    if (CourseManager :: course_exists($course,true)) {
-                    	// also subscribe to virtual courses through check on visual code
-                        $list = CourseManager :: get_courses_info_from_visual_code($course);
-                        foreach ($list as $vcourse) {
-                        	if ($vcourse['code'] == $course) {
-                        		//ignore, this has already been inserted
-                        	} else {
-                                CourseManager :: subscribe_user($user_id, $vcourse['code'],$user['Status']);                		
-                                $inserted_in_course[$vcourse['code']] = $vcourse['title'];
-                        	}
-                        }
-                    }
-        		}
-            }
-    		if (strlen($user['ClassName']) > 0) {
-    			$class_id = ClassManager :: get_class_id($user['ClassName']);
-    			ClassManager :: add_user($user_id, $class_id);
-    		}
-    		
-    		//saving extra fields
+		foreach ($users as $index => $user)	{
+			$user = complete_missing_data($user);
+
+			$user['Status'] = api_status_key($user['Status']);
+
+			$user_id = UserManager :: create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], api_get_setting('PlatformLanguage'), $user['PhoneNumber'], '', $user['AuthSource']);
+			if (!is_array($user['Courses']) && !empty($user['Courses'])) {
+				$user['Courses'] = array($user['Courses']);
+			}
+			if (is_array($user['Courses'])) {
+				foreach ($user['Courses'] as $index => $course) {
+					if (CourseManager :: course_exists($course)) {
+						CourseManager :: subscribe_user($user_id, $course,$user['Status']);
+						$course_info = CourseManager::get_course_information($course);
+						$inserted_in_course[$course] = $course_info['title'];
+					}
+					if (CourseManager :: course_exists($course, true)) {
+						// Also subscribe to virtual courses through check on visual code.
+						$list = CourseManager :: get_courses_info_from_visual_code($course);
+						foreach ($list as $vcourse) {
+							if ($vcourse['code'] == $course) {
+								// Ignore, this has already been inserted.
+							} else {
+								CourseManager :: subscribe_user($user_id, $vcourse['code'],$user['Status']);
+								$inserted_in_course[$vcourse['code']] = $vcourse['title'];
+							}
+						}
+					}
+				}
+			}
+			if (!empty($user['ClassName'])) {
+				$class_id = ClassManager :: get_class_id($user['ClassName']);
+				ClassManager :: add_user($user_id, $class_id);
+			}
+
+			// Saving extra fields.
 			global $extra_fields;
-			//print_R($user);	
-			//we are sure the extra field exist
-			foreach($extra_fields as $extras) {			
+
+			// We are sure that the extra field exists.
+			foreach($extra_fields as $extras) {
 				if (isset($user[$extras[1]])) {
-						$key 	= $extras[1];					 
-						$value 	= $user[$extras[1]];
-						UserManager::update_extra_field_value($user_id,$key,$value);	
+					$key 	= $extras[1];
+					$value 	= $user[$extras[1]];
+					UserManager::update_extra_field_value($user_id, $key,$value);
 				}
 			}
-		
-    		if ($sendMail) {			
-    			$recipient_name = api_get_person_name($user['FirstName'], $user['LastName'], null, PERSON_NAME_EMAIL_ADDRESS);
-    			$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');			
-    			$emailbody = get_lang('Dear').api_get_person_name($user['FirstName'], $user['LastName']).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('Settings')." $user[UserName]\n".get_lang('Pass')." : $user[Password]\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".api_get_path('WEB_PATH')." \n\n".get_lang('Problem')."\n\n".get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator')."";						
-    			$sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-    		    $email_admin = api_get_setting('emailAdministrator');			
-    			@api_mail($recipient_name, $user['Email'], $emailsubject, $emailbody, $sender_name,$email_admin);
-    		}
-    
-    	}
-    }
+
+			if ($send_mail) {
+				$recipient_name = api_get_person_name($user['FirstName'], $user['LastName'], null, PERSON_NAME_EMAIL_ADDRESS);
+				$emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
+				$emailbody = get_lang('Dear').api_get_person_name($user['FirstName'], $user['LastName']).",\n\n".get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('Settings')." $user[UserName]\n".get_lang('Pass')." : $user[Password]\n\n".get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".api_get_path('WEB_PATH')." \n\n".get_lang('Problem')."\n\n".get_lang('Formula').",\n\n".api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".get_lang('Email')." : ".api_get_setting('emailAdministrator')."";
+				$sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
+				$email_admin = api_get_setting('emailAdministrator');
+				@api_mail($recipient_name, $user['Email'], $emailsubject, $emailbody, $sender_name, $email_admin);
+			}
+		}
+	}
 }
+
 /**
- * Read the CSV-file 
+ * Read the CSV-file
  * @param string $file Path to the CSV-file
  * @return array All userinformation read from the file
  */
@@ -196,6 +198,7 @@ function parse_csv_data($file) {
  * XML-parser: handle start of element
  */
 function element_start($parser, $data) {
+	$data = api_utf8_decode($data);
 	global $user;
 	global $current_tag;
 	switch ($data) {
@@ -206,22 +209,21 @@ function element_start($parser, $data) {
 			$current_tag = $data;
 	}
 }
+
 /**
  * XML-parser: handle end of element
  */
 function element_end($parser, $data) {
+	$data = api_utf8_decode($data);
 	global $user;
 	global $users;
 	global $current_value;
-	switch ($data)
-	{
+	switch ($data) {
 		case 'Contact' :
-			if ($user['Status'] == '5')
-			{
+			if ($user['Status'] == '5') {
 				$user['Status'] = STUDENT;
 			}
-			if ($user['Status'] == '1')
-			{
+			if ($user['Status'] == '1') {
 				$user['Status'] = COURSEMANAGER;
 			}
 			$users[] = $user;
@@ -231,13 +233,16 @@ function element_end($parser, $data) {
 			break;
 	}
 }
+
 /**
  * XML-parser: handle character data
  */
 function character_data($parser, $data) {
+	$data = trim(api_utf8_decode($data));
 	global $current_value;
 	$current_value = $data;
 }
+
 /**
  * Read the XML-file
  * @param string $file Path to the XML-file
@@ -248,27 +253,26 @@ function parse_xml_data($file) {
 	global $current_value;
 	global $user;
 	global $users;
-	$users = array ();
-	$parser = xml_parser_create();
+	$users = array();
+	$parser = xml_parser_create('UTF-8');
 	xml_set_element_handler($parser, 'element_start', 'element_end');
-	xml_set_character_data_handler($parser, "character_data");
+	xml_set_character_data_handler($parser, 'character_data');
 	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
-	xml_parse($parser, file_get_contents($file));
+	xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
 	xml_parser_free($parser);
 	return $users;
 }
-// name of the language file that needs to be included
 
 $cidReset = true;
 $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script();
-require_once (api_get_path(LIBRARY_PATH).'fileManage.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'classmanager.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'import.lib.php');
-require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
-$formSent = 0;
-$errorMsg = '';
+
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'import.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+
 $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
 if (is_array($extAuthSource)) {
 	$defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
@@ -276,136 +280,139 @@ if (is_array($extAuthSource)) {
 
 $tool_name = get_lang('ImportUserListXMLCSV');
 
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 
 set_time_limit(0);
-$extra_fields = Usermanager::get_extra_fields(0, 0, 5, 'ASC',false);
-$user_id_error=array();
+$extra_fields = Usermanager::get_extra_fields(0, 0, 5, 'ASC', false);
+$user_id_error = array();
 if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
 	$file_type = $_POST['file_type'];
 	Security::clear_token();
-    $tok = Security::get_token(); 
-	
-	if (strcmp($file_type,'csv')===0){ //&& strcmp($_FILES['import_file']['type'],'text/'.$file_type.'')===0) {		
+	$tok = Security::get_token();
+
+	if (strcmp($file_type, 'csv') === 0) { //&& strcmp($_FILES['import_file']['type'],'text/'.$file_type.'')===0) {
 		$users = parse_csv_data($_FILES['import_file']['tmp_name']);
 		$errors = validate_data($users);
-		$error_kind_file=false;
-	} elseif (strcmp($file_type,'xml')===0){// && strcmp($_FILES['import_file']['type'],'text/'.$file_type.'')===0) {		
+		$error_kind_file = false;
+	} elseif (strcmp($file_type, 'xml') === 0) { // && strcmp($_FILES['import_file']['type'],'text/'.$file_type.'')===0) {
 		$users = parse_xml_data($_FILES['import_file']['tmp_name']);
 		$errors = validate_data($users);
-		$error_kind_file=false;
+		$error_kind_file = false;
 	} else {
-		$error_kind_file=true;
+		$error_kind_file = true;
 	}
-	
-	//list user id whith error
-	$user_id_error=array();
-	if (is_array($errors)){ 
+
+	// List user id whith error.
+	$user_id_error = array();
+	if (is_array($errors)) {
 		foreach ($errors as $my_errors) {
-			$user_id_error[]=$my_errors['UserName'];
-		}	
+			$user_id_error[] = $my_errors['UserName'];
+		}
 	}
-	if  (is_array($users)) {
+	if (is_array($users)) {
 		foreach ($users as $my_user) {
-			if (!in_array($my_user['UserName'],$user_id_error)) {
-				$users_to_insert[]=$my_user;
+			if (!in_array($my_user['UserName'], $user_id_error)) {
+				$users_to_insert[] = $my_user;
 			}
 		}
 	}
-	
-    $inserted_in_course = array();
 
-	if (strcmp($_FILES['import_file']['type'],'text/'.$file_type.'') === 0) {
-		save_data($users_to_insert);	
+	$inserted_in_course = array();
+
+	if (strcmp($_FILES['import_file']['type'], 'text/'.$file_type.'') === 0) {
+		save_data($users_to_insert);
 	} else {
 		$error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
 		header('Location: '.api_get_self().'?warn='.urlencode($error_message).'&amp;file_type='.$file_type.'&amp;sec_token='.$tok);
 		exit ();
 	}
 
-	if ( count($errors)>0 ) {
-		$see_message_import=get_lang('FileImportedJustUsersThatAreNotRegistered');
+	if (count($errors) > 0) {
+		$see_message_import = get_lang('FileImportedJustUsersThatAreNotRegistered');
 	} else {
-		$see_message_import=get_lang('FileImported');
+		$see_message_import = get_lang('FileImported');
 	}
-        $msg2 = '';
-	if (count($inserted_in_course)>1) {
-        $msg2 .="<br>".get_lang('UsersSubscribedToSeveralCoursesBecauseOfVirtualCourses').':';
-        foreach ($inserted_in_course as $course) {
-        	$msg2 .= ' '.$course.',';
-        }
-        $msg2 = substr($msg2,0,-1);
-	    $msg2 .= "</br>";
-    }
-    
+	$msg2 = '';
+	if (count($inserted_in_course) > 1) {
+		$msg2 .= '<br>'.get_lang('UsersSubscribedToSeveralCoursesBecauseOfVirtualCourses').':';
+		foreach ($inserted_in_course as $course) {
+			$msg2 .= ' '.$course.',';
+		}
+		$msg2 = substr($msg2, 0, -1);
+		$msg2 .= '</br>';
+	}
+
 	if (count($errors) != 0) {
 		$error_message = '<ul>';
 		foreach ($errors as $index => $error_user) {
 			$error_message .= '<li><b>'.$error_user['error'].'</b>: ';
-			$error_message .= $error_user['UserName'].'&nbsp;('.$error_user['FirstName'].' '.$error_user['LastName'].')';
+			$error_message .= '<strong>'.$error_user['UserName'].'</strong>&nbsp;('.api_get_person_name($error_user['FirstName'], $error_user['LastName']).')';
 			$error_message .= '</li>';
 		}
 		$error_message .= '</ul>';
 	}
-      
+
 	header('Location: user_list.php?action=show_message&message='.urlencode($see_message_import).'&warn='.urlencode($error_message).'&sec_token='.$tok);
 	exit ();
-	
 }
 
 Display :: display_header($tool_name);
 //api_display_tool_title($tool_name);
 
-if($_FILES['import_file']['size'] == 0 AND $_POST) {
+if ($_FILES['import_file']['size'] == 0 AND $_POST) {
 	Display::display_error_message(get_lang('ThisFieldIsRequired'));
 }
 
-if ($error_kind_file===true) {
+if ($error_kind_file === true) {
 	Display :: display_error_message(get_lang('YouMustImportAFileAccordingToSelectedOption'));
 } else if (isset($_GET['warn'])) {
 	$error_message = Security::remove_XSS($_GET['warn']);
 	Display :: display_error_message($error_message);
 }
+
 $form = new FormValidator('user_import');
 $form->addElement('header', '', $tool_name);
 $form->addElement('hidden', 'formSent');
 $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
-$form->addRule('import_file', get_lang('ThisFieldIsRequired'), 'required');
+//$form->addRule('import_file', get_lang('ThisFieldIsRequired'), 'required'); // This rule does not work, probably due to the security mechanism here.
 $allowed_file_types = array ('xml', 'csv');
-$form->addRule('file', get_lang('InvalidExtension').' ('.implode(',', $allowed_file_types).')', 'filetype', $allowed_file_types);
+//$form->addRule('import_file', get_lang('InvalidExtension').' ('.implode(',', $allowed_file_types).')', 'filetype', $allowed_file_types); // This rule does not work, probably due to the security mechanism here.
 $form->addElement('radio', 'file_type', get_lang('FileType'), 'XML (<a href="exemple.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)', 'xml');
 $form->addElement('radio', 'file_type', null, 'CSV (<a href="exemple.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)', 'csv');
 $form->addElement('radio', 'sendMail', get_lang('SendMailToUsers'), get_lang('Yes'), 1);
 $form->addElement('radio', 'sendMail', null, get_lang('No'), 0);
-$form->addElement('style_submit_button', 'submit',get_lang('Import'),'class="save"');
+$form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
 $defaults['formSent'] = 1;
+$defaults['sendMail'] = 0;
 $defaults['file_type'] = 'xml';
 $form->setDefaults($defaults);
 $form->display();
 
-$list=array();
-$list_reponse=array();
-$result_xml = '' ;
-$i=0;
+$list = array();
+$list_reponse = array();
+$result_xml = '';
+$i = 0;
 $count_fields = count($extra_fields);
 if ($count_fields > 0) {
-	foreach($extra_fields as $extra) {
+	foreach ($extra_fields as $extra) {
 		$list[] = $extra[1];
-		$list_reponse[]='xxx';				
+		$list_reponse[] = 'xxx';
 		$spaces = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
-		$result_xml.=$spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';	
-		if ($i!=$count_fields-1)
-			$result_xml.='<br/>';
-		$i++;	
+		$result_xml .= $spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';
+		if ($i != $count_fields - 1) {
+			$result_xml .= '<br/>';
+		}
+		$i++;
 	}
 }
+
 ?>
 <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
 
 <blockquote>
 <pre>
-<b>LastName</b>;<b>FirstName</b>;<b>Email</b>;UserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;<font style="color:red;"><?php if(count($list)>0) echo implode(';', $list).';';?></font>Courses;ClassName;
-<b>xxx</b>;<b>xxx</b>;<b>xxx</b>;xxx;xxx;<?php echo implode('/',$defined_auth_sources); ?>;xxx;xxx;user/teacher/drh;<font style="color:red;"><?php if(count($list_reponse)>0) echo implode(';', $list_reponse).';';?></font>xxx1|xxx2|xxx3;xxx;<br />
+<b>LastName</b>;<b>FirstName</b>;<b>Email</b>;UserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;<font style="color:red;"><?php if (count($list) > 0) echo implode(';', $list).';'; ?></font>Courses;ClassName;
+<b>xxx</b>;<b>xxx</b>;<b>xxx</b>;xxx;xxx;<?php echo implode('/', $defined_auth_sources); ?>;xxx;xxx;user/teacher/drh;<font style="color:red;"><?php if (count($list_reponse) > 0) echo implode(';', $list_reponse).';'; ?></font>xxx1|xxx2|xxx3;xxx;<br />
 </pre>
 </blockquote>
 
@@ -413,28 +420,26 @@ if ($count_fields > 0) {
 
 <blockquote>
 <pre>
-&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
+&lt;?xml version=&quot;1.0&quot; encoding=&quot;<?php echo api_refine_encoding_id(api_get_system_encoding()); ?>&quot;?&gt;
 &lt;Contacts&gt;
     &lt;Contact&gt;
         <b>&lt;LastName&gt;xxx&lt;/LastName&gt;</b>
         <b>&lt;FirstName&gt;xxx&lt;/FirstName&gt;</b>
         &lt;UserName&gt;xxx&lt;/UserName&gt;
         &lt;Password&gt;xxx&lt;/Password&gt;
-        &lt;AuthSource&gt;<?php echo implode('/',$defined_auth_sources); ?>&lt;/AuthSource&gt;
+        &lt;AuthSource&gt;<?php echo implode('/', $defined_auth_sources); ?>&lt;/AuthSource&gt;
         <b>&lt;Email&gt;xxx&lt;/Email&gt;</b>
         &lt;OfficialCode&gt;xxx&lt;/OfficialCode&gt;
         &lt;PhoneNumber&gt;xxx&lt;/PhoneNumber&gt;
-        &lt;Status&gt;user/teacher/drh&lt;/Status&gt;         <?php if ($result_xml!='') { echo '<br /><font style="color:red;">',$result_xml;echo '</font>';} ?>        
+        &lt;Status&gt;user/teacher/drh&lt;/Status&gt;         <?php if ($result_xml != '') { echo '<br /><font style="color:red;">', $result_xml; echo '</font>'; } ?>
         &lt;Courses&gt;xxx1|xxx2|xxx3&lt;/Courses&gt;
-        &lt;ClassName&gt;class 1&lt;/ClassName&gt;        
+        &lt;ClassName&gt;class 1&lt;/ClassName&gt;
     &lt;/Contact&gt;
 &lt;/Contacts&gt;
 </pre>
 </blockquote>
 
 <?php
-
-
 /*
 ==============================================================================
 		FOOTER

+ 26 - 26
main/admin/user_information.php

@@ -23,10 +23,10 @@
 ==============================================================================
 */
 /**
-============================================================================== 
+==============================================================================
 	@author Bart Mollet
 *	@package dokeos.admin
-============================================================================== 
+==============================================================================
 */
 /*
 ==============================================================================
@@ -47,7 +47,7 @@ $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAd
 $interbreadcrumb[] = array ("url" => 'user_list.php', "name" => get_lang('UserList'));
 if( ! isset($_GET['user_id']))
 {
-	api_not_allowed();	
+	api_not_allowed();
 }
 $user = api_get_user_info($_GET['user_id']);
 $tool_name = api_get_person_name($user['firstName'], $user['lastName']).(empty($user['official_code'])?'':' ('.$user['official_code'].')');
@@ -64,10 +64,10 @@ if( isset($_GET['action']) ) {
 			}
 			else
 			{
-				Display::display_error_message(get_lang('CannotUnsubscribeUserFromCourse'));	
+				Display::display_error_message(get_lang('CannotUnsubscribeUserFromCourse'));
 			}
-			break;	
-	}	
+			break;
+	}
 }
 api_display_tool_title($tool_name);
 echo '<div align="right" style="margin-right:4em;"><a href="'.api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$_GET['user_id'].'" title="'.get_lang('Reporting').'">'.Display::return_icon('statistics.gif',get_lang('Reporting')).'</a></div>'."\n";
@@ -135,12 +135,12 @@ if(count($sessions)>0){
 	$header[] = array (get_lang('Title'), true);
 	$header[] = array (get_lang('Status'), true);
 	$header[] = array ('', false);
-	
+
 	foreach($sessions as $enreg){
-		
+
 		$data = array ();
 		$personal_course_list = array();
-		
+
 		$id_session = $enreg['id'];
 		$personal_course_list_sql = "SELECT DISTINCT course.code k, course.directory d, course.visual_code c, course.db_name db, course.title i, ".(api_is_western_name_order() ? "CONCAT(user.firstname,' ',user.lastname)" : "CONCAT(user.lastname,' ',user.firstname)")." t, email, course.course_language l, 1 sort, category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name, IF(session_course.id_coach = ".$user_id.",'2', '5')
 									 FROM $tbl_session_course as session_course
@@ -155,42 +155,42 @@ if(count($sessions)>0){
 										ON session_course.id_session = session.id
 									 WHERE session_course.id_session = $id_session
 									 ORDER BY i";
-	
+
 		$course_list_sql_result = api_sql_query($personal_course_list_sql, __FILE__, __LINE__);
-	
+
 		while ($result_row = Database::fetch_array($course_list_sql_result)){
 			$key = $result_row['id_session'].' - '.$result_row['k'];
 			$result_row['s'] = $result_row['14'];
-	
+
 			if(!isset($personal_course_list[$key])){
 				$personal_course_list[$key] = $result_row;
 			}
 		}
-		
+
 		foreach ($personal_course_list as $my_course){
-		
+
 			$row = array ();
-			
+
 			$row[] = $my_course['k'];
 			$row[] = $my_course['i'];
 			$row[] = $my_course['s'] == STUDENT ? get_lang('Student') : get_lang('Teacher');
 			$tools = '<a href="course_information.php?code='.$my_course['k'].'">'.Display::return_icon('synthese_view.gif').'</a>'.
 					'<a href="'.api_get_path(WEB_COURSE_PATH).$my_course['d'].'?id_session='.$id_session.'">'.Display::return_icon('course_home.gif', get_lang('CourseHomepage')).'</a>' .
 					'<a href="course_edit.php?course_code='.$my_course['k'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
-			
+
 			if( $my_course->status == STUDENT ){
 				$tools .= '<a href="user_information.php?action=unsubscribe&course_code='.$my_course['k'].'&user_id='.$user['user_id'].'">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
-						
+
 			}
 			$row[] = $tools;
 			$data[] = $row;
-					
+
 		}
-		
+
 		echo $enreg['name'];
 		Display :: display_sortable_table($header, $data, array (), array (), array ('user_id' => $_GET['user_id']));
 		echo '<br><br><br>';
-		
+
 	}
 }
 else{
@@ -225,7 +225,7 @@ if (Database::num_rows($res) > 0)
 		if( $course->status == STUDENT )
 		{
 			$tools .= '<a href="user_information.php?action=unsubscribe&course_code='.$course->code.'&user_id='.$user['user_id'].'">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
-				
+
 		}
 		$row[] = $tools;
 		$data[] = $row;
@@ -277,14 +277,14 @@ else
 global $_configuration;
 if ($_configuration['multiple_access_urls']==true) {
 	require_once(api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
-	$url_list= UrlManager::get_access_url_from_user($user['user_id']);	
+	$url_list= UrlManager::get_access_url_from_user($user['user_id']);
 	if (count($url_list) > 0) {
 		$header = array();
 		$header[] = array (get_lang('URL'), true);
 		$data = array ();
 		foreach ($url_list as $url) {
 			$row = array();
-			$row[] = $url['url'];			
+			$row[] = $url['url'];
 			$data[] = $row;
 		}
 		echo '<p><b>'.get_lang('URLList').'</b></p>';
@@ -298,9 +298,9 @@ if ($_configuration['multiple_access_urls']==true) {
 
 /*
 ==============================================================================
-		FOOTER 
+		FOOTER
 ==============================================================================
-*/ 
+*/
 Display::display_footer();
-?> 
+?>
 

+ 61 - 61
main/admin/user_list.php

@@ -31,11 +31,11 @@ function load_course_list (div_course,my_user_id) {
 			$("div#div_"+my_user_id).attr("class","blackboard_show");
 			$("div#div_"+my_user_id).attr("style","");
 		}
-	});		
+	});
 }
 function clear_course_list (div_course) {
 	$("div#"+div_course).html("&nbsp;");
-	$("div#"+div_course).hide("");	
+	$("div#"+div_course).hide("");
 }
 </script>';
 $htmlHeadXtra[] = '<style type="text/css" media="screen, projection">
@@ -50,7 +50,7 @@ $htmlHeadXtra[] = '<style type="text/css" media="screen, projection">
 }
 .blackboard_hide {
 	display: none;
-}	
+}
 ';
 // xajax
 $xajax = new xajax();
@@ -68,7 +68,7 @@ function courses_of_user($arg)
 {
 	// do some stuff based on $arg like query data from a database and
 	// put it into a variable like $newContent
-    //$newContent = 'werkt het? en met een beetje meer text, wordt dat goed opgelost? ';    
+    //$newContent = 'werkt het? en met een beetje meer text, wordt dat goed opgelost? ';
     $personal_course_list = UserManager::get_personal_session_course_list($arg);
     $newContent = '';
     if(count($personal_course_list)>0)
@@ -81,20 +81,20 @@ function courses_of_user($arg)
     else
     {
     	$newContent .= '- '.get_lang('None').' -<br />';
-    }   
+    }
     $newContent = api_convert_encoding($newContent,'utf-8',api_get_setting('platform_charset'));
-     
+
 	// Instantiate the xajaxResponse object
 	$objResponse = new xajaxResponse();
-        
+
 	// add a command to the response to assign the innerHTML attribute of
 	// the element with id="SomeElementId" to whatever the new content is
 	$objResponse->addAssign("user".$arg,"innerHTML", $newContent);
 	$objResponse->addReplace("coursesofuser".$arg,"alt", $newContent);
 	$objResponse->addReplace("coursesofuser".$arg,"title", $newContent);
-	
+
 	$objResponse->addAssign("user".$arg,"style.display", "block");
-        
+
 	//return the  xajaxResponse object
 	return $objResponse;
 }
@@ -107,14 +107,14 @@ function empty_courses_of_user($arg)
 {
 	// do some stuff based on $arg like query data from a database and
 	// put it into a variable like $newContent
-    $newContent = '';    
+    $newContent = '';
 	// Instantiate the xajaxResponse object
 	$objResponse = new xajaxResponse();
 	// add a command to the response to assign the innerHTML attribute of
 	// the element with id="SomeElementId" to whatever the new content is
 	$objResponse->addAssign("user".$arg,"innerHTML", $newContent);
-	
-        
+
+
 	//return the  xajaxResponse object
 	return $objResponse;
 }
@@ -122,16 +122,16 @@ function empty_courses_of_user($arg)
 
 $htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
 $htmlHeadXtra[] = '<style>
-.tooltipLinkInner { 
+.tooltipLinkInner {
 	position:relative;
 	float:left;
 	color:blue;
-	text-decoration:none;												
+	text-decoration:none;
 }
 </style>';
 
 $this_section = SECTION_PLATFORM_ADMIN;
-api_protect_admin_script(true);	
+api_protect_admin_script(true);
 
 /**
 *	Make sure this function is protected because it does NOT check password!
@@ -142,7 +142,7 @@ api_protect_admin_script(true);
 *	@author Evie Embrechts
 *   @author Yannick Warnier <yannick.warnier@dokeos.com>
 */
-function login_user($user_id) {	
+function login_user($user_id) {
 	//init ---------------------------------------------------------------------
     //Load $_user to be sure we clean it before logging in
 	global $uidReset, $loginFailed, $_configuration, $_user;
@@ -164,11 +164,11 @@ function login_user($user_id) {
 	$sql_query = "SELECT * FROM $main_user_table WHERE user_id='$user_id'";
 	$sql_result = api_sql_query($sql_query, __FILE__, __LINE__);
 	$result = Database :: fetch_array($sql_result);
-    
+
     // check if the user is allowed to 'login_as'
     $can_login_as = (api_is_platform_admin() OR (api_is_session_admin() && $result['status'] == 5 ));
     if (!$can_login_as) { return false; }
-	
+
 	$firstname = $result['firstname'];
 	$lastname = $result['lastname'];
 	$user_id = $result['user_id'];
@@ -211,7 +211,7 @@ function login_user($user_id) {
 			$user_data = Database::fetch_array($sql_result);
 
             //Delog the current user
-			 
+
 			LoginDelete($_SESSION["_user"]["user_id"]);
 
 			// Cleaning session variables
@@ -241,8 +241,8 @@ function login_user($user_id) {
 			$_SESSION['login_as'] = true; // will be usefull later to know if the user is actually an admin or not (example reporting)s
 
 			$target_url = api_get_path(WEB_PATH)."user_portal.php";
-			//$message .= "<br/>Login successful. Go to <a href=\"$target_url\">$target_url</a>";			
-			$message .= '<br />'.sprintf(get_lang('LoginSuccessfulGoToX'),'<a href="'.$target_url.'">'.$target_url.'</a>');				
+			//$message .= "<br/>Login successful. Go to <a href=\"$target_url\">$target_url</a>";
+			$message .= '<br />'.sprintf(get_lang('LoginSuccessfulGoToX'),'<a href="'.$target_url.'">'.$target_url.'</a>');
 			Display :: display_header(get_lang('UserList'));
 			Display :: display_normal_message($message,false);
 			Display :: display_footer();
@@ -260,14 +260,14 @@ function get_number_of_users()
 {
 	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
 	$sql = "SELECT COUNT(u.user_id) AS total_number_of_items FROM $user_table u";
-	
-	// adding the filter to see the user's only of the current access_url 
+
+	// adding the filter to see the user's only of the current access_url
     global $_configuration;
     if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
     	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-    	$sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";    		
+    	$sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
     }
-    
+
 	if ( isset ($_GET['keyword'])) {
 		$keyword = Database::escape_string($_GET['keyword']);
 		$sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%'  OR u.username LIKE '%".$keyword."%' OR u.email LIKE '%".$keyword."%'  OR u.official_code LIKE '%".$keyword."%') ";
@@ -276,7 +276,7 @@ function get_number_of_users()
 		$keyword_firstname = Database::escape_string($_GET['keyword_firstname']);
 		$keyword_lastname = Database::escape_string($_GET['keyword_lastname']);
 		$keyword_email = Database::escape_string($_GET['keyword_email']);
-		$keyword_officialcode = Database::escape_string($_GET['keyword_officialcode']);		
+		$keyword_officialcode = Database::escape_string($_GET['keyword_officialcode']);
 		$keyword_username = Database::escape_string($_GET['keyword_username']);
 		$keyword_status = Database::escape_string($_GET['keyword_status']);
 		$query_admin_table = '';
@@ -303,10 +303,10 @@ function get_number_of_users()
 		}
 		$sql .= " ) ";
 	}
-	
+
     // adding the filter to see the user's only of the current access_url
-	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {		
-    		$sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();   	  
+	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
+    		$sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
     }
 
 	$res = api_sql_query($sql, __FILE__, __LINE__);
@@ -327,7 +327,7 @@ function get_user_data($from, $number_of_items, $column, $direction)
 	$sql = "SELECT
                  u.user_id				AS col0,
                  u.official_code		AS col1,
-				 ".(api_is_western_name_order() 
+				 ".(api_is_western_name_order()
                  ? "u.firstname 			AS col2,
                  u.lastname 			AS col3,"
                  : "u.lastname 			AS col2,
@@ -339,14 +339,14 @@ function get_user_data($from, $number_of_items, $column, $direction)
                  u.user_id				AS col8 ".
                  ", u.expiration_date      AS exp ".
             " FROM $user_table u ";
-                 
-    // adding the filter to see the user's only of the current access_url 
+
+    // adding the filter to see the user's only of the current access_url
     global $_configuration;
     if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
     	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-    	$sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";    		
+    	$sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
     }
-                 
+
 	if (isset ($_GET['keyword'])) {
 		$keyword = Database::escape_string($_GET['keyword']);
 		$sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%'  OR u.username LIKE '%".$keyword."%'  OR u.official_code LIKE '%".$keyword."%' OR u.email LIKE '%".$keyword."%' )";
@@ -360,7 +360,7 @@ function get_user_data($from, $number_of_items, $column, $direction)
 		$keyword_status = Database::escape_string($_GET['keyword_status']);
 		$query_admin_table = '';
 		$keyword_admin = '';
-		
+
 		if ($keyword_status == SESSIONADMIN) {
 			$keyword_status = '%';
 			$query_admin_table = " , $admin_table a ";
@@ -383,23 +383,23 @@ function get_user_data($from, $number_of_items, $column, $direction)
 		}
 		$sql .= " ) ";
 	}
-	
+
     // adding the filter to see the user's only of the current access_url
-	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {		
-    		$sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();   	  
+	if ((api_is_platform_admin() || api_is_session_admin()) && $_configuration['multiple_access_urls']==true && api_get_current_access_url_id()!=-1) {
+    		$sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
     }
-    
+
     if (!in_array($direction, array('ASC','DESC'))) {
-    	$direction = 'ASC';    	
-    }  
+    	$direction = 'ASC';
+    }
     $column = intval($column);
     $from = intval($from);
     $number_of_items = intval($number_of_items);
-    
+
 	$sql .= " ORDER BY col$column $direction ";
-	$sql .= " LIMIT $from,$number_of_items";	
+	$sql .= " LIMIT $from,$number_of_items";
 	$res = api_sql_query($sql, __FILE__, __LINE__);
-		
+
 	$users = array ();
     $t = time();
 	while ($user = Database::fetch_row($res)) {
@@ -449,21 +449,21 @@ function modify_filter($user_id,$url_params,$row)
 	} else {
 		$result .= Display::return_icon('course_na.gif',get_lang('Courses')).'&nbsp;&nbsp;';
 	}
-	
+
 	if (api_is_platform_admin()) {
 		if (!$user_is_anonymous) {
 			$result .= '<a href="user_information.php?user_id='.$user_id.'">'.Display::return_icon('synthese_view.gif', get_lang('Info')).'</a>&nbsp;&nbsp;';
 		} else {
 			$result .= Display::return_icon('synthese_view_na.gif', get_lang('Info')).'&nbsp;&nbsp;';
 		}
-	}	
-	
+	}
+
     //only allow platform admins to login_as, or session admins only for students (not teachers nor other admins)
     if (api_is_platform_admin() || (api_is_session_admin() && $row['6'] == $statusname[STUDENT])) {
     	if (!$user_is_anonymous) {
-        	$result .= '<a href="user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>&nbsp;&nbsp;';        	
+        	$result .= '<a href="user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>&nbsp;&nbsp;';
     	} else {
-    		$result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';	
+    		$result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
     	}
     } else {
     	$result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
@@ -473,15 +473,15 @@ function modify_filter($user_id,$url_params,$row)
 	} else {
 		$result .= '<a href="../mySpace/myStudents.php?student='.$user_id.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>&nbsp;&nbsp;';
 	}
-	
+
 	if (api_is_platform_admin()) {
 		if (!$user_is_anonymous) {
 			$result .= '<a href="user_edit.php?user_id='.$user_id.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>&nbsp;&nbsp;';
 		} else {
 				$result .= Display::return_icon('edit_na.gif', get_lang('Edit')).'</a>&nbsp;&nbsp;';
 		}
-	
-		if ($row[0]<>$_user['user_id'] && $user_is_anonymous == false) { 
+
+		if ($row[0]<>$_user['user_id'] && $user_is_anonymous == false) {
 			// you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
 			$result .= '<a href="user_list.php?action=delete_user&amp;user_id='.$user_id.'&amp;'.$url_params.'&amp;sec_token='.$_SESSION['sec_token'].'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
 		} else {
@@ -516,7 +516,7 @@ function active_filter($active, $url_params, $row) {
 	}
 
     if ($action=='edit') {
-        $result = Display::return_icon($image.'.gif', get_lang('AccountExpired'));    	
+        $result = Display::return_icon($image.'.gif', get_lang('AccountExpired'));
     }elseif ($row['0']<>$_user['user_id']) { // you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
 		$result = '<a href="user_list.php?action='.$action.'&amp;user_id='.$row['0'].'&amp;'.$url_params.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon($image.'.gif', get_lang(ucfirst($action))).'</a>';
 	}
@@ -561,7 +561,7 @@ function lock_unlock_user($status,$user_id)
  *
  * @param integer $status
  * @return string translation
- * 
+ *
  * @version march 2008
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  */
@@ -623,7 +623,7 @@ else
 	$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 	$tool_name = get_lang('UserList');
 	Display :: display_header($tool_name, "");
-	  
+
 	//api_display_tool_title($tool_name);
 	if (isset ($_GET['action'])) {
 		$check = Security::check_token('get');
@@ -634,11 +634,11 @@ else
                     	Display::display_warning_message(urldecode($_GET['warn']));
                     }
                     if (!empty($_GET['message'])) {
-                        Display :: display_normal_message(stripslashes($_GET['message']));                    	
+                        Display :: display_normal_message(stripslashes($_GET['message']));
                     }
 					break;
 				case 'delete_user' :
-					if (api_is_platform_admin()) {						
+					if (api_is_platform_admin()) {
 						if ($user_id != $_user['user_id'] && UserManager :: delete_user($_GET['user_id'])) {
 							Display :: display_normal_message(get_lang('UserDeleted'));
 						} else {
@@ -654,7 +654,7 @@ else
 					$message=lock_unlock_user('unlock',$_GET['user_id']);
 					Display :: display_normal_message($message);
 					break;
-	
+
 			}
 			Security::clear_token();
 		}
@@ -667,7 +667,7 @@ else
 			switch ($_POST['action'])
 			{
 				case 'delete' :
-					if (api_is_platform_admin()) {	
+					if (api_is_platform_admin()) {
 						$number_of_selected_users = count($_POST['id']);
 						$number_of_deleted_users = 0;
 						if (is_array($_POST['id'])) {
@@ -706,14 +706,14 @@ else
 	echo '<div class="actions" style="width:100%;">';
 	if (api_is_platform_admin()) {
 		echo '<span style="float:right; padding-top:7px;">'.
-			 '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_add.php">'.Display::return_icon('add_user_big.gif',get_lang('AddUsers')).get_lang('AddUsers').'</a>'.									
+			 '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_add.php">'.Display::return_icon('add_user_big.gif',get_lang('AddUsers')).get_lang('AddUsers').'</a>'.
 			 '</span>';
 	}
 	$form->display();
 	echo '</div>';
 	if (isset ($_GET['keyword'])) {
 		$parameters = array ('keyword' => Security::remove_XSS($_GET['keyword']));
-	} elseif (isset ($_GET['keyword_firstname'])) { 
+	} elseif (isset ($_GET['keyword_firstname'])) {
 		$parameters['keyword_firstname'] 	= Security::remove_XSS($_GET['keyword_firstname']);
 		$parameters['keyword_lastname']	 	= Security::remove_XSS($_GET['keyword_lastname']);
 		$parameters['keyword_email'] 	 	= Security::remove_XSS($_GET['keyword_email']);

+ 2 - 2
main/auth/inscription.php

@@ -111,12 +111,12 @@ if ($display_all_form===true) {
 	}
 	*/
 	//	USERNAME
-	$form->addElement('text', 'username', get_lang('UserName'), array('size' => 20));
+	$form->addElement('text', 'username', get_lang('UserName'), array('size' => USERNAME_MAX_LENGTH));
 	$form->applyFilter('username','trim');
 	$form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
+	$form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
 	$form->addRule('username', get_lang('UsernameWrong'), 'username');
 	$form->addRule('username', get_lang('UserTaken'), 'username_available');
-	$form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'),'20'), 'maxlength',20);
 	//	PASSWORD
 	$form->addElement('password', 'pass1', get_lang('Pass'),         array('size' => 40));
 	$form->addElement('password', 'pass2', get_lang('Confirmation'), array('size' => 40));

+ 253 - 282
main/auth/profile.php

@@ -10,53 +10,60 @@
 * @package dokeos.auth
 ==============================================================================
 */
+
 /**
  * Init section
  */
-// name of the language file that needs to be included
-$language_file = array('registration','messages','userInfo');
+
+// Language files that should be included.
+$language_file = array('registration', 'messages', 'userInfo');
+
 $cidReset = true;
+
 require_once '../inc/global.inc.php';
+
 if (!isset($_GET['show'])) {
-	 if (api_get_setting('allow_social_tool')=='true' || api_get_setting('allow_message_tool')=='true') {
+	 if (api_get_setting('allow_social_tool') == 'true' || api_get_setting('allow_message_tool') == 'true') {
 		header('Location:../social/index.php');
 		exit;
 	}
 }
+
 require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+
 $this_section = SECTION_MYPROFILE;
-$_SESSION['this_section']=$this_section;
+$_SESSION['this_section'] = $this_section;
 
-if (!(isset ($_user['user_id']) && $_user['user_id']) || api_is_anonymous($_user['user_id'],true)) {
+if (!(isset($_user['user_id']) && $_user['user_id']) || api_is_anonymous($_user['user_id'], true)) {
     api_not_allowed(true);
 }
 
 $htmlHeadXtra[] = '<script src="../inc/lib/javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
 $htmlHeadXtra[] = '<script type="text/javascript">
 function confirmation(name) {
-	if (confirm("'.get_lang('AreYouSureToDelete').' " + name + " ?"))
+	if (confirm("'.get_lang('AreYouSureToDelete', '').' " + name + " ?"))
 		{return true;}
 	else
 		{return false;}
 }
 function show_image(image,width,height) {
 	width = parseInt(width) + 20;
-	height = parseInt(height) + 20;			
+	height = parseInt(height) + 20;
 	window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \'\');
-		
-}			
+
+}
 </script>';
 
-if (api_get_setting('allow_message_tool')=='true') {
+if (api_get_setting('allow_message_tool') == 'true') {
 	$htmlHeadXtra[] ='<script type="text/javascript">
 	$(document).ready(function(){
 		$(".message-content .message-delete").click(function(){
 			$(this).parents(".message-content").animate({ opacity: "hide" }, "slow");
 			$(".message-view").animate({ opacity: "show" }, "slow");
-		});				
-		
+		});
+
 	});
-	</script>';	
+	</script>';
 }
 $htmlHeadXtra[] ='<script type="text/javascript">
 function generate_open_id_form() {
@@ -73,20 +80,19 @@ function generate_open_id_form() {
 	});
 }
 </script>';
-$interbreadcrumb[]= array (
-	'url' => '../auth/profile.php',
-	'name' => get_lang('ModifyProfile')
-);
+
+$interbreadcrumb[] = array('url' => '../auth/profile.php', 'name' => get_lang('ModifyProfile'));
 if (!empty ($_GET['coursePath'])) {
 	$course_url = api_get_path(WEB_COURSE_PATH).htmlentities(strip_tags($_GET['coursePath'])).'/index.php';
-	$interbreadcrumb[] = array ('url' => $course_url, 'name' => Security::remove_XSS($_GET['courseCode']));
+	$interbreadcrumb[] = array('url' => $course_url, 'name' => Security::remove_XSS($_GET['courseCode']));
 }
+
 $warning_msg = '';
-if(!empty($_GET['fe'])) {
+if (!empty($_GET['fe'])) {
 	$warning_msg .= get_lang('UplUnableToSaveFileFilteredExtension');
 	$_GET['fe'] = null;
 }
-if(!empty($_GET['cp'])) {
+if (!empty($_GET['cp'])) {
 	$warning_msg .= get_lang('CurrentPasswordEmptyOrIncorrect');
 	$_GET['cp'] = null;
 }
@@ -109,10 +115,7 @@ require_once api_get_path(LIBRARY_PATH).'image.lib.php';
 require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
 require_once api_get_path(LIBRARY_PATH).'social.lib.php';
 
-if (is_profile_editable())
-	$tool_name = get_lang('ModifProfile');
-else
-	$tool_name = get_lang('ViewProfile');
+$tool_name = is_profile_editable() ? get_lang('ModifProfile') : get_lang('ViewProfile');
 
 $table_user = Database :: get_main_table(TABLE_MAIN_USER);
 
@@ -121,39 +124,38 @@ $table_user = Database :: get_main_table(TABLE_MAIN_USER);
 	Form
 -----------------------------------------------------------
 */
+
 /*
  * Get initial values for all fields.
  */
-
 $user_data = UserManager::get_user_info_by_id(api_get_user_id());
-$array_list_key=UserManager::get_api_keys(api_get_user_id());
-$id_temp_key=UserManager::get_api_key_id(api_get_user_id(),'dokeos');
-$value_array=$array_list_key[$id_temp_key];
-$user_data['api_key_generate']=$value_array;
+$array_list_key = UserManager::get_api_keys(api_get_user_id());
+$id_temp_key = UserManager::get_api_key_id(api_get_user_id(), 'dokeos');
+$value_array = $array_list_key[$id_temp_key];
+$user_data['api_key_generate'] = $value_array;
 
 if ($user_data !== false) {
-	if (is_null($user_data['language']))
+	if (is_null($user_data['language'])) {
 		$user_data['language'] = api_get_setting('platformLanguage');
+	}
 }
 
 /*
  * Initialize the form.
  */
-$form = new FormValidator('profile', 'post', api_get_self()."?".str_replace('&fe=1','',$_SERVER['QUERY_STRING']), null, array('style' => 'width: 75%; float: '.($text_dir=='rtl'?'right;':'left;')));
+$form = new FormValidator('profile', 'post', api_get_self()."?".str_replace('&fe=1', '', $_SERVER['QUERY_STRING']), null, array('style' => 'width: 75%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;')));
 
 /* Make sure this is the first submit on the form, even though it is hidden!
  * Otherwise, if a user has productions and presses ENTER to submit, he will
  * attempt to delete the first production in the list. */
-//if (is_profile_editable())
+//if (is_profile_editable()) {
 //	$form->addElement('style_submit_button', null, get_lang('SaveSettings'), 'class="save"', array('style' => 'visibility:hidden;'));
+//}
 
 //	SUBMIT (visible)
-/*if (is_profile_editable())
-{
+/*if (is_profile_editable()) {
 	$form->addElement('style_submit_button', 'apply_change', get_lang('SaveSettings'), 'class="save"');
-}
-else
-{
+} else {
 	$form->freeze();
 }*/
 
@@ -174,18 +176,19 @@ if (api_is_western_name_order()) {
 	$form->addElement('text', 'lastname',  get_lang('LastName'),  array('size' => 40));
 	$form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
 }
-if (api_get_setting('profile', 'name') !== 'true')
+if (api_get_setting('profile', 'name') !== 'true') {
 	$form->freeze(array('lastname', 'firstname'));
+}
 $form->applyFilter(array('lastname', 'firstname'), 'stripslashes');
 $form->applyFilter(array('lastname', 'firstname'), 'trim');
 $form->addRule('lastname' , get_lang('ThisFieldIsRequired'), 'required');
 $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 
-
 //	USERNAME
-$form->addElement('text', 'username', get_lang('UserName'), array('size' => 40));
-if (api_get_setting('profile', 'login') !== 'true')
+$form->addElement('text', 'username', get_lang('UserName'), array('maxlength' => USERNAME_MAX_LENGTH, 'size' => 40));
+if (api_get_setting('profile', 'login') !== 'true') {
 	$form->freeze('username');
+}
 $form->applyFilter('username', 'stripslashes');
 $form->applyFilter('username', 'trim');
 $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
@@ -195,49 +198,57 @@ $form->addRule('username', get_lang('UserTaken'), 'username_available', $user_da
 //	OFFICIAL CODE
 if (CONFVAL_ASK_FOR_OFFICIAL_CODE) {
 	$form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => 40));
-	if (api_get_setting('profile', 'officialcode') !== 'true')
+	if (api_get_setting('profile', 'officialcode') !== 'true') {
 		$form->freeze('official_code');
+	}
 	$form->applyFilter('official_code', 'stripslashes');
 	$form->applyFilter('official_code', 'trim');
-	if (api_get_setting('registration', 'officialcode') == 'true' && api_get_setting('profile', 'officialcode') == 'true')
+	if (api_get_setting('registration', 'officialcode') == 'true' && api_get_setting('profile', 'officialcode') == 'true') {
 		$form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
+	}
 }
 
 //	EMAIL
 $form->addElement('text', 'email', get_lang('Email'), array('size' => 40));
-if (api_get_setting('profile', 'email') !== 'true')
+if (api_get_setting('profile', 'email') !== 'true') {
 	$form->freeze('email');
+}
 $form->applyFilter('email', 'stripslashes');
 $form->applyFilter('email', 'trim');
-if (api_get_setting('registration', 'email') == 'true')
+if (api_get_setting('registration', 'email') == 'true') {
 	$form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
+}
 $form->addRule('email', get_lang('EmailWrong'), 'email');
 
 // OPENID URL
-if(is_profile_editable() && api_get_setting('openid_authentication')=='true') {
+if (is_profile_editable() && api_get_setting('openid_authentication') == 'true') {
 	$form->addElement('text', 'openid', get_lang('OpenIDURL'), array('size' => 40));
-	if (api_get_setting('profile', 'openid') !== 'true')
+	if (api_get_setting('profile', 'openid') !== 'true') {
 		$form->freeze('openid');
+	}
 	$form->applyFilter('openid', 'trim');
-	//if (api_get_setting('registration', 'openid') == 'true')
+	//if (api_get_setting('registration', 'openid') == 'true') {
 	//	$form->addRule('openid', get_lang('ThisFieldIsRequired'), 'required');
+	//}
 }
 
 //	PHONE
 $form->addElement('text', 'phone', get_lang('phone'), array('size' => 20));
-if (api_get_setting('profile', 'phone') !== 'true')
+if (api_get_setting('profile', 'phone') !== 'true') {
 	$form->freeze('phone');
+}
 $form->applyFilter('phone', 'stripslashes');
 $form->applyFilter('phone', 'trim');
-/*if (api_get_setting('registration', 'phone') == 'true')
+/*if (api_get_setting('registration', 'phone') == 'true') {
 	$form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
+}
 $form->addRule('phone', get_lang('EmailWrong'), 'email');*/
 
 //	PICTURE
 if (is_profile_editable() && api_get_setting('profile', 'picture') == 'true') {
 	$form->addElement('file', 'picture', ($user_data['picture_uri'] != '' ? get_lang('UpdateImage') : get_lang('AddImage')));
 	$form->add_progress_bar();
-	if( strlen($user_data['picture_uri']) > 0) {
+	if (!empty($user_data['picture_uri'])) {
 		$form->addElement('checkbox', 'remove_picture', null, get_lang('DelImage'));
 	}
 	$allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
@@ -246,25 +257,26 @@ if (is_profile_editable() && api_get_setting('profile', 'picture') == 'true') {
 
 //	LANGUAGE
 $form->addElement('select_language', 'language', get_lang('Language'));
-if (api_get_setting('profile', 'language') !== 'true')
+if (api_get_setting('profile', 'language') !== 'true') {
 	$form->freeze('language');
+}
 
 //	EXTENDED PROFILE  this make the page very slow!
 if (api_get_setting('extended_profile') == 'true') {
-	if ($_GET['type']=='extended') {
-		//$form->addElement('html', '<a href="#" onclick="javascript:show_extend();"> show_extend_profile</a>');			
-		$form->addElement('static', null, '<em>'.get_lang('OptionalTextFields').'</em>');	
+	if ($_GET['type'] == 'extended') {
+		//$form->addElement('html', '<a href="javascript: void(0);" onclick="javascript: show_extend();"> show_extend_profile</a>');
+		$form->addElement('static', null, '<em>'.get_lang('OptionalTextFields').'</em>');
 		//	MY COMPETENCES
 		$form->add_html_editor('competences', get_lang('MyCompetences'), false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
 		//	MY DIPLOMAS
 		$form->add_html_editor('diplomas', get_lang('MyDiplomas'), false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
 		//	WHAT I AM ABLE TO TEACH
 		$form->add_html_editor('teach', get_lang('MyTeach'), false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
-	
+
 		//	MY PRODUCTIONS
 		$form->addElement('file', 'production', get_lang('MyProductions'));
-		if ($production_list = UserManager::build_production_list($_user['user_id'],'',true)) {
-				$form->addElement('static', 'productions_list', null, $production_list);
+		if ($production_list = UserManager::build_production_list($_user['user_id'], '', true)) {
+			$form->addElement('static', 'productions_list', null, $production_list);
 		}
 		//	MY PERSONAL OPEN AREA
 		$form->add_html_editor('openarea', get_lang('MyPersonalOpenArea'), false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
@@ -275,26 +287,26 @@ if (api_get_setting('extended_profile') == 'true') {
 
 //	PASSWORD
 if (is_profile_editable() && api_get_setting('profile', 'password') == 'true') {
-	
+
 	$form->addElement('password', 'password0', get_lang('Pass'), array('size' => 40));
 	$form->addElement('static', null, null, '<em>'.get_lang('Enter2passToChange').'</em>');
-	$form->addElement('password', 'password1', get_lang('NewPass'),         array('size' => 40));
+	$form->addElement('password', 'password1', get_lang('NewPass'), array('size' => 40));
 	$form->addElement('password', 'password2', get_lang('Confirmation'), array('size' => 40));
 	//	user must enter identical password twice so we can prevent some user errors
 	$form->addRule(array('password1', 'password2'), get_lang('PassTwo'), 'compare');
-	if (CHECK_PASS_EASY_TO_FIND)
+	if (CHECK_PASS_EASY_TO_FIND) {
 		$form->addRule('password1', get_lang('PassTooEasy').': '.api_generate_password(), 'callback', 'api_check_password');
-		
+	}
 }
 
 // EXTRA FIELDS
-$extra = UserManager::get_extra_fields(0,50,5,'ASC');
-$extra_data = UserManager::get_extra_user_data(api_get_user_id(),true);
-foreach($extra as $id => $field_details) {
-	if($field_details[6] == 0) {
+$extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
+$extra_data = UserManager::get_extra_user_data(api_get_user_id(), true);
+foreach ($extra as $id => $field_details) {
+	if ($field_details[6] == 0) {
 		continue;
 	}
-	switch($field_details[2]) {
+	switch ($field_details[2]) {
 		case USER_FIELD_TYPE_TEXT:
 			$form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 40));
 			$form->applyFilter('extra_'.$field_details[1], 'stripslashes');
@@ -310,91 +322,86 @@ foreach($extra as $id => $field_details) {
 			break;
 		case USER_FIELD_TYPE_RADIO:
 			$group = array();
-			foreach($field_details[9] as $option_id => $option_details) {
+			foreach ($field_details[9] as $option_id => $option_details) {
 				$options[$option_details[1]] = $option_details[2];
-				$group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1],$option_details[2].'<br />',$option_details[1]);
+				$group[] =& HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1], $option_details[2].'<br />', $option_details[1]);
 			}
 			$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '');
-			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);	
+			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
 			break;
 		case USER_FIELD_TYPE_SELECT:
 			$options = array();
-			foreach($field_details[9] as $option_id => $option_details) {
+			foreach ($field_details[9] as $option_id => $option_details) {
 				$options[$option_details[1]] = $option_details[2];
 			}
-			$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,'');	
-			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);			
+			$form->addElement('select', 'extra_'.$field_details[1], $field_details[3], $options, '');
+			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
 			break;
 		case USER_FIELD_TYPE_SELECT_MULTIPLE:
 			$options = array();
-			foreach($field_details[9] as $option_id => $option_details) {
+			foreach ($field_details[9] as $option_id => $option_details) {
 				$options[$option_details[1]] = $option_details[2];
 			}
-			$form->addElement('select','extra_'.$field_details[1],$field_details[3],$options,array('multiple' => 'multiple'));
-			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);	
+			$form->addElement('select', 'extra_'.$field_details[1], $field_details[3], $options, array('multiple' => 'multiple'));
+			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
 			break;
 		case USER_FIELD_TYPE_DATE:
-			$form->addElement('datepickerdate', 'extra_'.$field_details[1],$field_details[3], array('form_name'=>'profile'));
-			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);						
+			$form->addElement('datepickerdate', 'extra_'.$field_details[1], $field_details[3], array('form_name' => 'profile'));
+			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
 			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
 			$form->applyFilter('theme', 'trim');
 			$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
 			$form -> setDefaults($defaults);
 			break;
 		case USER_FIELD_TYPE_DATETIME:
-			$form->addElement('datepicker', 'extra_'.$field_details[1],$field_details[3], array('form_name'=>'profile'));
-			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear',1900);	
+			$form->addElement('datepicker', 'extra_'.$field_details[1],$field_details[3], array('form_name' => 'profile'));
+			$form->_elements[$form->_elementIndex['extra_'.$field_details[1]]]->setLocalOption('minYear', 1900);
 			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
 			$form->applyFilter('theme', 'trim');
 			$defaults['extra_'.$field_details[1]] = date('Y-m-d 12:00:00');
 			$form -> setDefaults($defaults);
 			break;
 		case USER_FIELD_TYPE_DOUBLE_SELECT:
-			foreach ($field_details[9] as $key=>$element) {
+			foreach ($field_details[9] as $key => $element) {
 				if ($element[2][0] == '*') {
-					$values['*'][$element[0]] = str_replace('*','',$element[2]);
+					$values['*'][$element[0]] = str_replace('*', '', $element[2]);
 				} else {
 					$values[0][$element[0]] = $element[2];
 				}
 			}
-			
-			$group='';
-			$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1],'',$values[0],'');
-			$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1].'*','',$values['*'],'');
+
+			$group = '';
+			$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1], '', $values[0], '');
+			$group[] =& HTML_QuickForm::createElement('select', 'extra_'.$field_details[1].'*', '', $values['*'], '');
 			$form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '&nbsp;');
 			if ($field_details[7] == 0)	$form->freeze('extra_'.$field_details[1]);
 
 			// recoding the selected values for double : if the user has selected certain values, we have to assign them to the correct select form
-			if (key_exists('extra_'.$field_details[1], $extra_data))
-			{
+			if (key_exists('extra_'.$field_details[1], $extra_data)) {
 				// exploding all the selected values (of both select forms)
-				$selected_values = explode(';',$extra_data['extra_'.$field_details[1]]);
-				$extra_data['extra_'.$field_details[1]]  =array();
-				
+				$selected_values = explode(';', $extra_data['extra_'.$field_details[1]]);
+				$extra_data['extra_'.$field_details[1]] = array();
+
 				// looping through the selected values and assigning the selected values to either the first or second select form
-				foreach ($selected_values as $key=>$selected_value)
-				{
-					if (key_exists($selected_value,$values[0]))
-					{
+				foreach ($selected_values as $key=>$selected_value) {
+					if (key_exists($selected_value,$values[0])) {
 						$extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1]] = $selected_value;
-					}
-					else 
-					{
+					} else {
 						$extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1].'*'] = $selected_value;
 					}
 				}
 			}
 			break;
 		case USER_FIELD_TYPE_DIVIDER:
-			$form->addElement('static',$field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
+			$form->addElement('static', $field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
 			break;
 	}
 }
 if (api_get_setting('profile', 'apikeys') == 'true') {
-	$form->addElement('html','<div id="div_api_key">');
-	$form->addElement('text', 'api_key_generate', get_lang('MyApiKey'), array('size' => 40,'id' => 'id_api_key_generate'));
-	$form->addElement('html','</div>');
-	$form->addElement('button', 'generate_api_key', get_lang('GenerateApiKey'),array('id' => 'id_generate_api_key','onclick' => 'generate_open_id_form()'));//generate_open_id_form()
+	$form->addElement('html', '<div id="div_api_key">');
+	$form->addElement('text', 'api_key_generate', get_lang('MyApiKey'), array('size' => 40, 'id' => 'id_api_key_generate'));
+	$form->addElement('html', '</div>');
+	$form->addElement('button', 'generate_api_key', get_lang('GenerateApiKey'), array('id' => 'id_generate_api_key', 'onclick' => 'javascript: generate_open_id_form();')); //generate_open_id_form()
 }
 //	SUBMIT
 if (is_profile_editable()) {
@@ -403,7 +410,7 @@ if (is_profile_editable()) {
 	$form->freeze();
 }
 
-$user_data = array_merge($user_data,$extra_data);
+$user_data = array_merge($user_data, $extra_data);
 $form->setDefaults($user_data);
 
 /*
@@ -423,8 +430,7 @@ $form->setDefaults($user_data);
  *
  * @return	boolean	Editability of the profile
  */
-function is_profile_editable()
-{
+function is_profile_editable() {
 	return $GLOBALS['profileIsEditable'];
 }
 
@@ -440,23 +446,23 @@ function is_profile_editable()
  * @param	$user_id User id
  * @return	The filename of the new picture or FALSE if the upload has failed
  */
-function upload_user_image($user_id)
-{
+function upload_user_image($user_id) {
+
 	/* Originally added by Miguel (miguel@cesga.es) - 2003-11-04
 	 * Code Refactoring by Hugues Peeters (hugues.peeters@claroline.net) - 2003-11-24
 	 * Moved inside a function and refactored by Thomas Corthals - 2005-11-04
 	 */
 
-	$image_path = UserManager::get_user_picture_path_by_id($user_id,'system',true);
+	$image_path = UserManager::get_user_picture_path_by_id($user_id, 'system', true);
 	$image_repository = $image_path['dir'];
 	$existing_image = $image_path['file'];
-  	$file_extension = explode('.', $_FILES['picture']['name']);
+	$file_extension = explode('.', $_FILES['picture']['name']);
 	$file_extension = strtolower($file_extension[count($file_extension) - 1]);
 
 	if (!file_exists($image_repository)) {
 		mkpath($image_repository);
-	} 
-	
+	}
+
 	if ($existing_image != '') {
 		if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE) {
 			$picture_filename = $existing_image;
@@ -474,36 +480,36 @@ function upload_user_image($user_id)
 	} else {
 		$picture_filename = (PREFIX_IMAGE_FILENAME_WITH_UID ? $user_id.'_' : '').uniqid('').'.'.$file_extension;
 	}
-	
+
 	// get the picture and resize only if the picture is bigger width
-	$picture_infos=@getimagesize($_FILES['picture']['tmp_name']);	
-	$type=$picture_infos[2];
+	$picture_infos = @getimagesize($_FILES['picture']['tmp_name']);
+	$type = $picture_infos[2];
 	$small_temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 22); //small picture
 	$medium_temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 85); //medium picture
 	$temp = UserManager::resize_picture($_FILES['picture']['tmp_name'], 200); // normal picture
 	$big_temp = new image($_FILES['picture']['tmp_name']); // original picture
-	
+
     switch (!empty($type)) {
 	    case 2 :
-	    	$small_temp->send_image('JPG',$image_repository.'small_'.$picture_filename); 
-	    	$medium_temp->send_image('JPG',$image_repository.'medium_'.$picture_filename);
-	    	$temp->send_image('JPG',$image_repository.$picture_filename);
-	    	$big_temp->send_image('JPG',$image_repository.'big_'.$picture_filename);	    		 
-	    	break;
+	    	$small_temp->send_image('JPG', $image_repository.'small_'.$picture_filename);
+	    	$medium_temp->send_image('JPG', $image_repository.'medium_'.$picture_filename);
+	    	$temp->send_image('JPG', $image_repository.$picture_filename);
+	    	$big_temp->send_image('JPG', $image_repository.'big_'.$picture_filename);
+            break;
 	    case 3 :
-	    	$small_temp->send_image('PNG',$image_repository.'small_'.$picture_filename);
-	    	$medium_temp->send_image('PNG',$image_repository.'medium_'.$picture_filename);
-	    	$temp->send_image('PNG',$image_repository.$picture_filename);
-	    	$big_temp->send_image('PNG',$image_repository.'big_'.$picture_filename);
-	    	break;
+	    	$small_temp->send_image('PNG', $image_repository.'small_'.$picture_filename);
+	    	$medium_temp->send_image('PNG', $image_repository.'medium_'.$picture_filename);
+	    	$temp->send_image('PNG', $image_repository.$picture_filename);
+	    	$big_temp->send_image('PNG', $image_repository.'big_'.$picture_filename);
+            break;
 	    case 1 :
-	    	$small_temp->send_image('GIF',$image_repository.'small_'.$picture_filename);
-	    	$medium_temp->send_image('GIF',$image_repository.'medium_'.$picture_filename);
-	    	$temp->send_image('GIF',$image_repository.$picture_filename);
-	    	$big_temp->send_image('GIF',$image_repository.'big_'.$picture_filename);	    		 
-	    	break;
+	    	$small_temp->send_image('GIF', $image_repository.'small_'.$picture_filename);
+	    	$medium_temp->send_image('GIF', $image_repository.'medium_'.$picture_filename);
+	    	$temp->send_image('GIF', $image_repository.$picture_filename);
+	    	$big_temp->send_image('GIF', $image_repository.'big_'.$picture_filename);
+            break;
     }
-    return $picture_filename;    
+    return $picture_filename;
 }
 
 /**
@@ -511,20 +517,15 @@ function upload_user_image($user_id)
  *
  * @param	$user_id	User id
  */
-function remove_user_image($user_id)
-{
-	$image_path = UserManager::get_user_picture_path_by_id($user_id,'system');
+function remove_user_image($user_id) {
+	$image_path = UserManager::get_user_picture_path_by_id($user_id, 'system');
 	$image_repository = $image_path['dir'];
 	$image = $image_path['file'];
 
-	if ($image != '')
-	{
-		if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) 
-		{
+	if (!empty($image)) {
+		if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
 			@rename($image_repository.$image, $image_repository.'deleted_'.date('Y_m_d_H_i_s').'_'.$image);
-		}
-		else
-		{
+		} else {
 			@unlink($image_repository.$image);
 		}
 	}
@@ -542,29 +543,26 @@ function remove_user_image($user_id)
  * @param	$user_id	User id
  * @return	The filename of the new production or FALSE if the upload has failed
  */
-function upload_user_production($user_id)
-{
-	$image_path = UserManager::get_user_picture_path_by_id($user_id,'system',true);
-	
+function upload_user_production($user_id) {
+	$image_path = UserManager::get_user_picture_path_by_id($user_id, 'system', true);
+
 	$production_repository = $image_path['dir'].$user_id.'/';
 
-	if (!file_exists($production_repository)) 
-	{
+	if (!file_exists($production_repository)) {
 		mkpath($production_repository);
 	}
 
 	$filename = replace_dangerous_char($_FILES['production']['name']);
 	$filename = disable_dangerous_file($filename);
 
-	if(filter_extension($filename))
-	{
-		if (@move_uploaded_file($_FILES['production']['tmp_name'], $production_repository.$filename))
-		{
+	if (filter_extension($filename)) {
+		if (@move_uploaded_file($_FILES['production']['tmp_name'], $production_repository.$filename)) {
 			return $filename;
 		}
 	}
 	return false; // this should be returned if anything went wrong with the upload
 }
+
 /**
  * Check current user's current password
  * @param	char	password
@@ -574,17 +572,14 @@ function upload_user_production($user_id)
 function check_user_password($password){
 	global $_user;
 	$user_id = $_user['user_id'];
-	if ( $user_id != strval(intval($user_id)) || empty($password) ) { return false; }
+	if ($user_id != strval(intval($user_id)) || empty($password)) { return false; }
 	$table_user = Database :: get_main_table(TABLE_MAIN_USER);
 	$password = api_get_encrypted_password($password);
-	$sql_password="SELECT * FROM $table_user WHERE user_id='".$user_id."' AND password='".$password."'";
-	$result=api_sql_query($sql_password, __FILE__, __LINE__);
-	if (Database::num_rows($result)==0) {
-		return false;
-	} else {
-		return true;
-	}
+	$sql_password = "SELECT * FROM $table_user WHERE user_id='".$user_id."' AND password='".$password."'";
+	$result = Database::query($sql_password, __FILE__, __LINE__);
+	return Database::num_rows($result) != 0;
 }
+
 /*
 ==============================================================================
 		MAIN CODE
@@ -595,149 +590,130 @@ $update_success = false;
 $upload_picture_success = false;
 $upload_production_success = false;
 
-if (!empty($_SESSION['profile_update']))
-{
+if (!empty($_SESSION['profile_update'])) {
 	$update_success = ($_SESSION['profile_update'] == 'success');
 	unset($_SESSION['profile_update']);
 }
 
-if (!empty($_SESSION['image_uploaded']))
-{
+if (!empty($_SESSION['image_uploaded'])) {
 	$upload_picture_success = ($_SESSION['image_uploaded'] == 'success');
 	unset($_SESSION['image_uploaded']);
 }
 
-if (!empty($_SESSION['production_uploaded']))
-{
+if (!empty($_SESSION['production_uploaded'])) {
+
 	$upload_production_success = ($_SESSION['production_uploaded'] == 'success');
 	unset($_SESSION['production_uploaded']);
+
 } elseif (isset($_POST['remove_production'])) {
-	foreach (array_keys($_POST['remove_production']) as $production)
-	{
+
+	foreach (array_keys($_POST['remove_production']) as $production) {
 		UserManager::remove_user_production($_user['user_id'], urldecode($production));
 	}
-
-	if ($production_list = UserManager::build_production_list($_user['user_id'], true,true))
+	if ($production_list = UserManager::build_production_list($_user['user_id'], true, true)) {
 		$form->insertElementBefore($form->createElement('static', null, null, $production_list), 'productions_list');
-
+	}
 	$form->removeElement('productions_list');
-
 	$file_deleted = true;
+
 } elseif ($form->validate()) {
+
 	$wrong_current_password = false;
 	$user_data = $form->exportValues();
-	//
+
 	// set password if a new one was provided
-	if(!empty($user_data['password0'])){
-		$val=check_user_password($user_data['password0']);
-		if ($val==true){
-			if (!empty($user_data['password1']))
-			$password = $user_data['password1'];
+	if (!empty($user_data['password0'])) {
+		if (check_user_password($user_data['password0'])) {
+			if (!empty($user_data['password1'])) {
+				$password = $user_data['password1'];
+			}
 		} else {
 			$wrong_current_password = true;
 		}
 	}
 	if (empty($user_data['password0']) && !empty($user_data['password1'])) {
-			$wrong_current_password = true;		
+			$wrong_current_password = true;
 	}
 
 	// upload picture if a new one is provided
-	if ($_FILES['picture']['size'])
-	{
-		if ($new_picture = upload_user_image($_user['user_id'])) 
-		{
+	if ($_FILES['picture']['size']) {
+		if ($new_picture = upload_user_image($_user['user_id'])) {
 			$user_data['picture_uri'] = $new_picture;
-			$_SESSION['image_uploaded'] = 'success';			
+			$_SESSION['image_uploaded'] = 'success';
 		}
 	}
 	// remove existing picture if asked
-	elseif (!empty($user_data['remove_picture']))
-	{
+	elseif (!empty($user_data['remove_picture'])) {
 		remove_user_image($_user['user_id']);
 		$user_data['picture_uri'] = '';
 	}
 
 	// upload production if a new one is provided
-	if ($_FILES['production']['size'])
-	{
+	if ($_FILES['production']['size']) {
 		$res = upload_user_production($_user['user_id']);
-		if(!$res)
-		{
+		if (!$res) {
 			//it's a bit excessive to assume the extension is the reason why upload_user_production() returned false, but it's true in most cases
 			$filtered_extension = true;
-		}
-		else
-		{
-			$_SESSION['production_uploaded'] = 'success';	
+		} else {
+			$_SESSION['production_uploaded'] = 'success';
 		}
 	}
 
-	
 	// remove values that shouldn't go in the database
 	unset($user_data['password0'],$user_data['password1'], $user_data['password2'], $user_data['MAX_FILE_SIZE'],
-		$user_data['remove_picture'], $user_data['apply_change']);
+	$user_data['remove_picture'], $user_data['apply_change']);
 
 	// Following RFC2396 (http://www.faqs.org/rfcs/rfc2396.html), a URI uses ':' as a reserved character
 	// we can thus ensure the URL doesn't contain any scheme name by searching for ':' in the string
-	$my_user_openid=isset($user_data['openid']) ? $user_data['openid'] : '';
-	if(!preg_match('/^[^:]*:\/\/.*$/',$my_user_openid))
-	{	//ensure there is at least a http:// scheme in the URI provided
+	$my_user_openid = isset($user_data['openid']) ? $user_data['openid'] : '';
+	if (!preg_match('/^[^:]*:\/\/.*$/', $my_user_openid)) {
+		//ensure there is at least a http:// scheme in the URI provided
 		$user_data['openid'] = 'http://'.$my_user_openid;
 	}
 	$extras = array();
 	// build SQL query
 	$sql = "UPDATE $table_user SET";
 	unset($user_data['api_key_generate']);
-	foreach($user_data as $key => $value)
-	{
-		if(substr($key,0,6)=='extra_') //an extra field
-		{
-			$extras[substr($key,6)] = $value;
-		}
-		else
-		{
+	foreach ($user_data as $key => $value) {
+		if (substr($key, 0, 6) == 'extra_') { //an extra field
+			$extras[substr($key, 6)] = $value;
+		} else {
 			$sql .= " $key = '".Database::escape_string($value)."',";
 		}
 	}
 
-	if (isset($password))
-	{
+	if (isset($password)) {
 		$password = api_get_encrypted_password($password);
-		$sql .= " password = '".Database::escape_string($password)."'";  		
-	}
-	else // remove trailing , from the query we have so far
-	{
+		$sql .= " password = '".Database::escape_string($password)."'";
+	} else {
+		// remove trailing , from the query we have so far
 		$sql = rtrim($sql, ',');
 	}
 
-	$sql .= " WHERE user_id  = '".$_user['user_id']."'";		
-	api_sql_query($sql, __FILE__, __LINE__);
+	$sql .= " WHERE user_id  = '".$_user['user_id']."'";
+	Database::query($sql, __FILE__, __LINE__);
 	//update the extra fields
-	foreach($extras as $key=>$value)
-	{
-		$myres = UserManager::update_extra_field_value($_user['user_id'],$key,$value);
+	foreach ($extras as $key => $value) {
+		$myres = UserManager::update_extra_field_value($_user['user_id'], $key, $value);
 	}
-	
+
 	// re-init the system to take new settings into account
 	$uidReset = true;
-	include (api_get_path(INCLUDE_PATH).'local.inc.php');
+	include api_get_path(INCLUDE_PATH).'local.inc.php';
 	$_SESSION['profile_update'] = 'success';
-	header("Location: ".api_get_self()."?{$_SERVER['QUERY_STRING']}".($filtered_extension && strstr($_SERVER['QUERY_STRING'],'&fe=1')===false?'&fe=1':'').($wrong_current_password && strstr($_SERVER['QUERY_STRING'],'&cp=1')===false?'&cp=1':''));
+	header("Location: ".api_get_self()."?{$_SERVER['QUERY_STRING']}".($filtered_extension && strpos($_SERVER['QUERY_STRING'], '&fe=1') === false ? '&fe=1' : '').($wrong_current_password && strpos($_SERVER['QUERY_STRING'], '&cp=1') === false ? '&cp=1' : ''));
 	exit;
 }
 
 if (isset($_GET['show'])) {
-	
-	if ((api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') ||(api_get_setting('allow_social_tool')=='true')) {
-		$interbreadcrumb[]= array (
-		'url' => 'javascript: void(0);',
-		'name' => get_lang('SocialNetwork')
-		);
-	} elseif ((api_get_setting('allow_social_tool')=='false' && api_get_setting('allow_message_tool')=='true')) {
-		$interbreadcrumb[]= array (
-		'url' => 'javascript: void(0);',
-		'name' => get_lang('MessageTool')
-		);	
+
+	if ((api_get_setting('allow_social_tool') == 'true' && api_get_setting('allow_message_tool') == 'true') || (api_get_setting('allow_social_tool') == 'true')) {
+
+		$interbreadcrumb[] = array ('url' => 'javascript: void(0);', 'name' => get_lang('SocialNetwork'));
+
+	} elseif ((api_get_setting('allow_social_tool') == 'false' && api_get_setting('allow_message_tool') == 'true')) {
+
+		$interbreadcrumb[] = array('url' => 'javascript: void(0);', 'name' => get_lang('MessageTool'));
 	}
 }
 
@@ -748,53 +724,50 @@ if (isset($_GET['show'])) {
 */
 Display :: display_header('');
 
-if (api_get_setting('extended_profile') == 'true') {	
+if (api_get_setting('extended_profile') == 'true') {
 	echo '<div class="actions">';
-	if (isset($_GET['show'])) {
-		$show='&amp;show='.Security::remove_XSS($_GET['show']);
+	$show = isset($_GET['show']) ? '&amp;show='.Security::remove_XSS($_GET['show']) : '';
+	if (isset($_GET['type']) && $_GET['type'] == 'extended') {
+		echo '<a href="profile.php?type=reduced'.$show.'">'.Display::return_icon('edit.gif', get_lang('EditNormalProfile')).'&nbsp;'.get_lang('EditNormalProfile').'</a>';
 	} else {
-		$show='';
+		echo '<a href="profile.php?type=extended'.$show.'">'.Display::return_icon('edit.gif', get_lang('EditExtendProfile')).'&nbsp;'.get_lang('EditExtendProfile').'</a>';
 	}
-	if (isset($_GET['type']) && $_GET['type']=='extended') {
-		echo '<a href="profile.php?type=reduced'.$show.'">'.Display::return_icon('edit.gif',get_lang('EditNormalProfile')).'&nbsp;'.get_lang('EditNormalProfile').'</a>';			
-	} else {
-		echo '<a href="profile.php?type=extended'.$show.'">'.Display::return_icon('edit.gif',get_lang('EditExtendProfile')).'&nbsp;'.get_lang('EditExtendProfile').'</a>';
-	}
-	if (api_get_setting('allow_social_tool')=='true' && api_get_setting('allow_message_tool')=='true') { 
-		echo '<a href="../social/profile.php">'.Display::return_icon('shared_profile.png',get_lang('ViewSharedProfile')).'&nbsp;'.get_lang('ViewSharedProfile').'</a>';
+	if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('allow_message_tool') == 'true') {
+		echo '<a href="../social/profile.php">'.Display::return_icon('shared_profile.png', get_lang('ViewSharedProfile')).'&nbsp;'.get_lang('ViewSharedProfile').'</a>';
 	}
 	echo '</div>';
-} 
+}
 
 if (!empty($file_deleted)) {
-	Display :: display_confirmation_message(get_lang('FileDeleted'),false);
+
+	Display :: display_confirmation_message(get_lang('FileDeleted'), false);
+
 } elseif (!empty($update_success)) {
-	$message=get_lang('ProfileReg');	
+	$message = get_lang('ProfileReg');
 
-	if ($upload_picture_success == true) {
-		$message.='<br /> '.get_lang('PictureUploaded');
+	if ($upload_picture_success) {
+		$message .= '<br /> '.get_lang('PictureUploaded');
 	}
-	
-	if ($upload_production_success == true) {
+
+	if ($upload_production_success) {
 		$message.='<br />'.get_lang('ProductionUploaded');
 	}
-		
-	Display :: display_confirmation_message($message,false);	
+
+	Display :: display_confirmation_message($message, false);
 }
 
-if(!empty($warning_msg))
-{
-	Display :: display_warning_message($warning_msg,false);
+if (!empty($warning_msg)) {
+	Display :: display_warning_message($warning_msg, false);
 }
 
 //User picture size is calculated from SYSTEM path
-$image_syspath = UserManager::get_user_picture_path_by_id(api_get_user_id(),'system',false,true);
+$image_syspath = UserManager::get_user_picture_path_by_id(api_get_user_id(), 'system', false, true);
 $image_syspath['dir'].$image_syspath['file'];
 
 $image_size = @getimagesize($image_syspath['dir'].$image_syspath['file']);
 
 //Web path
-$image_path = UserManager::get_user_picture_path_by_id(api_get_user_id(),'web',false,true);
+$image_path = UserManager::get_user_picture_path_by_id(api_get_user_id(), 'web', false, true);
 $image_dir = $image_path['dir'];
 $image = $image_path['file'];
 $image_file = $image_dir.$image;
@@ -803,56 +776,54 @@ $img_attributes = 'src="'.$image_file.'?rand='.time().'" '
 	.'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; margin-top:0px;padding:5px;" ';
 if ($image_size[0] > 300) {
 	//limit display width to 300px
-	$img_attributes .= 'width="300" ';	
+	$img_attributes .= 'width="300" ';
 }
 
 // get the path,width and height from original picture
 $big_image = $image_dir.'big_'.$image;
 
-$big_image_size = @getimagesize(api_url_to_local_path($big_image));
-$big_image_width= $big_image_size[0];
-$big_image_height= $big_image_size[1];
+$big_image_size = api_getimagesize($big_image);
+$big_image_width = $big_image_size[0];
+$big_image_height = $big_image_size[1];
 $url_big_image = $big_image.'?rnd='.time();
 
-// Modified by Ivan Tcholakov, 14-AUG-2009.
-// The position:absolute style has been removed for Opera-compatibility.
+// Style position:absolute has been removed for Opera-compatibility.
 //echo '<div id="image-message-container" style="float:right;display:inline;position:absolute;padding:3px;width:250px;" >';
 echo '<div id="image-message-container" style="float:right;display:inline;padding:3px;width:250px;" >';
-//
-if ($image=='unknown.jpg') {
+
+if ($image == 'unknown.jpg') {
 	echo '<img '.$img_attributes.' />';
 } else {
-	echo '<input type="image" '.$img_attributes.' onclick="return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
+	echo '<input type="image" '.$img_attributes.' onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');"/>';
 }
-if (api_get_setting('allow_message_tool')=='true') {	
-	include (api_get_path(LIBRARY_PATH).'message.lib.php');
+if (api_get_setting('allow_message_tool') == 'true') {
+	include api_get_path(LIBRARY_PATH).'message.lib.php';
 	$number_of_new_messages = MessageManager::get_new_messages();
-	$number_of_outbox_message=MessageManager::get_number_of_messages_sent();
-	$cant_out_box=' ('.$number_of_outbox_message.')';
+	$number_of_outbox_message = MessageManager::get_number_of_messages_sent();
+	$cant_out_box = ' ('.$number_of_outbox_message.')';
 	$cant_msg = ' ('.$number_of_new_messages.')';
-	$number_of_new_messages_of_friend=UserFriend::get_message_number_invitation_by_user_id(api_get_user_id());
+	$number_of_new_messages_of_friend = UserFriend::get_message_number_invitation_by_user_id(api_get_user_id());
 	//echo '<div class="message-view" style="display:none;">'.get_lang('ViewMessages').'</div>';
 	echo '<div class="message-content">
 			<h2 class="message-title">'.get_lang('Messages').'</h2>
 			<p>
 				<a href="../social/index.php#remote-tab-2" class="message-body">'.get_lang('Inbox').$cant_msg.' </a><br />
 				<a href="../social/index.php#remote-tab-3" class="message-body">'.get_lang('Outbox').$cant_out_box.'</a><br />
-			</p>';		
-	
-	/* if (api_get_setting('allow_social_tool')=='true') {		 
-		 if ($number_of_new_messages_of_friend>0) {
-			echo '<div class="message-content-internal">';		
-			echo '<a href="../social/index.php#remote-tab-4" style="color:#000000">'. Display::return_icon('info3.gif',get_lang('NewMessage'),'align="absmiddle"').'&nbsp;'.get_lang('Invitation ').'('.$number_of_new_messages_of_friend.')'.'</a>';
-			echo '</div><br/>';		    
-		 }			
+			</p>';
+
+	/*if (api_get_setting('allow_social_tool') == 'true') {
+		 if ($number_of_new_messages_of_friend > 0) {
+			echo '<div class="message-content-internal">';
+			echo '<a href="../social/index.php#remote-tab-4" style="color:#000000">'. Display::return_icon('info3.gif', get_lang('NewMessage'), 'align="absmiddle"').'&nbsp;'.get_lang('Invitation ').'('.$number_of_new_messages_of_friend.')'.'</a>';
+			echo '</div><br />';
+		 }
 	 }*/
 	echo '<img src="../img/delete.gif" alt="'.get_lang('Close').'" title="'.get_lang('Close').'"  class="message-delete" />';
-	if ($number_of_new_messages_of_friend>0) {
-		echo '<br/>';
+	if ($number_of_new_messages_of_friend > 0) {
+		echo '<br />';
 	}
 	echo '</div>';
 }
 echo '</div>';
 $form->display();
 Display :: display_footer();
-?>

+ 15 - 3
main/course_home/activity.php

@@ -389,7 +389,7 @@ if (isset($_GET['sent_http_request']) && $_GET['sent_http_request']==1) {
 		$requested_clase   = ($tool_visibility == 0 ) ? 'visible' : 'invisible';
 		$requested_message = ($tool_visibility == 0 ) ? 'is_active' : 'is_inactive';
     $requested_view    = ($tool_visibility == 0 ) ? 'visible.gif' : 'invisible.gif'; 
-    $requested_visible = ($tool_visibility == 0 ) ? 1 : 0;           		
+    $requested_visible = ($tool_visibility == 0 ) ? 1 : 0;
 	 	/*
 		-----------------------------------------------------------
 			HIDE AND REACTIVATE
@@ -476,8 +476,20 @@ if(api_is_platform_admin())
 // start of tools for CourseAdmins (teachers/tutors)
 if(api_is_allowed_to_edit())
 {
-	?>
-	<div class="normal-message" id="id_normal_message" style="display:none"><?php echo get_lang("PleaseStandBy")."<br/>".'<img src="/main/inc/lib/javascript/indicator.gif"/>'; ?></div>
+    $current_protocol  = $_SERVER['SERVER_PROTOCOL'];
+    $current_host      = $_SERVER['HTTP_HOST'];
+    $server_protocol = substr($current_protocol,0,strrpos($current_protocol,'/'));
+    $server_protocol = $server_protocol.'://';
+    if ($current_host == 'localhost') {
+      //Get information of path
+      $info = explode('courses',api_get_self());
+      $path_work = substr($info[0], 0, strlen($info[0]));
+    } else {
+      $path_work = "";
+    }
+
+?>
+	<div class="normal-message" id="id_normal_message" style="display:none"><?php echo get_lang("PleaseStandBy")."<br/>".'<img src="'.$server_protocol.$current_host.'/'.$path_work.'main/inc/lib/javascript/indicator.gif"/>'; ?></div>
 	<div class="confirmation-message" id="id_confirmation_message" style="display:none"></div>		
 	<div class="courseadminview">
 		<span class="viewcaption"><?php echo get_lang("Authoring") ?></span>

+ 12 - 2
main/course_home/course_home.php

@@ -64,6 +64,13 @@ $use_anonymous = true;
 // inlcuding the global file
 include '../../main/inc/global.inc.php';
 $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
+if ($_SERVER['HTTP_HOST'] == 'localhost') {
+    //Get information of path
+    $info = explode('courses',api_get_self());
+    $path_work = substr($info[0],0,strlen($info[0])-1);
+} else {
+    $path_work = "";
+} 
 $htmlHeadXtra[] ='<script type="text/javascript">
  $(document).ready(function() {
   $(".make_visible_and_invisible").attr("href","javascript:void(0);");
@@ -80,7 +87,10 @@ $htmlHeadXtra[] ='<script type="text/javascript">
 		//Delete last item
     	list_path_name[list_path_name.length-1]=null;
     	real_path = list_path_name.join("/");
-    
+        my_protocol = location.protocol;
+        my_host = location.host;
+        my_real_path = my_protocol+"//"+my_host;
+
 		$.ajax({
 			contentType: "application/x-www-form-urlencoded",
 			beforeSend: function(objeto) {
@@ -88,7 +98,7 @@ $htmlHeadXtra[] ='<script type="text/javascript">
 				$("#id_confirmation_message").hide();
 			},
 			type: "GET",
-			url: "/main/course_home/activity.php",
+			url: my_real_path+"'.$path_work.'/main/course_home/activity.php",
 			data: "id="+my_tool_id+"&sent_http_request=1",
 			success: function(datos) {
 				eval("var info="+datos);

+ 13 - 14
main/course_info/download.php

@@ -24,29 +24,29 @@
 
 session_cache_limiter('public');
 
-include('../inc/global.inc.php');
-$this_section=SECTION_COURSES;
+require '../inc/global.inc.php';
+$this_section = SECTION_COURSES;
 
-include_once(api_get_path(LIBRARY_PATH).'fileManage.lib.php');
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 
-$archivePath = api_get_path(SYS_PATH).$archiveDirName.'/';
-$archiveFile = $_GET['archive'];
+$archive_path = api_get_path(SYS_ARCHIVE_PATH);
+$archive_file = $_GET['archive'];
 
-$archiveFile = str_replace(array('..', '/', '\\'), '', $archiveFile);
+$archive_file = str_replace(array('..', '/', '\\'), '', $archive_file);
 
-list($extension) = getextension($archiveFile);
+list($extension) = getextension($archive_file);
 
-if (empty($extension) || !file_exists($archivePath.$archiveFile)) {
+if (empty($extension) || !file_exists($archive_path.$archive_file)) {
 	exit();
 }
 
 $content_type = '';
 
 if (in_array(strtolower($extension), array('xml','csv')) && api_is_platform_admin(true)) {
-	$content_type='application/force-download';
+	$content_type = 'application/force-download';
 }
 elseif (strtolower($extension) == 'zip' && $_cid && $is_courseAdmin) {
-	$content_type='application/force-download';
+	$content_type = 'application/force-download';
 }
 
 if (empty($content_type)) {
@@ -59,8 +59,7 @@ header('Cache-Control: public');
 header('Pragma: no-cache');
 
 header('Content-Type: '.$content_type);
-header('Content-Length: '.filesize($archivePath.$archiveFile));
-header('Content-Disposition: attachment; filename='.$archiveFile);
+header('Content-Length: '.filesize($archive_path.$archive_file));
+header('Content-Disposition: attachment; filename='.$archive_file);
 
-readfile($archivePath.$archiveFile);
-?>
+readfile($archive_path.$archive_file);

+ 3 - 1
main/coursecopy/classes/Announcement.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * An announcement
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 5 - 3
main/coursecopy/classes/Course.class.php

@@ -22,9 +22,11 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once ('LinkCategory.class.php');
-require_once ('Announcement.class.php');
-require_once ('Event.class.php');
+
+require_once 'LinkCategory.class.php';
+require_once 'Announcement.class.php';
+require_once 'Event.class.php';
+
 /**
  * A course-object to use in Export/Import/Backup/Copy
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 8 - 8
main/coursecopy/classes/CourseArchiver.class.php

@@ -23,10 +23,10 @@
 	Mail: info@dokeos.com
 ==============================================================================
 */
-require_once ('Course.class.php');
-require_once ('mkdirr.php');
-require_once ('rmdirr.php');
-require_once (api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php');
+
+require_once 'Course.class.php';
+require_once api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php';
+
 /**
  * Some functions to write a course-object to a zip-file and to read a course-
  * object from such a zip-file.
@@ -99,12 +99,12 @@ class CourseArchiver
 			foreach ($course->resources[RESOURCE_DOCUMENT] as $id => $document) {
 				if ($document->file_type == DOCUMENT) {
 					$doc_dir = $backup_dir.$document->path;
-					mkdirr(dirname($doc_dir), 0755);
+					@mkdir(dirname($doc_dir), 0755, true);
 					if (file_exists($course->path.$document->path)) {
 						copy($course->path.$document->path, $doc_dir);	
 					}					
 				} else {
-					mkdirr($backup_dir.$document->path, 0755);
+					@mkdir($backup_dir.$document->path, 0755, true);
 				}
 			}
 		}
@@ -116,7 +116,7 @@ class CourseArchiver
 			{
 				$doc_dir=dirname($backup_dir.$document->path);
 
-				mkdirr($doc_dir,0755);
+				@mkdir($doc_dir, 0755, true);
 
 				copyDirTo($course->path.$document->path, $doc_dir, false);
 			}
@@ -185,7 +185,7 @@ class CourseArchiver
 		// Create a temp directory
 		$tmp_dir_name = 'CourseArchiver_'.uniqid('');
 		$unzip_dir = api_get_path(SYS_ARCHIVE_PATH).''.$tmp_dir_name;
-		mkdirr($unzip_dir,0755);
+		@mkdir($unzip_dir, 0755, true);
 		@copy(api_get_path(SYS_ARCHIVE_PATH).''.$filename,$unzip_dir.'/backup.zip');
 		// unzip the archive
 		$zip = new PclZip($unzip_dir.'/backup.zip');

+ 20 - 22
main/coursecopy/classes/CourseBuilder.class.php

@@ -1,23 +1,25 @@
 <?php
 /* For licensing terms, see /dokeos_license.txt */
-require_once ('Course.class.php');
-require_once ('Event.class.php');
-require_once ('Link.class.php');
-require_once ('ToolIntro.class.php');
-require_once ('Document.class.php');
-require_once ('ScormDocument.class.php');
-require_once ('LinkCategory.class.php');
-require_once ('CourseDescription.class.php');
-require_once ('ForumPost.class.php');
-require_once ('ForumTopic.class.php');
-require_once ('Forum.class.php');
-require_once ('ForumCategory.class.php');
-require_once ('Quiz.class.php');
-require_once ('QuizQuestion.class.php');
-require_once ('Learnpath.class.php');
-require_once ('Survey.class.php');
-require_once ('SurveyQuestion.class.php');
-require_once ('Glossary.class.php');
+
+require_once 'Course.class.php';
+require_once 'Event.class.php';
+require_once 'Link.class.php';
+require_once 'ToolIntro.class.php';
+require_once 'Document.class.php';
+require_once 'ScormDocument.class.php';
+require_once 'LinkCategory.class.php';
+require_once 'CourseDescription.class.php';
+require_once 'ForumPost.class.php';
+require_once 'ForumTopic.class.php';
+require_once 'Forum.class.php';
+require_once 'ForumCategory.class.php';
+require_once 'Quiz.class.php';
+require_once 'QuizQuestion.class.php';
+require_once 'Learnpath.class.php';
+require_once 'Survey.class.php';
+require_once 'SurveyQuestion.class.php';
+require_once 'Glossary.class.php';
+
 /**
  * Class which can build a course-object from a Dokeos-course.
  * @author Bart Mollet <bart.mollet@hogent.be>
@@ -59,10 +61,7 @@ class CourseBuilder
 		$this->build_announcements();
 		$this->build_links();
 		$this->build_tool_intro();
-		// Enabled by Ivan Tcholakov, 27-AUG-2009.
-		////$this->build_forums();
 		$this->build_forums();
-		//
 		$this->build_documents();
 		$this->build_course_descriptions();
 		$this->build_quizzes();
@@ -448,7 +447,6 @@ class CourseBuilder
 
 		while ($obj = Database::fetch_object($db_result))
 		{
-
 			$items = array();
 			$sql_items = "SELECT * FROM ".$table_item." WHERE lp_id = ".$obj->id."";
 			$db_items = api_sql_query($sql_items);

+ 3 - 1
main/coursecopy/classes/CourseDescription.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * A course description
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 3 - 6
main/coursecopy/classes/CourseRecycler.class.php

@@ -23,8 +23,9 @@
 	Mail: info@dokeos.com
 ==============================================================================
 */
-require_once ('Course.class.php');
-require_once ('rmdirr.php');
+
+require_once 'Course.class.php';
+
 /**
  * Class to delete items from a Dokeos-course
  * @author Bart Mollet <bart.mollet@hogent.be>
@@ -78,12 +79,8 @@ class CourseRecycler
 		$this->recycle_events();
 		$this->recycle_announcements();
 		$this->recycle_documents();
-		// Enabled by Ivan Tcholakov, 27-AUG-2009.
-		////$this->recycle_forums();
-		////$this->recycle_forum_categories();
 		$this->recycle_forums();
 		$this->recycle_forum_categories();
-		//
 		$this->recycle_quizzes();
 		$this->recycle_surveys();
 		$this->recycle_learnpaths();

+ 17 - 21
main/coursecopy/classes/CourseRestorer.class.php

@@ -22,23 +22,22 @@
 	Mail: info@dokeos.com
 ==============================================================================
 */
-require_once ('Course.class.php');
-require_once ('Event.class.php');
-require_once ('Link.class.php');
-require_once ('ToolIntro.class.php');
-require_once ('LinkCategory.class.php');
-require_once ('ForumCategory.class.php');
-require_once ('Forum.class.php');
-require_once ('ForumTopic.class.php');
-require_once ('ForumPost.class.php');
-require_once ('CourseDescription.class.php');
-require_once ('Learnpath.class.php');
-require_once ('Survey.class.php');
-require_once ('SurveyQuestion.class.php');
-require_once ('mkdirr.php');
-require_once ('rmdirr.php');
-require_once ('Glossary.class.php');
-include_once(api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php');
+
+require_once 'Course.class.php';
+require_once 'Event.class.php';
+require_once 'Link.class.php';
+require_once 'ToolIntro.class.php';
+require_once 'LinkCategory.class.php';
+require_once 'ForumCategory.class.php';
+require_once 'Forum.class.php';
+require_once 'ForumTopic.class.php';
+require_once 'ForumPost.class.php';
+require_once 'CourseDescription.class.php';
+require_once 'Learnpath.class.php';
+require_once 'Survey.class.php';
+require_once 'SurveyQuestion.class.php';
+require_once 'Glossary.class.php';
+require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 
 define('FILE_SKIP', 1);
 define('FILE_RENAME', 2);
@@ -102,10 +101,7 @@ class CourseRestorer
 		$this->restore_documents();
 		$this->restore_scorm_documents();
 		$this->restore_course_descriptions();
-		// Enabled by Ivan Tcholakov, 30-AUG-2009.
-		////$this->restore_forums();
 		$this->restore_forums();
-		//
 		$this->restore_quizzes(); // after restore_documents! (for correct import of sound/video)
 		$this->restore_learnpaths();
 		$this->restore_surveys();
@@ -328,7 +324,7 @@ class CourseRestorer
 
 				$perm = api_get_setting('permissions_for_new_directories');
 			        $perm = octdec(!empty($perm)?$perm:'0770');
-				mkdirr(dirname($path.$document->path),$perm);
+				@mkdir(dirname($path.$document->path), $perm, true);
 
 				if (file_exists($path.$document->path))
 				{

+ 3 - 1
main/coursecopy/classes/CourseSelectForm.class.php

@@ -23,7 +23,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once ('Course.class.php');
+
+require_once 'Course.class.php';
+
 /**
  * Class to show a form to select resources
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 4 - 1
main/coursecopy/classes/Document.class.php

@@ -22,9 +22,12 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 define('DOCUMENT','file');
 define('FOLDER','folder');
+
 /**
  * An document
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 20 - 18
main/coursecopy/classes/DummyCourseCreator.class.php

@@ -23,20 +23,20 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once ('Course.class.php');
-require_once ('Document.class.php');
-require_once ('Event.class.php');
-require_once ('Link.class.php');
-require_once ('LinkCategory.class.php');
-require_once ('ForumCategory.class.php');
-require_once ('Forum.class.php');
-require_once ('ForumTopic.class.php');
-require_once ('ForumPost.class.php');
-require_once ('CourseDescription.class.php');
-require_once ('Learnpath.class.php');
-require_once ('CourseRestorer.class.php');
-require_once ('mkdirr.php');
-require_once ('rmdirr.php');
+
+require_once 'Course.class.php';
+require_once 'Document.class.php';
+require_once 'Event.class.php';
+require_once 'Link.class.php';
+require_once 'LinkCategory.class.php';
+require_once 'ForumCategory.class.php';
+require_once 'Forum.class.php';
+require_once 'ForumTopic.class.php';
+require_once 'ForumPost.class.php';
+require_once 'CourseDescription.class.php';
+require_once 'Learnpath.class.php';
+require_once 'CourseRestorer.class.php';
+
 class DummyCourseCreator
 {
 	/**
@@ -65,7 +65,7 @@ class DummyCourseCreator
 		$course = Database::get_course_info($course_code);
 		$this->course = new Course();
 		$tmp_path = api_get_path(SYS_COURSE_PATH).$course['directory'].'/document/tmp_'.uniqid('');
-		mkdirr($tmp_path);
+		@mkdir($tmp_path, 0755, true);
 		$this->course->backup_path = $tmp_path;
 		$this->create_dummy_links();
 		$this->create_dummy_events();
@@ -108,7 +108,7 @@ class DummyCourseCreator
 			$dir_to_make = $course_doc_path.$path;
 			if (!is_dir($dir_to_make))
 			{
-				mkdirr(str_replace('/',DIRECTORY_SEPARATOR,$dir_to_make));
+				@mkdir($dir_to_make, 0755, true);
 			}
 			$file = $course_doc_path.$path.$filename;
 			$fp = fopen($file, 'w');
@@ -215,17 +215,19 @@ class DummyCourseCreator
 		$last_forum_post = array ();
 		$last_topic_post = array ();
 		// create categorys
+		$order = 1;
 		for ($i = 1; $i <= $number_of_categories; $i ++)
 		{
-			$forumcat = new ForumCategory($i, $this->get_dummy_content('title'));
+			$forumcat = new ForumCategory($i, $this->get_dummy_content('title'), $this->get_dummy_content('description'), $order, 0, 0);
 			$this->course->add_resource($forumcat);
+			$order++;
 		}
 		// create posts
 		for ($post_id = 1; $post_id <= $number_of_posts; $post_id ++)
 		{
 			$topic_id = rand(1, $number_of_topics);
 			$last_topic_post[$topic_id] = $post_id;
-			$post = new ForumPost($post_id, $this->get_dummy_content('title'), $this->get_dummy_content('text'), 0, '127.0.0.1', 'Dokeos', 'Administrator', 0, 0, $topic_id);
+			$post = new ForumPost($post_id, $this->get_dummy_content('title'), $this->get_dummy_content('text'), date('Y-m-d H:i:s'), 1, 'Dokeos Administrator', 0, 0, $topic_id, 0, 1);
 			$this->course->add_resource($post);
 		}
 		// create topics

+ 3 - 1
main/coursecopy/classes/Event.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * An event
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 3 - 1
main/coursecopy/classes/Forum.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * A forum
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 3 - 1
main/coursecopy/classes/ForumCategory.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * A forum-category
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 3 - 1
main/coursecopy/classes/ForumPost.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * A forum-post
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 3 - 1
main/coursecopy/classes/ForumTopic.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * A forum-topic/thread
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 3 - 1
main/coursecopy/classes/Glossary.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * Add resource glossary
  * @author Isaac flores <florespaz@bidsoftperu.com>

+ 3 - 1
main/coursecopy/classes/Link.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * A WWW-link from the Links-module in a Dokeos-course.
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 3 - 1
main/coursecopy/classes/LinkCategory.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * A LinkCategory
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 3 - 1
main/coursecopy/classes/Quiz.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * An Quiz
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 3 - 1
main/coursecopy/classes/QuizQuestion.class.php

@@ -22,7 +22,9 @@
 	Mail: info@dokeos.com
 ============================================================================== 
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
+
 /**
  * An QuizQuestion
  * @author Bart Mollet <bart.mollet@hogent.be>

+ 2 - 1
main/coursecopy/classes/ScormDocument.class.php

@@ -22,7 +22,8 @@
 	Mail: info@dokeos.com
 ==============================================================================
 */
-require_once('Resource.class.php');
+
+require_once 'Resource.class.php';
 
 /**
  * ScormDocument class

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