Feature #306 - Platform administration tool: Cleaning code for course import. Revision again the logic for username validation and language id validation. A modification in the function api_validate_language(). Other minor fixes.

skala
Ivan Tcholakov 16 years ago
parent 5053645ad5
commit fe4de407cd
  1. 14
      main/admin/class_user_import.php
  2. 134
      main/admin/course_import.php
  3. 12
      main/admin/languages.php
  4. 2
      main/admin/session_import.php
  5. 23
      main/inc/lib/multibyte_string_functions.lib.php

@ -32,6 +32,7 @@
* Validates imported data. * Validates imported data.
*/ */
function validate_data($user_classes) { function validate_data($user_classes) {
global $purification_option_for_usernames;
$errors = array (); $errors = array ();
$classcodes = array (); $classcodes = array ();
foreach ($user_classes as $index => $user_class) { foreach ($user_classes as $index => $user_class) {
@ -62,16 +63,17 @@ function validate_data($user_classes) {
} }
// 3. Check username, first, check whether it is empty. // 3. Check username, first, check whether it is empty.
if (!UserManager::is_username_empty($user_class['UserName'])) { if (!UserManager::is_username_empty($user_class['UserName'])) {
// 3.1. Check whether username exists. // 3.1. Check whether username is too long.
if (UserManager::is_username_available($user_class['UserName'])) {
$user_class['error'] = get_lang('UnknownUser').': '.$user_class['UserName'];
$errors[] = $user_class;
}
// 3.2. Check whether username is too long.
if (UserManager::is_username_too_long($user_class['UserName'])) { if (UserManager::is_username_too_long($user_class['UserName'])) {
$user_class['error'] = get_lang('UserNameTooLong').': '.$user_class['UserName']; $user_class['error'] = get_lang('UserNameTooLong').': '.$user_class['UserName'];
$errors[] = $user_class; $errors[] = $user_class;
} }
$username = UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames);
// 3.2. Check whether username exists.
if (UserManager::is_username_available($username)) {
$user_class['error'] = get_lang('UnknownUser').': '.$username;
$errors[] = $user_class;
}
} }
} }
return $errors; return $errors;

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

@ -91,17 +91,17 @@ $htmlHeadXtra[] ='<script type="text/javascript">
$("#"+id_img_link_tool).attr("src",path_name_of_imglinktool); $("#"+id_img_link_tool).attr("src",path_name_of_imglinktool);
if (my_image_tool=="visible.gif") { if (my_image_tool=="visible.gif") {
$("#"+id_img_link_tool).attr("alt","'.get_lang('MakeAvailable').'"); $("#"+id_img_link_tool).attr("alt","'.get_lang('MakeAvailable', '').'");
$("#"+id_img_link_tool).attr("title","'.get_lang('MakeAvailable').'"); $("#"+id_img_link_tool).attr("title","'.get_lang('MakeAvailable', '').'");
} else { } else {
$("#"+id_img_link_tool).attr("alt","'.get_lang('MakeUnavailable').'"); $("#"+id_img_link_tool).attr("alt","'.get_lang('MakeUnavailable', '').'");
$("#"+id_img_link_tool).attr("title","'.get_lang('MakeUnavailable').'"); $("#"+id_img_link_tool).attr("title","'.get_lang('MakeUnavailable', '').'");
} }
if (datos=="set_visible") { if (datos=="set_visible") {
$("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowVisible').'</div>"); $("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowVisible', '').'</div>");
} else { } else {
$("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowHidden').'</div>"); $("#id_content_message").html("<div class=\"confirmation-message\">'.get_lang('LanguageIsNowHidden', '').'</div>");
} }
} }); } });

@ -170,7 +170,7 @@ if ($_POST['formSent']) {
$course_code = trim(api_utf8_decode($courseNode->CourseCode)); $course_code = trim(api_utf8_decode($courseNode->CourseCode));
$title = trim(api_utf8_decode($courseNode->CourseTitle)); $title = trim(api_utf8_decode($courseNode->CourseTitle));
$description = trim(api_utf8_decode($courseNode->CourseDescription)); $description = trim(api_utf8_decode($courseNode->CourseDescription));
$language = api_validate_language(trim(api_utf8_decode($courseNode->CourseLanguage))); $language = api_validate_language(api_utf8_decode($courseNode->CourseLanguage));
$username = trim(api_utf8_decode($courseNode->CourseTeacher)); $username = trim(api_utf8_decode($courseNode->CourseTeacher));
// Looking up for the teacher. // Looking up for the teacher.

@ -2792,7 +2792,7 @@ function api_is_valid_ascii(&$string) {
*/ */
/** /**
* Checks whether a given language identificator represents supported by the system language. * Checks whether a given language identificator represents supported by this library language.
* @param string $language The language identificator to be checked ('english', 'french', 'spanish', ...). * @param string $language The language identificator to be checked ('english', 'french', 'spanish', ...).
* @return bool $language TRUE if the language is supported, FALSE otherwise. * @return bool $language TRUE if the language is supported, FALSE otherwise.
*/ */
@ -2805,19 +2805,22 @@ function api_is_language_supported($language) {
} }
/** /**
* Validates the input language identificator in order always to return a language that is supported by the system. * Validates the input language identificator in order always to return a language that is enabled in the system.
* This function is to be used for data import when provided language identificators should be validated.
* @param string $language The language identificator to be validated. * @param string $language The language identificator to be validated.
* @param bool $purify A modifier to the returned result. If it is TRUE, then the returned language identificator is purified. * @return string Returns the input language identificator. If the input language is not enabled, platform language is returned then.
* @return string Returns the input language identificator, purified, if it was demanded. If the input language is not supported, the current interface language is returned then.
*/ */
function api_validate_language($language, $purify = false) { function api_validate_language($language) {
if (!api_is_language_supported($language)) { static $enabled_languages;
return api_get_interface_language($purify); if (!isset($enabled_languages)) {
$enabled_languages_info = api_get_languages();
$enabled_languages = $enabled_languages_info['folder'];
} }
if ($purify) { $language = str_replace('_km', '_KM', strtolower(trim($language)));
return api_refine_language_id($language); if (empty($language) || !in_array($language, $enabled_languages) || !api_is_language_supported($language)) {
$language = api_get_setting('platformLanguage');
} }
return str_replace('_km', '_KM', strtolower($language)); return $language;
} }
/** /**

Loading…
Cancel
Save