Example #1
0
/**
 * Route teachers to their category if none is specified
 * Files fixed : 
 * course/index.php
 * 
 * @return bool Request has been marked for rerouting
 */
function ent_installer_route_teacher_category()
{
    global $CFG, $DB, $USER;
    // Exit if a category is already requested
    $categoryid = optional_param('categoryid', 0, PARAM_INT);
    if ($categoryid) {
        return false;
    }
    require_once $CFG->dirroot . '/user/profile/lib.php';
    $myuser = $DB->get_record('user', array('id' => $USER->id));
    profile_load_data($myuser);
    // Exit if current user is not a teacher
    if (!isset($myuser->profile_field_enseignant) || !$myuser->profile_field_enseignant) {
        return false;
    }
    $institutionid = get_config('local_ent_installer', 'institution_id');
    $teachercatidnum = $institutionid . '$' . $myuser->idnumber . '$CAT';
    $existingcategory = $DB->get_record('course_categories', array('idnumber' => $teachercatidnum));
    // Exit if category cannot be found
    if (!$existingcategory) {
        return false;
    }
    //Let Moodle core course index trust that this category is requested
    $_GET['categoryid'] = $existingcategory->id;
    return true;
}
Example #2
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/user/profile/lib.php';
     require_once $CFG->libdir . '/csvlib.class.php';
     $username = $this->arguments[0];
     $filename = $this->expandedOptions['name'];
     $user = get_user_by_name($username);
     if (!$user) {
         cli_error("User not found.");
     } else {
         $userid = $user->id;
     }
     $fields = array('id' => 'id', 'username' => 'username', 'email' => 'email', 'firstname' => 'firstname', 'lastname' => 'lastname', 'idnumber' => 'idnumber', 'institution' => 'institution', 'department' => 'department', 'phone1' => 'phone1', 'phone2' => 'phone2', 'city' => 'city', 'url' => 'url', 'icq' => 'icq', 'skype' => 'skype', 'aim' => 'aim', 'yahoo' => 'yahoo', 'msn' => 'msn', 'country' => 'country');
     if ($extrafields = $DB->get_records('user_info_field')) {
         foreach ($extrafields as $n => $v) {
             $fields['profile_field_' . $v->shortname] = 'profile_field_' . $v->shortname;
         }
     }
     $csvexport = new \csv_export_writer();
     $csvexport->set_filename($filename);
     $csvexport->add_data($fields);
     $row = array();
     profile_load_data($user);
     $userprofiledata = array();
     foreach ($fields as $field => $unused) {
         if (is_array($user->{$field})) {
             $userprofiledata[] = reset($user->{$field});
         } else {
             $userprofiledata[] = $user->{$field};
         }
     }
     $csvexport->add_data($userprofiledata);
     file_put_contents($filename, $csvexport->print_csv_data(true));
     echo "User " . $user->username . " successfully downloaded\n";
 }
