Kaynağa Gözat

Removing deprecating function function get_setting() is replaced with api_get_setting(),
removing Database::get_user_info_from_id() replaced with api_get_user_info(), putting the text.lib.php, array.lib.php and online.inc.php into classes,
now we call libs with Text:: ArrayClass::, and Online::

Julio Montoya 12 yıl önce
ebeveyn
işleme
cfac24c461
100 değiştirilmiş dosya ile 1894 ekleme ve 2196 silme
  1. 0 8
      app/cache/.htaccess
  2. 2 2
      main/admin/calendar.lib.php
  3. 1 1
      main/admin/calendar_view_print.php
  4. 4 4
      main/admin/configure_homepage.php
  5. 1 1
      main/admin/configure_inscription.php
  6. 4 4
      main/admin/skills_import.php
  7. 10 10
      main/admin/sub_language.php
  8. 1 1
      main/admin/user_edit.php
  9. 1 1
      main/admin/user_import.php
  10. 1 1
      main/admin/user_list.php
  11. 1 1
      main/auth/inscription.php
  12. 9 9
      main/auth/shibboleth/app/shibboleth.class.php
  13. 2 2
      main/auth/shibboleth/lib/shibboleth_session.class.php
  14. 4 4
      main/auth/unsubscribe_account.php
  15. 6 6
      main/calendar/agenda.inc.php
  16. 2 12
      main/calendar/myagenda.inc.php
  17. 1 1
      main/calendar/print.php
  18. 1 1
      main/chat/chat_message.php
  19. 1 1
      main/course_info/infocours.php
  20. 2 2
      main/coursecopy/classes/Course.class.php
  21. 7 11
      main/document/create_audio.php
  22. 2 2
      main/document/create_document.php
  23. 6 12
      main/document/document.inc.php
  24. 1 1
      main/document/document.php
  25. 2 2
      main/document/document_lite.php
  26. 5 5
      main/document/document_quota.php
  27. 4 4
      main/document/show_content.php
  28. 7 7
      main/document/showinframesmin.php
  29. 12 12
      main/document/upload.php
  30. 9 9
      main/dropbox/index.php
  31. 2 2
      main/exercice/addlimits.php
  32. 1 1
      main/exercice/draggable.class.php
  33. 4 5
      main/exercice/exercise.class.php
  34. 9 10
      main/exercice/exercise.lib.php
  35. 3 3
      main/exercice/exercise_reminder.php
  36. 0 19
      main/exercice/export/scorm/scorm_classes.php
  37. 5 5
      main/exercice/freeanswer.class.php
  38. 3 3
      main/exercice/hotpotatoes.lib.php
  39. 2 2
      main/exercice/hotspot_admin.inc.php
  40. 1 1
      main/exercice/matching.class.php
  41. 14 14
      main/exercice/multiple_answer.class.php
  42. 30 30
      main/exercice/multiple_answer_combination.class.php
  43. 83 84
      main/exercice/multiple_answer_true_false.class.php
  44. 5 5
      main/exercice/oral_expression.class.php
  45. 1 1
      main/exercice/question.class.php
  46. 11 11
      main/exercice/question_create.php
  47. 7 7
      main/exercice/question_list_admin.inc.php
  48. 34 34
      main/exercice/stats.php
  49. 1 1
      main/exercice/testcategory.class.php
  50. 48 48
      main/exercice/unique_answer.class.php
  51. 3 3
      main/exercice/unique_answer_image.class.php
  52. 81 81
      main/exercice/unique_answer_no_option.class.php
  53. 35 35
      main/glossary/index.php
  54. 18 19
      main/gradebook/gradebook.php
  55. 6 6
      main/gradebook/gradebook_view_result.php
  56. 9 9
      main/gradebook/lib/be/surveylink.class.php
  57. 111 111
      main/gradebook/lib/fe/displaygradebook.php
  58. 119 119
      main/gradebook/lib/fe/evalform.class.php
  59. 8 22
      main/gradebook/lib/gradebook_functions_users.inc.php
  60. 11 11
      main/gradebook/lib/results_data_generator.class.php
  61. 9 9
      main/gradebook/user_stats.php
  62. 17 17
      main/group/group.php
  63. 4 4
      main/group/group_space.php
  64. 172 172
      main/inc/ajax/course_home.ajax.php
  65. 2 2
      main/inc/ajax/document.ajax.php
  66. 3 3
      main/inc/ajax/model.ajax.php
  67. 8 8
      main/inc/ajax/online.ajax.php
  68. 3 9
      main/inc/global.inc.php
  69. 80 99
      main/inc/lib/array.lib.php
  70. 2 2
      main/inc/lib/attendance.lib.php
  71. 4 4
      main/inc/lib/blog.lib.php
  72. 47 47
      main/inc/lib/course.lib.php
  73. 1 1
      main/inc/lib/course_home.lib.php
  74. 4 4
      main/inc/lib/course_request.lib.php
  75. 0 23
      main/inc/lib/database.lib.php
  76. 0 19
      main/inc/lib/database.mysqli.lib.php
  77. 2 2
      main/inc/lib/document.lib.php
  78. 17 17
      main/inc/lib/exercise_show_functions.lib.php
  79. 132 132
      main/inc/lib/extra_field.lib.php
  80. 1 1
      main/inc/lib/fck_course_document.inc.php
  81. 0 3
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajaxfilemanager.php
  82. 2 2
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/class.manager.php
  83. 2 2
      main/inc/lib/fckeditor/fckeditor.php
  84. 1 1
      main/inc/lib/fckeditor/repository.php
  85. 1 1
      main/inc/lib/fileManager.lib.php
  86. 12 12
      main/inc/lib/import.lib.php
  87. 7 7
      main/inc/lib/link.lib.php
  88. 36 49
      main/inc/lib/main_api.lib.php
  89. 24 108
      main/inc/lib/message.lib.php
  90. 14 8
      main/inc/lib/notification.lib.php
  91. 326 388
      main/inc/lib/online.inc.php
  92. 3 3
      main/inc/lib/page.lib.php
  93. 3 9
      main/inc/lib/pdf.lib.php
  94. 5 5
      main/inc/lib/plugin.class.php
  95. 1 1
      main/inc/lib/sessionmanager.lib.php
  96. 118 115
      main/inc/lib/social.lib.php
  97. 31 31
      main/inc/lib/statistics.lib.php
  98. 9 9
      main/inc/lib/system/io/csv_reader.class.php
  99. 1 1
      main/inc/lib/system_announcements.lib.php
  100. 16 27
      main/inc/lib/template.lib.php

+ 0 - 8
app/cache/.htaccess

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

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

@@ -885,7 +885,7 @@ function display_agenda_items()
      			display: the content
          --------------------------------------------------*/
         $content = $myrow['content'];
-        $content = make_clickable($content);
+        $content = Text::make_clickable($content);
         echo "<tr class='row_even'>";
         echo "<td colspan='3'>";
 
@@ -1084,7 +1084,7 @@ function display_one_agenda_item($agenda_id)
     $export_icon_high = '../img/export_high_fade.png';
 
     $content = $myrow['content'];
-    $content = make_clickable($content);
+    $content = Text::make_clickable($content);
     //echo "<tr><td class=\"".$text_style."\" colspan='2'>";
     //echo $content;
     //echo "</td></tr>";

+ 1 - 1
main/admin/calendar_view_print.php

@@ -51,7 +51,7 @@ $result			= Database::query($sql);
 while($row=Database::fetch_array($result))
 {
 	$row['content'] = $row['content'];
-	$row['content'] = make_clickable($row['content']);
+	$row['content'] = Text::make_clickable($row['content']);
 	$row['content'] = str_replace('<a ','<a target="_blank" ',$row['content']);
 
 	if(!empty($row['title']))

+ 4 - 4
main/admin/configure_homepage.php

@@ -185,7 +185,7 @@ if (!empty($action)) {
                 event_system(
                     LOG_HOMEPAGE_CHANGED,
                     'edit_top',
-                    cut(strip_tags($home_top), 254),
+                    Text::cut(strip_tags($home_top), 254),
                     api_get_utc_datetime(),
                     api_get_user_id()
                 );
@@ -225,7 +225,7 @@ if (!empty($action)) {
                 event_system(
                     LOG_HOMEPAGE_CHANGED,
                     'edit_notice',
-                    cut(strip_tags($notice_title), 254),
+                    Text::cut(strip_tags($notice_title), 254),
                     api_get_utc_datetime(),
                     api_get_user_id()
                 );
@@ -278,7 +278,7 @@ if (!empty($action)) {
                 event_system(
                     LOG_HOMEPAGE_CHANGED,
                     'edit_news',
-                    strip_tags(cut($home_news, 254)),
+                    strip_tags(Text::cut($home_news, 254)),
                     api_get_utc_datetime(),
                     api_get_user_id()
                 );
@@ -426,7 +426,7 @@ if (!empty($action)) {
                 event_system(
                     LOG_HOMEPAGE_CHANGED,
                     $action,
-                    cut($link_name.':'.$link_url, 254),
+                    Text::cut($link_name.':'.$link_url, 254),
                     api_get_utc_datetime(),
                     api_get_user_id()
                 );

+ 1 - 1
main/admin/configure_inscription.php

@@ -61,7 +61,7 @@ if (!empty($_SESSION['user_language_choice'])) {
 } elseif (!empty($_SESSION['_user']['language'])) {
     $lang = $_SESSION['_user']['language'];
 } else {
-    $lang = get_setting('platformLanguage');
+    $lang = api_get_setting('platformLanguage');
 }
 
 // ----- Ensuring availability of main files in the corresponding language -----

+ 4 - 4
main/admin/skills_import.php

@@ -139,7 +139,7 @@ function parse_xml_data($file) {
 	xml_set_element_handler($parser, 'element_start', 'element_end');
 	xml_set_character_data_handler($parser, 'character_data');
 	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
-	xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
+	xml_parse($parser, Text::api_utf8_encode_xml(file_get_contents($file)));
 	xml_parser_free($parser);
 	return $skills;
 }
@@ -188,7 +188,7 @@ if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
 			$skill_id_error[] = $my_errors['SkillName'];
 		}
 	}
-	
+
 	if (is_array($skills)) {
 		foreach ($skills as $my_skill) {
 			if (!in_array($my_skill['SkillName'], $skill_id_error)) {
@@ -197,9 +197,9 @@ if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
 		}
 	}
 
-	if (strcmp($file_type, 'csv') === 0) {	 
+	if (strcmp($file_type, 'csv') === 0) {
 		save_data($skills_to_insert);
-	} elseif (strcmp($file_type, 'xml') === 0) {   
+	} elseif (strcmp($file_type, 'xml') === 0) {
 		save_data($skills_to_insert);
 	} else {
 		$error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');

+ 10 - 10
main/admin/sub_language.php

@@ -25,7 +25,7 @@ $htmlHeadXtra[] ='<script type="text/javascript">
 		button_name=button_array[1];
 		file_id=button_array[2];
 		is_variable_language="$"+button_name;
-			
+
 		is_new_language=$("#txtid_"+file_id+"_"+button_name).attr("value");
    		if (is_new_language=="undefined") {
 			is_new_language="_";
@@ -39,13 +39,13 @@ $htmlHeadXtra[] ='<script type="text/javascript">
 				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) { 	
+				success: function(datos) {
 					if (datos == "1") {
 						$("#div_message_information_id").html("<div class=\"confirmation-message\">'.get_lang('TheNewWordHasBeenAdded').'</div>");
 					} else {
 						$("#div_message_information_id").html("<div class=\"warning-message\">" + datos +"</div>");
 					}
-				} 
+				}
 			});
 		} else {
 			$("#div_message_information_id").html("<div class=\"error-message\">'.get_lang('FormHasErrorsPleaseComplete').'</div>");
@@ -66,15 +66,15 @@ $sublanguage_folder_error = false;
 
 if (isset($_GET['id']) && $_GET['id']==strval(intval($_GET['id']))) {
 	$language_name              = SubLanguageManager::get_name_of_language_by_id ($_GET['id']);
-	$sub_language_name          = SubLanguageManager::get_name_of_language_by_id ($_GET['sub_language_id']);	
+	$sub_language_name          = SubLanguageManager::get_name_of_language_by_id ($_GET['sub_language_id']);
 	$all_data_of_language       = SubLanguageManager::get_all_information_of_language($_GET['id']);
 	$all_data_of_sublanguage    = SubLanguageManager::get_all_information_of_language($_GET['sub_language_id']);
-	$sub_language_file          = api_get_path(SYS_LANG_PATH).$all_data_of_sublanguage['dokeos_folder'];		
-	
+	$sub_language_file          = api_get_path(SYS_LANG_PATH).$all_data_of_sublanguage['dokeos_folder'];
+
 	if (!file_exists($sub_language_file) || !is_writable($sub_language_file)) {
 	    $sublanguage_folder_error = $sub_language_file.' '.get_lang('IsNotWritable');
-	}		
-	if (SubLanguageManager::check_if_exist_language_by_id($_GET['id'])===true) {		
+	}
+	if (SubLanguageManager::check_if_exist_language_by_id($_GET['id'])===true) {
 		$language_id_exist = true;
 	} else {
 		$language_id_exist = false;
@@ -197,7 +197,7 @@ function search_language_term($term, $search_in_variable = true , $search_in_eng
 				if (is_array($variable_value)) {
 					continue;
 				}
-				
+
 				if (is_array($variable_value))
 					echo $lang_file;
 				$founded = false;
@@ -270,7 +270,7 @@ function search_language_term($term, $search_in_variable = true , $search_in_eng
 		}
 	}
 
-	$list_info = array_unique_dimensional($list_info);
+	$list_info = ArrayClass::array_unique_dimensional($list_info);
 	return $list_info;
 }
 /**

+ 1 - 1
main/admin/user_edit.php

@@ -379,7 +379,7 @@ if ($form->validate()) {
         $hr_dept_id = intval($user['hr_dept_id']);
         $language = $user['language'];
         if ($user['radio_expiration_date'] == '1' && !$user_data['platform_admin']) {
-            $expiration_date = return_datetime_from_array($user['expiration_date']);
+            $expiration_date = Text::return_datetime_from_array($user['expiration_date']);
         } else {
             $expiration_date = '0000-00-00 00:00:00';
         }

+ 1 - 1
main/admin/user_import.php

@@ -245,7 +245,7 @@ function parse_xml_data($file) {
 	xml_set_element_handler($parser, 'element_start', 'element_end');
 	xml_set_character_data_handler($parser, 'character_data');
 	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
-	xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
+	xml_parse($parser, Text::api_utf8_encode_xml(file_get_contents($file)));
 	xml_parser_free($parser);
 	return $users;
 }

+ 1 - 1
main/admin/user_list.php

@@ -212,7 +212,7 @@ function login_user($user_id) {
 
             //Delog the current user
 
-			LoginDelete($_SESSION["_user"]["user_id"]);
+            Online::loginDelete($_SESSION["_user"]["user_id"]);
 
 			// Cleaning session variables
 			unset($_SESSION['_user']);

+ 1 - 1
main/auth/inscription.php

@@ -24,7 +24,7 @@ if (!empty($_SESSION['user_language_choice'])) {
 } elseif (!empty($_SESSION['_user']['language'])) {
     $user_selected_language = $_SESSION['_user']['language'];
 } else {
-    $user_selected_language = get_setting('platformLanguage');
+    $user_selected_language = api_get_setting('platformLanguage');
 }
 
 $form = new FormValidator('registration');

+ 9 - 9
main/auth/shibboleth/app/shibboleth.class.php

@@ -98,7 +98,7 @@ class Shibboleth
             /*
              * Tests if the user tried to login directly in a protected course before to come here
              * (this variable could be set in the modified code of /chamilo/inc/lib/main_api.lib.php)
-             * 
+             *
              * Note:
              *       this part was added to give the possibility to access Chamilo directly on a course URL from a link diplayed in a portal.
              *       This is not a direct Shibboleth related functionnality, but this could be used in a shibbolethized
@@ -109,7 +109,7 @@ class Shibboleth
              */
         }
         if ($url) {
-            //needed to log the user in his courses. Normally it is done by visiting /chamilo/index.php    
+            //needed to log the user in his courses. Normally it is done by visiting /chamilo/index.php
 //            $include_path = api_get_path(INCLUDE_PATH);
 //            require("$include_path/local.inc.php");
 //
@@ -160,7 +160,7 @@ class Shibboleth
     /**
      * Infer the rights/status the user can have in Chamilo based on his affiliation attribute
      *
-     * @param  ShibbolethUser $user      
+     * @param  ShibbolethUser $user
      * @return The Chamilo user status, one of TEACHER, STUDENT or UNKNOWN
      */
     public static function infer_user_status($user)
@@ -200,9 +200,9 @@ class Shibboleth
     /**
      * Return true if the user can ask for a greater status than student.
      * This happens for staff members.
-     * 
+     *
      * @param ShibbolethUser $user
-     * @return boolean 
+     * @return boolean
      */
     public static function infer_status_request($user)
     {
@@ -242,9 +242,9 @@ class Shibboleth
 
         $signagure = <<<EOT
 
-_________________________ 
-$firstname $lastname 
-$email 
+_________________________
+$firstname $lastname
+$email
 $status
 EOT;
 
@@ -257,7 +257,7 @@ EOT;
             $header .= "Cc: $shibb_admin_email";
         }
 
-        $administrator_email = get_setting('emailAdministrator');
+        $administrator_email = api_get_setting('emailAdministrator');
         $result = mail($administrator_email, $subject, $message);
         return (bool) $result;
     }

+ 2 - 2
main/auth/shibboleth/lib/shibboleth_session.class.php

@@ -43,7 +43,7 @@ class ShibbolethSession
     function logout()
     {
         $_SESSION['_user'] = array();
-        online_logout(null, false);
+        Online::logout(null, false);
     }
 
     /**
@@ -87,7 +87,7 @@ class ShibbolethSession
         $uidReset = true;
 
         $gidReset = true;
-        $cidReset = false; //FALSE !!      
+        $cidReset = false; //FALSE !!
 
         $mainDbName = Database :: get_main_database();
         $includePath = api_get_path(INCLUDE_PATH);

+ 4 - 4
main/auth/unsubscribe_account.php

@@ -14,15 +14,15 @@ $form = new FormValidator('user_add');
 $form->addElement('button', 'submit', get_lang('Unsubscribe'), array('onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang("UnsubscribeFromPlatformConfirm")))."')) return false;"));
 $content = $form->return_form();
 
-if ($form->validate()) {    
+if ($form->validate()) {
     $user_info = api_get_user_info();
-    $result = UserManager::delete_user($user_info['user_id']);    
+    $result = UserManager::delete_user($user_info['user_id']);
     if ($result) {
         $message = Display::return_message(sprintf(get_lang('UnsubscribeFromPlatformSuccess', $user_info['username'])));
         $content = null;
-        online_logout($user_info['user_id'], false);
+        Online::logout($user_info['user_id'], false);
         api_not_allowed(true, $message);
-    }    
+    }
 }
 
 $tpl = new Template($tool_name);

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

@@ -527,7 +527,7 @@ function display_monthcalendar($month, $year, $agenda_items)
 
                 if (key_exists($curday, $agenda_items)) {
                     $dayheader = Display::div($curday, array('class' => 'agenda_day'));
-                    $events_in_day = msort($agenda_items[$curday], 'start_date_tms');
+                    $events_in_day = ArrayClass::msort($agenda_items[$curday], 'start_date_tms');
                     foreach ($events_in_day as $value) {
 
                         $some_content = false;
@@ -588,7 +588,7 @@ function display_monthcalendar($month, $year, $agenda_items)
 
                             //Link to bubble
                             $url = Display::url(
-                                cut($value['title'], 40),
+                                Text::cut($value['title'], 40),
                                 '#',
                                 array('id' => $value['calendar_type'].'_'.$value['id'], 'class' => 'opener')
                             );
@@ -2041,7 +2041,7 @@ function display_agenda_items($agenda_items, $day = false)
         $col = 'start';
     }
 
-    $agenda_items = msort($agenda_items, $sort_item, $sort);
+    $agenda_items = ArrayClass::msort($agenda_items, $sort_item, $sort);
 
     //DISPLAY: NO ITEMS
     if (empty($agenda_items)) {
@@ -2412,7 +2412,7 @@ function display_one_agenda_item($agenda_id)
 
     // Content
     $content = $myrow['content'];
-    $content = make_clickable($content);
+    $content = Text::make_clickable($content);
 
     echo '<tr class="row_even">';
     echo '<td '.(api_is_allowed_to_edit() ? 'colspan="3"' : 'colspan="2"').'>';
@@ -3565,7 +3565,7 @@ function get_day_agendaitems($courses_dbs, $month, $year, $day)
 
             if ($setting_agenda_link == 'coursecode') {
                 $title = $array_course_info['title'];
-                $agenda_link = cut($title, 14, true);
+                $agenda_link = Text::cut($title, 14, true);
             } else {
                 $agenda_link = Display::return_icon('course_home.png', '&nbsp;', '', ICON_SIZE_SMALL);
             }
@@ -3682,7 +3682,7 @@ function get_week_agendaitems($courses_dbs, $month, $year, $week = '')
 
             if ($setting_agenda_link == 'coursecode') {
                 $title = $array_course_info['title'];
-                $agenda_link = cut($title, 14, true);
+                $agenda_link = Text::cut($title, 14, true);
             } else {
                 $agenda_link = Display::return_icon('course_home.png', '&nbsp;', '', ICON_SIZE_SMALL);
             }

+ 2 - 12
main/calendar/myagenda.inc.php

@@ -184,7 +184,7 @@ function display_mymonthcalendar($user_id, $agendaitems, $month, $year, $weekday
 
 				if (!empty($agendaitems[$curday])) {
 				   $items =  $agendaitems[$curday];
-				   $items =  msort($items, 'start_date_tms');
+				   $items =  ArrayClass::msort($items, 'start_date_tms');
 
 				   foreach($items  as $value) {
 				        $value['title'] = Security::remove_XSS($value['title']);
@@ -232,7 +232,7 @@ function display_mymonthcalendar($user_id, $agendaitems, $month, $year, $weekday
                             $link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
 
                             //Link to bubble
-                            $url = Display::url(cut($value['title'], 40), '#', array('id'=>$link, 'class'=>'opener'));
+                            $url = Display::url(Text::cut($value['title'], 40), '#', array('id'=>$link, 'class'=>'opener'));
                             $result .= $time.' '.$icon.' '.Display::div($url);
 
                             //Hidden content
@@ -874,20 +874,10 @@ function show_simple_personal_agenda($user_id) {
 			$content.= date("d", strtotime($myrow["date"]))." ".$MonthsLong[date("n", strtotime($myrow["date"])) - 1]." ".date("Y", strtotime($myrow["date"]))."&nbsp;";
 			$content.= strftime(get_lang("timeNoSecFormat"), strtotime($myrow["date"]));
 
-			/*--------------------------------------------------
-			 			display: the title
-			  --------------------------------------------------*/
 			$content.= '<br />';
 			$content.= $myrow['title'];
 			$content.= '<br />';
 
-			/*--------------------------------------------------
-			 			display: the content
-			  --------------------------------------------------*/
-			  /*
-			$content = $myrow['title'];
-			$content = make_clickable($content);
-			*/
 			return $content;
 		}
 	} else {

+ 1 - 1
main/calendar/print.php

@@ -47,7 +47,7 @@ $result			= Database::query($sql);
 <?php
 while($row=Database::fetch_array($result)) {
 	$row['content'] = $row['content'];
-	$row['content'] = make_clickable($row['content']);
+	$row['content'] = Text::make_clickable($row['content']);
 	$row['content'] = str_replace('<a ','<a target="_blank" ',$row['content']);
 
 	if(!empty($row['title'])) {

+ 1 - 1
main/chat/chat_message.php

@@ -257,7 +257,7 @@ if (!empty($course) && !empty($_user['user_id'])) {
 
         if (!api_is_anonymous()) {
             if (!empty($message)) {
-                $message = make_clickable($message);
+                $message = Text::make_clickable($message);
 
                 if (!file_exists($chat_path.$basename_chat.'.log.html')) {
                     $doc_id = FileManager::add_document(

+ 1 - 1
main/course_info/infocours.php

@@ -175,7 +175,7 @@ $group = array();
 $group[]=$form->createElement('select_theme', 'course_theme', null, array('class'=>' ', 'id'=>'course_theme_id'));
 $form->addGroup($group, '', array(get_lang("Stylesheets")), '');
 
-$form->addElement('label', get_lang('DocumentQuota'),  format_file_size(DocumentManager::get_course_quota()));
+$form->addElement('label', get_lang('DocumentQuota'), Text::format_file_size(DocumentManager::get_course_quota()));
 
 $form->addElement('style_submit_button', null, get_lang('SaveSettings'), 'class="save"');
 $form->addElement('html', '</div></div>');

+ 2 - 2
main/coursecopy/classes/Course.class.php

@@ -178,8 +178,8 @@ class Course
 							break;
 					}
 
-					$title = api_html_to_text($title);
-					$description = api_html_to_text($description);
+					$title = Text::api_html_to_text($title);
+					$description = Text::api_html_to_text($description);
 
 					if (!empty($title)) {
 						$sample_text .= $title."\n";

+ 7 - 11
main/document/create_audio.php

@@ -127,7 +127,7 @@ $dir_acum = '';
 for ($i = 0; $i < $array_len; $i++) {
     $url_dir = 'document.php?&curdirpath='.$dir_acum.$dir_array[$i];
     //Max char 80
-    $url_to_who = cut($dir_array[$i], 80);
+    $url_to_who = Text::cut($dir_array[$i], 80);
     if ($is_certificate_mode) {
         $interbreadcrumb[] = array(
             'url' => $url_dir.'&selectcat='.Security::remove_XSS($_GET['selectcat']),
@@ -313,16 +313,14 @@ if (Security::remove_XSS($_GET['dt2a']) == 'pediaphon') {
     ?>
 
 <!-- javascript form name form2 update voices -->
-<script type="text/javascript">
+<script>
     var langslist = document.form2.lang
     var voiceslist = document.form2.voices
-    var voices = new Array()
+    var voices = new Array();
 
-            < !--Default
-    message-- >
             voices[0] = ["<?php echo get_lang('FirstSelectALanguage'); ?>"]
 
-            < !--German-- >
+            // German
             voices[1] = ["<?php echo get_lang('Female').' (de1)'; ?>|de1", "<?php echo get_lang(
         'Male'
     ).' (de2)'; ?>|de2", "<?php echo get_lang('Female').' (de3)'; ?>|de3", "<?php echo get_lang(
@@ -333,7 +331,7 @@ if (Security::remove_XSS($_GET['dt2a']) == 'pediaphon') {
         'Female'
     ).' (de8 HQ)'; ?>|de8"]
 
-            < !--English-- >
+            // English
             voices[2] = ["<?php echo get_lang('Male').' (en1)'; ?>|en1", "<?php echo get_lang(
         'Male'
     ).' (en2 HQ)'; ?>|en2", "<?php echo get_lang('Female').' (us1)'; ?>| us1", "<?php echo get_lang(
@@ -342,10 +340,10 @@ if (Security::remove_XSS($_GET['dt2a']) == 'pediaphon') {
         'Female'
     ).'(us4 HQ)'; ?>|us4"]
 
-            < !--Spanish-- >
+            //Spanish
             voices[3] = ["<?php echo get_lang('Male').' (es5 HQ)'; ?>|es5"]
 
-            < !--French-- >
+            //French
             voices[4] = ["<?php echo get_lang('Female').' (fr8 HQ)'; ?>|fr8"]
 
 
@@ -355,8 +353,6 @@ if (Security::remove_XSS($_GET['dt2a']) == 'pediaphon') {
             voiceslist.options[voiceslist.options.length] = new Option(voices[selectedvoicegroup][i].split("|")[0], voices[selectedvoicegroup][i].split("|")[1])
     }
 </script>
-
-
 <?php
 }
 //end pediaphon

+ 2 - 2
main/document/create_document.php

@@ -463,7 +463,7 @@ if (!$is_certificate_mode && !is_my_shared_folder($_user['user_id'], $dir, $curr
 
                 $selected = (substr($dir, 0, -1) == $folder) ? ' selected="selected"' : '';
                 $path_parts = explode('/', $folder);
-                $folder_titles[$folder] = cut($folder_titles[$folder], 80);
+                $folder_titles[$folder] = Text::cut($folder_titles[$folder], 80);
                 $space_counter = count($path_parts) - 2;
                 if ($space_counter > 0) {
                     $label = str_repeat('&nbsp;&nbsp;&nbsp;', $space_counter).' &mdash; '.$folder_titles[$folder];
@@ -484,7 +484,7 @@ if (!$is_certificate_mode && !is_my_shared_folder($_user['user_id'], $dir, $curr
                 $label = '/ ('.get_lang('HomeDirectory').')';
             } else {
                 $path_parts = explode('/', str_replace($group_dir, '', $folder));
-                $label = cut($label, 80);
+                $label = Text::cut($label, 80);
                 $label = str_repeat('&nbsp;&nbsp;&nbsp;', count($path_parts) - 2).' &mdash; '.$label;
             }
             $parent_select->addOption($label, $folder);

+ 6 - 12
main/document/document.inc.php

@@ -61,7 +61,7 @@ function build_directory_selector($folders, $document_id, $group_dir = '', $chan
             foreach ($folders as $folder_id => & $folder) {
                 $selected = ($document_id == $folder_id) ? ' selected="selected"' : '';
                 $path_parts = explode('/', $folder);
-                $folder_titles[$folder] = cut($folder_titles[$folder], 80);
+                $folder_titles[$folder] = Text::cut($folder_titles[$folder], 80);
                 $counter = count($path_parts) - 2;
                 if ($counter > 0) {
                     $label = str_repeat('&nbsp;&nbsp;&nbsp;', $counter).' &mdash; '.$folder_titles[$folder];
@@ -83,7 +83,7 @@ function build_directory_selector($folders, $document_id, $group_dir = '', $chan
                     $label = get_lang('Documents');
                 } else {
                     $path_parts = explode('/', str_replace($group_dir, '', $folder));
-                    $label = cut($label, 80);
+                    $label = Text::cut($label, 80);
                     $label = str_repeat('&nbsp;&nbsp;&nbsp;', count($path_parts) - 2).' &mdash; '.$label;
                 }
                 $parent_select->addOption($label, $folder_id);
@@ -190,20 +190,14 @@ function create_document_link($document_data, $show_as_icon = false, $counter =
 
     $tooltip_title = $title;
 
-    //Cut long titles
-    //$title = cut($title, 120);
-
     $tooltip_title_alt = $tooltip_title;
     if ($path == '/shared_folder') {
         $tooltip_title_alt = get_lang('UserFolders');
     } elseif (strstr($path, 'shared_folder_session_')) {
         $tooltip_title_alt = get_lang('UserFolders').' ('.api_get_session_name(api_get_session_id()).')';
     } elseif (strstr($tooltip_title, 'sf_user_')) {
-        $userinfo = Database::get_user_info_from_id(substr($tooltip_title, 8));
-        $tooltip_title_alt = get_lang('UserFolder').' '.api_get_person_name(
-            $userinfo['firstname'],
-            $userinfo['lastname']
-        );
+        $userinfo = api_get_user_info(substr($tooltip_title, 8));
+        $tooltip_title_alt = get_lang('UserFolder').' '.$userinfo['complete_name'];
     } elseif ($path == '/chat_files') {
         $tooltip_title_alt = get_lang('ChatFiles');
     } elseif ($path == '/learning_path') {
@@ -487,7 +481,7 @@ function build_document_icon_tag($type, $path)
                 $basename = get_lang('UserFolders');
             }
         } elseif (strstr($basename, 'sf_user_')) {
-            $userinfo = Database::get_user_info_from_id(substr($basename, 8));
+            $userinfo = api_get_user_info(substr($basename, 8));
             $image_path = UserManager::get_user_picture_path_by_id(substr($basename, 8), 'web', false, true);
 
             if ($image_path['file'] == 'unknown.jpg') {
@@ -496,7 +490,7 @@ function build_document_icon_tag($type, $path)
                 $icon = '../upload/users/'.substr($basename, 8).'/'.$image_path['file'];
             }
 
-            $basename = get_lang('UserFolder').' '.api_get_person_name($userinfo['firstname'], $userinfo['lastname']);
+            $basename = get_lang('UserFolder').' '.$userinfo['complete_name'];
         } elseif (strstr($path, 'shared_folder_session_')) {
             if ($is_allowed_to_edit) {
                 $basename = '***('.api_get_session_name($current_session_id).')*** '.get_lang('HelpUsersFolder');

+ 1 - 1
main/document/document.php

@@ -1354,7 +1354,7 @@ if (isset($docs_and_folders) && is_array($docs_and_folders)) {
             ).'</i>'.$invisibility_span_close.$user_link;
 
             // Comments => display comment under the document name
-            $display_size = format_file_size($size);
+            $display_size = Text::format_file_size($size);
             $row[] = '<span style="display:none;">'.$size.'</span>'.$invisibility_span_open.$display_size.$invisibility_span_close;
 
             // Last edit date

+ 2 - 2
main/document/document_lite.php

@@ -892,7 +892,7 @@ if (isset($docs_and_folders) && is_array($docs_and_folders)) {
             $document_data['path'],
             $is_allowed_to_edit
         ) : $document_data['size'];
-        $row['size'] = format_file_size($size);
+        $row['size'] = Text::format_file_size($size);
 
         // Get the title or the basename depending on what we're using
         if ($document_data['title'] != '') {
@@ -982,7 +982,7 @@ if (isset($docs_and_folders) && is_array($docs_and_folders)) {
         ).'</i>'.$invisibility_span_close.$user_link;
 
         // Comments => display comment under the document name
-        $display_size = format_file_size($size);
+        $display_size = Text::format_file_size($size);
         $row[] = '<span style="display:none;">'.$size.'</span>'.$invisibility_span_open.$display_size.$invisibility_span_close;
 
         // Last edit date

+ 5 - 5
main/document/document_quota.php

@@ -47,7 +47,7 @@ $quota_bytes = DocumentManager::documents_total_space($course_id, 0 , 0);
 
 $quota_percentage = round($quota_bytes/$total_quota_bytes, 2)*100;
 
-$session[] = array(get_lang('Course').' ('.format_file_size($quota_bytes).')', $quota_percentage);
+$session[] = array(get_lang('Course').' ('.Text::format_file_size($quota_bytes).')', $quota_percentage);
 
 $used_quota_bytes = $quota_bytes;
 if (!empty($session_list)) {
@@ -61,7 +61,7 @@ if (!empty($session_list)) {
             $session_data['name'] = $session_data['name'] . ' * ';
         }
         $used_quota_bytes += $quota_bytes;
-        $session[] = array(addslashes(get_lang('Session').': '.$session_data['name']).' ('.format_file_size($quota_bytes).')', $quota_percentage);
+        $session[] = array(addslashes(get_lang('Session').': '.$session_data['name']).' ('.Text::format_file_size($quota_bytes).')', $quota_percentage);
     }
 }
 
@@ -79,7 +79,7 @@ if (!empty($group_list)) {
             $group_data['name'] = $group_data['name'] . ' * ';
         }
         $used_quota_bytes += $quota_bytes;
-        $session[] = array(addslashes(get_lang('Group').': '.$group_data['name']).' ('.format_file_size($quota_bytes).')', $quota_percentage);
+        $session[] = array(addslashes(get_lang('Group').': '.$group_data['name']).' ('.Text::format_file_size($quota_bytes).')', $quota_percentage);
     }
 }
 //Showing weight of documents uploaded by user
@@ -94,7 +94,7 @@ if (is_array($document_list)) {
        $quota_percentage = round($quota_bytes/$total_quota_bytes, 2)*100;
     }
 
-    $session[] = array(addslashes(get_lang('Teacher').': '.$user_name).' ('.format_file_size($quota_bytes).')', $quota_percentage);
+    $session[] = array(addslashes(get_lang('Teacher').': '.$user_name).' ('.Text::format_file_size($quota_bytes).')', $quota_percentage);
     //if a sesson is active
     if ($session_id != 0) {
         if (!empty($course_list)) {
@@ -112,7 +112,7 @@ if (is_array($document_list)) {
 }
 $quota_percentage = round(($total_quota_bytes - $used_quota_bytes)/$total_quota_bytes, 2)*100;
 
-$session[] = array(addslashes(get_lang('ShowCourseQuotaUse')).' ('.format_file_size($total_quota_bytes - $used_quota_bytes).') ', $quota_percentage);
+$session[] = array(addslashes(get_lang('ShowCourseQuotaUse')).' ('.Text::format_file_size($total_quota_bytes - $used_quota_bytes).') ', $quota_percentage);
 
 $quota_data = json_encode($session);
 

+ 4 - 4
main/document/show_content.php

@@ -2,7 +2,7 @@
 /* For licensing terms, see /license.txt */
 /**
  *	@author jmontoya
- *  
+ *
  *	@package chamilo.document
  */
 /**
@@ -21,13 +21,13 @@ $header_file = Security::remove_XSS($_GET['file']);
 $document_id = intval($_GET['id']);
 
 $course_info = api_get_course_info();
-$course_code = api_get_course_id(); 
+$course_code = api_get_course_id();
 
 if (empty($course_info)) {
     api_not_allowed(true);
 }
 
-//Generate path 
+//Generate path
 if (!$document_id) {
     $document_id = DocumentManager::get_document_id($course_info, $header_file);
 }
@@ -38,7 +38,7 @@ if (empty($document_data)) {
 }
 
 $header_file  = $document_data['path'];
-$name_to_show = cut($header_file, 80);
+$name_to_show = Text::cut($header_file, 80);
 
 $path_array = explode('/', str_replace('\\', '/', $header_file));
 $path_array = array_map('urldecode', $path_array);

+ 7 - 7
main/document/showinframesmin.php

@@ -2,7 +2,7 @@
 /* For licensing terms, see /license.txt */
 /**
  *	@author Juan Carlos Raña Trabado (herodoto@telefonica.net)
- *  
+ *
  *	@package chamilo.document
  */
 /**
@@ -24,13 +24,13 @@ $header_file = Security::remove_XSS($_GET['file']);
 $document_id = intval($_GET['id']);
 
 $course_info = api_get_course_info();
-$course_code = api_get_course_id(); 
+$course_code = api_get_course_id();
 
 if (empty($course_info)) {
     api_not_allowed(true);
 }
 
-//Generate path 
+//Generate path
 if (!$document_id) {
     $document_id = DocumentManager::get_document_id($course_info, $header_file);
 }
@@ -41,7 +41,7 @@ if (empty($document_data)) {
 }
 
 $header_file  = $document_data['path'];
-$name_to_show = cut($header_file, 80);
+$name_to_show = Text::cut($header_file, 80);
 
 $path_array = explode('/', str_replace('\\', '/', $header_file));
 $path_array = array_map('urldecode', $path_array);
@@ -130,12 +130,12 @@ $htmlHeadXtra[] = '
         //document.getElementById("mainFrame").style.height = ((docHeight-(parseInt(HeaderHeight)+parseInt(FooterHeight)))+60)+"px";
         my_iframe           = document.getElementById("mainFrame");
         new_height          = my_iframe.contentWindow.document.body.scrollHeight;
-        my_iframe.height    = my_iframe.contentWindow.document.body.scrollHeight + "px";        
+        my_iframe.height    = my_iframe.contentWindow.document.body.scrollHeight + "px";
     };
 
     // Fixes the content height of the frame
     window.onload = function() {
-         updateContentHeight();    
+         updateContentHeight();
         '.$js_glossary_in_documents.'
     }
 -->
@@ -158,6 +158,6 @@ if ($pathinfo['extension']=='wav' && preg_match('/_chnano_.wav/i', $file_url_web
 	echo '</div>';
 } else {
 	if ($pathinfo['extension']=='swf'){ $width='83%'; $height='83%';} else {$width='100%'; $height='';}
-	
+
 	echo '<iframe border="0" frameborder="0" scrolling="no" style="width:'.$width.'; height:'.$height.';background-color:#ffffff;" id="mainFrame" name="mainFrame" src="'.$file_url_web.'&amp;rand='.mt_rand(1, 10000).'"></iframe>';
 }

+ 12 - 12
main/document/upload.php

@@ -86,7 +86,7 @@ $(function () {
         buildUploadRow: function (files, index) {
 			$('.files').show();
             return $('<tr><td>' + files[index].name + '<\/td>' +
-					'<td class=\"file_upload_progress\"><div><\/div><\/td>' +                    
+					'<td class=\"file_upload_progress\"><div><\/div><\/td>' +
                     '<td class=\"file_upload_cancel\">' +
                     '<button class=\"ui-state-default ui-corner-all\" title=\"".get_lang('Cancel')."\">' + '<span class=\"ui-icon ui-icon-cancel\">".get_lang('Cancel')."<\/span>' +'<\/button>'+
 					'<\/td><\/tr>');
@@ -94,7 +94,7 @@ $(function () {
         buildDownloadRow: function (file) {
             return $('<tr><td>' + file.name + '<\/td> <td> ' + file.size + ' <\/td>  <td>&nbsp;' + file.result + ' <\/td> <\/tr>');
         }
-    });    
+    });
     $('#tabs').tabs();
 });
 </script>";
@@ -112,7 +112,7 @@ $selectcat = isset($_GET['selectcat']) ? Security::remove_XSS($_GET['selectcat']
 $document_data  = DocumentManager::get_document_data_by_id($_REQUEST['id'], api_get_course_id(), true);
 if (empty($document_data)) {
     $document_id  = $parent_id =  0;
-    $path = '/';    
+    $path = '/';
 } else {
     $document_id    = $document_data['id'];
     $path           = $document_data['path'];
@@ -120,13 +120,13 @@ if (empty($document_data)) {
 }
 $group_properties = array();
 // This needs cleaning!
-if (api_get_group_id()) { 
+if (api_get_group_id()) {
     // If the group id is set, check if the user has the right to be here
 	// Needed for group related stuff
 	require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php';
 	// Get group info
 	$group_properties = GroupManager::get_group_properties(api_get_group_id());
-	
+
 	if ($is_allowed_to_edit || GroupManager::is_user_in_group($_user['user_id'], api_get_group_id())) { // Only courseadmin or group members allowed
 		$to_group_id = api_get_group_id();
 		$req_gid = '&amp;gidReq='.api_get_group_id();
@@ -135,7 +135,7 @@ if (api_get_group_id()) {
 		api_not_allowed(true);
 	}
 } elseif ($is_allowed_to_edit || is_my_shared_folder(api_get_user_id(), $path, api_get_session_id())) {
-     
+
     // Admin for "regular" upload, no group documents. And check if is my shared folder
 	$to_group_id = 0;
 	$req_gid = '';
@@ -190,7 +190,7 @@ Display::display_header($nameTools, 'Doc');
 /*	Here we do all the work */
 
 // User has submitted a file
-if (!empty($_FILES)) {    
+if (!empty($_FILES)) {
     DocumentManager::upload_document($_FILES, $_POST['curdirpath'], $_POST['title'], $_POST['comment'], $_POST['unzip'], $_POST['if_exists'], $_POST['index_document'], true);
 }
 
@@ -226,7 +226,7 @@ $form = new FormValidator('upload', 'POST', $action.'#tabs-2', '', 'enctype="mul
 $form->addElement('hidden', 'id', $document_id);
 $form->addElement('hidden', 'curdirpath', $path);
 
-$course_quota = format_file_size(DocumentManager::get_course_quota() - DocumentManager::documents_total_space());
+$course_quota = Text::format_file_size(DocumentManager::get_course_quota() - DocumentManager::documents_total_space());
 
 $label = get_lang('MaxFileSize').': '.ini_get('upload_max_filesize').'<br/>'.get_lang('DocumentQuota').': '.$course_quota;
 
@@ -281,11 +281,11 @@ $multiple_form =  get_lang('ClickToSelectOrDragAndDropMultipleFilesOnTheUploadFi
 //<div style="width:50%;margin:0 auto;"> '.Display::div(Display::return_icon('folder_document.png', '', array(), 64), array('style'=>'float:left')).' '.get_lang('UploadFiles').'</div>
 $multiple_form .=  '
 	<center>
-	<form id="file_upload" action="'.$url.'" method="POST" enctype="multipart/form-data">    
-    	<input type="hidden" name="curdirpath" value="'.$path.'" />    
+	<form id="file_upload" action="'.$url.'" method="POST" enctype="multipart/form-data">
+    	<input type="hidden" name="curdirpath" value="'.$path.'" />
     	<input type="file" name="file" multiple>
     	<button type="submit">Upload</button>
-    	'.get_lang('UploadFiles').' 
+    	'.get_lang('UploadFiles').'
 	</form>
 	</center>
 	<table style="display:none; width:50%" class="files data_table">
@@ -301,6 +301,6 @@ if ($nav_info ['name'] == 'Internet Explorer') {
 	echo $simple_form;
 } else {
 	$headers = array(get_lang('Send') , get_lang('Send').' ('.get_lang('Simple').')');
-	echo Display::tabs($headers, array($multiple_form, $simple_form),'tabs');	
+	echo Display::tabs($headers, array($multiple_form, $simple_form),'tabs');
 }
 Display::display_footer();

+ 9 - 9
main/dropbox/index.php

@@ -145,9 +145,9 @@ if (isset($_POST['submitWork'])) {
 	$check = Security::check_token();
 	if ($check) {
         $message = store_add_dropbox();
-        if (!empty($message)) {        
+        if (!empty($message)) {
             Display :: display_confirmation_message($message);
-        }		
+        }
 	}
 }
 
@@ -309,7 +309,7 @@ if ($action != 'add') {
 		}
 	}
 
-	if (!$_GET['view'] OR $_GET['view'] == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {		
+	if (!$_GET['view'] OR $_GET['view'] == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {
 		// This is for the categories
 		if (isset($_GET['view_sent_category']) AND $_GET['view_sent_category'] != '') {
 			$view_dropbox_category_sent = $_GET['view_sent_category'];
@@ -365,7 +365,7 @@ if ($action != 'add') {
 
 	/*	RECEIVED FILES */
 
-	if ($_GET['view'] == 'received' OR !$dropbox_cnf['sent_received_tabs']) {		
+	if ($_GET['view'] == 'received' OR !$dropbox_cnf['sent_received_tabs']) {
 		// This is for the categories
 		if (isset($_GET['view_received_category']) AND $_GET['view_received_category'] != '') {
 			$view_dropbox_category_received = $_GET['view_received_category'];
@@ -445,7 +445,7 @@ if ($action != 'add') {
 				$dropbox_file_data[] = $link_open.build_document_icon_tag('file', $dropbox_file->title).'</a>';
 				$dropbox_file_data[] = '<a href="dropbox_download.php?'.api_get_cidreq().'&id='.$dropbox_file->id.'&amp;action=download">'.Display::return_icon('save.png', get_lang('Download'), array('style' => 'float:right;'),ICON_SIZE_SMALL).'</a>'.$link_open.$dropbox_file->title.'</a>'.$new_icon.'<br />'.$dropbox_file->description;
 				$file_size = $dropbox_file->filesize;
-				$dropbox_file_data[] = format_file_size($file_size);
+				$dropbox_file_data[] = Text::format_file_size($file_size);
 				$dropbox_file_data[] = $dropbox_file->author;
 				//$dropbox_file_data[] = $dropbox_file->description;
 
@@ -457,7 +457,7 @@ if ($action != 'add') {
 									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=movereceived&amp;move_id='.$dropbox_file->id.'&'.$sort_params.'">'.Display::return_icon('move.png', get_lang('Move'),'',ICON_SIZE_SMALL).'</a>
 									<a href="'.api_get_self().'?'.api_get_cidreq().'&view_received_category='.Security::remove_XSS($_GET['view_received_category']).'&amp;view_sent_category='.Security::remove_XSS($_GET['view_sent_category']).'&amp;view='.Security::remove_XSS($_GET['view']).'&amp;action=deletereceivedfile&amp;id='.$dropbox_file->id.'&'.$sort_params.'" onclick="javascript: return confirmation(\''.$dropbox_file->title.'\');">'.
                                     Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
-				
+
 				// This is a hack to have an additional row in a sortable table
 
 				if ($action == 'viewfeedback' AND isset($_GET['id']) and is_numeric($_GET['id']) AND $dropbox_file->id == $_GET['id']) {
@@ -516,7 +516,7 @@ if ($action != 'add') {
 
 	/*	SENT FILES */
 
-	if (!$_GET['view'] OR $_GET['view'] == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {		
+	if (!$_GET['view'] OR $_GET['view'] == 'sent' OR !$dropbox_cnf['sent_received_tabs']) {
 		// This is for the categories
 		if (isset($_GET['view_sent_category']) AND $_GET['view_sent_category'] != '') {
 			$view_dropbox_category_sent = $_GET['view_sent_category'];
@@ -526,7 +526,7 @@ if ($action != 'add') {
 
 		// Object initialisation
 		$dropbox_person = new Dropbox_Person(api_get_user_id(), $is_courseAdmin, $is_courseTutor);
-        
+
 		// Constructing the array that contains the total number of feedback messages per document.
 		$number_feedback = get_total_number_feedback();
 
@@ -587,7 +587,7 @@ if ($action != 'add') {
 				$dropbox_file_data[] = $link_open.build_document_icon_tag('file', $dropbox_file->title).'</a>';
 				$dropbox_file_data[] = '<a href="dropbox_download.php?'.api_get_cidreq().'&id='.$dropbox_file->id.'&amp;action=download">'.Display::return_icon('save.png', get_lang('Save'), array('style' => 'float:right;'),ICON_SIZE_SMALL).'</a>'.$link_open.$dropbox_file->title.'</a><br />'.$dropbox_file->description;
 				$file_size = $dropbox_file->filesize;
-				$dropbox_file_data[] = format_file_size($file_size);
+				$dropbox_file_data[] = Text::format_file_size($file_size);
 				foreach ($dropbox_file->recipients as $recipient) {
 					$receivers_celldata = display_user_link_work($recipient['user_id'], $recipient['name']).', '.$receivers_celldata;
 				}

+ 2 - 2
main/exercice/addlimits.php

@@ -31,7 +31,7 @@ $dsp_percent = false;
 $debug=0;
 if($debug>0)
 {
-	echo str_repeat('&nbsp;',0).'Entered exercise_result.php'."<br />\n";var_dump($_POST);
+	echo str_repeat('&nbsp;',0).'Entered exercise_result.php'."<br />\n";exervar_dump($_POST);
 }
 // general parameters passed via POST/GET
 if ( empty ( $origin ) )
@@ -185,7 +185,7 @@ if (isset($_POST['ok'])) {
 		Database::query($query);
 	} else {
 		$query = "UPDATE ".$TBL_EXERCICES." SET num_attempts = 0 WHERE id= $exercise_id";
-		Database::query($query); 
+		Database::query($query);
 	}
 }
 ?>

+ 1 - 1
main/exercice/draggable.class.php

@@ -70,7 +70,7 @@ class Draggable extends Matching
                         if ($answer->isCorrect($i)) {
                             $nb_matches++;
                             $defaults['answer['.$nb_matches.']']    = $answer->selectAnswer($i);
-                            $defaults['weighting['.$nb_matches.']'] = float_format($answer->selectWeighting($i), 1);
+                            $defaults['weighting['.$nb_matches.']'] = Text::float_format($answer->selectWeighting($i), 1);
                             $defaults['matches['.$nb_matches.']']   = $answer->correct[$i];//$nb_matches;
                         } else {
                             $nb_options++;

+ 4 - 5
main/exercice/exercise.class.php

@@ -195,7 +195,7 @@ class Exercise
 
     function getCutTitle()
     {
-        return cut($this->exercise, EXERCISE_MAX_NAME_SIZE);
+        return Text::cut($this->exercise, EXERCISE_MAX_NAME_SIZE);
     }
 
     /**
@@ -2750,7 +2750,6 @@ class Exercise
                             $answer = $temp;
                             /* // Deprecated code
                               // TeX parsing - replacement of texcode tags
-                              $texstring = api_parse_tex($texstring);
                               $answer = str_replace("{texcode}", $texstring, $answer);
                              */
                             $real_text[] = $answer;
@@ -3325,9 +3324,9 @@ class Exercise
                         } elseif ($answerType == MATCHING) {
                             //if ($origin != 'learnpath') {
                                 echo '<tr>';
-                                echo '<td>'.$answer_matching[$answerId].'</td><td>'.$user_answer.' / <b><span style="color: #008000;">'.text_filter(
+                                echo '<td>'.$answer_matching[$answerId].'</td><td>'.$user_answer.' / <b><span style="color: #008000;">'.
                                     $answer_matching[$answerCorrect]
-                                ).'</span></b></td>';
+                                .'</span></b></td>';
                                 echo '</tr>';
                             //}
                         }
@@ -4544,7 +4543,7 @@ class Exercise
                             $question_id = $media_questions[$question_id];
                         }
                     }
-                    $new_question_list = array_flatten($new_question_list);
+                    $new_question_list = ArrayClass::array_flatten($new_question_list);
                 }
             } else {
                 $new_question_list = $question_list;

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

@@ -1389,7 +1389,7 @@ function get_exam_results_data($from, $number_of_items, $column, $direction, $ex
 }
 
 /**
- * Converts the score with the exercise_max_note and exercise_min_score the platform settings + formats the results using the float_format function
+ * Converts the score with the exercise_max_note and exercise_min_score the platform settings + formats the results using the Text::float_format function
  *
  * @param   float   score
  * @param   float   weight
@@ -1419,9 +1419,9 @@ function show_score($score, $weight, $show_percentage = true, $use_platform_sett
     $percentage = (100 * $score) / ($weight != 0 ? $weight : 1);
 
     //Formats values
-    $percentage = float_format($percentage, 1);
-    $score = float_format($score, 1);
-    $weight = float_format($weight, 1);
+    $percentage = Text::float_format($percentage, 1);
+    $score = Text::float_format($score, 1);
+    $weight = Text::float_format($weight, 1);
 
     $html = null;
     if ($show_percentage) {
@@ -1439,7 +1439,7 @@ function show_score($score, $weight, $show_percentage = true, $use_platform_sett
 
 function is_success_exercise_result($score, $weight, $pass_percentage)
 {
-    $percentage = float_format(($score / ($weight != 0 ? $weight : 1)) * 100, 1);
+    $percentage = Text::float_format(($score / ($weight != 0 ? $weight : 1)) * 100, 1);
     if (isset($pass_percentage) && !empty($pass_percentage)) {
         if ($percentage >= $pass_percentage) {
             return true;
@@ -1492,7 +1492,7 @@ function convert_to_percentage($value)
 {
     $return = '-';
     if ($value != '') {
-        $return = float_format($value * 100, 1).' %';
+        $return = Text::float_format($value * 100, 1).' %';
     }
     return $return;
 }
@@ -1517,7 +1517,7 @@ function convert_score($score, $weight)
             }
         }
     }
-    $score_rounded = float_format($score, 1);
+    $score_rounded = Text::float_format($score, 1);
     return $score_rounded;
 }
 
@@ -1772,7 +1772,7 @@ function get_average_score($exercise_id, $course_code, $session_id)
                 $avg_score +=$score;
             }
         }
-        $avg_score = float_format($avg_score / count($user_results), 1);
+        $avg_score = Text::float_format($avg_score / count($user_results), 1);
     }
     return $avg_score;
 }
@@ -1845,7 +1845,7 @@ function get_best_average_score_by_exercise($exercise_id, $course_code, $session
         //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
         //$avg_score = ($avg_score / count($user_results));
         if (!empty($user_count)) {
-            $avg_score = float_format($avg_score / $user_count, 1) * 100;
+            $avg_score = Text::float_format($avg_score / $user_count, 1) * 100;
         } else {
             $avg_score = 0;
         }
@@ -2059,7 +2059,6 @@ function check_fill_in_blanks($answer, $user_answer)
             $answer = $temp;
             /* // Deprecated code
               // TeX parsing - replacement of texcode tags
-              $texstring = api_parse_tex($texstring);
               $answer = str_replace("{texcode}", $texstring, $answer);
              */
             $real_text[] = $answer;

+ 3 - 3
main/exercice/exercise_reminder.php

@@ -210,10 +210,10 @@ foreach ($question_list as $questionId) {
 
 	$counter++;
 	if ($objExercise->type == ONE_PER_PAGE) {
-	    $question_title = Display::url($counter.'. '.cut($objQuestionTmp->selectTitle(), 40), $url);
-	    $question_title = $counter.'. '.cut($objQuestionTmp->selectTitle(), 40);
+	    $question_title = Display::url($counter.'. '.Text::cut($objQuestionTmp->selectTitle(), 40), $url);
+	    $question_title = $counter.'. '.Text::cut($objQuestionTmp->selectTitle(), 40);
 	} else {
-	    $question_title = $counter.'. '.cut($objQuestionTmp->selectTitle(), 40);
+	    $question_title = $counter.'. '.Text::cut($objQuestionTmp->selectTitle(), 40);
 	}
     //Check if the question doesn't have an answer
     if (!in_array($questionId, $exercise_result)) {

+ 0 - 19
main/exercice/export/scorm/scorm_classes.php

@@ -715,25 +715,6 @@ class ScormAnswerHotspot extends Answer
 		}
 		$answer_list .= '</ol></div>';
 
-		/*
-		if(!$onlyAnswers)
-		{
-			$s="<tr>
-			  <td valign='top' colspan='2'>&nbsp;";
-			$questionName=text_filter($questionName);
-			$s.=$questionName;
-			$s.="</td>
-			</tr>
-			<tr>
-			  <td valign='top' colspan='2'>
-				<i>";
-			$questionDescription=text_filter($questionDescription);
-			$s.=$questionDescription;
-			$s.="</i>
-			  </td>
-			</tr>";
-		}
-		*/
 
 		//$canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1');
 		$canClick = true;

+ 5 - 5
main/exercice/freeanswer.class.php

@@ -41,7 +41,7 @@ if (!class_exists('FreeAnswer')):
             // setting the save button here and not in the question class.php
             $form->addElement('style_submit_button', 'submitQuestion', $text, 'class="' . $class . '"');
             if (!empty($this->id)) {
-                $form->setDefaults(array('weighting' => float_format($this->weighting, 1)));
+                $form->setDefaults(array('weighting' => Text::float_format($this->weighting, 1)));
             } else {
                 if ($this->isContent == 1) {
                     $form->setDefaults(array('weighting' => '10'));
@@ -58,18 +58,18 @@ if (!class_exists('FreeAnswer')):
             $this->save();
         }
 
-        function return_header($feedback_type = null, $counter = null, $score = null, $show_media = false) {            
+        function return_header($feedback_type = null, $counter = null, $score = null, $show_media = false) {
             if (!empty($score['comments']) || $score['score'] > 0) {
                 $score['revised'] = true;
             } else {
                 $score['revised'] = false;
             }
             $header = parent::return_header($feedback_type, $counter, $score, $show_media);
-            $header .= '<table class="' . $this->question_table_class . '" >	
-	        <tr>		
+            $header .= '<table class="' . $this->question_table_class . '" >
+	        <tr>
 			<th>' . get_lang("Answer") . '</th>
 			</tr>';
             return $header;
         }
-    }    
+    }
 endif;

+ 3 - 3
main/exercice/hotpotatoes.lib.php

@@ -57,7 +57,7 @@ function GetQuizName($fname, $fpath) {
             $contents = @fread($fp, filesize($fpath.$fname));
             @fclose($fp);
 
-            $title = api_get_title_html($contents);
+            $title = Text::api_get_title_html($contents);
         }
     }
     if ($title == '') {
@@ -73,8 +73,8 @@ function GetQuizName($fname, $fpath) {
  * Added conditional to the table if is empty.
  */
 function GetComment($path, $course_code = '') {
-    global $dbTable;    
-    $course_info = api_get_course_info($course_code);            
+    global $dbTable;
+    $course_info = api_get_course_info($course_code);
     $path = Database::escape_string($path);
     if (!empty($course_info) && !empty($path)) {
         $query = "SELECT comment FROM $dbTable WHERE c_id = {$course_info['real_id']} AND path='$path'";

+ 2 - 2
main/exercice/hotspot_admin.inc.php

@@ -595,7 +595,7 @@ if ($modifyAnswers) {
                                 foreach ($question_list as $key => $questionid) {
                                     $selected = '';
                                     $question = Question::read($questionid);
-                                    $val = 'Q' . $key . ' :' . substrwords($question->selectTitle(), ICON_SIZE_SMALL);
+                                    $val = 'Q' . $key . ' :' . Text::substrwords($question->selectTitle(), ICON_SIZE_SMALL);
                                     $select_lp_id[$id] = $details['lp_name'];
                                     if ($questionid == $select_question[$i]) {
                                         $selected = 'selected="selected"';
@@ -896,7 +896,7 @@ if ($modifyAnswers) {
                         foreach ($question_list as $key => $questionid) {
                             $selected = '';
                             $question = Question::read($questionid);
-                            $val = 'Q' . $key . ' :' . substrwords($question->selectTitle(), ICON_SIZE_SMALL);
+                            $val = 'Q' . $key . ' :' . Text::substrwords($question->selectTitle(), ICON_SIZE_SMALL);
                             $select_lp_id[$id] = $details['lp_name'];
                             if ($questionid == $select_question_noerror) {
                                 $selected = 'selected="selected"';

+ 1 - 1
main/exercice/matching.class.php

@@ -69,7 +69,7 @@ class Matching extends Question
                         if ($answer->isCorrect($i)) {
                             $nb_matches++;
                             $defaults['answer['.$nb_matches.']']    = $answer->selectAnswer($i);
-                            $defaults['weighting['.$nb_matches.']'] = float_format($answer->selectWeighting($i), 1);
+                            $defaults['weighting['.$nb_matches.']'] = Text::float_format($answer->selectWeighting($i), 1);
                             $defaults['matches['.$nb_matches.']']   = $answer->correct[$i];
                         } else {
                             $nb_options++;

+ 14 - 14
main/exercice/multiple_answer.class.php

@@ -91,7 +91,7 @@ class MultipleAnswer extends Question {
 			if(is_object($answer)) {
 				$defaults['answer['.$i.']'] = $answer -> answer[$i];
 				$defaults['comment['.$i.']'] = $answer -> comment[$i];
-				$defaults['weighting['.$i.']'] = float_format($answer -> weighting[$i], 1);
+				$defaults['weighting['.$i.']'] = Text::float_format($answer -> weighting[$i], 1);
 				$defaults['correct['.$i.']'] = $answer -> correct[$i];
 			} else {
 				$defaults['answer[1]']  = get_lang('DefaultMultipleAnswer2');
@@ -105,12 +105,12 @@ class MultipleAnswer extends Question {
 				$defaults['weighting[2]'] = -5;
 			}
 			$renderer = & $form->defaultRenderer();
-			            
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']');        
+
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']');
 
 			$answer_number=$form->addElement('text', 'counter['.$i.']', null, 'value="'.$i.'"');
 			$answer_number->freeze();
@@ -142,13 +142,13 @@ class MultipleAnswer extends Question {
 			//ie6 fix
 			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
                 $form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');
-                $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');				
+                $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');
                 $form->addElement('submit','submitQuestion',$text, 'class="'.$class.'"');
 			} else {
-                // setting the save button here and not in the question class.php                
+                // setting the save button here and not in the question class.php
                 $form->addElement('style_submit_button', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');
                 $form->addElement('style_submit_button', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');
-                $form->addElement('style_submit_button','submitQuestion',$text, 'class="'.$class.'"');				
+                $form->addElement('style_submit_button','submitQuestion',$text, 'class="'.$class.'"');
 			}
 		}
 		$renderer->setElementTemplate('{element}&nbsp;','lessAnswers');
@@ -205,17 +205,17 @@ class MultipleAnswer extends Question {
         $this->updateWeighting($questionWeighting);
         $this->save();
 	}
-	
+
 	function return_header($feedback_type = null, $counter = null, $score = null, $show_media = false) {
 	    $header = parent::return_header($feedback_type, $counter, $score, $show_media);
-	    $header .= '<table class="'.$this->question_table_class .'">			
+	    $header .= '<table class="'.$this->question_table_class .'">
 			<tr>
 				<th>'.get_lang("Choice").'</th>
 				<th>'. get_lang("ExpectedChoice").'</th>
 				<th>'. get_lang("Answer").'</th>';
-				if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { 
+				if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) {
     				$header .= '<th>'.get_lang("Comment").'</th>';
-				} else { 
+				} else {
 					$header .= '<th>&nbsp;</th>';
 				}
         $header .= '</tr>';

+ 30 - 30
main/exercice/multiple_answer_combination.class.php

@@ -54,9 +54,9 @@ class MultipleAnswerCombination extends Question {
 						</th>
 						<th width="50%">
 							'.get_lang('Answer').'
-						</th>';				
-						// show column comment when feedback is enable						
-						if ($obj_ex->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_EXAM ) {	
+						</th>';
+						// show column comment when feedback is enable
+						if ($obj_ex->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_EXAM ) {
 							$html .='<th>'.get_lang('Comment').'</th>';
 						}
 						$html .= '</tr>';
@@ -74,17 +74,17 @@ class MultipleAnswerCombination extends Question {
 
 		$form -> addElement('hidden', 'nb_answers');
 		$boxes_names = array();
-		
+
 		if ($nb_answers < 1) {
 			$nb_answers = 1;
 			Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
-		}		
+		}
 
 		for($i = 1 ; $i <= $nb_answers ; ++$i) {
 			if(is_object($answer)) {
 				$defaults['answer['.$i.']'] = $answer -> answer[$i];
 				$defaults['comment['.$i.']'] = $answer -> comment[$i];
-				$defaults['weighting['.$i.']'] = float_format($answer -> weighting[$i], 1);
+				$defaults['weighting['.$i.']'] = Text::float_format($answer -> weighting[$i], 1);
 				$defaults['correct['.$i.']'] = $answer -> correct[$i];
 			} else {
 				$defaults['answer[1]']  = get_lang('DefaultMultipleAnswer2');
@@ -94,15 +94,15 @@ class MultipleAnswerCombination extends Question {
 
 				$defaults['answer[2]']  = get_lang('DefaultMultipleAnswer1');
 				$defaults['comment[2]'] = get_lang('DefaultMultipleComment1');
-				$defaults['correct[2]'] = false;				
+				$defaults['correct[2]'] = false;
 			}
 			$renderer = & $form->defaultRenderer();
-			
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');  
-                    
+
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');
+
 
 			$answer_number=$form->addElement('text', 'counter['.$i.']', null,'value="'.$i.'"');
 			$answer_number->freeze();
@@ -112,40 +112,40 @@ class MultipleAnswerCombination extends Question {
 
 			$form->addElement('html_editor', 'answer['.$i.']',null, 'style="vertical-align:middle"', array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '100'));
 			$form->addRule('answer['.$i.']', get_lang('ThisFieldIsRequired'), 'required');
-			
+
 			if ($obj_ex->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_EXAM) {
 				$form->addElement('html_editor', 'comment['.$i.']',null, 'style="vertical-align:middle"', array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '100'));
 			}
-			//only 1 answer the all deal ...			
+			//only 1 answer the all deal ...
 			//$form->addElement('text', 'weighting['.$i.']',null, 'style="vertical-align:middle;margin-left: 0em;" size="5" value="10"');
-				
+
 			$form -> addElement ('html', '</tr>');
 		}
 		$form -> addElement ('html', '</table>');
 		$form -> addElement ('html', '<br />');
 
-		$form -> add_multiple_required_rule ($boxes_names , get_lang('ChooseAtLeastOneCheckbox') , 'multiple_required');		
-						
+		$form -> add_multiple_required_rule ($boxes_names , get_lang('ChooseAtLeastOneCheckbox') , 'multiple_required');
+
 		//only 1 answer the all deal ...
 		$form->addElement('text', 'weighting[1]', get_lang('Score'), array('class' => "span1", 'value' => '10'));
-				
+
 		$navigator_info = api_get_navigator();
 		global $text, $class;
 		//ie6 fix
 		if ($obj_ex->edit_exercise_in_lp == true) {
 			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
-                
+
                 $form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');
                 $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');
-                $form->addElement('submit', 'submitQuestion', $text, 'class="'.$class.'"');				
+                $form->addElement('submit', 'submitQuestion', $text, 'class="'.$class.'"');
 			} else {
-                
+
                 $form->addElement('style_submit_button', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');
                 $form->addElement('style_submit_button', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');
                 $form->addElement('style_submit_button', 'submitQuestion',$text, 'class="'.$class.'"');
-				
+
 				// setting the save button here and not in the question class.php
-				
+
 			}
 		}
 		$renderer->setElementTemplate('{element}&nbsp;','lessAnswers');
@@ -176,7 +176,7 @@ class MultipleAnswerCombination extends Question {
 		$objAnswer = new Answer($this->id);
 
 		$nb_answers = $form -> getSubmitValue('nb_answers');
-		
+
 		for($i=1 ; $i <= $nb_answers ; $i++)
         {
         	$answer = trim($form -> getSubmitValue('answer['.$i.']'));
@@ -208,20 +208,20 @@ class MultipleAnswerCombination extends Question {
         $this -> updateWeighting($questionWeighting);
         $this -> save();
 	}
-	
+
 	function return_header($feedback_type = null, $counter = null, $score = null, $show_media = false) {
 	    $header = parent::return_header($feedback_type, $counter, $score, $show_media);
-	    $header .= '<table class="'.$this->question_table_class .'">			
+	    $header .= '<table class="'.$this->question_table_class .'">
 			<tr>
 				<th>'.get_lang("Choice").'</th>
 				<th>'. get_lang("ExpectedChoice").'</th>
 				<th>'. get_lang("Answer").'</i></th>';
-				if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { 
+				if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) {
     				$header .= '<th>'.get_lang("Comment").'</th>';
-				} else { 
+				} else {
 					$header .= '<th>&nbsp;</th>';
 				}
         $header .= '</tr>';
-        return $header;	  
+        return $header;
 	}
 }

+ 83 - 84
main/exercice/multiple_answer_true_false.class.php

@@ -40,15 +40,15 @@ class MultipleAnswerTrueFalse extends Question {
 
 		$nb_answers  = isset($_POST['nb_answers']) ? $_POST['nb_answers'] : 4;  // The previous default value was 2. See task #1759.
 		$nb_answers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
-        
+
         $course_id = api_get_course_int_id();
 
 		$obj_ex = $_SESSION['objExercise'];
-                
+
         $renderer = & $form->defaultRenderer();
-               
+
         $defaults = array();
-               
+
 		$html = '<table class="data_table">
 					<tr style="text-align: center;">
 						<th>
@@ -59,7 +59,7 @@ class MultipleAnswerTrueFalse extends Question {
 						</th>
                         <th>
                             '.get_lang('False').'
-                        </th>     
+                        </th>
 						<th>
 							'.get_lang('Answer').'
 						</th>';
@@ -69,16 +69,16 @@ class MultipleAnswerTrueFalse extends Question {
         }
         $html .= '</tr>';
         $form -> addElement ('label', get_lang('Answers').'<br /> <img src="../img/fill_field.png">', $html);
-		
+
 		$correct = 0;
 		if (!empty($this -> id)) {
 			$answer = new Answer($this -> id);
-			$answer->read();			
+			$answer->read();
 			if (count($answer->nbrAnswers) > 0 && !$form->isSubmitted()) {
 				$nb_answers = $answer->nbrAnswers;
 			}
 		}
-		
+
 		$form -> addElement('hidden', 'nb_answers');
 		$boxes_names = array();
 
@@ -86,51 +86,50 @@ class MultipleAnswerTrueFalse extends Question {
 			$nb_answers = 1;
 			Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
 		}
-		
-        // Can be more options        
+
+        // Can be more options
         $option_data = Question::readQuestionOption($this->id, $course_id);
-          
+
 		for ($i = 1 ; $i <= $nb_answers ; ++$i) {
-            
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']'); 
-            
+
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');
+
             $answer_number=$form->addElement('text', 'counter['.$i.']',null,'value="'.$i.'"');
-            $answer_number->freeze();            
-            
-			if (is_object($answer)) {               
+            $answer_number->freeze();
+
+			if (is_object($answer)) {
 				$defaults['answer['.$i.']']     = $answer -> answer[$i];
 				$defaults['comment['.$i.']']    = $answer -> comment[$i];
-				//$defaults['weighting['.$i.']']  = float_format($answer -> weighting[$i], 1);
-      
+				      
                 $correct = $answer->correct[$i];
-                                
-                $defaults['correct['.$i.']']    = $correct;          
-			
-                $j = 1;             
+
+                $defaults['correct['.$i.']']    = $correct;
+
+                $j = 1;
                 if (!empty($option_data)) {
-                    foreach ($option_data as $id=>$data) {                 
+                    foreach ($option_data as $id=>$data) {
                         $form->addElement('radio', 'correct['.$i.']', null, null, $id);
                         $j++;
                         if ($j == 3) {
                         	break;
                         }
-                       
-                    }            
+
+                    }
                 }
-			} else {                
-                $form->addElement('radio', 'correct['.$i.']', null, null, 1);            
+			} else {
+                $form->addElement('radio', 'correct['.$i.']', null, null, 1);
                 $form->addElement('radio', 'correct['.$i.']', null, null, 2);
-            
+
                 $defaults['answer['.$i.']']     = '';
                 $defaults['comment['.$i.']']    = '';
-                $defaults['correct['.$i.']']    = '';                
-			}          
-            
+                $defaults['correct['.$i.']']    = '';
+			}
+
             //$form->addElement('select', 'correct['.$i.']',null, $this->options, array('id'=>$i,'onchange'=>'multiple_answer_true_false_onchange(this)'));
-            
+
 			$boxes_names[] = 'correct['.$i.']';
 
 			$form->addElement('html_editor', 'answer['.$i.']',null, 'style="vertical-align:middle"', array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '100'));
@@ -142,38 +141,38 @@ class MultipleAnswerTrueFalse extends Question {
 			}
 			$form->addElement ('html', '</tr>');
 		}
-        
+
 		$form->addElement('html', '</table>');
-		$form->addElement('html', '<br />');  
-        
+		$form->addElement('html', '<br />');
+
         $form->addElement('html', '<table><tr><td></td><td>'.get_lang('Correct').'</td><td>'.get_lang('Wrong').'</td><td>'.get_lang('DoubtScore').'</td></tr>');
-               
+
         $renderer->setElementTemplate('<tr><td><span class="form_required">*</span>'.get_lang('Score').'&nbsp;&nbsp;&nbsp;&nbsp;</td><td>{element} &nbsp;&nbsp; <br /><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --></td>', 'option[1]');
         $renderer->setElementTemplate('<td>{element} &nbsp;&nbsp;<br /><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --></td>', 'option[2]');
         $renderer->setElementTemplate('<td>{element} &nbsp;&nbsp;<br /><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --></td>', 'option[3]');
 
         // 3 scores
         $form->addElement('text', 'option[1]', get_lang('Correct'),   array('class'=>'span1','value'=>'1'));
-        $form->addElement('text', 'option[2]', get_lang('Wrong'),     array('class'=>'span1','value'=>'-0.5'));        
+        $form->addElement('text', 'option[2]', get_lang('Wrong'),     array('class'=>'span1','value'=>'-0.5'));
         $form->addElement('text', 'option[3]', get_lang('DoubtScore'),array('class'=>'span1','value'=>'0'));
-        
+
         $form->addRule('option[1]', get_lang('ThisFieldIsRequired'), 'required');
         $form->addRule('option[2]', get_lang('ThisFieldIsRequired'), 'required');
-        $form->addRule('option[3]', get_lang('ThisFieldIsRequired'), 'required');                
-        
+        $form->addRule('option[3]', get_lang('ThisFieldIsRequired'), 'required');
+
         $form -> addElement ('html', '</tr><table>');
-        $form -> addElement('hidden', 'options_count', 3);                    
-        $form -> addElement ('html', '</table><br /><br />');        
-        
+        $form -> addElement('hidden', 'options_count', 3);
+        $form -> addElement ('html', '</table><br /><br />');
+
         //Extra values True, false,  Dont known
         if (!empty($this->extra)) {
-            $scores = explode(':',$this->extra);        
+            $scores = explode(':',$this->extra);
             if (!empty($scores)) {
                 for ($i = 1; $i <=3; $i++) {
-                    $defaults['option['.$i.']']	= $scores[$i-1];                
-                }        
-            }        
-        }        
+                    $defaults['option['.$i.']']	= $scores[$i-1];
+                }
+            }
+        }
 
 		//$form -> add_multiple_required_rule ($boxes_names , get_lang('ChooseAtLeastOneCheckbox') , 'multiple_required');
 
@@ -183,16 +182,16 @@ class MultipleAnswerTrueFalse extends Question {
 		if ($obj_ex->edit_exercise_in_lp == true) {
 			//ie6 fix
 			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
-                
+
                 $form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');
-                $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');				
+                $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');
                 $form->addElement('submit', 'submitQuestion',$text, 'class="'.$class.'"');
 			} else {
                 // setting the save button here and not in the question class.php
-                
+
                 $form->addElement('style_submit_button', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');
                 $form->addElement('style_submit_button', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');
-                $form->addElement('style_submit_button', 'submitQuestion',$text, 'class="'.$class.'"');	
+                $form->addElement('style_submit_button', 'submitQuestion',$text, 'class="'.$class.'"');
 			}
 		}
 		$renderer->setElementTemplate('{element}&nbsp;','lessAnswers');
@@ -223,75 +222,75 @@ class MultipleAnswerTrueFalse extends Question {
 		$nb_answers       = $form->getSubmitValue('nb_answers');
         $options_count    = $form->getSubmitValue('options_count');
         $course_id        = api_get_course_int_id();
-       
+
         $correct = array();
         $options = Question::readQuestionOption($this->id, $course_id);
-        	
-        
+
+
         if (!empty($options)) {
             foreach ($options as $option_data) {
                 $id = $option_data['id'];
                 unset($option_data['id']);
                 Question::updateQuestionOption($id, $option_data, $course_id);
             }
-        } else {            
-            for ($i=1 ; $i <= 3 ; $i++) {                
+        } else {
+            for ($i=1 ; $i <= 3 ; $i++) {
         	   $last_id = Question::saveQuestionOption($this->id, $this->options[$i], $course_id, $i);
                $correct[$i] = $last_id;
-            }            
+            }
         }
-  
+
         //Getting quiz_question_options (true, false, doubt) because it's possible that there are more options in the future
         $new_options = Question::readQuestionOption($this->id, $course_id);
-        
+
         $sorted_by_position = array();
         foreach($new_options as $item) {
         	$sorted_by_position[$item['position']] = $item;
-        }        
-        
-        //Saving quiz_question.extra values that has the correct scores of the true, false, doubt options registered in this format XX:YY:ZZZ where XX is a float score value 
+        }
+
+        //Saving quiz_question.extra values that has the correct scores of the true, false, doubt options registered in this format XX:YY:ZZZ where XX is a float score value
         $extra_values = array();
         for ($i=1 ; $i <= 3 ; $i++) {
             $score = trim($form -> getSubmitValue('option['.$i.']'));
             $extra_values[]= $score;
-        }        
-        $this->setExtra(implode(':',$extra_values));       
-          
+        }
+        $this->setExtra(implode(':',$extra_values));
+
 		for ($i=1 ; $i <= $nb_answers ; $i++) {
         	$answer     = trim($form -> getSubmitValue('answer['.$i.']'));
             $comment    = trim($form -> getSubmitValue('comment['.$i.']'));
-            $goodAnswer = trim($form -> getSubmitValue('correct['.$i.']'));  
+            $goodAnswer = trim($form -> getSubmitValue('correct['.$i.']'));
             if (empty($options)) {
-                //If this is the first time that the question is created when change the default values from the form 1 and 2 by the correct "option id" registered 
+                //If this is the first time that the question is created when change the default values from the form 1 and 2 by the correct "option id" registered
                 $goodAnswer = $sorted_by_position[$goodAnswer]['id'];
-            }         
+            }
     	    $questionWeighting += $extra_values[0]; //By default 0 has the correct answers
-        	$objAnswer->createAnswer($answer, $goodAnswer, $comment,'',$i);            
-        }        
-    
+        	$objAnswer->createAnswer($answer, $goodAnswer, $comment,'',$i);
+        }
+
 
     	// saves the answers into the data base
         $objAnswer -> save();
-    
+
         // sets the total weighting of the question
         $this -> updateWeighting($questionWeighting);
         $this -> save();
 	}
-	
-	function return_header($feedback_type = null, $counter = null, $score = null, $show_media = false) {	    	    
-        $header = parent::return_header($feedback_type, $counter, $score, $show_media);        
-  	    $header .= '<table class="'.$this->question_table_class .'">		
+
+	function return_header($feedback_type = null, $counter = null, $score = null, $show_media = false) {
+        $header = parent::return_header($feedback_type, $counter, $score, $show_media);
+  	    $header .= '<table class="'.$this->question_table_class .'">
 		<tr>
 			<th>'.get_lang("Choice").'</th>
 			<th>'. get_lang("ExpectedChoice").'</th>
 			<th>'. get_lang("Answer").'</th>';
-			if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { 
+			if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) {
 				$header .= '<th>'.get_lang("Comment").'</th>';
-			} else { 
+			} else {
 				$header .= '<th>&nbsp;</th>';
 			}
         $header .= '</tr>';
-        return $header;	  
+        return $header;
 	}
 }
 endif;

+ 5 - 5
main/exercice/oral_expression.class.php

@@ -39,7 +39,7 @@ class OralExpression extends Question {
 		// setting the save button here and not in the question class.php
 		$form->addElement('style_submit_button','submitQuestion',$text, 'class="'.$class.'"');
 		if (!empty($this->id)) {
-			$form -> setDefaults(array('weighting' => float_format($this->weighting, 1)));
+			$form -> setDefaults(array('weighting' => Text::float_format($this->weighting, 1)));
 		} else {
 			if ($this -> isContent == 1) {
 				$form -> setDefaults(array('weighting' => '10'));
@@ -55,7 +55,7 @@ class OralExpression extends Question {
 		$this->weighting = $form -> getSubmitValue('weighting');
 		$this->save();
 	}
-	
+
 	function return_header($feedback_type = null, $counter = null, $score = null, $show_media = false) {
 	    $header = parent::return_header($feedback_type, $counter, $score, $show_media);
 	    $header .= '<table class="'.$this->question_table_class.'">
@@ -67,8 +67,8 @@ class OralExpression extends Question {
 			</tr>
 			<tr>
                 <th>&nbsp;</th>
-			</tr>';				
-        return $header;	  
-	}	
+			</tr>';
+        return $header;
+	}
 }
 endif;

+ 1 - 1
main/exercice/question.class.php

@@ -215,7 +215,7 @@ abstract class Question
      */
     function selectDescription()
     {
-        $this->description = text_filter($this->description);
+        $this->description = $this->description;
 
         return $this->description;
     }

+ 11 - 11
main/exercice/question_create.php

@@ -36,7 +36,7 @@ $form->addElement('header','',get_lang('AddQuestionToExercise'));
 
 $question_list = Question::get_question_type_list();
 $question_list_options = array();
-foreach ($question_list as $key=> $value) {    
+foreach ($question_list as $key=> $value) {
     $question_list_options[$key] = addslashes(get_lang($value[1]));
 }
 $form->addElement('select', 'question_type_hidden', get_lang('QuestionType'), $question_list_options, array('id' => 'question_type_hidden'));
@@ -52,7 +52,7 @@ $sql = "SELECT id,title,type,description, results_disabled FROM $tbl_exercices W
 $result = Database::query($sql);
 $exercises['-'] = '-'.get_lang('SelectExercice').'-';
 while ($row = Database :: fetch_array($result)) {
-	$exercises[$row['id']] = cut($row['title'], EXERCISE_MAX_NAME_SIZE);
+	$exercises[$row['id']] = Text::cut($row['title'], EXERCISE_MAX_NAME_SIZE);
 }
 $form->addElement('select', 'exercice', get_lang('Exercice'), $exercises);
 
@@ -72,26 +72,26 @@ $form->addRule('question_type_hidden', get_lang('InvalidQuestionType'), 'validqu
 if ($form->validate()) {
 	$values = $form->exportValues();
     $answer_type = $values['question_type_hidden'];
-    
+
 	// check feedback_type from current exercise for type of question delineation
-	$exercise_id = intval($values['exercice']);	
+	$exercise_id = intval($values['exercice']);
 	$sql = "SELECT feedback_type FROM $tbl_exercices WHERE c_id = $course_id AND id = '$exercise_id'";
 	$rs_feedback_type = Database::query($sql);
 	$row_feedback_type = Database::fetch_row($rs_feedback_type);
 	$feedback_type = $row_feedback_type[0];
-	
+
 	// if question type does not belong to self-evaluation (immediate feedback) it'll send an error
-	if (($answer_type == HOT_SPOT_DELINEATION && $feedback_type != 1) || 
+	if (($answer_type == HOT_SPOT_DELINEATION && $feedback_type != 1) ||
 		($feedback_type == 1 && ($answer_type != HOT_SPOT_DELINEATION && $answer_type != UNIQUE_ANSWER))) {
 		header('Location: question_create.php?'.api_get_cidreq().'&error=true');
-		exit;		
-	}	
+		exit;
+	}
 	header('Location: admin.php?exerciseId='.$values['exercice'].'&newQuestion=yes&isContent='.$values['is_content'].'&answerType='.$answer_type);
 	exit;
 } else {
 	// header
 	Display::display_header($nameTools);
-	
+
 	echo '<div class="actions">';
 	echo '<a href="exercice.php?show=test">'.Display :: return_icon('back.png', get_lang('BackToExercisesList'),'',ICON_SIZE_MEDIUM).'</a>';
 	echo '</div>';
@@ -104,10 +104,10 @@ if ($form->validate()) {
 }
 
 function check_question_type($parameter) {
-    $question_list = Question::get_question_type_list();    
+    $question_list = Question::get_question_type_list();
 	foreach ($question_list as $key => $value) {
 		$valid_question_types[] = $key;
-	}    
+	}
 	if (in_array($parameter, $valid_question_types)) {
 		return true;
 	} else {

+ 7 - 7
main/exercice/question_list_admin.inc.php

@@ -165,9 +165,9 @@ if (!$inATest) {
         $styleCat = "width:22%; float:left; padding-top:8px; text-align:center;";
         $styleLevel = "width:6%; float:left; padding-top:8px; text-align:center;";
         $styleScore = "width:4%; float:left; padding-top:8px; text-align:center;";
-        
+
         $category_list = Testcategory::getCategoryListName();
-        
+
         if (is_array($questionList)) {
 			foreach ($questionList as $id) {
 				//To avoid warning messages
@@ -191,17 +191,17 @@ if (!$inATest) {
                 $move = Display::return_icon('all_directions.png',get_lang('Move'), array('class'=>'moved', 'style'=>'margin-bottom:-0.5em;'));
 
                 // Question name
-				$questionName = Display::tag('div', '<a href="#" title = "'.$title.'">'.$move.' '.cut($title, 42).'</a>', array('style'=>$styleQuestion));
+				$questionName = Display::tag('div', '<a href="#" title = "'.$title.'">'.$move.' '.Text::cut($title, 42).'</a>', array('style'=>$styleQuestion));
 
 				// Question type
 				list($typeImg, $typeExpl) = $objQuestionTmp->get_type_icon_html();
-                
+
                 $question_media = null;
                 if (!empty($objQuestionTmp->parent_id)) {
                     $objQuestionMedia = Question::read($objQuestionTmp->parent_id);
                     $question_media  = Display::label($objQuestionMedia->question, 'info');
                 }
-                
+
 				$questionType = Display::tag('div', Display::return_icon($typeImg, $typeExpl, array(), ICON_SIZE_MEDIUM).$question_media, array('style' => $styleType));
 
 				// Question category
@@ -226,7 +226,7 @@ if (!$inATest) {
                     echo '<div class="header_operations">';
                         echo $questionName;
                         echo $questionType;
-                        
+
                         echo $questionCategory;
                         echo $questionLevel;
                         echo $questionScore;
@@ -247,7 +247,7 @@ if (!$inATest) {
 			}
 		}
 	}
-    
+
 	if (!$nbrQuestions) {
 	  	echo Display::display_warning_message(get_lang('NoQuestion'));
 	}

+ 34 - 34
main/exercice/stats.php

@@ -45,19 +45,19 @@ $headers = array(
 if (!empty($question_list)) {
 	foreach ($question_list as $question_id) {
 		$question_obj   = Question::read($question_id);
-		$exercise_stats = get_student_stats_by_question($question_id, $exercise_id, api_get_course_id(), api_get_session_id());        
+		$exercise_stats = get_student_stats_by_question($question_id, $exercise_id, api_get_course_id(), api_get_session_id());
         $count_users    = get_number_students_question_with_answer_count($question_id, $exercise_id, api_get_course_id(), api_get_session_id());
 
-		$data[$question_id]['name'] 						= cut($question_obj->question, 100);
+		$data[$question_id]['name'] 						= Text::cut($question_obj->question, 100);
         $data[$question_id]['type'] 						= $question_obj->get_question_type_name();
 		//$data[$question_id]['students_who_try_exercise'] 	= $exercise_stats['users'];
         $percentange = 0;
         if ($count_students) {
             $percentange = $count_users/$count_students*100;
         }
-        
+
         $data[$question_id]['students_who_try_exercise'] 	= Display::bar_progress($percentange, false, $count_users .' / '.$count_students);
-                
+
 		$data[$question_id]['lowest_score'] 				= round($exercise_stats['min'], 2);
 		$data[$question_id]['average_score'] 				= round($exercise_stats['average'], 2);
 		$data[$question_id]['highest_score'] 				= round($exercise_stats['max'], 2);
@@ -92,7 +92,7 @@ $headers = array(
 	get_lang('Question'),
 	get_lang('Answer'),
 	get_lang('Correct'),
-	get_lang('NumberStudentWhoSelectedIt')	
+	get_lang('NumberStudentWhoSelectedIt')
 );
 
 $data = array();
@@ -105,58 +105,58 @@ if (!empty($question_list)) {
 
         $answer = new Answer($question_id);
 		$answer_count = $answer->selectNbrAnswers();
-        
+
         for ($answer_id = 1; $answer_id <= $answer_count; $answer_id++) {
             $answer_info    = $answer->selectAnswer($answer_id);
             $is_correct     = $answer->isCorrect($answer_id);
             $correct_answer = $is_correct == 1 ? get_lang('Yes') : get_lang('No');
             $real_answer_id = $answer->selectAutoId($answer_id);
-            
+
             //$data[$id]['name'] .=$answer_count;
             //Overwriting values depending of the question
             switch ($question_obj->type) {
                 case FILL_IN_BLANKS :
                     $answer_info_db = $answer_info;
                     $answer_info = substr($answer_info, 0, strpos($answer_info, '::'));
-                    $correct_answer = $is_correct;                
+                    $correct_answer = $is_correct;
                     $answers = $objExercise->fill_in_blank_answer_to_array($answer_info);
                     $counter = 0;
                     foreach ($answers as $answer_item) {
                         if ($counter == 0) {
-                            $data[$id]['name']      = cut($question_obj->question, 100);
+                            $data[$id]['name']      = Text::cut($question_obj->question, 100);
                         } else {
                             $data[$id]['name']      = '-';
                         }
-                        $data[$id]['answer'] 	= $answer_item; 
-                        
+                        $data[$id]['answer'] 	= $answer_item;
+
                         $answer_item = api_substr($answer_item, 1);
                         $answer_item = api_substr($answer_item, 0, api_strlen($answer_item) -1);
-                                                                      
+
                         $data[$id]['correct'] 	= '-';
-                        
+
                         $count = get_number_students_answer_count($real_answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id(), FILL_IN_BLANKS, $answer_info_db, $answer_item);
-                        
+
                         $percentange = 0;
                         if (!empty($count_students)) {
                             $percentange = $count/$count_students*100;
                         }
                         $data[$id]['attempts'] 	= Display::bar_progress($percentange, false, $count .' / '.$count_students);
-                    
+
                         $id++;
-                        $counter++;                        
+                        $counter++;
                     }
                     break;
                 case MATCHING:
-                    if ($is_correct == 0) {                
-                        if ($answer_id == 1) {                
-                            $data[$id]['name']      = cut($question_obj->question, 100);
+                    if ($is_correct == 0) {
+                        if ($answer_id == 1) {
+                            $data[$id]['name']      = Text::cut($question_obj->question, 100);
                         } else {
                             $data[$id]['name']      = '-';
-                        }                        
+                        }
                         $correct = '';
-                        
+
                         for ($i = 1; $i <= $answer_count; $i++) {
-                             $is_correct_i = $answer->isCorrect($i);                             
+                             $is_correct_i = $answer->isCorrect($i);
                              if ($is_correct_i != 0 && $is_correct_i == $answer_id) {
                                  $correct = $answer->selectAnswer($i);
                                  break;
@@ -164,50 +164,50 @@ if (!empty($question_list)) {
                         }
                         $data[$id]['answer'] 	= $correct;
                         $data[$id]['correct'] 	= $answer_info;
-                        
+
                         $count = get_number_students_answer_count($answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id(), MATCHING);
                         $percentange = 0;
                         if (!empty($count_students)) {
                             $percentange = $count/$count_students*100;
                         }
                         $data[$id]['attempts'] 	= Display::bar_progress($percentange, false, $count .' / '.$count_students);
-                    }                    
+                    }
                     break;
                 case HOT_SPOT:
-                    if ($answer_id == 1) {                
-                        $data[$id]['name']      = cut($question_obj->question, 100);
+                    if ($answer_id == 1) {
+                        $data[$id]['name']      = Text::cut($question_obj->question, 100);
                     } else {
                         $data[$id]['name']      = '-';
                     }
                     $data[$id]['answer'] 	= $answer_info;
                     $data[$id]['correct'] 	= '-';
-                    
-                    $count = get_number_students_answer_hotspot_count($answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id());                    
+
+                    $count = get_number_students_answer_hotspot_count($answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id());
                     $percentange = 0;
                     if (!empty($count_students)) {
                         $percentange = $count/$count_students*100;
                     }
-                    $data[$id]['attempts'] 	= Display::bar_progress($percentange, false, $count .' / '.$count_students);                    
+                    $data[$id]['attempts'] 	= Display::bar_progress($percentange, false, $count .' / '.$count_students);
                     break;
                 default:
-                    if ($answer_id == 1) {                
-                        $data[$id]['name']      = cut($question_obj->question, 100);
+                    if ($answer_id == 1) {
+                        $data[$id]['name']      = Text::cut($question_obj->question, 100);
                     } else {
                         $data[$id]['name']      = '-';
                     }
                     $data[$id]['answer'] 	= $answer_info;
                     $data[$id]['correct'] 	= $correct_answer;
-                    
+
                     $count = get_number_students_answer_count($real_answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id());
                     $percentange = 0;
                     if (!empty($count_students)) {
                         $percentange = $count/$count_students*100;
                     }
                     $data[$id]['attempts'] 	= Display::bar_progress($percentange, false, $count .' / '.$count_students);
-            }            
+            }
             $id++;
         }
-        
+
 	}
 }
 

+ 1 - 1
main/exercice/testcategory.class.php

@@ -494,7 +494,7 @@ class Testcategory {
             if (!isset($all_categories[$category_id])) {
                 $category_name = get_lang('Untitled');
             } else {
-                $category_name = cut($all_categories[$category_id], 15);
+                $category_name = Text::cut($all_categories[$category_id], 15);
             }
             $category_list_to_render[] = $category_name;
         }

+ 48 - 48
main/exercice/unique_answer.class.php

@@ -64,7 +64,7 @@ class UniqueAnswer extends Question {
 		$comment_title='';
 
 		if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_END) {
-			$comment_title = '<th>'.get_lang('Comment').'</th>';            
+			$comment_title = '<th>'.get_lang('Comment').'</th>';
 		} elseif ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
             //Scenario
 			$editor_config['Width'] = '250';
@@ -88,11 +88,11 @@ class UniqueAnswer extends Question {
                         '.$feedback_title.'
                     <th width="50px">
                         '.get_lang('Weighting').'
-                    </th>        
+                    </th>
                 </tr>';
 
         $form -> addElement ('label', get_lang('Answers').'<br /> <img src="../img/fill_field.png">', $html);
-		
+
 		$defaults = array();
 		$correct = 0;
 		if(!empty($this -> id)) {
@@ -109,7 +109,7 @@ class UniqueAnswer extends Question {
 		$select_question=array();
 		$select_question[0] = get_lang('SelectTargetQuestion');
 
-		require_once '../newscorm/learnpathList.class.php';        
+		require_once '../newscorm/learnpathList.class.php';
 		if (is_array($question_list)) {
 			foreach ($question_list as $key=>$questionid) {
 				//To avoid warning messages
@@ -117,9 +117,9 @@ class UniqueAnswer extends Question {
 					continue;
 				}
 				$question = Question::read($questionid);
-                
+
                 if($question) {
-                    $select_question[$questionid]='Q'.$key.' :'.cut($question->selectTitle(),20);
+                    $select_question[$questionid]='Q'.$key.' :'.Text::cut($question->selectTitle(),20);
                 }
 			}
 		}
@@ -131,25 +131,25 @@ class UniqueAnswer extends Question {
 		$select_lp_id[0]=get_lang('SelectTargetLP');
 
 		foreach ($flat_list as $id => $details) {
-			$select_lp_id[$id] = cut($details['lp_name'],20);
+			$select_lp_id[$id] = Text::cut($details['lp_name'],20);
 		}
 
 		$temp_scenario = array();
-        
+
         if ($nb_answers < 1) {
             $nb_answers = 1;
             Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
-        }                        
+        }
 
         for ($i = 1 ; $i <= $nb_answers ; ++$i) {
-            $form -> addElement ('html', '<tr>');                
+            $form -> addElement ('html', '<tr>');
             if (isset($answer) && is_object($answer)) {
                 if ($answer -> correct[$i]) {
                     $correct = $i;
                 }
                 $defaults['answer['.$i.']']    = $answer->answer[$i];
                 $defaults['comment['.$i.']']   = $answer->comment[$i];
-                $defaults['weighting['.$i.']'] = float_format($answer->weighting[$i], 1);
+                $defaults['weighting['.$i.']'] = Text::float_format($answer->weighting[$i], 1);
 
                 $item_list=explode('@@',$answer -> destination[$i]);
 
@@ -185,67 +185,67 @@ class UniqueAnswer extends Question {
             $defaults['scenario'] = $temp_scenario;
 
             $renderer = $form->defaultRenderer();
-            
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');  
+
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');
             $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']');        
-            
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']');
+
             $answer_number = $form->addElement('text', 'counter['.$i.']',null,' value = "'.$i.'"');
             $answer_number->freeze();
 
             $form->addElement('radio', 'correct', null, null, $i, 'class="checkbox" style="margin-left: 0em;"');
             $form->addElement('html_editor', 'answer['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
-            
+
             $form->addRule('answer['.$i.']', get_lang('ThisFieldIsRequired'), 'required');
 
             if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_END) {
                 // feedback
                 $form->addElement('html_editor', 'comment['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
-            } elseif ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {                
+            } elseif ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
                 $form->addElement('html_editor', 'comment['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
                 // Direct feedback
-          
+
                 //Adding extra feedback fields
                 $group = array();
                 $group['try'.$i] = $form->createElement('checkbox', 'try'.$i, null , get_lang('TryAgain'));
                 $group['lp'.$i]  = $form->createElement('select', 'lp'.$i, get_lang('SeeTheory').': ', $select_lp_id);
                 $group['destination'.$i]= $form->createElement('select', 'destination'.$i, get_lang('GoToQuestion').': ' , $select_question);
                 $group['url'.$i] = $form->createElement('text', 'url'.$i, get_lang('Other').': ', array('class'=>'span2', 'placeholder' => get_lang('Other')));
-                $form->addGroup($group, 'scenario');                
-                
-                $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}', 'scenario');            
-                
+                $form->addGroup($group, 'scenario');
+
+                $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}', 'scenario');
+
             }
-            $form->addElement('text', 'weighting['.$i.']', null, array('class' => "span1", 'value' => '0'));                    
-            $form->addElement ('html', '</tr>');                
+            $form->addElement('text', 'weighting['.$i.']', null, array('class' => "span1", 'value' => '0'));
+            $form->addElement ('html', '</tr>');
         }
 
 		$form -> addElement ('html', '</table>');
-		$form -> addElement ('html', '<br />');        
-        
+		$form -> addElement ('html', '<br />');
+
 		$navigator_info = api_get_navigator();
 
 		global $text, $class;
-        
+
 		//ie6 fix
 		if ($obj_ex->edit_exercise_in_lp == true) {
-			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {                
+			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
                 $form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');
-                $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"'); 
+                $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');
                 $form->addElement('submit','submitQuestion',$text, 'class="'.$class.'"');
 			} else {
-                //setting the save button here and not in the question class.php                
+                //setting the save button here and not in the question class.php
                 $form->addElement('style_submit_button', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');
-                $form->addElement('style_submit_button', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');                
-                $form->addElement('style_submit_button', 'submitQuestion',$text, 'class="'.$class.'"');				
+                $form->addElement('style_submit_button', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');
+                $form->addElement('style_submit_button', 'submitQuestion',$text, 'class="'.$class.'"');
 			}
 		}
 		$renderer->setElementTemplate('{element}&nbsp;','submitQuestion');
 		$renderer->setElementTemplate('{element}&nbsp;','lessAnswers');
 		$renderer->setElementTemplate('{element}&nbsp;','moreAnswers');
-        
+
         $form->addElement('html', '</div></div>');
 
 		//We check the first radio button to be sure a radio button will be check
@@ -283,11 +283,11 @@ class UniqueAnswer extends Question {
             $weighting = trim($form -> getSubmitValue('weighting['.$i.']'));
 
             $scenario = $form -> getSubmitValue('scenario');
-            
+
            	//$list_destination = $form -> getSubmitValue('destination'.$i);
            	//$destination_str = $form -> getSubmitValue('destination'.$i);
 
- 		    $try = $scenario['try'.$i];            
+ 		    $try = $scenario['try'.$i];
             $lp = $scenario['lp'.$i];
  			$destination = $scenario['destination'.$i];
  			$url = trim($scenario['url'.$i]);
@@ -304,7 +304,7 @@ class UniqueAnswer extends Question {
 			lp_id = id of a learning path (0 if dont select)
 			selected_questions= ids of questions
 			url= an url
-	
+
  			$destination_str='';
  			foreach ($list_destination as $destination_id)
  			{
@@ -332,16 +332,16 @@ class UniqueAnswer extends Question {
  			if (empty($destination)) {
  				$destination=0;
  			}
-            
+
  			if ($url=='') {
  				$url=0;
  			}
 
  			//1@@1;2;@@2;4;4;@@http://www.chamilo.org
-			$dest = $try.'@@'.$lp.'@@'.$destination.'@@'.$url;            
+			$dest = $try.'@@'.$lp.'@@'.$destination.'@@'.$url;
         	$objAnswer->createAnswer($answer, $goodAnswer, $comment, $weighting, $i, null, null, $dest);
         }
-        
+
     	// saves the answers into the data base
         $objAnswer->save();
 
@@ -349,21 +349,21 @@ class UniqueAnswer extends Question {
         $this->updateWeighting($questionWeighting);
         $this->save();
 	}
-	
+
 	function return_header($feedback_type = null, $counter = null, $score = null, $show_media = false) {
 	    $header = parent::return_header($feedback_type, $counter, $score, $show_media);
-	    $header .= '<table class="'.$this->question_table_class .'">			
+	    $header .= '<table class="'.$this->question_table_class .'">
 			<tr>
 				<th>'.get_lang("Choice").'</th>
 				<th>'. get_lang("ExpectedChoice").'</th>
-				<th>'. get_lang("Answer").'</th>';        
-				if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { 
+				<th>'. get_lang("Answer").'</th>';
+				if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) {
     				$header .= '<th>'.get_lang("Comment").'</th>';
-				} else { 
+				} else {
 					$header .= '<th>&nbsp;</th>';
 				}
         $header .= '</tr>';
-        return $header;	
+        return $header;
     }
   /**
    * Create database record for the given answer
@@ -377,7 +377,7 @@ class UniqueAnswer extends Question {
    * @return void
    * @assert (1,null,'a','',1,1,null) === false
    * @assert (1,1,'','',1,1,null) === false
-   */  
+   */
   function create_answer($id=1, $question_id, $answer_title, $comment = '', $score = 0, $correct = 0, $course_id = null) {
     if (empty($question_id) or empty($answer_title)) { return false; }
     $tbl_quiz_answer = Database::get_course_table(TABLE_QUIZ_ANSWER);

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

@@ -112,7 +112,7 @@ class UniqueAnswerImage extends UniqueAnswer
                 $question = Question::read($questionid);
 
                 if ($question) {
-                    $select_question[$questionid] = 'Q'.$key.' :'.cut($question->selectTitle(), 20);
+                    $select_question[$questionid] = 'Q'.$key.' :'.Text::cut($question->selectTitle(), 20);
                 }
             }
         }
@@ -124,7 +124,7 @@ class UniqueAnswerImage extends UniqueAnswer
         $select_lp_id[0] = get_lang('SelectTargetLP');
 
         foreach ($flat_list as $id => $details) {
-            $select_lp_id[$id] = cut($details['lp_name'], 20);
+            $select_lp_id[$id] = Text::cut($details['lp_name'], 20);
         }
 
         $temp_scenario = array();
@@ -142,7 +142,7 @@ class UniqueAnswerImage extends UniqueAnswer
                 }
                 $defaults['answer['.$i.']']    = $answer->answer[$i];
                 $defaults['comment['.$i.']']   = $answer->comment[$i];
-                $defaults['weighting['.$i.']'] = float_format($answer->weighting[$i], 1);
+                $defaults['weighting['.$i.']'] = Text::float_format($answer->weighting[$i], 1);
 
                 $item_list = explode('@@', $answer->destination[$i]);
 

+ 81 - 81
main/exercice/unique_answer_no_option.class.php

@@ -52,7 +52,7 @@ class UniqueAnswerNoOption extends Question {
 
 		//this line define how many question by default appear when creating a choice question
 		$nb_answers  = isset($_POST['nb_answers']) ? (int) $_POST['nb_answers'] : 3;  // The previous default value was 2. See task #1759.
-		$nb_answers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0)); 
+		$nb_answers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
 
 		/*
 	 		Types of Feedback
@@ -88,32 +88,32 @@ class UniqueAnswerNoOption extends Question {
 							'.$feedback_title.'
 						<th width="60px">
 							'.get_lang('Weighting').'
-						</th>        
+						</th>
 					</tr>';
         $form -> addElement ('label', get_lang('Answers').'<br /> <img src="../img/fill_field.png">', $html);
 
 		$defaults = array();
 		$correct = 0;
-		
+
 		if (!empty($this -> id)) {
 			$answer = new Answer($this -> id);
 			$answer -> read();
 			if (count($answer->nbrAnswers)>0 && !$form->isSubmitted()) {
-				$nb_answers = $answer->nbrAnswers;				
+				$nb_answers = $answer->nbrAnswers;
 			}
 		}
 
 		$temp_scenario = array();
-	    	    
+
 		if ($nb_answers < 1) {
 			$nb_answers = 1;
 			Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
-		}				
+		}
         if ($_GET['editQuestion']) {
-            
+
             //fixing $nb_answers
             $new_list = array();
-            $count = 1;            
+            $count = 1;
             if (isset($_POST['lessAnswers'])) {
                 if (!isset($_SESSION['less_answer'])) {
                     $_SESSION['less_answer'] = $this -> id;
@@ -121,111 +121,111 @@ class UniqueAnswerNoOption extends Question {
                 }
             }
             for ($k = 1 ; $k <= $nb_answers; ++$k) {
-                if ($answer->position[$k] != '666') {                    
+                if ($answer->position[$k] != '666') {
                     $new_list[$count] = $count;
                     $count++;
                 }
-            }          
+            }
         } else {
-            for ($k = 1 ; $k <= $nb_answers; ++$k) {                                
-                $new_list[$k] = $k;                
-            }            
+            for ($k = 1 ; $k <= $nb_answers; ++$k) {
+                $new_list[$k] = $k;
+            }
         }
-        
+
         $i = 1;
-		//for ($k = 1 ; $k <= $real_nb_answers; $k++) {            
+		//for ($k = 1 ; $k <= $real_nb_answers; $k++) {
         foreach ($new_list as $key) {
-            $i = $key;	    
-			$form -> addElement ('html', '<tr>'); 
-		             
+            $i = $key;
+			$form -> addElement ('html', '<tr>');
+
 			if (is_object($answer)) {
 			    if($answer->position[$i] == 666) {
-			        //we set nothing			        
-			    } else {			    
+			        //we set nothing
+			    } else {
     				if ($answer->correct[$i]) {
     					$correct = $i;
     				}
-                    $answer_result = $answer->answer[$i];                
-                    $weight_result = float_format($answer->weighting[$i], 1);
+                    $answer_result = $answer->answer[$i];
+                    $weight_result = Text::float_format($answer->weighting[$i], 1);
                     if ($nb_answers == $i) {
                         $weight_result = '0';
                     }
-                    
+
     				$defaults['answer['.$i.']']    = $answer_result;
     				$defaults['comment['.$i.']']   = $answer->comment[$i];
     				$defaults['weighting['.$i.']'] = $weight_result;
-    
+
     				$item_list=explode('@@',$answer -> destination[$i]);
-    
+
     				$try       = $item_list[0];
     				$lp        = $item_list[1];
     				$list_dest = $item_list[2];
     				$url       = $item_list[3];
-    
+
     				if ($try==0)
     					$try_result=0;
     				else
     					$try_result=1;
-    
+
     				if ($url==0)
     					$url_result='';
     				else
     					$url_result=$url;
-    
+
     				$temp_scenario['url'.$i]        = $url_result;
     				$temp_scenario['try'.$i]        = $try_result;
     				$temp_scenario['lp'.$i]         = $lp;
     				$temp_scenario['destination'.$i]= $list_dest;
 			    }
 			}
-			
+
 			$defaults['scenario']=$temp_scenario;
 			$renderer = & $form->defaultRenderer();
-            
-			$renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');  
-            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']');        
-          
-            
+
+			$renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');
+            $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']');
+
+
 			$answer_number=$form->addElement('text', 'counter['.$i.']', null,'value="'.$i.'"');
 			$answer_number->freeze();
-		
-        
+
+
 			$form->addElement('radio', 'correct', null, null, $i, 'class="checkbox" style="margin-left: 0em;"');
 			$form->addElement('html_editor', 'answer['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
-			
+
 			if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_END) {
 				// feedback
 				$form->addElement('html_editor', 'comment['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
-			} elseif ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {     
-         
+			} elseif ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
+
 			}
 			$form->addElement('text', 'weighting['.$i.']', null, array('class' => "span1", 'value' => '0'));
 			$form->addElement('html', '</tr>');
-            $i++;				
-		}	
-		
+            $i++;
+		}
+
 		if (empty($this -> id)) {
 		    $form->addElement('hidden', 'new_question', 1);
 		}
-        
+
         //Adding the "I don't know" question answer
         //if (empty($this -> id)) {
-        $i = 666;        
-        $form -> addElement ('html', '<tr>'); 
+        $i = 666;
+        $form -> addElement ('html', '<tr>');
 
         $defaults['answer['.$i.']']     = get_lang('DontKnow');
         $defaults['weighting['.$i.']']  = 0;
         $defaults['scenario']=$temp_scenario;
         $renderer = & $form->defaultRenderer();
 
-        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct');  
-        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');  
-        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');  
-        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');  
-        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']'); 
+        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct');
+        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter['.$i.']');
+        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer['.$i.']');
+        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment['.$i.']');
+        $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']');
 
         $answer_number=$form->addElement('text', 'counter['.$i.']',null,'value="-"');
         $answer_number->freeze();
@@ -241,7 +241,7 @@ class UniqueAnswerNoOption extends Question {
         if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_END) {
             // feedback
             $form->addElement('html_editor', 'comment['.$i.']', null, 'style="vertical-align:middle"', $editor_config);
-        } elseif ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {                    
+        } elseif ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
 
         }
 
@@ -251,8 +251,8 @@ class UniqueAnswerNoOption extends Question {
         $form->addElement ('html', '</tr>');
 
      //}
-    
-       
+
+
 		$form -> addElement ('html', '</table>');
 		$form -> addElement ('html', '<br />');
 		$navigator_info = api_get_navigator();
@@ -260,15 +260,15 @@ class UniqueAnswerNoOption extends Question {
 		global $text, $class;
 		//ie6 fix
 		if ($obj_ex->edit_exercise_in_lp == true) {
-			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {                
-                $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');                
+			if ($navigator_info['name']=='Internet Explorer' &&  $navigator_info['version']=='6') {
+                $form->addElement('submit', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');
 				$form->addElement('submit', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');
                 $form->addElement('submit','submitQuestion',$text, 'class="'.$class.'"');
 			} else {
-                //setting the save button here and not in the question class.php                
+                //setting the save button here and not in the question class.php
                 $form->addElement('style_submit_button', 'lessAnswers', get_lang('LessAnswer'),'class="btn minus"');
                 $form->addElement('style_submit_button', 'moreAnswers', get_lang('PlusAnswer'),'class="btn plus"');
-                $form->addElement('style_submit_button','submitQuestion',$text, 'class="'.$class.'"');				
+                $form->addElement('style_submit_button','submitQuestion',$text, 'class="'.$class.'"');
 			}
 		}
 		$renderer->setElementTemplate('{element}&nbsp;','submitQuestion');
@@ -287,13 +287,13 @@ class UniqueAnswerNoOption extends Question {
 			$form -> setDefaults($defaults);
 		} else {
             $form -> setDefaults($defaults);
-		}		
-		
+		}
+
 		$form->addElement('hidden', 'nb_answers');
-		
-	
+
+
 	    $form->setConstants(array('nb_answers' => $nb_answers));
-		
+
 	}
 
 
@@ -310,19 +310,19 @@ class UniqueAnswerNoOption extends Question {
 		$nb_answers = $form -> getSubmitValue('nb_answers');
 		$minus = 1;
 		if ($form -> getSubmitValue('new_question')) {
-		    $minus = 0;    
-		}	
-            
+		    $minus = 0;
+		}
+
 		for ($i=1 ; $i <= $nb_answers - $minus; $i++) {
 		    $position   = trim($form -> getSubmitValue('position['.$i.']'));
         	$answer     = trim($form -> getSubmitValue('answer['.$i.']'));
             $comment    = trim($form -> getSubmitValue('comment['.$i.']'));
             $weighting  = trim($form -> getSubmitValue('weighting['.$i.']'));
             $scenario   = $form -> getSubmitValue('scenario');
-            
-            
+
+
 //
-            
+
            	//$list_destination = $form -> getSubmitValue('destination'.$i);
            	//$destination_str = $form -> getSubmitValue('destination'.$i);
 
@@ -371,7 +371,7 @@ class UniqueAnswerNoOption extends Question {
  			if (empty($destination)) {
  				$destination=0;
  			}
-            
+
  			if ($url=='') {
  				$url=0;
  			}
@@ -380,17 +380,17 @@ class UniqueAnswerNoOption extends Question {
 			$dest= $try.'@@'.$lp.'@@'.$destination.'@@'.$url;
         	$objAnswer -> createAnswer($answer,$goodAnswer,$comment,$weighting,$i,NULL,NULL,$dest);
         }
-        
+
         //Create 666 answer
         $i = 666;
         $answer     = trim($form -> getSubmitValue('answer['.$i.']'));
         $comment    = trim($form -> getSubmitValue('comment['.$i.']'));
         $weighting  = trim($form -> getSubmitValue('weighting['.$i.']'));
         $goodAnswer= ($correct == $i) ? true : false;
-        $dest       = ''; 
-            
+        $dest       = '';
+
         $objAnswer -> createAnswer($answer,$goodAnswer,$comment,$weighting,$i,NULL,NULL,$dest);
-        
+
     	// saves the answers into the data base
         $objAnswer -> save();
 
@@ -398,21 +398,21 @@ class UniqueAnswerNoOption extends Question {
         $this -> updateWeighting($questionWeighting);
         $this -> save();
 	}
-	
+
 	function return_header($feedback_type = null, $counter = null, $score = null, $show_media = false) {
 	    $header = parent::return_header($feedback_type, $counter, $score, $show_media);
-	    $header .= '<table class="'.$this->question_table_class .'">			
+	    $header .= '<table class="'.$this->question_table_class .'">
 			<tr>
 				<th>'.get_lang("Choice").'</th>
 				<th>'. get_lang("ExpectedChoice").'</th>
 				<th>'. get_lang("Answer").'</th>';
-				if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { 
+				if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) {
     				$header .= '<th>'.get_lang("Comment").'</th>';
-				} else { 
+				} else {
 					$header .= '<th>&nbsp;</th>';
 				}
         $header .= '</tr>';
-        return $header;	
+        return $header;
 	}
 }
 endif;

+ 35 - 35
main/glossary/index.php

@@ -23,7 +23,7 @@ api_protect_course_script(true);
 
 // Additional javascripts.
 $htmlHeadXtra[] = GlossaryManager::javascript_glossary();
-$htmlHeadXtra[] = '<script type="text/javascript">
+$htmlHeadXtra[] = '<script>
 function setFocus(){
     $("#glossary_title").focus();
 }
@@ -48,39 +48,39 @@ $action = isset($_GET['action']) ? $_GET['action'] : null;
 
 $tool = 'GlossaryManagement';
 
-$interbreadcrumb[] = array ("url"=>"index.php", "name"=> get_lang('Glossary'));         
+$interbreadcrumb[] = array ("url"=>"index.php", "name"=> get_lang('Glossary'));
 
 if (!empty($action)) {
-    
+
 }
 switch ($action) {
-    case 'addglossary':            
+    case 'addglossary':
         $tool_name =  get_lang('Add');
         break;
-    case 'edit_glossary':         
-        $tool_name =  get_lang('Edit');                    
-        break;                
+    case 'edit_glossary':
+        $tool_name =  get_lang('Edit');
+        break;
     case 'import':
-        $tool_name =  get_lang('ImportGlossary');        
+        $tool_name =  get_lang('ImportGlossary');
         break;
     case 'changeview':
-        $tool_name =  get_lang('List');        
-        break;    
+        $tool_name =  get_lang('List');
+        break;
 }
-            
-if (isset($_GET['action']) && $_GET['action'] == 'export') {	
+
+if (isset($_GET['action']) && $_GET['action'] == 'export') {
 	$data = GlossaryManager::get_glossary_data(0, GlossaryManager::get_number_glossary_terms (api_get_session_id()), 0, 'ASC');
-    
+
     usort($data, "sorter");
     $list = array();
     $list[] = array('term','definition');
     foreach($data as $line) {
         $list[] = array ($line[0], $line[1]);
-    }    
+    }
     $filename = 'glossary_course_'.api_get_course_id();
 	Export::export_table_csv_utf8($list, $filename);
 }
-if (isset($_GET['action']) && $_GET['action'] == 'export_to_pdf') {	
+if (isset($_GET['action']) && $_GET['action'] == 'export_to_pdf') {
     GlossaryManager::export_to_pdf();
 }
 
@@ -98,9 +98,9 @@ if (isset($_GET['action']) && $_GET['action'] == 'changeview' AND in_array($_GET
 }
 
 if (api_is_allowed_to_edit(null, true)) {
-    
+
     switch ($action) {
-        case 'addglossary':          
+        case 'addglossary':
             $form = new FormValidator('glossary','post', api_get_self().'?action='.Security::remove_XSS($_GET['action']));
             // settting the form elements
             $form->addElement('header', '', get_lang('TermAddNew'));
@@ -123,7 +123,7 @@ if (api_is_allowed_to_edit(null, true)) {
                 $token = Security::get_token();
                 $form->addElement('hidden','sec_token');
                 $form->setConstants(array('sec_token' => $token));
-                $form->display();                
+                $form->display();
             }
             break;
         case 'edit_glossary':
@@ -135,11 +135,11 @@ if (api_is_allowed_to_edit(null, true)) {
                 $form->addElement('hidden', 'glossary_id');
                 $form->addElement('text', 'glossary_title', get_lang('TermName'),array('size'=>'80'));
                 //$form->applyFilter('glossary_title', 'html_filter');
-                $form->addElement('html_editor', 'glossary_comment', get_lang('TermDefinition'), null, array('ToolbarSet' => 'Glossary', 'Width' => '90%', 'Height' => '300'));        
+                $form->addElement('html_editor', 'glossary_comment', get_lang('TermDefinition'), null, array('ToolbarSet' => 'Glossary', 'Width' => '90%', 'Height' => '300'));
                 $element = $form->addElement('text', 'insert_date', get_lang('CreationDate'),array('size'=>'100'));
-                $element ->freeze();        
+                $element ->freeze();
                 $element = $form->addElement('text', 'update_date', get_lang('UpdateDate'),array('size'=>'100'));
-                $element ->freeze();       
+                $element ->freeze();
                 $form->addElement('style_submit_button', 'SubmitGlossary', get_lang('TermUpdateButton'), 'class="save"');
 
                 // setting the defaults
@@ -177,7 +177,7 @@ if (api_is_allowed_to_edit(null, true)) {
                     $form->addElement('hidden', 'sec_token');
                     $form->setConstants(array('sec_token' => $token));
                     $form->display();
-                }                
+                }
             }
             break;
         case 'delete_glossary':
@@ -194,18 +194,18 @@ if (api_is_allowed_to_edit(null, true)) {
             break;
         case 'import':
             $form = new FormValidator('glossary','post', api_get_self().'?action=import');
-            $form->addElement('header', '', get_lang('ImportGlossary'));            
+            $form->addElement('header', '', get_lang('ImportGlossary'));
             $form->addElement('file', 'file', get_lang('ImportCSVFileLocation'));
             $form->addElement('checkbox', 'replace', null, get_lang('DeleteAllGlossaryTerms'));
             $form->addElement('style_submit_button', 'SubmitImport', get_lang('Import'), 'class="save"');
-            $form->display();       
-            
+            $form->display();
+
             echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')';
             echo '<pre>
                     <strong>term</strong>;<strong>definition</strong>;
                     "Hello";"Hola";
                     "Good";"Bueno";</pre>';
-            
+
             if ($form->validate()) {
                 //this is a bad idea //jm
                 if (isset($_POST['replace']) && $_POST['replace']) {
@@ -214,29 +214,29 @@ if (api_is_allowed_to_edit(null, true)) {
                             Display::display_error_message (get_lang ("CannotDeleteGlossary") . ':' . $term['id']);
                         }
                     }
-                }  
-                //$data = Import::csv_to_array($_FILES['file']['tmp_name']);     
+                }
+                //$data = Import::csv_to_array($_FILES['file']['tmp_name']);
                 $data = Import::csv_reader($_FILES['file']['tmp_name']);
                 $good = 0;
-                $bad = 0;                    
-                foreach ($data as $item) {                          
-                    if (GlossaryManager::save_glossary(array('glossary_title' => $item['term'], 'glossary_comment' => $item['definition']), false)) 
+                $bad = 0;
+                foreach ($data as $item) {
+                    if (GlossaryManager::save_glossary(array('glossary_title' => $item['term'], 'glossary_comment' => $item['definition']), false))
                         $good++;
                     else
                         $bad++;
                 }
-                      
+
                 Display::display_confirmation_message (get_lang ("TermsImported") . ':' . $good);
-                
+
                 if ($bad)
                     Display::display_error_message (get_lang ("TermsNotImported") . ':' . $bad);
-                
+
                 GlossaryManager::display_glossary();
             }
             break;
         default:
             GlossaryManager::display_glossary();
-            break;        
+            break;
     }
 } else {
     GlossaryManager::display_glossary();

+ 18 - 19
main/gradebook/gradebook.php

@@ -15,10 +15,10 @@ $_in_course = false;
 //make sure the destination for scripts is index.php instead of gradebook.php
 require_once '../inc/global.inc.php';
 if (!empty($_GET['course'])) {
-	$_SESSION['gradebook_dest'] = 'index.php';	
+	$_SESSION['gradebook_dest'] = 'index.php';
 	$this_section = SECTION_COURSES;
 } else {
-	$_SESSION['gradebook_dest'] = 'gradebook.php';	
+	$_SESSION['gradebook_dest'] = 'gradebook.php';
 	$this_section = SECTION_MYGRADEBOOK;
 	unset($_GET['course']);
 }
@@ -252,7 +252,7 @@ if (isset ($_GET['visiblelink'])) {
 if (isset ($_GET['deletelink'])) {
 	block_students();
 	//fixing #5229
-	if (!empty($_GET['deletelink'])) {	
+	if (!empty($_GET['deletelink'])) {
 		$link= LinkFactory :: load($_GET['deletelink']);
 		if ($link[0] != null) {
 			$link[0]->delete();
@@ -394,25 +394,25 @@ if (!isset($_GET['exportpdf']) and !isset($_GET['export_certificate'])) {
 			'name' => get_lang('ToolGradebook')
 		);
 		Display :: display_header(get_lang('FlatView'));
-	} elseif (isset ($_GET['search'])) {		
+	} elseif (isset ($_GET['search'])) {
 		if ($_SESSION['gradebook_dest'] == 'index.php') {
-			$gradebook_dest = Security::remove_XSS($_SESSION['gradebook_dest']).'?cidReq='.Security::remove_XSS($_GET['course']).'&amp;';	
+			$gradebook_dest = Security::remove_XSS($_SESSION['gradebook_dest']).'?cidReq='.Security::remove_XSS($_GET['course']).'&amp;';
 		} else {
 			$gradebook_dest = Security::remove_XSS($_SESSION['gradebook_dest']);
-		}	
-		
+		}
+
 		$interbreadcrumb[]= array ('url' => $gradebook_dest,'name' => get_lang('Gradebook'));
 
-		if ((isset($_GET['selectcat']) && $_GET['selectcat']>0)) {			
+		if ((isset($_GET['selectcat']) && $_GET['selectcat']>0)) {
 			if (!empty($_GET['course'])) {
-				$interbreadcrumb[]= array ('url' => $gradebook_dest.'selectcat='.Security::remove_XSS($_GET['selectcat']),'name' => get_lang('Details'));	
+				$interbreadcrumb[]= array ('url' => $gradebook_dest.'selectcat='.Security::remove_XSS($_GET['selectcat']),'name' => get_lang('Details'));
 			} else {
 				$interbreadcrumb[]= array ('url' => $_SESSION['gradebook_dest'].'?selectcat=0','name' => get_lang('Details'));
-			}	
-		}		
+			}
+		}
 	 	Display :: display_header('');
-	} else { 
-		Display :: display_header(''); 
+	} else {
+		Display :: display_header('');
 	}
 }
 
@@ -479,7 +479,7 @@ if ($simple_search_form->validate() && (empty($keyword))) {
 	$keyword = $values['keyword'];
 }
 if (!empty($keyword)) {
-    
+
 	$cats= Category :: load($category);
 	$allcat= array ();
 	if ((isset($_GET['selectcat']) && $_GET['selectcat']==0) && isset($_GET['search'])) {
@@ -493,7 +493,7 @@ if (!empty($keyword)) {
 	}
 
 } elseif (isset ($_GET['studentoverview'])) {
-    //@todo this code seems to be deprecated because the gradebook tab is off 
+    //@todo this code seems to be deprecated because the gradebook tab is off
 	$cats= Category :: load($category);
 	$stud_id= (api_is_allowed_to_edit() ? null : api_get_user_id());
 	$allcat= array ();
@@ -507,7 +507,7 @@ if (!empty($keyword)) {
 		foreach ($data_array as $data) {
 			$newarray[] = array_slice($data, 1);
 		}
-		$pdf= new Cezpdf(); 
+		$pdf= new Cezpdf();
 		$pdf->selectFont(api_get_path(LIBRARY_PATH).'ezpdf/fonts/Courier.afm');
 		$pdf->ezSetMargins(30, 30, 50, 30);
 		$pdf->ezSetY(810);
@@ -527,7 +527,7 @@ if (!empty($keyword)) {
 	}
 	$category = Category :: load ($_GET['cat_id']);
 	if ($category[0]->is_certificate_available($user_id)) {
-		$user= get_user_info_from_id($user_id);
+		$user= api_get_user_info($user_id);
 		$scoredisplay = ScoreDisplay :: instance();
 		$scorecourse = $category[0]->calc_score($user_id);
 		$scorecourse_display = (isset($scorecourse) ? $scoredisplay->display_score($scorecourse,SCORE_AVERAGE) : get_lang('NoResultsAvailable'));
@@ -552,8 +552,7 @@ if (!empty($keyword)) {
 		$pdf->line(50,50,790,50);
 		$pdf->line(50,550,790,550);
 		$pdf->ezSetY(450);
-        //@todo replace image
-		//$pdf->ezImage(api_get_path(SYS_CODE_PATH).'img/dokeos_logo_certif.png',1,400,'','center','');
+
 		$pdf->ezSetY(480);
 		$pdf->ezText($certif_text,28,array('justification'=>'center'));
 		//$pdf->ezSetY(750);

+ 6 - 6
main/gradebook/gradebook_view_result.php

@@ -156,7 +156,7 @@ if (isset ($_GET['import'])) {
                     );
                     exit;
                 }
-                $userinfo = get_user_info_from_id($importedresult['user_id']);
+                $userinfo = api_get_user_info($importedresult['user_id']);
                 if ($userinfo['lastname'] != $importedresult['lastname'] || $userinfo['firstname'] != $importedresult['firstname'] || $userinfo['official_code'] != $importedresult['official_code']) {
                     if (!isset ($values['ignoreerrors'])) {
                         header(
@@ -346,7 +346,7 @@ if (isset($_GET['export'])) {
 
         // export results to xml or csv file
         foreach ($results as $result) {
-            $userinfo = get_user_info_from_id($result->get_user_id());
+            $userinfo = api_get_user_info($result->get_user_id());
             $data['username'] = $userinfo['username']; //$result->get_user_id();
             $data['official_code'] = $userinfo['official_code'];
             $data['lastname'] = $userinfo['lastname'];
@@ -514,18 +514,18 @@ if (isset ($_GET['importoverwritescore'])) {
     Display :: display_confirmation_message(get_lang('ImportOverWriteScore').' '.$_GET['importoverwritescore']);
 }
 if (isset ($_GET['import_user_error'])) {
-    $userinfo = get_user_info_from_id($_GET['import_user_error']);
+    $userinfo = api_get_user_info($_GET['import_user_error']);
     Display :: display_warning_message(
-        get_lang('UserInfoDoesNotMatch').' '.api_get_person_name($userinfo['firstname'], $userinfo['lastname'])
+        get_lang('UserInfoDoesNotMatch').' '.$userinfo['complete_name']
     );
 }
 if (isset ($_GET['allresdeleted'])) {
     Display :: display_confirmation_message(get_lang('AllResultDeleted'));
 }
 if (isset ($_GET['import_score_error'])) {
-    $userinfo = get_user_info_from_id($_GET['import_score_error']);
+    $userinfo = api_get_user_info($_GET['import_score_error']);
     Display :: display_warning_message(
-        get_lang('ScoreDoesNotMatch').' '.api_get_person_name($userinfo['firstname'], $userinfo['lastname'])
+        get_lang('ScoreDoesNotMatch').' '.$userinfo['complete_name']
     );
 }
 if ($file_type == null) { //show the result header

+ 9 - 9
main/gradebook/lib/be/surveylink.class.php

@@ -64,7 +64,7 @@ class SurveyLink extends AbstractLink
     	$sql = 'SELECT survey_id, title, code FROM '.$tbl_survey.' WHERE c_id = '.$course_id.' AND session_id = '.intval($session_id).'';
 		$result = Database::query($sql);
 		while ($data = Database::fetch_array($result)) {
-			$links[] = array($data['survey_id'], api_trunc_str($data['code'].': '.self::html_to_text($data['title']), 80));
+			$links[] = array($data['survey_id'], Text::api_trunc_str($data['code'].': '.self::html_to_text($data['title']), 80));
 		};
 		return isset($links) ? $links : null;
     }
@@ -89,7 +89,7 @@ class SurveyLink extends AbstractLink
 
 		$links = array();
 		while ($data = Database::fetch_array($result)) {
-			$links[] = array($data['survey_id'], api_trunc_str($data['code'].': '.self::html_to_text($data['title']), 80));
+			$links[] = array($data['survey_id'], Text::api_trunc_str($data['code'].': '.self::html_to_text($data['title']), 80));
 		}
 		return $links;
     }
@@ -105,14 +105,14 @@ class SurveyLink extends AbstractLink
 		$get_individual_score = !is_null($stud_id);
 		$sql = "SELECT COUNT(i.answered) FROM $tbl_survey AS s JOIN $tbl_survey_invitation AS i ON s.code = i.survey_code
 				WHERE 	s.c_id = {$this->course_id} AND
-						i.c_id = {$this->course_id} AND 
-						s.survey_id = $ref_id AND 
+						i.c_id = {$this->course_id} AND
+						s.survey_id = $ref_id AND
 						i.session_id = $session_id";
 
 		$sql_result = Database::query($sql);
 		$data = Database::fetch_array($sql_result);
 		return ($data[0] != 0);
-	
+
     }
 
     public function calc_score($stud_id = null) {
@@ -120,7 +120,7 @@ class SurveyLink extends AbstractLink
     	// Note: Max score is assumed to be always 1 for surveys,
     	// only student's participation is to be taken into account.
     	$max_score = 1;
-    	
+
     	$ref_id = intval($this->get_ref_id());
 		$session_id = api_get_session_id();
 		$tbl_survey = Database::get_course_table(TABLE_SURVEY, $database_name);
@@ -131,7 +131,7 @@ class SurveyLink extends AbstractLink
 		$sql = "SELECT i.answered FROM $tbl_survey AS s JOIN $tbl_survey_invitation AS i
 				ON s.code = i.survey_code
 				WHERE 	s.c_id = {$this->course_id} AND
-						i.c_id = {$this->course_id} AND 
+						i.c_id = {$this->course_id} AND
 						s.survey_id = $ref_id AND i.session_id = $session_id";
 
 		if ($get_individual_score) {
@@ -160,7 +160,7 @@ class SurveyLink extends AbstractLink
 				return null;
 			}
 			return array($sum, $rescount);
-		}		
+		}
     }
 
     /**
@@ -168,7 +168,7 @@ class SurveyLink extends AbstractLink
      */
     private function get_survey_table() {
     	$this->survey_table = Database :: get_course_table(TABLE_SURVEY);
-   		return $this->survey_table;		
+   		return $this->survey_table;
     }
 
     /**

+ 111 - 111
main/gradebook/lib/fe/displaygradebook.php

@@ -19,7 +19,7 @@ class DisplayGradebook
 	*/
 	static function display_header_result($evalobj, $selectcat, $page) {
 		if (api_is_allowed_to_edit(null, true)) {
-			$header = '<div class="actions">';			
+			$header = '<div class="actions">';
 			if ($page != 'statistics') {
 			    $header .= '<a href="'.Security::remove_XSS($_SESSION['gradebook_dest']).'?selectcat=' . $selectcat . '">'. Display::return_icon(('back.png'),get_lang('FolderView'),'',ICON_SIZE_MEDIUM).'</a>';
     			if ($evalobj->get_course_code() == null) {
@@ -27,22 +27,22 @@ class DisplayGradebook
     				//$header .= '<a href="gradebook_add_user.php?selecteval=' . $evalobj->get_id() . '"><img src="../img/add_user_big.gif" alt="' . get_lang('AddStudent') . '" align="absmiddle" /> ' . get_lang('AddStudent') . '</a>';
     			} elseif (!$evalobj->has_results()) {
     				$header .= '<a href="gradebook_add_result.php?selectcat=' . $selectcat . '&selecteval=' . $evalobj->get_id() . '">
-    				'.Display::return_icon('evaluation_rate.png',get_lang('AddResult'),'',ICON_SIZE_MEDIUM) . '</a>';				
+    				'.Display::return_icon('evaluation_rate.png',get_lang('AddResult'),'',ICON_SIZE_MEDIUM) . '</a>';
     			}
-                
+
                 if (api_is_platform_admin() || $evalobj->is_locked() == false) {
-                    $header .= '<a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&import=">'.Display::return_icon('import_evaluation.png',get_lang('ImportResult'),'',ICON_SIZE_MEDIUM) . '</a>';			
+                    $header .= '<a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&import=">'.Display::return_icon('import_evaluation.png',get_lang('ImportResult'),'',ICON_SIZE_MEDIUM) . '</a>';
                 }
-                
+
     			if ($evalobj->has_results()) {
     				$header .= '<a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&export=">'.Display::return_icon('export_evaluation.png',get_lang('ExportResult'),'',ICON_SIZE_MEDIUM) . '</a>';
-                    
+
                     if (api_is_platform_admin() || $evalobj->is_locked() == false) {
                         $header .= '<a href="gradebook_edit_result.php?selecteval=' . $evalobj->get_id() .'">'.Display::return_icon('edit.png',get_lang('EditResult'),'',ICON_SIZE_MEDIUM).'</a>';
                         $header .= '<a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&deleteall=" onclick="return confirmationall();">'.Display::return_icon('delete.png',get_lang('DeleteResult'),'',ICON_SIZE_MEDIUM).'</a>';
                     }
     			}
-    			
+
     			$header .= '<a href="' . api_get_self() . '?print=&selecteval=' . $evalobj->get_id() . '" target="_blank">'.Display::return_icon('printer.png',get_lang('Print'),'',ICON_SIZE_MEDIUM).'</a>';
 			} else {
 			    $header .= '<a href="gradebook_view_result.php?selecteval='.Security::remove_XSS($_GET['selecteval']).'"> '.Display::return_icon(('back.png'),get_lang('FolderView'),'',ICON_SIZE_MEDIUM) . '</a>';
@@ -57,59 +57,59 @@ class DisplayGradebook
 		}
 
 		$scoredisplay = ScoreDisplay :: instance();
-        
+
         $student_score = '';
-        
+
 		if (($evalobj->has_results())){ // TODO this check needed ?
 			$score = $evalobj->calc_score();
-        
+
 			if ($score != null) {
                 $average= get_lang('Average') . ' :<b> ' .$scoredisplay->display_score($score, SCORE_AVERAGE) . '</b>';
                 $student_score = $evalobj->calc_score(api_get_user_id());
-                $student_score = Display::tag('h3', get_lang('Score').': '.$scoredisplay->display_score($student_score, SCORE_DIV_PERCENT));                            
-            }				
+                $student_score = Display::tag('h3', get_lang('Score').': '.$scoredisplay->display_score($student_score, SCORE_DIV_PERCENT));
+            }
 		}
-		
+
 		if (!$evalobj->get_description() == '') {
 			$description= get_lang('Description') . ' :<b> ' . $evalobj->get_description() . '</b><br>';
 		}
-        
+
 		if ($evalobj->get_course_code() == null) {
 			$course= get_lang('CourseIndependent');
 		} else {
 			$course= get_course_name_from_code($evalobj->get_course_code());
 		}
-    
+
 		$evalinfo= '<table width="100%" border="0"><tr><td>';
-		$evalinfo .= '<h2>'.$evalobj->get_name().'</h2><hr>'; 
+		$evalinfo .= '<h2>'.$evalobj->get_name().'</h2><hr>';
 		$evalinfo .= $description;
 		$evalinfo .= get_lang('Course') . ' :<b> ' . $course . '</b><br />';
 		//'<br>' . get_lang('Weight') . ' :<b> ' . $evalobj->get_weight() . '</b><br>' . get_lang('Visible') . ' :<b> ' . $visible . '</b>
         $evalinfo .=  get_lang('QualificationNumeric') . ' :<b> ' . $evalobj->get_max() . '</b><br>'.$average;
-        
+
         if (!api_is_allowed_to_edit()) {
             $evalinfo .= $student_score;
         }
-                
+
 		if (!$evalobj->has_results()) {
 			$evalinfo .= '<br /><i>' . get_lang('NoResultsInEvaluation') . '</i>';
 		} elseif ($scoredisplay->is_custom() && api_get_self() != '/main/gradebook/gradebook_statistics.php') {
             if (api_is_allowed_to_edit(null, true)) {
-                if ($page != 'statistics') {    
+                if ($page != 'statistics') {
                     //$evalinfo .= '<br /><br /><a href="gradebook_view_result.php?selecteval='.Security::remove_XSS($_GET['selecteval']).'"> '.Display::return_icon(('evaluation_rate.png'),get_lang('ViewResult'),'',ICON_SIZE_MEDIUM) . '</a>';
                 }
             }
         }
-        if ($page != 'statistics') {    
+        if ($page != 'statistics') {
             if (api_is_allowed_to_edit(null, true)) {
                 $evalinfo .= '<br /><a href="gradebook_statistics.php?selecteval='.Security::remove_XSS($_GET['selecteval']).'"> '.Display::return_icon(('statistics.png'),get_lang('ViewStatistics'),'',ICON_SIZE_MEDIUM).'</a>';
             }
         }
-        $evalinfo .= '</td><td><img style="float:right; position:relative;" src="../img/tutorial.gif"></td></table>';        
+        $evalinfo .= '</td><td><img style="float:right; position:relative;" src="../img/tutorial.gif"></td></table>';
 		echo $evalinfo;
 		echo $header;
 	}
-    
+
 	/**
 	* Displays the header for the flatview page containing filters
 	* @param $catobj
@@ -166,9 +166,9 @@ class DisplayGradebook
         } else {
             $select_cat = $catobj->get_parent_id();
             $url = 'gradebook_flatview.php';
-        }        
-        $header .= '<a href="'.$url.'?'.api_get_cidreq().'&selectcat='.$select_cat.'">'. Display::return_icon('back.png',get_lang('FolderView'),'',ICON_SIZE_MEDIUM).'</a>';    
-		
+        }
+        $header .= '<a href="'.$url.'?'.api_get_cidreq().'&selectcat='.$select_cat.'">'. Display::return_icon('back.png',get_lang('FolderView'),'',ICON_SIZE_MEDIUM).'</a>';
+
 
 		// this MUST be a GET variable not a POST
 		if (isset($_GET['show'])) {
@@ -181,25 +181,25 @@ class DisplayGradebook
 		$header .= '<a href="' . api_get_self() . '?export_format=doc&export_report=export_report&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('export_doc.png', get_lang('ExportAsDOC'),'',ICON_SIZE_MEDIUM).'</a>';
 		$header .= '<a href="' . api_get_self() . '?print=&selectcat=' . $catobj->get_id() . '" target="_blank">'.Display::return_icon('printer.png', get_lang('Print'),'',ICON_SIZE_MEDIUM).'</a>';
 		$header .= '<a href="' . api_get_self() . '?exportpdf=&selectcat=' . $catobj->get_id() . '" >'.Display::return_icon('pdf.png', get_lang('ExportToPDF'),'',ICON_SIZE_MEDIUM).'</a>';
-		$header .= '</div>';		
+		$header .= '</div>';
 		echo $header;
-	}	
-	
+	}
+
 	function display_header_gradebook_per_gradebook($catobj, $showtree, $selectcat, $is_course_admin, $is_platform_admin, $simple_search_form, $show_add_qualification = true, $show_add_link = true) {
 		// Student
 		$status = CourseManager::get_user_in_course_status(api_get_user_id(), api_get_course_id());
 		$objcat = new Category();
 		$course_id = Database::get_course_by_category($selectcat);
 		$message_resource=$objcat->show_message_resource_delete($course_id);
-		
+
 		if (!$is_course_admin && $status<>1 && $selectcat<>0) {
 			$user_id = api_get_user_id();
-			$user= get_user_info_from_id($user_id);
-		
+			$user= api_get_user_info($user_id);
+
 			$catcourse= Category :: load($catobj->get_id());
 			$scoredisplay = ScoreDisplay :: instance();
 			$scorecourse = $catcourse[0]->calc_score($user_id);
-		
+
 			// generating the total score for a course
 			$allevals= $catcourse[0]->get_evaluations($user_id,true);
 			$alllinks= $catcourse[0]->get_links($user_id,true);
@@ -211,23 +211,23 @@ class DisplayGradebook
 				$score = $item->calc_score($user_id);
 				$my_score_denom=($score[1]==0) ? 1 : $score[1];
 				$item_value+=$score[0]/$my_score_denom*$item->get_weight();
-				$item_total+=$item->get_weight();				
+				$item_total+=$item->get_weight();
 			}
 			$item_value = number_format($item_value, 2, '.', ' ');
 			$total_score=array($item_value,$item_total);
 			$scorecourse_display = $scoredisplay->display_score($total_score, SCORE_DIV_PERCENT);
-		
+
 			$cattotal = Category :: load(0);
 			$scoretotal= $cattotal[0]->calc_score(api_get_user_id());
 			$scoretotal_display = (isset($scoretotal) ? $scoredisplay->display_score($scoretotal, SCORE_PERCENT) : get_lang('NoResultsAvailable'));
-			$scoreinfo = get_lang('StatsStudent') . ' :<b> '.api_get_person_name($user['firstname'], $user['lastname']).'</b><br />';
+			$scoreinfo = get_lang('StatsStudent') . ' :<b> '.$user['complete_name'].'</b><br />';
 			if ((!$catobj->get_id() == '0') && (!isset ($_GET['studentoverview'])) && (!isset ($_GET['search']))) {
 				$scoreinfo.= '<h2>'.get_lang('Total') . ' : ' . $scorecourse_display . '</h2>';
-			}		
+			}
 			Display :: display_normal_message($scoreinfo, false);
 		}
-        
-		// show navigation tree and buttons?		
+
+		// show navigation tree and buttons?
 		$header = '<div class="actions"><table border=0>';
 		if (($showtree == '1') || (isset ($_GET['studentoverview']))) {
 			$header .= '<tr>';
@@ -237,10 +237,10 @@ class DisplayGradebook
 			$header .= '<td style=" ">' . get_lang('CurrentCategory') . '</td>' .
 							'<td style=" "><form name="selector"><select name="selectcat" onchange="document.selector.submit()">';
 			$cats= Category :: load();
-		
+
 			$tree= $cats[0]->get_tree();
 			unset ($cats);
-				
+
 			foreach ($tree as $cat) {
 				for ($i= 0; $i < $cat[2]; $i++) {
 					$line .= '&mdash;';
@@ -274,20 +274,20 @@ class DisplayGradebook
 			$header .= '</td></tr>';
 		}
 		$header.='</table></div>';
-		
+
 		// for course admin & platform admin add item buttons are added to the header
 		$header .= '<div class="actions">';
-		
+
 		$my_category = $catobj->shows_all_information_an_category($catobj->get_id());
 		$user_id     = api_get_user_id();
 		$course_code = $my_category['course_code'];
 		$status_user = api_get_status_of_user_in_course ($user_id,$course_code);
-		
+
 		//$header .= '<a href="gradebook_add_cat.php?'.api_get_cidreq().'&selectcat=0"><img src="../img/folder_new.gif" alt="' . get_lang('AddGradebook') . '" /></a></td>';
-		
+
 		if (api_is_allowed_to_edit(null, true)) {
 			if ($selectcat == '0') {
-				if ($show_add_qualification === true) {						
+				if ($show_add_qualification === true) {
 				}
 				if ($show_add_link) {
 					//$header .= '<td><a href="gradebook_add_eval.php?'.api_get_cidreq().'"><img src="../img/filenew.gif" alt="' . get_lang('NewEvaluation') . '" /> ' . get_lang('NewEvaluation') . '</a>';
@@ -307,45 +307,45 @@ class DisplayGradebook
 					if ($cats[0]->get_course_code() != null && !$message_resource) {
 						//$header .= '<td><a href="gradebook_add_link.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '"><img src="../img/link.gif" alt="' . get_lang('MakeLink') . '" align="absmiddle" /> ' . get_lang('MakeLink') . '</a>';
 						//$header .= '<td><a href="gradebook_add_link.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('new_online_evaluation.png', get_lang('MakeLink'),'',ICON_SIZE_MEDIUM).'</a>';
-		
+
 					} else {
 					//	$header .= '<td><a href="gradebook_add_link_select_course.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('new_online_evaluation.png', get_lang('MakeLink'),'',ICON_SIZE_MEDIUM).'</a>';
 					}
 				}
-		
+
 				if (!$message_resource) {
 					$myname = $catobj->shows_all_information_an_category($catobj->get_id());
-		
+
 					$my_course_id=api_get_course_id();
 					$my_file= substr($_SESSION['gradebook_dest'],0,5);
-		
+
 					$header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('stats.png', get_lang('FlatView'),'',ICON_SIZE_MEDIUM).'</a>';
 					$header .= '<td style="vertical-align: top;"><a href="gradebook_display_certificate.php?'.$my_api_cidreq.'&amp;cat_id='.(int)$_GET['selectcat'].'">'.Display::return_icon('certificate_list.png', get_lang('GradebookSeeListOfStudentsCertificates'),'',ICON_SIZE_MEDIUM).'</a>';
-						
+
 					$visibility_icon    = ($catobj->is_visible() == 0) ? 'invisible' : 'visible';
 					$visibility_command = ($catobj->is_visible() == 0) ? 'set_visible' : 'set_invisible';
-					 
+
 					//Right icons
 					$modify_icons  = '<a href="gradebook_edit_cat.php?editcat='.$catobj->get_id().'&cidReq='.$catobj->get_course_code().'">'.Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_MEDIUM).'</a>';
 					//$modify_icons .= '<a href="../document/document.php?curdirpath=/certificates&'.$my_api_cidreq.'&origin=gradebook&selectcat=' . $catobj->get_id() . '">'.
-					//Display::return_icon('certificate.png', get_lang('AttachCertificate'),'',ICON_SIZE_MEDIUM).'</a>';	
-	
+					//Display::return_icon('certificate.png', get_lang('AttachCertificate'),'',ICON_SIZE_MEDIUM).'</a>';
+
 					//hide or delete are not options available
 					//$modify_icons .= '&nbsp;<a  href="' . api_get_self() . '?visiblecat=' . $catobj->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=0 ">'.Display::return_icon($visibility_icon.'.png', get_lang('Visible'),'',ICON_SIZE_MEDIUM).'</a>';
 					if ($catobj->get_name() != api_get_course_id()) {
 						$modify_icons .= '&nbsp;<a  href="' . api_get_self() . '?deletecat=' . $catobj->get_id() . '&amp;selectcat=0&amp;cidReq='.$catobj->get_course_code().'" onclick="return confirmation();">'.Display::return_icon('delete.png', get_lang('DeleteAll'),'',ICON_SIZE_MEDIUM).'</a>';
-					}					 
+					}
 					$header .= Display::div($modify_icons, array('class'=>'right'));
-						
+
 				}
 			}
 		} elseif (isset ($_GET['search'])) {
 			$header .= '<b>'.get_lang('SearchResults').' :</b>';
 		}
 		$header .= '</div>';
-		echo $header;		
+		echo $header;
 	}
-    
+
 	/**
 	 * Displays the header for the gradebook containing the navigation tree and links
 	 * @param category_object $currentcat
@@ -362,15 +362,15 @@ class DisplayGradebook
 		$objcat = new Category();
 		$course_id = Database::get_course_by_category($selectcat);
 		$message_resource = $objcat->show_message_resource_delete($course_id);
-        
+
         $grade_model_id = $catobj->get_grade_model_id();
-        
+
         //@todo move these in a function
         $sum_categories_weight_array = array();
-        if (isset($catobj) && !empty($catobj)) {            
+        if (isset($catobj) && !empty($catobj)) {
             $categories = Category::load(null, null, null, $catobj->get_id());
             if (!empty($categories)) {
-                foreach ($categories as $category) {                  
+                foreach ($categories as $category) {
                     $sum_categories_weight_array[$category->get_id()] = $category->get_weight();
                 }
             } else {
@@ -382,30 +382,30 @@ class DisplayGradebook
 			$user_id = api_get_user_id();
 			$catcourse	  = Category::load($catobj->get_id());
             $main_weight = $catcourse[0]->get_weight();
-			$scoredisplay = ScoreDisplay :: instance();			
+			$scoredisplay = ScoreDisplay :: instance();
 
 			// generating the total score for a course
 			$allevals= $catcourse[0]->get_evaluations($user_id,true);
 			$alllinks= $catcourse[0]->get_links($user_id,true);
 			$evals_links = array_merge($allevals, $alllinks);
-            
+
 			$item_value =0;
 			$item_total = 0;
-            $item_total_value = 0;     
-            
+            $item_total_value = 0;
+
 			for ($count=0; $count < count($evals_links); $count++) {
 				$item           = $evals_links[$count];
 				$score          = $item->calc_score($user_id);
                 $divide			= ( ($score[1])==0 ) ? 1 : $score[1];
-                
-                $sub_cat_percentage = $sum_categories_weight_array[$item->get_category_id()];                
+
+                $sub_cat_percentage = $sum_categories_weight_array[$item->get_category_id()];
                 //$item_value     = $score[0]/$divide;
                 $item_value     = $score[0]/$divide*$item->get_weight()*$sub_cat_percentage/$main_weight;
                 $item_value_total +=$item_value;
-			}            
+			}
             $item_total = $main_weight;
-            
-			$total_score = array($item_value_total, $item_total);       
+
+			$total_score = array($item_value_total, $item_total);
 			$scorecourse_display = $scoredisplay->display_score($total_score, SCORE_DIV_PERCENT);
 
 			if ((!$catobj->get_id() == '0') && (!isset ($_GET['studentoverview'])) && (!isset ($_GET['search']))) {
@@ -413,10 +413,10 @@ class DisplayGradebook
 			}
 			Display :: display_normal_message($scoreinfo, false);
 		}
-        
-		// show navigation tree and buttons?		
+
+		// show navigation tree and buttons?
 		if (($showtree == '1') || (isset ($_GET['studentoverview']))) {
-            $header = '<div class="actions"><table>';            
+            $header = '<div class="actions"><table>';
 			$header .= '<tr>';
 			if (!$selectcat == '0') {
 				$header .= '<td><a href="' . api_get_self() . '?selectcat=' . $catobj->get_parent_id() . '">'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('RootCat'),'',ICON_SIZE_MEDIUM).'</a></td>';
@@ -425,9 +425,9 @@ class DisplayGradebook
 					'<td><form name="selector"><select name="selectcat" onchange="document.selector.submit()">';
 			$cats= Category :: load();
 
-			$tree= $cats[0]->get_tree();            
+			$tree= $cats[0]->get_tree();
 			unset ($cats);
-			
+
 			foreach ($tree as $cat) {
 				for ($i= 0; $i < $cat[2]; $i++) {
 					$line .= '&mdash;';
@@ -461,25 +461,25 @@ class DisplayGradebook
 			}
 			$header .= '</td></tr>';
             $header.='</table></div>';
-		}		
+		}
 
 		// for course admin & platform admin add item buttons are added to the header
 		$header .= '<div class="actions">';
-		
+
 		$my_category = $catobj->shows_all_information_an_category($catobj->get_id());
 		$user_id     = api_get_user_id();
-        
-		//$course_code = $my_category['course_code'];        
+
+		//$course_code = $my_category['course_code'];
 		//$status_user = api_get_status_of_user_in_course ($user_id,$course_code);
-		
+
 		if (api_is_allowed_to_edit(null, true)) {
-            
+
             if (empty($grade_model_id) || $grade_model_id == -1) {
-                $header .= '<a href="gradebook_add_cat.php?'.api_get_cidreq().'&selectcat='.$catobj->get_id().'">'.Display::return_icon('new_folder.png', get_lang('AddGradebook'), array(), ICON_SIZE_MEDIUM).'</a></td>';			
+                $header .= '<a href="gradebook_add_cat.php?'.api_get_cidreq().'&selectcat='.$catobj->get_id().'">'.Display::return_icon('new_folder.png', get_lang('AddGradebook'), array(), ICON_SIZE_MEDIUM).'</a></td>';
             }
-			
+
 			if ($selectcat == '0') {
-                if ($show_add_qualification === true) {				   
+                if ($show_add_qualification === true) {
                 }
                 if ($show_add_link) {
 				    //$header .= '<td><a href="gradebook_add_eval.php?'.api_get_cidreq().'"><img src="../img/filenew.gif" alt="' . get_lang('NewEvaluation') . '" /> ' . get_lang('NewEvaluation') . '</a>';
@@ -489,14 +489,14 @@ class DisplayGradebook
     				//$header .= '<a href="gradebook_add_cat.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '" ><img src="../img/folder_new.gif" alt="' . get_lang('NewSubCategory') . '" align="absmiddle" /> ' . get_lang('NewSubCategory') . '</a></td>';
                 }
                 $my_category = $catobj->shows_all_information_an_category($catobj->get_id());
-                              
+
 				$my_api_cidreq = api_get_cidreq();
 				if ($my_api_cidreq=='') {
 					$my_api_cidreq='cidReq='.$my_category['course_code'];
 				}
                 if ($show_add_link && !$message_resource) {
     				$header .= '<td><a href="gradebook_add_eval.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '" >'.Display::return_icon('new_evaluation.png', get_lang('NewEvaluation'),'',ICON_SIZE_MEDIUM).'</a>';
-                    $cats = Category :: load($selectcat);                    
+                    $cats = Category :: load($selectcat);
                     if ($cats[0]->get_course_code() != null && !$message_resource) {
                         //$header .= '<td><a href="gradebook_add_link.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '"><img src="../img/link.gif" alt="' . get_lang('MakeLink') . '" align="absmiddle" /> ' . get_lang('MakeLink') . '</a>';
                         $header .= '<td><a href="gradebook_add_link.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('new_online_evaluation.png', get_lang('MakeLink'),'',ICON_SIZE_MEDIUM).'</a>';
@@ -507,50 +507,50 @@ class DisplayGradebook
 
                 if (!$message_resource) {
                 	//$myname = $catobj->shows_all_information_an_category($catobj->get_id());
-                 	
+
                 	//$my_course_id=api_get_course_id();
                 	//$my_file= substr($_SESSION['gradebook_dest'],0,5);
-                		
-					$header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('stats.png', get_lang('FlatView'),'',ICON_SIZE_MEDIUM).'</a>';					
+
+					$header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('stats.png', get_lang('FlatView'),'',ICON_SIZE_MEDIUM).'</a>';
 					$header .= '<td style="vertical-align: top;"><a href="gradebook_display_certificate.php?'.$my_api_cidreq.'&amp;cat_id='.(int)$_GET['selectcat'].'">'.Display::return_icon('certificate_list.png', get_lang('GradebookSeeListOfStudentsCertificates'),'',ICON_SIZE_MEDIUM).'</a>';
-					
+
 					//$visibility_icon    = ($catobj->is_visible() == 0) ? 'invisible' : 'visible';
 			        //$visibility_command = ($catobj->is_visible() == 0) ? 'set_visible' : 'set_invisible';
-			        
+
 					//Right icons
-					
+
             		$modify_icons  = '<a href="gradebook_edit_cat.php?editcat='.$catobj->get_id().'&amp;cidReq='.$catobj->get_course_code().'">'.Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_MEDIUM).'</a>';
             		$modify_icons .= '<a href="../document/document.php?curdirpath=/certificates&'.$my_api_cidreq.'&origin=gradebook&selectcat=' . $catobj->get_id() . '">'.
             							Display::return_icon('certificate.png', get_lang('AttachCertificate'),'',ICON_SIZE_MEDIUM).'</a>';
-            		
+
                     if (empty($categories)) {
                         $modify_icons .= '<a href="gradebook_edit_all.php?id_session='.api_get_session_id().'&amp;'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() . '">'.Display::return_icon('percentage.png', get_lang('EditAllWeights'),'',ICON_SIZE_MEDIUM).'</a>';
-                    }                    
+                    }
 		    $score_display_custom = api_get_setting('gradebook_score_display_custom');
             		if (api_get_setting('teachers_can_change_score_settings') == 'true' && $score_display_custom['my_display_custom'] == 'true') {
                         $modify_icons .= '<a href="gradebook_scoring_system.php?'.$my_api_cidreq.'&selectcat=' . $catobj->get_id() .'">'.Display::return_icon('ranking.png', get_lang('ScoreEdit'),'',ICON_SIZE_MEDIUM).'</a>';
                     }
-            		$header .= Display::div($modify_icons, array('class'=>'right'));					
+            		$header .= Display::div($modify_icons, array('class'=>'right'));
                 }
 			}
 		} elseif (isset ($_GET['search'])) {
 			$header .= '<b>'.get_lang('SearchResults').' :</b>';
 		}
 		$header .= '</div>';
-        
-		echo $header;		
-		
+
+		echo $header;
+
 		if (api_is_allowed_to_edit(null, true)) {
-    	    $weight = ((intval($catobj->get_weight())>0) ? $catobj->get_weight() : 0);                        			
+    	    $weight = ((intval($catobj->get_weight())>0) ? $catobj->get_weight() : 0);
     		$weight            = get_lang('TotalWeight').' : '.$weight;
-    		
+
     		$min_certification = (intval($catobj->get_certificate_min_score()>0) ? $catobj->get_certificate_min_score() : 0);
     		$min_certification = get_lang('CertificateMinScore').' : '.$min_certification;
             $edit_icon  = '<a class="right_link" href="gradebook_edit_cat.php?editcat='.$catobj->get_id().'&amp;cidReq='.$catobj->get_course_code().'">'.Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>';
             //$msg = Display::tag('h3', $weight.' - '.$min_certification);
             $msg = Display::tag('h4', $weight.' - '.$min_certification.$edit_icon);
     		//@todo show description
-    		$description       = (($catobj->get_description() == "" || is_null($catobj->get_description())) ? '' : '<strong>'.get_lang('GradebookDescriptionLog').'</strong>'.': '.$catobj->get_description());    				
+    		$description       = (($catobj->get_description() == "" || is_null($catobj->get_description())) ? '' : '<strong>'.get_lang('GradebookDescriptionLog').'</strong>'.': '.$catobj->get_description());
     		Display::display_normal_message($msg, false);
     		if (!empty($description)) {
     		    echo Display::div($description, array());
@@ -561,7 +561,7 @@ class DisplayGradebook
 	function display_reduce_header_gradebook($catobj,$is_course_admin, $is_platform_admin, $simple_search_form, $show_add_qualification = true, $show_add_link = true) {
 		//student
 		if (!$is_course_admin) {
-			$user= get_user_info_from_id(api_get_user_id());
+			$user= api_get_user_info(api_get_user_id());
 			$catcourse= Category :: load($catobj->get_id());
 			$scoredisplay = ScoreDisplay :: instance();
 			$scorecourse = $catcourse[0]->calc_score(api_get_user_id());
@@ -569,7 +569,7 @@ class DisplayGradebook
 			$cattotal = Category :: load(0);
 			$scoretotal= $cattotal[0]->calc_score(api_get_user_id());
 			$scoretotal_display = (isset($scoretotal) ? $scoredisplay->display_score($scoretotal,SCORE_PERCENT) : get_lang('NoResultsAvailable'));
-			$scoreinfo = get_lang('StatsStudent') . ' :<b> '.api_get_person_name($user['firstname'], $user['lastname']).'</b><br />';
+			$scoreinfo = get_lang('StatsStudent') . ' :<b> '.$user['complete_name'].'</b><br />';
 			if ((!$catobj->get_id() == '0') && (!isset ($_GET['studentoverview'])) && (!isset ($_GET['search'])))
 				$scoreinfo.= '<br />'.get_lang('TotalForThisCategory') . ' : <b>' . $scorecourse_display . '</b>';
 			$scoreinfo.= '<br />'.get_lang('Total') . ' : <b>' . $scoretotal_display . '</b>';
@@ -594,7 +594,7 @@ class DisplayGradebook
 	function display_header_user($userid) {
 		$select_cat   = intval($_GET['selectcat']);
 		$user_id      = $userid;
-		$user         = get_user_info_from_id($user_id);
+		$user         = api_get_user_info($user_id);
 
 		$catcourse    = Category :: load($select_cat);
 		$scoredisplay = ScoreDisplay :: instance();
@@ -617,7 +617,7 @@ class DisplayGradebook
 		$item_value = number_format($item_value, 2, '.', ' ');
 		$total_score=array($item_value,$item_total);
 		$scorecourse_display = $scoredisplay->display_score($total_score,SCORE_DIV_PERCENT);
-		
+
 		//$scorecourse_display = (isset($scorecourse) ? $scoredisplay->display_score($scorecourse,SCORE_AVERAGE) : get_lang('NoResultsAvailable'));
 		$cattotal = Category :: load(0);
 		$scoretotal= $cattotal[0]->calc_score($user_id);
@@ -628,21 +628,21 @@ class DisplayGradebook
         //Web path
         $image_path = UserManager::get_user_picture_path_by_id($userid,'web',false,true);
         $image_file = $image_path['dir'].$image_path['file'];
-		$img_attributes= 'src="' . $image_file . '?rand=' . time() . '" ' . 'alt="' . api_get_person_name($user['firstname'], $user['lastname']) . '" ';
+		$img_attributes= 'src="' . $image_file . '?rand=' . time() . '" ' . 'alt="' . $user['complete_name'] . '" ';
 		if ($image_size[0] > 200) {
 		 //limit display width to 200px
  			$img_attributes .= 'width="200" ';
 		}
-		$info = '<div class="row"><div class="span3">';        
+		$info = '<div class="row"><div class="span3">';
         $info .= '<div class="thumbnail"><img ' . $img_attributes . '/></div>';
-        $info .= '</div>';        
+        $info .= '</div>';
         $info .= '<div class="span6">';
 		$info .= get_lang('Name') . ' :  <a target="_blank" href="'.api_get_path(WEB_CODE_PATH).'social/profile.php?u=' . $userid . '"> ' . api_get_person_name($user['firstname'], $user['lastname']) . '</a><br />';
-        
+
 		if (api_get_setting('show_email_addresses') == 'true') {
             $info .= get_lang('Email') . ' : <a href="mailto:' . $user['email'] . '">' . $user['email'] . '</a><br />';
         }
-        
+
 		$info .= get_lang('TotalUser') . ' : <b>' . $scorecourse_display . '</b>';
 		$info .= '</div>';
         $info .= '</div>';
@@ -651,6 +651,6 @@ class DisplayGradebook
 		//$scoreinfo.= '<br />'.get_lang('Total') . ' : <b>' . $scorecourse_display . '</b>';
 
 		//$scoreinfo.= '<br />'.get_lang('Total') . ' : <b>' . $scoretotal_display . '</b>';
-        echo $info;		
+        echo $info;
 	}
 }

+ 119 - 119
main/gradebook/lib/fe/evalform.class.php

@@ -50,7 +50,7 @@ class EvalForm extends FormValidator
 	 * @param method
 	 * @param action
 	 */
-	public function __construct($form_type, $evaluation_object, $result_object, $form_name, $method= 'post', $action= null, $extra1 = null, $extra2 = null) {        
+	public function __construct($form_type, $evaluation_object, $result_object, $form_name, $method= 'post', $action= null, $extra1 = null, $extra2 = null) {
 		parent::__construct($form_name, $method, $action);
 
 		if (isset ($evaluation_object)) {
@@ -62,40 +62,40 @@ class EvalForm extends FormValidator
 		if (isset ($extra1)) {
 			$this->extra = $extra1;
 		}
-        
+
         switch ($form_type) {
             case self :: TYPE_EDIT:
-                $this->build_editing_form();    
+                $this->build_editing_form();
                 break;
             case self :: TYPE_ADD:
-                $this->build_add_form();    
+                $this->build_add_form();
                 break;
             case self :: TYPE_MOVE:
-                $this->build_editing_form();    
+                $this->build_editing_form();
                 break;
             case self :: TYPE_RESULT_ADD:
-                $this->build_result_add_form();    
+                $this->build_result_add_form();
                 break;
             case self :: TYPE_RESULT_EDIT:
-                $this->build_result_edit_form();    
-                break;            
+                $this->build_result_edit_form();
+                break;
             case self :: TYPE_ALL_RESULTS_EDIT:
-                $this->build_all_results_edit_form();    
+                $this->build_all_results_edit_form();
                 break;
             case self :: TYPE_ADD_USERS_TO_EVAL:
-                $this->build_add_user_to_eval();    
-                break;        
+                $this->build_add_user_to_eval();
+                break;
         }
 		$this->setDefaults();
 	}
 	/**
 	 * This form will build a form to add users to an evaluation
 	 */
-	protected function build_add_user_to_eval() {		
+	protected function build_add_user_to_eval() {
 		$this->addElement('header', get_lang('ChooseUser'));
 		$select= $this->addElement('select', 'firstLetterUser', get_lang('FirstLetter'), null, array(
 			'onchange'=> 'document.add_users_to_evaluation.submit()'
-		));		
+		));
 		$select->addOption('','');
 		for ($i = 65; $i <= 90; $i ++) {
 			$letter = chr($i);
@@ -117,7 +117,7 @@ class EvalForm extends FormValidator
 		}
 		$this->addElement('submit', 'submit_button', get_lang('AddUserToEval'));
 	}
-    
+
 	/**
 	 * This function builds a form to edit all results in an evaluation
 	 */
@@ -126,54 +126,54 @@ class EvalForm extends FormValidator
 		$this->addElement('hidden', 'maxvalue', $this->evaluation_object->get_max());
 		$this->addElement('hidden', 'minvalue', 0);
 		$this->addElement('header', get_lang('EditResult'));
-        
-		$renderer =& $this->defaultRenderer();	
-        
+
+		$renderer =& $this->defaultRenderer();
+
         // set new form template
         $form_template = '<form{attributes}>
                     <table class="data_table" border="0" cellpadding="5" cellspacing="5">{content}
-                    </table>		      
-                </form>';        
+                    </table>
+                </form>';
         $renderer->setFormTemplate($form_template);
-	
+
         if (api_is_western_name_order()){
     		$renderer->setHeaderTemplate(
     		   '<tr>
-    		       <th>'.get_lang('OfficialCode').'</th>		
+    		       <th>'.get_lang('OfficialCode').'</th>
     		      <th>'.get_lang('UserName').'</th>
     		      <th>'.get_lang('FirstName').'</th>
-    		      <th>'.get_lang('LastName').'</th>		
+    		      <th>'.get_lang('LastName').'</th>
     		      <th>'.get_lang('Qualify').'</th>
-    		   </tr>'  
+    		   </tr>'
     		);
         } else {
         	$renderer->setHeaderTemplate(
                '<tr>
-                   <th>'.get_lang('OfficialCode').'</th>        
+                   <th>'.get_lang('OfficialCode').'</th>
                   <th>'.get_lang('UserName').'</th>
                   <th>'.get_lang('LastName').'</th>
-                  <th>'.get_lang('FirstName').'</th>     
+                  <th>'.get_lang('FirstName').'</th>
                   <th>'.get_lang('Qualify').'</th>
-               </tr>'  
+               </tr>'
             );
-        }   
+        }
 		$template_submit =  '<tr>
-			       <td colspan="4" ></td>			         
+			       <td colspan="4" ></td>
 			      <td >
 			       {element}
 			         <!-- BEGIN error --><br /><span style="color: #ff0000;font-size:10px">{error}</span><!-- END error -->
 			      </td>
-			   </tr>';	
+			   </tr>';
 
 		$results_and_users = array();
 		foreach ($this->result_object as $result) {
-			$user= get_user_info_from_id($result->get_user_id());
+			$user = api_get_user_info($result->get_user_id());
 			$results_and_users[] = array ('result' => $result, 'user' => $user);
-		}        
+		}
 		usort($results_and_users, array ('EvalForm', 'sort_by_user'));
 
 		$defaults = array();
-		
+
 		foreach ($results_and_users as $result_and_user) {
 			$user = $result_and_user['user'];
 			$result = $result_and_user['result'];
@@ -191,30 +191,30 @@ class EvalForm extends FormValidator
 			$this->addRule(array (
 			'score[' . $result->get_id() . ']', 'minvalue'), get_lang('UnderMin'), 'compare', '>=');
 			$defaults['score[' . $result->get_id() . ']'] = $result->get_score();
-			
+
             if (api_is_western_name_order() ) {
             	$user_info = '<td align="left" >'.$user['firstname'].'</td>';
                 $user_info .= '<td align="left" >'.$user['lastname'].'</td>';
             } else {
                 $user_info = '<td align="left" >'.$user['lastname'].'</td>';
-            	$user_info .= '<td align="left" >'.$user['firstname'].'</td>';                
+            	$user_info .= '<td align="left" >'.$user['firstname'].'</td>';
             }
-			
+
 			$template =  '<tr>
 		      <td align="left" >'.$user['official_code'].'</td>
-		      <td align="left" >'.$user['username'].'</td>		      
+		      <td align="left" >'.$user['username'].'</td>
 		      '.$user_info.'
 		       <td align="left">{element} / '.$this->evaluation_object->get_max().'
 		         <!-- BEGIN error --><br /><span style="color: #ff0000;font-size:10px">{error}</span><!-- END error -->
 		      </td>
-		   </tr>';	
-		   $renderer->setElementTemplate($template,'score[' . $result->get_id() . ']');		   
+		   </tr>';
+		   $renderer->setElementTemplate($template,'score[' . $result->get_id() . ']');
 		}
 		$this->setDefaults($defaults);
 		$this->addElement('style_submit_button', 'submit',get_lang('EditResult'),'class="save"');
 		$renderer->setElementTemplate($template_submit,'submit');
 	}
-    
+
 	/**
 	 * This function builds a form to move an item to another category
 	 *
@@ -234,20 +234,20 @@ class EvalForm extends FormValidator
 		}
 		$this->addElement('style_submit_button' , 'submit', get_lang('Ok'),'class="save"');
 	}
-    
+
 	/**
 	 * Builds a result form containing inputs for all students with a given course_code
 	 */
 	protected function build_result_add_form() {
-        $renderer =& $this->defaultRenderer();        
+        $renderer =& $this->defaultRenderer();
         $renderer->setFormTemplate(
 		   '<form{attributes}>
 		      <table class="data_table">
               {content}
-		      </table>		      
+		      </table>
 		   </form>'
-		);        
-        
+		);
+
 		$tblusers = get_users_in_course($this->evaluation_object->get_course_code());
 		$nr_users = 0;
 		//extra field for check on maxvalue
@@ -255,51 +255,51 @@ class EvalForm extends FormValidator
 		$this->addElement('hidden', 'minvalue', 0);
 		$this->addElement('header', get_lang('AddResult'));
 
-        if (api_is_western_name_order()){   
+        if (api_is_western_name_order()){
             $renderer->setHeaderTemplate(
                '<tr>
-                   <th>'.get_lang('OfficialCode').'</th>        
+                   <th>'.get_lang('OfficialCode').'</th>
                   <th>'.get_lang('UserName').'</th>
                   <th>'.get_lang('FirstName').'</th>
-                  <th>'.get_lang('LastName').'</th>     
+                  <th>'.get_lang('LastName').'</th>
                   <th>'.get_lang('Qualify').'</th>
-               </tr>'  
+               </tr>'
             );
         } else {
             $renderer->setHeaderTemplate(
                '<tr>
-                   <th>'.get_lang('OfficialCode').'</th>        
+                   <th>'.get_lang('OfficialCode').'</th>
                   <th>'.get_lang('UserName').'</th>
                   <th>'.get_lang('LastName').'</th>
-                  <th>'.get_lang('FirstName').'</th>     
+                  <th>'.get_lang('FirstName').'</th>
                   <th>'.get_lang('Qualify').'</th>
-               </tr>'  
+               </tr>'
             );
-        }	   
-        
+        }
+
 		foreach ($tblusers as $user) {
-            
+
             $element_name = 'score['.$user[0].']';
-            			
+
 			//user_id, user.username, lastname, firstname
 			$this->add_textfield($element_name,
 								 $this->build_stud_label($user[0], $user[1], $user[2], $user[3]),
 								 false,
 								 array ('class' => 'span1','maxlength' => 5));
-            
+
 			$this->addRule($element_name, get_lang('OnlyNumbers'), 'numeric');
 			$this->addRule(array($element_name,'maxvalue'), get_lang('OverMax'), 'compare', '<=');
-			$this->addRule(array($element_name,'minvalue'), get_lang('UnderMin'), 'compare', '>=');            
-            
+			$this->addRule(array($element_name,'minvalue'), get_lang('UnderMin'), 'compare', '>=');
+
             if (api_is_western_name_order() ) {
                 $user_info = '<td align="left" >'.$user[3].'</td>';
                 $user_info .= '<td align="left" >'.$user[2].'</td>';
             } else {
                 $user_info = '<td align="left" >'.$user[2].'</td>';
-                $user_info .= '<td align="left" >'.$user[3].'</td>';                
+                $user_info .= '<td align="left" >'.$user[3].'</td>';
             }
-			$nr_users++;           
-                   
+			$nr_users++;
+
             $template =  '<tr>
 		      <td align="left" >'.$user[4].'</td>
 		      <td align="left" >'.$user[1].'</td>
@@ -307,23 +307,23 @@ class EvalForm extends FormValidator
 		       <td align="left">{element} / '.$this->evaluation_object->get_max().'
 		         <!-- BEGIN error --><br /><span style="color: #ff0000;font-size:10px">{error}</span><!-- END error -->
 		      </td>
-            </tr>';  
+            </tr>';
 			$renderer->setElementTemplate($template, $element_name);
-		}		
+		}
 		$this->addElement('hidden', 'nr_users', $nr_users);
-		$this->addElement('hidden', 'evaluation_id', $this->result_object->get_evaluation_id());		
-		$this->addElement('style_submit_button', 'submit', get_lang('AddResult'),'class="save"');	
-        
+		$this->addElement('hidden', 'evaluation_id', $this->result_object->get_evaluation_id());
+		$this->addElement('style_submit_button', 'submit', get_lang('AddResult'),'class="save"');
+
         $template_submit =  '<tr>
-                <td colspan="4" ></td>			         
+                <td colspan="4" ></td>
                 <td >
                 {element}
                     <!-- BEGIN error --><br /><span style="color: #ff0000;font-size:10px">{error}</span><!-- END error -->
                 </td>
-            </tr>';	
-		$renderer->setElementTemplate($template_submit, 'submit');           
+            </tr>';
+		$renderer->setElementTemplate($template_submit, 'submit');
 	}
-    
+
 	/**
 	 * Builds a form to edit a result
 	 */
@@ -336,19 +336,19 @@ class EvalForm extends FormValidator
 		$renderer =& $this->defaultRenderer();
 		$renderer->setElementTemplate('<span>{element}</span> ');
 		$this->addElement('label', get_lang('User'), $userinfo['complete_name']);
-        
+
 		$this->add_textfield('score', array(get_lang('Score'), null, '/ '.$this->evaluation_object->get_max()), false, array (
 			'size' => '4',
             'class' => 'span1',
 			'maxlength' => '5'
-		));		
+		));
 
 /*		$this->add_textfield('maximum', null, false, array (
 			'size' => '4',
 			'maxlength' => '5',
 			'disabled' => 'disabled'
 		));*/
-        
+
 		$this->addElement('style_submit_button', 'submit', get_lang('Edit'),'class="save"');
 		$this->addElement('hidden', 'minvalue', 0);
 		$this->addElement('hidden', 'hid_user_id', $this->result_object->get_user_id());
@@ -367,8 +367,8 @@ class EvalForm extends FormValidator
 	 * Builds a form to add an evaluation
 	 */
 	protected function build_add_form() {
-		$this->setDefaults(array (	'hid_user_id' => $this->evaluation_object->get_user_id(), 
-									'hid_category_id' => $this->evaluation_object->get_category_id(), 
+		$this->setDefaults(array (	'hid_user_id' => $this->evaluation_object->get_user_id(),
+									'hid_category_id' => $this->evaluation_object->get_category_id(),
 									'hid_course_code' => $this->evaluation_object->get_course_code(), 'created_at' => api_get_utc_datetime()));
 		$this->build_basic_form(0);
 		if ($this->evaluation_object->get_course_code() == null) {
@@ -378,76 +378,76 @@ class EvalForm extends FormValidator
 		}
 		$this->addElement('style_submit_button', 'submit', get_lang('AddAssessment'),'class="add"');
 	}
-    
+
 	/**
 	 * Builds a form to edit an evaluation
 	 */
-	protected function build_editing_form() {        
+	protected function build_editing_form() {
         $parent_cat = Category :: load($this->evaluation_object->get_category_id());
         if ($parent_cat[0]->get_parent_id() == 0) {
-            $weight_mask = $this->evaluation_object->get_weight();            
+            $weight_mask = $this->evaluation_object->get_weight();
         } else {
             $cat = Category :: load($parent_cat[0]->get_parent_id());
-            $global_weight = $cat[0]->get_weight();                
+            $global_weight = $cat[0]->get_weight();
             $weight_mask = $global_weight*$this->evaluation_object->get_weight()/$parent_cat[0]->get_weight() ;
         }
         $weight_mask = $this->evaluation_object->get_weight();
-            
-		$this->setDefaults(array (	'hid_id'            => $this->evaluation_object->get_id(), 
-									'name'              => $this->evaluation_object->get_name(), 
-									'description'       => $this->evaluation_object->get_description(), 
-									'hid_user_id'       => $this->evaluation_object->get_user_id(), 
-									'hid_course_code'   => $this->evaluation_object->get_course_code(), 
-									'hid_category_id'   => $this->evaluation_object->get_category_id(), 
-									'created_at'        => api_get_utc_datetime($this->evaluation_object->get_date()), 
+
+		$this->setDefaults(array (	'hid_id'            => $this->evaluation_object->get_id(),
+									'name'              => $this->evaluation_object->get_name(),
+									'description'       => $this->evaluation_object->get_description(),
+									'hid_user_id'       => $this->evaluation_object->get_user_id(),
+									'hid_course_code'   => $this->evaluation_object->get_course_code(),
+									'hid_category_id'   => $this->evaluation_object->get_category_id(),
+									'created_at'        => api_get_utc_datetime($this->evaluation_object->get_date()),
 									'weight'            => $weight,
                                     'weight_mask'       => $weight_mask,
-                                    'max'               => $this->evaluation_object->get_max(), 
+                                    'max'               => $this->evaluation_object->get_max(),
                                     'visible'           => $this->evaluation_object->is_visible()));
 		$id_current=isset($this->id)?$this->id :null;
 		$this->addElement('hidden', 'hid_id', $id_current);
 		$this->build_basic_form(1);
 		$this->addElement('style_submit_button', 'submit', get_lang('ModifyEvaluation'),'class="save"');
 	}
-    
+
 	/**
 	 * Builds a basic form that is used in add and edit
 	 */
 	private function build_basic_form($edit= 0) {
 		$form_title = get_lang('NewEvaluation');
-        
+
 		if ($_GET['editeval']==1) {
 			$form_title = get_lang('EditEvaluation');
 		}
 
 		$this->addElement('header', $form_title);
 		$this->addElement('hidden', 'zero', 0);
-		$this->addElement('hidden', 'hid_user_id');		
+		$this->addElement('hidden', 'hid_user_id');
 		$this->addElement('hidden', 'hid_course_code');
-        
+
 		$this->add_textfield('name', get_lang('EvaluationName'), true, array (
 			'class'         => 'span3',
 			'maxlength'     => '50',
 			'id'            => 'evaluation_title'
 		));
-        
+
         $cat_id = $this->evaluation_object->get_category_id();
-        
-        $session_id  = api_get_session_id();        
+
+        $session_id  = api_get_session_id();
         $course_code = api_get_course_id();
-        $all_categories = Category :: load(null, null, $course_code, null, null, $session_id, false);        
-                
+        $all_categories = Category :: load(null, null, $course_code, null, null, $session_id, false);
+
         if (count($all_categories) == 1) {
             $this->addElement('hidden', 'hid_category_id', $cat_id);
         } else {
             $select_gradebook = $this->addElement('select', 'hid_category_id', get_lang('SelectGradebook'), array(), array('id' => 'hid_category_id'));
             $this->addRule('hid_category_id', get_lang('ThisFieldIsRequired'), 'nonzero');
-        
+
             $default_weight = 0;
             if (!empty($all_categories)) {
                 foreach ($all_categories as $my_cat) {
-                    if ($my_cat->get_course_code() == api_get_course_id()) {         
-                        $grade_model_id = $my_cat->get_grade_model_id();                     
+                    if ($my_cat->get_course_code() == api_get_course_id()) {
+                        $grade_model_id = $my_cat->get_grade_model_id();
                         if (empty($grade_model_id)) {
                             if ($my_cat->get_parent_id() == 0) {
                                 $default_weight = $my_cat->get_weight();
@@ -461,26 +461,26 @@ class EvalForm extends FormValidator
                             $select_gradebook->addoption(get_lang('Select'), 0);
                         }
                         if ($this->evaluation_object->get_category_id() == $my_cat->get_id()) {
-                            $default_weight = $my_cat->get_weight();                        
-                        }                                        
-                    }           
+                            $default_weight = $my_cat->get_weight();
+                        }
+                    }
                 }
             }
         }
-        
+
 		$this->add_textfield('weight_mask', array(get_lang('Weight'), null, ' [0 .. '.$all_categories[0]->get_weight().'] '), true, array (
 			'size' => '4',
 			'maxlength' => '5',
             'class' => 'span1'
 		));
-        
+
         /*$this->add_textfield('weight', array(null, null, '/ <span id="max_weight">'.$default_weight.'</span>'), true, array (
             	'size' => '4',
 			'maxlength' => '5',
             'class' => 'span1'
 		));*/
-        
-        
+
+
 		if ($edit) {
 			if (!$this->evaluation_object->has_results()) {
 				$this->add_textfield('max', get_lang('QualificationNumeric'), true, array (
@@ -492,7 +492,7 @@ class EvalForm extends FormValidator
 					'class' => 'span1',
 					'maxlength' => '5',
 					'disabled' => 'disabled'
-				));				
+				));
 			}
 		} else {
 			$this->add_textfield('max', get_lang('QualificationNumeric'), true, array (
@@ -501,34 +501,34 @@ class EvalForm extends FormValidator
 			));
             $default_max = api_get_setting('gradebook_default_weight');
             $defaults['max'] = isset($default_max) ?  $default_max : 100;
-            $this->setDefaults($defaults);            
-		}       
-        
+            $this->setDefaults($defaults);
+		}
+
 		$this->addElement('textarea', 'description', get_lang('Description'), array (
 			'rows' => '3',
 			'class' => 'span3',
-		));       
-        
+		));
+
         $this->addRule('hid_category_id', get_lang('ThisFieldIsRequired'), 'required');
 		$this->addElement('checkbox', 'visible', null, get_lang('Visible'));
 		$this->addRule('weight_mask', get_lang('OnlyNumbers'), 'numeric');
 		$this->addRule(array('weight_mask', 'zero'), get_lang('NegativeValue'), 'compare', '>=');
 		$this->addRule('max', get_lang('OnlyNumbers'), 'numeric');
 		$this->addRule(array('max', 'zero'), get_lang('NegativeValue'), 'compare', '>=');
-        
-        $setting = api_get_setting('tool_visible_by_default_at_creation');   
+
+        $setting = api_get_setting('tool_visible_by_default_at_creation');
         $visibility_default = 1;
-        if (isset($setting['gradebook']) && $setting['gradebook'] == 'false') {            
+        if (isset($setting['gradebook']) && $setting['gradebook'] == 'false') {
             $visibility_default = 0;
-        }            
+        }
 		$this->setDefaults(array('visible' => $visibility_default));
-        
+
 	}
 
 	function display() {
 		parent :: display();
 	}
-    
+
 	function setDefaults($defaults= array(), $filter = null) {
 		parent :: setDefaults($defaults, $filter);
 	}

+ 8 - 22
main/gradebook/lib/gradebook_functions_users.inc.php

@@ -26,12 +26,12 @@ function get_users_in_course($course_id) {
 			 	AND scru.status=0
 			 	AND scru.course_code='$course_id' AND id_session ='$current_session' $order_clause ";
 	} else {
-		$sql = 'SELECT user.user_id, user.username, lastname, firstname, official_code 
-                FROM '.$tbl_course_user.' as course_rel_user, '.$tbl_user.' as user 
-                WHERE   course_rel_user.user_id=user.user_id AND 
-                        course_rel_user.status='.STUDENT.' AND 
+		$sql = 'SELECT user.user_id, user.username, lastname, firstname, official_code
+                FROM '.$tbl_course_user.' as course_rel_user, '.$tbl_user.' as user
+                WHERE   course_rel_user.user_id=user.user_id AND
+                        course_rel_user.status='.STUDENT.' AND
                         course_rel_user.course_code = "'.$course_id.'" '.$order_clause;
-	}    
+	}
 	$result = Database::query($sql);
 	return get_user_array_from_sql_result($result);
 }
@@ -69,15 +69,15 @@ function get_all_users ($evals = array(), $links = array()) {
 			$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
 			$tbl_res = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 
-			$sql = 'SELECT user.user_id,lastname, firstname, user.official_code 
-                    FROM '.$tbl_res.' as res, '.$tbl_user.' as user 
+			$sql = 'SELECT user.user_id,lastname, firstname, user.official_code
+                    FROM '.$tbl_res.' as res, '.$tbl_user.' as user
                     WHERE res.evaluation_id = '.intval($eval->get_id())
 					.' AND res.user_id = user.user_id';
 			$result = Database::query($sql);
 			$users = array_merge($users, get_user_array_from_sql_result($result));
 		}
 	}
-    
+
 	foreach ($links as $link) {
 		// links are always in a course
 		$coursecode = $link->get_course_code();
@@ -119,18 +119,4 @@ function find_students($mask= '') {
 	$result= Database::query($sql);
 	$db_users= Database::store_result($result);
 	return $db_users;
-}
-
-/**
- * Get user information from a given id
- * @param int $userid The userid
- * @deprecated replace this function with the api_get_user_info()
- * @return array All user information as an associative array
- */
-function get_user_info_from_id($userid) {
-	$user_table= Database :: get_main_table(TABLE_MAIN_USER);
-	$sql= 'SELECT * FROM ' . $user_table . ' WHERE user_id=' . intval($userid);
-	$res= Database::query($sql);
-	$user= Database::fetch_array($res, 'ASSOC');
-	return $user;
 }

+ 11 - 11
main/gradebook/lib/results_data_generator.class.php

@@ -73,7 +73,7 @@ class ResultsDataGenerator
 		$table = array();
 		foreach($this->results as $result) {
 			$user = array();
-			$info = get_user_info_from_id($result->get_user_id());
+			$info = api_get_user_info($result->get_user_id());
 			$user['id'] = $result->get_user_id();
 			if ($pdf){
 				$user['username'] = $info['username'];
@@ -87,12 +87,12 @@ class ResultsDataGenerator
 				$user['score'] = $this->get_score_display($result->get_score(),true, $ignore_score_color);
 			}
             $user['percentage_score'] = intval($scoredisplay->display_score(array($result->get_score(), $this->evaluation->get_max()), SCORE_PERCENT, SCORE_BOTH, true));
-			if ($pdf && $number_decimals == null){				
+			if ($pdf && $number_decimals == null){
 				$user['scoreletter'] = $result->get_score();
-			}			
-			if ($scoredisplay->is_custom()) {				
-				$user['display'] = $this->get_score_display($result->get_score(), false, $ignore_score_color);				
-			}			
+			}
+			if ($scoredisplay->is_custom()) {
+				$user['display'] = $this->get_score_display($result->get_score(), false, $ignore_score_color);
+			}
 			$table[] = $user;
 		}
 
@@ -102,7 +102,7 @@ class ResultsDataGenerator
 			usort($table, array('ResultsDataGenerator', 'sort_by_last_name'));
 		} elseif ($sorting & self :: RDG_SORT_FIRSTNAME) {
 			usort($table, array('ResultsDataGenerator', 'sort_by_first_name'));
-		} elseif ($sorting & self :: RDG_SORT_SCORE) {            
+		} elseif ($sorting & self :: RDG_SORT_SCORE) {
 			usort($table, array('ResultsDataGenerator', 'sort_by_score'));
 		} elseif ($sorting & self :: RDG_SORT_MASK) {
 			usort($table, array('ResultsDataGenerator', 'sort_by_mask'));
@@ -110,7 +110,7 @@ class ResultsDataGenerator
 		if ($sorting & self :: RDG_SORT_DESC) {
 			$table = array_reverse($table);
 		}
-		$return = array_slice($table, $start, $count);		
+		$return = array_slice($table, $start, $count);
 		return $return;
 
 	}
@@ -120,11 +120,11 @@ class ResultsDataGenerator
 			$scoredisplay = ScoreDisplay :: instance();
 			$type = SCORE_CUSTOM;
 			if ($realscore === true) {
-			    $type = SCORE_DIV_PERCENT ; 
-			}			
+			    $type = SCORE_DIV_PERCENT ;
+			}
 			return $scoredisplay->display_score(array($score, $this->evaluation->get_max()), $type, SCORE_BOTH, $ignore_score_color);
         }
-        return '';		
+        return '';
 	}
 
 	// Sort functions - used internally

+ 9 - 9
main/gradebook/user_stats.php

@@ -48,15 +48,15 @@ $user_table= new UserTable($my_user_id, $allevals, $alllinks, $addparams);
 
 if (isset ($_GET['exportpdf'])) {
 	$datagen       = new UserDataGenerator($my_user_id, $allevals, $alllinks);
-	$data_array    = $datagen->get_data(UserDataGenerator :: UDG_SORT_NAME, 0, null, true);    
+	$data_array    = $datagen->get_data(UserDataGenerator :: UDG_SORT_NAME, 0, null, true);
 	$newarray      = array ();
-	$displayscore  = Scoredisplay :: instance();	
-	foreach ($data_array as $data) {        
+	$displayscore  = Scoredisplay :: instance();
+	foreach ($data_array as $data) {
         $newarray[] = array_slice($data, 1);
 	}
-	$userinfo = get_user_info_from_id($my_user_id);    
-	$html .= get_lang('Results').' : '.api_get_person_name($userinfo['firstname'], $userinfo['lastname']).' ('. api_convert_and_format_date(null, DATE_FORMAT_SHORT). ' ' . api_convert_and_format_date(null, TIME_NO_SEC_FORMAT) .')';
-	
+	$userinfo = api_get_user_info($my_user_id);
+	$html .= get_lang('Results').' : '.$userinfo['complete_name'].' ('. api_convert_and_format_date(null, DATE_FORMAT_SHORT). ' ' . api_convert_and_format_date(null, TIME_NO_SEC_FORMAT) .')';
+
 	if ($displayscore->is_custom()) {
 		$header_names= array (
             get_lang('Evaluation'), get_lang('Course'), get_lang('Category'), get_lang('EvaluationAverage'),get_lang('Result'),get_lang('Display'));
@@ -64,7 +64,7 @@ if (isset ($_GET['exportpdf'])) {
 		$header_names= array (
 			get_lang('Evaluation'), get_lang('Course'), get_lang('Category'), get_lang('EvaluationAverage'),get_lang('Result'));
 	}
-    
+
     $table = new HTML_Table(array('class' => 'data_table'));
     $row = 0;
     $column = 0;
@@ -81,9 +81,9 @@ if (isset ($_GET['exportpdf'])) {
             $column++;
             $row++;
         }
-    }    
+    }
     $html .= $table->toHtml();
-    
+
     require_once api_get_path(LIBRARY_PATH).'pdf.lib.php';
     $pdf = new PDF();
     $pdf->content_to_pdf($html);

+ 17 - 17
main/group/group.php

@@ -44,8 +44,8 @@ if (api_get_setting('allow_group_categories') == 'false') {
 	$res = Database::query($sql);
 	$num = Database::num_rows($res);
 	if ($num == 0) {
-		$sql = "INSERT INTO ".$cat_table." ( c_id, id , title , description , forum_state, wiki_state, max_student, self_reg_allowed, self_unreg_allowed, groups_per_user, display_order) 
-		VALUES ($course_id, '2', '".lang2db(get_lang('DefaultGroupCategory'))."', '', '1', '1', '8', '0', '0', '0', '0');";
+		$sql = "INSERT INTO ".$cat_table." ( c_id, id , title , description , forum_state, wiki_state, max_student, self_reg_allowed, self_unreg_allowed, groups_per_user, display_order)
+		VALUES ($course_id, '2', '".Database::escape_string(get_lang('DefaultGroupCategory'))."', '', '1', '1', '8', '0', '0', '0', '0');";
 		Database::query ($sql);
 	}
 }
@@ -123,7 +123,7 @@ if (api_is_allowed_to_edit(false, true)) {
 				}
 				break;
 			case 'fill_selected' :
-				if (is_array($_POST['group'])) {                    
+				if (is_array($_POST['group'])) {
                     GroupManager :: fill_groups($my_group);
                     Display :: display_confirmation_message(get_lang('SelectedGroupsFilled'));
 				}
@@ -146,7 +146,7 @@ if (api_is_allowed_to_edit(false, true)) {
 				GroupManager :: unsubscribe_all_users($my_get_id);
 				Display :: display_confirmation_message(get_lang('GroupEmptied'));
 				break;
-			case 'fill_one':                
+			case 'fill_one':
 				GroupManager :: fill_groups($my_get_id);
 				Display :: display_confirmation_message(get_lang('GroupFilledGroups'));
 				break;
@@ -161,21 +161,21 @@ if (api_is_allowed_to_edit(false, true)) {
 echo '<div class="actions">';
 if (api_is_allowed_to_edit(false, true)) {
 	echo '<a href="group_creation.php?'.api_get_cidreq().'">'.Display::return_icon('new_group.png', get_lang('NewGroupCreate'),'',ICON_SIZE_MEDIUM).'</a>';
-	if (CourseManager::count_rows_course_table(Database::get_course_table(TABLE_GROUP),api_get_session_id(), api_get_course_int_id()) > 0) {		
+	if (CourseManager::count_rows_course_table(Database::get_course_table(TABLE_GROUP),api_get_session_id(), api_get_course_int_id()) > 0) {
 		echo '<a href="group_overview.php?'.api_get_cidreq().'">'.Display::return_icon('group_summary.png', get_lang('GroupOverview'),'',ICON_SIZE_MEDIUM).'</a>';
 	}
 	if (api_get_setting('allow_group_categories') == 'true') {
 		echo '<a href="group_category.php?'.api_get_cidreq().'&action=add_category">'.Display::return_icon('new_folder.png', get_lang('AddCategory'),'',ICON_SIZE_MEDIUM).'</a>';
 	} else {
         echo '<a href="group_category.php?'.api_get_cidreq().'&id=2">'.Display::return_icon('settings.png', get_lang('PropModify'),'',ICON_SIZE_MEDIUM).'</a>';
-	}	
-	echo  '<a href="group_overview.php?'.api_get_cidreq().'&action=export&type=xls">'.Display::return_icon('export_excel.png', get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a>';	
-	echo '<a href="../user/user.php?'.api_get_cidreq().'">'.Display::return_icon('user.png', get_lang('GoTo').' '.get_lang('Users'),'',ICON_SIZE_MEDIUM).'</a>';	
+	}
+	echo  '<a href="group_overview.php?'.api_get_cidreq().'&action=export&type=xls">'.Display::return_icon('export_excel.png', get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a>';
+	echo '<a href="../user/user.php?'.api_get_cidreq().'">'.Display::return_icon('user.png', get_lang('GoTo').' '.get_lang('Users'),'',ICON_SIZE_MEDIUM).'</a>';
 }
 
 $group_cats = GroupManager :: get_categories(api_get_course_id());
 
-if (api_get_setting('allow_group_categories') == 'true' && count($group_cats) > 1) {	
+if (api_get_setting('allow_group_categories') == 'true' && count($group_cats) > 1) {
 	echo ' <a href="?'.api_get_cidreq().'&show_all=1">'.Display::return_icon('group.png',get_lang('ShowAll'),'',ICON_SIZE_MEDIUM).'</a>';
 }
 echo '</div>';
@@ -188,15 +188,15 @@ if (api_get_setting('allow_group_categories') == 'true') {
     foreach ($group_cats as $index => $category) {
         if (isset ($_GET['show_all']) || (isset ($_GET['category']) && $_GET['category'] == $category['id'])) {
             //echo '<img src="../img/folder_group_category.gif" alt=""/>';
-            //echo '<a href="group.php?'.api_get_cidreq().'&origin='.Security::remove_XSS($_GET['origin']).'">'.$category['title'].'</a>';            
+            //echo '<a href="group.php?'.api_get_cidreq().'&origin='.Security::remove_XSS($_GET['origin']).'">'.$category['title'].'</a>';
         } else {
             //echo '<img src="../img/folder_document.gif" alt=""/>';
             //echo '<a href="group.php?'.api_get_cidreq().'&origin='.Security::remove_XSS($_GET['origin']).'&amp;category='.$category['id'].'">'.$category['title'].'</a>';
-            //echo Display::page_header($category['title']);            
+            //echo Display::page_header($category['title']);
         }
         $group_list = GroupManager :: get_group_list($category['id']);
         $label = Display::label(count($group_list).' '.get_lang('ExistingGroups'), 'info');
-        
+
         $actions = null;
         if (api_is_allowed_to_edit(false, true)) {
             $actions .= '<a href="group_category.php?'.api_get_cidreq().'&id='.$category['id'].'"  title="'.get_lang('Edit').'">'.Display::return_icon('edit.png', get_lang('EditGroup'),'',ICON_SIZE_SMALL).'</a>';
@@ -208,15 +208,15 @@ if (api_get_setting('allow_group_categories') == 'true') {
                 $actions .= ' <a href="group.php?'.api_get_cidreq().'&action=swap_cat_order&amp;id1='.$category['id'].'&amp;id2='.$group_cats[$index +1]['id'].'">'.Display::return_icon('down.png','&nbsp;','',ICON_SIZE_SMALL).'</a>';
             }
         }
-        
+
         echo Display::page_header($category['title'].' '. $label.' '.$actions);
-        
+
         echo '<p style="margin: 0px;margin-left: 50px;">'.$category['description'].'</p><p/>';
-        
-        GroupManager ::process_groups($group_list, $category['id']);        
+
+        GroupManager ::process_groups($group_list, $category['id']);
     }
 } else {
-    $group_list = GroupManager :: get_group_list();            
+    $group_list = GroupManager :: get_group_list();
     GroupManager ::process_groups($group_list);
 }
 

+ 4 - 4
main/group/group_space.php

@@ -289,7 +289,7 @@ if (count($tutors) == 0) {
 } else {
     isset($origin) ? $my_origin = $origin : $my_origin = '';
     foreach ($tutors as $index => $tutor) {
-        $tab_user_info = Database::get_user_info_from_id($tutor['user_id']);
+        $tab_user_info = api_get_user_info($tutor['user_id']);
         $username = api_htmlentities(sprintf(get_lang('LoginX'), $tab_user_info['username']), ENT_QUOTES);
         $image_path = UserManager::get_user_picture_path_by_id($tutor['user_id'], 'web', false, true);
         $image_repository = $image_path['dir'];
@@ -463,11 +463,11 @@ function email_filter($email)
 function user_icon_filter($user_id)
 {
     global $origin;
-    $userinfo = Database::get_user_info_from_id($user_id);
+    $userinfo = api_get_user_info($user_id);
     $image_path = UserManager::get_user_picture_path_by_id($user_id, 'web', false, true);
     $image_repository = $image_path['dir'];
     $existing_image = $image_path['file'];
-    $photo = '<center><img src="'.$image_repository.$existing_image.'" alt="'.api_get_person_name($userinfo['firstname'], $userinfo['lastname']).'"  width="22" height="22" title="'.api_get_person_name($userinfo['firstname'], $userinfo['lastname']).'" /></center>';
+    $photo = '<center><img src="'.$image_repository.$existing_image.'" alt="'.$userinfo['complete_name'].'"  width="22" height="22" title="'.$userinfo['complete_name'].'" /></center>';
     return '<a href="../user/userInfo.php?origin='.$origin.'&amp;uInfo='.$user_id.'">'.$photo;
 }
 
@@ -484,7 +484,7 @@ function user_icon_filter($user_id)
 function user_name_filter($name, $url_params, $row)
 {
     global $origin;
-    $tab_user_info = Database::get_user_info_from_id($row[0]);
+    $tab_user_info = api_get_user_info($row[0]);
     $username = api_htmlentities(sprintf(get_lang('LoginX'), $tab_user_info['username']), ENT_QUOTES);
     return '<a href="../user/userInfo.php?uInfo='.$row[0].'&amp;'.$url_params.'" title="'.$username.'">'.$name.'</a>';
 }

+ 172 - 172
main/inc/ajax/course_home.ajax.php

@@ -12,21 +12,21 @@ switch ($action) {
 		require_once '../global.inc.php';
         $course_id = api_get_course_int_id();
 		if (api_is_allowed_to_edit(null,true)) {
-			$tool_table = Database::get_course_table(TABLE_TOOL_LIST);			
+			$tool_table = Database::get_course_table(TABLE_TOOL_LIST);
 			$tool_info = api_get_tool_information($_GET["id"]);
 			$tool_visibility   = $tool_info['visibility'];
 			$tool_image        = $tool_info['image'];
-			if (api_get_setting('homepage_view') != 'activity_big') {			                    
+			if (api_get_setting('homepage_view') != 'activity_big') {
                 $new_image        = Display::return_icon(str_replace('.gif','_na.gif',$tool_image), null, null, null, null, true);
                 $tool_image       = Display::return_icon($tool_image, null, null, null, null, true);
 			} else {
 			    $tool_image        = $tool_info['image'];
 			    $tool_image        = (substr($tool_info['image'], 0, strpos($tool_info['image'], '.'))).'.png';
-                $new_image         = str_replace('.png','_na.png',$tool_image);  
+                $new_image         = str_replace('.png','_na.png',$tool_image);
                 $new_image         = api_get_path(WEB_IMG_PATH).'icons/64/'.$new_image;
-                $tool_image        = api_get_path(WEB_IMG_PATH).'icons/64/'.$tool_image;            
+                $tool_image        = api_get_path(WEB_IMG_PATH).'icons/64/'.$tool_image;
 			}
-			
+
 			$requested_image   = ($tool_visibility == 0 ) ? $tool_image : $new_image;
 			$requested_clase   = ($tool_visibility == 0 ) ? 'visible' : 'invisible';
 			$requested_message = ($tool_visibility == 0 ) ? 'is_active' : 'is_inactive';
@@ -56,7 +56,7 @@ switch ($action) {
 
 				$sql="UPDATE $tool_table SET visibility=$requested_visible WHERE c_id = $course_id AND id='".intval($_GET['id'])."'";
 				Database::query($sql);
-			}	
+			}
 			$response_data = array(
 				'image'   => $requested_image,
 				'tclass'  => $requested_clase,
@@ -66,74 +66,74 @@ switch ($action) {
 			echo json_encode($response_data);
         }
         break;
-	
+
 	case 'show_course_information' :
-	
+
 		$language_file = array('course_description');
 		require_once '../global.inc.php';
-		
-		// Get the name of the database course.		
+
+		// Get the name of the database course.
 		$tbl_course_description = Database::get_course_table(TABLE_COURSE_DESCRIPTION);
-		
+
 		$course_info = api_get_course_info($_GET['code']);
-		
+
 		if ($course_info['visibility'] != COURSE_VISIBILITY_OPEN_WORLD) {
 			if (api_is_anonymous()) {
 				exit;
-			}		
-		}		
+			}
+		}
 		echo Display::tag('h2', $course_info['name']);
 		echo '<br />';
-	
+
 		$sql = "SELECT * FROM $tbl_course_description WHERE c_id = ".$course_info['real_id']." AND session_id = 0 ORDER BY id";
 		$result = Database::query($sql);
-		if (Database::num_rows($result) > 0 ) {		        
+		if (Database::num_rows($result) > 0 ) {
 		    while ($description = Database::fetch_object($result)) {
 			    $descriptions[$description->id] = $description;
-		    }		    
+		    }
             // Function that displays the details of the course description in html.
 		    echo CourseManager::get_details_course_description_html($descriptions, api_get_system_encoding(), false);
 		} else {
 		    echo get_lang('NoDescription');
-		}		
-	    break;    
-    /** 
+		}
+	    break;
+    /**
      * @todo this functions need to belong to a class or a special wrapper to process the AJAX petitions from the jqgrid
      */
-    case 'session_courses_lp_default':        
-        
-        require_once '../global.inc.php';                
-        require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';        
-        
+    case 'session_courses_lp_default':
+
+        require_once '../global.inc.php';
+        require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
+
         $page  = intval($_REQUEST['page']);     //page
         $limit = intval($_REQUEST['rows']);     // quantity of rows
-        $sidx  = $_REQUEST['sidx'];    //index to filter         
+        $sidx  = $_REQUEST['sidx'];    //index to filter
         $sord  = $_REQUEST['sord'];    //asc or desc
         if (!in_array($sord, array('asc','desc'))) {
         	$sord = 'desc';
-        }        
+        }
         $session_id  = intval($_REQUEST['session_id']);
         $course_id   = intval($_REQUEST['course_id']);
-        
+
         //Filter users that does not belong to the session
         if (!api_is_platform_admin()) {
             $new_session_list = UserManager::get_personal_session_course_list(api_get_user_id());
             $my_session_list  = array();
             foreach($new_session_list as $item) {
-                if (!empty($item['id_session'])) 
+                if (!empty($item['id_session']))
                     $my_session_list[] = $item['id_session'];
-            }        
+            }
             if (!in_array($session_id, $my_session_list)) {
             	break;
             }
-        }        
-                        
+        }
+
         if(!$sidx) $sidx = 1;
-        
-        $start = $limit*$page - $limit;         
-        $course_list    = SessionManager::get_course_list_by_session_id($session_id);        
+
+        $start = $limit*$page - $limit;
+        $course_list    = SessionManager::get_course_list_by_session_id($session_id);
         $count = 0;
-        
+
         foreach ($course_list as $item) {
             if (isset($course_id) && !empty($course_id)) {
                 if ($course_id != $item['id']) {
@@ -141,13 +141,13 @@ switch ($action) {
                 }
             }
             $list               = new LearnpathList(api_get_user_id(), $item['code'], $session_id);
-            $flat_list          = $list->get_flat_list(); 
+            $flat_list          = $list->get_flat_list();
             $lps[$item['code']] = $flat_list;
             $course_url         = api_get_path(WEB_COURSE_PATH).$item['directory'].'/?id_session='.$session_id;
             $item['title']      = Display::url($item['title'], $course_url, array('target'=>SESSION_LINK_TARGET));
-            
-            foreach($flat_list as $lp_id => $lp_item) {                                                    
-                $temp[$count]['id']= $lp_id;                
+
+            foreach($flat_list as $lp_id => $lp_item) {
+                $temp[$count]['id']= $lp_id;
                 $lp_url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?cidReq='.$item['code'].'&id_session='.$session_id.'&lp_id='.$lp_id.'&action=view';
                 $last_date = Tracking::get_last_connection_date_on_the_course(api_get_user_id(),$item['code'], $session_id, false);
                 if ($lp_item['modified_on'] == '0000-00-00 00:00:00' || empty($lp_item['modified_on'])) {
@@ -160,117 +160,117 @@ switch ($action) {
                     $label      = get_lang('LearnpathUpdated');
                 }
                 if (strtotime($last_date) < strtotime($lp_date)) {
-                    $icons = Display::return_icon($image, get_lang('TitleNotification').': '.$label.' - '.$lp_date);                    
+                    $icons = Display::return_icon($image, get_lang('TitleNotification').': '.$label.' - '.$lp_date);
                 }
-                
+
                 if (!empty($lp_item['publicated_on'])) {
                     $date = substr($lp_item['publicated_on'], 0, 10);
                 } else {
                     $date = '-';
                 }
-                
+
                 //Checking LP publicated and expired_on dates
-                if (!empty($lp_item['publicated_on']) && $lp_item['publicated_on'] != '0000-00-00 00:00:00') {                        
-                    if ($now < api_strtotime($lp_item['publicated_on'], 'UTC')) {                        
+                if (!empty($lp_item['publicated_on']) && $lp_item['publicated_on'] != '0000-00-00 00:00:00') {
+                    if ($now < api_strtotime($lp_item['publicated_on'], 'UTC')) {
                         continue;
                     }
                 }
-                
+
                 if (!empty($lp_item['expired_on']) && $lp_item['expired_on'] != '0000-00-00 00:00:00') {
                     if ($now > api_strtotime($lp_item['expired_on'], 'UTC')) {
                         continue;
                     }
                 }
-                
+
                 $temp[$count]['cell']=array($date, $item['title'], Display::url($icons.' '.$lp_item['lp_name'], $lp_url, array('target'=>SESSION_LINK_TARGET)));
                 $temp[$count]['course'] = strip_tags($item['title']);
                 $temp[$count]['lp']     = $lp_item['lp_name'];
                 $temp[$count]['date']   = $lp_item['publicated_on'];
-                $count++;     
-            }              
-        } 
-        
-        $temp = msort($temp, $sidx, $sord);
-        
+                $count++;
+            }
+        }
+
+        $temp = ArrayClass::msort($temp, $sidx, $sord);
+
         $i =0;
-        $response = new stdClass(); 
+        $response = new stdClass();
         foreach($temp as $key=>$row) {
             $row = $row['cell'];
-            if (!empty($row)) {            
-                if ($key >= $start  && $key < ($start + $limit)) {                 
+            if (!empty($row)) {
+                if ($key >= $start  && $key < ($start + $limit)) {
                     $response->rows[$i]['id']= $key;
                     $response->rows[$i]['cell']=array($row[0], $row[1], $row[2]);
-                    $i++;                
+                    $i++;
                 }
             }
-        }        
-        
-        if($count > 0 && $limit > 0) { 
-            $total_pages = ceil($count/$limit); 
-        } else { 
-            $total_pages = 0; 
-        }         
-        $response->total    = $total_pages;         
-        if ($page > $total_pages) { 
+        }
+
+        if($count > 0 && $limit > 0) {
+            $total_pages = ceil($count/$limit);
+        } else {
+            $total_pages = 0;
+        }
+        $response->total    = $total_pages;
+        if ($page > $total_pages) {
             $response->page= $total_pages;
         } else {
-            $response->page = $page;	
-        }        
-        $response->records = $count;    
-        echo json_encode($response);        
+            $response->page = $page;
+        }
+        $response->records = $count;
+        echo json_encode($response);
         break;
-        
+
     case 'session_courses_lp_by_week':
-        
-        require_once '../global.inc.php';                
-        require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';        
-        
+
+        require_once '../global.inc.php';
+        require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
+
         $page  = intval($_REQUEST['page']);     //page
         $limit = intval($_REQUEST['rows']);     // quantity of rows
-        $sidx  = $_REQUEST['sidx'];    //index to filter    
+        $sidx  = $_REQUEST['sidx'];    //index to filter
         if (empty($sidx)) $sidx = 'course';
         $sord  = $_REQUEST['sord'];    //asc or desc
         if (!in_array($sord, array('asc','desc'))) {
             $sord = 'desc';
         }
-                
+
         $session_id  = intval($_REQUEST['session_id']);
         $course_id   = intval($_REQUEST['course_id']);
-        
+
         //Filter users that does not belong to the session
         if (!api_is_platform_admin()) {
             $new_session_list = UserManager::get_personal_session_course_list(api_get_user_id());
             $my_session_list  = array();
             foreach($new_session_list as $item) {
-                if (!empty($item['id_session'])) 
+                if (!empty($item['id_session']))
                     $my_session_list[] = $item['id_session'];
-            }        
+            }
             if (!in_array($session_id, $my_session_list)) {
                 break;
             }
-        }        
-        
-        $start = $limit*$page - $limit;         
+        }
+
+        $start = $limit*$page - $limit;
         $course_list    = SessionManager::get_course_list_by_session_id($session_id);
-                        
+
         $count = 0;
         $temp = array();
-        foreach ($course_list as $item) {    
+        foreach ($course_list as $item) {
             if (isset($course_id) && !empty($course_id)) {
                 if ($course_id != $item['id']) {
                     continue;
                 }
             }
-            
+
             $list               = new LearnpathList(api_get_user_id(),$item['code'], $session_id, 'publicated_on DESC');
-            $flat_list          = $list->get_flat_list();    
+            $flat_list          = $list->get_flat_list();
             $lps[$item['code']] = $flat_list;
             $item['title'] = Display::url($item['title'],api_get_path(WEB_COURSE_PATH).$item['directory'].'/?id_session='.$session_id,array('target'=>SESSION_LINK_TARGET));
-            
+
             foreach($flat_list as $lp_id => $lp_item) {
                 $temp[$count]['id']= $lp_id;
                 $lp_url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?cidReq='.$item['code'].'&id_session='.$session_id.'&lp_id='.$lp_id.'&action=view';
-                
+
                 $last_date = Tracking::get_last_connection_date_on_the_course(api_get_user_id(),$item['code'], $session_id, false);
                 if ($lp_item['modified_on'] == '0000-00-00 00:00:00' || empty($lp_item['modified_on'])) {
                     $lp_date = api_get_local_time($lp_item['created_on']);
@@ -282,118 +282,118 @@ switch ($action) {
                     $label      = get_lang('LearnpathUpdated');
                 }
                 if (strtotime($last_date) < strtotime($lp_date)) {
-                    $icons = Display::return_icon($image, get_lang('TitleNotification').': '.$label.' - '.$lp_date);                    
+                    $icons = Display::return_icon($image, get_lang('TitleNotification').': '.$label.' - '.$lp_date);
                 }
-                
+
                 if (!empty($lp_item['publicated_on'])) {
                     $date = substr($lp_item['publicated_on'], 0, 10);
                 } else {
                     $date = '-';
                 }
-                
+
                  //Checking LP publicated and expired_on dates
-                
+
                 if (!empty($lp_item['publicated_on']) && $lp_item['publicated_on'] != '0000-00-00 00:00:00') {
-                    $week_data = date('Y', api_strtotime($lp_item['publicated_on'], 'UTC')).' - '.get_week_from_day($lp_item['publicated_on']);                   
-                    if ($now < api_strtotime($lp_item['publicated_on'], 'UTC')) {                        
+                    $week_data = date('Y', api_strtotime($lp_item['publicated_on'], 'UTC')).' - '.get_week_from_day($lp_item['publicated_on']);
+                    if ($now < api_strtotime($lp_item['publicated_on'], 'UTC')) {
                         continue;
                     }
                 } else {
                     $week_data = '';
                 }
-                
+
                 if (!empty($lp_item['expired_on']) && $lp_item['expired_on'] != '0000-00-00 00:00:00') {
                     if ($now > api_strtotime($lp_item['expired_on'], 'UTC')) {
                         continue;
                     }
                 }
-            
+
                 $temp[$count]['cell']   = array($week_data, $date, $item['title'], Display::url($icons.' '.$lp_item['lp_name'], $lp_url, array('target'=>SESSION_LINK_TARGET)));
                 $temp[$count]['course'] = strip_tags($item['title']);
                 $temp[$count]['lp']     = $lp_item['lp_name'];
-                $count++;     
-            }              
+                $count++;
+            }
         }
-        
-        $temp = msort($temp, $sidx, $sord);
-            
-        $response = new stdClass(); 
-        $i =0;        
-        foreach($temp as $key=>$row) {   
-            $row = $row['cell'];     
-            if (!empty($row)) {    
-                if ($key >= $start  && $key < ($start + $limit)) {                 
+
+        $temp = ArrayClass::msort($temp, $sidx, $sord);
+
+        $response = new stdClass();
+        $i =0;
+        foreach($temp as $key=>$row) {
+            $row = $row['cell'];
+            if (!empty($row)) {
+                if ($key >= $start  && $key < ($start + $limit)) {
                     $response->rows[$i]['id']= $key;
                     $response->rows[$i]['cell']=array($row[0], $row[1], $row[2],$row[3]);
-                    $i++;                
+                    $i++;
                 }
             }
         }
-        
-        if($count > 0 && $limit > 0) { 
-            $total_pages = ceil($count/$limit); 
-        } else { 
-            $total_pages = 0; 
-        }         
-        $response->total    = $total_pages;         
-        if ($page > $total_pages) { 
+
+        if($count > 0 && $limit > 0) {
+            $total_pages = ceil($count/$limit);
+        } else {
+            $total_pages = 0;
+        }
+        $response->total    = $total_pages;
+        if ($page > $total_pages) {
             $response->page = $total_pages;
         } else {
-            $response->page = $page;    
-        }        
-        $response->records = $count;    
-        echo json_encode($response); 
+            $response->page = $page;
+        }
+        $response->records = $count;
+        echo json_encode($response);
         break;
-        
+
 
     case 'session_courses_lp_by_course':
-        
-        require_once '../global.inc.php';                
-        require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';        
-        
+
+        require_once '../global.inc.php';
+        require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
+
         $page  = intval($_REQUEST['page']);     //page
         $limit = intval($_REQUEST['rows']);     // quantity of rows
-        $sidx  = $_REQUEST['sidx'];    //index to filter         
+        $sidx  = $_REQUEST['sidx'];    //index to filter
         $sord  = $_REQUEST['sord'];    //asc or desc
         if (!in_array($sord, array('asc','desc'))) {
             $sord = 'desc';
-        }        
+        }
         $session_id  = intval($_REQUEST['session_id']);
         $course_id   = intval($_REQUEST['course_id']);
-        
+
         //Filter users that does not belong to the session
         if (!api_is_platform_admin()) {
             $new_session_list = UserManager::get_personal_session_course_list(api_get_user_id());
             $my_session_list  = array();
             foreach($new_session_list as $item) {
-                if (!empty($item['id_session'])) 
+                if (!empty($item['id_session']))
                     $my_session_list[] = $item['id_session'];
-            }        
+            }
             if (!in_array($session_id, $my_session_list)) {
                 break;
             }
         }
-                
+
         if(!$sidx) $sidx =1;
-        
-        $start = $limit*$page - $limit; 
-        
+
+        $start = $limit*$page - $limit;
+
         $course_list = SessionManager::get_course_list_by_session_id($session_id);
-                        
+
         $count = 0;
-        
-        foreach ($course_list as $item) {   
+
+        foreach ($course_list as $item) {
             if (isset($course_id) && !empty($course_id)) {
                 if ($course_id != $item['id']) {
                     continue;
                 }
             }
-             
+
             $list               = new LearnpathList(api_get_user_id(),$item['code'],$session_id);
-            $flat_list          = $list->get_flat_list();    
+            $flat_list          = $list->get_flat_list();
             $lps[$item['code']] = $flat_list;
             $item['title']      = Display::url($item['title'],api_get_path(WEB_COURSE_PATH).$item['directory'].'/?id_session='.$session_id, array('target'=>SESSION_LINK_TARGET));
-            foreach($flat_list as $lp_id => $lp_item) {                                                    
+            foreach($flat_list as $lp_id => $lp_item) {
                 $temp[$count]['id']= $lp_id;
                 $lp_url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?cidReq='.$item['code'].'&id_session='.$session_id.'&lp_id='.$lp_id.'&action=view';
                 $last_date = Tracking::get_last_connection_date_on_the_course(api_get_user_id(),$item['code'], $session_id, false);
@@ -407,63 +407,63 @@ switch ($action) {
                     $label      = get_lang('LearnpathUpdated');
                 }
                 if (strtotime($last_date) < strtotime($lp_date)) {
-                    $icons = Display::return_icon($image, get_lang('TitleNotification').': '.$label.' - '.$lp_date);                    
+                    $icons = Display::return_icon($image, get_lang('TitleNotification').': '.$label.' - '.$lp_date);
                 }
                 if (!empty($lp_item['publicated_on'])) {
                     $date = substr($lp_item['publicated_on'], 0, 10);
                 } else {
                     $date = '-';
                 }
-                
+
                  //Checking LP publicated and expired_on dates
-                if (!empty($lp_item['publicated_on']) && $lp_item['publicated_on'] != '0000-00-00 00:00:00') {                        
-                    if ($now < api_strtotime($lp_item['publicated_on'], 'UTC')) {                        
+                if (!empty($lp_item['publicated_on']) && $lp_item['publicated_on'] != '0000-00-00 00:00:00') {
+                    if ($now < api_strtotime($lp_item['publicated_on'], 'UTC')) {
                         continue;
                     }
-                }                
+                }
                 if (!empty($lp_item['expired_on']) && $lp_item['expired_on'] != '0000-00-00 00:00:00') {
                     if ($now > api_strtotime($lp_item['expired_on'], 'UTC')) {
                         continue;
                     }
-                }                
+                }
                 $temp[$count]['cell'] = array($date, $item['title'], Display::url($icons.' '.$lp_item['lp_name'], $lp_url, array('target'=>SESSION_LINK_TARGET)));
                 $temp[$count]['course'] = strip_tags($item['title']);
                 $temp[$count]['lp']     = $lp_item['lp_name'];
                 $temp[$count]['date']   = $lp_item['publicated_on'];
-                
-                $count++;     
-            }              
+
+                $count++;
+            }
         }
-        
-        $temp = msort($temp, $sidx, $sord);
-        
-        $response = new stdClass(); 
+
+        $temp = ArrayClass::msort($temp, $sidx, $sord);
+
+        $response = new stdClass();
         $i =0;
-        foreach($temp as $key=>$row) {   
-            $row = $row['cell'];   
-            if (!empty($row)) {           
-                if ($key >= $start  && $key < ($start + $limit)) {                 
+        foreach($temp as $key=>$row) {
+            $row = $row['cell'];
+            if (!empty($row)) {
+                if ($key >= $start  && $key < ($start + $limit)) {
                     $response->rows[$i]['id']= $key;
                     $response->rows[$i]['cell']=array($row[0], $row[1], $row[2],$row[3]);
-                    $i++;                
+                    $i++;
                 }
             }
         }
-        
-        if($count > 0 && $limit > 0) { 
-            $total_pages = ceil($count/$limit); 
-        } else { 
-            $total_pages = 0; 
-        }         
-        $response->total    = $total_pages;         
-        if ($page > $total_pages) { 
+
+        if($count > 0 && $limit > 0) {
+            $total_pages = ceil($count/$limit);
+        } else {
+            $total_pages = 0;
+        }
+        $response->total    = $total_pages;
+        if ($page > $total_pages) {
             $response->page= $total_pages;
         } else {
-            $response->page = $page;    
-        }        
-        $response->records = $count; 
-        
-        echo json_encode($response); 
+            $response->page = $page;
+        }
+        $response->records = $count;
+
+        echo json_encode($response);
         break;
 	default:
 		echo '';

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

@@ -24,13 +24,13 @@ switch($action) {
 		    exit;
 		}
 
-		if (!empty($_FILES)) {		    
+		if (!empty($_FILES)) {
 		    $file = $_FILES['file'];
 		    $result = DocumentManager::upload_document($_FILES, $_POST['curdirpath'], $file['name'], null, 0, 'overwrite', false, false);
 		    $json = array();
 		    $json['name'] = Display::url(api_htmlentities($file['name']), api_htmlentities($result['url']), array('target'=>'_blank'));
 		    $json['type'] = api_htmlentities($file['type']);
-		    $json['size'] = format_file_size($file['size']);
+		    $json['size'] = Text::format_file_size($file['size']);
 		    if (!empty($result) && is_array($result)) {
 		        $json['result'] = Display::return_icon('accept.png', get_lang('Uploaded'));
 		    } else {

+ 3 - 3
main/inc/ajax/model.ajax.php

@@ -344,7 +344,7 @@ switch ($action) {
 	case 'get_user_skill_ranking':
         $columns = array('photo', 'firstname', 'lastname', 'skills_acquired', 'currently_learning', 'rank');
 	    $result = $skill->get_user_list_skill_ranking($start, $limit, $sidx, $sord, $where_condition);
-        $result = msort($result, 'skills_acquired', 'asc');
+        $result = ArrayClass::msort($result, 'skills_acquired', 'asc');
 
         $skills_in_course = array();
 	    if (!empty($result)) {
@@ -543,7 +543,7 @@ switch ($action) {
             $sidx = 'name';
         }
         //Multidimensional sort
-        msort($result, $sidx);
+        ArrayClass::msort($result, $sidx);
         break;
     case 'get_extra_fields':
         $obj = new ExtraField($type);
@@ -614,7 +614,7 @@ switch ($action) {
             $sidx = 'name';
         }
         //Multidimensional sort
-        msort($result, $sidx);
+          ArrayClass::msort($result, $sidx);
         break;
 
     default:

+ 8 - 8
main/inc/ajax/online.ajax.php

@@ -16,17 +16,17 @@ switch($action) {
             $_SESSION['who_is_online_counter'] = 2;
         }
         $images_to_show = 9;
-        
-        $page = intval($_REQUEST['online_page_nr']);        
-        $max_page = round(who_is_online_count()/$images_to_show);
+
+        $page = intval($_REQUEST['online_page_nr']);
+        $max_page = round(Online::who_is_online_count()/$images_to_show);
         $page_rows = ($page-1)*9 + 1;
-        
+
         if (!empty($max_page) && $page <= $max_page) {
             if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
-                $user_list = who_is_online_in_this_course($page_rows, $images_to_show, api_get_user_id(), api_get_setting('time_limit_whosonline'), $_GET['cidReq']);
-            } else {                                
-                $user_list = who_is_online($page_rows, $images_to_show);		
-            } 
+                $user_list = Online::who_is_online_in_this_course($page_rows, $images_to_show, api_get_user_id(), api_get_setting('time_limit_whosonline'), $_GET['cidReq']);
+            } else {
+                $user_list = Online::who_is_online($page_rows, $images_to_show);
+            }
             if (!empty($user_list)) {
                 echo SocialManager::display_user_list($user_list);
                 exit;

+ 3 - 9
main/inc/global.inc.php

@@ -107,15 +107,12 @@ if ($alreadyInstalled) {
 require_once $includePath.'/lib/main_api.lib.php';
 
 
-/** Inclusion of internationalization libraries */
+// Inclusion of internationalization libraries
 require_once $includePath.'/lib/internationalization.lib.php';
 
-/**
- * Functions for internal use behind this API
- */
+// Functions for internal use behind this API
 require_once $includePath.'/lib/internationalization_internal.lib.php';
 
-
 // Do not over-use this variable. It is only for this script's local use.
 $libPath = $includePath.'/lib/';
 
@@ -507,10 +504,7 @@ $app['default_layout'] = $app['template_style'].'/layout/layout_1_col.tpl';
 
 //Database constants
 require_once $libPath.'database.constants.inc.php';
-require_once $libPath.'text.lib.php';
-require_once $libPath.'array.lib.php';
 require_once $libPath.'events.lib.inc.php';
-require_once $libPath.'online.inc.php';
 
 // Connect to the server database and select the main chamilo database.
 if (!($conn_return = @Database::connect(
@@ -662,7 +656,7 @@ $app['mailer'] = $app->share(function ($app) {
 
 // Check and modify the date of user in the track.e.online table
 if ($alreadyInstalled && !$x = strpos($_SERVER['PHP_SELF'], 'whoisonline.php')) {
-    LoginCheck(isset($_user['user_id']) ? $_user['user_id'] : '');
+    Online::LoginCheck(isset($_user['user_id']) ? $_user['user_id'] : '');
 }
 
 $app['api_get_languages'] = api_get_languages();

+ 80 - 99
main/inc/lib/array.lib.php

@@ -7,119 +7,100 @@
 *	@package chamilo.library
 */
 
+class ArrayClass {
 
-/**
- * Removes duplicate values from a dimensional array
- *
- * @param array a dimensional array
- * @return array an array with unique values
- * 
- */
-function array_unique_dimensional($array) {
-    if(!is_array($array))
-		return $array;
 
-    foreach ($array as &$myvalue) {
-        $myvalue=serialize($myvalue);
-    }
+    /**
+     * Removes duplicate values from a dimensional array
+     *
+     * @param array a dimensional array
+     * @return array an array with unique values
+     *
+     */
+    function array_unique_dimensional($array) {
+        if(!is_array($array))
+            return $array;
 
-    $array=array_unique($array);
+        foreach ($array as &$myvalue) {
+            $myvalue=serialize($myvalue);
+        }
 
-    foreach ($array as &$myvalue) {
-        $myvalue=unserialize($myvalue);
-    }
-    return $array;
-}
+        $array=array_unique($array);
 
-/**
- * 
- * Sort multidimensional arrays
- * 
- * @param 	array 	unsorted multidimensional array
- * @param 	string	key to be sorted
- * @return 	array	result array
- * @author	found in http://php.net/manual/en/function.sort.php
- */
-function msort($array, $id='id', $order = 'desc') {
-    if (empty($array)) {
+        foreach ($array as &$myvalue) {
+            $myvalue=unserialize($myvalue);
+        }
         return $array;
     }
-    $temp_array = array();
-    while (count($array)>0) {
-        $lowest_id = 0;
-        $index=0;
-        foreach ($array as $item) {
-            if ($order == 'desc') {
-                if ($item[$id]<$array[$lowest_id][$id]) {
-                    $lowest_id = $index;
-                }
-            } else {
-                if ($item[$id]>$array[$lowest_id][$id]) {
-                    $lowest_id = $index;
+
+    /**
+     *
+     * Sort multidimensional arrays
+     *
+     * @param 	array 	unsorted multidimensional array
+     * @param 	string	key to be sorted
+     * @return 	array	result array
+     * @author	found in http://php.net/manual/en/function.sort.php
+     */
+    function msort($array, $id='id', $order = 'desc') {
+        if (empty($array)) {
+            return $array;
+        }
+        $temp_array = array();
+        while (count($array)>0) {
+            $lowest_id = 0;
+            $index=0;
+            foreach ($array as $item) {
+                if ($order == 'desc') {
+                    if ($item[$id]<$array[$lowest_id][$id]) {
+                        $lowest_id = $index;
+                    }
+                } else {
+                    if ($item[$id]>$array[$lowest_id][$id]) {
+                        $lowest_id = $index;
+                    }
                 }
+                $index++;
             }
-            $index++;
+            $temp_array[] = $array[$lowest_id];
+            $array = array_merge(array_slice($array, 0, $lowest_id), array_slice($array, $lowest_id+1));
         }
-        $temp_array[] = $array[$lowest_id];
-        $array = array_merge(array_slice($array, 0, $lowest_id), array_slice($array, $lowest_id+1));
+        return $temp_array;
     }
-    return $temp_array;
-}
 
-function array_walk_recursive_limited(&$array, $function, $apply_to_keys_also = false) {
-	static $recursive_counter = 0;
-	if (++$recursive_counter > 1000) {
-		die('possible deep recursion attack');
-	}
-	foreach ($array as $key => $value) {
-		if (is_array($value)) {
-			array_walk_recursive_limited($array[$key], $function, $apply_to_keys_also);
-		} else {
-			$array[$key] = $function($value);
-		}
-		if ($apply_to_keys_also && is_string($key)) {
-			$new_key = $function($key);
-			if ($new_key != $key) {
-				$array[$new_key] = $array[$key];
-				unset($array[$key]);
-			}
-		}
-	}	
-	$recursive_counter--;
-}
+    function utf8_sort($array) {
+        $old_locale = setlocale(LC_ALL, null);
+        $code = api_get_language_isocode();
+        $locale_list = array($code.'.utf8', 'en.utf8','en_US.utf8','en_GB.utf8');
+        $try_sort = false;
 
-function utf8_sort($array) {
-	$old_locale = setlocale(LC_ALL, null);	
-	$code = api_get_language_isocode();
-	$locale_list = array($code.'.utf8', 'en.utf8','en_US.utf8','en_GB.utf8');
-	$try_sort = false;
-	
-	foreach($locale_list as $locale) {
-		$my_local = setlocale(LC_COLLATE, $locale);
-		if ($my_local) {
-			$try_sort = true;
-			break;
-		}
-	}
-	
-	if ($try_sort) {
-		uasort($array, 'strcoll');
-	}
-	setlocale(LC_COLLATE, $old_locale);	
-	return $array;
-}
+        foreach($locale_list as $locale) {
+            $my_local = setlocale(LC_COLLATE, $locale);
+            if ($my_local) {
+                $try_sort = true;
+                break;
+            }
+        }
+
+        if ($try_sort) {
+            uasort($array, 'strcoll');
+        }
+        setlocale(LC_COLLATE, $old_locale);
+        return $array;
+    }
 
-function array_to_string($array, $separator = ',') {
-    if (empty($array)) {
-        return '';
+    function array_to_string($array, $separator = ',') {
+        if (empty($array)) {
+            return '';
+        }
+        return implode($separator.' ', $array);
     }
-    return implode($separator.' ', $array);
-}
 
-function array_flatten(array $array) {
-    $flatten = array();
-    array_walk_recursive($array, function($value) use(&$flatten) {
-        $flatten[] = $value;
-    });
-    return $flatten;
+    function array_flatten(array $array) {
+        $flatten = array();
+        array_walk_recursive($array, function($value) use(&$flatten) {
+            $flatten[] = $value;
+        });
+        return $flatten;
+    }
 }

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

@@ -625,7 +625,7 @@ class Attendance
 	}
 
     /**
-     * Unstable version! Needs review! Use only for speed boosts! 
+     * Unstable version! Needs review! Use only for speed boosts!
      * Add attendaces sheet inside table, by group to reduce db stress
      * @param       array  Array of calendar_id, user_id, status, attendance_id, course_id, date, all assumed pre-filtered
      * @param       bool   Whether to save absent users
@@ -1401,7 +1401,7 @@ class Attendance
 	 * @return	string	date and time e.g: '2010-02-10 12:30:00'
 	 */
 	public function build_datetime_from_array($array) {
-        return return_datetime_from_array($array);
+        return Text::return_datetime_from_array($array);
 	}
 
 	/** Setters for fields of attendances tables **/

+ 4 - 4
main/inc/lib/blog.lib.php

@@ -812,7 +812,7 @@ class Blog
 
                 // Prepare data
                 $blog_post_id = $blog_post['post_id'];
-                $blog_post_text = make_clickable(stripslashes($blog_post['full_text']));
+                $blog_post_text = Text::make_clickable(stripslashes($blog_post['full_text']));
                 $blog_post_date = api_convert_and_format_date(
                     $blog_post['date_creation'],
                     null,
@@ -823,7 +823,7 @@ class Blog
 
                 $introduction_text = "";
                 $words = 0;
-                $blog_post_text_cut = cut($blog_post_text, $limit);
+                $blog_post_text_cut = Text::cut($blog_post_text, $limit);
                 $words = strlen($blog_post_text);
 
                 if ($words >= $limit) {
@@ -958,7 +958,7 @@ class Blog
         $blog_post_comments = Database::fetch_array($result);
 
         // Prepare data
-        $blog_post_text = make_clickable(stripslashes($blog_post['full_text']));
+        $blog_post_text = Text::make_clickable(stripslashes($blog_post['full_text']));
         $blog_post_date = api_convert_and_format_date($blog_post['date_creation'], null, date_default_timezone_get());
         $blog_post_actions = "";
 
@@ -1200,7 +1200,7 @@ class Blog
             $border_color = '';
 
             // Prepare data
-            $comment_text = make_clickable(stripslashes($comment['comment']));
+            $comment_text = Text::make_clickable(stripslashes($comment['comment']));
             $blog_comment_date = api_convert_and_format_date(
                 $comment['date_creation'],
                 null,

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

@@ -1252,7 +1252,7 @@ class CourseManager {
         $rs = Database::query('SELECT id_user FROM '.Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER).
                 ' WHERE id_session="'.$session_id.'" AND course_code="'.$course_code.'" AND status = 2');
         while ($user = Database::fetch_array($rs)) {
-            $user_info = Database::get_user_info_from_id($user['id_user']);
+            $user_info = api_get_user_info($user['id_user']);
             $user_info['status'] = $user['status'];
             $user_info['role'] = $user['role'];
             $user_info['tutor_id'] = $user['tutor_id'];
@@ -1263,9 +1263,9 @@ class CourseManager {
         // We get the session coach.
         $rs = Database::query('SELECT id_coach FROM '.Database::get_main_table(TABLE_MAIN_SESSION).' WHERE id="'.$session_id.'"');
         $session_id_coach = Database::result($rs, 0, 'id_coach');
-        $user_info = Database::get_user_info_from_id($session_id_coach);
+        $user_info = api_get_user_info($session_id_coach);
         $user_info['status'] = $user['status'];
-        $user_info['role'] = $user['role'];
+        $user_info['role'] = $user['role']; //Role field exists?
         $user_info['tutor_id'] = $user['tutor_id'];
         $user_info['email'] = $user['email'];
         $users[$session_id_coach] = $user_info;
@@ -1355,7 +1355,7 @@ class CourseManager {
                  $list[]= $teacher_name;
             }
             if (!empty($list)) {
-                $teacher_string = array_to_string($list, $separator);
+                $teacher_string = ArrayClass::array_to_string($list, $separator);
             }
         }
         return $teacher_string;
@@ -1417,7 +1417,7 @@ class CourseManager {
         }
         $coaches_to_string = null;
         if (is_array($course_coachs) && count($course_coachs)> 0 ) {
-            $coaches_to_string = array_to_string($course_coachs, $separator);
+            $coaches_to_string = ArrayClass::array_to_string($course_coachs, $separator);
         }
         return $coaches_to_string;
     }
@@ -4130,26 +4130,26 @@ class CourseManager {
 
         /*    Course tools  */
 
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_DESCRIPTION . "','course_description/','info.gif','".string2binary(api_get_setting('course_create_active_tools', 'course_description')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_CALENDAR_EVENT . "','calendar/agenda.php','agenda.gif','".string2binary(api_get_setting('course_create_active_tools', 'agenda')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_DOCUMENT . "','document/document.php','folder_document.gif','".string2binary(api_get_setting('course_create_active_tools', 'documents')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_LEARNPATH . "','newscorm/lp_controller.php','scorms.gif','".string2binary(api_get_setting('course_create_active_tools', 'learning_path')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_LINK . "','link/link.php','links.gif','".string2binary(api_get_setting('course_create_active_tools', 'links')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_QUIZ . "','exercice/exercice.php','quiz.gif','".string2binary(api_get_setting('course_create_active_tools', 'quiz')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_ANNOUNCEMENT . "','announcements/announcements.php','valves.gif','".string2binary(api_get_setting('course_create_active_tools', 'announcements')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_FORUM . "','forum/index.php','forum.gif','".string2binary(api_get_setting('course_create_active_tools', 'forums')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_DROPBOX . "','dropbox/index.php','dropbox.gif','".string2binary(api_get_setting('course_create_active_tools', 'dropbox')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_USER . "','user/user.php','members.gif','".string2binary(api_get_setting('course_create_active_tools', 'users')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GROUP . "','group/group.php','group.gif','".string2binary(api_get_setting('course_create_active_tools', 'groups')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_CHAT . "','chat/chat.php','chat.gif','".string2binary(api_get_setting('course_create_active_tools', 'chat')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_STUDENTPUBLICATION . "','work/work.php','works.gif','".string2binary(api_get_setting('course_create_active_tools', 'student_publications')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_SURVEY."','survey/survey_list.php','survey.gif','".string2binary(api_get_setting('course_create_active_tools', 'survey')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_WIKI ."','wiki/index.php','wiki.gif','".string2binary(api_get_setting('course_create_active_tools', 'wiki')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GRADEBOOK."','gradebook/index.php','gradebook.gif','".string2binary(api_get_setting('course_create_active_tools', 'gradebook')). "','0','squaregrey.gif','NO','_self','authoring','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GLOSSARY."','glossary/index.php','glossary.gif','".string2binary(api_get_setting('course_create_active_tools', 'glossary')). "','0','squaregrey.gif','NO','_self','authoring','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_NOTEBOOK."','notebook/index.php','notebook.gif','".string2binary(api_get_setting('course_create_active_tools', 'notebook'))."','0','squaregrey.gif','NO','_self','interaction','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_ATTENDANCE."','attendance/index.php','attendance.gif','".string2binary(api_get_setting('course_create_active_tools', 'attendances'))."','0','squaregrey.gif','NO','_self','authoring','0')");
-        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_PROGRESS."','course_progress/index.php','course_progress.gif','".string2binary(api_get_setting('course_create_active_tools', 'course_progress'))."','0','squaregrey.gif','NO','_self','authoring','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_DESCRIPTION . "','course_description/','info.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'course_description')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_CALENDAR_EVENT . "','calendar/agenda.php','agenda.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'agenda')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_DOCUMENT . "','document/document.php','folder_document.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'documents')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_LEARNPATH . "','newscorm/lp_controller.php','scorms.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'learning_path')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_LINK . "','link/link.php','links.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'links')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_QUIZ . "','exercice/exercice.php','quiz.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'quiz')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_ANNOUNCEMENT . "','announcements/announcements.php','valves.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'announcements')) . "','0','squaregrey.gif','NO','_self','authoring','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_FORUM . "','forum/index.php','forum.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'forums')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_DROPBOX . "','dropbox/index.php','dropbox.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'dropbox')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_USER . "','user/user.php','members.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'users')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GROUP . "','group/group.php','group.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'groups')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_CHAT . "','chat/chat.php','chat.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'chat')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_STUDENTPUBLICATION . "','work/work.php','works.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'student_publications')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_SURVEY."','survey/survey_list.php','survey.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'survey')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_WIKI ."','wiki/index.php','wiki.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'wiki')) . "','0','squaregrey.gif','NO','_self','interaction','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GRADEBOOK."','gradebook/index.php','gradebook.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'gradebook')). "','0','squaregrey.gif','NO','_self','authoring','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GLOSSARY."','glossary/index.php','glossary.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'glossary')). "','0','squaregrey.gif','NO','_self','authoring','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_NOTEBOOK."','notebook/index.php','notebook.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'notebook'))."','0','squaregrey.gif','NO','_self','interaction','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_ATTENDANCE."','attendance/index.php','attendance.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'attendances'))."','0','squaregrey.gif','NO','_self','authoring','0')");
+        Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_PROGRESS."','course_progress/index.php','course_progress.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'course_progress'))."','0','squaregrey.gif','NO','_self','authoring','0')");
 
         if (api_get_setting('service_visio', 'active') == 'true') {
             $mycheck = api_get_setting('service_visio', 'visio_host');
@@ -4160,11 +4160,11 @@ class CourseManager {
         }
 
         if (api_get_setting('search_enabled') == 'true') {
-            Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_SEARCH. "','search/','info.gif','".string2binary(api_get_setting('course_create_active_tools', 'enable_search')) . "','0','search.gif','NO','_self','authoring','0')");
+            Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_SEARCH. "','search/','info.gif','".Text::string2binary(api_get_setting('course_create_active_tools', 'enable_search')) . "','0','search.gif','NO','_self','authoring','0')");
         }
 
         // Smartblogs (Kevin Van Den Haute :: kevin@develop-it.be)
-        $sql = "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL,'" . TOOL_BLOGS . "','blog/blog_admin.php','blog_admin.gif','" . string2binary(api_get_setting('course_create_active_tools', 'blogs')) . "','1','squaregrey.gif','NO','_self','admin','0')";
+        $sql = "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL,'" . TOOL_BLOGS . "','blog/blog_admin.php','blog_admin.gif','" . Text::string2binary(api_get_setting('course_create_active_tools', 'blogs')) . "','1','squaregrey.gif','NO','_self','admin','0')";
         Database::query($sql);
         // end of Smartblogs
 
@@ -4199,7 +4199,7 @@ class CourseManager {
         /* Group tool */
 
         Database::query("INSERT INTO $TABLEGROUPCATEGORIES  (c_id,  id , title , description , max_student , self_reg_allowed , self_unreg_allowed , groups_per_user , display_order )
-                VALUES ($course_id, '2', '".lang2db(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
+                VALUES ($course_id, '2', '".Database::escape_string(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
 
         /*    Example Material  */
         global $language_interface;
@@ -4376,7 +4376,7 @@ class CourseManager {
 
             /* Agenda tool */
 
-            Database::query("INSERT INTO $TABLETOOLAGENDA  VALUES ($course_id, NULL, '".lang2db(get_lang('AgendaCreationTitle')) . "', '".lang2db(get_lang('AgendaCreationContenu')) . "', now(), now(), NULL, 0, 0)");
+            Database::query("INSERT INTO $TABLETOOLAGENDA  VALUES ($course_id, NULL, '".Database::escape_string(get_lang('AgendaCreationTitle')) . "', '".Database::escape_string(get_lang('AgendaCreationContenu')) . "', now(), now(), NULL, 0, 0)");
             // We need to add the item properties too!
             $insert_id = Database :: insert_id();
             $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id, '" . TOOL_CALENDAR_EVENT . "',1,NOW(),NOW(),$insert_id,'AgendaAdded',1,0,NULL,1)";
@@ -4385,7 +4385,7 @@ class CourseManager {
             /*  Links tool */
 
             $add_google_link_sql = "INSERT INTO $TABLETOOLLINK  (c_id, url, title, description, category_id, display_order, on_homepage, target)
-                    VALUES ($course_id, 'http://www.google.com','Google','".lang2db(get_lang('Google')) . "','0','0','0','_self')";
+                    VALUES ($course_id, 'http://www.google.com','Google','".Database::escape_string(get_lang('Google')) . "','0','0','0','_self')";
             Database::query($add_google_link_sql);
 
             // We need to add the item properties too!
@@ -4395,7 +4395,7 @@ class CourseManager {
             Database::query($sql);
 
             $add_wikipedia_link_sql = "INSERT INTO $TABLETOOLLINK  (c_id, url, title, description, category_id, display_order, on_homepage, target)
-                    VALUES ($course_id, 'http://www.wikipedia.org','Wikipedia','".lang2db(get_lang('Wikipedia')) . "','0','1','0','_self')";
+                    VALUES ($course_id, 'http://www.wikipedia.org','Wikipedia','".Database::escape_string(get_lang('Wikipedia')) . "','0','1','0','_self')";
             Database::query($add_wikipedia_link_sql);
 
             // We need to add the item properties too!
@@ -4406,7 +4406,7 @@ class CourseManager {
             /* Annoucement tool */
 
             $sql = "INSERT INTO $TABLETOOLANNOUNCEMENTS  (c_id, title,content,end_date,display_order,email_sent)
-                    VALUES ($course_id, '".lang2db(get_lang('AnnouncementExampleTitle')) . "', '".lang2db(get_lang('AnnouncementEx')) . "', NOW(), '1','0')";
+                    VALUES ($course_id, '".Database::escape_string(get_lang('AnnouncementExampleTitle')) . "', '".Database::escape_string(get_lang('AnnouncementEx')) . "', NOW(), '1','0')";
             Database::query($sql);
 
             // We need to add the item properties too!
@@ -4419,53 +4419,53 @@ class CourseManager {
 
             $intro_text='<p style="text-align: center;">
                             <img src="'.api_get_path(REL_CODE_PATH).'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
-                            <h2>'.lang2db(get_lang('IntroductionText')).'</h2>
+                            <h2>'.Database::escape_string(get_lang('IntroductionText')).'</h2>
                          </p>';
             Database::query("INSERT INTO $TABLEINTROS  VALUES ($course_id, '" . TOOL_COURSE_HOMEPAGE . "','".$intro_text."', 0)");
-            Database::query("INSERT INTO $TABLEINTROS  VALUES ($course_id, '" . TOOL_STUDENTPUBLICATION . "','".lang2db(get_lang('IntroductionTwo')) . "', 0)");
+            Database::query("INSERT INTO $TABLEINTROS  VALUES ($course_id, '" . TOOL_STUDENTPUBLICATION . "','".Database::escape_string(get_lang('IntroductionTwo')) . "', 0)");
 
             // Wiki intro
-            $intro_wiki='<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td width="110" valign="top" align="left"></td><td valign="top" align="left">'.lang2db(get_lang('IntroductionWiki')).'</td></tr></table>';
+            $intro_wiki='<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td width="110" valign="top" align="left"></td><td valign="top" align="left">'.Database::escape_string(get_lang('IntroductionWiki')).'</td></tr></table>';
             Database::query("INSERT INTO $TABLEINTROS  VALUES ($course_id, '" . TOOL_WIKI . "','".$intro_wiki. "', 0)");
 
             /*  Exercise tool */
 
-            Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '1', '1', '".lang2db(get_lang('Ridiculise')) . "', '0', '".lang2db(get_lang('NoPsychology')) . "', '-5', '1')");
-            Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id,  '2', '1', '".lang2db(get_lang('AdmitError')) . "', '0', '".lang2db(get_lang('NoSeduction')) . "', '-5', '2')");
-            Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id,  '3', '1', '".lang2db(get_lang('Force')) . "', '1', '".lang2db(get_lang('Indeed')) . "', '5', '3')");
-            Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id,  '4', '1', '".lang2db(get_lang('Contradiction')) . "', '1', '".lang2db(get_lang('NotFalse')) . "', '5', '4')");
+            Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '1', '1', '".Database::escape_string(get_lang('Ridiculise')) . "', '0', '".Database::escape_string(get_lang('NoPsychology')) . "', '-5', '1')");
+            Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id,  '2', '1', '".Database::escape_string(get_lang('AdmitError')) . "', '0', '".Database::escape_string(get_lang('NoSeduction')) . "', '-5', '2')");
+            Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id,  '3', '1', '".Database::escape_string(get_lang('Force')) . "', '1', '".Database::escape_string(get_lang('Indeed')) . "', '5', '3')");
+            Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id,  '4', '1', '".Database::escape_string(get_lang('Contradiction')) . "', '1', '".Database::escape_string(get_lang('NotFalse')) . "', '5', '4')");
 
             $html=Database::escape_string('<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td width="110" valign="top" align="left"><img src="'.api_get_path(WEB_CODE_PATH).'default_course_document/images/mr_dokeos/thinking.jpg"></td><td valign="top" align="left">'.get_lang('Antique').'</td></tr></table>');
 
             Database::query('INSERT INTO '.$TABLEQUIZ .
               ' (c_id, title, description, type, random, random_answers, active, results_disabled ) ' .
-              ' VALUES ('.$course_id.', "'.lang2db(get_lang('ExerciceEx')) . '",' .
+              ' VALUES ('.$course_id.', "'.Database::escape_string(get_lang('ExerciceEx')) . '",' .
               ' "'.$html.'", "1", "0", "0", "1", "0")');
             $exercise_id = Database :: insert_id();
             Database::query("INSERT INTO $TABLEQUIZQUESTIONLIST  (c_id, id, question, description, ponderation, position, type, picture, level)
-                            VALUES ( '.$course_id.', '1', '".lang2db(get_lang('SocraticIrony')) . "', '".lang2db(get_lang('ManyAnswers')) . "', '10', '1', '2','',1)");
+                            VALUES ( '.$course_id.', '1', '".Database::escape_string(get_lang('SocraticIrony')) . "', '".Database::escape_string(get_lang('ManyAnswers')) . "', '10', '1', '2','',1)");
             Database::query("INSERT INTO $TABLEQUIZQUESTION  (c_id, question_id, exercice_id, question_order) VALUES ('.$course_id.', 1,1,1)");
 
             /* Forum tool */
 
-            Database::query("INSERT INTO $TABLEFORUMCATEGORIES VALUES ($course_id, 1,'".lang2db(get_lang('ExampleForumCategory'))."', '', 1, 0, 0)");
+            Database::query("INSERT INTO $TABLEFORUMCATEGORIES VALUES ($course_id, 1,'".Database::escape_string(get_lang('ExampleForumCategory'))."', '', 1, 0, 0)");
             $insert_id = Database :: insert_id();
             Database::query("INSERT INTO $TABLEITEMPROPERTY  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
                             VALUES ($course_id, 'forum_category',1,NOW(),NOW(),$insert_id,'ForumCategoryAdded',1,0,NULL,1)");
 
             Database::query("INSERT INTO $TABLEFORUMS (c_id, forum_title, forum_comment, forum_threads,forum_posts,forum_last_post,forum_category, allow_anonymous, allow_edit,allow_attachments, allow_new_threads,default_view,forum_of_group,forum_group_public_private, forum_order,locked,session_id )
-                            VALUES ($course_id, '".lang2db(get_lang('ExampleForum'))."', '', 0, 0, 0, 1, 0, 1, '0', 1, 'flat','0', 'public', 1, 0,0)");
+                            VALUES ($course_id, '".Database::escape_string(get_lang('ExampleForum'))."', '', 0, 0, 0, 1, 0, 1, '0', 1, 'flat','0', 'public', 1, 0,0)");
             $insert_id = Database :: insert_id();
             Database::query("INSERT INTO $TABLEITEMPROPERTY  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
                              VALUES ($course_id, '".TOOL_FORUM."', 1,NOW(),NOW(),$insert_id,'ForumAdded',1,0,NULL,1)");
 
             Database::query("INSERT INTO $TABLEFORUMTHREADS (c_id, thread_id, thread_title, forum_id, thread_replies, thread_poster_id, thread_poster_name, thread_views, thread_last_post, thread_date, locked, thread_qualify_max, session_id)
-                            VALUES ($course_id, 1, '".lang2db(get_lang('ExampleThread'))."', 1, 0, 1, '', 0, 1, NOW(), 0, 10, 0)");
+                            VALUES ($course_id, 1, '".Database::escape_string(get_lang('ExampleThread'))."', 1, 0, 1, '', 0, 1, NOW(), 0, 10, 0)");
             $insert_id = Database :: insert_id();
             Database::query("INSERT INTO $TABLEITEMPROPERTY  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)
                             VALUES ($course_id, 'forum_thread',1,NOW(),NOW(),$insert_id,'ForumThreadAdded',1,0,NULL,1)");
 
-            Database::query("INSERT INTO $TABLEFORUMPOSTS VALUES ($course_id, 1, '".lang2db(get_lang('ExampleThread'))."', '".lang2db(get_lang('ExampleThreadContent'))."', 1, 1, 1, '', NOW(), 0, 0, 1)");
+            Database::query("INSERT INTO $TABLEFORUMPOSTS VALUES ($course_id, 1, '".Database::escape_string(get_lang('ExampleThread'))."', '".Database::escape_string(get_lang('ExampleThreadContent'))."', 1, 1, 1, '', NOW(), 0, 0, 1)");
 
             /* Gradebook tool */
             $course = api_get_course_info_by_id($course_id);
@@ -4594,7 +4594,7 @@ class CourseManager {
                 directory       = '".Database :: escape_string($directory) . "',
                 course_language = '".Database :: escape_string($course_language) . "',
                 title           = '".Database :: escape_string($title) . "',
-                description     = '".lang2db(get_lang('CourseDescription')) . "',
+                description     = '".Database::escape_string(get_lang('CourseDescription')) . "',
                 category_code   = '".Database :: escape_string($category_code) . "',
                 visibility      = '".$visibility . "',
                 show_score      = '1',
@@ -4624,7 +4624,7 @@ class CourseManager {
                                 course_code     = '".Database :: escape_string($code). "',
                                 user_id         = '".intval($user_id) . "',
                                 status          = '1',
-                                role            = '".lang2db(get_lang('Professor')) . "',
+                                role            = '".Database::escape_string(get_lang('Professor')) . "',
                                 tutor_id        = '0',
                                 sort            = '". ($i_course_sort) . "',
                                 user_course_cat = '0'";

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

@@ -901,7 +901,7 @@ class CourseHome {
                 $tool_name = get_lang($variable);
             }
             */
-            $tool_name = get_lang('Tool'.api_underscore_to_camel_case($tool['name']));
+            $tool_name = get_lang('Tool'.Text::api_underscore_to_camel_case($tool['name']));
         }
 
         return $tool_name;

+ 4 - 4
main/inc/lib/course_request.lib.php

@@ -139,7 +139,7 @@ class CourseRequestManager {
         $sender_name_teacher = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
         $sender_email_teacher = $user_info['mail'];
         $recipient_name_admin = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-        $recipient_email_admin = get_setting('emailAdministrator');
+        $recipient_email_admin = api_get_setting('emailAdministrator');
 
         @api_mail($recipient_name_admin, $recipient_email_admin, $email_subject, $email_body_admin, $sender_name_teacher, $sender_email_teacher);
 
@@ -380,7 +380,7 @@ class CourseRequestManager {
             $email_body .= "\n".get_lang('CourseRequestLegalNote', null, $email_language)."\n";
 
             $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-            $sender_email = get_setting('emailAdministrator');
+            $sender_email = api_get_setting('emailAdministrator');
             $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
             $recipient_email = $user_info['mail'];
             $extra_headers = 'Bcc: '.$sender_email;
@@ -443,7 +443,7 @@ class CourseRequestManager {
         $email_body .= "\n".get_lang('CourseRequestLegalNote', null, $email_language)."\n";
 
         $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-        $sender_email = get_setting('emailAdministrator');
+        $sender_email = api_get_setting('emailAdministrator');
         $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
         $recipient_email = $user_info['mail'];
         $extra_headers = 'Bcc: '.$sender_email;
@@ -506,7 +506,7 @@ class CourseRequestManager {
         $email_body .= "\n".get_lang('CourseRequestLegalNote', null, $email_language)."\n";
 
         $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
-        $sender_email = get_setting('emailAdministrator');
+        $sender_email = api_get_setting('emailAdministrator');
         $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
         $recipient_email = $user_info['mail'];
         $extra_headers = 'Bcc: '.$sender_email;

+ 0 - 23
main/inc/lib/database.lib.php

@@ -241,29 +241,6 @@ class Database
         return $result === false ? array('db_name' => '') : $result;
     }
 
-    /**
-     * Gets user details from the "user" table
-     * @param $user_id (integer): the id of the user
-     * @return $user_info (array): user_id, lname, fname, username, email, ...
-     * @author Patrick Cool <patrick.cool@UGent.be>, expanded to get info for any user
-     * @author Roan Embrechts, first version + converted to Database API
-     * @version 30 September 2004
-     * @desc find all the information about a specified user. Without parameter this is the current user.
-     * @todo shouldn't this be in the user.lib.php script?
-     */
-    public static function get_user_info_from_id($user_id = '')
-    {
-        if (empty($user_id)) {
-            return $GLOBALS['_user'];
-        }
-        $table = self::get_main_table(TABLE_MAIN_USER);
-        $user_id = self::escape_string($user_id);
-
-        return self::generate_abstract_user_field_names(
-            self::fetch_array(self::query("SELECT * FROM $table WHERE user_id = '$user_id'"))
-        );
-    }
-
     /**
      * Returns course code from a given gradebook category's id
      * @param int  Category ID

+ 0 - 19
main/inc/lib/database.mysqli.lib.php

@@ -210,25 +210,6 @@ class Database {
         return $result === false ? array('db_name' => '') : $result;
     }
 
-    /**
-     *	@param $user_id (integer): the id of the user
-     *	@return $user_info (array): user_id, lastname, firstname, username, email, ...
-     *	@author Patrick Cool <patrick.cool@UGent.be>, expanded to get info for any user
-     *	@author Roan Embrechts, first version + converted to Database API
-     *	@version 30 September 2004
-     *	@desc find all the information about a specified user. Without parameter this is the current user.
-     * 	@todo shouldn't this be in the user.lib.php script?
-     */
-    public static function get_user_info_from_id($user_id = '') {
-        if (empty($user_id)) {
-            return $GLOBALS['_user'];
-        }
-        $table = self::get_main_table(TABLE_MAIN_USER);
-        $user_id = self::escape_string($user_id);
-        return self::generate_abstract_user_field_names(
-            self::fetch_array(self::query("SELECT * FROM $table WHERE user_id = '$user_id'")));
-    }
-
     /**
      * Returns course code from a given gradebook category's id
      * @param int  Category ID

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

@@ -347,13 +347,13 @@ class DocumentManager
             //header('Pragma: no-cache');
             switch ($content_type) {
                 case 'text/html':
-                    $encoding = @api_detect_encoding_html(file_get_contents($full_file_name));
+                    $encoding = Text::api_detect_encoding_html(file_get_contents($full_file_name));
                     if (!empty($encoding)) {
                         $content_type .= '; charset='.$encoding;
                     }
                     break;
                 case 'text/plain':
-                    $encoding = @api_detect_encoding(strip_tags(file_get_contents($full_file_name)));
+                    $encoding = Text::api_detect_encoding(strip_tags(file_get_contents($full_file_name)));
                     if (!empty($encoding)) {
                         $content_type .= '; charset='.$encoding;
                     }

+ 17 - 17
main/inc/lib/exercise_show_functions.lib.php

@@ -157,9 +157,9 @@ class ExerciseShowFunctions {
 			<td valign="top" align="left" >
 				<?php
                 if ($studentChoice) {
-                    echo '<span style="font-weight: bold; color: #008000;">'.nl2br(make_clickable($answerComment)).'</span>';
+                    echo '<span style="font-weight: bold; color: #008000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
                 } else {
-                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
                 }
 
 				?>
@@ -210,18 +210,18 @@ class ExerciseShowFunctions {
             if ($studentChoice) {
 				if ($answerCorrect) {
                     $color = 'green';
-					//echo '<span style="font-weight: bold; color: #008000;">'.nl2br(make_clickable($answerComment)).'</span>';
+					//echo '<span style="font-weight: bold; color: #008000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
 				} else {
                     $color = 'black';
-                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
 				}
-                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(make_clickable($answerComment)).'</span>';
+                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(Text::make_clickable($answerComment)).'</span>';
 
 			} else {
 				if ($answerCorrect) {
-					//echo '<span style="font-weight: bold; color: #000;">'.nl2br(make_clickable($answerComment)).'</span>';
+					//echo '<span style="font-weight: bold; color: #000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
 				} else {
-                    //echo '<span style="font-weight: normal; color: #000;">'.nl2br(make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: normal; color: #000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
 				}
 			}
 			?>
@@ -262,18 +262,18 @@ class ExerciseShowFunctions {
             if ($studentChoice) {
                 if ($answerCorrect) {
                     $color = 'green';
-                    //echo '<span style="font-weight: bold; color: #008000;">'.nl2br(make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: bold; color: #008000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
                 } else {
                     $color = 'black';
-                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
                 }
-                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(make_clickable($answerComment)).'</span>';
+                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(Text::make_clickable($answerComment)).'</span>';
 
             } else {
                 if ($answerCorrect) {
-                    //echo '<span style="font-weight: bold; color: #000;">'.nl2br(make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: bold; color: #000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
                 } else {
-                    //echo '<span style="font-weight: normal; color: #000;">'.nl2br(make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: normal; color: #000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
                 }
             }
             ?>
@@ -344,7 +344,7 @@ class ExerciseShowFunctions {
                 if ($studentChoice == $answerCorrect) {
                     $color = "green";
                 }
-                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(make_clickable($answerComment)).'</span>';
+                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(Text::make_clickable($answerComment)).'</span>';
             }
             ?>
         </td>
@@ -414,15 +414,15 @@ class ExerciseShowFunctions {
                 if ($studentChoice == $answerCorrect) {
                     $color = "green";
                 }
-                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(make_clickable($answerComment)).'</span>';
+                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(Text::make_clickable($answerComment)).'</span>';
             }
             if ($studentChoice == 2 || $studentChoice == '') {
-            	//echo '<span style="font-weight: bold; color: #000;">'.nl2br(make_clickable($answerComment)).'</span>';
+            	//echo '<span style="font-weight: bold; color: #000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
             } else {
 				if ($studentChoice == $answerCorrect) {
-	            	//echo '<span style="font-weight: bold; color: #008000;">'.nl2br(make_clickable($answerComment)).'</span>';
+	            	//echo '<span style="font-weight: bold; color: #008000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
 				} else {
-                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
 				}
             }
             ?>

+ 132 - 132
main/inc/lib/extra_field.lib.php

@@ -1,8 +1,8 @@
 <?php
 
 class ExtraField extends Model {
-    public $columns = array('id', 'field_type', 'field_variable', 'field_display_text', 'field_default_value', 'field_order', 'field_visible', 'field_changeable', 'field_filter', 'tms');   
-    
+    public $columns = array('id', 'field_type', 'field_variable', 'field_display_text', 'field_default_value', 'field_order', 'field_visible', 'field_changeable', 'field_filter', 'tms');
+
     CONST FIELD_TYPE_TEXT =                    1;
     CONST FIELD_TYPE_TEXTAREA =                2;
     CONST FIELD_TYPE_RADIO =                   3;
@@ -15,59 +15,59 @@ class ExtraField extends Model {
     CONST FIELD_TYPE_TAG =                     10;
     CONST FIELD_TYPE_TIMEZONE =                11;
     CONST FIELD_TYPE_SOCIAL_PROFILE =          12;
-    
+
     public $type = 'user'; //or session or course
     public $handler_id = 'user_id';
-    
+
     function __construct($type) {
         $this->type = $type;
         switch ($this->type) {
-            case 'course':                
+            case 'course':
                 $this->table_field_options  = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_OPTIONS);
                 $this->table_field_values   = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
-                
+
                 //Used for the model
-                $this->table                = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);                
-                $this->handler_id           = 'course_code';              
-                break;            
-            case 'user':                
+                $this->table                = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
+                $this->handler_id           = 'course_code';
+                break;
+            case 'user':
                 $this->table_field_options  = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
                 $this->table_field_values   = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-                
+
                 //Used for the model
                 $this->table                = Database::get_main_table(TABLE_MAIN_USER_FIELD);
                 $this->handler_id           = 'user_id';
                 break;
-            case 'session':                
+            case 'session':
                 $this->table_field_options  = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_OPTIONS);
                 $this->table_field_values   = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
-                
+
                 //Used for the model
-                $this->table                = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);                
-                $this->handler_id           = 'session_id';                
-            break;                
-        }        
-    }    
-         
+                $this->table                = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
+                $this->handler_id           = 'session_id';
+            break;
+        }
+    }
+
     public function get_count() {
         $row = Database::select('count(*) as count', $this->table, array(), 'first');
         return $row['count'];
     }
-    
-        
+
+
     public function get_all($where_conditions = array(), $order_field_options_by = null) {
         $options = Database::select('*', $this->table, array('where'=>$where_conditions, 'order' =>'field_order ASC'));
-        
+
         $field_option = new ExtraFieldOption($this->type);
         if (!empty($options)) {
-            foreach ($options as &$option) {                
+            foreach ($options as &$option) {
                 $option['options'] = $field_option->get_field_options_by_field($option['id'], false, $order_field_options_by);
             }
-        }        
+        }
         return $options;
     }
-    
-       
+
+
     public function get_handler_field_info_by_field_variable($field_variable) {
         $field_variable = Database::escape_string($field_variable);
         $sql_field = "SELECT * FROM {$this->table} WHERE field_variable = '$field_variable'";
@@ -79,8 +79,8 @@ class ExtraField extends Model {
             return false;
         }
     }
-    
-    public function get_max_field_order() {        
+
+    public function get_max_field_order() {
         $sql = "SELECT MAX(field_order) FROM {$this->table}";
         $res = Database::query($sql);
 
@@ -91,7 +91,7 @@ class ExtraField extends Model {
         }
         return $order;
     }
-    
+
     public static function get_extra_fields_by_handler($handler) {
         $types = array();
         $types[self::FIELD_TYPE_TEXT]            = get_lang('FieldTypeText');
@@ -106,58 +106,58 @@ class ExtraField extends Model {
         $types[self::FIELD_TYPE_TAG]             = get_lang('FieldTypeTag');
         $types[self::FIELD_TYPE_TIMEZONE]        = get_lang('FieldTypeTimezone');
         $types[self::FIELD_TYPE_SOCIAL_PROFILE]  = get_lang('FieldTypeSocialProfile');
-        
+
         switch ($handler) {
             case 'course':
-            case 'session':              
+            case 'session':
                 unset($types[self::FIELD_TYPE_TAG]);
-                unset($types[self::FIELD_TYPE_SOCIAL_PROFILE]);            
+                unset($types[self::FIELD_TYPE_SOCIAL_PROFILE]);
                 break;
-            case 'user':                
+            case 'user':
                 break;
         }
         return $types;
-    }    
-        
+    }
+
     public function add_elements($form, $item_id = null) {
         if (empty($form)) {
             return false;
-        }   
+        }
         $extra_data = false;
         if (!empty($item_id)) {
-            $extra_data = self::get_handler_extra_data($item_id);            
+            $extra_data = self::get_handler_extra_data($item_id);
             if ($form) {
                 $form->setDefaults($extra_data);
-            }            
-        }        
-        $extra_fields = self::get_all();        
-        $extra = ExtraField::set_extra_fields_in_form($form, $extra_data, $this->type.'_field', false, false, $this->type, $extra_fields);        
+            }
+        }
+        $extra_fields = self::get_all();
+        $extra = ExtraField::set_extra_fields_in_form($form, $extra_data, $this->type.'_field', false, false, $this->type, $extra_fields);
         return $extra;
     }
-      
-    
+
+
     public function get_handler_extra_data($item_id) {
         if (empty($item_id)) {
             return array();
         }
-		$extra_data = array();		
-        $fields = self::get_all();        
-        $field_values = new ExtraFieldValue($this->type);		
-		
+		$extra_data = array();
+        $fields = self::get_all();
+        $field_values = new ExtraFieldValue($this->type);
+
 		if (!empty($fields) > 0) {
 			foreach ($fields as $field) {
-                $field_value = $field_values->get_values_by_handler_and_field_id($item_id, $field['id']);                
+                $field_value = $field_values->get_values_by_handler_and_field_id($item_id, $field['id']);
                 if ($field_value) {
-                    $field_value = $field_value['field_value'];                    
-                    
+                    $field_value = $field_value['field_value'];
+
                     switch ($field['field_type']) {
-                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:                            
-                            $selected_options = explode('::', $field_value);                            
+                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
+                            $selected_options = explode('::', $field_value);
                             $extra_data['extra_'.$field['field_variable']]['extra_'.$field['field_variable']] = $selected_options[0];
                             $extra_data['extra_'.$field['field_variable']]['extra_'.$field['field_variable'].'_second'] = $selected_options[1];
                             break;
                         case ExtraField::FIELD_TYPE_SELECT_MULTIPLE:
-                            $field_value = explode(';', $field_value);                                
+                            $field_value = explode(';', $field_value);
                         case ExtraField::FIELD_TYPE_RADIO:
                             $extra_data['extra_'.$field['field_variable']]['extra_'.$field['field_variable']] = $field_value;
                             break;
@@ -165,13 +165,13 @@ class ExtraField extends Model {
                             $extra_data['extra_'.$field['field_variable']] = $field_value;
                             break;
                     }
-                }				
+                }
 			}
-		}        
+		}
 		return $extra_data;
     }
-    
-    public static function get_all_extra_field_by_type($field_type) {		
+
+    public function get_all_extra_field_by_type($field_type) {
 		// all the information of the field
 		$sql = "SELECT * FROM  {$this->table} WHERE field_type='".Database::escape_string($field_type)."'";
 		$result = Database::query($sql);
@@ -181,20 +181,20 @@ class ExtraField extends Model {
 		}
 		return $return;
 	}
-    
-        
+
+
     public function get_field_types() {
-        return self::get_extra_fields_by_handler($this->type);        
+        return self::get_extra_fields_by_handler($this->type);
     }
-    
-    public function get_field_type_by_id($id) {            
+
+    public function get_field_type_by_id($id) {
         $types = self::get_field_types();
         if (isset($types[$id])) {
             return $types[$id];
         }
-        return null;    
-    }    
-    
+        return null;
+    }
+
     /**
      * Converts a string like this:
      * France:Paris;Bretagne;Marseilles;Lyon|Belgique:Bruxelles;Namur;Liège;Bruges|Peru:Lima;Piura;
@@ -215,13 +215,13 @@ class ExtraField extends Model {
                 $id++;
             }
         }
-        return $options_parsed;        
+        return $options_parsed;
     }
-    
+
     static function extra_field_double_select_convert_array_to_ordered_array($options) {
         $options_parsed = array();
         if (!empty($options)) {
-            foreach ($options as $option) {            
+            foreach ($options as $option) {
                 if ($option['option_value'] == 0 ) {
                     $options_parsed[$option['id']][] = $option;
                 } else {
@@ -231,20 +231,20 @@ class ExtraField extends Model {
         }
         return $options_parsed;
     }
-    
+
     /**
-  
+
      * @param array options the result of the get_field_options_by_field() array
      */
     static function extra_field_double_select_convert_array_to_string($options) {
         $string = null;
         //var_dump($options);
         $options_parsed = self::extra_field_double_select_convert_array_to_ordered_array($options);
-        
+
         if (!empty($options_parsed)) {
             foreach ($options_parsed as $option) {
-                foreach ($option as $key => $item) {                
-                    $string .= $item['option_display_text'];          
+                foreach ($option as $key => $item) {
+                    $string .= $item['option_display_text'];
                     if ($key == 0) {
                         $string .= ':';
                     } else {
@@ -253,31 +253,31 @@ class ExtraField extends Model {
                         }
                     }
                 }
-                $string .= '|';            
+                $string .= '|';
             }
         }
-        
+
         if (!empty($string)) {
            $string = substr($string, 0, strlen($string)-1);
-        }        
+        }
         return $string;
     }
-            
+
     function clean_parameters($params) {
-        if (!isset($params['field_variable']) || empty($params['field_variable'])) {             
-            $params['field_variable'] = trim(strtolower(str_replace(" ","_", $params['field_display_text'])));	            
+        if (!isset($params['field_variable']) || empty($params['field_variable'])) {
+            $params['field_variable'] = trim(strtolower(str_replace(" ","_", $params['field_display_text'])));
         }
-        
+
         if (!isset($params['field_order'])) {
             $max_order = self::get_max_field_order();
             $params['field_order'] = $max_order;
         }
         return $params;
     }
-    
+
     public function save($params, $show_query = false) {
-        $session_field_info = self::get_handler_field_info_by_field_variable($params['field_variable']);        
-        $params = self::clean_parameters($params);            
+        $session_field_info = self::get_handler_field_info_by_field_variable($params['field_variable']);
+        $params = self::clean_parameters($params);
         if ($session_field_info) {
             return $session_field_info['id'];
         } else {
@@ -285,57 +285,57 @@ class ExtraField extends Model {
                 $params['tms'] = api_get_utc_datetime();
             }
             $id = parent::save($params, $show_query);
-            if ($id) {            
+            if ($id) {
                 $session_field_option = new SessionFieldOption();
                 $params['field_id'] = $id;
                 $session_field_option->save($params);
             }
             return $id;
-        } 
+        }
      }
-     
-          
+
+
     public function update($params) {
-        $params = self::clean_parameters($params);        
-        if (isset($params['id'])) {            
+        $params = self::clean_parameters($params);
+        if (isset($params['id'])) {
              $field_option = new ExtraFieldOption($this->type);
              $params['field_id'] = $params['id'];
              $field_option->save($params);
          }
-         parent::update($params);         
+         parent::update($params);
     }
-     
+
     public function delete($id) {
 	    parent::delete($id);
-        $field_option = new ExtraFieldOption($this->type);        
+        $field_option = new ExtraFieldOption($this->type);
         $field_option->delete_all_options_by_field_id($id);
-        
+
         $session_field_values = new ExtraFieldValue($this->type);
-        $session_field_values->delete_all_values_by_field_id($id);       
+        $session_field_values->delete_all_values_by_field_id($id);
     }
-    
-    static function set_extra_fields_in_form($form, $extra_data, $form_name, $admin_permissions = false, $user_id = null, $type = 'user', $extra = null) {          
+
+    static function set_extra_fields_in_form($form, $extra_data, $form_name, $admin_permissions = false, $user_id = null, $type = 'user', $extra = null) {
         $user_id = intval($user_id);
-        
+
         // User extra fields
         if ($type == 'user') {
-            $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC', true, null, true);            
-        }       
-        
+            $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC', true, null, true);
+        }
+
         $jquery_ready_content = null;
-        
+
         if (!empty($extra))
-        foreach ($extra as $field_details) {       
+        foreach ($extra as $field_details) {
             if (!$admin_permissions) {
                 if ($field_details['field_visible'] == 0) {
                     continue;
                 }
-            }           
+            }
             switch ($field_details['field_type']) {
                 case ExtraField::FIELD_TYPE_TEXT:
                     $form->addElement('text', 'extra_'.$field_details['field_variable'], $field_details['field_display_text'], array('class' => 'span4'));
                     $form->applyFilter('extra_'.$field_details['field_variable'], 'stripslashes');
-                    $form->applyFilter('extra_'.$field_details['field_variable'], 'trim');                    
+                    $form->applyFilter('extra_'.$field_details['field_variable'], 'trim');
                     if (!$admin_permissions) {
                         if ($field_details['field_visible'] == 0)	$form->freeze('extra_'.$field_details['field_variable']);
                     }
@@ -364,20 +364,20 @@ class ExtraField extends Model {
                     $get_lang_variables = false;
                     if (in_array($field_details['field_variable'], array('mail_notify_message','mail_notify_invitation', 'mail_notify_group_message'))) {
                         $get_lang_variables = true;
-                    }                
+                    }
                     $options = array();
-                   
+
                     foreach ($field_details['options'] as $option_id => $option_details) {
                         //$options[$option_details['option_value']] = $option_details['option_display_text'];
                         if ($get_lang_variables) {
                             $options[$option_details['option_value']] = get_lang($option_details['option_display_text']);
                         } else {
-                          $options[$option_details['option_value']] = $option_details['option_display_text'];  
+                          $options[$option_details['option_value']] = $option_details['option_display_text'];
                         }
                     }
                     if ($get_lang_variables) {
                         $field_details['field_display_text'] = get_lang($field_details['field_display_text']);
-                    }                    
+                    }
                     //chzn-select doesn't work for sessions??
                     $form->addElement('select','extra_'.$field_details['field_variable'], $field_details['field_display_text'], $options, array('class'=>'', 'id'=>'extra_'.$field_details['field_variable']));
                     if (!$admin_permissions) {
@@ -405,7 +405,7 @@ class ExtraField extends Model {
                     $form -> setDefaults($defaults);
                     if (!$admin_permissions) {
                         if ($field_details['field_visible'] == 0) {
-                            $form->freeze('extra_'.$field_details['field_variable']);                            
+                            $form->freeze('extra_'.$field_details['field_variable']);
                         }
                     }
                     $form->applyFilter('theme', 'trim');
@@ -424,15 +424,15 @@ class ExtraField extends Model {
                     break;
                 case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
                     $first_select_id = 'first_extra_'.$field_details['field_variable'];
-                    
+
                     $url = api_get_path(WEB_AJAX_PATH).'extra_field.ajax.php?1=1';
 
-                    $jquery_ready_content .= '                        
-                        $("#'.$first_select_id.'").on("change", function() {                   
+                    $jquery_ready_content .= '
+                        $("#'.$first_select_id.'").on("change", function() {
                             var id = $(this).val();
                             if (id) {
-                                $.ajax({ 
-                                    url: "'.$url.'&a=get_second_select_options", 
+                                $.ajax({
+                                    url: "'.$url.'&a=get_second_select_options",
                                     dataType: "json",
                                     data: "type='.$type.'&field_id='.$field_details['id'].'&option_value_id="+id,
                                     success: function(data) {
@@ -442,28 +442,28 @@ class ExtraField extends Model {
                                                 value: index,
                                                 text: value
                                             }));
-                                        });                           
-                                    },            
-                                });  
+                                        });
+                                    },
+                                });
                             } else {
                                 $("#second_extra_'.$field_details['field_variable'].'").empty();
                             }
                         });';
-                    
+
                     $first_id = null;
                     $second_id = null;
-                    
+
                     if (!empty($extra_data)) {
                         $first_id = $extra_data['extra_'.$field_details['field_variable']]['extra_'.$field_details['field_variable']];
-                        $second_id = $extra_data['extra_'.$field_details['field_variable']]['extra_'.$field_details['field_variable'].'_second'];                        
+                        $second_id = $extra_data['extra_'.$field_details['field_variable']]['extra_'.$field_details['field_variable'].'_second'];
                     }
 
                     $options = ExtraField::extra_field_double_select_convert_array_to_ordered_array($field_details['options']);
                     $values = array('' => get_lang('Select'));
-                    
+
                     $second_values = array();
-                    if (!empty($options)) {                        
-                        foreach ($options as $option) {                            
+                    if (!empty($options)) {
+                        foreach ($options as $option) {
                             foreach ($option as $sub_option) {
                                 if ($sub_option['option_value'] == '0') {
                                     $values[$sub_option['id']] = $sub_option['option_display_text'];
@@ -474,12 +474,12 @@ class ExtraField extends Model {
                                 }
                             }
                         }
-                    }                    
+                    }
                     $group = array();
                     $group[] = $form->createElement('select', 'extra_'.$field_details['field_variable'], null, $values, array('id' => $first_select_id));
                     $group[] = $form->createElement('select', 'extra_'.$field_details['field_variable'].'_second', null, $second_values, array('id'=>'second_extra_'.$field_details['field_variable']));
                     $form->addGroup($group, 'extra_'.$field_details['field_variable'], $field_details['field_display_text'], '&nbsp;');
-                    
+
                     if (!$admin_permissions) {
                         if ($field_details['field_visible'] == 0) {
                             $form->freeze('extra_'.$field_details['field_variable']);
@@ -491,7 +491,7 @@ class ExtraField extends Model {
                     break;
                 case ExtraField::FIELD_TYPE_TAG:
                     //the magic should be here
-                    $user_tags = UserManager::get_user_tags($user_id, $field_details['id']);                    
+                    $user_tags = UserManager::get_user_tags($user_id, $field_details['id']);
 
                     $tag_list = '';
                     if (is_array($user_tags) && count($user_tags) > 0) {
@@ -517,7 +517,7 @@ class ExtraField extends Model {
                         filter_case: true,
                         filter_hide: true,
                         complete_text:"$complete_text",
-                        firstselected: false,             
+                        firstselected: false,
                         filter_selected: true,
                         newel: true
                     });
@@ -531,17 +531,17 @@ EOF;
                     // get the social network's favicon
                     $icon_path = UserManager::get_favicon_from_url($extra_data['extra_'.$field_details['field_variable']], $field_details['field_default_value']);
                     // special hack for hi5
-                    $leftpad = '1.7'; 
-                    $top = '0.4'; 
-                    $domain = parse_url($icon_path, PHP_URL_HOST); 
+                    $leftpad = '1.7';
+                    $top = '0.4';
+                    $domain = parse_url($icon_path, PHP_URL_HOST);
                     if ($domain == 'www.hi5.com' or $domain == 'hi5.com') {
-                        $leftpad = '3'; $top = '0';                        
+                        $leftpad = '3'; $top = '0';
                     }
                     // print the input field
                     $form->addElement('text', 'extra_'.$field_details['field_variable'], $field_details['field_display_text'], array('size' => 60, 'style' => 'background-image: url(\''.$icon_path.'\'); background-repeat: no-repeat; background-position: 0.4em '.$top.'em; padding-left: '.$leftpad.'em; '));
                     $form->applyFilter('extra_'.$field_details['field_variable'], 'stripslashes');
                     $form->applyFilter('extra_'.$field_details['field_variable'], 'trim');
-                    if ($field_details['field_visible'] == 0) {	
+                    if ($field_details['field_visible'] == 0) {
                         $form->freeze('extra_'.$field_details['field_variable']);
                     }
                     break;

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

@@ -200,7 +200,7 @@ if ($docs_and_folders) {
 		$row[] = '<a href="#" onclick="javascript: OpenFile(\''.$http_www.'/'.$id['title'].'\', \''.$sType.'\');return false;">'.$id['title'].'</a>';
 		//comments => display comment under the document name
 		//$row[] = $invisibility_span_open.nl2br(htmlspecialchars($id['comment'])).$invisibility_span_close;
-		$display_size = format_file_size($size);
+		$display_size = Text::format_file_size($size);
 		$row[] = '<span style="display:none;">'.$size.'</span>'.$invisibility_span_open.$display_size.$invisibility_span_close;
 		//last edit date
 		$display_date = date('d.m.Y', (strtotime($id['lastedit_date'])));

+ 0 - 3
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/ajaxfilemanager.php

@@ -99,9 +99,6 @@ if(!empty($_GET['view'])) {
 	?>
 	<!--var shared_folder_session = '<?php //echo get_lang('UserFolders').' ('.api_get_session_name($course_session).')';?>'; --><!--// problem does not refresh, does not synchronize with javascript -->
 	var shared_folder_session = '<?php echo get_lang('UserFolders').'*';?>';
-	<?php
-
-	//$userinfo=Database::get_user_info_from_id(substr(basename($folderInfo['path']), 8));	// problem with $folderInfo['path'] does not refresh, sincronisation with javascript?>
 	<!--var shared_user_folder = '<?php //echo api_get_person_name($userinfo['firstname'], $userinfo['lastname']);?>'; --><!--// problem does not refresh, does not synchronize with javascript -->
 	var shared_user_folder = '<?php echo get_lang('User');?>';
 

+ 2 - 2
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/class.manager.php

@@ -96,8 +96,8 @@ class manager
             if (sizeof($folderInfo)) {
                 //for Chamilo in a name folder, replace num user by user names
                 if (preg_match('/sf_user_/', basename($this->getCurrentFolderPath()))) {
-                    $userinfo = Database::get_user_info_from_id(substr(basename($this->getCurrentFolderPath()), 8));
-                    $this->currentFolderInfo['name'] = api_get_person_name($userinfo['firstname'], $userinfo['lastname']);
+                    $userinfo = api_get_user_info(substr(basename($this->getCurrentFolderPath()), 8));
+                    $this->currentFolderInfo['name'] = $userinfo['complete_name'];
                 } else {
                     $this->currentFolderInfo['name'] = str_replace('_', ' ', basename($this->getCurrentFolderPath())); //for Chamilo. Prevent long directory name
                 }

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

@@ -380,7 +380,7 @@ class FCKeditor
             $toolbar_config[$this->ToolbarSet] = array();
             if (preg_match('/[a-zA-Z_]+/', $toolbar_dir) && preg_match('/[a-zA-Z_]+/', $this->ToolbarSet)) { // A security check.
                 // Seeking the toolbar.
-                @include api_get_path(LIBRARY_PATH).'fckeditor/toolbars/'.$toolbar_dir.'/'.api_camel_case_to_underscore($this->ToolbarSet).'.php';
+                @include api_get_path(LIBRARY_PATH).'fckeditor/toolbars/'.$toolbar_dir.'/'.Text::api_camel_case_to_underscore($this->ToolbarSet).'.php';
                 if (!isset($config['ToolbarSets']['Normal'])) {
                     // No toolbar has been found yet.
                     if ($toolbar_dir == 'default') {
@@ -388,7 +388,7 @@ class FCKeditor
                         $this->ToolbarSet = 'Default';
                     } else {
                         // The custom toolbar does not exist, then trying to load the default one.
-                        @include api_get_path(LIBRARY_PATH).'fckeditor/toolbars/default/'.api_camel_case_to_underscore($this->ToolbarSet).'.php';
+                        @include api_get_path(LIBRARY_PATH).'fckeditor/toolbars/default/'.Text::api_camel_case_to_underscore($this->ToolbarSet).'.php';
                         if (!isset($config['ToolbarSets']['Normal'])) {
                             // It does not exist in default toolbar definitions, giving up.
                             $this->ToolbarSet = 'Default';

+ 1 - 1
main/inc/lib/fckeditor/repository.php

@@ -58,7 +58,7 @@ if (api_is_in_course()) {
     $sys_course_path = api_get_path(SYS_COURSE_PATH);
     $base_work_dir = $sys_course_path.$course_dir;
     $current_session_id = api_get_session_id();
-    $userinfo = Database::get_user_info_from_id(api_get_user_id());
+    $userinfo = api_get_user_info(api_get_user_id());
 
     if ($current_session_id == 0) {
         //Create shared folder. Necessary for courses recycled. Allways session_id should be zero. Allway should be created from a base course, never from a session.

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

@@ -782,7 +782,7 @@ class FileManager
                 // Not used at the moment, but could be handy if we want to limit the size of an upload (e.g. image upload in html editor).
                 $max_file_size = intval($_POST['MAX_FILE_SIZE']);
                 if ($show_output) {
-                    Display::display_error_message(get_lang('UplExceedMaxPostSize').format_file_size($max_file_size));
+                    Display::display_error_message(get_lang('UplExceedMaxPostSize').Text::format_file_size($max_file_size));
                 }
 
                 return false;

+ 12 - 12
main/inc/lib/import.lib.php

@@ -10,11 +10,11 @@
  * @package	 chamilo.library
  */
 class Import {
-    
+
     /**
      *
      * @param string $path
-     * @return \CsvReader 
+     * @return \CsvReader
      */
     static function csv_reader($path)
     {
@@ -37,8 +37,8 @@ class Import {
 	 *   ...
 	 * @param string $filename	The path to the CSV-file which should be imported.
 	 * @return array			Returns an array (in the system encoding) that contains all data from the CSV-file.
-     * 
-     * 
+     *
+     *
      * @deprecated use cvs_reader instead
 	 */
 	static function csv_to_array($filename, $csv_order = 'vertical') {
@@ -68,17 +68,17 @@ class Import {
 		if ($handle === false) {
 			return $result;
 		}
-        
+
         if ($csv_order == 'vertical') {
-            $keys = api_fgetcsv($handle, null, ';');        
+            $keys = Text::api_fgetcsv($handle, null, ';');
             foreach ($keys as $key => &$key_value) {
                 $key_value = api_to_system_encoding($key_value, $from_encoding);
             }
         }
-        
-		while (($row_tmp = api_fgetcsv($handle, null, ';')) !== false) {
+
+		while (($row_tmp = Text::api_fgetcsv($handle, null, ';')) !== false) {
 			$row = array();
-			// Avoid empty lines in csv            
+			// Avoid empty lines in csv
 			if (is_array($row_tmp) && count($row_tmp) > 0 && $row_tmp[0] != '') {
 				if (!is_null($row_tmp[0])) {
                     if ($csv_order == 'vertical') {
@@ -90,18 +90,18 @@ class Import {
                         $count = 1;
                         foreach ($row_tmp as $index => $value) {
                             if ($count == 1) {
-                                $first = $value;                                
+                                $first = $value;
                             } else {
                                 $row[$first][] = api_to_system_encoding($value, $from_encoding);
                             }
                             $count++;
                         }
-                    }                    
+                    }
 					$result[] = $row;
 				}
 			}
 		}
-        
+
 		fclose($handle);
 		return $result;
 	}

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

@@ -115,16 +115,16 @@ function addlinkcategory($type) {
 			$catlinkstatus = get_lang('LinkAdded');
 			Database :: query($sql);
 			$link_id = Database :: insert_id();
-            
+
             if ($link_id) {
-                api_set_default_visibility($link_id, TOOL_LINK);           
+                api_set_default_visibility($link_id, TOOL_LINK);
             }
 
 			if ((api_get_setting('search_enabled') == 'true') && $link_id && extension_loaded('xapian')) {
 				require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
 				require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
 				require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
-                
+
                 $course_int_id = api_get_course_int_id();
 
 				$courseid = api_get_course_id();
@@ -440,9 +440,9 @@ function editlinkcategory($type) {
 			// Update search enchine and its values table if enabled.
 			if (api_get_setting('search_enabled') == 'true') {
 				$link_id = intval($_POST['id']);
-                
+
                 $course_int_id = api_get_course_int_id();
-                
+
 				$course_id = api_get_course_id();
 				$link_url = Database :: escape_string($_POST['urllink']);
 				$link_title = Database :: escape_string($_POST['title']);
@@ -549,7 +549,7 @@ function editlinkcategory($type) {
 
 		// This is used to put the modified info of the category-form into the database.
 		if ($submit_category) {
-			$sql = "UPDATE " . $tbl_categories . " 
+			$sql = "UPDATE " . $tbl_categories . "
                     SET category_title='" . Database :: escape_string($_POST['category_title']) . "', description='" . Database :: escape_string($_POST['description']) . "'
 			        WHERE c_id = $course_id AND id='" . Database :: escape_string($_POST['id']) . "'";
 			Database :: query($sql);
@@ -943,7 +943,7 @@ function import_csvfile() {
 
 				// Modified by Ivan Tcholakov, 01-FEB-2010.
 				//while (($data = fgetcsv($myFile, 32768, $listsep))) {
-				while (($data = api_fgetcsv($myFile, null, $listsep))) {
+				while (($data = Text::api_fgetcsv($myFile, null, $listsep))) {
 					//
 					foreach ($data as $i => & $text) {
 						$linkdata[$columns[$i]] = $text;

+ 36 - 49
main/inc/lib/main_api.lib.php

@@ -368,6 +368,18 @@ define('TEACHER_HTML', 3);
 define('STUDENT_HTML_FULLPAGE', 4);
 define('TEACHER_HTML_FULLPAGE', 5);
 
+
+define('EXERCISE_NUMBER_OF_DECIMALS', 2);
+
+
+/* XML processing functions */
+
+// A regular expression for accessing declared encoding within xml-formatted text.
+// Published by Steve Minutillo,
+// http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss/
+define('_PCRE_XML_ENCODING', '/<\?xml.*encoding=[\'"](.*?)[\'"].*\?>/m');
+
+
 /* PATHS & FILES - ROUTINES */
 
 /**
@@ -927,6 +939,14 @@ function api_protect_course_script($print_headers = false, $allow_session_admins
     global $is_allowed_in_course;
     $is_visible = false;
 
+    $course_info = api_get_course_info();
+
+    //If course is not set then is not allowed to enter in a course page
+
+    if (empty($course_info)) {
+        api_not_allowed($print_headers);
+    }
+
     if (api_is_drh()) {
         return true;
     }
@@ -935,8 +955,6 @@ function api_protect_course_script($print_headers = false, $allow_session_admins
     	return true;
     }
 
-    $course_info = api_get_course_info();
-
     if (isset($course_info) && isset($course_info['visibility'])) {
     	switch ($course_info['visibility']) {
     		default:
@@ -1133,6 +1151,13 @@ function _api_format_user($user, $add_password = false) {
     if (!empty($user['username'])) {
         $result['complete_name_with_username'] 	= $result['complete_name'].' ('.$user['username'].')';
     }
+
+    $result['complete_name_login_as']= $result['complete_name'];
+
+    if (!empty($user['username'])) {
+        $result['complete_name_login_as'] = $result['complete_name'].' ('.sprintf(get_lang('LoginX'), $user['username']).')';
+    }
+
     $result['firstname'] 		= $firstname;
     $result['lastname'] 		= $lastname;
 
@@ -1235,7 +1260,7 @@ function api_get_user_info($user_id = '', $check_if_user_is_online = false, $sho
     if (Database::num_rows($result) > 0) {
         $result_array = Database::fetch_array($result);
 		if ($check_if_user_is_online) {
-            $use_status_in_platform = user_is_online($user_id);
+            $use_status_in_platform = Online::user_is_online($user_id);
 
 			$result_array['user_is_online'] = $use_status_in_platform;
             $user_online_in_chat = 0;
@@ -1410,6 +1435,7 @@ function api_get_course_info($course_code = null, $add_extra_values = false) {
         $_course = array();
         if (Database::num_rows($result) > 0) {
             $course_data = Database::fetch_array($result);
+
             if ($add_extra_values) {
                 $extra_field_values = new ExtraField('course');
                 $course_data['extra_fields'] = $extra_field_values->get_handler_extra_data($course_code);
@@ -1419,7 +1445,9 @@ function api_get_course_info($course_code = null, $add_extra_values = false) {
         return $_course;
     }
     global $_course;
-    if ($_course == '-1') $_course = array();
+    if ($_course == '-1') {
+        $_course = array();
+    }
     return $_course;
 }
 
@@ -1443,9 +1471,10 @@ function api_get_course_info_by_id($id = null, $add_extra_values = false) {
         $_course = array();
         if (Database::num_rows($result) > 0) {
             $course_data = Database::fetch_array($result);
+            var_dump($course_data);
             if ($add_extra_values) {
                 $extra_field_values = new ExtraField('course');
-                $course_data['extra_fields'] = $extra_field_values->get_handler_extra_data($course_code);
+                $course_data['extra_fields'] = $extra_field_values->get_handler_extra_data($course_data['code']);
             }
             $_course = api_format_course_array($course_data);
         }
@@ -1466,8 +1495,8 @@ function api_format_course_array($course_data) {
 
     $_course = array();
 
-    $_course['id'           ]         = $course_data['code'           ];
-    $_course['real_id'      ]         = $course_data['id'              ];
+    $_course['id'           ]         = $course_data['code'];
+    $_course['real_id'      ]         = $course_data['id'];
 
     // Added
     $_course['code'         ]         = $course_data['code'           ];
@@ -5371,25 +5400,6 @@ function api_get_tool_information_by_name($name) {
 
 /* DEPRECATED FUNCTIONS */
 
-/**
- * Deprecated, use api_trunc_str() instead.
- */
-function shorten($input, $length = 15, $encoding = null) {
-    $length = intval($length);
-    if (!$length) {
-        $length = 15;
-    }
-    return api_trunc_str($input, $length, '...', false, $encoding);
-}
-
-/**
- * DEPRECATED, use api_get_setting instead
- */
-function get_setting($variable, $key = NULL) {
-    global $_setting;
-    return api_get_setting($variable, $key);
-}
-
 /**
  * deprecated: use api_is_allowed_to_edit() instead
  */
@@ -5397,26 +5407,6 @@ function is_allowed_to_edit() {
     return api_is_allowed_to_edit();
 }
 
-/**
- * deprecated: 19-SEP-2009: Use api_get_path(TO_SYS, $url) instead.
- */
-function api_url_to_local_path($url) {
-    return api_get_path(TO_SYS, $url);
-}
-
-/**
- * @deprecated 27-SEP-2009: Use Database::store_result($result) instead.
- */
-function api_store_result($result) {
-    return Database::store_result($result);
-}
-
-/**
- * @deprecated 28-SEP-2009: Use Database::query($query, $file, $line) instead.
- */
-function api_sql_query($query, $file = '', $line = 0) {
-    return Database::query($query, $file, $line);
-}
 
 /**
  *
@@ -5521,9 +5511,6 @@ function api_send_mail($to, $subject, $message, $additional_headers = null, $add
     return 1;
 }
 
-/* END OF DEPRECATED FUNCTIONS SECTION */
-
-
 /**
  * Function used to protect a "global" admin script.
  * The function blocks access when the user has no global platform admin rights.

+ 24 - 108
main/inc/lib/message.lib.php

@@ -18,13 +18,13 @@ class MessageManager
 {
     public static function get_online_user_list($current_user_id)
     {
-        global $_configuration;
         //@todo this is a bad idea to parse all users online
-        $count = who_is_online_count();
-        $userlist = who_is_online(0, $count, null, null, 30, true);
+        $count = Online::who_is_online_count();
+        $userlist = Online::who_is_online(0, $count, null, null, 30, true);
         $online_user_list = array();
         foreach ($userlist as $user_id) {
-            $online_user_list[$user_id] = GetFullUserName($user_id).($current_user_id == $user_id ? ("&nbsp;(".get_lang(
+            $userInfo = api_get_user_info($user_id);
+            $online_user_list[$user_id] = $userInfo['complete_name'].($current_user_id == $user_id ? ("&nbsp;(".get_lang(
                 'Myself'
             ).")") : (""));
         }
@@ -57,8 +57,8 @@ class MessageManager
      */
     public static function users_connected_by_id()
     {
-        $count = who_is_online_count();
-        $user_connect = who_is_online(0, $count, null, null, 30, true);
+        $count = Online::who_is_online_count();
+        $user_connect = Online::who_is_online(0, $count, null, null, 30, true);
         $user_id_list = array();
         for ($i = 0; $i < count($user_connect); $i++) {
             $user_id_list[$i] = $user_connect[$i][0];
@@ -124,7 +124,7 @@ class MessageManager
         while ($result = Database::fetch_row($sql_result)) {
             $message[0] = $result[0];
             $result[2] = Security::remove_XSS($result[2], STUDENT, true);
-            $result[2] = cut($result[2], 80, true);
+            $result[2] = Text::cut($result[2], 80, true);
 
             if ($result[4] == 1) {
                 $class = 'class = "unread"';
@@ -135,9 +135,9 @@ class MessageManager
             if (isset($_GET['f']) && $_GET['f'] == 'social') {
                 $link = '&f=social';
             }
-            $message[1] = '<a '.$class.' href="view_message.php?id='.$result[0].$link.'">'.$result[2].'</a><br />'.GetFullUserName(
-                ($result[1])
-            );
+            $userInfo = api_get_user_info($result[1]);
+
+            $message[1] = '<a '.$class.' href="view_message.php?id='.$result[0].$link.'">'.$result[2].'</a><br />'.$userInfo['complete_name'];
             $message[3] = '<a href="new_message.php?re_id='.$result[0].$link.'">'.Display::return_icon(
                 'message_reply.png',
                 get_lang('ReplyToMessage')
@@ -215,7 +215,7 @@ class MessageManager
             if ($total_filesize > intval(api_get_setting('message_max_upload_filesize'))) {
                 return sprintf(
                     get_lang("FilesSizeExceedsX"),
-                    format_file_size(api_get_setting('message_max_upload_filesize'))
+                    Text::format_file_size(api_get_setting('message_max_upload_filesize'))
                 );
             }
         }
@@ -289,14 +289,14 @@ class MessageManager
 
             //Load user settings
             $notification = new Notification();
+            $sender_info = array();
 
             if (empty($group_id)) {
-                $sender_info = array();
                 if (!empty($user_sender_id)) {
                     $sender_info = api_get_user_info($user_sender_id);
                 }
                 $notification->save_notification(
-                    NOTIFICATION_TYPE_MESSAGE,
+                    Notification::NOTIFICATION_TYPE_MESSAGE,
                     array($receiver_user_id),
                     $subject,
                     $content,
@@ -743,18 +743,17 @@ class MessageManager
             }
             $class = 'class = "read"';
             $result[2] = Security::remove_XSS($result[2]);
+            $userInfo = api_get_user_info($result[4]);
 
             if ($request === true) {
-                $message[1] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.GetFullUserName(
-                    $result[4]
-                ).'</a>';
+
+                $message[1] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.$userInfo['complete_name'].'</a>';
                 $message[2] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.str_replace(
                     "\\",
                     "",
                     $result[2]
                 ).'</a>';
                 $message[3] = api_convert_and_format_date($result[3], DATE_TIME_FORMAT_LONG); //date stays the same
-
                 $message[4] = '&nbsp;&nbsp;<a onclick="delete_one_message_outbox('.$result[0].')" href="javascript:void(0)"  >'.Display::return_icon(
                     'delete.png',
                     get_lang('DeleteMessage')
@@ -764,10 +763,7 @@ class MessageManager
                 if ($_GET['f'] == 'social') {
                     $link = '&f=social';
                 }
-                $message[1] = '<a '.$class.' onclick="show_sent_message ('.$result[0].')" href="../messages/view_message.php?id_send='.$result[0].$link.'">'.$result[2].'</a><br />'.GetFullUserName(
-                    $result[4]
-                );
-                //$message[2] = '<a '.$class.' onclick="show_sent_message ('.$result[0].')" href="../messages/view_message.php?id_send='.$result[0].$link.'">'.$result[2].'</a>';
+                $message[1] = '<a '.$class.' onclick="show_sent_message ('.$result[0].')" href="../messages/view_message.php?id_send='.$result[0].$link.'">'.$result[2].'</a><br />'.$userInfo['complete_name'];
                 $message[2] = api_convert_and_format_date($result[3], DATE_TIME_FORMAT_LONG); //date stays the same
                 $message[3] = '<a href="outbox.php?action=deleteone&id='.$result[0].'&f='.Security::remove_XSS(
                     $_GET['f']
@@ -863,12 +859,13 @@ class MessageManager
         }
 
         if (api_get_setting('allow_social_tool') == 'true') {
+            $userInfo = api_get_user_info($row[2]);
             if ($source == 'outbox') {
                 $message_content .= get_lang('From').': <a href="'.api_get_path(
                     WEB_PATH
                 ).'main/social/profile.php?u='.$user_sender_id.'">'.$name.'</a> '.api_strtolower(
                     get_lang('To')
-                ).'&nbsp;<b>'.GetFullUserName($row[2]).'</b>';
+                ).'&nbsp;<b>'.$userInfo['complete_name'].'</b>';
             } else {
                 $message_content .= get_lang('From').' <a href="'.api_get_path(
                     WEB_PATH
@@ -877,10 +874,11 @@ class MessageManager
                 ).'&nbsp;<b>'.get_lang('Me').'</b>';
             }
         } else {
+            $userInfo = api_get_user_info($row['user_receiver_id']);
             if ($source == 'outbox') {
                 $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(
                     get_lang('To')
-                ).' <b>'.GetFullUserName($row['user_receiver_id']).'</b>';
+                ).' <b>'.$userInfo['complete_name'].'</b>';
             } else {
                 $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(
                     get_lang('To')
@@ -932,86 +930,6 @@ class MessageManager
     }
 
 
-    /**
-     * display message box sent showing it into outbox
-     * @return void
-     */
-    public static function show_message_box_sent()
-    {
-        global $charset;
-
-        $table_message = Database::get_main_table(TABLE_MESSAGE);
-        $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
-
-        $message_id = '';
-        if (is_numeric($_GET['id_send'])) {
-            $query = "SELECT * FROM $table_message WHERE user_sender_id=".api_get_user_id()." AND id=".intval(
-                Database::escape_string($_GET['id_send'])
-            )." AND msg_status=4;";
-            $result = Database::query($query);
-            $message_id = intval($_GET['id_send']);
-        }
-        $path = 'outbox.php';
-
-        // get file attachments by message id
-        $files_attachments = self::get_links_message_attachment_files($message_id, 'outbox');
-
-        $row = Database::fetch_array($result);
-        $user_con = self::users_connected_by_id();
-        $band = 0;
-        $reply = '';
-        for ($i = 0; $i < count($user_con); $i++) {
-            if ($row[1] == $user_con[$i]) {
-                $band = 1;
-            }
-        }
-        echo '<div class=actions>';
-        echo '<a onclick="close_and_open_outbox()" href="javascript:void(0)">'.Display::return_icon(
-            'folder_up.gif',
-            api_xml_http_response_encode(get_lang('BackToOutbox'))
-        ).api_xml_http_response_encode(get_lang('BackToOutbox')).'</a>';
-        echo '<a onclick="delete_one_message_outbox('.$row[0].')" href="javascript:void(0)"  >'.Display::return_icon(
-            'delete.png',
-            api_xml_http_response_encode(get_lang('DeleteMessage'))
-        ).api_xml_http_response_encode(get_lang('DeleteMessage')).'</a>';
-        echo '</div><br />';
-        echo '
-		<table class="message_view_table" >
-		    <TR>
-		      <TD width=10>&nbsp; </TD>
-		      <TD vAlign=top width="100%">
-		      	<TABLE>
-		            <TR>
-		              <TD width="100%">
-		                    <TR> <h1>'.str_replace("\\", "", api_xml_http_response_encode($row[5])).'</h1></TR>
-		              </TD>
-		              <TR>
-		              	<TD>'.api_xml_http_response_encode(
-            get_lang('From').'&nbsp;<b>'.GetFullUserName($row[1]).'</b> '.api_strtolower(
-                get_lang('To')
-            ).'&nbsp;  <b>'.GetFullUserName($row[2])
-        ).'</b> </TD>
-		              </TR>
-		              <TR>
-		              <TD >'.api_xml_http_response_encode(get_lang('Date').'&nbsp; '.$row[4]).'</TD>
-		              </TR>
-		            </TR>
-		        </TABLE>
-		        <br />
-		        <TABLE height="209px" width="100%" bgColor=#ffffff>
-		          <TBODY>
-		            <TR>
-		              <TD vAlign=top>'.str_replace("\\", "", api_xml_http_response_encode($row[6])).'</TD>
-		            </TR>
-		          </TBODY>
-		        </TABLE>
-		        <div id="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>
-		        <DIV class=HT style="PADDING-BOTTOM: 5px"> </DIV></TD>
-		      <TD width=10>&nbsp;</TD>
-		    </TR>
-		</TABLE>';
-    }
-
     /**
      * get user id by user email
      * @param string $user_email
@@ -1144,10 +1062,6 @@ class MessageManager
                 $html .= '<div class="span2">';
                 $html .= $user_info;
                 $html .= '</div>';
-                //group_topics.php?action=delete&id=3&topic_id=6
-                //$date.
-
-                //$html .= Display::div($title.Security::remove_XSS(cut($topic['content'], 150), STUDENT, true).$user_info, array('class'=>'group_discussions_info')).' </tr> '.$actions.'</table>';
 
                 $html .= '</div>'; //rounded_div
 
@@ -1457,7 +1371,7 @@ class MessageManager
                 while ($row_file = Database::fetch_array($rs_file)) {
                     $archiveFile = $row_file['path'];
                     $filename = $row_file['filename'];
-                    $filesize = format_file_size($row_file['size']);
+                    $filesize = Text::format_file_size($row_file['size']);
                     $filecomment = $row_file['comment'];
                     $links_attach_file[] = $attach_icon.'&nbsp;<a href="'.$archiveURL.$archiveFile.'">'.$filename.'</a>&nbsp;('.$filesize.')'.(!empty($filecomment) ? '&nbsp;-&nbsp;<i>'.$filecomment.'</i>' : '');
                 }
@@ -1583,6 +1497,8 @@ class MessageManager
             'BackToOutbox'
         ).'</a>';
 
+        $html = null;
+
         if (isset ($_REQUEST['action'])) {
             switch ($_REQUEST['action']) {
                 case 'delete' :

+ 14 - 8
main/inc/lib/notification.lib.php

@@ -19,23 +19,25 @@ class Notification extends Model
     public $columns = array('id', 'dest_user_id', 'dest_mail', 'title', 'content', 'send_freq', 'created_at', 'sent_at');
     public $max_content_length = 254; //Max lenght of the notification.content field
     public $debug = false;
-//@todo put constants in an array
-
     public $type;
     public $admin_name;
     public $admin_email;
-//default values
+
+    public $send_email_as_user;
+
+    //default values
     const NOTIFY_MESSAGE_AT_ONCE = 1;
     const NOTIFY_MESSAGE_DAILY = 8;
     const NOTIFY_MESSAGE_WEEKLY = 12;
     const NOTIFY_MESSAGE_NO = 0;
-//mail_notify_message ("At once", "Daily", "No")
+    //mail_notify_message ("At once", "Daily", "No")
 
     const NOTIFY_INVITATION_AT_ONCE = 1;
     const NOTIFY_INVITATION_DAILY = 8;
     const NOTIFY_INVITATION_WEEKLY = 12;
     const NOTIFY_INVITATION_NO = 0;
-//mail_notify_invitation ("At once", "Daily", "No")
+
+    //mail_notify_invitation ("At once", "Daily", "No")
 
     const NOTIFY_GROUP_AT_ONCE = 1;
     const NOTIFY_GROUP_DAILY = 8;
@@ -45,10 +47,14 @@ class Notification extends Model
     const NOTIFICATION_TYPE_INVITATION = 2;
     const NOTIFICATION_TYPE_GROUP = 3;
 
-// mail_notify_group_message ("At once", "Daily", "No")
+    // mail_notify_group_message ("At once", "Daily", "No")
+
+    /**
+     *
+    */
     public function __construct()
     {
-        $this->table       = Database::get_main_table(TABLE_NOTIFICATION);
+        $this->table = Database::get_main_table(TABLE_NOTIFICATION);
 
         $this->sender_email  = api_get_setting('noreply_email_address');
         $this->sender_name   = api_get_setting('siteName');
@@ -190,7 +196,7 @@ class Notification extends Model
                 	    $params['dest_user_id']  = $user_id;
                 	    $params['dest_mail']     = $user_info['mail'];
                 	    $params['title']         = $title;
-                	    $params['content']       = cut($content, $this->max_content_length);
+                	    $params['content']       = Text::cut($content, $this->max_content_length);
                 	    $params['send_freq']     = $user_setting;
                         $params['sender_id']     = $sender_id;
                 	    $this->save($params);

+ 326 - 388
main/inc/lib/online.inc.php

@@ -19,433 +19,371 @@
 
 use \ChamiloSession as Session;
 
-function LoginCheck($uid) {
-	global $_course;
-	$uid = (int) $uid;
-	$online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
-	if (!empty($uid)) {
-        $login_ip = '';
-        if(!empty($_SERVER['REMOTE_ADDR'])) {
-		  $login_ip = Database::escape_string($_SERVER['REMOTE_ADDR']);
-        }
+class Online {
+
+    function LoginCheck($uid) {
+        global $_course;
+        $uid = (int) $uid;
+        $online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        if (!empty($uid)) {
+            $login_ip = '';
+            if(!empty($_SERVER['REMOTE_ADDR'])) {
+              $login_ip = Database::escape_string($_SERVER['REMOTE_ADDR']);
+            }
 
-		$login_date = api_get_utc_datetime();
-		$access_url_id = 1;
-		if (api_get_multiple_access_url() && api_get_current_access_url_id()!=-1) {
-			$access_url_id = api_get_current_access_url_id();
-		}
-		$session_id = api_get_session_id();
-		// if the $_course array exists this means we are in a course and we have to store this in the who's online table also
-		// to have the x users in this course feature working
-		if (is_array($_course) && count($_course)>0 && !empty($_course['id'])) {
-            $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, course, session_id, access_url_id) VALUES ($uid,$uid,'$login_date','$login_ip', '".$_course['id']."' , '$session_id' , '$access_url_id' )";
-		} else {
-            $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, session_id, access_url_id) VALUES ($uid,$uid,'$login_date','$login_ip', '$session_id', '$access_url_id')";
-		}
-		@Database::query($query);
-	}
-}
+            $login_date = api_get_utc_datetime();
+            $access_url_id = 1;
+            if (api_get_multiple_access_url() && api_get_current_access_url_id()!=-1) {
+                $access_url_id = api_get_current_access_url_id();
+            }
+            $session_id = api_get_session_id();
+            // if the $_course array exists this means we are in a course and we have to store this in the who's online table also
+            // to have the x users in this course feature working
+            if (is_array($_course) && count($_course)>0 && !empty($_course['id'])) {
+                $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, course, session_id, access_url_id) VALUES ($uid,$uid,'$login_date','$login_ip', '".$_course['id']."' , '$session_id' , '$access_url_id' )";
+            } else {
+                $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, session_id, access_url_id) VALUES ($uid,$uid,'$login_date','$login_ip', '$session_id', '$access_url_id')";
+            }
+            @Database::query($query);
+        }
+    }
 
-/**
- * This function handles the logout and is called whenever there is a $_GET['logout']
- * @return void  Directly redirects the user or leaves him where he is, but doesn't return anything
- * @author Fernando P. García <fernando@develcuy.com>
- */
-function online_logout($user_id = null, $logout_redirect = false) {
-    global $extAuthSource;
+    /**
+     * This function handles the logout and is called whenever there is a $_GET['logout']
+     * @return void  Directly redirects the user or leaves him where he is, but doesn't return anything
+     * @author Fernando P. García <fernando@develcuy.com>
+     */
+    function logout($user_id = null, $logout_redirect = false) {
+        global $extAuthSource;
 
-    // Database table definition
-    $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
+        // Database table definition
+        $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
 
-    if (empty($user_id)) {
-        $user_id = api_get_user_id();
-    }
+        if (empty($user_id)) {
+            $user_id = api_get_user_id();
+        }
 
-    //Changing global chat status to offline
-    if (api_is_global_chat_enabled()) {
-        $chat = new Chat();
-        $chat->set_user_status(0);
-    }
+        //Changing global chat status to offline
+        if (api_is_global_chat_enabled()) {
+            $chat = new Chat();
+            $chat->set_user_status(0);
+        }
 
-    // selecting the last login of the user
-    $sql_last_connection="SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='$user_id' ORDER BY login_date DESC LIMIT 0,1";
-    $q_last_connection=Database::query($sql_last_connection);
-    $i_id_last_connection = null;
-    if (Database::num_rows($q_last_connection)>0) {
-        $i_id_last_connection = Database::result($q_last_connection,0,"login_id");
-    }
+        // selecting the last login of the user
+        $sql_last_connection="SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='$user_id' ORDER BY login_date DESC LIMIT 0,1";
+        $q_last_connection=Database::query($sql_last_connection);
+        $i_id_last_connection = null;
+        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']) && !empty($i_id_last_connection)) {
-        $current_date = api_get_utc_datetime();
-        $s_sql_update_logout_date="UPDATE $tbl_track_login SET logout_date='".$current_date."' WHERE login_id = '$i_id_last_connection'";
-        Database::query($s_sql_update_logout_date);
-    }
+        if (!isset($_SESSION['login_as']) && !empty($i_id_last_connection)) {
+            $current_date = api_get_utc_datetime();
+            $s_sql_update_logout_date="UPDATE $tbl_track_login SET logout_date='".$current_date."' WHERE login_id = '$i_id_last_connection'";
+            Database::query($s_sql_update_logout_date);
+        }
 
-    LoginDelete($user_id); //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
-    $uinfo = api_get_user_info($user_id);
-    if (($uinfo['auth_source'] != PLATFORM_AUTH_SOURCE) && is_array($extAuthSource)) {
-        if (is_array($extAuthSource[$uinfo['auth_source']])) {
-            $subarray = $extAuthSource[$uinfo['auth_source']];
-            if (!empty($subarray['logout']) && file_exists($subarray['logout'])) {
-                require_once($subarray['logout']);
-                $logout_function = $uinfo['auth_source'].'_logout';
-                if (function_exists($logout_function)) {
-                    $logout_function($uinfo);
+        Online::loginDelete($user_id); //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
+        $uinfo = api_get_user_info($user_id);
+        if (($uinfo['auth_source'] != PLATFORM_AUTH_SOURCE) && is_array($extAuthSource)) {
+            if (is_array($extAuthSource[$uinfo['auth_source']])) {
+                $subarray = $extAuthSource[$uinfo['auth_source']];
+                if (!empty($subarray['logout']) && file_exists($subarray['logout'])) {
+                    require_once($subarray['logout']);
+                    $logout_function = $uinfo['auth_source'].'_logout';
+                    if (function_exists($logout_function)) {
+                        $logout_function($uinfo);
+                    }
                 }
             }
         }
-    }
 
-    require_once api_get_path(SYS_PATH) . 'main/chat/chat_functions.lib.php';
-    exit_of_chat($user_id);
+        require_once api_get_path(SYS_PATH) . 'main/chat/chat_functions.lib.php';
+        exit_of_chat($user_id);
 
-    Session::destroy();
-    if ($logout_redirect) {
-        header("Location: index.php");
-        return;
+        Session::destroy();
+        if ($logout_redirect) {
+            header("Location: index.php");
+            exit;
+        }
     }
-}
 
-/**
- * Remove all login records from the track_e_online stats table, for the given user ID.
- * @param int User ID
- * @return void
- */
-function LoginDelete($user_id) {
-	$online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
-    $user_id = intval($user_id);
-	$query = "DELETE FROM ".$online_table ." WHERE login_user_id = '".$user_id."'";
-	@Database::query($query);
-}
+    /**
+     * Remove all login records from the track_e_online stats table, for the given user ID.
+     * @param int User ID
+     * @return bool
+     */
+    function loginDelete($user_id) {
+        $online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        $user_id = intval($user_id);
+        if (empty($user_id)) {
+            return false;
+        }
+        $query = "DELETE FROM ".$online_table ." WHERE login_user_id = '".$user_id."'";
+        Database::query($query);
+        return true;
+    }
 
-function user_is_online($user_id) {
-	$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
-	$table_user			= Database::get_main_table(TABLE_MAIN_USER);
+    function user_is_online($user_id) {
+        $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        $table_user			= Database::get_main_table(TABLE_MAIN_USER);
 
 
-	$access_url_id		= api_get_current_access_url_id();
-	$time_limit			= api_get_setting('time_limit_whosonline');
+        $access_url_id		= api_get_current_access_url_id();
+        $time_limit			= api_get_setting('time_limit_whosonline');
 
-    $online_time 	= time() - $time_limit*60;
-    $limit_date		= api_get_utc_datetime($online_time);
+        $online_time 	= time() - $time_limit*60;
+        $limit_date		= api_get_utc_datetime($online_time);
 
-	$query = " SELECT login_user_id,login_date FROM ".$track_online_table ." track INNER JOIN ".$table_user ." u ON (u.user_id=track.login_user_id)
-               WHERE track.access_url_id =  $access_url_id AND
-                    login_date >= '".$limit_date."'  AND
-                    u.user_id =  $user_id
-               LIMIT 1 ";
+        $query = " SELECT login_user_id,login_date FROM ".$track_online_table ." track INNER JOIN ".$table_user ." u ON (u.user_id=track.login_user_id)
+                   WHERE track.access_url_id =  $access_url_id AND
+                        login_date >= '".$limit_date."'  AND
+                        u.user_id =  $user_id
+                   LIMIT 1 ";
 
-	$result = Database::query($query);
-	if (Database::num_rows($result)) {
-		return true;
-	}
-	return false;
+        $result = Database::query($query);
+        if (Database::num_rows($result)) {
+            return true;
+        }
+        return false;
 
-}
+    }
 
-/**
- * Gives a list of people online now (and in the last $valid minutes)
- * @return  array       For each line, a list of user IDs and login dates, or FALSE on error or empty results
- */
-function who_is_online($from, $number_of_items, $column = null, $direction = null, $time_limit = null, $friends = false) {
+    /**
+     * Gives a list of people online now (and in the last $valid minutes)
+     * @return  array       For each line, a list of user IDs and login dates, or FALSE on error or empty results
+     */
+    function who_is_online($from, $number_of_items, $column = null, $direction = null, $time_limit = null, $friends = false) {
+
+        // Time limit in seconds?
+        if (empty($time_limit)) {
+            $time_limit = api_get_setting('time_limit_whosonline');
+        } else {
+            $time_limit = intval($time_limit);
+        }
 
-    // Time limit in seconds?
-    if (empty($time_limit)) {
-        $time_limit = api_get_setting('time_limit_whosonline');
-    } else {
-        $time_limit = intval($time_limit);
-    }
+        $from            = intval($from);
+        $number_of_items = intval($number_of_items);
 
-    $from            = intval($from);
-    $number_of_items = intval($number_of_items);
+        if (empty($column)) {
+            $column = 'picture_uri';
+            if ($friends) {
+                $column = 'login_date';
+            }
+        }
+
+        if (empty($direction)) {
+            $direction = 'DESC';
+        } else {
+            if (!in_array(strtolower($direction), array('asc', 'desc'))) {
+                $direction = 'DESC';
+            }
+        }
+
+        $online_time 		= time() - $time_limit*60;
+        $current_date		= api_get_utc_datetime($online_time);
+        $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        $friend_user_table  = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
+        $table_user			= Database::get_main_table(TABLE_MAIN_USER);
+        $query              = '';
 
-    if (empty($column)) {
-        $column = 'picture_uri';
         if ($friends) {
-            $column = 'login_date';
+            // 	who friends from social network is online
+            $query = "SELECT DISTINCT login_user_id, login_date
+                      FROM $track_online_table INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
+                      WHERE     login_date >= '".$current_date."' AND
+                                friend_user_id <> '".api_get_user_id()."' AND
+                                relation_type='".USER_RELATION_TYPE_FRIEND."' AND
+                                user_id = '".api_get_user_id()."'
+                      ORDER BY $column $direction
+                      LIMIT $from, $number_of_items";
+        } else {
+            $query = "SELECT DISTINCT login_user_id, login_date FROM ".$track_online_table ." e INNER JOIN ".$table_user ." u ON (u.user_id=e.login_user_id)
+                      WHERE u.status != ".ANONYMOUS." AND login_date >= '".$current_date."'
+                      ORDER BY $column $direction
+                      LIMIT $from, $number_of_items";
         }
-    }
 
-    if (empty($direction)) {
-        $direction = 'DESC';
-    } else {
-        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
-            $direction = 'DESC';
+        if (api_get_multiple_access_url()) {
+            $access_url_id = api_get_current_access_url_id();
+            if ($access_url_id != -1) {
+                if ($friends) {
+                    // 	friends from social network is online
+                    $query = "SELECT distinct login_user_id,login_date
+                                FROM $track_online_table track INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
+                                WHERE   track.access_url_id =  $access_url_id AND
+                                        login_date >= '".$current_date."' AND
+                                        friend_user_id <> '".api_get_user_id()."' AND
+                                        relation_type='".USER_RELATION_TYPE_FRIEND."'
+                                ORDER BY $column $direction
+                                LIMIT $from, $number_of_items";
+                } else {
+                    // all users online
+                    $query = "SELECT login_user_id, login_date FROM ".$track_online_table ." track INNER JOIN ".$table_user ." u
+                              ON (u.user_id=track.login_user_id)
+                              WHERE u.status != ".ANONYMOUS." AND track.access_url_id =  $access_url_id AND
+                                    login_date >= '".$current_date."'
+                              ORDER BY $column $direction
+                              LIMIT $from, $number_of_items";
+                }
+            }
+        }
+
+        //This query will show all registered users. Only for dev purposes.
+        /*$query = "SELECT DISTINCT u.user_id as login_user_id, login_date FROM ".$track_online_table ."  e , $table_user u
+                GROUP by u.user_id
+                ORDER BY $column $direction
+                LIMIT $from, $number_of_items"; */
+
+        $result = Database::query($query);
+        if ($result) {
+            /*$valid_date_time = new DateTime();
+            $diff = "PT".$time_limit.'M';
+            $valid_date_time->sub(new DateInterval($diff));*/
+            $users_online = array();
+            while(list($login_user_id, $login_date) = Database::fetch_row($result)) {
+                    $users_online[] = $login_user_id;
+                /*$user_login_date = new DateTime($login_date);
+                var_dump($user_login_date->format('Y-m-d H:i:s'), $valid_date_time->format('Y-m-d H:i:s'));
+                if ($user_login_date->format('Y-m-d H:i:s') > $valid_date_time->format('Y-m-d H:i:s')) {
+
+                }*/
+            }
+            return $users_online;
+        } else {
+            return false;
         }
     }
 
-    $online_time 		= time() - $time_limit*60;
-	$current_date		= api_get_utc_datetime($online_time);
-	$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
-	$friend_user_table  = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
-	$table_user			= Database::get_main_table(TABLE_MAIN_USER);
-	$query              = '';
-
-	if ($friends) {
-		// 	who friends from social network is online
-		$query = "SELECT DISTINCT login_user_id, login_date
-				  FROM $track_online_table INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
-				  WHERE     login_date >= '".$current_date."' AND
-                            friend_user_id <> '".api_get_user_id()."' AND
-                            relation_type='".USER_RELATION_TYPE_FRIEND."' AND
-                            user_id = '".api_get_user_id()."'
-                  ORDER BY $column $direction
-                  LIMIT $from, $number_of_items";
-	} else {
-		$query = "SELECT DISTINCT login_user_id, login_date FROM ".$track_online_table ." e INNER JOIN ".$table_user ." u ON (u.user_id=e.login_user_id)
-                  WHERE u.status != ".ANONYMOUS." AND login_date >= '".$current_date."'
-                  ORDER BY $column $direction
-                  LIMIT $from, $number_of_items";
-	}
-
-	if (api_get_multiple_access_url()) {
-		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1) {
-			if ($friends) {
-				// 	friends from social network is online
-				$query = "SELECT distinct login_user_id,login_date
-							FROM $track_online_table track INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
-							WHERE   track.access_url_id =  $access_url_id AND
-                                    login_date >= '".$current_date."' AND
-                                    friend_user_id <> '".api_get_user_id()."' AND
-                                    relation_type='".USER_RELATION_TYPE_FRIEND."'
-                            ORDER BY $column $direction
-                            LIMIT $from, $number_of_items";
-			} else {
-				// all users online
-				$query = "SELECT login_user_id, login_date FROM ".$track_online_table ." track INNER JOIN ".$table_user ." u
-                          ON (u.user_id=track.login_user_id)
-						  WHERE u.status != ".ANONYMOUS." AND track.access_url_id =  $access_url_id AND
-                                login_date >= '".$current_date."'
-                          ORDER BY $column $direction
-                          LIMIT $from, $number_of_items";
-			}
-		}
-	}
-
-	//This query will show all registered users. Only for dev purposes.
-	/*$query = "SELECT DISTINCT u.user_id as login_user_id, login_date FROM ".$track_online_table ."  e , $table_user u
-            GROUP by u.user_id
-            ORDER BY $column $direction
-            LIMIT $from, $number_of_items"; */
-
-	$result = Database::query($query);
-	if ($result) {
-        /*$valid_date_time = new DateTime();
-        $diff = "PT".$time_limit.'M';
-        $valid_date_time->sub(new DateInterval($diff));*/
-		$users_online = array();
-		while(list($login_user_id, $login_date) = Database::fetch_row($result)) {
-				$users_online[] = $login_user_id;
-            /*$user_login_date = new DateTime($login_date);
-            var_dump($user_login_date->format('Y-m-d H:i:s'), $valid_date_time->format('Y-m-d H:i:s'));
-			if ($user_login_date->format('Y-m-d H:i:s') > $valid_date_time->format('Y-m-d H:i:s')) {
-
-			}*/
-		}
-		return $users_online;
-	} else {
-		return false;
-	}
-}
+    function who_is_online_count($time_limit = null, $friends = false) {
+        if (empty($time_limit)) {
+            $time_limit = api_get_setting('time_limit_whosonline');
+        } else {
+            $time_limit = intval($time_limit);
+        }
+        $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        $friend_user_table  = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
+        $table_user			= Database::get_main_table(TABLE_MAIN_USER);
+        $query = '';
 
-function who_is_online_count($time_limit = null, $friends = false) {
-    if (empty($time_limit)) {
-        $time_limit = api_get_setting('time_limit_whosonline');
-    } else {
-        $time_limit = intval($time_limit);
-    }
-	$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
-	$friend_user_table  = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
-    $table_user			= Database::get_main_table(TABLE_MAIN_USER);
-	$query = '';
-
-
-    $online_time 		= time() - $time_limit*60;
-	$current_date		= api_get_utc_datetime($online_time);
-
-	if ($friends) {
-		// 	who friends from social network is online
-		$query = "SELECT DISTINCT count(login_user_id) as count
-				  FROM $track_online_table INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
-				  WHERE login_date >= '$current_date' AND friend_user_id <> '".api_get_user_id()."' AND relation_type='".USER_RELATION_TYPE_FRIEND."' AND user_id = '".api_get_user_id()."' ";
-	} else {
-		// All users online
-		$query = "SELECT count(login_id) as count
-                  FROM $track_online_table track INNER JOIN $table_user u ON (u.user_id=track.login_user_id)
-                  WHERE u.status != ".ANONYMOUS." AND login_date >= '$current_date'  ";
-	}
-
-	if (api_get_multiple_access_url()) {
-		$access_url_id = api_get_current_access_url_id();
-		if ($access_url_id != -1) {
-			if ($friends) {
-				// 	friends from social network is online
-				$query = "SELECT DISTINCT count(login_user_id) as count
-							FROM $track_online_table track
-							INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
-							WHERE track.access_url_id = $access_url_id AND login_date >= '".$current_date."' AND friend_user_id <> '".api_get_user_id()."' AND relation_type='".USER_RELATION_TYPE_FRIEND."'  ";
-			} else {
-				// all users online
-				$query = "SELECT count(login_id) as count FROM $track_online_table track
-                          INNER JOIN $table_user u ON (u.user_id=track.login_user_id)
-						  WHERE u.status != ".ANONYMOUS." AND track.access_url_id =  $access_url_id AND login_date >= '$current_date' ";
-			}
-		}
-	}
-
-    //Dev purposes show all users online
-
-    /*$table_user = Database::get_main_table(TABLE_MAIN_USER);
-    $query = "SELECT count(*)  as count FROM ".$table_user ."   ";*/
-
-	$result = Database::query($query);
-	if (Database::num_rows($result) > 0) {
-		$row = Database::fetch_array($result);
-		return $row['count'];
-	} else {
-		return false;
-	}
-}
 
+        $online_time 		= time() - $time_limit*60;
+        $current_date		= api_get_utc_datetime($online_time);
 
-/**
-* Returns a list (array) of users who are online and in this course.
-* @param    int User ID
-* @param    int Number of minutes
-* @param    string  Course code (could be empty, but then the function returns false)
-* @return   array   Each line gives a user id and a login time
-*/
-function who_is_online_in_this_course($from, $number_of_items, $uid, $time_limit, $course_code) {
-	if (empty($course_code)) return false;
+        if ($friends) {
+            // 	who friends from social network is online
+            $query = "SELECT DISTINCT count(login_user_id) as count
+                      FROM $track_online_table INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
+                      WHERE login_date >= '$current_date' AND friend_user_id <> '".api_get_user_id()."' AND relation_type='".USER_RELATION_TYPE_FRIEND."' AND user_id = '".api_get_user_id()."' ";
+        } else {
+            // All users online
+            $query = "SELECT count(login_id) as count
+                      FROM $track_online_table track INNER JOIN $table_user u ON (u.user_id=track.login_user_id)
+                      WHERE u.status != ".ANONYMOUS." AND login_date >= '$current_date'  ";
+        }
 
-    if (empty($time_limit)) {
-        $time_limit = api_get_setting('time_limit_whosonline');
-    } else {
-        $time_limit = intval($time_limit);
+        if (api_get_multiple_access_url()) {
+            $access_url_id = api_get_current_access_url_id();
+            if ($access_url_id != -1) {
+                if ($friends) {
+                    // 	friends from social network is online
+                    $query = "SELECT DISTINCT count(login_user_id) as count
+                                FROM $track_online_table track
+                                INNER JOIN $friend_user_table ON (friend_user_id = login_user_id)
+                                WHERE track.access_url_id = $access_url_id AND login_date >= '".$current_date."' AND friend_user_id <> '".api_get_user_id()."' AND relation_type='".USER_RELATION_TYPE_FRIEND."'  ";
+                } else {
+                    // all users online
+                    $query = "SELECT count(login_id) as count FROM $track_online_table track
+                              INNER JOIN $table_user u ON (u.user_id=track.login_user_id)
+                              WHERE u.status != ".ANONYMOUS." AND track.access_url_id =  $access_url_id AND login_date >= '$current_date' ";
+                }
+            }
+        }
+
+        //Dev purposes show all users online
+
+        /*$table_user = Database::get_main_table(TABLE_MAIN_USER);
+        $query = "SELECT count(*)  as count FROM ".$table_user ."   ";*/
+
+        $result = Database::query($query);
+        if (Database::num_rows($result) > 0) {
+            $row = Database::fetch_array($result);
+            return $row['count'];
+        } else {
+            return false;
+        }
     }
 
-    $online_time 		= time() - $time_limit*60;
-    $current_date		= api_get_utc_datetime($online_time);
-    $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
-    $course_code        = Database::escape_string($course_code);
-
-    $from            = intval($from);
-    $number_of_items = intval($number_of_items);
-
-	$query = "SELECT login_user_id, login_date FROM $track_online_table
-              WHERE login_user_id <> 2 AND course='$course_code' AND login_date >= '$current_date'
-              LIMIT $from, $number_of_items ";
-
-	$result = Database::query($query);
-	if ($result) {
-        /*$valid_date_time = new DateTime();
-        $diff = "PT".$time_limit.'M';
-        $valid_date_time->sub(new DateInterval($diff));*/
-		$users_online = array();
-
-		while (list($login_user_id, $login_date) = Database::fetch_row($result)) {
-            /*$user_login_date = new DateTime($login_date);
-			if ($user_login_date > $valid_date_time->format('Y-m-d H:i:s')) {*/
-				$users_online[] = $login_user_id;
-			}
-		return $users_online;
-	} else {
-		return false;
-	}
-}
 
-function who_is_online_in_this_course_count($uid, $time_limit, $coursecode=null) {
-	if(empty($coursecode)) return false;
-	$track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
-	$coursecode = Database::escape_string($coursecode);
-	$time_limit = Database::escape_string($time_limit);
-
-    $online_time 		= time() - $time_limit*60;
-	$current_date		= api_get_utc_datetime($online_time);
-
-	$query = "SELECT count(login_user_id) as count FROM ".$track_online_table ."
-              WHERE login_user_id <> 2 AND course='".$coursecode."' AND login_date >= '$current_date' ";
-	$result = Database::query($query);
-	if (Database::num_rows($result) > 0) {
-		$row = Database::fetch_array($result);
-		return $row['count'];
-	} else {
-		return false;
-	}
-}
+    /**
+    * Returns a list (array) of users who are online and in this course.
+    * @param    int User ID
+    * @param    int Number of minutes
+    * @param    string  Course code (could be empty, but then the function returns false)
+    * @return   array   Each line gives a user id and a login time
+    */
+    function who_is_online_in_this_course($from, $number_of_items, $uid, $time_limit, $course_code) {
+        if (empty($course_code)) return false;
+
+        if (empty($time_limit)) {
+            $time_limit = api_get_setting('time_limit_whosonline');
+        } else {
+            $time_limit = intval($time_limit);
+        }
 
-/**
- * Gets the full user name for a given user ID
- * @param   int User ID
- * @return  string  The full username, elements separated by an HTML space
- * @deprecated user api_get_user_info($user_id)
- */
-function GetFullUserName($uid) {
-	$uid = (int) $uid;
-	$uid = Database::escape_string($uid);
-	$user_table = Database::get_main_table(TABLE_MAIN_USER);
-	$query = "SELECT firstname, lastname FROM ".$user_table." WHERE user_id='$uid'";
-	$result = @Database::query($query);
-	if (count($result)>0) {
-		$str = '';
-		while(list($firstname,$lastname)= Database::fetch_array($result)) {
-			$str = str_replace(' ', '&nbsp;', api_get_person_name($firstname, $lastname));
-			return $str;
-		}
-	}
-}
+        $online_time 		= time() - $time_limit*60;
+        $current_date		= api_get_utc_datetime($online_time);
+        $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        $course_code        = Database::escape_string($course_code);
+
+        $from            = intval($from);
+        $number_of_items = intval($number_of_items);
+
+        $query = "SELECT login_user_id, login_date FROM $track_online_table
+                  WHERE login_user_id <> 2 AND course='$course_code' AND login_date >= '$current_date'
+                  LIMIT $from, $number_of_items ";
+
+        $result = Database::query($query);
+        if ($result) {
+            /*$valid_date_time = new DateTime();
+            $diff = "PT".$time_limit.'M';
+            $valid_date_time->sub(new DateInterval($diff));*/
+            $users_online = array();
+
+            while (list($login_user_id, $login_date) = Database::fetch_row($result)) {
+                /*$user_login_date = new DateTime($login_date);
+                if ($user_login_date > $valid_date_time->format('Y-m-d H:i:s')) {*/
+                    $users_online[] = $login_user_id;
+                }
+            return $users_online;
+        } else {
+            return false;
+        }
+    }
 
-/**
- * Gets a list of chat calls made by others to the current user (info kept in main.user table)
- * @param   none - taken from global space
- * @return  string  An HTML-formatted message
- */
-function chatcall() {
-	global $_user, $_cid;
-
-	if (!$_user['user_id']) {
-		return (false);
-	}
-	$track_user_table = Database::get_main_table(TABLE_MAIN_USER);
-	$sql="select chatcall_user_id, chatcall_date from $track_user_table where ( user_id = '".$_user['user_id']."' )";
-	$result=Database::query($sql);
-	$row=Database::fetch_array($result);
-
-	$login_date=$row['chatcall_date'];
-	$hour = substr($login_date,11,2);
-	$minute = substr($login_date,14,2);
-	$secund = substr($login_date,17,2);
-	$month = substr($login_date,5,2);
-	$day = substr($login_date,8,2);
-	$year = substr($login_date,0,4);
-	$calltime = mktime($hour,$minute,$secund,$month,$day,$year);
-
-	$time = api_get_utc_datetime($time);
-	$minute_passed=5;  //within this limit, the chat call request is valid
-	$limittime = mktime(date("H"),date("i")-$minute_passed,date("s"),date("m"),date("d"),date("Y"));
-
-	if (($row['chatcall_user_id']) and ($calltime>$limittime)) {
-		$webpath=api_get_path(WEB_CODE_PATH);
-		$message=get_lang('YouWereCalled').' : '.GetFullUserName($row['chatcall_user_id'],'').'<br>'.get_lang('DoYouAccept')
-							."<p>"
-				."<a href=\"".$webpath."chat/chat.php?cidReq=".$_cid."&origin=whoisonlinejoin\">"
-				. get_lang("Yes")
-				."</a>"
-				."&nbsp;&nbsp;|&nbsp;&nbsp;"
-				."<a href=\"".api_get_path(WEB_PATH)."webchatdeny.php\">"
-				. get_lang("No")
-				."</a>"
-				."</p>";
-
-		return($message);
-	} else {
-		return false;
-	}
+    function who_is_online_in_this_course_count($uid, $time_limit, $coursecode=null) {
+        if(empty($coursecode)) return false;
+        $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE);
+        $coursecode = Database::escape_string($coursecode);
+        $time_limit = Database::escape_string($time_limit);
+
+        $online_time 		= time() - $time_limit*60;
+        $current_date		= api_get_utc_datetime($online_time);
+
+        $query = "SELECT count(login_user_id) as count FROM ".$track_online_table ."
+                  WHERE login_user_id <> 2 AND course='".$coursecode."' AND login_date >= '$current_date' ";
+        $result = Database::query($query);
+        if (Database::num_rows($result) > 0) {
+            $row = Database::fetch_array($result);
+            return $row['count'];
+        } else {
+            return false;
+        }
+    }
 }

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

@@ -432,7 +432,7 @@ class PageController
                 }
             }
             if (!empty($exercise_list)) {
-                $exercise_list = msort($exercise_list, 'tms');
+                $exercise_list = ArrayClass::msort($exercise_list, 'tms');
                 $my_exercise = $exercise_list[0];
                 $url = Display::url($my_exercise['title'], api_get_path(WEB_CODE_PATH).'exercice/overview.php?exerciseId='.$my_exercise['id'].'&cidReq='.$my_exercise['course_code'].'&id_session='.$my_exercise['session_id']);
                 $tpl->assign('exercise_url', $url);
@@ -976,9 +976,9 @@ class PageController
 
         $message = "22---Page loaded in:".($mtime-START);
         $app['monolog']->addInfo($message);
-        $message = "memory_get_usage: ".format_file_size(memory_get_usage(true));
+        $message = "memory_get_usage: ".Text::format_file_size(memory_get_usage(true));
         $app['monolog']->addInfo($message);
-        $message = "memory_get_peak_usage: ".format_file_size(memory_get_peak_usage(true));
+        $message = "memory_get_peak_usage: ".Text::format_file_size(memory_get_peak_usage(true));
         $app['monolog']->addInfo($message);
     }
 }

+ 3 - 9
main/inc/lib/pdf.lib.php

@@ -233,8 +233,8 @@ class PDF {
                     }
                 }
 
-                api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.
-                $title = api_get_title_html($document_html, 'UTF-8', 'UTF-8');  // TODO: Maybe it is better idea the title to be passed through
+                Text::api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.
+                $title = Text::api_get_title_html($document_html, 'UTF-8', 'UTF-8');  // TODO: Maybe it is better idea the title to be passed through
                                                                                 // $_GET[] too, as it is done with file name.
                                                                               // At the moment the title is retrieved from the html document itself.
                 //echo $document_html;exit;
@@ -337,13 +337,7 @@ class PDF {
         //$document_html= str_replace('src="',$src_http_www, $document_html);
         //$document_html= str_replace('temp_template_path', 'src="/main/default_course_document/', $document_html);// restore src templates
 
-        api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.
-        $title = api_get_title_html($document_html, 'UTF-8', 'UTF-8');  // TODO: Maybe it is better idea the title to be passed through
-                                                                        // $_GET[] too, as it is done with file name.
-                                                                        // At the moment the title is retrieved from the html document itself.
-       /* if (empty($title)) {
-            $title = $filename; // Here file name is expected to contain ASCII symbols only.
-        }*/
+        Text::api_set_encoding_html($document_html, 'UTF-8'); // The library mPDF expects UTF-8 encoded input data.
 
         if (!empty($css)) {
             $this->pdf->WriteHTML($css, 1);

+ 5 - 5
main/inc/lib/plugin.class.php

@@ -3,7 +3,7 @@
 
 /**
  * Base class for plugins
- * 
+ *
  * This class has to be extended by every plugin. It defines basic methods
  * to install/uninstall and get information about a plugin
  *
@@ -25,7 +25,7 @@ class Plugin {
     public  $is_course_plugin = false;
 
     /**
-     * When creating a new course, these settings are added to the course, in 
+     * When creating a new course, these settings are added to the course, in
      * the course_info/infocours.php
      * To show the plugin course icons you need to add these icons:
      * main/img/icons/22/plugin_name.png
@@ -72,7 +72,7 @@ class Plugin {
         $result['version']          = $this->get_version();
         $result['author']           = $this->get_author();
         $result['plugin_class']     = get_class($this);
-        $result['is_course_plugin'] = $this->is_course_plugin;        
+        $result['is_course_plugin'] = $this->is_course_plugin;
 
         if ($form = $this->get_settings_form()) {
             $result['settings_form'] = $form;
@@ -249,7 +249,7 @@ class Plugin {
                         $this->strings[$key] = $string;
                     }
                 }
-            } 
+            }
         }
 
         if (isset($this->strings[$name])) {
@@ -321,7 +321,7 @@ class Plugin {
         $result = Database::query($sql);
         if (!Database::num_rows($result)) {
             $tool_link = "$plugin_name/start.php";
-            $visibility = string2binary(api_get_setting('course_create_active_tools', $plugin_name));
+            $visibility = Text::string2binary(api_get_setting('course_create_active_tools', $plugin_name));
             $sql_course = "INSERT INTO $t_tool VALUES ($course_id, NULL, '$plugin_name', '$tool_link', '$plugin_name.png',' ".$visibility."','0', 'squaregrey.gif','NO','_self','plugin','0')";
             $r = Database::query($sql_course);
         }

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

@@ -997,7 +997,7 @@ class SessionManager {
                     if (!in_array($user_id, $existingUsers)) {
                         $subject = '['.get_setting('siteName').'] '.get_lang('YourReg').' '.get_setting('siteName');
                         $user_info = api_get_user_info($user_id);
-                        $content    = get_lang('Dear')." ".stripslashes($user_info['complete_name']).",\n\n".sprintf(get_lang('YouAreRegisterToSessionX'), $session_name) ." \n\n" .get_lang('Address') ." ". get_setting('siteName') ." ". get_lang('Is') ." : ". api_get_path(WEB_PATH) ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".get_setting('administratorName')." ".get_setting('administratorSurname')."\n". get_lang('Manager'). " ".get_setting('siteName')."\nT. ".get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".get_setting('emailAdministrator');
+                        $content    = get_lang('Dear')." ".stripslashes($user_info['complete_name']).",\n\n".sprintf(get_lang('YouAreRegisterToSessionX'), $session_name) ." \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".get_setting('administratorName')." ".get_setting('administratorSurname')."\n". get_lang('Manager'). " ".get_setting('siteName')."\nT. ".get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".get_setting('emailAdministrator');
                         MessageManager::send_message($user_id, $subject, $content, array(), array(), null, null, null, null, null);
                     }
                 }

+ 118 - 115
main/inc/lib/social.lib.php

@@ -31,7 +31,7 @@ class SocialManager extends UserManager {
 
     /**
      * Allow to see contacts list
-     * @author isaac flores paz 
+     * @author isaac flores paz
      * @return array
      */
     public static function show_list_type_friends () {
@@ -50,14 +50,14 @@ class SocialManager extends UserManager {
             return $friend_relation_list;
         }
     }
-    
+
     /**
      * Get relation type contact by name
      * @param string names of the kind of relation
      * @return int
-     * @author isaac flores paz 
+     * @author isaac flores paz
      */
-    public static function get_relation_type_by_name ($relation_type_name) {        
+    public static function get_relation_type_by_name ($relation_type_name) {
         $list_type_friend = self::show_list_type_friends();
         foreach ($list_type_friend as $value_type_friend) {
             if (strtolower($value_type_friend['title'])==$relation_type_name) {
@@ -65,13 +65,13 @@ class SocialManager extends UserManager {
             }
         }
     }
-    
+
     /**
      * Get the kind of relation between contacts
      * @param int user id
      * @param int user friend id
      * @param string
-     * @author isaac flores paz 
+     * @author isaac flores paz
      */
     public static function get_relation_between_contacts ($user_id,$user_friend) {
         $tbl_my_friend_relation_type = Database :: get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
@@ -95,7 +95,7 @@ class SocialManager extends UserManager {
      * @param bool true will load firstname, lastname, and image name
      * @return array
      * @author Julio Montoya <gugli100@gmail.com> Cleaning code, function renamed, $load_extra_info option added
-     * @author isaac flores paz 
+     * @author isaac flores paz
      */
     public static function get_friends($user_id, $id_group = null, $search_name = null, $load_extra_info = true) {
         $list_ids_friends=array();
@@ -131,9 +131,9 @@ class SocialManager extends UserManager {
      * @param int group id
      * @param string name to search
      * @param array
-     * @author isaac flores paz 
+     * @author isaac flores paz
      */
-    public static function get_list_path_web_by_user_id ($user_id,$id_group=null,$search_name=null) {        
+    public static function get_list_path_web_by_user_id ($user_id,$id_group=null,$search_name=null) {
         $combine_friend = array();
         $list_ids = self::get_friends($user_id,$id_group,$search_name);
         if (is_array($list_ids)) {
@@ -152,7 +152,7 @@ class SocialManager extends UserManager {
      * @param int user id
      * @return array
      */
-    public static function get_list_web_path_user_invitation_by_user_id ($user_id) {        
+    public static function get_list_web_path_user_invitation_by_user_id ($user_id) {
         $list_ids = self::get_list_invitation_of_friends_by_user_id((int)$user_id);
         $list_path_image_friend = array();
         foreach ($list_ids as $values_ids) {
@@ -175,30 +175,30 @@ class SocialManager extends UserManager {
         $tbl_message = Database::get_main_table(TABLE_MAIN_MESSAGE);
         $user_id = intval($user_id);
         $friend_id = intval($friend_id);
-        
+
         //Just in case we replace the and \n and \n\r while saving in the DB
-        $message_content = str_replace(array("\n", "\n\r"), '<br />', $message_content);        
-        
+        $message_content = str_replace(array("\n", "\n\r"), '<br />', $message_content);
+
         $clean_message_title   = Database::escape_string($message_title);
         $clean_message_content = Database::escape_string($message_content);
-        
+
         $now = api_get_utc_datetime();
-        
+
         $sql_exist='SELECT COUNT(*) AS count FROM '.$tbl_message.' WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status IN(5,6,7);';
 
         $res_exist = Database::query($sql_exist);
         $row_exist = Database::fetch_array($res_exist,'ASSOC');
-        
+
         if ($row_exist['count']==0) {
-                        
-            $sql=' INSERT INTO '.$tbl_message.'(user_sender_id,user_receiver_id,msg_status,send_date,title,content) 
+
+            $sql=' INSERT INTO '.$tbl_message.'(user_sender_id,user_receiver_id,msg_status,send_date,title,content)
                    VALUES('.$user_id.','.$friend_id.','.MESSAGE_STATUS_INVITATION_PENDING.',"'.$now.'","'.$clean_message_title.'","'.$clean_message_content.'") ';
-            Database::query($sql);    
-            
+            Database::query($sql);
+
             $sender_info = api_get_user_info($user_id);
-            $notification = new Notification(); 
+            $notification = new Notification();
             $notification->save_notification(Notification::NOTIFICATION_TYPE_INVITATION, array($friend_id), $message_title, $message_content, $sender_info);
-                
+
             return true;
         } else {
             //invitation already exist
@@ -216,7 +216,7 @@ class SocialManager extends UserManager {
     }
     /**
      * Get number messages of the inbox
-     * @author isaac flores paz 
+     * @author isaac flores paz
      * @param int user receiver id
      * @return int
      */
@@ -230,7 +230,7 @@ class SocialManager extends UserManager {
 
     /**
      * Get invitation list received by user
-     * @author isaac flores paz 
+     * @author isaac flores paz
      * @param int user id
      * @return array()
      */
@@ -267,7 +267,7 @@ class SocialManager extends UserManager {
      * Accepts invitation
      * @param int user sender id
      * @param int user receiver id
-     * @author isaac flores paz 
+     * @author isaac flores paz
      * @author Julio Montoya <gugli100@gmail.com> Cleaning code
      */
     public static function invitation_accepted ($user_send_id,$user_receiver_id) {
@@ -279,7 +279,7 @@ class SocialManager extends UserManager {
      * Denies invitation
      * @param int user sender id
      * @param int user receiver id
-     * @author isaac flores paz 
+     * @author isaac flores paz
      * @author Julio Montoya <gugli100@gmail.com> Cleaning code
      */
     public static function invitation_denied ($user_send_id,$user_receiver_id) {
@@ -291,7 +291,7 @@ class SocialManager extends UserManager {
     }
     /**
      * allow attach to group
-     * @author isaac flores paz 
+     * @author isaac flores paz
      * @param int user to qualify
      * @param int kind of rating
      * @return void()
@@ -311,15 +311,15 @@ class SocialManager extends UserManager {
      */
     public static function send_invitation_friend_user($userfriend_id, $subject_message = '', $content_message = '') {
         global $charset;
-        
+
         $user_info = array();
         $user_info = api_get_user_info($userfriend_id);
         $succes = get_lang('MessageSentTo');
         $succes.= ' : '.api_get_person_name($user_info['firstName'], $user_info['lastName']);
-        
+
         if (isset($subject_message) && isset($content_message) && isset($userfriend_id)) {
-            $send_message = MessageManager::send_message($userfriend_id, $subject_message, $content_message); 
-            
+            $send_message = MessageManager::send_message($userfriend_id, $subject_message, $content_message);
+
             if ($send_message) {
                 echo Display::display_confirmation_message($succes,true);
             } else {
@@ -327,7 +327,7 @@ class SocialManager extends UserManager {
             }
             return false;
         } elseif (isset($userfriend_id) && !isset($subject_message)) {
-            $count_is_true = false;            
+            $count_is_true = false;
             if (isset($userfriend_id) && $userfriend_id>0) {
                 $message_title = get_lang('Invitation');
                 $count_is_true = self::send_invitation_friend(api_get_user_id(), $userfriend_id, $message_title, $content_message);
@@ -398,12 +398,12 @@ class SocialManager extends UserManager {
     public static function get_logged_user_course_html($my_course, $count) {
         //initialise
         $result = '';
-                
-        $course_code   = $my_course['code'];        
+
+        $course_code   = $my_course['code'];
         $course_title  = $my_course['course_info']['title'];
-        
+
         $course_info = Database :: get_course_info($course_code);
-        
+
         $course_id = $course_info['real_id'];
 
         $course_access_settings = CourseManager :: get_access_settings($course_code);
@@ -411,7 +411,7 @@ class SocialManager extends UserManager {
         $course_visibility = $course_access_settings['visibility'];
 
         $user_in_course_status = CourseManager :: get_user_in_course_status(api_get_user_id(), $course_code);
-        
+
         $s_htlm_status_icon = Display::return_icon('course.gif', get_lang('Course'));
 
         //display course entry
@@ -426,9 +426,9 @@ class SocialManager extends UserManager {
             $result .= $course_title." "." ".get_lang('CourseClosed')."";
         }
         $result .= '</h3>';
-     
+
         $result .= '</li>';
-        $result .= '</div>';        
+        $result .= '</div>';
         return $result;
     }
 
@@ -444,18 +444,18 @@ class SocialManager extends UserManager {
     public static function show_social_menu($show = '', $group_id = 0, $user_id = 0, $show_full_profile = false, $show_delete_account_button = false) {
         if (empty($user_id)) {
             $user_id = api_get_user_id();
-        }       
+        }
         $user_info = api_get_user_info($user_id, true);
-        
+
         $current_user_id = api_get_user_id();
         $current_user_info = api_get_user_info($current_user_id, true);
-                
+
         if ($current_user_id == $user_id) {
             $user_friend_relation = null;
         } else {
             $user_friend_relation = SocialManager::get_relation_between_contacts($current_user_id, $user_id);
         }
-        
+
         $show_groups      = array('groups', 'group_messages', 'messages_list', 'group_add', 'mygroups', 'group_edit', 'member_list', 'invite_friends', 'waiting_list', 'browse_groups');
         //$show_messages    = array('messages', 'messages_inbox', 'messages_outbox', 'messages_compose');
 
@@ -468,30 +468,30 @@ class SocialManager extends UserManager {
         $group_pending_invitations = count($group_pending_invitations);
         $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
         $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) :'');
-        
+
         $html = '<div class="social-menu">';
           if (in_array($show, $show_groups) && !empty($group_id)) {
             //--- Group image
             $group_info = GroupPortalManager::get_group_data($group_id);
             $big        = GroupPortalManager::get_picture_group($group_id, $group_info['picture_uri'],160,GROUP_IMAGE_SIZE_BIG);
-            
-            $html .= '<div class="social-content-image">';                
-                $html .= '<div class="well social-background-content">';                
+
+            $html .= '<div class="social-content-image">';
+                $html .= '<div class="well social-background-content">';
                 $html .= Display::url('<img src='.$big['file'].' class="social-groups-image" /> </a><br /><br />', api_get_path(WEB_PATH).'main/social/groups.php?id='.$group_id);
                 if (GroupPortalManager::is_group_admin($group_id, api_get_user_id())) {
                     $html .= '<div id="edit_image" class="hidden_message" style="display:none"><a href="'.api_get_path(WEB_PATH).'main/social/group_edit.php?id='.$group_id.'">'.get_lang('EditGroup').'</a></div>';
                 }
                 $html .= '</div>';
               $html .= '</div>';
-              
+
           } else {
-            $img_array = UserManager::get_user_picture_path_by_id($user_id,'web',true,true);              
+            $img_array = UserManager::get_user_picture_path_by_id($user_id,'web',true,true);
             $big_image = UserManager::get_picture_user($user_id, $img_array['file'],'', USER_IMAGE_SIZE_BIG);
             $big_image = $big_image['file'].'?'.uniqid();
             $normal_image = $img_array['dir'].$img_array['file'].'?'.uniqid();
 
               //--- User image
-            
+
             $html .= '<div class="well social-background-content">';
                 if ($img_array['file'] != 'unknown.jpg') {
                     $html .= '<a class="thumbnail thickbox" href="'.$big_image.'"><img src='.$normal_image.' /> </a>';
@@ -502,12 +502,12 @@ class SocialManager extends UserManager {
                     $html .= '<div id="edit_image" class="hidden_message" style="display:none">';
                     $html .= '<a href="'.api_get_path(WEB_PATH).'main/auth/profile.php">'.get_lang('EditProfile').'</a></div>';
                 }
-            $html .= '</div>';              
+            $html .= '</div>';
           }
 
-        if (!in_array($show, array('shared_profile', 'groups', 'group_edit', 'member_list','waiting_list','invite_friends'))) {            
+        if (!in_array($show, array('shared_profile', 'groups', 'group_edit', 'member_list','waiting_list','invite_friends'))) {
 
-            $html .= '<div class="well sidebar-nav"><ul class="nav nav-list">';      
+            $html .= '<div class="well sidebar-nav"><ul class="nav nav-list">';
             $active = $show=='home' ? 'active' : null;
             $html .= '<li class="'.$active.'"><a href="'.api_get_path(WEB_PATH).'main/social/home.php">'.Display::return_icon('home.png',get_lang('Home'),array()).get_lang('Home').'</a></li>';
             $active = $show=='messages' ? 'active' : null;
@@ -516,7 +516,7 @@ class SocialManager extends UserManager {
             //Invitations
             $active = $show=='invitations' ? 'active' : null;
             $html .= '<li class="'.$active.'"><a href="'.api_get_path(WEB_PATH).'main/social/invitations.php">'.Display::return_icon('invitation.png',get_lang('Invitations'),array()).get_lang('Invitations').$total_invitations.'</a></li>';
-            
+
             //Shared profile and groups
             $active = $show=='shared_profile' ? 'active' : null;
             $html .= '<li class="'.$active.'"><a href="'.api_get_path(WEB_PATH).'main/social/profile.php">'.Display::return_icon('my_shared_profile.png',get_lang('ViewMySharedProfile'),array()).get_lang('ViewMySharedProfile').'</a></li>';
@@ -528,14 +528,14 @@ class SocialManager extends UserManager {
             //Search users
             $active = $show=='search' ? 'active' : null;
             $html .= '<li class="'.$active.'"><a href="'.api_get_path(WEB_PATH).'main/social/search.php">'.Display::return_icon('zoom.png',get_lang('Search'), array()).get_lang('Search').'</a></li>';
-                    
+
             //My files
             $active = $show=='myfiles' ? 'active' : null;
-            $html .= '<li class="'.$active.'"><a href="'.api_get_path(WEB_PATH).'main/social/myfiles.php">'.Display::return_icon('briefcase.png',get_lang('MyFiles'),array(), 16).get_lang('MyFiles').'</span></a></li>';    
+            $html .= '<li class="'.$active.'"><a href="'.api_get_path(WEB_PATH).'main/social/myfiles.php">'.Display::return_icon('briefcase.png',get_lang('MyFiles'),array(), 16).get_lang('MyFiles').'</span></a></li>';
             $html .='</ul>
-                  </div>';         
+                  </div>';
         }
-        
+
         if (in_array($show, $show_groups) && !empty($group_id)) {
             $html .= GroupPortalManager::show_group_column_information($group_id, api_get_user_id(), $show);
         }
@@ -560,12 +560,12 @@ class SocialManager extends UserManager {
                 $active = $show=='myfiles' ? 'active' : null;
                 $html .= '<li class="'.$active.'"><a href="'.api_get_path(WEB_PATH).'main/social/myfiles.php">'.Display::return_icon('briefcase.png',get_lang('MyFiles'),array(),16).get_lang('MyFiles').'</a></li>';
             }
-            
+
             // My friend profile
 
             if ($user_id != api_get_user_id()) {
                 $html .=  '<li><a href="javascript:void(0);" onclick="javascript:send_message_to_user(\''.$user_id.'\');" title="'.get_lang('SendMessage').'">';
-                $html .=  Display::return_icon('compose_message.png',get_lang('SendMessage')).'&nbsp;&nbsp;'.get_lang('SendMessage').'</a></li>';                        
+                $html .=  Display::return_icon('compose_message.png',get_lang('SendMessage')).'&nbsp;&nbsp;'.get_lang('SendMessage').'</a></li>';
             }
 
             //check if I already sent an invitation message
@@ -594,7 +594,7 @@ class SocialManager extends UserManager {
                         }
                     }
                     } else {
-                       // Do something? 
+                       // Do something?
                     if ($user_id != api_get_user_id()) {
                         if ($current_user_info['user_is_online_in_chat'] == 1) {
                             $message = Security::remove_XSS(sprintf(get_lang("YouHaveToAddXAsAFriendFirst", $user_name)));
@@ -613,7 +613,7 @@ class SocialManager extends UserManager {
                 $i=1;
                 if (is_array($personal_course_list)) {
                     foreach ($personal_course_list as $my_course) {
-                        if ($i<=10) {                            
+                        if ($i<=10) {
                             $course_list_code[] = array('code' => $my_course['code']);
                         } else {
                             break;
@@ -621,7 +621,7 @@ class SocialManager extends UserManager {
                         $i++;
                     }
                     //to avoid repeted courses
-                    $course_list_code = array_unique_dimensional($course_list_code);
+                    $course_list_code = ArrayClass::array_unique_dimensional($course_list_code);
                 }
 
                 //-----Announcements
@@ -629,10 +629,10 @@ class SocialManager extends UserManager {
                 $announcements = array();
                 foreach ($course_list_code as $course) {
                     $course_info = api_get_course_info($course['code']);
-                    if (!empty($course_info)) {                    
-                        $content = AnnouncementManager::get_all_annoucement_by_user_course($course_info['code'], $my_announcement_by_user_id);                    
-                        
-                          if (!empty($content)) {                          
+                    if (!empty($course_info)) {
+                        $content = AnnouncementManager::get_all_annoucement_by_user_course($course_info['code'], $my_announcement_by_user_id);
+
+                          if (!empty($content)) {
                             $url = Display::url(Display::return_icon('announcement.png',get_lang('Announcements')).$course_info['name'].' ('.$content['count'].')', api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$course['code']);
                             $announcements[] = Display::tag('li', $url);
                           }
@@ -650,16 +650,16 @@ class SocialManager extends UserManager {
                   }
             }
         }
-        
-        if ($show_delete_account_button) {        
-            $html .= '<div class="sidebar-nav"><ul><li>';       
+
+        if ($show_delete_account_button) {
+            $html .= '<div class="sidebar-nav"><ul><li>';
             $url = api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php';
             $html .= Display::url(Display::return_icon('delete.png',get_lang('Unsubscribe'), array(), ICON_SIZE_TINY).get_lang('Unsubscribe'), $url);
-            $html .= '</li></ul></div>';            
-        }        
+            $html .= '</li></ul></div>';
+        }
         $html .= '</div>';
-        
-        
+
+
         return $html;
     }
 
@@ -667,32 +667,32 @@ class SocialManager extends UserManager {
      * Displays a sortable table with the list of online users.
      * @param array $user_list
      */
-    public static function display_user_list($user_list) {        
+    public static function display_user_list($user_list) {
         if ($_GET['id'] == '') {
-            
-            $column_size = '9'; 
+
+            $column_size = '9';
             $add_row = false;
             if (api_is_anonymous()) {
-                $column_size = '12';                   
+                $column_size = '12';
                 $add_row = true;
             }
-            
+
             $extra_params = array();
             $course_url = '';
             if (strlen($_GET['cidReq']) > 0) {
                 $extra_params['cidReq'] = Security::remove_XSS($_GET['cidReq']);
                 $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
-            }          
-            
+            }
+
             if ($add_row) {
                 $html .='<div class="row">';
             }
-            
-            $html .= '<div class="span'.$column_size.'">';            
-            
-            $html .= '<ul id="online_grid_container" class="thumbnails">';            
+
+            $html .= '<div class="span'.$column_size.'">';
+
+            $html .= '<ul id="online_grid_container" class="thumbnails">';
             foreach ($user_list as $uid) {
-                $user_info = api_get_user_info($uid);                
+                $user_info = api_get_user_info($uid);
                 //Anonymous users can't have access to the profile
                 if (!api_is_anonymous()) {
                     if (api_get_setting('allow_social_tool')=='true') {
@@ -704,35 +704,35 @@ class SocialManager extends UserManager {
                     $url = '#';
                 }
                 $image_array = UserManager::get_user_picture_path_by_id($uid, 'system', false, true);
-                
+
                 // reduce image
                 $name = $user_info['complete_name'];
                 $status_icon = Display::span('', array('class' => 'online_user_in_text'));
                 $user_status = $user_info['status'] == 1 ? Display::span('', array('class' => 'teacher_online')) : Display::span('', array('class' => 'student_online'));
-                
+
                 if ($image_array['file'] == 'unknown.jpg' || !file_exists($image_array['dir'].$image_array['file'])) {
-                    $friends_profile['file'] = api_get_path(WEB_CODE_PATH).'img/unknown_180_100.jpg';                                                                             
+                    $friends_profile['file'] = api_get_path(WEB_CODE_PATH).'img/unknown_180_100.jpg';
                     $img = '<img title = "'.$name.'" alt="'.$name.'" src="'.$friends_profile['file'].'">';
                 } else {
-                    $friends_profile = UserManager::get_picture_user($uid, $image_array['file'], 80, USER_IMAGE_SIZE_ORIGINAL);                                        
-                    $img = '<img title = "'.$name.'" alt="'.$name.'" src="'.$friends_profile['file'].'">';                                                                        
-                }           
+                    $friends_profile = UserManager::get_picture_user($uid, $image_array['file'], 80, USER_IMAGE_SIZE_ORIGINAL);
+                    $img = '<img title = "'.$name.'" alt="'.$name.'" src="'.$friends_profile['file'].'">';
+                }
                 $name = '<a href="'.$url.'">'.$status_icon.$user_status.$name.'</a><br>';
-                $html .= '<li class="span'.($column_size/3).'"><div class="thumbnail">'.$img.'<div class="caption">'.$name.'</div</div></li>';                
-            }            
+                $html .= '<li class="span'.($column_size/3).'"><div class="thumbnail">'.$img.'<div class="caption">'.$name.'</div</div></li>';
+            }
             $counter = $_SESSION['who_is_online_counter'];
-            
-            $html .= '</ul></div>';            
+
+            $html .= '</ul></div>';
             if (count($user_list) >= 9) {
                 $html .= '<div class="span'.$column_size.'"><a class="btn btn-large" id="link_load_more_items" data_link="'.$counter.'" >'.get_lang('More').'</a></div>';
             }
             if ($add_row) {
-                $html .= '</div>';    
+                $html .= '</div>';
             }
         }
         return $html;
-    }    
-    
+    }
+
     /**
      * Displays the information of an individual user
      * @param int $user_id
@@ -744,15 +744,18 @@ class SocialManager extends UserManager {
         $user_table = Database::get_main_table(TABLE_MAIN_USER);
         $sql = "SELECT * FROM $user_table WHERE user_id = ".$safe_user_id;
         $result = Database::query($sql);
+
+        $userInfo = api_get_user_info($user_id);
+
         if (Database::num_rows($result) == 1) {
-            $user_object = Database::fetch_object($result);            
-            $alt  = GetFullUserName($user_id).($_SESSION['_uid'] == $user_id ? '&nbsp;('.get_lang('Me').')' : '');
+            $user_object = Database::fetch_object($result);
+            $alt  = $userInfo['complete_name'].($_SESSION['_uid'] == $user_id ? '&nbsp;('.get_lang('Me').')' : '');
 
             $status = get_status_from_code($user_object->status);
-            
+
             $interbreadcrumb[] = array('url' => 'whoisonline.php', 'name' => get_lang('UsersOnLineList'));
-            Display::display_header($alt, null, $alt);            
-            
+            Display::display_header($alt, null, $alt);
+
             echo '<div class ="thumbnail">';
             if (strlen(trim($user_object->picture_uri)) > 0) {
                 $sysdir_array = UserManager::get_user_picture_path_by_id($safe_user_id, 'system');
@@ -761,9 +764,9 @@ class SocialManager extends UserManager {
                 $webdir = $webdir_array['dir'];
                 $fullurl = $webdir.$user_object->picture_uri;
                 $system_image_path = $sysdir.$user_object->picture_uri;
-                list($width, $height, $type, $attr) = @getimagesize($system_image_path);                    
+                list($width, $height, $type, $attr) = @getimagesize($system_image_path);
                 $height += 30;
-                $width += 30;                    
+                $width += 30;
                 // get the path,width and height from original picture
                 $big_image = $webdir.'big_'.$user_object->picture_uri;
                 $big_image_size = api_getimagesize($big_image);
@@ -773,18 +776,18 @@ class SocialManager extends UserManager {
                 //echo '<a href="javascript:void()" onclick="javascript: return show_image(\''.$url_big_image.'\',\''.$big_image_width.'\',\''.$big_image_height.'\');" >';
                 echo '<img src="'.$fullurl.'" alt="'.$alt.'" />';
             } else {
-                echo Display::return_icon('unknown.jpg', get_lang('Unknown'));                    
-            }            
+                echo Display::return_icon('unknown.jpg', get_lang('Unknown'));
+            }
             if (!empty($status)) {
                 echo '<div class="caption">'.$status.'</div>';
             }
             echo '</div>';
 
-                     
+
             if (api_get_setting('show_email_addresses') == 'true') {
                 echo Display::encrypted_mailto_link($user_object->email,$user_object->email).'<br />';
             }
-                        
+
             if ($user_object->competences) {
                 echo Display::page_subheader(get_lang('MyCompetences'));
                 echo '<p>'.$user_object->competences.'</p>';
@@ -802,7 +805,7 @@ class SocialManager extends UserManager {
                 echo Display::page_subheader(get_lang('MyPersonalOpenArea'));
                 echo '<p>'.$user_object->openarea.'</p>';
             }
-            
+
         } else    {
             Display::display_header(get_lang('UsersOnLineList'));
             echo '<div class="actions-title">';
@@ -810,7 +813,7 @@ class SocialManager extends UserManager {
             echo '</div>';
         }
     }
-    
+
     /**
      * Display productions in whoisonline
      * @param int $user_id User id
@@ -860,7 +863,7 @@ class SocialManager extends UserManager {
             echo '</ul></dd>';
         }
     }
-    
+
     public static function social_wrapper_div($content, $span_count) {
         $span_count = intval($span_count);
         $html = '<div class="span'.$span_count.'">';
@@ -868,9 +871,9 @@ class SocialManager extends UserManager {
         $html .= $content;
         $html .= '</div></div>';
         return $html;
-        
+
     }
-    
+
     /**
      * Dummy function
      *

+ 31 - 31
main/inc/lib/statistics.lib.php

@@ -6,7 +6,7 @@
 * @package chamilo.statistics
 */
 class Statistics {
-    
+
     /**
      * Converts a number of bytes in a formatted string
      * @param int $size
@@ -18,7 +18,7 @@ class Statistics {
         if ($size >= pow(2,20) && $size < pow(2,30)) return round($size / pow(2,20), 1)." MB";
         if ($size > pow(2,30)) return round($size / pow(2,30), 2)." GB";
     }
-    
+
     /**
      * Count courses
      * @param string $category_code  Code of a course category. Default: count
@@ -136,14 +136,14 @@ class Statistics {
         $obj = Database::fetch_object($res);
         return $obj->total_number_of_items;
     }
-    
+
     /**
      * Get activities data to display
      */
     static function get_activities_data($from, $number_of_items, $column, $direction) {
         global $dateTimeFormatLong, $_configuration;
         $track_e_default    		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
-        $table_user 				= Database::get_main_table(TABLE_MAIN_USER);        
+        $table_user 				= Database::get_main_table(TABLE_MAIN_USER);
         $access_url_rel_user_table	= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $current_url_id 			= api_get_current_access_url_id();
 
@@ -190,25 +190,25 @@ class Statistics {
 
         $res = Database::query($sql);
         $activities = array();
-        while ($row = Database::fetch_row($res)) {            
+        while ($row = Database::fetch_row($res)) {
             if (strpos($row[1], '_object') === false) {
                 $row[2] = $row[2];
             } else {
                 if (!empty($row[2])) {
                     $row[2] = unserialize($row[2]);
                     if (is_array($row[2]) && !empty($row[2])) {
-                        $row[2] = implode_with_key(', ', $row[2]);
+                        $row[2] = Text::implode_with_key(', ', $row[2]);
                     }
                 }
             }
-        	if (!empty($row['default_date']) && $row['default_date'] != '0000-00-00 00:00:00') {        	
+        	if (!empty($row['default_date']) && $row['default_date'] != '0000-00-00 00:00:00') {
             	$row['default_date'] = api_get_local_time($row['default_date']);
         	} else {
         		$row['default_date'] = '-';
         	}
             if (!empty($row[4])) { //user ID
                 $row[3] = Display::url($row[3],api_get_path(WEB_CODE_PATH).'admin/user_information?user_id='.$row[5], array('title' => get_lang('UserInfo')));
-            
+
                 $row[4] = TrackingUserLog::get_ip_from_user_event($row[4],$row[5],true);
                 if (empty($row[4])) {
                     $row[4] = get_lang('Unknown');
@@ -216,7 +216,7 @@ class Statistics {
             }
             $activities[] = $row;
         }
-        
+
         return $activities;
     }
 
@@ -234,7 +234,7 @@ class Statistics {
         }
         return $categories;
     }
-    
+
     /**
      * Rescale data
      * @param array $data The data that should be rescaled
@@ -254,7 +254,7 @@ class Statistics {
         }
         return $result;
     }
-    
+
     /**
      * Show statistics
      * @param string $title The title
@@ -272,13 +272,13 @@ class Statistics {
         foreach ($stats as $subtitle => $number) {
             $total += $number;
         }
-        
-        foreach ($stats as $subtitle => $number) {            
+
+        foreach ($stats as $subtitle => $number) {
             if (!$is_file_size) {
                 $number_label = number_format($number, 0, ',', '.');
             } else {
                 $number_label = Statistics::make_size_string($number);
-            }            
+            }
             $percentage = ($total>0?number_format(100*$number/$total, 1, ',', '.'):'0');
 
             echo '<tr class="row_'.($i%2 == 0 ? 'odd' : 'even').'">
@@ -301,7 +301,7 @@ class Statistics {
         }
         echo '</table>';
     }
-    
+
     /**
      * Show some stats about the number of logins
      * @param string $type month, hour or day
@@ -376,7 +376,7 @@ class Statistics {
         }
         Statistics::print_stats(get_lang('AllLogins').' ('.$period.')', $result, true);
     }
-    
+
     /**
      * Print the number of recent logins
      */
@@ -439,7 +439,7 @@ class Statistics {
         }
         Statistics::print_stats(get_lang('PlatformToolAccess'),$result,true);
     }
-    
+
     /**
      * Show some stats about the number of courses per language
      */
@@ -450,8 +450,8 @@ class Statistics {
         $current_url_id = api_get_current_access_url_id();
         if ($_configuration['multiple_access_urls']) {
             $sql = "SELECT course_language, count( c.code ) AS number_of_courses ".
-                   "FROM $table as c, $access_url_rel_course_table as u 
-            		WHERE u.course_code=c.code AND access_url_id='".$current_url_id."' 
+                   "FROM $table as c, $access_url_rel_course_table as u
+            		WHERE u.course_code=c.code AND access_url_id='".$current_url_id."'
             		GROUP BY course_language ORDER BY number_of_courses DESC";
         } else {
             $sql = "SELECT course_language, count( code ) AS number_of_courses ".
@@ -464,7 +464,7 @@ class Statistics {
         }
         Statistics::print_stats(get_lang('CountCourseByLanguage'),$result,true);
     }
-    
+
     /**
      * Shows the number of users having their picture uploaded in Dokeos.
      */
@@ -506,7 +506,7 @@ class Statistics {
         echo '<div class="actions">';
         $form->display();
         echo '</div>';
-        
+
         $table = new SortableTable('activities', array('Statistics','get_number_of_activities'), array('Statistics','get_activities_data'),5,50,'DESC');
         $parameters = array();
 
@@ -608,9 +608,9 @@ class Statistics {
         $message_table 				= Database::get_main_table(TABLE_MAIN_MESSAGE);
         $user_table 				= Database::get_main_table(TABLE_MAIN_USER);
         $access_url_rel_user_table	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-        
+
         $current_url_id 			= api_get_current_access_url_id();
-        
+
         switch ($message_type) {
             case 'sent':
                 $field = 'user_sender_id';
@@ -620,7 +620,7 @@ class Statistics {
                 break;
         }
         if ($_configuration['multiple_access_urls']) {
-        	
+
             $sql = "SELECT lastname, firstname, username, COUNT($field) AS count_message ".
                 "FROM ".$access_url_rel_user_table." as url, ".$message_table." m ".
                 "LEFT JOIN ".$user_table." u ON m.$field = u.user_id ".
@@ -653,7 +653,7 @@ class Statistics {
         $user_table = Database::get_main_table(TABLE_MAIN_USER);
         $access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $current_url_id = api_get_current_access_url_id();
-        
+
         if ($_configuration['multiple_access_urls']) {
             $sql = "SELECT lastname, firstname, username, COUNT(friend_user_id) AS count_friend ".
                 "FROM ".$access_url_rel_user_table." as url, ".$user_friend_table." uf ".
@@ -675,7 +675,7 @@ class Statistics {
         }
         return $list_friends;
     }
-    
+
     /**
      * Print the number of users that didn't login for a certain period of time
      */
@@ -693,23 +693,23 @@ class Statistics {
             $table_url = '';
             $where_url='';
         }
-        $sql[get_lang('Thisday')]    = 
+        $sql[get_lang('Thisday')]    =
             "SELECT count(distinct(login_user_id)) AS number ".
             " FROM $table $table_url ".
             " WHERE DATE_ADD(login_date, INTERVAL 1 DAY) >= NOW() $where_url";
-        $sql[get_lang('Last7days')]  = 
+        $sql[get_lang('Last7days')]  =
             "SELECT count(distinct(login_user_id)) AS number ".
             " FROM $table $table_url ".
             " WHERE DATE_ADD(login_date, INTERVAL 7 DAY) >= NOW() $where_url";
-        $sql[get_lang('Last31days')] = 
+        $sql[get_lang('Last31days')] =
             "SELECT count(distinct(login_user_id)) AS number ".
             " FROM $table $table_url ".
             " WHERE DATE_ADD(login_date, INTERVAL 31 DAY) >= NOW() $where_url";
-        $sql[sprintf(get_lang('LastXMonths'),6)] = 
+        $sql[sprintf(get_lang('LastXMonths'),6)] =
             "SELECT count(distinct(login_user_id)) AS number ".
             " FROM $table $table_url ".
             " WHERE DATE_ADD(login_date, INTERVAL 6 MONTH) >= NOW() $where_url";
-        $sql[get_lang('NeverConnected')]      = 
+        $sql[get_lang('NeverConnected')]      =
             "SELECT count(distinct(login_user_id)) AS number ".
             " FROM $table $table_url WHERE 1=1 $where_url";
         foreach ($sql as $index => $query) {

+ 9 - 9
main/inc/lib/system/io/csv_reader.class.php

@@ -1,21 +1,21 @@
 <?php
 
 /**
- * Read cvs data from a stream - string/FileReader. 
- * 
+ * Read cvs data from a stream - string/FileReader.
+ *
  * Returns data as associative arrays (headers are the keys of the array).
  * Skip blank lines ?? is it such a good idea?
- * 
+ *
  * Usage:
- * 
+ *
  *      $reader = CsvReader::create('path');
  *      foreach($reader as $items){
  *          foreach($items as $key=>$value){
  *              echo "$key : $value";
  *          }
  *      }
- * 
- * 
+ *
+ *
  *
  * @copyright (c) 2012 University of Geneva
  * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html
@@ -29,7 +29,7 @@ class CsvReader implements Iterator
      * @param string|FileReader $stream
      * @param string $delimiter
      * @param string $enclosure
-     * @return CsvReader 
+     * @return CsvReader
      */
     static function create($stream, $delimiter = ';', $enclosure = '"')
     {
@@ -81,7 +81,7 @@ class CsvReader implements Iterator
         if (empty($line)) {
             return array();
         }
-        $data = api_str_getcsv($line, $this->get_delimiter(), $this->get_enclosure());
+        $data = Text::api_str_getcsv($line, $this->get_delimiter(), $this->get_enclosure());
         if ($this->headers) {
             $result = array();
             foreach ($data as $index => $value) {
@@ -100,7 +100,7 @@ class CsvReader implements Iterator
 
     /**
      * Returns the next non empty line
-     * 
+     *
      * @return boolean|string
      */
     protected function next_line()

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

@@ -627,7 +627,7 @@ class SystemAnnouncementManager {
                 $url = api_get_path(WEB_PATH).'news_list.php?id='.$announcement->id;
                 if (empty($id)) {
                     if (api_strlen(strip_tags($content)) > $cut_size) {
-                        $content = cut($announcement->content, $cut_size).' '.Display::url(get_lang('More'), $url);
+                        $content = Text::cut($announcement->content, $cut_size).' '.Display::url(get_lang('More'), $url);
                     }
                 }
                 $html .=  '<li><h2>'.$announcement->title.'</h2>'.$content.'</li>';

+ 16 - 27
main/inc/lib/template.lib.php

@@ -587,7 +587,7 @@ class Template
         $this->assign('menu', $menu);
 
         //Breadcrumb
-        $breadcrumb = $this->return_breadcrumb($interbreadcrumb, $nameTools);
+        $breadcrumb = $this->returnBreadcrumb($interbreadcrumb, $nameTools);
         $this->assign('breadcrumb', $breadcrumb);
 
         //Extra content
@@ -640,10 +640,10 @@ class Template
                     }
                     if (count($coachs_email) > 1) {
                         $tutor_data .= get_lang('Coachs').' : ';
-                        $tutor_data .= array_to_string($email_link, CourseManager::USER_SEPARATOR);
+                        $tutor_data .= ArrayClass::array_to_string($email_link, CourseManager::USER_SEPARATOR);
                     } elseif (count($coachs_email) == 1) {
                         $tutor_data .= get_lang('Coach').' : ';
-                        $tutor_data .= array_to_string($email_link, CourseManager::USER_SEPARATOR);
+                        $tutor_data .= ArrayClass::array_to_string($email_link, CourseManager::USER_SEPARATOR);
                     } elseif (count($coachs_email) == 0) {
                         $tutor_data .= '';
                     }
@@ -669,7 +669,7 @@ class Template
                     if (count($mail) > 1) {
                         $label = get_lang('Teachers');
                     }
-                    $teacher_data .= $label.' : '.array_to_string($teachers_parsed, CourseManager::USER_SEPARATOR);
+                    $teacher_data .= $label.' : '.ArrayClass::array_to_string($teachers_parsed, CourseManager::USER_SEPARATOR);
                 }
                 $this->assign('teachers', $teacher_data);
             }
@@ -734,8 +734,8 @@ class Template
         $mtime = $mtime[1] + $mtime[0];
         error_log('--------------------------------------------------------');
         error_log("Page loaded in:".($mtime - START));
-        error_log("memory_get_usage: ".format_file_size(memory_get_usage(true)));
-        error_log("memory_get_peak_usage: ".format_file_size(memory_get_peak_usage(true)));
+        error_log("memory_get_usage: ".Text::format_file_size(memory_get_usage(true)));
+        error_log("memory_get_peak_usage: ".Text::format_file_size(memory_get_peak_usage(true)));
     }
 
     function return_menu()
@@ -1028,11 +1028,11 @@ class Template
             'users'
         ) == 'true' AND $user_id) OR (api_get_setting('showonline', 'course') == 'true' AND $user_id AND $course_id)
         ) {
-            $number = who_is_online_count(api_get_setting('time_limit_whosonline'));
+            $number = Online::who_is_online_count(api_get_setting('time_limit_whosonline'));
 
             $number_online_in_course = 0;
             if (!empty($_course['id'])) {
-                $number_online_in_course = who_is_online_in_this_course_count(
+                $number_online_in_course = Online::who_is_online_in_this_course_count(
                     $user_id,
                     api_get_setting('time_limit_whosonline'),
                     $_course['id']
@@ -1230,7 +1230,7 @@ class Template
         return $return;
     }
 
-    function return_breadcrumb($interbreadcrumb)
+    function returnBreadcrumb($interbreadcrumb)
     {
         $session_id = api_get_session_id();
         $session_name = api_get_session_name($session_id);
@@ -1246,13 +1246,13 @@ class Template
 
         // part 1: Course Homepage. If we are in a course then the first breadcrumb is a link to the course homepage
         // hide_course_breadcrumb the parameter has been added to hide the name of the course, that appeared in the default $interbreadcrumb
-        $session_name = cut($session_name, MAX_LENGTH_BREADCRUMB);
+        $session_name = Text::cut($session_name, MAX_LENGTH_BREADCRUMB);
         $my_session_name = is_null($session_name) ? '' : '&nbsp;('.$session_name.')';
 
         if (!empty($_course) && !isset($_GET['hide_course_breadcrumb'])) {
 
             $navigation_item['url'] = $web_course_path.$_course['path'].'/index.php'.(!empty($session_id) ? '?id_session='.$session_id : '');
-            $course_title = cut($_course['name'], MAX_LENGTH_BREADCRUMB);
+            $course_title = Text::cut($_course['name'], MAX_LENGTH_BREADCRUMB);
 
             switch (api_get_setting('breadcrumbs_course_homepage')) {
                 case 'get_lang':
@@ -1287,16 +1287,11 @@ class Template
                     }
                     break;
             }
-            /**
-             * @todo could be useful adding the My courses in the breadcrumb
-            $navigation_item_my_courses['title'] = get_lang('MyCourses');
-            $navigation_item_my_courses['url'] = api_get_path(WEB_PATH).'user_portal.php';
-            $navigation[] = $navigation_item_my_courses;
-             */
             $navigation[] = $navigation_item;
         }
 
-        // part 2: Interbreadcrumbs. If there is an array $interbreadcrumb defined then these have to appear before the last breadcrumb (which is the tool itself)
+        // part 2: Interbreadcrumbs.
+        //If there is an array $interbreadcrumb defined then these have to appear before the last breadcrumb (which is the tool itself)
         if (isset($interbreadcrumb) && is_array($interbreadcrumb)) {
             foreach ($interbreadcrumb as $breadcrumb_step) {
                 if ($breadcrumb_step['url'] != '#') {
@@ -1312,8 +1307,8 @@ class Template
                 } elseif (strstr($breadcrumb_step['name'], 'shared_folder_session_')) {
                     $navigation_item['title'] = get_lang('UserFolders');
                 } elseif (strstr($breadcrumb_step['name'], 'sf_user_')) {
-                    $userinfo = Database::get_user_info_from_id(substr($breadcrumb_step['name'], 8));
-                    $navigation_item['title'] = api_get_person_name($userinfo['firstname'], $userinfo['lastname']);
+                    $userinfo = api_get_user_info(substr($breadcrumb_step['name'], 8));
+                    $navigation_item['title'] = $userinfo['complete_name'];
                 } elseif ($breadcrumb_step['name'] == 'chat_files') {
                     $navigation_item['title'] = get_lang('ChatFiles');
                 } elseif ($breadcrumb_step['name'] == 'images') {
@@ -1329,7 +1324,7 @@ class Template
                 }
                 //Fixes breadcrumb title now we applied the Security::remove_XSS and we cut the string depending of the MAX_LENGTH_BREADCRUMB value
 
-                $navigation_item['title'] = cut($navigation_item['title'], MAX_LENGTH_BREADCRUMB);
+                $navigation_item['title'] = Text::cut($navigation_item['title'], MAX_LENGTH_BREADCRUMB);
                 $navigation_item['title'] = Security::remove_XSS($navigation_item['title']);
                 $navigation[] = $navigation_item;
             }
@@ -1338,12 +1333,6 @@ class Template
 
         // part 3: The tool itself. If we are on the course homepage we do not want to display the title of the course because this
         // is the same as the first part of the breadcrumbs (see part 1)
-        /*
-        if (isset($nameTools) && $language_file != 'course_home') { // TODO: This condition $language_file != 'course_home' might bring surprises.
-            $navigation_item['url'] = '#';
-            $navigation_item['title'] = $nameTools;
-            $navigation[] = $navigation_item;
-        }*/
 
         $final_navigation = array();
         $counter = 0;

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor