Adding import csv CRON see BT#6369

1.9.x
Julio Montoya 11 years ago
parent dfb1ba063c
commit e8ca90ee5d
  1. 319
      main/admin/session_import.php
  2. 318
      main/cron/import_csv.php
  3. 17
      main/inc/lib/main_api.lib.php
  4. 353
      main/inc/lib/sessionmanager.lib.php

@ -42,7 +42,7 @@ $purification_option_for_usernames = false;
$inserted_in_course = array();
global $_configuration;
global $_configuration;
if ($_POST['formSent']) {
if (isset($_FILES['import_file']['tmp_name']) && !empty($_FILES['import_file']['tmp_name'])) {
@ -76,27 +76,27 @@ if ($_POST['formSent']) {
if (count($root->Users->User) > 0) {
// Creating/updating users from <Sessions> <Users> base node.
foreach ($root->Users->User as $node_user) {
foreach ($root->Users->User as $node_user) {
$username = $username_old = trim(api_utf8_decode($node_user->Username));
if (UserManager::is_username_available($username)) {
if (UserManager::is_username_available($username)) {
$password = api_utf8_decode($node_user->Password);
if (empty($password)) {
$password = api_generate_password();
}
switch ($node_user->Status) {
case 'student' :
$status = 5;
case 'student' :
$status = 5;
break;
case 'teacher' :
$status = 1;
case 'teacher' :
$status = 1;
break;
default :
$status = 5;
default :
$status = 5;
$error_message .= get_lang('StudentStatusWasGivenTo').' : '.$username.'<br />';
}
$result = UserManager::create_user(
api_utf8_decode($node_user->Firstname),
api_utf8_decode($node_user->Firstname),
api_utf8_decode($node_user->Lastname),
$status,
api_utf8_decode($node_user->Email),
@ -113,7 +113,7 @@ if ($_POST['formSent']) {
null,
null,
$send_mail
);
);
} else {
$lastname = trim(api_utf8_decode($node_user->Lastname));
$firstname = trim(api_utf8_decode($node_user->Firstname));
@ -144,28 +144,28 @@ if ($_POST['formSent']) {
}
// Creating courses from <Sessions> <Courses> base node.
if (count($root->Courses->Course) > 0) {
foreach ($root->Courses->Course as $courseNode) {
$params = array();
if (empty($courseNode->CourseTitle)) {
$params['title'] = api_utf8_decode($courseNode->CourseCode);
} else {
$params['title'] = api_utf8_decode($courseNode->CourseTitle);
}
$params['wanted_code'] = api_utf8_decode($courseNode->CourseCode);
$params['wanted_code'] = api_utf8_decode($courseNode->CourseCode);
$params['tutor_name'] = null;
$params['course_category'] = null;
$params['course_category'] = null;
$params['course_language'] = api_get_valid_language(api_utf8_decode($courseNode->CourseLanguage));
$params['user_id'] = api_get_user_id();
// Looking up for the teacher.
$username = trim(api_utf8_decode($courseNode->CourseTeacher));
$sql = "SELECT user_id, lastname, firstname FROM $tbl_user WHERE username='$username'";
$rs = Database::query($sql);
list($user_id, $lastname, $firstname) = Database::fetch_array($rs);
$params['teachers'] = $user_id;
CourseManager::create_course($params);
}
@ -287,8 +287,8 @@ if ($_POST['formSent']) {
}
// Associate the session with access_url.
global $_configuration;
if ($_configuration['multiple_access_urls']) {
global $_configuration;
if ($_configuration['multiple_access_urls']) {
$access_url_id = api_get_current_access_url_id();
UrlManager::add_session_to_url($session_id, $access_url_id);
} else {
@ -457,280 +457,9 @@ if ($_POST['formSent']) {
// CSV
$content = file($_FILES['import_file']['tmp_name']);
if (!api_strstr($content[0], ';')) {
$error_message = get_lang('NotCSV');
} else {
$tag_names = array();
foreach ($content as $key => $enreg) {
$enreg = explode(';', trim($enreg));
if ($key) {
foreach ($tag_names as $tag_key => $tag_name) {
$sessions[$key - 1][$tag_name] = $enreg[$tag_key];
}
} else {
foreach ($enreg as $tag_name) {
$tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
}
if (!in_array('SessionName', $tag_names) || !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)) {
$error_message = get_lang('NoNeededData');
break;
}
}
}
// Looping the sessions.
foreach ($sessions as $enreg) {
$user_counter = 0;
$course_counter = 0;
$session_name = $enreg['SessionName'];
$date_start = $enreg['DateStart'];
$date_end = $enreg['DateEnd'];
$visibility = $enreg['Visibility'];
$session_category_id = $enreg['SessionCategory'];
// Searching a coach.
if (!empty($enreg['Coach'])) {
$coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
if ($coach_id === false) {
// If the coach-user does not exist - I'm the coach.
$coach_id = api_get_user_id();
}
} else {
$coach_id = api_get_user_id();
}
if (!$updatesession) {
// Always create a session.
$unique_name = false; // This MUST be initializead.
$i = 0;
// Change session name, verify that session doesn't exist.
while (!$unique_name) {
if ($i > 1) {
$suffix = ' - '.$i;
}
$sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.Database::escape_string($session_name.$suffix).'"';
$rs = Database::query($sql);
if (Database::result($rs, 0, 0)) {
$i++;
} else {
$unique_name = true;
$session_name .= $suffix;
}
}
// Creating the session.
$sql_session = "INSERT IGNORE INTO $tbl_session SET
name = '".Database::escape_string($session_name)."',
id_coach = '$coach_id',
date_start = '$date_start',
date_end = '$date_end',
visibility = '$visibility',
session_category_id = '$session_category_id',
session_admin_id=".intval($_user['user_id']);
$rs_session = Database::query($sql_session);
$session_id = Database::insert_id();
$session_counter++;
} else {
$my_session_result = SessionManager::get_session_by_name($session_name);
if ($my_session_result === false) {
// Creating a session.
$sql_session = "INSERT IGNORE INTO $tbl_session SET
name = '$session_name',
id_coach = '$coach_id',
date_start = '$date_start',
date_end = '$date_end',
visibility = '$visibility',
session_category_id = '$session_category_id'";
$rs_session = Database::query($sql_session);
// We get the last insert id.
$my_session_result = SessionManager::get_session_by_name($session_name);
$session_id = $my_session_result['id'];
//echo '<br>';
} else {
// The session already exists, update it then.
$sql_session = "UPDATE $tbl_session SET
id_coach = '$coach_id',
date_start = '$date_start',
date_end = '$date_end',
visibility = '$visibility',
session_category_id = '$session_category_id'
WHERE name = '$session_name'";
$rs_session = Database::query($sql_session);
$session_id = Database::query("SELECT id FROM $tbl_session WHERE name='$session_name'");
list($session_id) = Database::fetch_array($session_id);
Database::query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'");
Database::query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'");
Database::query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'");
}
$session_counter++;
}
$users = explode('|', $enreg['Users']);
// Adding the relationship "Session - User".
if (is_array($users)) {
foreach ($users as $user) {
$user_id = UserManager::get_user_id_from_username($user);
if ($user_id !== false) {
// Insert new users.
$sql = "INSERT IGNORE INTO $tbl_session_user SET
id_user='$user_id',
id_session = '$session_id'";
$rs_user = Database::query($sql);
$user_counter++;
}
}
}
$courses = explode('|', $enreg['Courses']);
foreach ($courses as $course) {
$course_code = api_strtoupper(api_substr($course, 0, api_strpos($course, '[')));
if (CourseManager::course_exists($course_code)) {
// If the course exists we continue.
$course_info = CourseManager::get_course_information($course_code);
$coach = api_strstr($course, '[');
$coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
if (!empty($coach)) {
$coach_id = UserManager::get_user_id_from_username($coach);
if ($coach_id === false) {
$coach_id = '';
}
} else {
$coach = '';
}
// Adding the course to a session.
$sql_course = "INSERT IGNORE INTO $tbl_session_course SET
course_code = '$course_code',
id_session='$session_id'";
$rs_course = Database::query($sql_course);
$course_counter++;
$course_split = array();
$pattern = "/\[(.*?)\]/";
preg_match_all($pattern, $course, $matches);
if (isset($matches[1])) {
$course_coaches = $matches[1][0];
$course_users = $matches[1][1];
}
$course_users = explode(',', $course_users);
$course_coaches = explode(',', $course_coaches);
// Adding coaches to session course user
if (!empty($course_coaches)) {
foreach ($course_coaches as $course_coach) {
$coach_id = UserManager::get_user_id_from_username($course_coach);
if ($coach_id !== false) {
$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
id_user='$coach_id',
course_code='$course_code',
id_session = '$session_id',
status = 2 ";
$rs_coachs = Database::query($sql);
} else {
$error_message .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
}
}
}
$users_in_course_counter = 0;
// Adding the relationship "Session - Course - User".
foreach ($course_users as $user) {
$user_id = UserManager::get_user_id_from_username($user);
if ($user_id !== false) {
$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
id_user='$user_id',
course_code='$course_code',
id_session = '$session_id'";
$rs_users = Database::query($sql);
$users_in_course_counter++;
} else {
$error_message .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
}
}
$sql = "UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='$course_code'";
Database::query($sql);
$course_info = CourseManager::get_course_information($course_code);
$inserted_in_course[$course_code] = $course_info['title'];
} else {
// TODO: We should create the course as in the XML import.
}
if (CourseManager::course_exists($course_code, true)) {
$list = CourseManager :: get_courses_info_from_visual_code($course_code);
foreach ($list as $vcourse) {
if ($vcourse['code'] == $course_code) {
// Ignore, this has already been inserted.
} else {
$coach = api_strstr($course, '[');
$coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
// Adding the relationship "Session - Course".
$sql_course = "INSERT IGNORE INTO $tbl_session_course SET
course_code = '".$vcourse['code']."',
id_session='$session_id'";
$rs_course = Database::query($sql_course);
// adding coachs to session course user
foreach ($course_coaches as $course_coach) {
$coach_id = UserManager::get_user_id_from_username($course_coach);
if ($coach_id !== false) {
$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
id_user='$coach_id',
course_code='{$vcourse['code']}',
id_session = '$session_id',
status = 2 ";
$rs_coachs = Database::query($sql);
} else {
$error_message .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
}
}
$users_in_course_counter = 0;
// Adding the relationship "Session - Course - User".
foreach ($course_users as $user) {
$user_id = UserManager::get_user_id_from_username($user);
if ($user_id !== false) {
$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
id_user='$user_id',
course_code='{$vcourse['code']}',
id_session = '$session_id'";
$rs_users = Database::query($sql);
$users_in_course_counter++;
} else {
$error_message .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
}
}
Database::query("UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='".$vcourse['code']."'");
}
}
$inserted_in_course[$vcourse['code']] = $vcourse['title'];
}
}
$access_url_id = api_get_current_access_url_id();
UrlManager::add_session_to_url($session_id, $access_url_id);
$sql_update_users = "UPDATE $tbl_session SET nbr_users='$user_counter', nbr_courses='$course_counter' WHERE id='$session_id'";
Database::query($sql_update_users);
}
}
$result = SessionManager::importCSV($_FILES['import_file']['tmp_name'], $updatesession, api_get_user_id());
$error_message = $result['error_message'];
$session_counter = $result['session_counter'];
}
if (!empty($error_message)) {
@ -868,4 +597,4 @@ $form->display();
<?php
/* FOOTER */
Display::display_footer();
Display::display_footer();

@ -0,0 +1,318 @@
<?php
if (PHP_SAPI!='cli') {
die('Run this script through the command line or comment this line in the code');
}
require_once '../inc/global.inc.php';
require_once api_get_path(LIBRARY_PATH).'log.class.php';
$path = api_get_path(SYS_CODE_PATH).'cron/incoming/';
$files = scandir($path);
if (!empty($files)) {
foreach ($files as $file) {
$fileInfo = pathinfo($file);
if ($fileInfo['extension'] == 'csv') {
// teachers_yyyymmdd.csv, courses_yyyymmdd.csv, students_yyyymmdd.csv and sessions_yyyymmdd.csv
$parts = explode('_', $fileInfo['filename']);
$method = 'import'.ucwords($parts[0]);
if (function_exists($method)) {
$method($path.$fileInfo['basename']);
} else {
echo "Error - This file can't be processed.";
exit;
}
}
}
}
/**
* @param $file
*/
function moveFile($file)
{
$moved = str_replace('incoming', 'treated', $file);
// $result = rename($file, $moved);
$result = 1;
if ($result) {
Log::info("Moving file to the treated folder: $file");
} else {
Log::error("Error - Cant move file to the treated folder: $file");
}
}
/**
* File to import
* @param string $file
*/
function importTeachers($file)
{
$data = Import::csv_to_array($file);
Log::info("-- Import Teachers --");
Log::info("Reading file: $file");
/* Unique identifier: official-code username.
Email address and password should never get updated. *ok
The only fields that I can think of that should update if the data changes in the csv file are FirstName and LastName. *ok
A slight edit of these fields should be taken into account. ???
Adding teachers is no problem, but deleting them shouldn’t be automated, but we should get a log of “to delete teachers”.
We’ll handle that manually if applicable.
No delete!
*/
if (!empty($data)) {
foreach ($data as $row) {
$userInfo = api_get_user_info_from_username($row['username']);
$userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
if (empty($userInfo) && empty($userInfoByOfficialCode)) {
// Create user
$result = UserManager::create_user(
$row['firstname'],
$row['lastname'],
COURSEMANAGER,
$row['email'],
$row['username'],
$row['password'],
$row['official_code'],
$row['language'],
$row['phone'],
$row['picture'], //picture
PLATFORM_AUTH_SOURCE, // ?
$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
1, //active
0,
null, // extra
null, //$encrypt_method = '',
false //$send_mail = false
);
if ($result) {
Log::info("Info - Teachers - User created: ".$row['username']);
} else {
Log::error("Error - Teachers - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
}
} else {
if (empty($userInfo)) {
Log::error("Error - Teachers - Can't update user :".$row['username']);
continue;
}
// Update user
$result = UserManager::update_user(
$userInfo['user_id'],
$row['firstname'], // <<-- changed
$row['lastname'], // <<-- changed
$userInfo['username'],
null, //$password = null,
$auth_source = null,
$userInfo['email'],
COURSEMANAGER,
$userInfo['official_code'],
$userInfo['phone'],
$userInfo['picture_uri'],
$userInfo['expiration_date'],
$userInfo['active'],
null, //$creator_id = null,
0, //$hr_dept_id = 0,
null, // $extra = null,
null, //$language = 'english',
null, //$encrypt_method = '',
false, //$send_email = false,
0 //$reset_password = 0
);
if ($result) {
Log::info("Teachers - User updated: ".$row['username']);
} else {
Log::error("Teachers - User not updated: ".$row['username']);
}
}
// UserManager::delete_user();
moveFile($file);
}
}
}
function importStudents($file)
{
$data = Import::csv_to_array($file);
Log::info("-- Import Students --");
Log::info("Reading file: $file");
/*
* Another users import.
Unique identifier: official code and username . ok
Username and password should never get updated. ok
If an update should need to occur (because it changed in the .csv), we’ll want that logged. We will handle this manually in that case.
All other fields should be updateable, though passwords should of course not get updated. ok
If a user gets deleted (not there anymore),
He should be set inactive one year after the current date. So I presume you’ll just update the expiration date. We want to grant access to courses up to a year after deletion.
*/
if (!empty($data)) {
foreach ($data as $row) {
$userInfo = api_get_user_info_from_username($row['username']);
$userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
if (empty($userInfo) && empty($userInfoByOfficialCode)) {
// Create user
$result = UserManager::create_user(
$row['firstname'],
$row['lastname'],
STUDENT,
$row['email'],
$row['username'],
$row['password'],
$row['official_code'],
$row['language'],
$row['phone'],
$row['picture'], //picture
PLATFORM_AUTH_SOURCE, // ?
$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
1, //active
0,
null, // extra
null, //$encrypt_method = '',
false //$send_mail = false
);
if ($result) {
Log::info("Students - User created: ".$row['username']);
} else {
Log::error("Students - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
}
} else {
if (empty($userInfo)) {
Log::error("Students - Can't update user :".$row['username']);
continue;
}
if ($row['action'] == 'delete') {
// INactive one year later
$userInfo['expiration_date'] = api_get_utc_datetime(api_strtotime(time() + 365*24*60*60));
}
// Update user
$result = UserManager::update_user(
$userInfo['user_id'],
$row['firstname'], // <<-- changed
$row['lastname'], // <<-- changed
$userInfo['username'],
null, //$password = null,
$auth_source = null,
$userInfo['email'],
STUDENT,
$userInfo['official_code'],
$userInfo['phone'],
$userInfo['picture_uri'],
$userInfo['expiration_date'],
$userInfo['active'],
null, //$creator_id = null,
0, //$hr_dept_id = 0,
null, // $extra = null,
null, //$language = 'english',
null, //$encrypt_method = '',
false, //$send_email = false,
0 //$reset_password = 0
);
if ($result) {
Log::info("Students - User updated: ".$row['username']);
} else {
Log::error("Students - User NOT updated: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
}
}
// UserManager::delete_user();
moveFile($file);
}
}
moveFile($file);
}
function importCourses($file)
{
$data = Import::csv_to_array($file);
Log::info("Reading file: $file");
if (!empty($data)) {
foreach ($data as $row) {
$courseInfo = api_get_course_info($row['course_code']);
if (empty($courseInfo)) {
// Create
$params = array();
$params['title'] = $row['title'];
$params['exemplary_content'] = false;
$params['wanted_code'] = $row['course_code'];
$params['category_code'] = $row['category_code'];
$params['course_language'] = $row['language'];
//$params['gradebook_model_id'] = isset($course_values['gradebook_model_id']) ? $course_values['gradebook_model_id'] : null;
$courseInfo = CourseManager::create_course($params);
if (!empty($courseInfo)) {
Log::info("Courses - Course created ".$courseInfo['code']);
} else {
Log::error("Courses - Can't create course:".$row['title']);
}
} else {
// Update
$params = array(
'title' => $row['title'],
);
$result = CourseManager::update_attributes($courseInfo['id'], $params);
if ($result) {
Log::info("Courses - Course updated ".$courseInfo['code']);
} else {
Log::error("Courses - Course NOT updated ".$courseInfo['code']);
}
/*course_language='".Database::escape_string($course_language)."',
title='".Database::escape_string($title)."',
category_code='".Database::escape_string($category_code)."',
tutor_name='".Database::escape_string($tutor_name)."',
visual_code='".Database::escape_string($visual_code)."',
department_name='".Database::escape_string($department_name)."',
department_url='".Database::escape_string($department_url)."',
disk_quota='".Database::escape_string($disk_quota)."',
visibility = '".Database::escape_string($visibility)."',
subscribe = '".Database::escape_string($subscribe)."',
unsubscribe='*/
}
}
}
moveFile($file);
}
function importSessions($file)
{
$result = SessionManager::importCSV($file, true, 1, true);
if (!empty($result['error_message'])) {
Log::error($result['error_message']);
}
Log::info("Sessions - Sessions parsed: ".$result['session_counter']);
moveFile($file);
/*$data = Import::csv_to_array($file);
Log::info("Reading file: $file");
if (!empty($data)) {
foreach ($data as $row) {
if (empty($courseInfo)) {
}
}
}
moveFile($file);*/
}

@ -6434,3 +6434,20 @@ function api_get_bytes_memory_limit($mem){
}
return $mem;
}
/**
* Finds all the information about a user from username instead of user id
* @param $username (string): the username
* @return $user_info (array): user_id, lastname, firstname, username, email, ...
* @author Yannick Warnier <yannick.warnier@beeznest.com>
*/
function api_get_user_info_from_official_code($official_code = '') {
if (empty($official_code)) { return false; }
$sql = "SELECT * FROM ".Database :: get_main_table(TABLE_MAIN_USER)." WHERE official_code ='".Database::escape_string($official_code)."'";
$result = Database::query($sql);
if (Database::num_rows($result) > 0) {
$result_array = Database::fetch_array($result);
return _api_format_user($result_array);
}
return false;
}

@ -241,15 +241,15 @@ class SessionManager {
$today = date('Y-m-d', $today);
$select = "SELECT * FROM (SELECT
IF (
IF (
(s.date_start <= '$today' AND '$today' < s.date_end) OR
(s.nb_days_access_before_beginning > 0 AND DATEDIFF(s.date_start,'".$today."' ".") <= s.nb_days_access_before_beginning) OR
(s.nb_days_access_after_end > 0 AND DATEDIFF('".$today."',s.date_end) <= s.nb_days_access_after_end) OR
(s.date_start = '0000-00-00' AND s.date_end = '0000-00-00' ) OR
(s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
('$today' < s.date_end AND '0000-00-00' = s.date_start)
, 1, 0)
, 1, 0)
as session_active,
s.name,
nbr_courses,
@ -1842,4 +1842,349 @@ class SessionManager {
}
return $session_array;
}
}
/**
* @param string $file
* @param bool $updatesession options:
* true: if the session exists it will be updated
* false: if session exists a new session will be created adding a counter session1, session2, etc
* @param int $user_id
* @return array
*/
static function importCSV($file, $updatesession, $user_id = null, $debug = false)
{
$content = file($file);
$error_message = null;
$session_counter = 0;
if (empty($user_id)) {
$user_id = api_get_user_id();
}
$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
$tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
$tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
$tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
if (!api_strstr($content[0], ';')) {
$error_message = get_lang('NotCSV');
} else {
$tag_names = array();
foreach ($content as $key => $enreg) {
$enreg = explode(';', trim($enreg));
if ($key) {
foreach ($tag_names as $tag_key => $tag_name) {
$sessions[$key - 1][$tag_name] = $enreg[$tag_key];
}
} else {
foreach ($enreg as $tag_name) {
$tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
}
if (!in_array('SessionName', $tag_names) || !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)) {
$error_message = get_lang('NoNeededData');
break;
}
}
}
// Looping the sessions.
foreach ($sessions as $enreg) {
$user_counter = 0;
$course_counter = 0;
$session_name = $enreg['SessionName'];
$date_start = $enreg['DateStart'];
$date_end = $enreg['DateEnd'];
$visibility = $enreg['Visibility'];
$session_category_id = $enreg['SessionCategory'];
// Searching a coach.
if (!empty($enreg['Coach'])) {
$coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
if ($coach_id === false) {
// If the coach-user does not exist - I'm the coach.
$coach_id = api_get_user_id();
}
} else {
$coach_id = api_get_user_id();
}
if (!$updatesession) {
// Always create a session.
$unique_name = false; // This MUST be initializead.
$i = 0;
// Change session name, verify that session doesn't exist.
while (!$unique_name) {
if ($i > 1) {
$suffix = ' - '.$i;
}
$sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.Database::escape_string($session_name.$suffix).'"';
$rs = Database::query($sql);
if (Database::result($rs, 0, 0)) {
$i++;
} else {
$unique_name = true;
$session_name .= $suffix;
}
}
// Creating the session.
$sql_session = "INSERT IGNORE INTO $tbl_session SET
name = '".Database::escape_string($session_name)."',
id_coach = '$coach_id',
date_start = '$date_start',
date_end = '$date_end',
visibility = '$visibility',
session_category_id = '$session_category_id',
session_admin_id=".intval($user_id);
Database::query($sql_session);
$session_id = Database::insert_id();
if ($debug) {
if ($session_id) {
Log::info("Sessions - Session created: #$session_id - $session_name");
} else {
Log::error("Sessions - Session NOT created $session_name");
}
}
$session_counter++;
} else {
$my_session_result = SessionManager::get_session_by_name($session_name);
if ($my_session_result === false) {
// Creating a session.
$sql_session = "INSERT IGNORE INTO $tbl_session SET
name = '$session_name',
id_coach = '$coach_id',
date_start = '$date_start',
date_end = '$date_end',
visibility = '$visibility',
session_category_id = '$session_category_id'";
Database::query($sql_session);
// We get the last insert id.
$my_session_result = SessionManager::get_session_by_name($session_name);
$session_id = $my_session_result['id'];
if ($debug) {
if ($session_id) {
Log::info("Sessions - #$session_id created: $session_name");
} else {
Log::error("Sessions - Session NOT created $session_name");
}
}
} else {
// The session already exists, update it then.
$sql_session = "UPDATE $tbl_session SET
id_coach = '$coach_id',
date_start = '$date_start',
date_end = '$date_end',
visibility = '$visibility',
session_category_id = '$session_category_id'
WHERE name = '$session_name'";
Database::query($sql_session);
$session_id = Database::query("SELECT id FROM $tbl_session WHERE name='$session_name'");
list($session_id) = Database::fetch_array($session_id);
Database::query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'");
Database::query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'");
Database::query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'");
}
$session_counter++;
}
$users = explode('|', $enreg['Users']);
// Adding the relationship "Session - User".
if (is_array($users)) {
foreach ($users as $user) {
$user_id = UserManager::get_user_id_from_username($user);
if ($user_id !== false) {
// Insert new users.
$sql = "INSERT IGNORE INTO $tbl_session_user SET
id_user='$user_id',
id_session = '$session_id'";
Database::query($sql);
if ($debug) {
Log::info("Sessions - Adding User #$user_id to session #$session_id");
}
$user_counter++;
}
}
}
$courses = explode('|', $enreg['Courses']);
foreach ($courses as $course) {
$course_code = api_strtoupper(api_substr($course, 0, api_strpos($course, '[')));
if (CourseManager::course_exists($course_code)) {
// If the course exists we continue.
$course_info = CourseManager::get_course_information($course_code);
$coach = api_strstr($course, '[');
$coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
if (!empty($coach)) {
$coach_id = UserManager::get_user_id_from_username($coach);
if ($coach_id === false) {
$coach_id = '';
}
} else {
$coach = '';
}
// Adding the course to a session.
$sql_course = "INSERT IGNORE INTO $tbl_session_course SET
course_code = '$course_code',
id_session='$session_id'";
Database::query($sql_course);
if ($debug) {
Log::info("Sessions - Adding course '$course_code' to session #$session_id");
}
$course_counter++;
$pattern = "/\[(.*?)\]/";
preg_match_all($pattern, $course, $matches);
if (isset($matches[1])) {
$course_coaches = $matches[1][0];
$course_users = $matches[1][1];
}
$course_users = explode(',', $course_users);
$course_coaches = explode(',', $course_coaches);
// Adding coaches to session course user
if (!empty($course_coaches)) {
foreach ($course_coaches as $course_coach) {
$coach_id = UserManager::get_user_id_from_username($course_coach);
if ($coach_id !== false) {
$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
id_user='$coach_id',
course_code='$course_code',
id_session = '$session_id',
status = 2 ";
Database::query($sql);
if ($debug) {
Log::info("Sessions - Adding course coach: user #$coach_id to course: '$course_code' and session #$session_id");
}
} else {
$error_message .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
}
}
}
$users_in_course_counter = 0;
// Adding the relationship "Session - Course - User".
foreach ($course_users as $user) {
$user_id = UserManager::get_user_id_from_username($user);
if ($user_id !== false) {
$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
id_user='$user_id',
course_code='$course_code',
id_session = '$session_id'";
Database::query($sql);
if ($debug) {
Log::info("Sessions - Adding student: user #$user_id to course: '$course_code' and session #$session_id");
}
$users_in_course_counter++;
} else {
$error_message .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
}
}
$sql = "UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='$course_code'";
Database::query($sql);
$course_info = CourseManager::get_course_information($course_code);
$inserted_in_course[$course_code] = $course_info['title'];
} else {
// TODO: We should create the course as in the XML import.
}
if (CourseManager::course_exists($course_code, true)) {
$list = CourseManager :: get_courses_info_from_visual_code($course_code);
foreach ($list as $vcourse) {
if ($vcourse['code'] == $course_code) {
// Ignore, this has already been inserted.
} else {
$coach = api_strstr($course, '[');
$coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
// Adding the relationship "Session - Course".
$sql_course = "INSERT IGNORE INTO $tbl_session_course SET
course_code = '".$vcourse['code']."',
id_session='$session_id'";
Database::query($sql_course);
if ($debug) {
Log::info("Sessions - Adding course to session: course: '".$vcourse['code']."' and session #$session_id");
}
// adding coachs to session course user
foreach ($course_coaches as $course_coach) {
$coach_id = UserManager::get_user_id_from_username($course_coach);
if ($coach_id !== false) {
$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
id_user='$coach_id',
course_code='{$vcourse['code']}',
id_session = '$session_id',
status = 2 ";
Database::query($sql);
if ($debug) {
Log::info("Sessions - Adding coach to session: user #$coach_id course: '".$vcourse['code']."' and session #$session_id");
}
} else {
$error_message .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
}
}
$users_in_course_counter = 0;
// Adding the relationship "Session - Course - User".
foreach ($course_users as $user) {
$user_id = UserManager::get_user_id_from_username($user);
if ($user_id !== false) {
$sql = "INSERT IGNORE INTO $tbl_session_course_user SET
id_user='$user_id',
course_code='{$vcourse['code']}',
id_session = '$session_id'";
Database::query($sql);
if ($debug) {
Log::info("Sessions - Adding user to session: user #$user_id course: '".$vcourse['code']."' and session #$session_id");
}
$users_in_course_counter++;
} else {
$error_message .= get_lang('UserDoesNotExist').' : '.$user.'<br />';
}
}
Database::query("UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='".$vcourse['code']."'");
}
}
$inserted_in_course[$vcourse['code']] = $vcourse['title'];
}
}
$access_url_id = api_get_current_access_url_id();
UrlManager::add_session_to_url($session_id, $access_url_id);
$sql_update_users = "UPDATE $tbl_session SET nbr_users='$user_counter', nbr_courses='$course_counter' WHERE id='$session_id'";
Database::query($sql_update_users);
}
}
return array(
'error_message' => $error_message,
'session_counter' => $session_counter
);
}
}

Loading…
Cancel
Save