function update_profile_fields($user, $data)
{
    profile_load_data($user);
    $user->profile_field_state = $data->state;
    $user->profile_field_companyName = $data->companyName;
    $user->profile_field_website = $data->website;
    $user->profile_field_zone = $data->zone;
    //echo "<br/>-".$data->zone."-";
    profile_save_data($user);
}
function user_download_csv($userids, $fields, $includecompanyfield)
{
    global $CFG, $SESSION, $DB;
    require_once $CFG->dirroot . '/user/profile/lib.php';
    $filename = clean_filename(get_string('users') . '.csv');
    header("Content-Type: application/download\n");
    header("Content-Disposition: attachment; filename={$filename}");
    header("Expires: 0");
    header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
    header("Pragma: public");
    $delimiter = get_string('listsep', 'langconfig');
    $encdelim = '&#' . ord($delimiter);
    $row = array();
    foreach ($fields as $fieldname) {
        if ($includecompanyfield || $fieldname != "profile_field_company") {
            $row[] = str_replace($delimiter, $encdelim, $fieldname);
        }
    }
    $row[] = "temppassword";
    echo implode($delimiter, $row) . "\n";
    foreach ($userids as $userid) {
        // Stop the script from timing out on large numbers of users.
        set_time_limit(30);
        $row = array();
        if (!($user = $DB->get_record('user', array('id' => $userid)))) {
            continue;
        }
        profile_load_data($user);
        foreach ($fields as $field => $unused) {
            // Stop the script from timing out on large numbers of users.
            set_time_limit(30);
            if ($includecompanyfield || $field != "profile_field_company") {
                $row[] = str_replace($delimiter, $encdelim, $user->{$field});
            }
        }
        $row[] = str_replace($delimiter, $encdelim, company_user::get_temporary_password($user));
        echo implode($delimiter, $row) . "\n";
    }
    die;
}
 function definition()
 {
     global $USER, $CFG, $DB;
     $mform = $this->_form;
     $course = $this->_customdata['course'];
     // this contains the data of this form
     $category = $this->_customdata['category'];
     $editoroptions = $this->_customdata['editoroptions'];
     $returnto = $this->_customdata['returnto'];
     $systemcontext = get_context_instance(CONTEXT_SYSTEM);
     $categorycontext = get_context_instance(CONTEXT_COURSECAT, $category->id);
     if (!empty($course->id)) {
         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
         $context = $coursecontext;
     } else {
         $coursecontext = null;
         $context = $categorycontext;
     }
     $courseconfig = get_config('moodlecourse');
     $this->course = $course;
     $this->context = $context;
     /// form definition with new course defaults
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     $mform->addElement('hidden', 'returnto', null);
     $mform->setType('returnto', PARAM_ALPHANUM);
     $mform->setConstant('returnto', $returnto);
     // verify permissions to change course category or keep current
     if (empty($course->id)) {
         if (has_capability('moodle/course:create', $categorycontext)) {
             $displaylist = array();
             $parentlist = array();
             make_categories_list($displaylist, $parentlist, 'moodle/course:create');
             $mform->addElement('select', 'category', get_string('category'), $displaylist);
             $mform->addHelpButton('category', 'category');
             $mform->setDefault('category', $category->id);
         } else {
             $mform->addElement('hidden', 'category', null);
             $mform->setType('category', PARAM_INT);
             $mform->setConstant('category', $category->id);
         }
     } else {
         if (has_capability('moodle/course:changecategory', $coursecontext)) {
             $displaylist = array();
             $parentlist = array();
             make_categories_list($displaylist, $parentlist, 'moodle/course:create');
             if (!isset($displaylist[$course->category])) {
                 //always keep current
                 $displaylist[$course->category] = format_string($DB->get_field('course_categories', 'name', array('id' => $course->category)));
             }
             $mform->addElement('select', 'category', get_string('category'), $displaylist);
             $mform->addHelpButton('category', 'category');
         } else {
             //keep current
             $mform->addElement('hidden', 'category', null);
             $mform->setType('category', PARAM_INT);
             $mform->setConstant('category', $course->category);
         }
     }
     $mform->addElement('text', 'fullname', get_string('fullnamecourse'), 'maxlength="254" size="50"');
     $mform->addHelpButton('fullname', 'fullnamecourse');
     $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
     $mform->setType('fullname', PARAM_MULTILANG);
     if (!empty($course->id) and !has_capability('moodle/course:changefullname', $coursecontext)) {
         $mform->hardFreeze('fullname');
         $mform->setConstant('fullname', $course->fullname);
     }
     $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
     $mform->addHelpButton('shortname', 'shortnamecourse');
     $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
     $mform->setType('shortname', PARAM_MULTILANG);
     if (!empty($course->id) and !has_capability('moodle/course:changeshortname', $coursecontext)) {
         $mform->hardFreeze('shortname');
         $mform->setConstant('shortname', $course->shortname);
     }
     $mform->addElement('text', 'idnumber', get_string('idnumbercourse'), 'maxlength="100"  size="10"');
     $mform->addHelpButton('idnumber', 'idnumbercourse');
     $mform->setType('idnumber', PARAM_RAW);
     if (!empty($course->id) and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
         $mform->hardFreeze('idnumber');
         $mform->setConstants('idnumber', $course->idnumber);
     }
     $mform->addElement('editor', 'summary_editor', get_string('coursesummary'), null, $editoroptions);
     $mform->addHelpButton('summary_editor', 'coursesummary');
     $mform->setType('summary_editor', PARAM_RAW);
     if (!empty($course->id) and !has_capability('moodle/course:changesummary', $coursecontext)) {
         $mform->hardFreeze('summary_editor');
     }
     $courseformats = get_plugin_list('format');
     $formcourseformats = array();
     foreach ($courseformats as $courseformat => $formatdir) {
         $formcourseformats[$courseformat] = get_string('pluginname', "format_{$courseformat}");
     }
     $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
     $mform->addHelpButton('format', 'format');
     $mform->setDefault('format', $courseconfig->format);
     $mform->addElement('select', 'coursedisplay', get_string('coursedisplay'), array(COURSE_DISPLAY_SINGLEPAGE => get_string('coursedisplay_single'), COURSE_DISPLAY_MULTIPAGE => get_string('coursedisplay_multi')));
     $mform->addHelpButton('coursedisplay', 'coursedisplay');
     $mform->setDefault('coursedisplay', COURSE_DISPLAY_SINGLEPAGE);
     for ($i = 0; $i <= $courseconfig->maxsections; $i++) {
         $sectionmenu[$i] = "{$i}";
     }
     $mform->addElement('select', 'numsections', get_string('numberweeks'), $sectionmenu);
     $mform->setDefault('numsections', $courseconfig->numsections);
     $mform->addElement('date_selector', 'startdate', get_string('startdate'));
     $mform->addHelpButton('startdate', 'startdate');
     $mform->setDefault('startdate', time() + 3600 * 24);
     $choices = array();
     $choices['0'] = get_string('hiddensectionscollapsed');
     $choices['1'] = get_string('hiddensectionsinvisible');
     $mform->addElement('select', 'hiddensections', get_string('hiddensections'), $choices);
     $mform->addHelpButton('hiddensections', 'hiddensections');
     $mform->setDefault('hiddensections', $courseconfig->hiddensections);
     $options = range(0, 10);
     $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
     $mform->addHelpButton('newsitems', 'newsitemsnumber');
     $mform->setDefault('newsitems', $courseconfig->newsitems);
     $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
     $mform->addHelpButton('showgrades', 'showgrades');
     $mform->setDefault('showgrades', $courseconfig->showgrades);
     $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
     $mform->addHelpButton('showreports', 'showreports');
     $mform->setDefault('showreports', $courseconfig->showreports);
     $choices = get_max_upload_sizes($CFG->maxbytes);
     $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
     $mform->addHelpButton('maxbytes', 'maximumupload');
     $mform->setDefault('maxbytes', $courseconfig->maxbytes);
     if (!empty($course->legacyfiles) or !empty($CFG->legacyfilesinnewcourses)) {
         if (empty($course->legacyfiles)) {
             //0 or missing means no legacy files ever used in this course - new course or nobody turned on legacy files yet
             $choices = array('0' => get_string('no'), '2' => get_string('yes'));
         } else {
             $choices = array('1' => get_string('no'), '2' => get_string('yes'));
         }
         $mform->addElement('select', 'legacyfiles', get_string('courselegacyfiles'), $choices);
         $mform->addHelpButton('legacyfiles', 'courselegacyfiles');
         if (!isset($courseconfig->legacyfiles)) {
             // in case this was not initialised properly due to switching of $CFG->legacyfilesinnewcourses
             $courseconfig->legacyfiles = 0;
         }
         $mform->setDefault('legacyfiles', $courseconfig->legacyfiles);
     }
     if (!empty($CFG->allowcoursethemes)) {
         $themeobjects = get_list_of_themes();
         $themes = array();
         $themes[''] = get_string('forceno');
         foreach ($themeobjects as $key => $theme) {
             if (empty($theme->hidefromselector)) {
                 $themes[$key] = get_string('pluginname', 'theme_' . $theme->name);
             }
         }
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     //--------------------------------------------------------------------------------
     enrol_course_edit_form($mform, $course, $context);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('groups', 'group'));
     $choices = array();
     $choices[NOGROUPS] = get_string('groupsnone', 'group');
     $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
     $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
     $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $choices);
     $mform->addHelpButton('groupmode', 'groupmode', 'group');
     $mform->setDefault('groupmode', $courseconfig->groupmode);
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'groupmodeforce', get_string('groupmodeforce', 'group'), $choices);
     $mform->addHelpButton('groupmodeforce', 'groupmodeforce', 'group');
     $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);
     //default groupings selector
     $options = array();
     $options[0] = get_string('none');
     $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('availability'));
     $choices = array();
     $choices['0'] = get_string('courseavailablenot');
     $choices['1'] = get_string('courseavailable');
     $mform->addElement('select', 'visible', get_string('availability'), $choices);
     $mform->addHelpButton('visible', 'availability');
     $mform->setDefault('visible', $courseconfig->visible);
     if (!has_capability('moodle/course:visibility', $context)) {
         $mform->hardFreeze('visible');
         if (!empty($course->id)) {
             $mform->setConstant('visible', $course->visible);
         } else {
             $mform->setConstant('visible', $category->visible);
         }
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('language'));
     $languages = array();
     $languages[''] = get_string('forceno');
     $languages += get_string_manager()->get_list_of_translations();
     $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
     $mform->setDefault('lang', $courseconfig->lang);
     //--------------------------------------------------------------------------------
     if (completion_info::is_enabled_for_site()) {
         $mform->addElement('header', '', get_string('progress', 'completion'));
         $mform->addElement('select', 'enablecompletion', get_string('completion', 'completion'), array(0 => get_string('completiondisabled', 'completion'), 1 => get_string('completionenabled', 'completion')));
         $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);
         $mform->addElement('checkbox', 'completionstartonenrol', get_string('completionstartonenrol', 'completion'));
         $mform->setDefault('completionstartonenrol', $courseconfig->completionstartonenrol);
         $mform->disabledIf('completionstartonenrol', 'enablecompletion', 'eq', 0);
     } else {
         $mform->addElement('hidden', 'enablecompletion');
         $mform->setType('enablecompletion', PARAM_INT);
         $mform->setDefault('enablecompletion', 0);
         $mform->addElement('hidden', 'completionstartonenrol');
         $mform->setType('completionstartonenrol', PARAM_INT);
         $mform->setDefault('completionstartonenrol', 0);
     }
     /// customizable role names in this course
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'rolerenaming', get_string('rolerenaming'));
     $mform->addHelpButton('rolerenaming', 'rolerenaming');
     if ($roles = get_all_roles()) {
         if ($coursecontext) {
             $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS_RAW);
         }
         $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE);
         foreach ($roles as $role) {
             $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->name));
             if (isset($role->localname)) {
                 $mform->setDefault('role_' . $role->id, $role->localname);
             }
             $mform->setType('role_' . $role->id, PARAM_TEXT);
             if (!in_array($role->id, $assignableroles)) {
                 $mform->setAdvanced('role_' . $role->id);
             }
         }
     }
     // customisable profile fields
     //--------------------------------------------------------------------------------
     profile_definition($mform);
     //--------------------------------------------------------------------------------
     $this->add_action_buttons();
     //--------------------------------------------------------------------------------
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
     /// finally set the current form data
     //--------------------------------------------------------------------------------
     profile_load_data($course);
     $this->set_data($course);
 }
 /**
  * Assemble the user data.
  *
  * This returns the final data to be passed to update_user().
  *
  * @param array $finaldata current data.
  * @param bool $usedefaults are defaults allowed?
  * @param array $existingdata existing category data.
  * @param bool $missingonly ignore fields which are already set.
  * @return array
  */
 protected function get_final_update_data($data, $existingdata, $usedefaults = false, $missingonly = false)
 {
     global $DB, $UUC_STD_FIELDS, $UUC_PRF_FIELDS, $UUC_DEFAULTS;
     $doupdate = false;
     $existingdata->timemodified = time();
     profile_load_data($existingdata);
     // Changing auth information.
     if (isset($existingdata->auth) && isset($data->auth)) {
         $existingdata->auth = $data->auth;
         if ($data->auth === 'nologin') {
             $this->dologout = true;
         }
     }
     $allfields = array_merge($UUC_STD_FIELDS, $UUC_PRF_FIELDS);
     foreach ($allfields as $field) {
         // These fields are being processed separatedly.
         if ($field === 'password' || $field === 'auth' || $field === 'suspended' || $field === 'oldusername') {
             continue;
         }
         // Field not present in the CSV file.
         if (!isset($data->{$field}) && !isset($existingdata->{$field})) {
             if ($this->updatemode === tool_uploadusercli_processor::UPDATE_ALL_WITH_DATA_OR_DEFAULTS && !empty($UUC_DEFAULTS[$field])) {
                 $data->{$field} = $UUC_DEFAULTS[$field];
             } else {
                 continue;
             }
         }
         if ($missingonly) {
             if ($existingdata->{$field}) {
                 continue;
             }
         } else {
             if ($this->updatemode === tool_uploadusercli_processor::UPDATE_ALL_WITH_DATA_OR_DEFAULTS) {
                 // Override everything.
             } else {
                 if ($this->updatemode === tool_uploadusercli_processor::UPDATE_ALL_WITH_DATA_ONLY) {
                     if (!empty($UUC_DEFAULTS[$field])) {
                         // Do not override with form defaults.
                         continue;
                     }
                 }
             }
         }
         if (!isset($data->{$field}) || $existingdata->{$field} !== $data->{$field}) {
             if ($field === 'email') {
                 if ($DB->record_exists('user', array('email' => $data->email))) {
                     if ($this->importoptions['noemailduplicates']) {
                         $this->error('useremailduplicate', new lang_string('useremailduplicate', 'error'));
                         return false;
                     } else {
                         $this->set_status('useremailduplicate', new lang_string('useremailduplicate', 'error'));
                     }
                 }
                 if (!validate_email($data->email)) {
                     $this->set_status('invalidemail', new lang_string('invalidemail'));
                 }
             } else {
                 if ($field === 'lang') {
                     if (empty($data->lang)) {
                         // Don't change language if not already set.
                         continue;
                     } else {
                         if (clean_param($data->lang, PARAM_LANG) === '') {
                             $this->set_status('cannotfindlang', new lang_string('cannotfindlang', 'error', $data->lang));
                             continue;
                         }
                     }
                 }
             }
             // A new field was added to data while processing it.
             if (!empty($data->{$field}) && $data->{$field} !== '') {
                 $existingdata->{$field} = $data->{$field};
             }
             $doupdate = true;
         }
     }
     try {
         $auth = get_auth_plugin($existingdata->auth);
     } catch (Exception $e) {
         $this->error('userautherror', new lang_string('userautherror', 'error', s($existingdata->auth)));
         return false;
     }
     $isinternalauth = $auth->is_internal();
     if ($this->importoptions['allowsuspends'] && isset($data->suspended) && $data->suspended !== '') {
         $data->suspended = $data->suspended ? 1 : 0;
         if ($existingdata->suspended != $data->suspended) {
             $existingdata->suspended = $data->suspended;
             $doupdate = true;
             if ($existingdata->suspended) {
                 $this->dologout = true;
             }
             if ($existingdata->suspended) {
                 $this->set_status('usersuspended', new lang_string('usersuspended', 'tool_uploadusercli'));
             }
         }
     }
     $oldpasswd = $existingdata->password;
     if ($this->isremote) {
         // Do not modify remote users' passwords.
     } else {
         if (!$isinternalauth) {
             $existingdata->password = AUTH_PASSWORD_NOT_CACHED;
             unset_user_preference('create_password', $existingdata);
             unset_user_preference('auth_forcepasswordchange', $existingdata);
         } else {
             if (!empty($data->password)) {
                 if ($this->can_update() && $this->updatemode != tool_uploadusercli_processor::UPDATE_MISSING_WITH_DATA_OR_DEFAULTS) {
                     $errmsg = NULL;
                     $weak = !check_password_policy($data->password, $errmsg);
                     if ($this->importoptions['forcepassworchange'] === tool_uploadusercli_processor::FORCE_PASSWORD_CHANGE_ALL || $this->reset_password() && $weak) {
                         set_user_preference('auth_forcepasswordchange', $existingdata);
                     } else {
                         unset_user_preference('auth_forcepasswordchange', $existingdata);
                     }
                     unset_user_preference('create_password', $existingdata);
                     $existingdata->password = hash_internal_user_password($data->password, true);
                 }
             }
         }
     }
     return $existingdata;
 }
 /**
  * Get all the users to be saved to file.
  *
  * @return stdClass[] The users.
  */
 protected function get_users()
 {
     global $DB;
     // Constructing the requested user fields.
     $userfields = array();
     $getprofilefields = false;
     foreach ($this->fields as $field) {
         if (preg_match('/^profile_field_/', $field)) {
             $getprofilefields = true;
         } else {
             $userfields[] = 'u.' . $field;
         }
     }
     $userfields[] = 'u.id';
     $userfields = implode(',', $userfields);
     $courses = $this->get_courses();
     $users = array();
     // Finding the users assigned to the course with the specified roles.
     foreach ($courses as $key => $course) {
         $coursecontext = context_course::instance($course->id);
         foreach ($this->roles as $key => $role) {
             $usersassigned = get_role_users($this->rolescache[$role], $coursecontext, false, $userfields, $userfields);
             foreach ($usersassigned as $username => $user) {
                 if (!isset($users[$username])) {
                     $users[$username] = $user;
                     $users[$username]->roles = array();
                 }
                 $users[$username]->roles[] = array($role => $course->shortname);
             }
         }
     }
     // Getting all the profile fields.
     if ($getprofilefields) {
         foreach ($users as $username => $user) {
             profile_load_data($user);
         }
     }
     // Overridding fields.
     if ($this->useoverrides) {
         foreach ($users as $username => $user) {
             foreach ($this->overrides as $field => $value) {
                 $user->{$field} = $value;
             }
         }
     }
     return $users;
 }
