[svn r14674] - Added extra user fields tables (see FS#2371)

- Added extra user fields management scripts (see FS#2371)
skala
Yannick Warnier 18 years ago
parent 6a5f038420
commit e0ea4e9601
  1. 3
      main/admin/index.php
  2. 10
      main/admin/user_add.php
  3. 270
      main/admin/user_fields.php
  4. 121
      main/admin/user_fields_add.php
  5. 39
      main/auth/profile.php
  6. 15
      main/inc/lib/database.lib.php
  7. 382
      main/inc/lib/usermanager.lib.php
  8. 29
      main/install/dokeos_main.sql
  9. 3
      main/install/migrate-db-1.8.4-1.8.5-pre.sql

@ -1,4 +1,4 @@
<?php // $Id: index.php 14281 2008-02-11 15:52:36Z yannoo $
<?php // $Id: index.php 14674 2008-03-20 12:24:34Z yannoo $
/*
==============================================================================
Dokeos - elearning and course management software
@ -94,6 +94,7 @@ $keyword_url = Security::remove_XSS($_GET['keyword']);
<li><a href="user_add.php"><?php echo get_lang('AddUsers') ?></a></li>
<li><a href="user_export.php"><?php echo get_lang('ExportUserListXMLCSV') ?></a></li>
<li><a href="user_import.php"><?php echo get_lang('ImportUserListXMLCSV') ?></a></li>
<li><a href="user_fields.php"><?php echo get_lang('ManageUserFields'); ?></a></li>
</ul>
</div>

@ -1,9 +1,9 @@
<?php // $Id: user_add.php 14672 2008-03-20 11:14:01Z yannoo $
<?php // $Id: user_add.php 14674 2008-03-20 12:24:34Z yannoo $
/*
==============================================================================
Dokeos - elearning and course management software
Copyright (c) 2004 Dokeos S.A.
Copyright (c) 2004-2008 Dokeos S.A.
Copyright (c) 2003 Ghent University (UGent)
Copyright (c) 2001 Universite catholique de Louvain (UCL)
Copyright (c) Olivier Brouckaert
@ -272,12 +272,14 @@ if( $form->validate())
if(isset($user['submit_plus']))
{
//we want to add more. Prepare report message and redirect to the same page (to clean the form)
header('Location: user_add.php?message='.urlencode(get_lang('UserAdded')));
$tok = Security::get_token();
header('Location: user_add.php?message='.urlencode(get_lang('UserAdded').'&sec_token='.$tok));
exit ();
}
else
{
header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('UserAdded')));
$tok = Security::get_token();
header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('UserAdded').'&sec_token='.$tok));
exit ();
}
}

@ -46,206 +46,87 @@ $table_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
$table_uf_opt = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
$table_uf_val = Database :: get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
if(!empty($_GET['message'])){
$message = $_GET['message'];
}
$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
$tool_name = get_lang('UserFields');
/*
// Create the form
$form = new FormValidator('user_add');
// Lastname
$form->addElement('text','lastname',get_lang('LastName'));
$form->applyFilter('lastname','html_filter');
$form->applyFilter('lastname','trim');
$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
// Firstname
$form->addElement('text','firstname',get_lang('FirstName'));
$form->applyFilter('firstname','html_filter');
$form->applyFilter('firstname','trim');
$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
// Official code
$form->addElement('text', 'official_code', get_lang('OfficialCode'),array('size' => '40'));
$form->applyFilter('official_code','html_filter');
$form->applyFilter('official_code','trim');
// Email
$form->addElement('text', 'email', get_lang('Email'),array('size' => '40'));
$form->addRule('email', get_lang('EmailWrong'), 'email');
$form->addRule('email', get_lang('EmailWrong'), 'required');
// Phone
$form->addElement('text','phone',get_lang('PhoneNumber'));
// Picture
$form->addElement('file', 'picture', get_lang('AddPicture'));
$allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
$form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
// Username
$form->addElement('text', 'username', get_lang('LoginName'),array('maxlength'=>20));
$form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
$form->addRule('username', get_lang('OnlyLettersAndNumbersAllowed'), 'username');
$form->addRule('username', '', 'maxlength',20);
$form->addRule('username', get_lang('UserTaken'), 'username_available', $user_data['username']);
// Password
$group = array();
$auth_sources = 0; //make available wider as we need it in case of form reset (see below)
if(count($extAuthSource) > 0)
{
$group[] =& HTML_QuickForm::createElement('radio','password_auto',null,get_lang('ExternalAuthentication').' ',2);
$auth_sources = array();
foreach($extAuthSource as $key => $info)
{
$auth_sources[$key] = $key;
}
$group[] =& HTML_QuickForm::createElement('select','auth_source',null,$auth_sources);
$group[] =& HTML_QuickForm::createElement('static','','','<br />');
}
$group[] =& HTML_QuickForm::createElement('radio','password_auto',get_lang('Password'),get_lang('AutoGeneratePassword').'<br />',1);
$group[] =& HTML_QuickForm::createElement('radio', 'password_auto','id="radio_user_password"',null,0);
$group[] =& HTML_QuickForm::createElement('password', 'password',null,'onkeydown=password_switch_radio_button(document.user_add,"password[password_auto]")');
$form->addGroup($group, 'password', get_lang('Password'), '');
// Status
$status = array();
$status[COURSEMANAGER] = get_lang('CourseAdmin');
$status[STUDENT] = get_lang('Student');
$form->addElement('select','status',get_lang('Status'),$status);
// Platform admin
$group = array();
$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin',null,get_lang('Yes'),1);
$group[] =& HTML_QuickForm::createElement('radio', 'platform_admin',null,get_lang('No'),0);
$form->addGroup($group, 'admin', get_lang('PlatformAdmin'), '&nbsp;');
// Send email
$group = array();
$group[] =& HTML_QuickForm::createElement('radio', 'send_mail',null,get_lang('Yes'),1);
$group[] =& HTML_QuickForm::createElement('radio', 'send_mail',null,get_lang('No'),0);
$form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;');
// Expiration Date
$form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
$group = array ();
$group[] = & $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
$group[] = & $form->createElement('datepicker','expiration_date', null, array ('form_name' => $form->getAttribute('name'), 'onChange'=>'enable_expiration_date()'));
$form->addGroup($group, 'max_member_group', null, '', false);
// Active account or inactive account
$form->addElement('radio','active',get_lang('ActiveAccount'),get_lang('Active'),1);
$form->addElement('radio','active','',get_lang('Inactive'),0);
// Set default values
$defaults['admin']['platform_admin'] = 0;
$defaults['mail']['send_mail'] = 1;
$defaults['password']['password_auto'] = 1;
$defaults['active'] = 1;
$defaults['expiration_date']=array();
$days = api_get_setting('account_valid_duration');
$time = strtotime('+'.$days.' day');
$defaults['expiration_date']['d']=date('d',$time);
$defaults['expiration_date']['F']=date('m',$time);
$defaults['expiration_date']['Y']=date('Y',$time);
$defaults['radio_expiration_date'] = 0;
$form->setDefaults($defaults);
// Submit button
$form->addElement('submit', 'submit', get_lang('Add'));
$form->addElement('submit', 'submit_plus', get_lang('Add').'+');
// Validate form
if( $form->validate())
// Display form
if(1)
{
$check = Security::check_token('post');
if($check)
$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
$tool_name = get_lang('UserFields');
Display :: display_header($tool_name, "");
//api_display_tool_title($tool_name);
if (isset ($_GET['action']))
{
$user = $form->exportValues();
$picture_element = & $form->getElement('picture');
$picture = $picture_element->getValue();
$picture_uri = '';
if (strlen($picture['name']) > 0)
$check = Security::check_token('get');
if($check)
{
if(!is_dir(api_get_path(SYS_CODE_PATH).'upload/users/')){
if(mkdir(api_get_path(SYS_CODE_PATH).'upload/users/'))
{
$perm = api_get_setting('permissions_for_new_directories');
$perm = octdec(!empty($perm)?$perm:'0770');
chmod(api_get_path(SYS_CODE_PATH).'upload/users/');
}
}
$picture_uri = uniqid('').'_'.replace_dangerous_char($picture['name']);
$picture_location = api_get_path(SYS_CODE_PATH).'upload/users/'.$picture_uri;
move_uploaded_file($picture['tmp_name'], $picture_location);
}
$lastname = $user['lastname'];
$firstname = $user['firstname'];
$official_code = $user['official_code'];
$email = $user['email'];
$phone = $user['phone'];
$username = $user['username'];
$status = intval($user['status']);
$picture = $_FILES['picture'];
$platform_admin = intval($user['admin']['platform_admin']);
$send_mail = intval($user['mail']['send_mail']);
if(count($extAuthSource) > 0 && $user['password']['password_auto'] == '2')
{
$auth_source = $user['password']['auth_source'];
$password = 'PLACEHOLDER';
}
else
{
$auth_source = PLATFORM_AUTH_SOURCE;
$password = $user['password']['password_auto'] == '1' ? api_generate_password() : $user['password']['password'];
}
if ($user['radio_expiration_date']=='1' )
{
$expiration_date=$user['expiration_date'];
}
else
{
$expiration_date='0000-00-00 00:00:00';
}
$active = intval($user['active']);
switch ($_GET['action'])
{
case 'show_message' :
Display :: display_normal_message($_GET['message']);
break;
case 'delete_user' :
if ($user_id != $_user['user_id'] && UserManager :: delete_user($_GET['user_id']))
{
Display :: display_normal_message(get_lang('UserDeleted'));
}
else
{
Display :: display_error_message(get_lang('CannotDeleteUser'));
}
break;
case 'lock' :
$message=lock_unlock_user('lock',$_GET['user_id']);
Display :: display_normal_message($message);
break;
case 'unlock';
$message=lock_unlock_user('unlock',$_GET['user_id']);
Display :: display_normal_message($message);
break;
$user_id = UserManager::create_user($firstname,$lastname,$status,$email,$username,$password,$official_code,api_get_setting('platformLanguage'),$phone,$picture_uri,$auth_source,$expiration_date,$active);
if ($platform_admin)
{
$sql = "INSERT INTO $table_admin SET user_id = '".$user_id."'";
api_sql_query($sql,__FILE__,__LINE__);
}
if (!empty ($email) && $send_mail)
{
$emailto = '"'.$firstname.' '.$lastname.'" <'.$email.'>';
$emailsubject = '['.get_setting('siteName').'] '.get_lang('YourReg').' '.get_setting('siteName');
$emailheaders = 'From: '.get_setting('administratorName').' '.get_setting('administratorSurname').' <'.get_setting('emailAdministrator').">\n";
$emailheaders .= 'Reply-To: '.get_setting('emailAdministrator');
$emailbody=get_lang('Dear')." ".stripslashes("$firstname $lastname").",\n\n".get_lang('YouAreReg')." ". get_setting('siteName') ." ".get_lang('Settings')." ". $username ."\n". get_lang('Pass')." : ".stripslashes($password)."\n\n" .get_lang('Address') ." ". get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\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');
@api_send_mail($emailto, $emailsubject, $emailbody, $emailheaders);
}
Security::clear_token();
if(isset($user['submit_plus']))
{
//we want to add more. Prepare report message and redirect to the same page (to clean the form)
header('Location: user_add.php?message='.urlencode(get_lang('UserAdded')));
exit ();
}
Security::clear_token();
}
else
}
if (isset ($_POST['action']))
{
$check = Security::check_token('get');
if($check)
{
header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('UserAdded')));
exit ();
switch ($_POST['action'])
{
default:
break;
}
Security::clear_token();
}
}
}else{
if(isset($_POST['submit'])){
Security::clear_token();
}
$token = Security::get_token();
$form->addElement('hidden','sec_token');
$form->setConstants(array('sec_token' => $token));
// Create an add-field box
$form = new FormValidator('add_field','post','','',null,false);
$renderer =& $form->defaultRenderer();
$renderer->setElementTemplate('<span>{element}</span> ');
//$form->addElement('text','label',get_lang('FieldLabel'));
//$form->addElement('text','type',get_lang('FieldType'));
//$form->addElement('text','title',get_lang('FieldTitle'));
//$form->addElement('text','default',get_lang('FieldDefaultValue'));
//$form->addElement('submit','submit',get_lang('Search'));
$form->addElement('static','search_advanced_link',null,'<a href="user_fields_add.php?action=fill">'.get_lang('AddUserField').'</a>');
$form->display();
// Create a sortable table with user-data
$parameters['sec_token'] = Security::get_token();
$table = new SortableTable('extra_fields', 'get_number_of_extra_fields', 'get_extra_fields',5);
$table->set_additional_parameters($parameters);
$table->set_header(0, '', false);
$table->set_header(1, get_lang('FieldLabel'));
$table->set_header(2, get_lang('FieldType'));
$table->set_header(3, get_lang('FieldTitle'));
$table->set_header(4, get_lang('FieldDefaultValue'));
$table->set_header(5, '', false);
$table->set_header(6, get_lang('FieldVisibility'));
$table->set_header(7, get_lang('FieldChangeability'));
$table->display();
}
*/
// Display form
Display::display_header($tool_name);
//api_display_tool_title($tool_name);
if(!empty($message)){
Display::display_normal_message($message);
}
//$form->display();
@ -255,4 +136,13 @@ if(!empty($message)){
==============================================================================
*/
Display::display_footer();
//gateway functions to the UserManager methods (provided for SorteableTable callback mechanism)
function get_number_of_extra_fields()
{
return UserManager::get_number_of_extra_fields();
}
function get_extra_fields($f,$n,$o,$d)
{
return UserManager::get_extra_fields($f,$n,$o,$d);
}
?>

@ -0,0 +1,121 @@
<?php // $Id: $
/*
==============================================================================
Dokeos - elearning and course management software
Copyright (c) 2008 Dokeos S.A.
For a full list of contributors, see "credits.txt".
The full license can be read in "license.txt".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
See the GNU General Public License for more details.
Contact: Dokeos, rue du Corbeau, 108, B-1000 Brussels, Belgium, info@dokeos.com
==============================================================================
*/
/**
==============================================================================
* @package dokeos.admin
==============================================================================
*/
// name of the language file that needs to be included
$language_file = array('admin','registration');
$cidReset = true;
// including necessary libraries
require ('../inc/global.inc.php');
$libpath = api_get_path(LIBRARY_PATH);
include_once ($libpath.'usermanager.lib.php');
require_once ($libpath.'formvalidator/FormValidator.class.php');
// section for the tabs
$this_section=SECTION_PLATFORM_ADMIN;
// user permissions
api_protect_admin_script();
// Database table definitions
$table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
$table_user = Database :: get_main_table(TABLE_MAIN_USER);
$table_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
$table_uf_opt = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
$table_uf_val = Database :: get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
$tool_name = get_lang('AddUserFields');
// Create the form
$form = new FormValidator('user_fields_add');
// Field variable name
$form->addElement('text','fieldlabel',get_lang('FieldLabel'));
$form->applyFilter('fieldlabel','html_filter');
$form->applyFilter('fieldlabel','trim');
$form->addRule('fieldlabel', get_lang('ThisFieldIsRequired'), 'required');
$form->addRule('fieldlabel', get_lang('OnlyLettersAndNumbersAllowed'), 'username');
$form->addRule('fieldlabel', '', 'maxlength',20);
$form->addRule('fieldlabel', get_lang('FieldTaken'), 'fieldlabel_available');
// Field type
$types = array();
$types[USER_FIELD_TYPE_TEXT] = get_lang('FieldTypeText');
//$types[USER_FIELD_TYPE_TEXTAREA] = get_lang('FieldTypeTextarea');
//$types[USER_FIELD_TYPE_RADIO] = get_lang('FieldTypeRadio');
//$types[USER_FIELD_TYPE_SELECT] = get_lang('FieldTypeSelect');
//$types[USER_FIELD_TYPE_SELECT_MULTIPLE] = get_lang('FieldTypeSelectMultiple');
$form->addElement('select','fieldtype',get_lang('FieldType'),$types);
$form->addRule('fieltype', get_lang('ThisFieldIsRequired'), 'required');
// Field display name
$form->addElement('text','fieldtitle',get_lang('FieldTitle'));
$form->applyFilter('fieldtitle','html_filter');
$form->applyFilter('fieldtitle','trim');
$form->addRule('fieldtitle', get_lang('ThisFieldIsRequired'), 'required');
// Field default value
$form->addElement('text','fielddefaultvalue',get_lang('FieldDefaultValue'));
// Set default values
$defaults = array();
$form->setDefaults($defaults);
// Submit button
$form->addElement('submit', 'submit', get_lang('Add'));
// Validate form
if( $form->validate())
{
$check = Security::check_token('post');
if($check)
{
$field = $form->exportValues();
$fieldlabel = $field['fieldlabel'];
$fieldtype = $field['fieldtype'];
$fieldtitle = $field['fieldtitle'];
$fielddefault = $field['fielddefaultvalue'];
$field_id = UserManager::create_extra_field($fieldlabel,$fieldtype,$fieldtitle,$fielddefault);
Security::clear_token();
header('Location: user_fields.php?action=show_message&message='.urlencode(get_lang('FieldAdded')));
exit ();
}
}else{
if(isset($_POST['submit'])){
Security::clear_token();
}
$token = Security::get_token();
$form->addElement('hidden','sec_token');
$form->setConstants(array('sec_token' => $token));
}
// Display form
Display::display_header($tool_name);
//api_display_tool_title($tool_name);
if(!empty($_GET['message'])){
Display::display_normal_message($_GET['message']);
}
$form->display();
/*
==============================================================================
FOOTER
==============================================================================
*/
Display::display_footer();
?>

@ -1,5 +1,5 @@
<?php
// $Id: profile.php 14667 2008-03-19 15:08:54Z juliomontoya $
// $Id: profile.php 14674 2008-03-20 12:24:34Z yannoo $
/*
==============================================================================
Dokeos - elearning and course management software
@ -271,6 +271,23 @@ if (is_profile_editable() && api_get_setting('profile', 'password') == 'true')
$form->addRule('password1', get_lang('PassTooEasy').': '.api_generate_password(), 'callback', 'api_check_password');
}
// EXTRA FIELDS
$extra = UserManager::get_extra_fields();
$ftypeco = array(); //make a correspondance array for the form types
foreach($extra as $id => $field_details)
{
if($field_details[6] == 0)
{
continue;
}
//todo add field type management (rather than just "text")
$form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 40));
if ($field_details[7] == 0)
$form->freeze('extra_'.$field_details[1]);
$form->applyFilter('extra_'.$field_details[1], 'stripslashes');
$form->applyFilter('extra_'.$field_details[1], 'trim');
}
// SUBMIT
if (is_profile_editable())
{
@ -284,6 +301,8 @@ else
/*
* Set initial values for all fields.
*/
$extra_data = UserManager::get_extra_user_data(api_get_user_id(),true);
$user_data = array_merge($user_data,$extra_data);
$form->setDefaults($user_data);
/*
@ -537,12 +556,20 @@ elseif ($form->validate())
{ //ensure there is at least a http:// scheme in the URI provided
$user_data['openid'] = 'http://'.$user_data['openid'];
}
$extras = array();
// build SQL query
$sql = "UPDATE $table_user SET";
foreach($user_data as $key => $value)
{
$sql .= " $key = '".addslashes($value)."',";
if(substr($key,0,6)=='extra_') //an extra field
{
$extras[substr($key,6)] = $value;
}
else
{
$sql .= " $key = '".addslashes($value)."',";
}
}
if (isset($password))
@ -562,9 +589,15 @@ elseif ($form->validate())
}
$sql .= " WHERE user_id = '".$_user['user_id']."'";
api_sql_query($sql, __FILE__, __LINE__);
//update the extra fields
foreach($extras as $key=>$value)
{
$myres = UserManager::update_extra_field_value($_user['user_id'],$key,$value);
}
// re-init the system to take new settings into account
$uidReset = true;
include (api_get_path(INCLUDE_PATH).'local.inc.php');

@ -1,4 +1,4 @@
<?php // $Id: database.lib.php 14543 2008-03-09 17:32:54Z yannoo $
<?php // $Id: database.lib.php 14674 2008-03-20 12:24:34Z yannoo $
/* See license terms in /dokeos_license.txt */
/**
==============================================================================
@ -43,11 +43,14 @@ define('TABLE_MAIN_SHARED_SURVEY_QUESTION', 'shared_survey_question');
define('TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION', 'shared_survey_question_option');
define('TABLE_MAIN_TEMPLATES', 'templates');
define('TABLE_MAIN_OPENID_ASSOCIATION','openid_association');
define('TABLE_MAIN_GRADEBOOK_CATEGORY', 'gradebook_category');
define('TABLE_MAIN_GRADEBOOK_EVALUATION', 'gradebook_evaluation');
define('TABLE_MAIN_GRADEBOOK_RESULT', 'gradebook_result');
define('TABLE_MAIN_GRADEBOOK_LINK', 'gradebook_link');
define('TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY', 'gradebook_score_display');
define('TABLE_MAIN_GRADEBOOK_CATEGORY', 'gradebook_category');
define('TABLE_MAIN_GRADEBOOK_EVALUATION', 'gradebook_evaluation');
define('TABLE_MAIN_GRADEBOOK_RESULT', 'gradebook_result');
define('TABLE_MAIN_GRADEBOOK_LINK', 'gradebook_link');
define('TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY','gradebook_score_display');
define('TABLE_MAIN_USER_FIELD', 'user_field');
define('TABLE_MAIN_USER_FIELD_OPTIONS', 'user_field_options');
define('TABLE_MAIN_USER_FIELD_VALUES', 'user_field_values');
//statistic database tables
define('TABLE_STATISTIC_TRACK_E_LASTACCESS', 'track_e_lastaccess');

@ -30,6 +30,13 @@
* @package dokeos.library
==============================================================================
*/
// define constants for user extra field types
define('USER_FIELD_TYPE_TEXT',1);
define('USER_FIELD_TYPE_TEXTAREA',2);
define('USER_FIELD_TYPE_RADIO',3);
define('USER_FIELD_TYPE_SELECT',4);
define('USER_FIELD_TYPE_SELECT_MULTIPLE',5);
class UserManager
{
/**
@ -37,27 +44,29 @@ class UserManager
* @author Hugues Peeters <peeters@ipm.ucl.ac.be>,
* Roan Embrechts <roan_embrechts@yahoo.com>
*
* @param string $firstName
* string $lastName
* int $status
* string $email
* string $loginName
* string $password
* string $official_code (optional)
* string $phone (optional)
* string $picture_uri (optional)
* string $auth_source (optional)
*
* @param string Firstname
* @param string Lastname
* @param int Status (1 for course tutor, 5 for student, 6 for anonymous)
* @param string e-mail address
* @param string Login
* @param string Password
* @param string Any official code (optional)
* @param int User language (optional)
* @param string Phone number (optional)
* @param string Picture URI (optional)
* @param string Authentication source (optional, defaults to 'platform', dependind on constant)
* @param string Account expiration date (optional, defaults to '0000-00-00 00:00:00')
* @param int Whether the account is enabled or disabled by default
* @param int The user ID of the person who registered this user (optional, defaults to null)
* @param int The department of HR in which the user is registered (optional, defaults to 0)
* @return int new user id - if the new user creation succeeds
* boolean false otherwise
*
* @desc The function tries to retrieve $_user['user_id'] from the global space.
* if it exists, $_user['user_id'] is the creator id If a problem arises,
* it stores the error message in global $api_failureList
*
* @todo Add the user language to the parameters
*/
function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language='', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expiration_date = '0000-00-00 00:00:00', $active = 1, $hr_dept_id=0)
function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language='', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expiration_date = '0000-00-00 00:00:00', $active = 1, $hr_dept_id=0, $extra=null)
{
global $_user, $userPasswordCrypted;
@ -100,17 +109,27 @@ class UserManager
expiration_date = '".Database::escape_string($expiration_date)."',
hr_dept_id = '".Database::escape_string($hr_dept_id)."',
active = '".Database::escape_string($active)."'";
error_log($sql);
$result = api_sql_query($sql);
if ($result)
{
//echo "id returned";
return Database::get_last_insert_id();
$return=Database::get_last_insert_id();
}
else
{
//echo "false - failed" ;
return false;
$return=false;
}
if(is_array($extra) AND count($extra)>0)
{
$res = true;
foreach($extra as $fname => $fvalue)
{
$res = $res && UserManager::update_extra_field($return,$fname,$fvalue);
}
}
return $return;
}
/**
@ -212,6 +231,11 @@ class UserManager
$gradebook_results_table = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
$sql = 'DELETE FROM '.$gradebook_results_table.' WHERE user_id = '.$user_id;
api_sql_query($sql, __FILE__, __LINE__);
$user = Database::fetch_array($res);
$t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
$sqlv = "DELETE FROM $t_ufv WHERE user_id = $user_id";
$resv = api_sql_query($sqlv,__FILE__,__LINE__);
return true;
}
@ -243,10 +267,12 @@ class UserManager
* @param string $official_code
* @param string $phone
* @param string $picture_uri
* @param int $creator_id
* @param int The user ID of the person who registered this user (optional, defaults to null)
* @param int The department of HR in which the user is registered (optional, defaults to 0)
* @param array A series of additional fields to add to this user as extra fields (optional, defaults to null)
* @return boolean true if the user information was updated
*/
function update_user($user_id, $firstname, $lastname, $username, $password = null, $auth_source = null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active, $creator_id= null, $hr_dept_id=0)
function update_user($user_id, $firstname, $lastname, $username, $password = null, $auth_source = null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active, $creator_id= null, $hr_dept_id=0, $extra=null)
{
global $userPasswordCrypted;
$table_user = Database :: get_main_table(TABLE_MAIN_USER);
@ -277,7 +303,17 @@ class UserManager
$sql .= ", creator_id='".Database::escape_string($creator_id)."'";
}
$sql .= " WHERE user_id='$user_id'";
return api_sql_query($sql,__FILE__,__LINE__);
$return = api_sql_query($sql,__FILE__,__LINE__);
if(is_array($extra) and count($extra)>0)
{
$res = true;
foreach($extra as $fname => $fvalue)
{
$res = $res && UserManager::update_extra_field($user_id,$fname,$fvalue);
}
}
return $return;
}
/**
@ -327,7 +363,7 @@ class UserManager
/**
* Get user information
* @param string $username The username
* @param string The username
* @return array All user information as an associative array
*/
function get_user_info($username)
@ -348,10 +384,11 @@ class UserManager
/**
* Get user information
* @param string $id The id
* @return array All user information as an associative array
* @param string The id
* @param boolean Whether to return the user's extra fields (defaults to false)
* @return array All user information as an associative array
*/
function get_user_info_by_id($user_id)
function get_user_info_by_id($user_id,$user_fields=false)
{
$user_id = intval($user_id);
$user_table = Database :: get_main_table(TABLE_MAIN_USER);
@ -360,6 +397,29 @@ class UserManager
if(Database::num_rows($res)>0)
{
$user = Database::fetch_array($res);
$t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
$t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
$sqlf = "SELECT * FROM $t_uf ORDER BY field_order";
$resf = api_sql_query($sqlf,__FILE__,__LINE__);
if(Database::num_rows($resf)>0)
{
while($rowf = Database::fetch_array($resf))
{
$sqlv = "SELECT * FROM $t_ufv WHERE field_id = ".$rowf['id']." AND user_id = ".$user['user_id']." ORDER BY id DESC";
$resv = api_sql_query($sqlv,__FILE__,__LINE__);
if(Database::num_rows($resv)>0)
{
//There should be only one value for a field and a user
$rowv = Database::fetch_array($resv);
$user['extra'][$rowf['field_variable']] = $rowv['field_value'];
}
else
{
$user['extra'][$rowf['field_variable']] = '';
}
}
}
}
else
{
@ -620,5 +680,281 @@ class UserManager
$production_path = UserManager::get_user_picture_path_by_id($user_id,'system',true);
unlink($production_path['dir'].$user_id.'/'.$production);
}
/**
* Update an extra field
* @param integer Field ID
* @param array Database columns and their new value
* @return boolean true if field updated, false otherwise
*/
function update_extra_field($fid,$columns)
{
//TODO check that values added are values proposed for enumerated field types
$t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
$fid = Database::escape_string($fid);
$sqluf = "UPDATE $t_uf SET ";
$known_fields = array('id','field_variable','field_type','field_display_text','field_default_value','field_order','field_visible','field_changeable');
$safecolumns = array();
foreach($columns as $index => $newval)
{
if(in_array($index,$known_fields))
{
$safecolumns[$index] = Database::escape_string($newval);
$sqluf .= $index." = '".$safecolumns[$index]."', ";
}
}
$time = time();
$sqluf .= " tms = FROM_UNIXTIME($time) WHERE id='$fid'";
$resuf = api_sql_query($sqluf,__FILE__,__LINE__);
return $resuf;
}
/**
* Update an extra field value for a given user
* @param integer User ID
* @param string Field variable name
* @param string Field value
* @return boolean true if field updated, false otherwise
*/
function update_extra_field_value($user_id,$fname,$fvalue='')
{
//TODO check that values added are values proposed for enumerated field types
$t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
$t_ufo = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
$t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
$fname = Database::escape_string($fname);
$fvalue = Database::escape_string($fvalue);
$sqluf = "SELECT * FROM $t_uf WHERE field_variable='$fname'";
$resuf = api_sql_query($sqluf,__FILE__,__LINE__);
if(Database::num_rows($resuf)==1)
{ //ok, the field exists
// Check if enumerated field, if the option is available
$rowuf = Database::fetch_array($resuf);
switch($rowuf['field_type'])
{
case 3:
case 4:
case 5:
$sqluo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowuf['id'];
$resuo = api_sql_query($sqluo,__FILE__,__LINE__);
if(Database::num_rows($resuo)>0)
{
$check = false;
while($rowuo = Database::fetch_array($resuo))
{
if($rowuo['field_value'] == $fvalue)
{
$check = true;
break;
}
}
if($check == false)
{
return false; //option value not found
}
}
else
{
return false; //enumerated type but no option found
}
break;
case 1:
case 2:
default:
break;
}
$tms = time();
$sqlufv = "SELECT * FROM $t_ufv WHERE user_id = $user_id AND field_id = ".$rowuf['id']." ORDER BY id";
$resufv = api_sql_query($sqlufv,__FILE__,__LINE__);
$n = Database::num_rows($resufv);
if($n>1)
{
//problem, we already have to values for this field and user combination - keep last one
while($rowufv = Database::fetch_array($resufv))
{
if($n > 1)
{
$sqld = "DELETE FROM $t_ufv WHERE id = ".$rowufv['id'];
$resd = api_sql_query($sqld,__FILE__,__LINE__);
$n--;
}
$rowufv = Database::fetch_array($resufv);
$sqlu = "UPDATE $t_ufv SET field_value = '$fvalue', tms = $tms WHERE id = ".$rowufv['id'];
$resu = api_sql_query($sqlu,__FILE__,__LINE__);
return($resu?true:false);
}
}
elseif($n==1)
{
//we need to update the current record
$rowufv = Database::fetch_array($resufv);
$sqlu = "UPDATE $t_ufv SET field_value = '$fvalue', tms = $tms WHERE id = ".$rowufv['id'];
error_log('UM::update_extra_field_value: '.$sqlu);
$resu = api_sql_query($sqlu,__FILE__,__LINE__);
return($resu?true:false);
}
else
{
$sqli = "INSERT INTO $t_ufv (user_id,field_id,field_value,tms) " .
"VALUES ($user_id,".$rowuf['id'].",'$fvalue',$tms)";
error_log('UM::update_extra_field_value: '.$sqli);
$resi = api_sql_query($sqli,__FILE__,__LINE__);
return($resi?true:false);
}
}
else
{
return false; //field not found
}
}
/**
* Get an array of extra fieds with field details (type, default value and options)
* @param integer Offset (from which row)
* @param integer Number of items
* @param integer
* @return array Extra fields details (e.g. $list[2]['type'], $list[4]['options'][2]['title']
*/
function get_extra_fields($from=0, $number_of_items=20, $column=5, $direction='ASC')
{
$fields = array();
$t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
$t_ufo = Database :: get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
$columns = array('id','field_variable','field_type','field_display_text','field_default_value','field_order','tms');
$sort_direction = '';
if(in_array(strtoupper($direction),array('ASC','DESC')))
{
$sort_direction = strtoupper($direction);
}
$sqlf = "SELECT * FROM $t_uf ORDER BY ".$columns[$column]." $sort_direction LIMIT ".Database::escape_string($from).','.Database::escape_string($number_of_items);
$resf = api_sql_query($sqlf,__FILE__,__LINE__);
if(Database::num_rows($resf)>0)
{
while($rowf = Database::fetch_array($resf))
{
$fields[$rowf['id']] = array(
0=>$rowf['id'],
1=>$rowf['field_variable'],
2=>$rowf['field_type'],
3=>(empty($rowf['field_display_text'])?'':get_lang($rowf['field_display_text'])),
4=>$rowf['field_default_value'],
5=>$rowf['field_order'],
6=>$rowf['field_visible'],
7=>$rowf['field_changeable'],
8=>array()
);
$sqlo = "SELECT * FROM $t_ufo WHERE field_id = ".$rowf['id'];
$reso = api_sql_query($sqlo,__FILE__,__LINE__);
if(Database::num_rows($reso)>0)
{
while($rowo = Database::fetch_array($reso))
{
$fields[$rowf['id']][8][$rowo['id']] = array(
0=>$rowo['id'],
1=>$rowo['option_value'],
2=>$rowo['option_display_text'],
3=>$rowo['option_order']
);
}
}
}
}
return $fields;
}
/**
* Get the number of extra fields currently recorded
* @return integer Number of fields
*/
function get_number_of_extra_fields()
{
$t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
$sqlf = "SELECT * FROM $t_uf ORDER BY field_order";
$resf = api_sql_query($sqlf,__FILE__,__LINE__);
return Database::num_rows($resf);
}
/**
* Creates a new extra field
* @param string Field's internal variable name
* @param int Field's type
* @param string Field's language var name
* @param string Field's default value
* @return int new user id - if the new user creation succeeds, false otherwise
*/
function create_extra_field($fieldvarname, $fieldtype, $fieldtitle, $fielddefault)
{
// database table definition
$table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
// First check wether the login already exists
if (! UserManager::is_extra_field_available($fieldvarname))
return api_set_failure('login-pass already taken');
$sql = "SELECT MAX(field_order) FROM $table_field";
$res = api_sql_query($sql,__FILE__,__LINE__);
$order = 0;
if(Database::num_rows($res)>0)
{
$row = Database::fetch_array($res);
$order = $row[0]+1;
}
$time = time();
$sql = "INSERT INTO $table_field
SET field_type = '".Database::escape_string($fieldtype)."',
field_variable = '".Database::escape_string($fieldvarname)."',
field_display_text = '".Database::escape_string($fieldtitle)."',
field_default_value = '".Database::escape_string($fielddefault)."',
field_order = '$order',
tms = FROM_UNIXTIME($time)";
$result = api_sql_query($sql);
if ($result)
{
//echo "id returned";
$return=Database::get_last_insert_id();
}
else
{
//echo "false - failed" ;
$return=false;
}
return $return;
}
/**
* Check if a field is available
* @param string the wanted username
* @return boolean true if the wanted username is available
*/
function is_extra_field_available($fieldname)
{
$t_uf = Database :: get_main_table(TABLE_MAIN_USER_FIELD);
$sql = "SELECT * FROM $t_uf WHERE field_variable = '".Database::escape_string($fieldname)."'";
$res = api_sql_query($sql,__FILE__,__LINE__);
return Database::num_rows($res) <= 0;
}
/**
* Gets user extra fields data
* @param integer User ID
* @param boolean Whether to prefix the fields indexes with "extra_" (might be used by formvalidator)
* @return array Array of fields => value for the given user
*/
function get_extra_user_data($user_id, $prefix=false)
{
$extra_data = array();
$t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
$t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
$user_id = Database::escape_string($user_id);
$sql = "SELECT f.id as fid, f.field_variable as fvar, fv.field_value as fval FROM $t_uf f, $t_ufv fv WHERE fv.user_id = $user_id AND fv.field_id = f.id ORDER BY f.field_order";
$res = api_sql_query($sql,__FILE__,__LINE__);
if(Database::num_rows($res)>0)
{
while($row = Database::fetch_array($res))
{
if($prefix)
{
$extra_data['extra_'.$row['fvar']] = $row['fval'];
}
else
{
$extra_data[$row['fvar']] = $row['fval'];
}
}
}
return $extra_data;
}
}
?>

@ -895,3 +895,32 @@ CREATE TABLE gradebook_score_display (
display varchar(40) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE user_field (
id INT NOT NULL auto_increment,
field_type int NOT NULL DEFAULT 1,
field_variable varchar(64) NOT NULL,
field_display_text varchar(64),
field_default_value text,
field_order int,
field_visible tinyint default 0,
field_changeable tinyint default 0,
tms TIMESTAMP,
PRIMARY KEY(id)
);
CREATE TABLE user_field_options (
id int NOT NULL auto_increment,
field_id int NOT NULL,
option_value text,
option_display_text varchar(64),
option_order int,
tms TIMESTAMP,
PRIMARY KEY (id)
);
CREATE TABLE user_field_values(
id int NOT NULL auto_increment,
user_id int NOT NULL,
field_id int NOT NULL,
field_value text,
tms TIMESTAMP,
PRIMARY KEY(id)
);

@ -66,6 +66,9 @@ DELETE FROM settings_current WHERE variable='service_visio' AND subkey='visio_is
INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext) VALUES ('allow_course_theme',NULL,'radio','Course','true','AllowCourseThemeTitle','AllowCourseThemeComment',NULL,NULL);
INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_course_theme', 'true', 'Yes');
INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_course_theme', 'false', 'No');
CREATE TABLE user_field (id INT NOT NULL auto_increment,field_type int NOT NULL DEFAULT 1,field_variable varchar(64) NOT NULL,field_display_text varchar(64),field_default_value text,field_order int,field_visible tinyint default 0,field_changeable tinyint default 0,tms TIMESTAMP,PRIMARY KEY(id));
CREATE TABLE user_field_options (id int NOT NULL auto_increment,field_id int NOT NULL,option_value text,option_display_text varchar(64),option_order int,tms TIMESTAMP,PRIMARY KEY (id));
CREATE TABLE user_field_values(id int NOT NULL auto_increment,user_id int NOT NULL,field_id int NOT NULL,field_value text,tms TIMESTAMP,PRIMARY KEY(id));
-- xxSTATSxx
ALTER TABLE track_e_downloads ADD INDEX (down_user_id);

Loading…
Cancel
Save