diff --git a/main/admin/index.php b/main/admin/index.php index 034e764886..e4a88af2ef 100644 --- a/main/admin/index.php +++ b/main/admin/index.php @@ -1,4 +1,4 @@ -
  • +
  • diff --git a/main/admin/user_add.php b/main/admin/user_add.php index fb7f2e39a9..04d741f2ac 100644 --- a/main/admin/user_add.php +++ b/main/admin/user_add.php @@ -1,9 +1,9 @@ -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 (); } } diff --git a/main/admin/user_fields.php b/main/admin/user_fields.php index 58a9e11998..eab87e0075 100644 --- a/main/admin/user_fields.php +++ b/main/admin/user_fields.php @@ -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','','','
    '); -} -$group[] =& HTML_QuickForm::createElement('radio','password_auto',get_lang('Password'),get_lang('AutoGeneratePassword').'
    ',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'), ' '); -// 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'), ' '); -// 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('{element} '); + //$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,''.get_lang('AddUserField').''); + $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); +} ?> \ No newline at end of file diff --git a/main/admin/user_fields_add.php b/main/admin/user_fields_add.php new file mode 100644 index 0000000000..8301c9024d --- /dev/null +++ b/main/admin/user_fields_add.php @@ -0,0 +1,121 @@ + '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(); +?> \ No newline at end of file diff --git a/main/auth/profile.php b/main/auth/profile.php index c3065302bb..a37b845509 100644 --- a/main/auth/profile.php +++ b/main/auth/profile.php @@ -1,5 +1,5 @@ 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'); diff --git a/main/inc/lib/database.lib.php b/main/inc/lib/database.lib.php index c480b1a69e..0f166941cd 100644 --- a/main/inc/lib/database.lib.php +++ b/main/inc/lib/database.lib.php @@ -1,4 +1,4 @@ -, * Roan Embrechts * - * @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; + } } ?> \ No newline at end of file diff --git a/main/install/dokeos_main.sql b/main/install/dokeos_main.sql index 1ab42aeb0d..1af00aad34 100644 --- a/main/install/dokeos_main.sql +++ b/main/install/dokeos_main.sql @@ -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) +); \ No newline at end of file diff --git a/main/install/migrate-db-1.8.4-1.8.5-pre.sql b/main/install/migrate-db-1.8.4-1.8.5-pre.sql index d0c52f9a37..007b568881 100644 --- a/main/install/migrate-db-1.8.4-1.8.5-pre.sql +++ b/main/install/migrate-db-1.8.4-1.8.5-pre.sql @@ -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);