Example #8
0
 /**
  * Function to synchronize the curriculum data with the Moodle data.
  *
  * @param boolean $tomoodle Optional direction to synchronize the data.
  *
  */
 function synchronize_moodle_user($tomoodle = true, $createnew = false)
 {
     global $CFG, $CURMAN;
     static $mu_loop_detect = array();
     // Create a new Moodle user record to update with.
     if (!($muserid = get_field('user', 'id', 'idnumber', $this->idnumber, 'mnethostid', $CFG->mnet_localhost_id, 'deleted', 0)) && !$createnew) {
         return false;
     }
     if ($tomoodle) {
         if ($createnew && !$muserid) {
             /// Add a new user
             $record = new stdClass();
             $record->idnumber = $this->idnumber;
             $record->username = $this->username;
             /// Check if already hashed... (not active now)
             if (!empty($CURMAN->passwordnothashed)) {
                 $record->password = hash_internal_user_password($this->password);
             } else {
                 $record->password = $this->password;
             }
             $record->firstname = $this->firstname;
             $record->lastname = $this->lastname;
             $record->email = $this->email;
             $record->confirmed = 1;
             $record->mnethostid = $CFG->mnet_localhost_id;
             $record->address = $this->address;
             $record->city = $this->city;
             $record->country = $this->country;
             $record->timemodified = time();
             $record->lang = $this->language;
             $record->id = insert_record('user', $record);
         } else {
             if ($muserid) {
                 /// Update an existing user
                 $record = new stdClass();
                 $record->id = $muserid;
                 $record->idnumber = $this->idnumber;
                 $record->username = $this->username;
                 /// Check if already hashed... (not active now)
                 if (!empty($CURMAN->passwordnothashed)) {
                     $record->password = hash_internal_user_password($this->password);
                 } else {
                     $record->password = $this->password;
                 }
                 $record->firstname = $this->firstname;
                 $record->lastname = $this->lastname;
                 $record->email = $this->email;
                 $record->address = $this->address;
                 $record->city = $this->city;
                 $record->country = $this->country;
                 $record->timemodified = time();
                 $record->lang = $this->language;
                 update_record('user', $record);
             } else {
                 return true;
             }
         }
         // avoid update loops
         if (isset($mu_loop_detect[$this->id])) {
             return $record->id;
         }
         $mu_loop_detect[$this->id] = true;
         // synchronize profile fields
         $origrec = clone $record;
         profile_load_data($origrec);
         $fields = field::get_for_context_level(context_level_base::get_custom_context_level('user', 'block_curr_admin'));
         $mfields = $CURMAN->db->get_records('user_info_field', '', '', '', 'shortname');
         $fields = $fields ? $fields : array();
         $changed = false;
         require_once CURMAN_DIRLOCATION . '/plugins/moodle_profile/custom_fields.php';
         foreach ($fields as $field) {
             $field = new field($field);
             if (isset($field->owners['moodle_profile']) && $field->owners['moodle_profile']->exclude == cm_moodle_profile::sync_to_moodle && isset($mfields[$field->shortname])) {
                 $shortname = $field->shortname;
                 $fieldname = "field_{$shortname}";
                 $mfieldname = "profile_{$fieldname}";
                 $mfieldvalue = isset($origrec->{$mfieldname}) ? $origrec->{$mfieldname} : null;
                 if (isset($this->{$fieldname}) && $mfieldvalue != $this->{$fieldname}) {
                     $record->{$mfieldname} = $this->{$fieldname};
                     $changed = true;
                 }
             }
         }
         profile_save_data(addslashes_recursive($record));
         if ($muserid) {
             if ($changed) {
                 events_trigger('user_updated', $record);
             }
         } else {
             events_trigger('user_created', $record);
         }
         unset($mu_loop_detect[$this->id]);
         return $record->id;
     }
 }
Example #9
0
/**
 * Migrate a single Moodle user to the Program Management system.  Will
 * only do this for users who have an idnumber set.
 *
 * @param object $mu Moodle user object
 * @return boolean Whether user was synchronized or not
 */
function pm_moodle_user_to_pm($mu)
{
    global $CFG, $DB;
    require_once $CFG->dirroot . '/lib/moodlelib.php';
    require_once elis::lib('data/customfield.class.php');
    require_once elispm::lib('data/user.class.php');
    require_once elispm::lib('data/usermoodle.class.php');
    require_once elis::lib('data/data_filter.class.php');
    require_once $CFG->dirroot . '/user/profile/lib.php';
    require_once elis::lib('lib.php');
    if (!isset($mu->id)) {
        return true;
    }
    // re-fetch, in case this is from a stale event
    $mu = $DB->get_record('user', array('id' => $mu->id));
    if (user_not_fully_set_up($mu) || !$mu->confirmed) {
        // Prevent the sync if a bare-bones user record is being created by create_user_record
        // or Moodle user has not yet been confirmed.
        return true;
    }
    //not going to be concerned with city or password for now
    if (empty($mu->idnumber) && elis::$config->local_elisprogram->auto_assign_user_idnumber) {
        //make sure the current user's username does not match up with some other user's
        //idnumber (necessary since usernames and idnumbers aren't bound to one another)
        if (!$DB->record_exists('user', array('idnumber' => $mu->username))) {
            $mu->idnumber = $mu->username;
            $DB->update_record('user', $mu);
        }
    }
    // skip user if no ID number set
    if (empty($mu->idnumber)) {
        return true;
    }
    // track whether we're syncing an idnumber change over to the PM system
    $idnumber_updated = false;
    // track whether an associated Moodle user is linked to the current PM user
    $moodle_user_exists = false;
    // determine if the user is already noted as having been associated to a PM user
    // this will join to Moodle user and PM user table to ensure data correctness
    $filters = array();
    $filters[] = new join_filter('muserid', 'user', 'id');
    $filters[] = new join_filter('cuserid', user::TABLE, 'id');
    $filters[] = new field_filter('muserid', $mu->id);
    if ($um = usermoodle::find($filters)) {
        if ($um->valid()) {
            $um = $um->current();
            //signal that an associated user already exists
            $moodle_user_exists = true;
            // determine if the Moodle user idnumber was updated
            if ($um->idnumber != $mu->idnumber) {
                //signal that the idnumber was synced over
                $idnumber_updated = true;
                // update the PM user with the new idnumber
                $cmuser = new user();
                $cmuser->id = $um->cuserid;
                $cmuser->idnumber = $mu->idnumber;
                $cmuser->save();
                // update the association table with the new idnumber
                $um->idnumber = $mu->idnumber;
                $um->save();
            }
        }
    }
    // find the linked PM user
    //filter for the basic condition on the Moodle user id
    $condition_filter = new field_filter('id', $mu->id);
    //filter for joining the association table
    $association_filter = new join_filter('muserid', 'user', 'id', $condition_filter);
    //outermost filter
    $filter = new join_filter('id', usermoodle::TABLE, 'cuserid', $association_filter);
    $cu = user::find($filter);
    if ($cu->valid()) {
        $cu = $cu->current();
    } else {
        // if a user with the same username but different idnumber exists,
        // we can't sync over because it will violate PM user uniqueness
        // constraints
        $cu = user::find(new field_filter('username', $mu->username));
        if ($cu->valid()) {
            return true;
        }
        // if no such PM user exists, create a new one
        $cu = new user();
        $cu->transfercredits = 0;
        $cu->timecreated = time();
    }
    // synchronize standard fields
    $cu->username = $mu->username;
    $cu->password = $mu->password;
    // only need to update the idnumber if it wasn't handled above
    if (!$idnumber_updated) {
        $cu->idnumber = $mu->idnumber;
    }
    $cu->firstname = $mu->firstname;
    $cu->lastname = $mu->lastname;
    $cu->email = $mu->email;
    $cu->address = $mu->address;
    $cu->city = $mu->city;
    $cu->country = $mu->country;
    if (!empty($mu->phone1)) {
        $cu->phone = $mu->phone1;
    }
    if (!empty($mu->phone2)) {
        $cu->phone2 = $mu->phone2;
    }
    if (!empty($mu->lang)) {
        $cu->language = $mu->lang;
    }
    $cu->timemodified = time();
    // synchronize custom profile fields
    profile_load_data($mu);
    fix_moodle_profile_fields($mu);
    $fields = field::get_for_context_level(CONTEXT_ELIS_USER);
    $fields = $fields ? $fields : array();
    require_once elis::plugin_file('elisfields_moodleprofile', 'custom_fields.php');
    foreach ($fields as $field) {
        $field = new field($field);
        if (!moodle_profile_can_sync($field->shortname)) {
            continue;
        }
        if (isset($field->owners['moodle_profile']) && isset($mu->{"profile_field_{$field->shortname}"})) {
            // check if should sync user profile field settings
            if ($field->owners['moodle_profile']->exclude == pm_moodle_profile::sync_from_moodle) {
                sync_profile_field_settings_from_moodle($field);
            }
            $fieldname = "field_{$field->shortname}";
            $cu->{$fieldname} = $mu->{"profile_field_{$field->shortname}"};
        }
    }
    //specifically tell the user save not to use the local_elisprogram_usr_mdl for syncing
    //because the record hasn't been inserted yet (see below)
    try {
        $cu->save(false);
    } catch (Exception $ex) {
        if (in_cron()) {
            mtrace(get_string('record_not_created_reason', 'local_elisprogram', array('message' => $ex->getMessage() . " [{$mu->id}]")));
            return false;
        } else {
            throw new Exception($ex->getMessage());
        }
    }
    // if no user association record exists, create one
    if (!$moodle_user_exists) {
        $um = new usermoodle();
        $um->cuserid = $cu->id;
        $um->muserid = $mu->id;
        $um->idnumber = $mu->idnumber;
        $um->save();
    }
    return true;
}
Example #10
0
 }
 if ($skip) {
     continue;
 }
 if ($existinguser) {
     $user->id = $existinguser->id;
     $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id' => $existinguser->id)), s($existinguser->username)), 'normal', false);
     if (is_siteadmin($user->id)) {
         $upt->track('status', $strusernotupdatedadmin, 'error');
         $userserrors++;
         continue;
     }
     $existinguser->timemodified = time();
     // do NOT mess with timecreated or firstaccess here!
     //load existing profile data
     profile_load_data($existinguser);
     $upt->track('auth', $existinguser->auth, 'normal', false);
     $doupdate = false;
     if ($updatetype != UU_UPDATE_NOCHANGES) {
         if (!empty($user->auth) and $user->auth !== $existinguser->auth) {
             $upt->track('auth', s($existinguser->auth) . '-->' . s($user->auth), 'info', false);
             $existinguser->auth = $user->auth;
             if (!isset($supportedauths[$user->auth])) {
                 $upt->track('auth', $struserauthunsupported, 'warning');
             }
             $doupdate = true;
         }
         $allcolumns = array_merge($STD_FIELDS, $PRF_FIELDS);
         foreach ($allcolumns as $column) {
             if ($column === 'username' or $column === 'password' or $column === 'auth') {
                 // these can not be changed here
Example #11
0
 /**
  * Validate that custom user fields are synched over to Moodle when PM user is updated
  * during an import
  */
 public function test_user_custom_field_sync_on_user_update()
 {
     // NOTE: not testing all cases because ELIS handles the details and this.
     // Seems to already work.
     global $CFG, $DB;
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once elis::lib('data/customfield.class.php');
     require_once elispm::file('accesslib.php');
     require_once elispm::lib('data/user.class.php');
     require_once $CFG->dirroot . '/user/profile/lib.php';
     require_once $CFG->dirroot . '/user/profile/definelib.php';
     require_once $CFG->dirroot . '/user/profile/field/checkbox/define.class.php';
     // The associated Moodle user profile field.
     $profiledefinecheckbox = new profile_define_checkbox();
     $data = new stdClass();
     $data->datatype = 'checkbox';
     $data->categoryid = 99999;
     $data->shortname = 'testfieldshortname';
     $data->name = 'testfieldname';
     $profiledefinecheckbox->define_save($data);
     // Set up the user.
     $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA'));
     $user->save();
     // Field category.
     $fieldcategory = new field_category(array('name' => 'testcategoryname'));
     $fieldcategory->save();
     // Custom field.
     $field = new field(array('categoryid' => $fieldcategory->id, 'shortname' => 'testfieldshortname', 'name' => 'testfieldname', 'datatype' => 'bool'));
     $field->save();
     // Field owners
     field_owner::ensure_field_owner_exists($field, 'moodle_profile');
     $DB->execute("UPDATE {" . field_owner::TABLE . "} SET exclude = ?", array(pm_moodle_profile::sync_to_moodle));
     $manualowneroptions = array('required' => 0, 'edit_capability' => '', 'view_capability' => '', 'control' => 'checkbox');
     field_owner::ensure_field_owner_exists($field, 'manual', $manualowneroptions);
     // Field context level assocation.
     $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => CONTEXT_ELIS_USER));
     $fieldcontextlevel->save();
     // Reset cached custom fields.
     $user = new user();
     $user->reset_custom_field_list();
     // Run the user create action.
     $record = new stdClass();
     $record->action = 'update';
     $record->idnumber = 'testuseridnumber';
     $record->username = '******';
     $record->email = '*****@*****.**';
     $record->testfieldshortname = 1;
     $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis');
     $importplugin->fslogger = new silent_fslogger(null);
     $importplugin->process_record('user', $record, 'bogus');
     // Validation.
     $user = new stdClass();
     $user->id = $DB->get_field('user', 'id', array('username' => 'testuserusername'));
     profile_load_data($user);
     $this->assertEquals(1, $user->profile_field_testfieldshortname);
 }
Example #12
0
 /**
  * Post authentication hook.
  * This method is called from authenticate_user_login() for all enabled auth plugins.
  *
  * @param object $user user object, later used for $USER
  * @param string $username (with system magic quotes)
  * @param string $password plain text password (with system magic quotes)
  */
 function user_authenticated_hook(&$user, $username, $password)
 {
     global $DB, $SESSION;
     $context = context_system::instance();
     $uid = $user->id;
     // Ignore users from don't_touch list
     $ignore = explode(",", $this->config->donttouchusers);
     if (!empty($ignore) and array_search($username, $ignore) !== false) {
         $SESSION->mcautoenrolled = TRUE;
         return true;
     }
     // Ignore guests
     if ($uid < 2) {
         $SESSION->mcautoenrolled = TRUE;
         return true;
     }
     // ********************** Get COHORTS data
     $clause = array('contextid' => $context->id);
     if ($this->config->enableunenrol == 1) {
         $clause['component'] = self::COMPONENT_NAME;
     }
     $cohorts = $DB->get_records('cohort', $clause);
     $cohorts_list = array();
     foreach ($cohorts as $cohort) {
         $cid = $cohort->id;
         $cname = format_string($cohort->name);
         $cohorts_list[$cid] = $cname;
     }
     // Get advanced user data
     profile_load_data($user);
     profile_load_custom_fields($user);
     $user_profile_data = mcae_prepare_profile_data($user, $this->config->secondrule_fld);
     // Additional values for email
     list($email_username, $email_domain) = explode("@", $user_profile_data['email']);
     // email root domain
     $email_domain_array = explode('.', $email_domain);
     if (count($email_domain_array) > 2) {
         $email_rootdomain = $email_domain_array[count($email_domain_array) - 2] . '.' . $email_domain_array[count($email_domain_array) - 1];
     } else {
         $email_rootdomain = $email_domain;
     }
     $user_profile_data['email'] = array('full' => $user_profile_data['email'], 'username' => $email_username, 'domain' => $email_domain, 'rootdomain' => $email_rootdomain);
     // Delimiter
     $delimiter = $this->config->delim;
     $delim = strtr($delimiter, array('CR+LF' => chr(13) . chr(10), 'CR' => chr(13), 'LF' => chr(10)));
     // Calculate a cohort names for user
     $replacements_tpl = $this->config->replace_arr;
     $replacements = array();
     if (!empty($replacements_tpl)) {
         $replacements_pre = explode($delim, $replacements_tpl);
         foreach ($replacements_pre as $rap) {
             list($key, $val) = explode("|", $rap);
             $replacements[$key] = $val;
         }
     }
     // Generate cohorts array
     $main_rule = $this->config->mainrule_fld;
     $templates_tpl = array();
     $templates = array();
     if (!empty($main_rule)) {
         $templates_tpl = explode($delim, $main_rule);
     } else {
         $SESSION->mcautoenrolled = TRUE;
         return;
         //Empty mainrule
     }
     // Find %split function
     foreach ($templates_tpl as $item) {
         if (preg_match('/(?<full>%split\\((?<fld>\\w*)\\|(?<delim>.{1,5})\\))/', $item, $split_params)) {
             // Split!
             $splitted = explode($split_params['delim'], $user_profile_data[$split_params['fld']]);
             foreach ($splitted as $key => $val) {
                 $user_profile_data[$split_params['fld'] . "_{$key}"] = $val;
                 $templates[] = strtr($item, array("{$split_params['full']}" => "{{ {$split_params['fld']}_{$key} }}"));
             }
         } else {
             $templates[] = $item;
         }
     }
     $processed = array();
     // Process templates with Mustache
     foreach ($templates as $cohort) {
         $cohortname = $this->mustache->render($cohort, $user_profile_data);
         $cohortname = !empty($replacements) ? strtr($cohortname, $replacements) : $cohortname;
         if ($cohortname == '') {
             continue;
             // We don't want an empty cohort name
         }
         $cid = array_search($cohortname, $cohorts_list);
         if ($cid !== false) {
             if (!$DB->record_exists('cohort_members', array('cohortid' => $cid, 'userid' => $user->id))) {
                 cohort_add_member($cid, $user->id);
             }
         } else {
             // Cohort not exist so create a new one
             $newcohort = new stdClass();
             $newcohort->name = $cohortname;
             $newcohort->description = "created " . date("d-m-Y");
             $newcohort->contextid = $context->id;
             if ($this->config->enableunenrol == 1) {
                 $newcohort->component = "auth_mcae";
             }
             $cid = cohort_add_cohort($newcohort);
             cohort_add_member($cid, $user->id);
             // Prevent creation new cohorts with same names
             $cohorts_list[$cid] = $cohortname;
         }
         $processed[] = $cid;
     }
     $SESSION->mcautoenrolled = TRUE;
     //Unenrol user
     if ($this->config->enableunenrol == 1) {
         //List of cohorts where this user enrolled
         $sql = "SELECT c.id AS cid FROM {cohort} c JOIN {cohort_members} cm ON cm.cohortid = c.id WHERE c.component = 'auth_mcae' AND cm.userid = {$uid}";
         $enrolledcohorts = $DB->get_records_sql($sql);
         foreach ($enrolledcohorts as $ec) {
             if (array_search($ec->cid, $processed) === false) {
                 cohort_remove_member($ec->cid, $uid);
             }
         }
     }
 }
Example #13
0
 */
defined('MOODLE_INTERNAL') || die;
global $USER;
require_once $CFG->dirroot . '/user/profile/lib.php';
require_once $CFG->dirroot . '/auth/mcae/lib.php';
if ($hassiteconfig) {
    // needs this condition or there is error on login page
    $ADMIN->add('accounts', new admin_externalpage('cohorttoolmcae', get_string('auth_cohorttoolmcae', 'auth_mcae'), new moodle_url('/auth/mcae/convert.php')));
    $ADMIN->add('accounts', new admin_externalpage('cohortviewmcae', get_string('auth_cohortviewmcae', 'auth_mcae'), new moodle_url('/auth/mcae/view.php')));
}
if ($ADMIN->fulltree) {
    $settings->add(new admin_setting_configtextarea('auth_mcae/mainrule_fld', get_string('auth_mainrule_fld', 'auth_mcae'), '', ''));
    // Profile field helper
    $fldlist = array();
    $usr_helper = $DB->get_record('user', array('id' => 2));
    profile_load_data($usr_helper);
    profile_load_custom_fields($usr_helper);
    $fldlist = mcae_prepare_profile_data($usr_helper);
    // Additional values for email
    list($email_username, $email_domain) = explode("@", $fldlist['email']);
    // Email root domain
    $email_domain_array = explode('.', $email_domain);
    if (count($email_domain_array) > 2) {
        $email_rootdomain = $email_domain_array[count($email_domain_array) - 2] . '.' . $email_domain_array[count($email_domain_array) - 1];
    } else {
        $email_rootdomain = $email_domain;
    }
    $fldlist['email'] = array('full' => $fldlist['email'], 'username' => $email_username, 'domain' => $email_domain, 'rootdomain' => $email_rootdomain);
    //print_r($fldlist);
    $help_array = array();
    mcae_print_profile_data($fldlist, '', $help_array);
function user_download_csv($fields)
{
    global $CFG, $SESSION, $DB;
    require_once $CFG->dirroot . '/user/profile/lib.php';
    require_once $CFG->libdir . '/csvlib.class.php';
    $filename = clean_filename(get_string('users'));
    $csvexport = new csv_export_writer();
    $csvexport->set_filename($filename);
    $csvexport->add_data($fields);
    foreach ($SESSION->bulk_users as $userid) {
        $row = array();
        if (!($user = $DB->get_record('user', array('id' => $userid)))) {
            continue;
        }
        profile_load_data($user);
        $userprofiledata = array();
        foreach ($fields as $field => $unused) {
            // Custom user profile textarea fields come in an array
            // The first element is the text and the second is the format.
            // We only take the text.
            if (is_array($user->{$field})) {
                $userprofiledata[] = reset($user->{$field});
            } else {
                $userprofiledata[] = $user->{$field};
            }
        }
        $csvexport->add_data($userprofiledata);
    }
    $csvexport->download_file();
    die;
}
}
//if user has the right and the map doesn't require the students consent to appear on the map
//then show button to update locations for users - locations will be try to be set from users' profile location
if (has_capability("mod/map:setotherslocation", $context, $USER->id) && $map->requireok == 0 && $map->studentlocations == 1) {
    print_box(print_single_button("update_locations.php?id=" . $id, null, get_string("updateuserlocations", "map"), "post", "_self", true), "button");
}
//only allow members to add student locations or extra locations
if ($memberOfGroup) {
    //should this map show student locations
    if ($map->studentlocations == 1 && has_capability('mod/map:setownlocation', $context)) {
        $locForm = new mod_map_user_location_form();
        if (!isset($user_map_location)) {
            //no user location has been set for current user
            //fill form with profile location
            require_once $CFG->dirroot . '/user/profile/lib.php';
            profile_load_data($USER);
            print_box(format_text(get_string("usernolocation", "map"), FORMAT_PLAIN), 'generalbox', 'intro');
            $curLocation = new object();
            $curLocation->city = $USER->city;
            $curLocation->state = map_get_user_state($USER);
            $curLocation->country = $USER->country;
            $curLocation->id = $cm->id;
            $curLocation->action = "insertlocation";
            $curLocation->userid = $USER->id;
            $locForm->set_data($curLocation);
        } else {
            if ($user_map_location->showcode == 0) {
                //user has explicitly said they don't want to show up on the map
                $locForm = new mod_map_reset_location_form();
            }
            //user has set location
Example #16
0
/**
 * Migrate a single Moodle user to the Curriculum Management system.  Will
 * only do this for users who have an idnumber set.
 */
function cm_moodle_user_to_cm($mu)
{
    global $CURMAN, $CFG;
    require_once CURMAN_DIRLOCATION . '/lib/customfield.class.php';
    require_once CURMAN_DIRLOCATION . '/lib/user.class.php';
    require_once $CFG->dirroot . '/user/profile/lib.php';
    // re-fetch, in case this is from a stale event
    $mu = addslashes_recursive($CURMAN->db->get_record('user', 'id', $mu->id));
    if (empty($mu->idnumber) && $CURMAN->config->auto_assign_user_idnumber) {
        $mu->idnumber = $mu->username;
        $CURMAN->db->update_record('user', $mu);
    }
    if (empty($mu->idnumber)) {
        return true;
    } else {
        if (empty($mu->country)) {
            //this is necessary because PM requires this field
            return true;
        } else {
            if ($cu = $CURMAN->db->get_record('crlm_user', 'idnumber', $mu->idnumber)) {
                $cu = new user(addslashes_recursive($cu));
                // synchronize any profile changes
                $cu->username = $mu->username;
                $cu->password = $mu->password;
                $cu->idnumber = $mu->idnumber;
                $cu->firstname = $mu->firstname;
                $cu->lastname = $mu->lastname;
                $cu->email = $mu->email;
                $cu->address = $mu->address;
                $cu->city = $mu->city;
                $cu->country = $mu->country;
                $cu->phone = empty($mu->phone1) ? empty($cu->phone) ? '' : $cu->phone : $mu->phone1;
                $cu->phone2 = empty($mu->phone2) ? empty($cu->phone2) ? '' : $cu->phone2 : $mu->phone2;
                $cu->language = empty($mu->lang) ? empty($cu->language) ? '' : $cu->language : $mu->lang;
                $cu->timemodified = time();
                // synchronize custom profile fields
                profile_load_data($mu);
                $fields = field::get_for_context_level(context_level_base::get_custom_context_level('user', 'block_curr_admin'));
                $fields = $fields ? $fields : array();
                require_once CURMAN_DIRLOCATION . '/plugins/moodle_profile/custom_fields.php';
                foreach ($fields as $field) {
                    $field = new field($field);
                    if (isset($field->owners['moodle_profile']) && $field->owners['moodle_profile']->exclude == cm_moodle_profile::sync_from_moodle) {
                        $fieldname = "field_{$field->shortname}";
                        $cu->{$fieldname} = $mu->{"profile_field_{$field->shortname}"};
                    }
                }
                $cu->update();
            } else {
                $cu = new user();
                $cu->username = $mu->username;
                $cu->password = $mu->password;
                $cu->idnumber = $mu->idnumber;
                $cu->firstname = $mu->firstname;
                $cu->lastname = $mu->lastname;
                $cu->email = $mu->email;
                $cu->address = $mu->address;
                $cu->city = $mu->city;
                $cu->country = $mu->country;
                $cu->phone = $mu->phone1;
                $cu->phone2 = $mu->phone2;
                $cu->language = $mu->lang;
                $cu->transfercredits = 0;
                $cu->timecreated = $cu->timemodified = time();
                // synchronize profile fields
                profile_load_data($mu);
                $fields = field::get_for_context_level(context_level_base::get_custom_context_level('user', 'block_curr_admin'));
                $fields = $fields ? $fields : array();
                require_once CURMAN_DIRLOCATION . '/plugins/moodle_profile/custom_fields.php';
                foreach ($fields as $field) {
                    $field = new field($field);
                    if (isset($field->owners['moodle_profile']) && $field->owners['moodle_profile']->exclude == cm_moodle_profile::sync_from_moodle) {
                        $fieldname = "field_{$field->shortname}";
                        $cu->{$fieldname} = $mu->{"profile_field_{$field->shortname}"};
                    }
                }
                $cu->add();
            }
        }
    }
    return true;
}
function read_user($user_id)
{
    global $DB;
    $user = $DB->get_record('user', array('id' => $user_id), '*', MUST_EXIST);
    profile_load_data($user);
    // Add custom profile data
    return $user;
}
Example #18
0
function user_download_csv($fields)
{
    global $CFG, $SESSION, $DB;
    require_once $CFG->dirroot . '/user/profile/lib.php';
    $filename = clean_filename(get_string('users') . '.csv');
    header("Content-Type: application/download\n");
    header("Content-Disposition: attachment; filename=\"{$filename}\"");
    header("Expires: 0");
    header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
    header("Pragma: public");
    $delimiter = get_string('listsep', 'langconfig');
    $encdelim = '&#' . ord($delimiter);
    $row = array();
    foreach ($fields as $fieldname) {
        $row[] = str_replace($delimiter, $encdelim, $fieldname);
    }
    echo implode($delimiter, $row) . "\n";
    foreach ($SESSION->bulk_users as $userid) {
        $row = array();
        if (!($user = $DB->get_record('user', array('id' => $userid)))) {
            continue;
        }
        profile_load_data($user);
        foreach ($fields as $field => $unused) {
            $row[] = str_replace($delimiter, $encdelim, $user->{$field});
        }
        echo implode($delimiter, $row) . "\n";
    }
    die;
}
Example #19
0
    /**
     * Checks menu access based on admin settings and a users custom profile fields
     *
     * @param string $ftype the custom profile field
     * @param string $setvalue the expected value a user must have in their profile field
     * @param string $menu a token to identify the menu used to store access in session
     * @return boolean
     */
    public function check_menu_access($ftype, $setvalue, $menu) {
        global $PAGE, $USER, $CFG;
        $usersvalue = 'default-zz'; // Just want a value that will not be matched by accident.
        $sessttl = (time() + ($PAGE->theme->settings->menusessionttl * 60));
        $menuttl = $menu . 'ttl';

        if ($PAGE->theme->settings->menusession) {
            if (isset($USER->theme_adaptable_menus[$menu])) {

                if ($USER->theme_adaptable_menus[$menuttl] >= time()) {
                    if ($USER->theme_adaptable_menus[$menu] == true) {
                        return true;
                    } else if ($USER->theme_adaptable_menus[$menu] == false) {
                        return false;
                    }
                }
            }
        }

        require_once($CFG->dirroot.'/user/profile/lib.php');
        require_once($CFG->dirroot.'/user/lib.php');
        profile_load_data($USER);
        $ftype = "profile_field_$ftype";
        if (isset($USER->$ftype)) {
            $usersvalue = $USER->$ftype;
        }

        if ($usersvalue == $setvalue) {
            $USER->theme_adaptable_menus[$menu] = true;
            $USER->theme_adaptable_menus[$menuttl] = $sessttl;
            return true;
        }

        $USER->theme_adaptable_menus[$menu] = false;
        $USER->theme_adaptable_menus[$menuttl] = $sessttl;
        return false;
    }
Example #20
0
 /**
  * Test that a record can be modified, and that the corresponding Moodle
  * user is modified.
  */
 public function test_canupdaterecordandsynctomoodle()
 {
     global $DB;
     require_once elispm::lib('lib.php');
     $this->load_csv_data();
     // Read a record.
     $src = new user(103, null, array(), false, array());
     $src->reset_custom_field_list();
     // Modify the data.
     $src->firstname = 'Testuser';
     $src->lastname = 'One';
     $src->field_sometext = 'boo';
     $src->field_sometextfrompm = 'bla';
     $src->save();
     // Read it back.
     $retr = new user($src->id, null, array(), false, array());
     $this->assertEquals($src->firstname, $retr->firstname);
     $this->assertEquals($src->lastname, $retr->lastname);
     // Check the Moodle user.
     $retr = $DB->get_record('user', array('id' => 100));
     profile_load_data($retr);
     fix_moodle_profile_fields($retr);
     $this->assertEquals($src->firstname, $retr->firstname);
     $this->assertEquals($src->lastname, $retr->lastname);
     // Check custom fields.
     $result = new moodle_recordset_phpunit_datatable('user_info_data', $DB->get_records('user_info_data', null, '', 'id, userid, fieldid, data'));
     $dataset = new PHPUnit_Extensions_Database_DataSet_CsvDataSet();
     $dataset->addTable('user_info_data', elispm::file('tests/fixtures/user_info_data.csv'));
     $dataset = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($dataset);
     // Only the second text field should be changed; everything else should be the same.
     $dataset->addFullReplacement('Second text entry field', 'bla');
     $this->assertTablesEqual($dataset->getTable('user_info_data'), $result);
 }
Example #21
0
 /**
  * Function to synchronize the curriculum data with the Moodle data.
  *
  * @param boolean $tomoodle Optional direction to synchronize the data.
  * @param boolean $strict_match Whether we should use the association table rather
  *                               than just check idnumbers when comparing to Moodle users
  *
  */
 function synchronize_moodle_user($tomoodle = true, $createnew = false, $strict_match = true)
 {
     global $CFG;
     require_once $CFG->dirroot . '/admin/tool/uploaduser/locallib.php';
     require_once elispm::lib('data/usermoodle.class.php');
     require_once elis::lib('lib.php');
     static $mu_loop_detect = array();
     // Create a new Moodle user record to update with.
     if (!($muser = $this->get_moodleuser($strict_match)) && !$createnew) {
         return false;
     }
     $muserid = $muser ? $muser->id : false;
     if ($tomoodle) {
         // map PM user fields to Moodle user fields
         $mdlfieldmap = array('idnumber' => 'idnumber', 'username' => 'username', 'firstname' => 'firstname', 'lastname' => 'lastname', 'email' => 'email', 'address' => 'address', 'city' => 'city', 'country' => 'country', 'language' => 'lang');
         // determine if the user is already noted as having been associated to a PM user
         if ($um = usermoodle::find(new field_filter('cuserid', $this->id))) {
             if ($um->valid()) {
                 $um = $um->current();
                 // determine if the PM user idnumber was updated
                 if ($um->idnumber != $this->idnumber) {
                     // update the Moodle user with the new idnumber
                     $muser = new stdClass();
                     $muser->id = $um->muserid;
                     $muser->idnumber = $this->idnumber;
                     $this->_db->update_record('user', $muser);
                     // update the association table with the new idnumber
                     $um->idnumber = $this->idnumber;
                     $um->save();
                 }
             }
         }
         //try to update the idnumber of a matching Moodle user that
         //doesn't have an idnumber set yet
         $exists_params = array('username' => $this->username, 'mnethostid' => $CFG->mnet_localhost_id);
         if ($moodle_user = $this->_db->get_record('user', $exists_params)) {
             if (empty($moodle_user->idnumber)) {
                 //potentially old data, so set the idnumber
                 $moodle_user->idnumber = $this->idnumber;
                 $this->_db->update_record('user', $moodle_user);
                 $muserid = $moodle_user->id;
             } else {
                 if ($this->idnumber != $moodle_user->idnumber) {
                     //the username points to a pre-existing Moodle user
                     //with a non-matching idnumber, so something horrible
                     //happened
                     return;
                 }
             }
         }
         if ($createnew && !$muserid) {
             /// Add a new user
             $record = new stdClass();
             foreach ($mdlfieldmap as $pmfield => $mdlfield) {
                 if (isset($this->{$pmfield})) {
                     $record->{$mdlfield} = $this->{$pmfield};
                 }
             }
             $record->password = $this->password === null ? '' : $this->password;
             $record->confirmed = 1;
             $record->mnethostid = $CFG->mnet_localhost_id;
             $record->timemodified = time();
             $record->id = $this->_db->insert_record('user', $record);
         } else {
             if ($muserid) {
                 /// Update an existing user
                 $record = new stdClass();
                 $record->id = $muserid;
                 foreach ($mdlfieldmap as $pmfield => $mdlfield) {
                     if (isset($this->{$pmfield})) {
                         $record->{$mdlfield} = $this->{$pmfield};
                     }
                 }
                 if (!empty($this->password)) {
                     $record->password = $this->password;
                 }
                 $record->timemodified = time();
                 $this->_db->update_record('user', $record);
             } else {
                 return true;
             }
         }
         // avoid update loops
         if (isset($mu_loop_detect[$this->id])) {
             return $record->id;
         }
         $mu_loop_detect[$this->id] = true;
         // synchronize profile fields
         $origrec = clone $record;
         profile_load_data($origrec);
         fix_moodle_profile_fields($origrec);
         $fields = field::get_for_context_level(CONTEXT_ELIS_USER);
         $mfields = $this->_db->get_records('user_info_field', array(), '', 'shortname');
         $fields = $fields ? $fields : array();
         $changed = false;
         require_once elis::plugin_file('elisfields_moodleprofile', 'custom_fields.php');
         foreach ($fields as $field) {
             $field = new field($field);
             if (!moodle_profile_can_sync($field->shortname)) {
                 continue;
             }
             if (isset($field->owners['moodle_profile']) && $field->owners['moodle_profile']->exclude == pm_moodle_profile::sync_to_moodle && isset($mfields[$field->shortname])) {
                 $shortname = $field->shortname;
                 $fieldname = "field_{$shortname}";
                 $mfieldname = "profile_{$fieldname}";
                 $mfieldvalue = isset($origrec->{$mfieldname}) ? $origrec->{$mfieldname} : null;
                 if ($mfieldvalue != $this->{$fieldname}) {
                     $record->{$mfieldname} = $this->{$fieldname};
                     $changed = true;
                     sync_profile_field_settings_to_moodle($field);
                 }
             }
         }
         $record = uu_pre_process_custom_profile_data($record);
         profile_save_data($record);
         if ($muserid) {
             if ($changed) {
                 events_trigger('user_updated', $record);
             }
         } else {
             // if no user association record exists, create one
             $um = new usermoodle();
             $um->cuserid = $this->id;
             $um->muserid = $record->id;
             $um->idnumber = $this->idnumber;
             $um->save();
             events_trigger('user_created', $record);
         }
         unset($mu_loop_detect[$this->id]);
         return $record->id;
     }
 }
Example #22
0
$PAGE->set_context($personalcontext);
if ($USER->id != $user->id) {
    $PAGE->navigation->extend_for_user($user);
} else {
    if ($node = $PAGE->navigation->find('myprofile', navigation_node::TYPE_ROOTNODE)) {
        $node->force_open();
    }
}
// Process email change cancellation.
if ($cancelemailchange) {
    cancel_email_update($user->id);
}
// Load user preferences.
useredit_load_preferences($user);
// Load custom profile fields data.
profile_load_data($user);
// Prepare the editor and create form.
$editoroptions = array('maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $CFG->maxbytes, 'trusttext' => false, 'forcehttps' => false, 'context' => $personalcontext);
$user = file_prepare_standard_editor($user, 'description', $editoroptions, $personalcontext, 'user', 'profile', 0);
// Prepare filemanager draft area.
$draftitemid = 0;
$filemanagercontext = $editoroptions['context'];
$filemanageroptions = array('maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image');
file_prepare_draft_area($draftitemid, $filemanagercontext->id, 'user', 'newicon', 0, $filemanageroptions);
$user->imagefile = $draftitemid;
// Create form.
$userform = new user_edit_form(new moodle_url($PAGE->url, array('returnto' => $returnto)), array('editoroptions' => $editoroptions, 'filemanageroptions' => $filemanageroptions, 'user' => $user));
$emailchanged = false;
if ($usernew = $userform->get_data()) {
    // Deciding where to send the user back in most cases.
    if ($returnto === 'profile') {
 /**
  * Validate that the import does not create bogus profile field data on user update
  */
 public function test_version1importvalidatesprofilefieldsonupdate()
 {
     global $CFG, $DB;
     // Run the "create user" import.
     $this->run_core_user_import(array());
     $userid = $DB->get_field('user', 'id', array('username' => 'rlipusername', 'mnethostid' => $CFG->mnet_localhost_id));
     // Create the category.
     $category = new stdClass();
     $category->sortorder = $DB->count_records('user_info_category') + 1;
     $category->id = $DB->insert_record('user_info_category', $category);
     // Try to insert bogus checkbox data.
     $this->create_profile_field('rlipcheckbox', 'checkbox', $category->id);
     $params = array('action' => 'update', 'username' => 'rlipusername', 'profile_field_rlipcheckbox' => '2');
     $this->run_core_user_import($params);
     $user = new stdClass();
     $user->id = $userid;
     profile_load_data($user);
     fix_moodle_profile_fields($user);
     $this->assertEquals(isset($user->profile_field_rlipcheckbox), false);
     // Try to insert bogus datetime data.
     $this->create_profile_field('rlipdatetime', 'datetime', $category->id);
     $params = array('action' => 'update', 'username' => 'rlipusername', 'profile_field_rlipdatetime' => '1000000000');
     $this->run_core_user_import($params);
     $user = new stdClass();
     $user->id = $userid;
     profile_load_data($user);
     fix_moodle_profile_fields($user);
     $this->assertEquals(isset($user->profile_field_rlipcheckbox), false);
     // Try to insert bogus menu data.
     $this->create_profile_field('rlipmenu', 'menu', $category->id, "rlipoption1\nrlipoption1B");
     $params = array('action' => 'update', 'username' => 'rlipusername', 'profile_field_rlipmenu' => 'rlipoption2');
     $this->run_core_user_import($params);
     $user = new stdClass();
     $user->id = $userid;
     profile_load_data($user);
     fix_moodle_profile_fields($user);
     $this->assertEquals(isset($user->profile_field_rlipcheckbox), false);
 }