/**
  * get_course_risks
  *
  * @param int $courseid     courseid of the course
  * @param int $startdate    start of range in seconds
  * @param int $enddate      end of range in seconds
  * @access public
  * @return array            list of risk values, key'd on userid
  */
 public function get_course_risks($startdate = null, $enddate = null)
 {
     global $DB;
     // TODO: Move the user list building somewhere static, otherwise its done for every indicator.
     $pluginconfig = get_config('engagement');
     if (!isset($pluginconfig->roles)) {
         $roleids = array_keys(get_archetype_roles('student'));
     } else {
         $roles = $pluginconfig->roles;
         $roleids = explode(',', $roles);
     }
     list($esql, $eparams) = get_enrolled_sql($this->context, '', 0, true);
     // Only active users.
     list($rsql, $rparams) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED, 'roles');
     $sql = "SELECT " . $DB->sql_concat_join("'_'", array('je.id', 'ra.id')) . ", je.id as jeid\n                FROM ({$esql}) je\n                JOIN {role_assignments} ra ON (ra.userid = je.id)\n                WHERE ra.contextid = :contextid AND ra.roleid {$rsql}";
     $params = array_merge($eparams, $rparams);
     $params['contextid'] = $this->context->id;
     $result = $DB->get_records_sql($sql, $params);
     $users = array();
     foreach ($result as $key => $row) {
         if (!isset($users[$row->jeid])) {
             $users[$row->jeid] = true;
         }
     }
     $users = array_keys($users);
     return self::get_risk_for_users($users, $startdate, $enddate);
 }
Example #2
0
function xmldb_enrol_self_upgrade($oldversion)
{
    global $CFG;
    // Moodle v2.8.0 release upgrade line.
    // Put any upgrade step following this.
    // Moodle v2.9.0 release upgrade line.
    // Put any upgrade step following this.
    // Moodle v3.0.0 release upgrade line.
    // Put any upgrade step following this.
    // Moodle v3.1.0 release upgrade line.
    // Put any upgrade step following this.
    if ($oldversion < 2016052301) {
        global $DB;
        // Get roles with manager archetype.
        $managerroles = get_archetype_roles('manager');
        if (!empty($managerroles)) {
            // Remove wrong CAP_PROHIBIT from self:holdkey.
            foreach ($managerroles as $role) {
                $DB->execute("DELETE\n                                FROM {role_capabilities}\n                               WHERE roleid = ? AND capability = ? AND permission = ?", array($role->id, 'enrol/self:holdkey', CAP_PROHIBIT));
            }
        }
        upgrade_plugin_savepoint(true, 2016052301, 'enrol', 'self');
    }
    return true;
}
Example #3
0
function xmldb_enrol_category_install()
{
    global $CFG, $DB;
    if (!$DB->record_exists_select('role_assignments', "contextid IN (SELECT id FROM {context} WHERE contextlevel = ?)", array(CONTEXT_COURSECAT))) {
        // fresh install or nobody used category enrol
        return;
    }
    // existing sites need a way to keep category role enrols, but we do not want to encourage that on new sites
    // extremely ugly hack, the sync depends on the capabilities so we unfortunately force update of caps here
    // note: this is not officially supported and should not be copied elsewhere! :-(
    update_capabilities('enrol_category');
    $syscontext = get_context_instance(CONTEXT_SYSTEM);
    $archetypes = array('student', 'teacher', 'editingteacher');
    $enableplugin = false;
    foreach ($archetypes as $archetype) {
        $roles = get_archetype_roles($archetype);
        foreach ($roles as $role) {
            if (!$DB->record_exists_select('role_assignments', "roleid = ? AND contextid IN (SELECT id FROM {context} WHERE contextlevel = ?)", array($role->id, CONTEXT_COURSECAT))) {
                continue;
            }
            assign_capability('enrol/category:synchronised', CAP_ALLOW, $role->id, $syscontext->id, true);
            $levels = get_role_contextlevels($role->id);
            $levels[] = CONTEXT_COURSECAT;
            set_role_contextlevels($role->id, $levels);
            $enableplugin = true;
        }
    }
    if (!$enableplugin) {
        return;
    }
    // enable this plugin
    $enabledplugins = explode(',', $CFG->enrol_plugins_enabled);
    $enabledplugins[] = 'category';
    $enabledplugins = array_unique($enabledplugins);
    set_config('enrol_plugins_enabled', implode(',', $enabledplugins));
    // brute force course resync, this may take a while
    require_once "{$CFG->dirroot}/enrol/category/locallib.php";
    enrol_category_sync_full();
}
 /**
  * This function calculates all unassigned students for a particular grouping.
  * We enforce a rule that students can only be a member of one group in the
  * grouping.
  *
  * @return array {IDs => names) of potential members.
  *
  */
 public function get_potential_students()
 {
     $student = get_archetype_roles('student');
     $student = reset($student);
     $allmembers = groups_get_potential_members($this->courseid, $student->id);
     $allocatedmembers = $this->get_all_grouped_students();
     $potentialmemberids = array();
     foreach ($allmembers as $allmember) {
         if (array_search($allmember->id, $allocatedmembers) === false) {
             $potentialmemberids[] = $allmember->id;
         }
     }
     sort($potentialmemberids);
     $potentialmembernames = block_skills_group_retrieve_names($potentialmemberids);
     // Note: array_combine() will not work with empty arrays.
     if (count($potentialmemberids) > 0) {
         return array_combine($potentialmemberids, $potentialmembernames);
     } else {
         return array();
     }
 }
Example #5
0
 /**
  * Return the default setting for this control
  *
  * @return array Array of default settings
  */
 public function get_defaultsetting()
 {
     global $CFG;
     if (during_initial_install()) {
         return null;
     }
     $result = array();
     foreach ($this->types as $archetype) {
         if ($caproles = get_archetype_roles($archetype)) {
             foreach ($caproles as $caprole) {
                 $result[$caprole->id] = 1;
             }
         }
     }
     return $result;
 }
Example #6
0
 function definition()
 {
     global $CFG, $USER;
     $mform = $this->_form;
     $columns = $this->_customdata['columns'];
     $data = $this->_customdata['data'];
     // I am the template user, why should it be the administrator? we have roles now, other ppl may use this script ;-)
     $templateuser = $USER;
     // upload settings and file
     $mform->addElement('header', 'settingsheader', get_string('settings'));
     $choices = array(UU_USER_ADDNEW => get_string('uuoptype_addnew', 'tool_uploaduser'), UU_USER_ADDINC => get_string('uuoptype_addinc', 'tool_uploaduser'), UU_USER_ADD_UPDATE => get_string('uuoptype_addupdate', 'tool_uploaduser'), UU_USER_UPDATE => get_string('uuoptype_update', 'tool_uploaduser'));
     $mform->addElement('select', 'uutype', get_string('uuoptype', 'tool_uploaduser'), $choices);
     $choices = array(0 => get_string('infilefield', 'auth'), 1 => get_string('createpasswordifneeded', 'auth'));
     $mform->addElement('select', 'uupasswordnew', get_string('uupasswordnew', 'tool_uploaduser'), $choices);
     $mform->setDefault('uupasswordnew', 1);
     $mform->disabledIf('uupasswordnew', 'uutype', 'eq', UU_USER_UPDATE);
     $choices = array(UU_UPDATE_NOCHANGES => get_string('nochanges', 'tool_uploaduser'), UU_UPDATE_FILEOVERRIDE => get_string('uuupdatefromfile', 'tool_uploaduser'), UU_UPDATE_ALLOVERRIDE => get_string('uuupdateall', 'tool_uploaduser'), UU_UPDATE_MISSING => get_string('uuupdatemissing', 'tool_uploaduser'));
     $mform->addElement('select', 'uuupdatetype', get_string('uuupdatetype', 'tool_uploaduser'), $choices);
     $mform->setDefault('uuupdatetype', UU_UPDATE_NOCHANGES);
     $mform->disabledIf('uuupdatetype', 'uutype', 'eq', UU_USER_ADDNEW);
     $mform->disabledIf('uuupdatetype', 'uutype', 'eq', UU_USER_ADDINC);
     $choices = array(0 => get_string('nochanges', 'tool_uploaduser'), 1 => get_string('update'));
     $mform->addElement('select', 'uupasswordold', get_string('uupasswordold', 'tool_uploaduser'), $choices);
     $mform->setDefault('uupasswordold', 0);
     $mform->disabledIf('uupasswordold', 'uutype', 'eq', UU_USER_ADDNEW);
     $mform->disabledIf('uupasswordold', 'uutype', 'eq', UU_USER_ADDINC);
     $mform->disabledIf('uupasswordold', 'uuupdatetype', 'eq', 0);
     $mform->disabledIf('uupasswordold', 'uuupdatetype', 'eq', 3);
     $choices = array(UU_PWRESET_WEAK => get_string('usersweakpassword', 'tool_uploaduser'), UU_PWRESET_NONE => get_string('none'), UU_PWRESET_ALL => get_string('all'));
     if (empty($CFG->passwordpolicy)) {
         unset($choices[UU_PWRESET_WEAK]);
     }
     $mform->addElement('select', 'uuforcepasswordchange', get_string('forcepasswordchange', 'core'), $choices);
     $mform->addElement('selectyesno', 'uuallowrenames', get_string('allowrenames', 'tool_uploaduser'));
     $mform->setDefault('uuallowrenames', 0);
     $mform->disabledIf('uuallowrenames', 'uutype', 'eq', UU_USER_ADDNEW);
     $mform->disabledIf('uuallowrenames', 'uutype', 'eq', UU_USER_ADDINC);
     $mform->addElement('selectyesno', 'uuallowdeletes', get_string('allowdeletes', 'tool_uploaduser'));
     $mform->setDefault('uuallowdeletes', 0);
     $mform->disabledIf('uuallowdeletes', 'uutype', 'eq', UU_USER_ADDNEW);
     $mform->disabledIf('uuallowdeletes', 'uutype', 'eq', UU_USER_ADDINC);
     $mform->addElement('selectyesno', 'uuallowsuspends', get_string('allowsuspends', 'tool_uploaduser'));
     $mform->setDefault('uuallowsuspends', 1);
     $mform->disabledIf('uuallowsuspends', 'uutype', 'eq', UU_USER_ADDNEW);
     $mform->disabledIf('uuallowsuspends', 'uutype', 'eq', UU_USER_ADDINC);
     if (!empty($CFG->allowaccountssameemail)) {
         $mform->addElement('selectyesno', 'uunoemailduplicates', get_string('uunoemailduplicates', 'tool_uploaduser'));
         $mform->setDefault('uunoemailduplicates', 1);
     } else {
         $mform->addElement('hidden', 'uunoemailduplicates', 1);
     }
     $mform->setType('uunoemailduplicates', PARAM_BOOL);
     $mform->addElement('selectyesno', 'uustandardusernames', get_string('uustandardusernames', 'tool_uploaduser'));
     $mform->setDefault('uustandardusernames', 1);
     $choices = array(UU_BULK_NONE => get_string('no'), UU_BULK_NEW => get_string('uubulknew', 'tool_uploaduser'), UU_BULK_UPDATED => get_string('uubulkupdated', 'tool_uploaduser'), UU_BULK_ALL => get_string('uubulkall', 'tool_uploaduser'));
     $mform->addElement('select', 'uubulk', get_string('uubulk', 'tool_uploaduser'), $choices);
     $mform->setDefault('uubulk', 0);
     // roles selection
     $showroles = false;
     foreach ($columns as $column) {
         if (preg_match('/^type\\d+$/', $column)) {
             $showroles = true;
             break;
         }
     }
     if ($showroles) {
         $mform->addElement('header', 'rolesheader', get_string('roles'));
         $choices = uu_allowed_roles(true);
         $mform->addElement('select', 'uulegacy1', get_string('uulegacy1role', 'tool_uploaduser'), $choices);
         if ($studentroles = get_archetype_roles('student')) {
             foreach ($studentroles as $role) {
                 if (isset($choices[$role->id])) {
                     $mform->setDefault('uulegacy1', $role->id);
                     break;
                 }
             }
             unset($studentroles);
         }
         $mform->addElement('select', 'uulegacy2', get_string('uulegacy2role', 'tool_uploaduser'), $choices);
         if ($editteacherroles = get_archetype_roles('editingteacher')) {
             foreach ($editteacherroles as $role) {
                 if (isset($choices[$role->id])) {
                     $mform->setDefault('uulegacy2', $role->id);
                     break;
                 }
             }
             unset($editteacherroles);
         }
         $mform->addElement('select', 'uulegacy3', get_string('uulegacy3role', 'tool_uploaduser'), $choices);
         if ($teacherroles = get_archetype_roles('teacher')) {
             foreach ($teacherroles as $role) {
                 if (isset($choices[$role->id])) {
                     $mform->setDefault('uulegacy3', $role->id);
                     break;
                 }
             }
             unset($teacherroles);
         }
     }
     // default values
     $mform->addElement('header', 'defaultheader', get_string('defaultvalues', 'tool_uploaduser'));
     $mform->addElement('text', 'username', get_string('uuusernametemplate', 'tool_uploaduser'), 'size="20"');
     $mform->setType('username', PARAM_RAW);
     // No cleaning here. The process verifies it later.
     $mform->addRule('username', get_string('requiredtemplate', 'tool_uploaduser'), 'required', null, 'client');
     $mform->disabledIf('username', 'uutype', 'eq', UU_USER_ADD_UPDATE);
     $mform->disabledIf('username', 'uutype', 'eq', UU_USER_UPDATE);
     $mform->setForceLtr('username');
     $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"');
     $mform->setType('email', PARAM_RAW);
     // No cleaning here. The process verifies it later.
     $mform->disabledIf('email', 'uutype', 'eq', UU_USER_ADD_UPDATE);
     $mform->disabledIf('email', 'uutype', 'eq', UU_USER_UPDATE);
     $mform->setForceLtr('email');
     // only enabled and known to work plugins
     $choices = uu_supported_auths();
     $mform->addElement('select', 'auth', get_string('chooseauthmethod', 'auth'), $choices);
     $mform->setDefault('auth', 'manual');
     // manual is a sensible backwards compatible default
     $mform->addHelpButton('auth', 'chooseauthmethod', 'auth');
     $mform->setAdvanced('auth');
     $choices = array(0 => get_string('emaildisplayno'), 1 => get_string('emaildisplayyes'), 2 => get_string('emaildisplaycourse'));
     $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
     $mform->setDefault('maildisplay', core_user::get_property_default('maildisplay'));
     $choices = array(0 => get_string('textformat'), 1 => get_string('htmlformat'));
     $mform->addElement('select', 'mailformat', get_string('emailformat'), $choices);
     $mform->setDefault('mailformat', core_user::get_property_default('mailformat'));
     $mform->setAdvanced('mailformat');
     $choices = array(0 => get_string('emaildigestoff'), 1 => get_string('emaildigestcomplete'), 2 => get_string('emaildigestsubjects'));
     $mform->addElement('select', 'maildigest', get_string('emaildigest'), $choices);
     $mform->setDefault('maildigest', core_user::get_property_default('maildigest'));
     $mform->setAdvanced('maildigest');
     $choices = array(1 => get_string('autosubscribeyes'), 0 => get_string('autosubscribeno'));
     $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
     $mform->setDefault('autosubscribe', core_user::get_property_default('autosubscribe'));
     $mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="25"');
     $mform->setType('city', PARAM_TEXT);
     if (empty($CFG->defaultcity)) {
         $mform->setDefault('city', $templateuser->city);
     } else {
         $mform->setDefault('city', core_user::get_property_default('city'));
     }
     $choices = get_string_manager()->get_list_of_countries();
     $choices = array('' => get_string('selectacountry') . '...') + $choices;
     $mform->addElement('select', 'country', get_string('selectacountry'), $choices);
     if (empty($CFG->country)) {
         $mform->setDefault('country', $templateuser->country);
     } else {
         $mform->setDefault('country', core_user::get_property_default('country'));
     }
     $mform->setAdvanced('country');
     $choices = core_date::get_list_of_timezones($templateuser->timezone, true);
     $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
     $mform->setDefault('timezone', $templateuser->timezone);
     $mform->setAdvanced('timezone');
     $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations());
     $mform->setDefault('lang', $templateuser->lang);
     $mform->setAdvanced('lang');
     $editoroptions = array('maxfiles' => 0, 'maxbytes' => 0, 'trusttext' => false, 'forcehttps' => false);
     $mform->addElement('editor', 'description', get_string('userdescription'), null, $editoroptions);
     $mform->setType('description', PARAM_CLEANHTML);
     $mform->addHelpButton('description', 'userdescription');
     $mform->setAdvanced('description');
     $mform->addElement('text', 'url', get_string('webpage'), 'maxlength="255" size="50"');
     $mform->setType('url', PARAM_URL);
     $mform->setAdvanced('url');
     $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
     $mform->setType('idnumber', PARAM_NOTAGS);
     $mform->setForceLtr('idnumber');
     $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="255" size="25"');
     $mform->setType('institution', PARAM_TEXT);
     $mform->setDefault('institution', $templateuser->institution);
     $mform->addElement('text', 'department', get_string('department'), 'maxlength="255" size="25"');
     $mform->setType('department', PARAM_TEXT);
     $mform->setDefault('department', $templateuser->department);
     $mform->addElement('text', 'phone1', get_string('phone1'), 'maxlength="20" size="25"');
     $mform->setType('phone1', PARAM_NOTAGS);
     $mform->setAdvanced('phone1');
     $mform->setForceLtr('phone1');
     $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
     $mform->setType('phone2', PARAM_NOTAGS);
     $mform->setAdvanced('phone2');
     $mform->setForceLtr('phone2');
     $mform->addElement('text', 'address', get_string('address'), 'maxlength="255" size="25"');
     $mform->setType('address', PARAM_TEXT);
     $mform->setAdvanced('address');
     // Next the profile defaults
     profile_definition($mform);
     // hidden fields
     $mform->addElement('hidden', 'iid');
     $mform->setType('iid', PARAM_INT);
     $mform->addElement('hidden', 'previewrows');
     $mform->setType('previewrows', PARAM_INT);
     $this->add_action_buttons(true, get_string('uploadusers', 'tool_uploaduser'));
     $this->set_data($data);
 }
Example #7
0
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
/**
 * Cohort enrolment plugin settings and default values
 *
 * @package    enrol_mnet
 * @copyright  2010 David Mudrak <*****@*****.**>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
defined('MOODLE_INTERNAL') || die;
if ($ADMIN->fulltree) {
    //--- general settings -----------------------------------------------------------------------------------
    $settings->add(new admin_setting_heading('enrol_mnet_settings', '', get_string('pluginname_desc', 'enrol_mnet')));
    //--- enrol instance defaults ----------------------------------------------------------------------------
    if (!during_initial_install()) {
        $options = get_default_enrol_roles(context_system::instance());
        $student = get_archetype_roles('student');
        $student = reset($student);
        $settings->add(new admin_setting_configselect_with_advanced('enrol_mnet/roleid', get_string('defaultrole', 'role'), '', array('value' => $student->id, 'adv' => true), $options));
    }
}
Example #8
0
 /**
  * Sync roles for this user
  *
  * @param $user object user object (without system magic quotes)
  */
 function sync_roles($user)
 {
     $iscreator = $this->iscreator($user->username);
     if ($iscreator === null) {
         return;
         // Nothing to sync - creators not configured
     }
     if ($roles = get_archetype_roles('coursecreator')) {
         $creatorrole = array_shift($roles);
         // We can only use one, let's use the first one
         $systemcontext = context_system::instance();
         if ($iscreator) {
             // Following calls will not create duplicates
             role_assign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
         } else {
             // Unassign only if previously assigned by this plugin!
             role_unassign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
         }
     }
 }
Example #9
0
 /**
  * @expectedException        require_login_exception
  * @expectedExceptionMessage Activity is hidden
  */
 public function test_view_glossary_without_permission()
 {
     $this->resetAfterTest(true);
     // Generate all the things.
     $c1 = $this->getDataGenerator()->create_course();
     $g1 = $this->getDataGenerator()->create_module('glossary', array('course' => $c1->id));
     $u1 = $this->getDataGenerator()->create_user();
     $this->getDataGenerator()->enrol_user($u1->id, $c1->id);
     $ctx = context_module::instance($g1->cmid);
     // Revoke permission.
     $roles = get_archetype_roles('user');
     $role = array_shift($roles);
     assign_capability('mod/glossary:view', CAP_PROHIBIT, $role->id, $ctx, true);
     accesslib_clear_all_caches_for_unit_testing();
     // Assertion.
     $this->setUser($u1);
     mod_glossary_external::view_glossary($g1->id, 'letter');
 }
 /**
  * push in grouptool registered users to moodle-groups
  *
  * @param int $groupid optional only for this group
  * @param int $groupingid optional only for this grouping
  * @param bool $previewonly optional get only the preview
  * @return array($error, $message)
  */
 public function push_registrations($groupid = 0, $groupingid = 0, $previewonly = false)
 {
     global $DB, $CFG;
     // Trigger the event!
     \mod_grouptool\event\registration_push_started::create_from_object($this->cm)->trigger();
     $userinfo = get_enrolled_users($this->context);
     $return = array();
     // Get active groups filtered by groupid, grouping_id, grouptoolid!
     $agrps = $this->get_active_groups(true, false, 0, $groupid, $groupingid);
     foreach ($agrps as $groupid => $agrp) {
         foreach ($agrp->registered as $reg) {
             $info = new stdClass();
             if (!key_exists($reg->userid, $userinfo)) {
                 $userinfo[$reg->userid] = $DB->get_record('user', array('id' => $reg->userid));
             }
             $info->username = fullname($userinfo[$reg->userid]);
             $info->groupname = $agrp->name;
             if (!groups_is_member($groupid, $reg->userid)) {
                 // Add to group if is not already!
                 if (!$previewonly) {
                     if (!is_enrolled($this->context, $reg->userid)) {
                         /*
                          * if user's not enrolled already we force manual enrollment in course,
                          * so we can add the user to the group
                          */
                         require_once $CFG->dirroot . '/enrol/manual/locallib.php';
                         require_once $CFG->libdir . '/accesslib.php';
                         if (!($enrolmanual = enrol_get_plugin('manual'))) {
                             throw new coding_exception('Can not instantiate enrol_manual');
                         }
                         if (!($instance = $DB->get_record('enrol', array('courseid' => $this->course->id, 'enrol' => 'manual'), '*', IGNORE_MISSING))) {
                             if ($instanceid = $enrolmanual->add_default_instance($this->course)) {
                                 $instance = $DB->get_record('enrol', array('courseid' => $this->course->id, 'enrol' => 'manual'), '*', MUST_EXIST);
                             }
                         }
                         if ($instance != false) {
                             $archroles = get_archetype_roles('student');
                             $archrole = array_shift($archroles);
                             $enrolmanual->enrol_user($instance, $reg->userid, $archrole->id, time());
                         } else {
                             $message .= html_writer::tag('div', $OUTPUT->notification(get_string('cant_enrol', 'grouptool'), 'notifyproblem'));
                         }
                     }
                     if (groups_add_member($groupid, $reg->userid)) {
                         $return[] = html_writer::tag('div', get_string('added_member', 'grouptool', $info), array('class' => 'notifysuccess'));
                     } else {
                         $return[] = html_writer::tag('div', get_string('could_not_add', 'grouptool', $info), array('class' => 'notifyproblem'));
                     }
                 } else {
                     $return[] = html_writer::tag('div', get_string('add_member', 'grouptool', $info), array('class' => 'notifysuccess'));
                 }
             } else {
                 $return[] = html_writer::tag('div', get_string('already_member', 'grouptool', $info), array('class' => 'ignored'));
             }
         }
     }
     switch (count($return)) {
         default:
             return array(false, implode("<br />\n", $return));
             break;
         case 1:
             return array(false, current($return));
             break;
         case 0:
             return array(true, get_string('nothing_to_push', 'grouptool'));
             break;
     }
 }
Example #11
0
 function load_defaults()
 {
     global $CFG, $COURSE, $DB;
     $mform =& $this->_form;
     $defaults = array('reset_events' => 1, 'reset_roles_local' => 1, 'reset_gradebook_grades' => 1, 'reset_notes' => 1);
     // Set student as default in unenrol user list, if role with student archetype exist.
     if ($studentrole = get_archetype_roles('student')) {
         $defaults['unenrol_users'] = array_keys($studentrole);
     }
     if ($allmods = $DB->get_records('modules')) {
         foreach ($allmods as $mod) {
             $modname = $mod->name;
             $modfile = $CFG->dirroot . "/mod/{$modname}/lib.php";
             $mod_reset_course_form_defaults = $modname . '_reset_course_form_defaults';
             if (file_exists($modfile)) {
                 @(include_once $modfile);
                 if (function_exists($mod_reset_course_form_defaults)) {
                     if ($moddefs = $mod_reset_course_form_defaults($COURSE)) {
                         $defaults = $defaults + $moddefs;
                     }
                 }
             }
         }
     }
     foreach ($defaults as $element => $default) {
         $mform->setDefault($element, $default);
     }
 }
Example #12
0
 /**
  * Setup function- we will create a course and add an assign instance to it.
  */
 protected function setUp()
 {
     global $DB;
     $this->resetAfterTest(true);
     // Create some users.
     $creator = $this->getDataGenerator()->create_user();
     $user = $this->getDataGenerator()->create_user();
     $catuser = $this->getDataGenerator()->create_user();
     $category = $this->getDataGenerator()->create_category();
     $othercategory = $this->getDataGenerator()->create_category();
     $catcreator = $this->getDataGenerator()->create_user();
     $syscontext = context_system::instance();
     $catcontext = context_coursecat::instance($category->id);
     $othercatcontext = context_coursecat::instance($othercategory->id);
     // Fetching default authenticated user role.
     $userroles = get_archetype_roles('user');
     $this->assertCount(1, $userroles);
     $authrole = array_pop($userroles);
     // Reset all default authenticated users permissions.
     unassign_capability('moodle/competency:competencygrade', $authrole->id);
     unassign_capability('moodle/competency:competencymanage', $authrole->id);
     unassign_capability('moodle/competency:competencyview', $authrole->id);
     unassign_capability('moodle/competency:planmanage', $authrole->id);
     unassign_capability('moodle/competency:planmanagedraft', $authrole->id);
     unassign_capability('moodle/competency:planmanageown', $authrole->id);
     unassign_capability('moodle/competency:planview', $authrole->id);
     unassign_capability('moodle/competency:planviewdraft', $authrole->id);
     unassign_capability('moodle/competency:planviewown', $authrole->id);
     unassign_capability('moodle/competency:planviewowndraft', $authrole->id);
     unassign_capability('moodle/competency:templatemanage', $authrole->id);
     unassign_capability('moodle/competency:templateview', $authrole->id);
     unassign_capability('moodle/cohort:manage', $authrole->id);
     unassign_capability('moodle/competency:coursecompetencyconfigure', $authrole->id);
     // Creating specific roles.
     $this->creatorrole = create_role('Creator role', 'creatorrole', 'learning plan creator role description');
     $this->userrole = create_role('User role', 'userrole', 'learning plan user role description');
     assign_capability('moodle/competency:competencymanage', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:competencycompetencyconfigure', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:competencyview', CAP_ALLOW, $this->userrole, $syscontext->id);
     assign_capability('moodle/competency:planmanage', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:planmanagedraft', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:planmanageown', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:planview', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:planviewdraft', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:templatemanage', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:competencygrade', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/cohort:manage', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:templateview', CAP_ALLOW, $this->userrole, $syscontext->id);
     assign_capability('moodle/competency:planviewown', CAP_ALLOW, $this->userrole, $syscontext->id);
     assign_capability('moodle/competency:planviewowndraft', CAP_ALLOW, $this->userrole, $syscontext->id);
     role_assign($this->creatorrole, $creator->id, $syscontext->id);
     role_assign($this->creatorrole, $catcreator->id, $catcontext->id);
     role_assign($this->userrole, $user->id, $syscontext->id);
     role_assign($this->userrole, $catuser->id, $catcontext->id);
     $this->creator = $creator;
     $this->catcreator = $catcreator;
     $this->user = $user;
     $this->catuser = $catuser;
     $this->category = $category;
     $this->othercategory = $othercategory;
     $this->getDataGenerator()->create_scale(array("id" => "1", "scale" => "value1, value2"));
     $this->getDataGenerator()->create_scale(array("id" => "2", "scale" => "value3, value4"));
     $this->getDataGenerator()->create_scale(array("id" => "3", "scale" => "value5, value6"));
     $this->getDataGenerator()->create_scale(array("id" => "4", "scale" => "value7, value8"));
     $this->scaleconfiguration1 = '[{"scaleid":"1"},{"name":"value1","id":1,"scaledefault":1,"proficient":0},' . '{"name":"value2","id":2,"scaledefault":0,"proficient":1}]';
     $this->scaleconfiguration2 = '[{"scaleid":"2"},{"name":"value3","id":1,"scaledefault":1,"proficient":0},' . '{"name":"value4","id":2,"scaledefault":0,"proficient":1}]';
     $this->scaleconfiguration3 = '[{"scaleid":"3"},{"name":"value5","id":1,"scaledefault":1,"proficient":0},' . '{"name":"value6","id":2,"scaledefault":0,"proficient":1}]';
     $this->scaleconfiguration4 = '[{"scaleid":"4"},{"name":"value8","id":1,"scaledefault":1,"proficient":0},' . '{"name":"value8","id":2,"scaledefault":0,"proficient":1}]';
     accesslib_clear_all_caches_for_unit_testing();
 }
Example #13
0
 /**
  * Setup function- we will create a course and add an assign instance to it.
  */
 protected function setUp()
 {
     global $DB;
     $this->resetAfterTest(true);
     // Create some users.
     $creator = $this->getDataGenerator()->create_user();
     $user = $this->getDataGenerator()->create_user();
     $catuser = $this->getDataGenerator()->create_user();
     $catcreator = $this->getDataGenerator()->create_user();
     $category = $this->getDataGenerator()->create_category();
     $othercategory = $this->getDataGenerator()->create_category();
     $syscontext = context_system::instance();
     $catcontext = context_coursecat::instance($category->id);
     // Fetching default authenticated user role.
     $userroles = get_archetype_roles('user');
     $this->assertCount(1, $userroles);
     $authrole = array_pop($userroles);
     // Reset all default authenticated users permissions.
     unassign_capability('moodle/competency:competencygrade', $authrole->id);
     unassign_capability('moodle/competency:competencymanage', $authrole->id);
     unassign_capability('moodle/competency:competencyview', $authrole->id);
     unassign_capability('moodle/competency:planmanage', $authrole->id);
     unassign_capability('moodle/competency:planmanagedraft', $authrole->id);
     unassign_capability('moodle/competency:planmanageown', $authrole->id);
     unassign_capability('moodle/competency:planview', $authrole->id);
     unassign_capability('moodle/competency:planviewdraft', $authrole->id);
     unassign_capability('moodle/competency:planviewown', $authrole->id);
     unassign_capability('moodle/competency:planviewowndraft', $authrole->id);
     unassign_capability('moodle/competency:templatemanage', $authrole->id);
     unassign_capability('moodle/competency:templateview', $authrole->id);
     unassign_capability('moodle/cohort:manage', $authrole->id);
     unassign_capability('moodle/competency:coursecompetencyconfigure', $authrole->id);
     // Creating specific roles.
     $this->creatorrole = create_role('Creator role', 'lpcreatorrole', 'learning plan creator role description');
     $this->userrole = create_role('User role', 'lpuserrole', 'learning plan user role description');
     assign_capability('moodle/competency:competencymanage', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:competencycompetencyconfigure', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:planmanage', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:planmanagedraft', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:planmanageown', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:planview', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:planviewdraft', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:templatemanage', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:competencygrade', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/cohort:manage', CAP_ALLOW, $this->creatorrole, $syscontext->id);
     assign_capability('moodle/competency:competencyview', CAP_ALLOW, $this->userrole, $syscontext->id);
     assign_capability('moodle/competency:templateview', CAP_ALLOW, $this->userrole, $syscontext->id);
     assign_capability('moodle/competency:planviewown', CAP_ALLOW, $this->userrole, $syscontext->id);
     assign_capability('moodle/competency:planviewowndraft', CAP_ALLOW, $this->userrole, $syscontext->id);
     role_assign($this->creatorrole, $creator->id, $syscontext->id);
     role_assign($this->creatorrole, $catcreator->id, $catcontext->id);
     role_assign($this->userrole, $user->id, $syscontext->id);
     role_assign($this->userrole, $catuser->id, $catcontext->id);
     $this->creator = $creator;
     $this->catcreator = $catcreator;
     $this->user = $user;
     $this->catuser = $catuser;
     $this->category = $category;
     $this->othercategory = $othercategory;
     accesslib_clear_all_caches_for_unit_testing();
 }
Example #14
0
    function definition (){
        global $CFG, $USER;

        $mform   =& $this->_form;
        $columns =& $this->_customdata;

        // I am the template user, why should it be the administrator? we have roles now, other ppl may use this script ;-)
        $templateuser = $USER;

        // upload settings and file
        $mform->addElement('header', 'settingsheader', get_string('settings'));
        $mform->addElement('static', 'uutypelabel', get_string('uuoptype', 'admin') );

        $choices = array(0 => get_string('infilefield', 'auth'), 1 => get_string('createpasswordifneeded', 'auth'));
        $mform->addElement('select', 'uupasswordnew', get_string('uupasswordnew', 'admin'), $choices);
        $mform->setDefault('uupasswordnew', 1);
        $mform->disabledIf('uupasswordnew', 'uutype', 'eq', UU_UPDATE);

        $choices = array(0 => get_string('nochanges', 'admin'),
                         1 => get_string('uuupdatefromfile', 'admin'),
                         2 => get_string('uuupdateall', 'admin'),
                         3 => get_string('uuupdatemissing', 'admin'));
        $mform->addElement('select', 'uuupdatetype', get_string('uuupdatetype', 'admin'), $choices);
        $mform->setDefault('uuupdatetype', 0);
        $mform->disabledIf('uuupdatetype', 'uutype', 'eq', UU_ADDNEW);
        $mform->disabledIf('uuupdatetype', 'uutype', 'eq', UU_ADDINC);

        $choices = array(0 => get_string('nochanges', 'admin'), 1 => get_string('update'));
        $mform->addElement('select', 'uupasswordold', get_string('uupasswordold', 'admin'), $choices);
        $mform->setDefault('uupasswordold', 0);
        $mform->disabledIf('uupasswordold', 'uutype', 'eq', UU_ADDNEW);
        $mform->disabledIf('uupasswordold', 'uutype', 'eq', UU_ADDINC);
        $mform->disabledIf('uupasswordold', 'uuupdatetype', 'eq', 0);
        $mform->disabledIf('uupasswordold', 'uuupdatetype', 'eq', 3);

        $mform->addElement('selectyesno', 'uuallowrenames', get_string('allowrenames', 'admin'));
        $mform->setDefault('uuallowrenames', 0);
        $mform->disabledIf('uuallowrenames', 'uutype', 'eq', UU_ADDNEW);
        $mform->disabledIf('uuallowrenames', 'uutype', 'eq', UU_ADDINC);

        $mform->addElement('selectyesno', 'uuallowdeletes', get_string('allowdeletes', 'admin'));
        $mform->setDefault('uuallowdeletes', 0);
        $mform->disabledIf('uuallowdeletes', 'uutype', 'eq', UU_ADDNEW);
        $mform->disabledIf('uuallowdeletes', 'uutype', 'eq', UU_ADDINC);

        $mform->addElement('selectyesno', 'uunoemailduplicates', get_string('uunoemailduplicates', 'admin'));
        $mform->setDefault('uunoemailduplicates', 1);

        $choices = array(0 => get_string('no'),
                         1 => get_string('uubulknew', 'admin'),
                         2 => get_string('uubulkupdated', 'admin'),
                         3 => get_string('uubulkall', 'admin'));
        $mform->addElement('select', 'uubulk', get_string('uubulk', 'admin'), $choices);
        $mform->setDefault('uubulk', 0);

        // roles selection
        $showroles = false;
        foreach ($columns as $column) {
            if (preg_match('/^type\d+$/', $column)) {
                $showroles = true;
                break;
            }
        }
        if ($showroles) {
            $mform->addElement('header', 'rolesheader', get_string('roles'));

            $choices = uu_allowed_roles(true);

            $mform->addElement('select', 'uulegacy1', get_string('uulegacy1role', 'admin'), $choices);
            if ($studentroles = get_archetype_roles('student')) {
                foreach ($studentroles as $role) {
                    if (isset($choices[$role->id])) {
                        $mform->setDefault('uulegacy1', $role->id);
                        break;
                    }
                }
                unset($studentroles);
            }

            $mform->addElement('select', 'uulegacy2', get_string('uulegacy2role', 'admin'), $choices);
            if ($editteacherroles = get_archetype_roles('editingteacher')) {
                foreach ($editteacherroles as $role) {
                    if (isset($choices[$role->id])) {
                        $mform->setDefault('uulegacy2', $role->id);
                        break;
                    }
                }
                unset($editteacherroles);
            }

            $mform->addElement('select', 'uulegacy3', get_string('uulegacy3role', 'admin'), $choices);
            if ($teacherroles = get_archetype_roles('teacher')) {
                foreach ($teacherroles as $role) {
                    if (isset($choices[$role->id])) {
                        $mform->setDefault('uulegacy3', $role->id);
                        break;
                    }
                }
                unset($teacherroles);
            }
        }

        // default values
        $mform->addElement('header', 'defaultheader', get_string('defaultvalues', 'admin'));

        $mform->addElement('text', 'username', get_string('username'), 'size="20"');
        $mform->addRule('username', get_string('requiredtemplate', 'admin'), 'required', null, 'client');

        // only enabled and known to work plugins
        $choices = uu_allowed_auths();
        $mform->addElement('select', 'auth', get_string('chooseauthmethod','auth'), $choices);
        $mform->setDefault('auth', 'manual'); // manual is a sensible backwards compatible default
        $mform->addHelpButton('auth', 'chooseauthmethod', 'auth');
        $mform->setAdvanced('auth');

        $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"');

        $choices = array(0 => get_string('emaildisplayno'), 1 => get_string('emaildisplayyes'), 2 => get_string('emaildisplaycourse'));
        $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
        $mform->setDefault('maildisplay', 2);

        $choices = array(0 => get_string('textformat'), 1 => get_string('htmlformat'));
        $mform->addElement('select', 'mailformat', get_string('emailformat'), $choices);
        $mform->setDefault('mailformat', 1);
        $mform->setAdvanced('mailformat');

        $choices = array(0 => get_string('emaildigestoff'), 1 => get_string('emaildigestcomplete'), 2 => get_string('emaildigestsubjects'));
        $mform->addElement('select', 'maildigest', get_string('emaildigest'), $choices);
        $mform->setDefault('maildigest', 0);
        $mform->setAdvanced('maildigest');

        $choices = array(0 => get_string('autosubscribeyes'), 1 => get_string('autosubscribeno'));
        $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
        $mform->setDefault('autosubscribe', 1);

        $editors = editors_get_enabled();
        if (count($editors) > 1) {
            $choices = array();
            $choices['0'] = get_string('texteditor');
            $choices['1'] = get_string('htmleditor');
            $mform->addElement('select', 'htmleditor', get_string('textediting'), $choices);
            $mform->setDefault('htmleditor', 1);
        } else {
            $mform->addElement('hidden', 'htmleditor');
            $mform->setDefault('htmleditor', 1);
            $mform->setType('htmleditor', PARAM_INT);
        }

        if (empty($CFG->enableajax)) {
            $mform->addElement('static', 'ajax', get_string('ajaxuse'), get_string('ajaxno'));
        } else {
            $choices = array( 0 => get_string('ajaxno'), 1 => get_string('ajaxyes'));
            $mform->addElement('select', 'ajax', get_string('ajaxuse'), $choices);
            $mform->setDefault('ajax', 1);
        }
        $mform->setAdvanced('ajax');

        $mform->addElement('text', 'city', get_string('city'), 'maxlength="100" size="25"');
        $mform->setType('city', PARAM_MULTILANG);
        if (empty($CFG->defaultcity)) {
            $mform->setDefault('city', $templateuser->city);
        } else {
            $mform->setDefault('city', $CFG->defaultcity);
        }

        $mform->addElement('select', 'country', get_string('selectacountry'), get_string_manager()->get_list_of_countries());
        if (empty($CFG->country)) {
            $mform->setDefault('country', $templateuser->country);
        } else {
            $mform->setDefault('country', $CFG->country);
        }
        $mform->setAdvanced('country');

        $choices = get_list_of_timezones();
        $choices['99'] = get_string('serverlocaltime');
        $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
        $mform->setDefault('timezone', $templateuser->timezone);
        $mform->setAdvanced('timezone');

        $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations());
        $mform->setDefault('lang', $templateuser->lang);
        $mform->setAdvanced('lang');

        $editoroptions = array('maxfiles'=>0, 'maxbytes'=>0, 'trusttext'=>false, 'forcehttps'=>false);
        $mform->addElement('editor', 'description', get_string('userdescription'), null, $editoroptions);
        $mform->setType('description', PARAM_CLEANHTML);
        $mform->addHelpButton('description', 'userdescription');
        $mform->setAdvanced('description');

        $mform->addElement('text', 'url', get_string('webpage'), 'maxlength="255" size="50"');
        $mform->setAdvanced('url');

        $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="64" size="25"');
        $mform->setType('idnumber', PARAM_NOTAGS);

        $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="40" size="25"');
        $mform->setType('institution', PARAM_MULTILANG);
        $mform->setDefault('institution', $templateuser->institution);

        $mform->addElement('text', 'department', get_string('department'), 'maxlength="30" size="25"');
        $mform->setType('department', PARAM_MULTILANG);
        $mform->setDefault('department', $templateuser->department);

        $mform->addElement('text', 'phone1', get_string('phone'), 'maxlength="20" size="25"');
        $mform->setType('phone1', PARAM_NOTAGS);
        $mform->setAdvanced('phone1');

        $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
        $mform->setType('phone2', PARAM_NOTAGS);
        $mform->setAdvanced('phone2');

        $mform->addElement('text', 'address', get_string('address'), 'maxlength="70" size="25"');
        $mform->setType('address', PARAM_MULTILANG);
        $mform->setAdvanced('address');

        // Next the profile defaults
        profile_definition($mform);

        // hidden fields
        $mform->addElement('hidden', 'iid');
        $mform->setType('iid', PARAM_INT);

        $mform->addElement('hidden', 'previewrows');
        $mform->setType('previewrows', PARAM_INT);

        $mform->addElement('hidden', 'readcount');
        $mform->setType('readcount', PARAM_INT);

        $mform->addElement('hidden', 'uutype');
        $mform->setType('uutype', PARAM_INT);

        $this->add_action_buttons(true, get_string('uploadusers', 'admin'));
    }
Example #15
0
/**
 * Syncronizes user from external LDAP server to moodle user table
 *
 * Sync is now using username attribute.
 *
 * Syncing users removes or suspends users that dont exists anymore in external LDAP.
 * Creates new users and updates coursecreator status of users.
 *
 * @param bool $do_updates will do pull in data updates from LDAP if relevant
 */
function local_ent_installer_sync_users($ldapauth, $options)
{
    global $CFG, $DB, $MATCH_STATUS;
    mtrace('');
    $enable = get_config('local_ent_installer', 'sync_enable');
    if (!$enable) {
        mtrace(get_string('syncdisabled', 'local_ent_installer'));
        return;
    }
    $USERFIELDS = local_ent_installer_load_user_fields();
    $lastrun = get_config('local_ent_installer', 'last_sync_date');
    mtrace(get_string('lastrun', 'local_ent_installer', userdate($lastrun)));
    mtrace(get_string('connectingldap', 'auth_ldap'));
    if (isset($CFG->auth_ldap_sync_user_type)) {
        $ldapauth->config->user_type = $CFG->auth_ldap_sync_user_type;
    }
    if (isset($CFG->auth_ldap_sync_search_contexts)) {
        $ldapauth->config->contexts = $CFG->auth_ldap_sync_search_contexts;
    }
    $ldapconnection = $ldapauth->ldap_connect();
    $dbman = $DB->get_manager();
    list($usec, $sec) = explode(' ', microtime());
    $starttick = (double) $sec + (double) $usec;
    // Define table user to be created.
    $table = new xmldb_table('tmp_extuser');
    $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
    $table->add_field('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
    $table->add_field('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
    $table->add_field('usertype', XMLDB_TYPE_CHAR, '16', null, null, null, null);
    $table->add_field('lastmodified', XMLDB_TYPE_INTEGER, '11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
    $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
    $table->add_index('userprofile', XMLDB_INDEX_UNIQUE, array('mnethostid', 'username', 'usertype'));
    mtrace(get_string('creatingtemptable', 'auth_ldap', 'tmp_extuser'));
    if ($dbman->table_exists($table)) {
        $dbman->drop_table($table);
    }
    $dbman->create_temp_table($table);
    //
    // get user's list from ldap to sql in a scalable fashion from different user profiles
    // defined as LDAP filters
    //
    // prepare some data we'll need
    $filters = array();
    $institutionid = get_config('local_ent_installer', 'institution_id');
    // Students.
    if (empty($options['role']) || preg_match('/eleve/', $options['role'])) {
        $filterdef = new StdClass();
        $filterdef->institution = '(ENTPersonEtablissements=' . $institutionid . ')';
        $filterdef->usertype = '(ENTPersonProfils=Eleves)';
        $filterdef->userfield = 'eleve';
        $filters[] = $filterdef;
    }
    // Teaching staff.
    if (empty($options['role']) || preg_match('/enseignant/', $options['role'])) {
        $filterdef = new StdClass();
        $filterdef->institution = '(ENTPersonEtablissements=' . $institutionid . ')';
        $filterdef->usertype = '(|(ENTPersonProfils=Professeurs)(ENTPersonProfils=Documentalistes)(ENTPersonProfils=ProfesseursVacataires)(ENTPersonProfils=Inspecteur))';
        $filterdef->userfield = 'enseignant';
        $filters[] = $filterdef;
    }
    // Non teaching staff.
    if (empty($options['role']) || preg_match('/administration/', $options['role'])) {
        $filterdef = new StdClass();
        $filterdef->institution = '(ENTPersonEtablissements=' . $institutionid . ')';
        $filterdef->usertype = '(|(ENTPersonProfils=Administrateurs)(ENTPersonProfils=Direction)(ENTPersonProfils=PersonnelAdministratif)(ENTPersonProfils=PersonnelNonEnseignant)' . '(ENTPersonProfils=AdministrateurITOP)(ENTPersonProfils=PersonnelVieScolaire)(ENTPersonProfils=ATOS)(ENTPersonProfils=PersonnelRectorat)(ENTPersonProfils=MissionTice)' . '(ENTPersonProfils=TuteurEntreprise)(ENTPersonProfils=CollectivitesLocales)(ENTPersonProfils=AccompagnementEducatif)(ENTPersonProfils=CPE)(ENTPersonProfils=Invite)' . '(ENTPersonProfils=AdminProjet))';
        $filterdef->userfield = 'administration';
        $filters[] = $filterdef;
    }
    $contexts = explode(';', $ldapauth->config->contexts);
    if (!empty($ldapauth->config->create_context)) {
        array_push($contexts, $ldapauth->config->create_context);
    }
    $ldap_pagedresults = ldap_paged_results_supported($ldapauth->config->ldap_version);
    $ldap_cookie = '';
    foreach ($filters as $filterdef) {
        $filter = '(&(' . $ldapauth->config->user_attribute . '=*)' . $filterdef->usertype . $filterdef->institution . ')';
        foreach ($contexts as $context) {
            $context = trim($context);
            if (empty($context)) {
                continue;
            }
            do {
                if ($ldap_pagedresults) {
                    ldap_control_paged_result($ldapconnection, $ldapauth->config->pagesize, true, $ldap_cookie);
                }
                if ($ldapauth->config->search_sub) {
                    // Use ldap_search to find first user from subtree.
                    mtrace("ldapsearch {$context}, {$filter} for " . $ldapauth->config->user_attribute);
                    $ldap_result = ldap_search($ldapconnection, $context, $filter, array($ldapauth->config->user_attribute, 'whenChanged'));
                } else {
                    // Search only in this context.
                    mtrace("ldaplist {$context}, {$filter} for " . $ldapauth->config->user_attribute);
                    $ldap_result = ldap_list($ldapconnection, $context, $filter, array($ldapauth->config->user_attribute, 'whenChanged'));
                }
                if (!$ldap_result) {
                    continue;
                }
                if ($ldap_pagedresults) {
                    ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
                }
                if ($entry = @ldap_first_entry($ldapconnection, $ldap_result)) {
                    do {
                        $value = ldap_get_values_len($ldapconnection, $entry, $ldapauth->config->user_attribute);
                        $value = core_text::convert($value[0], $ldapauth->config->ldapencoding, 'utf-8');
                        $modify = ldap_get_values_len($ldapconnection, $entry, 'whenChanged');
                        // $modify = strtotime($modify[0]); // OpenLDAP version
                        if (preg_match('/(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/', $modify[0], $matches)) {
                            $year = $matches[1];
                            $month = $matches[2];
                            $day = $matches[3];
                            $hour = $matches[4];
                            $min = $matches[5];
                            $sec = $matches[6];
                            $modify = mktime($hour, $min, $sec, $month, $day, $year);
                        } else {
                            $modify = time();
                        }
                        local_ent_installer_ldap_bulk_insert($value, $filterdef->userfield, $modify);
                    } while ($entry = ldap_next_entry($ldapconnection, $entry));
                }
                unset($ldap_result);
                // Free mem.
            } while ($ldap_pagedresults && !empty($ldap_cookie));
        }
    }
    /*
     * If LDAP paged results were used, the current connection must be completely
     * closed and a new one created, to work without paged results from here on.
     */
    if ($ldap_pagedresults) {
        $ldapauth->ldap_close(true);
        $ldapconnection = $ldapauth->ldap_connect();
    }
    /*
     * preserve our user database
     * if the temp table is empty, it probably means that something went wrong, exit
     * so as to avoid mass deletion of users; which is hard to undo
     */
    $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
    if ($count < 1) {
        mtrace(get_string('didntgetusersfromldap', 'auth_ldap'));
        $dbman->drop_table($table);
        $ldapauth->ldap_close(true);
        return false;
    } else {
        mtrace(get_string('gotcountrecordsfromldap', 'auth_ldap', $count));
    }
    /********************** User removal. *****************************/
    /*
     * Find users in DB that aren't in ldap -- to be removed!
     * this is still not as scalable (but how often do we mass delete?)
     */
    if ($ldapauth->config->removeuser != AUTH_REMOVEUSER_KEEP) {
        $sql = '
            SELECT
                u.*
            FROM 
                {user} u
            LEFT JOIN 
                {tmp_extuser} e
            ON 
                (u.username = e.username AND u.mnethostid = e.mnethostid)
            WHERE
                u.auth = ? AND 
                u.deleted = 0 AND 
                e.username IS NULL
        ';
        $real_user_auth = get_config('local_ent_installer', 'real_used_auth');
        $remove_users = $DB->get_records_sql($sql, array($real_user_auth));
        if (!empty($remove_users)) {
            mtrace(get_string('userentriestoremove', 'auth_ldap', count($remove_users)));
            foreach ($remove_users as $user) {
                if ($ldapauth->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
                    if (empty($options['simulate'])) {
                        if (empty($options['fulldelete'])) {
                            // Make a light delete of users, but keeping data for revival.
                            $user->deleted = 1;
                            try {
                                $DB->update_record('user', $user);
                                // Subscription does not work if it contains a user marked as deleted
                                $DB->delete_records('cohort_members', array('userid' => $user->id));
                                mtrace(get_string('auth_dbdeleteuser', 'auth_db', array('name' => $user->username, 'id' => $user->id)));
                            } catch (Exception $e) {
                                mtrace(get_string('auth_dbdeleteusererror', 'auth_db', $user->username));
                            }
                        } else {
                            // Make a complete delete of users, enrols, grades and data
                            if (delete_user($user)) {
                                echo "\t";
                                mtrace(get_string('auth_dbdeleteuser', 'auth_db', array('name' => $user->username, 'id' => $user->id)));
                            } else {
                                echo "\t";
                                mtrace(get_string('auth_dbdeleteusererror', 'auth_db', $user->username));
                            }
                        }
                    } else {
                        mtrace(get_string('simulateuserdelete', 'ent_installer', $user->username));
                    }
                } elseif ($ldapauth->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
                    if (empty($options['simulate'])) {
                        $updateuser = new stdClass();
                        $updateuser->id = $user->id;
                        $updateuser->auth = 'nologin';
                        $DB->update_record('user', $updateuser);
                        echo "\t";
                        mtrace(get_string('auth_dbsuspenduser', 'auth_db', array('name' => $user->username, 'id' => $user->id)));
                        $euser = $DB->get_record('user', array('id' => $user->id));
                        //events_trigger('user_updated', $euser); => deprecated !
                        $event = core\event\user_updated::create_from_userid($euser->id);
                        $event->trigger();
                    } else {
                        mtrace(get_string('simulateusersuspend', 'ent_installer', $user->username));
                    }
                }
            }
        } else {
            mtrace(get_string('nouserentriestoremove', 'auth_ldap'));
        }
        unset($remove_users);
        // free mem!
    } else {
        mtrace("AUTH_REMOVEUSER_KEEP is on or ldapauth config removeuser is off");
    }
    /********************* Revive suspended users. *********************************/
    if (!empty($ldapauth->config->removeuser) && $ldapauth->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
        $sql = "\n            SELECT\n                u.id, u.username\n            FROM\n                {user} u\n            JOIN\n                {tmp_extuser} e\n            ON\n                (u.username = e.username AND u.mnethostid = e.mnethostid)\n            WHERE\n                u.auth = 'nologin' AND u.deleted = 0\n        ";
        $revive_users = $DB->get_records_sql($sql);
        if (!empty($revive_users)) {
            mtrace(get_string('userentriestorevive', 'auth_ldap', count($revive_users)));
            foreach ($revive_users as $user) {
                $updateuser = new stdClass();
                $updateuser->id = $user->id;
                $updateuser->auth = $ldapauth->authtype;
                $DB->update_record('user', $updateuser);
                echo "\t";
                mtrace(get_string('auth_dbreviveduser', 'auth_db', array('name' => $user->username, 'id' => $user->id)));
                $euser = $DB->get_record('user', array('id' => $user->id));
                //events_trigger('user_updated', $euser); => deprecated !
                $event = core\event\user_updated::create_from_userid($euser->id);
                $event->trigger();
            }
        } else {
            mtrace(get_string('nouserentriestorevive', 'auth_ldap'));
        }
        unset($revive_users);
    }
    /****************************** User Updates - time-consuming (optional). ***************************/
    // This might be an OBSOLETE code, regarding the updat ecapability of the create process.
    if (!empty($options['doupdates'])) {
        // Narrow down what fields we need to update.
        $all_keys = array_keys(get_object_vars($ldapauth->config));
        $updatekeys = array();
        foreach ($all_keys as $key) {
            if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
                /*
                 * If we have a field to update it from
                 * and it must be updated 'onlogin' we
                 * update it on cron
                 */
                if (!empty($ldapauth->config->{'field_map_' . $match[1]}) && $ldapauth->config->{$match[0]} === 'onlogin') {
                    // The actual key name.
                    array_push($updatekeys, $match[1]);
                }
            }
        }
        unset($all_keys);
        unset($key);
    } else {
        mtrace(get_string('noupdatestobedone', 'auth_ldap'));
    }
    if (@$options['doupdates'] and !empty($updatekeys)) {
        // Run updates only if relevant.
        $users = $DB->get_records_sql('SELECT u.username, u.id
                                         FROM {user} u
                                        WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?', array($ldapauth->authtype, $CFG->mnet_localhost_id));
        if (!empty($users)) {
            mtrace(get_string('userentriestoupdate', 'auth_ldap', count($users)));
            $sitecontext = context_system::instance();
            if (!empty($ldapauth->config->creators) and !empty($ldapauth->config->memberattribute) && ($roles = get_archetype_roles('coursecreator'))) {
                // We can only use one, let's use the first one.
                $creatorrole = array_shift($roles);
            } else {
                $creatorrole = false;
            }
            $transaction = $DB->start_delegated_transaction();
            $xcount = 0;
            $maxxcount = 100;
            foreach ($users as $user) {
                echo "\t";
                $tracestr = get_string('auth_dbupdatinguser', 'auth_db', array('name' => $user->username, 'id' => $user->id));
                if (!$ldapauth->update_user_record($user->username, $updatekeys)) {
                    $tracestr .= ' - ' . get_string('skipped');
                }
                mtrace($tracestr);
                $xcount++;
                // Update course creators if needed.
                if ($creatorrole !== false) {
                    if ($ldapauth->iscreator($user->username)) {
                        role_assign($creatorrole->id, $user->id, $sitecontext->id, $ldapauth->roleauth);
                    } else {
                        role_unassign($creatorrole->id, $user->id, $sitecontext->id, $ldapauth->roleauth);
                    }
                }
            }
            $transaction->allow_commit();
            unset($users);
            // free mem
        }
    } else {
        // End do updates.
        mtrace(get_string('noupdatestobedone', 'auth_ldap'));
    }
    /***************************** User Additions or full profile update. **********************************/
    /*
     * Find users missing in DB that are in LDAP or users that have been modified since last run
     * and gives me a nifty object I don't want.
     * note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
     */
    if (empty($options['force'])) {
        $sql = 'SELECT e.id, e.username, e.usertype
                  FROM {tmp_extuser} e
                  LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
                 WHERE u.id IS NULL OR (
                 e.lastmodified > ? ) ORDER BY e.username';
        $params = array($lastrun);
    } else {
        $sql = 'SELECT e.id, e.username, e.usertype
                  FROM {tmp_extuser} e ORDER BY e.username';
        $params = array();
    }
    $add_users = $DB->get_records_sql($sql, $params);
    if (!empty($add_users)) {
        mtrace(get_string('userentriestoadd', 'auth_ldap', count($add_users)));
        $sitecontext = context_system::instance();
        if (!empty($ldapauth->config->creators) && !empty($ldapauth->config->memberattribute) && ($roles = get_archetype_roles('coursecreator'))) {
            // We can only use one, let's use the first one.
            $creatorrole = array_shift($roles);
        } else {
            $creatorrole = false;
        }
        $inserterrorcount = 0;
        $updateerrorcount = 0;
        $insertcount = 0;
        $updatecount = 0;
        // Before processing each user we check that every common hosts access keys fields are correctly set up
        if (file_exists($CFG->dirroot . '/blocks/user_mnet_hosts/locallib.php')) {
            require_once $CFG->dirroot . '/blocks/user_mnet_hosts/locallib.php';
            $like = $DB->sql_like('wwwroot', ':wwwroot', false, false);
            $mainhosts = explode(',', @$CFG->mainhostprefix);
            if (!empty($mainhosts)) {
                foreach ($mainhosts as $hostwww) {
                    // Check if common hosts exist
                    if ($commonroots = $DB->get_records_select('mnet_host', " {$like} AND deleted <> 1 ", array('wwwroot' => $hostwww . '%'))) {
                        foreach ($commonroots as $root) {
                            // Check if current common host access key field exists, if not create one
                            $expectedname = user_mnet_hosts_make_accesskey($root->wwwroot, true);
                            $accessmainhost = $DB->get_records('user_info_field', array('shortname' => $expectedname), '', 'id');
                            if (!$accessmainhost) {
                                mtrace("Common host access key '{$expectedname}' not found");
                                if (!isset($CFG->accesscategory)) {
                                    $accesscategory = new stdClass();
                                    $accesscategory->name = get_string('accesscategory', 'block_user_mnet_hosts');
                                    $accesscategory->sortorder = 1;
                                    $id = $DB->insert_record('user_info_category', $accesscategory);
                                    set_config('accesscategory', $id);
                                }
                                $hostkey = user_mnet_hosts_make_accesskey($root->wwwroot, false);
                                $newfield = new stdClass();
                                $newfield->shortname = $expectedname;
                                $newfield->name = get_string('fieldname', 'block_user_mnet_hosts') . ' ' . $hostkey;
                                $newfield->datatype = 'checkbox';
                                $newfield->locked = 1;
                                $newfield->categoryid = $CFG->accesscategory;
                                if ($DB->insert_record('user_info_field', $newfield)) {
                                    mtrace("Common host access key created : {$expectedname}");
                                } else {
                                    mtrace("Common host access key creation error : {$expectedname}");
                                }
                            }
                        }
                    }
                }
            }
        }
        // Before processing each user we check that custom field to store ENT profil & guid are correctly set up
        $infoscateg = $DB->get_records('user_info_category', array('name' => 'Informations académiques'), '', 'id');
        if (!empty($infoscateg)) {
            $infoscateg = array_values($infoscateg);
            $idinfocateg = $infoscateg[0]->id;
            $profilent = $DB->get_records('user_info_field', array('shortname' => 'profilent'), '', 'id');
            if (empty($profilent)) {
                $maxsortorder = $DB->get_records_sql('SELECT MAX(sortorder) AS maxsortorder FROM {user_info_field} WHERE categoryid = ?', array($idinfocateg));
                $maxsortorder = array_values($maxsortorder);
                $sortordertoinsert = $maxsortorder[0]->maxsortorder + 1;
                $user_info_field = new stdClass();
                $user_info_field->shortname = 'profilent';
                $user_info_field->name = 'Profil ENT';
                $user_info_field->datatype = 'text';
                $user_info_field->description = '<p>Les profils ENT sont utilisés pour traitements spécifiques post-synchronisation et proviennent du champ ENTPersonProfils du SDET<br></p>';
                $user_info_field->descriptionformat = 1;
                $user_info_field->categoryid = $idinfocateg;
                $user_info_field->sortorder = $sortordertoinsert;
                $user_info_field->required = 0;
                $user_info_field->locked = 1;
                $user_info_field->visible = 0;
                $user_info_field->forceunique = 0;
                $user_info_field->signup = 0;
                $user_info_field->defaultdata = '';
                $user_info_field->defaultdataformat = 0;
                $user_info_field->param1 = '30';
                $user_info_field->param2 = '2048';
                $user_info_field->param3 = '0';
                $user_info_field->param4 = '';
                $user_info_field->param5 = '';
                $fieldid = $DB->insert_record('user_info_field', $user_info_field);
                mtrace("user_info_field : 'profilent' inserted !");
                if ($USERFIELDS['profilent'] == 0 && $fieldid != 0) {
                    $USERFIELDS['profilent'] = $fieldid;
                } else {
                    mtrace("user_info_field : cannot get id for 'profilent' !");
                }
            }
            $guident = $DB->get_records('user_info_field', array('shortname' => 'guident'), '', 'id');
            if (empty($guident)) {
                $maxsortorder = $DB->get_records_sql('SELECT MAX(sortorder) AS maxsortorder FROM {user_info_field} WHERE categoryid = ?', array($idinfocateg));
                $maxsortorder = array_values($maxsortorder);
                $sortordertoinsert = $maxsortorder[0]->maxsortorder + 1;
                $user_info_field = new stdClass();
                $user_info_field->shortname = 'guident';
                $user_info_field->name = 'Guid ENT';
                $user_info_field->datatype = 'text';
                $user_info_field->description = '<p><p>Le GUID ENT est utilisé pour la synchronisation des comptes et provient du champ AD objectGuid<br></p></p>';
                $user_info_field->descriptionformat = 1;
                $user_info_field->categoryid = $idinfocateg;
                $user_info_field->sortorder = $sortordertoinsert;
                $user_info_field->required = 0;
                $user_info_field->locked = 1;
                $user_info_field->visible = 0;
                $user_info_field->forceunique = 0;
                $user_info_field->signup = 0;
                $user_info_field->defaultdata = '';
                $user_info_field->defaultdataformat = 0;
                $user_info_field->param1 = '36';
                $user_info_field->param2 = '2048';
                $user_info_field->param3 = '0';
                $user_info_field->param4 = '';
                $user_info_field->param5 = '';
                $fieldid = $DB->insert_record('user_info_field', $user_info_field);
                mtrace("user_info_field : 'guident' inserted !");
                if ($USERFIELDS['guident'] == 0 && $fieldid != 0) {
                    $USERFIELDS['guident'] = $fieldid;
                } else {
                    mtrace("user_info_field : cannot get id for 'guident' !");
                }
            }
        } else {
            mtrace("user_info_category : 'Informations académiques' missing !");
        }
        // We scan new proposed users from LDAP.
        foreach ($add_users as $user) {
            // Save usertype.
            $usertype = $user->usertype;
            $user = local_ent_installer_get_userinfo_asobj($ldapauth, $user->username, $options);
            // Restore usertype in user.
            $user->usertype = $usertype;
            // Post filter of idnumber
            list($foosdetprefix, $user->idnumber) = explode('$', $user->idnumber);
            if (empty($user->firstname)) {
                mtrace('ERROR : Missing firstname in incoming record ' . $user->username);
                $updateerrorcount++;
                continue;
            }
            if (empty($user->lastname)) {
                mtrace('ERROR : Missing lastname in incoming record ' . $user->username);
                $updateerrorcount++;
                continue;
            }
            if (empty($user->email)) {
                $user->email = local_ent_installer_generate_email($user);
            }
            // Prep a few params.
            $user->modified = time();
            $user->confirmed = 1;
            $user->deleted = 0;
            $user->suspended = 0;
            // Authentication is the ldap plugin or a real auth plugin defined in setup.
            $realauth = get_config('local_ent_installer', 'real_used_auth');
            $user->auth = empty($realauth) ? $ldapauth->authtype : $realauth;
            $user->mnethostid = $CFG->mnet_localhost_id;
            $user->country = $CFG->country;
            /*
             * Get_userinfo_asobj() might have replaced $user->username with the value.
             * from the LDAP server (which can be mixed-case). Make sure it's lowercase
             */
            $user->username = trim(core_text::strtolower($user->username));
            if (empty($user->lang)) {
                $user->lang = $CFG->lang;
            }
            /*
             * Process additional info for student :
             * extra information fields transport and regime.
             */
            if ($user->usertype == 'eleve') {
                // Transport.
                $user->profile_field_transport = 'Y' == @$user->ENTEleveTransport ? '1' : 0;
                // Regime.
                $user->profile_field_regime = @$user->ENTEleveRegime;
                // Cohort (must have).
                $user->profile_field_cohort = $user->ENTEleveClasses;
            }
            // Profil ENT
            $user->profile_field_profil = $user->ENTPersonProfils;
            // Guid ENT
            $user->profile_field_guid = $user->objectGUID;
            $personfunction = @$user->ENTPersonFonctions;
            unset($user->ENTPersonFonctions);
            // Get the last term of personfunction and set it as department.
            if (!empty($personfunction)) {
                preg_match('/\\$([^\\$]+)$/', $personfunction, $matches);
                $user->department = $matches[1];
            }
            if (empty($options['simulate'])) {
                // Creation/full update sequence.
                $a = clone $user;
                $a->function = $personfunction;
                /*
                 * Special case : si there a matching policy possible for previous accounts NOT being
                 * created by this system ? 
                 */
                try {
                    $oldrec = local_ent_installer_guess_old_record($user, $status);
                } catch (Exception $e) {
                    mtrace('ERROR : Fail to bind user ' . $user->username);
                    if ($options['verbose']) {
                        trace_debug($e);
                    }
                    $inserterrorcount++;
                    continue;
                }
                if ($oldrec) {
                    $a->status = $MATCH_STATUS[$status];
                    $id = $user->id = $oldrec->id;
                    try {
                        $DB->update_record('user', $user);
                        mtrace(get_string('dbupdateuser', 'local_ent_installer', $a));
                        $updatecount++;
                    } catch (Exception $e) {
                        mtrace('ERROR : Fail to update user ' . $user->username);
                        if ($options['verbose']) {
                            trace_debug($e);
                        }
                        $updateerrorcount++;
                        continue;
                    }
                } else {
                    try {
                        $id = $DB->insert_record('user', $user);
                        mtrace(get_string('dbinsertuser', 'local_ent_installer', $a));
                        $insertcount++;
                    } catch (Exception $e) {
                        mtrace('ERROR : Fail to insert user ' . $user->username);
                        if ($options['verbose']) {
                            trace_debug($e);
                        }
                        $inserterrorcount++;
                        continue;
                    }
                }
            } else {
                $a = clone $user;
                $a->function = $personfunction;
                if (!($oldrec = local_ent_installer_guess_old_record($user, $status))) {
                    mtrace(get_string('dbinsertusersimul', 'local_ent_installer', $a));
                } else {
                    $a->status = $MATCH_STATUS[$status];
                    mtrace(get_string('dbupdateusersimul', 'local_ent_installer', $a));
                }
            }
            if (empty($options['simulate'])) {
                $euser = $DB->get_record('user', array('id' => $id));
                //events_trigger('user_created', $euser); => deprecated !
                $event = core\event\user_created::create_from_userid($euser->id);
                $event->trigger();
                if (!empty($ldapauth->config->forcechangepassword)) {
                    set_user_preference('auth_forcepasswordchange', 1, $id);
                }
                // Cohort information / create/update cohorts.
                if ($user->usertype == 'eleve') {
                    // Adds user to cohort and create cohort if missing.
                    $cohortshort = local_ent_installer_check_cohort($id, $user->profile_field_cohort);
                    local_ent_installer_update_info_data($id, $USERFIELDS['transport'], $user->profile_field_transport);
                    local_ent_installer_update_info_data($id, $USERFIELDS['regime'], $user->profile_field_regime);
                    local_ent_installer_update_info_data($id, $USERFIELDS['cohort'], $cohortshort);
                    if (isset($user->ENTEleveGroupes) && count($user->ENTEleveGroupes) > 0) {
                        foreach ($user->ENTEleveGroupes as $group) {
                            $cohortshort = local_ent_installer_check_cohort($id, $group, false, $options['verbose']);
                        }
                    }
                }
                // Create profil cohort to allow enrollment by profil
                $cohortshort = local_ent_installer_check_cohort($id, $user->profile_field_profil, false, $options['verbose']);
                if ($user->profile_field_profil == 'Administrateurs') {
                    if (isset($id)) {
                        $managerrole = $DB->get_record('role', array('shortname' => 'manager'));
                        role_assign($managerrole->id, $id, 1);
                        // 1=system context
                    } else {
                        mtrace('WARNING : Cannot assign role manager to ' . $user->username);
                    }
                }
                local_ent_installer_update_info_data($id, $USERFIELDS['profilent'], $user->profile_field_profil);
                local_ent_installer_update_info_data($id, $USERFIELDS['guident'], $user->profile_field_guid);
                // Add course creators if needed.
                if ($creatorrole !== false and $ldapauth->iscreator($user->username)) {
                    role_assign($creatorrole->id, $id, $sitecontext->id, $ldapauth->roleauth);
                }
                // Process user_fields setup.
                if (preg_match('#\\$CTR\\$#', $personfunction)) {
                    // Special case.
                    local_ent_installer_update_info_data($id, $USERFIELDS['cdt'], 1);
                } else {
                    // Other user types.
                    local_ent_installer_update_info_data($id, $USERFIELDS[$user->usertype], 1);
                }
                if (file_exists($CFG->dirroot . '/blocks/user_mnet_hosts/locallib.php')) {
                    // user_mnet_hosts local library has already been included upstream of this script
                    // All users have access marked on self.
                    user_mnet_hosts_set_access($id, true);
                    // Setting default access field policy for powered users.
                    if ($user->usertype == 'enseignant' || $user->usertype == 'administration') {
                        $like = $DB->sql_like('wwwroot', ':wwwroot', false, false);
                        $mainhosts = explode(',', @$CFG->mainhostprefix);
                        $given = false;
                        if (!empty($mainhosts)) {
                            foreach ($mainhosts as $hostwww) {
                                if ($commonroots = $DB->get_records_select('mnet_host', " {$like} AND deleted <> 1 ", array('wwwroot' => $hostwww . '%'))) {
                                    foreach ($commonroots as $root) {
                                        $given = true;
                                        user_mnet_hosts_set_access($id, true, $root->wwwroot);
                                    }
                                }
                            }
                        }
                        if (!$given) {
                            mtrace('Giving teacher access : no common host found ');
                        }
                    }
                }
                // Add a workplace to teachers.
                if ($user->usertype == 'enseignant') {
                    if (get_config('local_ent_installer', 'build_teacher_category')) {
                        if (isset($options['unassignteachercategoryrole'])) {
                            local_ent_installer_make_teacher_category($euser, $options['unassignteachercategoryrole']);
                        } else {
                            local_ent_installer_make_teacher_category($euser);
                        }
                    }
                }
                // Identify librarians and give library enabled role at system level.
                if (preg_match('#\\$DOC\\$#', $personfunction)) {
                    if ($role = $DB->get_record('role', array('shortname' => 'librarian'))) {
                        $systemcontext = context_system::instance();
                        role_assign($role->id, $id, $systemcontext->id);
                    }
                }
            }
        }
        unset($add_users);
        // free mem
    } else {
        mtrace(get_string('nouserstobeadded', 'auth_ldap'));
    }
    $ldapauth->ldap_close();
    list($usec, $sec) = explode(' ', microtime());
    $stoptick = (double) $sec + (double) $usec;
    $deltatime = $stoptick - $starttick;
    mtrace('Execution time : ' . $deltatime);
    $benchrec = new StdClass();
    $benchrec->timestart = floor($starttick);
    $benchrec->timerun = ceil($deltatime);
    $benchrec->added = 0 + @$insertcount;
    $benchrec->updated = 0 + @$updatecount;
    $benchrec->updateerrors = 0 + @$inserterrorcount;
    $benchrec->inserterrors = 0 + @$updateerrorcount;
    $DB->insert_record('local_ent_installer', $benchrec);
    // Mark last time the user sync was run.
    set_config('last_sync_date', time(), 'local_ent_installer');
    try {
        $dbman->drop_table($table);
    } catch (Exception $e) {
    }
    return true;
}
 /**
  * Creates csv file and add it to the threadgroup for use case.
  *
  * @Given /^I login as any "([^"]*)" enrolled in course "([^"]*)"$/
  */
 public function i_login_as_any_enrolled_in_course($rolearchtype, $courseshortname)
 {
     global $DB, $CFG;
     if (!($id = $DB->get_field('course', 'id', array('shortname' => $courseshortname)))) {
         util::performance_exception('The specified course with shortname "' . $courseshortname . '" does not exist');
     }
     $coursecontext = \context_course::instance($id);
     if ($roles = get_archetype_roles($rolearchtype)) {
         $roles = array_keys($roles);
     }
     $roleid = $roles[0];
     $users = get_role_users($roleid, $coursecontext, false, 'u.id,u.username', 'u.id ASC');
     if (!$users) {
         util::performance_exception("Course without users with role: " . $rolearchtype);
     }
     $data = "";
     foreach ($users as $user) {
         $data .= $user->username . "," . $user->username . "," . $user->id . PHP_EOL;
     }
     $testplanfilename = $rolearchtype . '_' . behat_hooks::$featurefile . '.csv';
     $csvfile = util::get_final_testplan_path() . DIRECTORY_SEPARATOR . $testplanfilename;
     $testplanfilepath = "";
     if (isset($CFG->testplanfiles_dataroot)) {
         $testplanfilepath = $CFG->testplanfiles_dataroot . DIRECTORY_SEPARATOR;
     }
     file_put_contents($csvfile, $data);
     testplan_writer::create_csv_data($testplanfilepath, $testplanfilename, $rolearchtype);
     $firstuser = array_shift($users);
     return new Given('I log in as "' . $firstuser->username . '"');
 }
 /**
  * Test default enrol roles.
  */
 public function test_get_default_enrol_roles()
 {
     $this->resetAfterTest();
     $course = $this->getDataGenerator()->create_course();
     $coursecontext = context_course::instance($course->id);
     $id2 = create_role('New student role', 'student2', 'New student description', 'student');
     set_role_contextlevels($id2, array(CONTEXT_COURSE));
     $allroles = get_all_roles();
     $expected = array($id2 => $allroles[$id2]);
     foreach (get_role_archetypes() as $archetype) {
         $defaults = get_default_contextlevels($archetype);
         if (in_array(CONTEXT_COURSE, $defaults)) {
             $roles = get_archetype_roles($archetype);
             foreach ($roles as $role) {
                 $expected[$role->id] = $role;
             }
         }
     }
     $roles = get_default_enrol_roles($coursecontext);
     foreach ($allroles as $role) {
         $this->assertEquals(isset($expected[$role->id]), isset($roles[$role->id]));
         if (isset($roles[$role->id])) {
             $this->assertSame(role_get_name($role, $coursecontext), $roles[$role->id]);
         }
     }
 }
Example #18
0
 /**
  * Test the user competency grade rated in course event.
  *
  */
 public function test_user_competency_rated_in_course()
 {
     $this->resetAfterTest(true);
     $this->setAdminUser();
     $dg = $this->getDataGenerator();
     $lpg = $this->getDataGenerator()->get_plugin_generator('core_competency');
     $scale = $dg->create_scale(array('scale' => 'A,B,C,D'));
     $course = $dg->create_course();
     $user = $dg->create_user();
     $studentarch = get_archetype_roles('student');
     $studentrole = array_shift($studentarch);
     $scaleconfig = array(array('scaleid' => $scale->id));
     $scaleconfig[] = array('name' => 'A', 'id' => 1, 'scaledefault' => 0, 'proficient' => 0);
     $scaleconfig[] = array('name' => 'B', 'id' => 2, 'scaledefault' => 1, 'proficient' => 0);
     $scaleconfig[] = array('name' => 'C', 'id' => 3, 'scaledefault' => 0, 'proficient' => 1);
     $scaleconfig[] = array('name' => 'D', 'id' => 4, 'scaledefault' => 0, 'proficient' => 1);
     $fr = $lpg->create_framework();
     $c = $lpg->create_competency(array('competencyframeworkid' => $fr->get_id(), 'scaleid' => $scale->id, 'scaleconfiguration' => $scaleconfig));
     // Enrol the user as students in course.
     $dg->enrol_user($user->id, $course->id, $studentrole->id);
     $lpg->create_course_competency(array('courseid' => $course->id, 'competencyid' => $c->get_id()));
     $uc = $lpg->create_user_competency(array('userid' => $user->id, 'competencyid' => $c->get_id()));
     // Trigger and capture the event.
     $sink = $this->redirectEvents();
     api::grade_competency_in_course($course->id, $user->id, $c->get_id(), 2, true);
     // Get our event event.
     $events = $sink->get_events();
     // Evidence created.
     $this->assertCount(2, $events);
     $evidencecreatedevent = $events[0];
     $event = $events[1];
     // Check that the event data is valid.
     $this->assertInstanceOf('\\core\\event\\competency_evidence_created', $evidencecreatedevent);
     $this->assertInstanceOf('\\core\\event\\competency_user_competency_rated_in_course', $event);
     $this->assertEquals(context_course::instance($course->id)->id, $event->contextid);
     $this->assertEquals($course->id, $event->courseid);
     $this->assertEquals($uc->get_userid(), $event->relateduserid);
     $this->assertEquals($uc->get_competencyid(), $event->other['competencyid']);
     $this->assertEquals(2, $event->other['grade']);
     $this->assertEventContextNotUsed($event);
     $this->assertDebuggingNotCalled();
 }
 /**
  * This function confirms the remote (ID provider) host's mnet session
  * by communicating the token and UA over the XMLRPC transport layer, and
  * returns the local user record on success.
  *
  *   @param string    $token           The random session token.
  *   @param mnet_peer $remotepeer   The ID provider mnet_peer object.
  *   @return array The local user record.
  */
 function confirm_mnet_session($token, $remotepeer)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
     require_once $CFG->libdir . '/gdlib.php';
     // verify the remote host is configured locally before attempting RPC call
     if (!($remotehost = $DB->get_record('mnet_host', array('wwwroot' => $remotepeer->wwwroot, 'deleted' => 0)))) {
         print_error('notpermittedtoland', 'mnet');
     }
     // set up the RPC request
     $mnetrequest = new mnet_xmlrpc_client();
     $mnetrequest->set_method('auth/mnet/auth.php/user_authorise');
     // set $token and $useragent parameters
     $mnetrequest->add_param($token);
     $mnetrequest->add_param(sha1($_SERVER['HTTP_USER_AGENT']));
     // Thunderbirds are go! Do RPC call and store response
     if ($mnetrequest->send($remotepeer) === true) {
         $remoteuser = (object) $mnetrequest->response;
     } else {
         foreach ($mnetrequest->error as $errormessage) {
             list($code, $message) = array_map('trim', explode(':', $errormessage, 2));
             if ($code == 702) {
                 $site = get_site();
                 print_error('mnet_session_prohibited', 'mnet', $remotepeer->wwwroot, format_string($site->fullname));
                 exit;
             }
             $message .= "ERROR {$code}:<br/>{$errormessage}<br/>";
         }
         print_error("rpcerror", '', '', $message);
     }
     unset($mnetrequest);
     if (empty($remoteuser) or empty($remoteuser->username)) {
         print_error('unknownerror', 'mnet');
         exit;
     }
     if (user_not_fully_set_up($remoteuser)) {
         print_error('notenoughidpinfo', 'mnet');
         exit;
     }
     $remoteuser = mnet_strip_user($remoteuser, mnet_fields_to_import($remotepeer));
     $remoteuser->auth = 'mnet';
     $remoteuser->wwwroot = $remotepeer->wwwroot;
     // the user may roam from Moodle 1.x where lang has _utf8 suffix
     // also, make sure that the lang is actually installed, otherwise set site default
     if (isset($remoteuser->lang)) {
         $remoteuser->lang = clean_param(str_replace('_utf8', '', $remoteuser->lang), PARAM_LANG);
     }
     if (empty($remoteuser->lang)) {
         if (!empty($CFG->lang)) {
             $remoteuser->lang = $CFG->lang;
         } else {
             $remoteuser->lang = 'en';
         }
     }
     $firsttime = false;
     // get the local record for the remote user
     $localuser = $DB->get_record('user', array('username' => $remoteuser->username, 'mnethostid' => $remotehost->id));
     // add the remote user to the database if necessary, and if allowed
     // TODO: refactor into a separate function
     if (empty($localuser) || !$localuser->id) {
         /*
         if (empty($this->config->auto_add_remote_users)) {
             print_error('nolocaluser', 'mnet');
         } See MDL-21327   for why this is commented out
         */
         $remoteuser->mnethostid = $remotehost->id;
         $remoteuser->firstaccess = time();
         // First time user in this server, grab it here
         $remoteuser->id = $DB->insert_record('user', $remoteuser);
         $firsttime = true;
         $localuser = $remoteuser;
     }
     // check sso access control list for permission first
     if (!$this->can_login_remotely($localuser->username, $remotehost->id)) {
         print_error('sso_mnet_login_refused', 'mnet', '', array('user' => $localuser->username, 'host' => $remotehost->name));
     }
     $fs = get_file_storage();
     // update the local user record with remote user data
     foreach ((array) $remoteuser as $key => $val) {
         if ($key == '_mnet_userpicture_timemodified' and empty($CFG->disableuserimages) and isset($remoteuser->picture)) {
             // update the user picture if there is a newer verion at the identity provider
             $usercontext = get_context_instance(CONTEXT_USER, $localuser->id, MUST_EXIST);
             if ($usericonfile = $fs->get_file($usercontext->id, 'user', 'icon', 0, '/', 'f1.png')) {
                 $localtimemodified = $usericonfile->get_timemodified();
             } else {
                 if ($usericonfile = $fs->get_file($usercontext->id, 'user', 'icon', 0, '/', 'f1.jpg')) {
                     $localtimemodified = $usericonfile->get_timemodified();
                 } else {
                     $localtimemodified = 0;
                 }
             }
             if (!empty($val) and $localtimemodified < $val) {
                 mnet_debug('refetching the user picture from the identity provider host');
                 $fetchrequest = new mnet_xmlrpc_client();
                 $fetchrequest->set_method('auth/mnet/auth.php/fetch_user_image');
                 $fetchrequest->add_param($localuser->username);
                 if ($fetchrequest->send($remotepeer) === true) {
                     if (strlen($fetchrequest->response['f1']) > 0) {
                         $imagefilename = $CFG->dataroot . '/temp/mnet-usericon-' . $localuser->id;
                         $imagecontents = base64_decode($fetchrequest->response['f1']);
                         file_put_contents($imagefilename, $imagecontents);
                         if (process_new_icon($usercontext, 'user', 'icon', 0, $imagefilename)) {
                             $localuser->picture = 1;
                         }
                         unlink($imagefilename);
                     }
                     // note that since Moodle 2.0 we ignore $fetchrequest->response['f2']
                     // the mimetype information provided is ignored and the type of the file is detected
                     // by process_new_icon()
                 }
             }
         }
         if ($key == 'myhosts') {
             $localuser->mnet_foreign_host_array = array();
             foreach ($val as $rhost) {
                 $name = clean_param($rhost['name'], PARAM_ALPHANUM);
                 $url = clean_param($rhost['url'], PARAM_URL);
                 $count = clean_param($rhost['count'], PARAM_INT);
                 $url_is_local = stristr($url, $CFG->wwwroot);
                 if (!empty($name) && !empty($count) && empty($url_is_local)) {
                     $localuser->mnet_foreign_host_array[] = array('name' => $name, 'url' => $url, 'count' => $count);
                 }
             }
         }
         $localuser->{$key} = $val;
     }
     $localuser->mnethostid = $remotepeer->id;
     if (empty($localuser->firstaccess)) {
         // Now firstaccess, grab it here
         $localuser->firstaccess = time();
     }
     $DB->update_record('user', $localuser);
     if (!$firsttime) {
         // repeat customer! let the IDP know about enrolments
         // we have for this user.
         // set up the RPC request
         $mnetrequest = new mnet_xmlrpc_client();
         $mnetrequest->set_method('auth/mnet/auth.php/update_enrolments');
         // pass username and an assoc array of "my courses"
         // with info so that the IDP can maintain mnetservice_enrol_enrolments
         $mnetrequest->add_param($remoteuser->username);
         $fields = 'id, category, sortorder, fullname, shortname, idnumber, summary, startdate, visible';
         $courses = enrol_get_users_courses($localuser->id, false, $fields, 'visible DESC,sortorder ASC');
         if (is_array($courses) && !empty($courses)) {
             // Second request to do the JOINs that we'd have done
             // inside enrol_get_users_courses() if we had been allowed
             $sql = "SELECT c.id,\n                               cc.name AS cat_name, cc.description AS cat_description\n                          FROM {course} c\n                          JOIN {course_categories} cc ON c.category = cc.id\n                         WHERE c.id IN (" . join(',', array_keys($courses)) . ')';
             $extra = $DB->get_records_sql($sql);
             $keys = array_keys($courses);
             $defaultrole = reset(get_archetype_roles('student'));
             //$defaultrole = get_default_course_role($ccache[$shortname]); //TODO: rewrite this completely, there is no default course role any more!!!
             foreach ($keys as $id) {
                 if ($courses[$id]->visible == 0) {
                     unset($courses[$id]);
                     continue;
                 }
                 $courses[$id]->cat_id = $courses[$id]->category;
                 $courses[$id]->defaultroleid = $defaultrole->id;
                 unset($courses[$id]->category);
                 unset($courses[$id]->visible);
                 $courses[$id]->cat_name = $extra[$id]->cat_name;
                 $courses[$id]->cat_description = $extra[$id]->cat_description;
                 $courses[$id]->defaultrolename = $defaultrole->name;
                 // coerce to array
                 $courses[$id] = (array) $courses[$id];
             }
         } else {
             // if the array is empty, send it anyway
             // we may be clearing out stale entries
             $courses = array();
         }
         $mnetrequest->add_param($courses);
         // Call 0800-RPC Now! -- we don't care too much if it fails
         // as it's just informational.
         if ($mnetrequest->send($remotepeer) === false) {
             // error_log(print_r($mnetrequest->error,1));
         }
     }
     return $localuser;
 }
Example #20
0
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
/**
 * Cohort enrolment plugin settings and presets.
 *
 * @package    enrol
 * @subpackage jwc
 * @copyright  2010 Petr Skoda {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
defined('MOODLE_INTERNAL') || die;
if ($ADMIN->fulltree) {
    //--- general settings -----------------------------------------------------------------------------------
    $settings->add(new admin_setting_heading('enrol_jwc_settings', '', get_string('pluginname_desc', 'enrol_jwc')));
    //--- enrol instance defaults ----------------------------------------------------------------------------
    if (!during_initial_install()) {
        $options = get_default_enrol_roles(get_context_instance(CONTEXT_SYSTEM));
        $student = get_archetype_roles('student');
        $student = reset($student);
        $settings->add(new admin_setting_configselect('enrol_jwc/roleid', '学生角色', '', $student->id, $options));
        $teacher = get_archetype_roles('editingteacher');
        $teacher = reset($teacher);
        $settings->add(new admin_setting_configselect('enrol_jwc/teacherroleid', '教师角色', '', $teacher->id, $options));
        $settings->add(new admin_setting_configtext('enrol_jwc/semester', '当前学期', '“2011秋季,2012春季”之类,与教务系统必须相符。每学期第一周必须修改设置。', '20XXX季'));
        $settings->add(new admin_setting_configtext('enrol_jwc/signprefix', '签名前缀', '访问教务处数字签名的前缀', ''));
        $settings->add(new admin_setting_configtext('enrol_jwc/signsuffix', '签名后缀', '访问教务处数字签名的后缀', ''));
        $settings->add(new admin_setting_configcheckbox('enrol_jwc/unenrolall', '清除所有选课', '<strong>慎重!!!</strong>勾选后,在下次cron运行时,会把所有已经同步的选课都清理掉。清理之后,此选项被自动禁用。应该只在每学期初设一下此选项。', 0));
    }
}
 public function definition()
 {
     global $CFG, $USER, $SESSION;
     $mform =& $this->_form;
     $columns =& $this->_customdata;
     // I am the template user, why should it be the administrator? we have roles now, other ppl may use this script ;-).
     $templateuser = $USER;
     // Upload settings and file.
     $mform->addElement('header', 'settingsheader', get_string('settings'));
     $mform->addElement('static', 'uutypelabel', get_string('uuoptype', 'tool_uploaduser'));
     $choices = array(0 => get_string('infilefield', 'auth'), 1 => get_string('createpasswordifneeded', 'auth'));
     $mform->addElement('select', 'uupasswordnew', get_string('uupasswordnew', 'tool_uploaduser'), $choices);
     $mform->setDefault('uupasswordnew', 1);
     $mform->disabledIf('uupasswordnew', 'uutype', 'eq', UU_UPDATE);
     $mform->addElement('selectyesno', 'sendnewpasswordemails', get_string('sendnewpasswordemails', 'block_iomad_company_admin'));
     $mform->setDefault('sendnewpasswordemails', 1);
     $choices = array(0 => get_string('nochanges', 'tool_uploaduser'), 1 => get_string('uuupdatefromfile', 'tool_uploaduser'), 2 => get_string('uuupdateall', 'tool_uploaduser'), 3 => get_string('uuupdatemissing', 'tool_uploaduser'));
     $mform->addElement('select', 'uuupdatetype', get_string('uuupdatetype', 'tool_uploaduser'), $choices);
     $mform->setDefault('uuupdatetype', 0);
     $mform->disabledIf('uuupdatetype', 'uutype', 'eq', UU_ADDNEW);
     $mform->disabledIf('uuupdatetype', 'uutype', 'eq', UU_ADDINC);
     $choices = array(0 => get_string('nochanges', 'tool_uploaduser'), 1 => get_string('update'));
     $mform->addElement('select', 'uupasswordold', get_string('uupasswordold', 'tool_uploaduser'), $choices);
     $mform->setDefault('uupasswordold', 0);
     $mform->disabledIf('uupasswordold', 'uutype', 'eq', UU_ADDNEW);
     $mform->disabledIf('uupasswordold', 'uutype', 'eq', UU_ADDINC);
     $mform->disabledIf('uupasswordold', 'uuupdatetype', 'eq', 0);
     $mform->disabledIf('uupasswordold', 'uuupdatetype', 'eq', 3);
     $mform->addElement('selectyesno', 'uuallowrenames', get_string('allowrenames', 'tool_uploaduser'));
     $mform->setDefault('uuallowrenames', 0);
     $mform->disabledIf('uuallowrenames', 'uutype', 'eq', UU_ADDNEW);
     $mform->disabledIf('uuallowrenames', 'uutype', 'eq', UU_ADDINC);
     $mform->addElement('selectyesno', 'uuallowdeletes', get_string('allowdeletes', 'tool_uploaduser'));
     $mform->setDefault('uuallowdeletes', 0);
     $mform->disabledIf('uuallowdeletes', 'uutype', 'eq', UU_ADDNEW);
     $mform->disabledIf('uuallowdeletes', 'uutype', 'eq', UU_ADDINC);
     $mform->addElement('selectyesno', 'uunoemailduplicates', get_string('uunoemailduplicates', 'tool_uploaduser'));
     $mform->setDefault('uunoemailduplicates', 1);
     $choices = array(0 => get_string('no'), 1 => get_string('uubulknew', 'tool_uploaduser'), 2 => get_string('uubulkupdated', 'tool_uploaduser'), 3 => get_string('uubulkall', 'tool_uploaduser'));
     $mform->addElement('select', 'uubulk', get_string('uubulk', 'tool_uploaduser'), $choices);
     $mform->setDefault('uubulk', 0);
     // Roles selection.
     $showroles = false;
     foreach ($columns as $column) {
         if (preg_match('/^type\\d+$/', $column)) {
             $showroles = true;
             break;
         }
     }
     if ($showroles) {
         $mform->addElement('header', 'rolesheader', get_string('roles'));
         $choices = uu_allowed_roles(true);
         $mform->addElement('select', 'uulegacy1', get_string('uulegacy1role', 'tool_uploaduser'), $choices);
         if ($studentroles = get_archetype_roles('student')) {
             foreach ($studentroles as $role) {
                 if (isset($choices[$role->id])) {
                     $mform->setDefault('uulegacy1', $role->id);
                     break;
                 }
             }
             unset($studentroles);
         }
         $mform->addElement('select', 'uulegacy2', get_string('uulegacy2role', 'tool_uploaduser'), $choices);
         if ($editteacherroles = get_archetype_roles('editingteacher')) {
             foreach ($editteacherroles as $role) {
                 if (isset($choices[$role->id])) {
                     $mform->setDefault('uulegacy2', $role->id);
                     break;
                 }
             }
             unset($editteacherroles);
         }
         $mform->addElement('select', 'uulegacy3', get_string('uulegacy3role', 'tool_uploaduser'), $choices);
         if ($teacherroles = get_archetype_roles('teacher')) {
             foreach ($teacherroles as $role) {
                 if (isset($choices[$role->id])) {
                     $mform->setDefault('uulegacy3', $role->id);
                     break;
                 }
             }
             unset($teacherroles);
         }
     }
     // Next the profile defaults.
     profile_definition($mform);
     // Remove the company profile field from the form (this was added by the call to profile_definition
     // above but we don't want the user to edit this here).
     // Hidden fields.
     $mform->addElement('hidden', 'iid');
     $mform->setType('iid', PARAM_INT);
     $mform->addElement('hidden', 'auth');
     $mform->setDefault('auth', '');
     $mform->setType('auth', PARAM_TEXT);
     $mform->addElement('hidden', 'previewrows');
     $mform->setType('previewrows', PARAM_INT);
     $mform->addElement('hidden', 'readcount');
     $mform->setType('readcount', PARAM_INT);
     $mform->addElement('hidden', 'uutype');
     $mform->setType('uutype', PARAM_INT);
     $mform->addElement('hidden', 'companyid', $this->selectedcompany);
     $mform->setType('companyid', PARAM_INT);
 }
Example #22
0
 public function test_restore_course_summary_in_existing_course_without_permissions()
 {
     global $DB;
     $this->resetAfterTest();
     $dg = $this->getDataGenerator();
     $u1 = $dg->create_user();
     $managers = get_archetype_roles('manager');
     $manager = array_shift($managers);
     $roleid = $this->create_role_with_caps('moodle/course:changesummary', CAP_PROHIBIT);
     $dg->role_assign($manager->id, $u1->id);
     $dg->role_assign($roleid, $u1->id);
     $c1 = $dg->create_course(['shortname' => 'SN', 'fullname' => 'FN', 'summary' => 'DESC', 'summaryformat' => FORMAT_MOODLE]);
     $c2 = $dg->create_course(['shortname' => 'A1', 'fullname' => 'B1', 'summary' => 'C1', 'summaryformat' => FORMAT_PLAIN]);
     // The summary and format do not change.
     $backupid = $this->backup_course($c1->id);
     $restored = $this->restore_to_existing_course($backupid, $c2->id, $u1->id);
     $this->assertEquals('SN_1', $restored->shortname);
     $this->assertEquals('FN copy 1', $restored->fullname);
     $this->assertEquals($c2->summary, $restored->summary);
     $this->assertEquals($c2->summaryformat, $restored->summaryformat);
 }
 /**
  * Form Definition
  */
 function definition()
 {
     global $CFG, $COURSE;
     $mform =& $this->_form;
     $mform->addElement('header', 'autogroup', get_string('general'));
     $mform->addElement('text', 'namingscheme', get_string('namingscheme', 'group'));
     $mform->addHelpButton('namingscheme', 'namingscheme', 'group');
     $mform->addRule('namingscheme', get_string('required'), 'required', null, 'client');
     $mform->setType('namingscheme', PARAM_TEXT);
     // There must not be duplicate group names in course.
     $template = get_string('grouptemplate', 'group');
     $gname = groups_parse_name($template, 0);
     if (!groups_get_group_by_name($COURSE->id, $gname)) {
         $mform->setDefault('namingscheme', $template);
     }
     $options = array('groups' => get_string('numgroups', 'group'), 'members' => get_string('nummembers', 'group'));
     $mform->addElement('select', 'groupby', get_string('groupby', 'group'), $options);
     $mform->addElement('text', 'number', get_string('number', 'group'), 'maxlength="4" size="4"');
     $mform->setType('number', PARAM_INT);
     $mform->addRule('number', null, 'numeric', null, 'client');
     $mform->addRule('number', get_string('required'), 'required', null, 'client');
     $mform->addElement('header', 'groupmembershdr', get_string('groupmembers', 'group'));
     $mform->setExpanded('groupmembershdr', true);
     $options = array(0 => get_string('all'));
     $options += $this->_customdata['roles'];
     $mform->addElement('select', 'roleid', get_string('selectfromrole', 'group'), $options);
     $student = get_archetype_roles('student');
     $student = reset($student);
     if ($student and array_key_exists($student->id, $options)) {
         $mform->setDefault('roleid', $student->id);
     }
     if ($cohorts = cohort_get_available_cohorts(context_course::instance($COURSE->id), COHORT_WITH_ENROLLED_MEMBERS_ONLY)) {
         $options = array(0 => get_string('anycohort', 'cohort'));
         foreach ($cohorts as $c) {
             $options[$c->id] = format_string($c->name, true, context::instance_by_id($c->contextid));
         }
         $mform->addElement('select', 'cohortid', get_string('selectfromcohort', 'cohort'), $options);
         $mform->setDefault('cohortid', '0');
     } else {
         $mform->addElement('hidden', 'cohortid');
         $mform->setType('cohortid', PARAM_INT);
         $mform->setConstant('cohortid', '0');
     }
     if ($groupings = groups_get_all_groupings($COURSE->id)) {
         $options = array();
         $options[0] = get_string('none');
         foreach ($groupings as $grouping) {
             $options[$grouping->id] = format_string($grouping->name);
         }
         $mform->addElement('select', 'groupingid', get_string('selectfromgrouping', 'group'), $options);
         $mform->setDefault('groupingid', 0);
         $mform->disabledIf('groupingid', 'notingroup', 'checked');
     } else {
         $mform->addElement('hidden', 'groupingid');
         $mform->setType('groupingid', PARAM_INT);
         $mform->setConstant('groupingid', 0);
     }
     if ($groups = groups_get_all_groups($COURSE->id)) {
         $options = array();
         $options[0] = get_string('none');
         foreach ($groups as $group) {
             $options[$group->id] = format_string($group->name);
         }
         $mform->addElement('select', 'groupid', get_string('selectfromgroup', 'group'), $options);
         $mform->setDefault('groupid', 0);
         $mform->disabledIf('groupid', 'notingroup', 'checked');
     } else {
         $mform->addElement('hidden', 'groupid');
         $mform->setType('groupid', PARAM_INT);
         $mform->setConstant('groupid', 0);
     }
     $options = array('no' => get_string('noallocation', 'group'), 'random' => get_string('random', 'group'), 'firstname' => get_string('byfirstname', 'group'), 'lastname' => get_string('bylastname', 'group'), 'idnumber' => get_string('byidnumber', 'group'));
     $mform->addElement('select', 'allocateby', get_string('allocateby', 'group'), $options);
     $mform->setDefault('allocateby', 'random');
     $mform->addElement('checkbox', 'nosmallgroups', get_string('nosmallgroups', 'group'));
     $mform->disabledIf('nosmallgroups', 'groupby', 'noteq', 'members');
     $mform->addElement('checkbox', 'notingroup', get_string('notingroup', 'group'));
     $mform->disabledIf('notingroup', 'groupingid', 'neq', 0);
     $mform->disabledIf('notingroup', 'groupid', 'neq', 0);
     $mform->addElement('header', 'groupinghdr', get_string('grouping', 'group'));
     $options = array('0' => get_string('nogrouping', 'group'), '-1' => get_string('newgrouping', 'group'));
     if ($groupings = groups_get_all_groupings($COURSE->id)) {
         foreach ($groupings as $grouping) {
             $options[$grouping->id] = strip_tags(format_string($grouping->name));
         }
     }
     $mform->addElement('select', 'grouping', get_string('createingrouping', 'group'), $options);
     if ($groupings) {
         $mform->setDefault('grouping', '-1');
     }
     $mform->addElement('text', 'groupingname', get_string('groupingname', 'group'), $options);
     $mform->setType('groupingname', PARAM_TEXT);
     $mform->disabledIf('groupingname', 'grouping', 'noteq', '-1');
     $mform->addElement('hidden', 'courseid');
     $mform->setType('courseid', PARAM_INT);
     $mform->addElement('hidden', 'seed');
     $mform->setType('seed', PARAM_INT);
     $buttonarray = array();
     $buttonarray[] =& $mform->createElement('submit', 'preview', get_string('preview'));
     $buttonarray[] =& $mform->createElement('submit', 'submitbutton', get_string('submit'));
     $buttonarray[] =& $mform->createElement('cancel');
     $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
     $mform->closeHeaderBefore('buttonar');
 }
Example #24
0
 /**
  * Test course statistics api functions.
  */
 public function test_course_statistics()
 {
     $this->resetAfterTest(true);
     $dg = $this->getDataGenerator();
     $lpg = $dg->get_plugin_generator('core_competency');
     $this->setAdminUser();
     $u1 = $dg->create_user();
     $u2 = $dg->create_user();
     $u3 = $dg->create_user();
     $u4 = $dg->create_user();
     $c1 = $dg->create_course();
     $framework = $lpg->create_framework();
     // Enrol students in the course.
     $studentarch = get_archetype_roles('student');
     $studentrole = array_shift($studentarch);
     $coursecontext = context_course::instance($c1->id);
     $dg->role_assign($studentrole->id, $u1->id, $coursecontext->id);
     $dg->enrol_user($u1->id, $c1->id, $studentrole->id);
     $dg->role_assign($studentrole->id, $u2->id, $coursecontext->id);
     $dg->enrol_user($u2->id, $c1->id, $studentrole->id);
     $dg->role_assign($studentrole->id, $u3->id, $coursecontext->id);
     $dg->enrol_user($u3->id, $c1->id, $studentrole->id);
     $dg->role_assign($studentrole->id, $u4->id, $coursecontext->id);
     $dg->enrol_user($u4->id, $c1->id, $studentrole->id);
     // Create 6 competencies.
     $comp1 = $lpg->create_competency(array('competencyframeworkid' => $framework->get_id()));
     $comp2 = $lpg->create_competency(array('competencyframeworkid' => $framework->get_id()));
     $comp3 = $lpg->create_competency(array('competencyframeworkid' => $framework->get_id()));
     $comp4 = $lpg->create_competency(array('competencyframeworkid' => $framework->get_id()));
     $comp5 = $lpg->create_competency(array('competencyframeworkid' => $framework->get_id()));
     $comp6 = $lpg->create_competency(array('competencyframeworkid' => $framework->get_id()));
     // Link 6 out of 6 to a course.
     $lpg->create_course_competency(array('competencyid' => $comp1->get_id(), 'courseid' => $c1->id));
     $lpg->create_course_competency(array('competencyid' => $comp2->get_id(), 'courseid' => $c1->id));
     $lpg->create_course_competency(array('competencyid' => $comp3->get_id(), 'courseid' => $c1->id));
     $lpg->create_course_competency(array('competencyid' => $comp4->get_id(), 'courseid' => $c1->id));
     $lpg->create_course_competency(array('competencyid' => $comp5->get_id(), 'courseid' => $c1->id));
     $lpg->create_course_competency(array('competencyid' => $comp6->get_id(), 'courseid' => $c1->id));
     // Rate some competencies.
     // User 1.
     api::grade_competency_in_course($c1, $u1->id, $comp1->get_id(), 4, 'Unit test');
     api::grade_competency_in_course($c1, $u1->id, $comp2->get_id(), 4, 'Unit test');
     api::grade_competency_in_course($c1, $u1->id, $comp3->get_id(), 4, 'Unit test');
     api::grade_competency_in_course($c1, $u1->id, $comp4->get_id(), 4, 'Unit test');
     // User 2.
     api::grade_competency_in_course($c1, $u2->id, $comp1->get_id(), 1, 'Unit test');
     api::grade_competency_in_course($c1, $u2->id, $comp2->get_id(), 1, 'Unit test');
     api::grade_competency_in_course($c1, $u2->id, $comp3->get_id(), 1, 'Unit test');
     api::grade_competency_in_course($c1, $u2->id, $comp4->get_id(), 1, 'Unit test');
     // User 3.
     api::grade_competency_in_course($c1, $u3->id, $comp1->get_id(), 3, 'Unit test');
     api::grade_competency_in_course($c1, $u3->id, $comp2->get_id(), 3, 'Unit test');
     // User 4.
     api::grade_competency_in_course($c1, $u4->id, $comp1->get_id(), 2, 'Unit test');
     api::grade_competency_in_course($c1, $u4->id, $comp2->get_id(), 2, 'Unit test');
     // OK we have enough data - lets call some API functions and check for expected results.
     $result = api::count_proficient_competencies_in_course_for_user($c1->id, $u1->id);
     $this->assertEquals(4, $result);
     $result = api::count_proficient_competencies_in_course_for_user($c1->id, $u2->id);
     $this->assertEquals(0, $result);
     $result = api::count_proficient_competencies_in_course_for_user($c1->id, $u3->id);
     $this->assertEquals(2, $result);
     $result = api::count_proficient_competencies_in_course_for_user($c1->id, $u4->id);
     $this->assertEquals(0, $result);
     $result = api::get_least_proficient_competencies_for_course($c1->id, 0, 2);
     // We should get 5 and 6 in repeatable order.
     $valid = false;
     if ($comp5->get_id() == $result[0]->get_id() || $comp6->get_id() == $result[0]->get_id()) {
         $valid = true;
     }
     $this->assertTrue($valid);
     $valid = false;
     if ($comp5->get_id() == $result[1]->get_id() || $comp6->get_id() == $result[1]->get_id()) {
         $valid = true;
     }
     $this->assertTrue($valid);
     $expected = $result[1]->get_id();
     $result = api::get_least_proficient_competencies_for_course($c1->id, 1, 1);
     $this->assertEquals($result[0]->get_id(), $expected);
 }
Example #25
0
/**
 * Returns a role object that is the default role for new enrolments in a given course
 *
 * @deprecated
 * @param object $course
 * @return object returns a role or NULL if none set
 */
function get_default_course_role($course) {
    debugging('Function get_default_course_role() is deprecated, please use individual enrol plugin settings instead!');

    $student = get_archetype_roles('student');
    $student = reset($student);

    return $student;
}
 /**
  * Form Definition
  */
 function definition()
 {
     global $CFG, $COURSE;
     $mform =& $this->_form;
     $mform->addElement('header', 'autogroup', get_string('autocreategroups', 'group'));
     $options = array(0 => get_string('all'));
     $options += $this->_customdata['roles'];
     $mform->addElement('select', 'roleid', get_string('selectfromrole', 'group'), $options);
     $student = get_archetype_roles('student');
     $student = reset($student);
     if ($student and array_key_exists($student->id, $options)) {
         $mform->setDefault('roleid', $student->id);
     }
     $context = context_course::instance($COURSE->id);
     if (has_capability('moodle/cohort:view', $context)) {
         $options = cohort_get_visible_list($COURSE);
         if ($options) {
             $options = array(0 => get_string('anycohort', 'cohort')) + $options;
             $mform->addElement('select', 'cohortid', get_string('selectfromcohort', 'cohort'), $options);
             $mform->setDefault('cohortid', '0');
         } else {
             $mform->addElement('hidden', 'cohortid');
             $mform->setType('cohortid', PARAM_INT);
             $mform->setConstant('cohortid', '0');
         }
     } else {
         $mform->addElement('hidden', 'cohortid');
         $mform->setType('cohortid', PARAM_INT);
         $mform->setConstant('cohortid', '0');
     }
     $options = array('groups' => get_string('numgroups', 'group'), 'members' => get_string('nummembers', 'group'));
     $mform->addElement('select', 'groupby', get_string('groupby', 'group'), $options);
     $mform->addElement('text', 'number', get_string('number', 'group'), 'maxlength="4" size="4"');
     $mform->setType('number', PARAM_INT);
     $mform->addRule('number', null, 'numeric', null, 'client');
     $mform->addRule('number', get_string('required'), 'required', null, 'client');
     $mform->addElement('checkbox', 'nosmallgroups', get_string('nosmallgroups', 'group'));
     $mform->disabledIf('nosmallgroups', 'groupby', 'noteq', 'members');
     $mform->setAdvanced('nosmallgroups');
     $options = array('no' => get_string('noallocation', 'group'), 'random' => get_string('random', 'group'), 'firstname' => get_string('byfirstname', 'group'), 'lastname' => get_string('bylastname', 'group'), 'idnumber' => get_string('byidnumber', 'group'));
     $mform->addElement('select', 'allocateby', get_string('allocateby', 'group'), $options);
     $mform->setDefault('allocateby', 'random');
     $mform->setAdvanced('allocateby');
     $mform->addElement('text', 'namingscheme', get_string('namingscheme', 'group'));
     $mform->addHelpButton('namingscheme', 'namingscheme', 'group');
     $mform->addRule('namingscheme', get_string('required'), 'required', null, 'client');
     $mform->setType('namingscheme', PARAM_TEXT);
     // there must not be duplicate group names in course
     $template = get_string('grouptemplate', 'group');
     $gname = groups_parse_name($template, 0);
     if (!groups_get_group_by_name($COURSE->id, $gname)) {
         $mform->setDefault('namingscheme', $template);
     }
     $options = array('0' => get_string('no'), '-1' => get_string('newgrouping', 'group'));
     if ($groupings = groups_get_all_groupings($COURSE->id)) {
         foreach ($groupings as $grouping) {
             $options[$grouping->id] = strip_tags(format_string($grouping->name));
         }
     }
     $mform->addElement('select', 'grouping', get_string('createingrouping', 'group'), $options);
     if ($groupings) {
         $mform->setDefault('grouping', '-1');
     }
     $mform->addElement('text', 'groupingname', get_string('groupingname', 'group'), $options);
     $mform->setType('groupingname', PARAM_TEXT);
     $mform->disabledIf('groupingname', 'grouping', 'noteq', '-1');
     $mform->addElement('hidden', 'courseid');
     $mform->setType('courseid', PARAM_INT);
     $mform->addElement('hidden', 'seed');
     $mform->setType('seed', PARAM_INT);
     $buttonarray = array();
     $buttonarray[] =& $mform->createElement('submit', 'preview', get_string('preview'));
     $buttonarray[] =& $mform->createElement('submit', 'submitbutton', get_string('submit'));
     $buttonarray[] =& $mform->createElement('cancel');
     $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
     $mform->closeHeaderBefore('buttonar');
 }
Example #27
0
/**
 * Assign the defaults found in this capability definition to roles that have
 * the corresponding legacy capabilities assigned to them.
 *
 * @param string $capability
 * @param array $legacyperms an array in the format (example):
 *                      'guest' => CAP_PREVENT,
 *                      'student' => CAP_ALLOW,
 *                      'teacher' => CAP_ALLOW,
 *                      'editingteacher' => CAP_ALLOW,
 *                      'coursecreator' => CAP_ALLOW,
 *                      'manager' => CAP_ALLOW
 * @return boolean success or failure.
 */
function assign_legacy_capabilities($capability, $legacyperms)
{
    $archetypes = get_role_archetypes();
    foreach ($legacyperms as $type => $perm) {
        $systemcontext = context_system::instance();
        if ($type === 'admin') {
            debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
            $type = 'manager';
        }
        if (!array_key_exists($type, $archetypes)) {
            print_error('invalidlegacy', '', '', $type);
        }
        if ($roles = get_archetype_roles($type)) {
            foreach ($roles as $role) {
                // Assign a site level capability.
                if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 /**
  * Definition of group creation form
  */
 protected function definition()
 {
     global $CFG, $DB, $PAGE;
     $mform = $this->_form;
     $mform->addElement('hidden', 'id');
     $mform->setDefault('id', $this->_customdata['id']);
     $mform->setType('id', PARAM_INT);
     $this->context = \context_module::instance($this->_customdata['id']);
     $cm = get_coursemodule_from_id('grouptool', $this->_customdata['id']);
     $course = $DB->get_record('course', array('id' => $cm->course));
     $grouptool = $DB->get_record('grouptool', array('id' => $cm->instance), '*', MUST_EXIST);
     $coursecontext = \context_course::instance($cm->course);
     $mform->addElement('hidden', 'tab');
     $mform->setDefault('tab', 'group_creation');
     $mform->setType('tab', PARAM_TEXT);
     if (has_capability('mod/grouptool:create_groups', $this->context)) {
         /* -------------------------------------------------------------------------------
          * Adding the "group creation" fieldset, where all the common settings are showed!
          */
         $mform->addElement('header', 'group_creation', get_string('groupcreation', 'grouptool'));
         $options = array(0 => get_string('all'));
         $options += $this->_customdata['roles'];
         $mform->addElement('select', 'roleid', get_string('selectfromrole', 'group'), $options);
         $student = get_archetype_roles('student');
         $student = reset($student);
         if ($student and array_key_exists($student->id, $options)) {
             $mform->setDefault('roleid', $student->id);
         }
         $canviewcohorts = has_capability('moodle/cohort:view', $this->context);
         if ($canviewcohorts) {
             $cohorts = cohort_get_available_cohorts($coursecontext, true, 0, 0);
             if (count($cohorts) != 0) {
                 $options = array(0 => get_string('anycohort', 'cohort'));
                 foreach ($cohorts as $cohort) {
                     $options[$cohort->id] = $cohort->name;
                 }
                 $mform->addElement('select', 'cohortid', get_string('selectfromcohort', 'grouptool'), $options);
                 $mform->setDefault('cohortid', '0');
             }
         } else {
             $cohorts = array();
         }
         if (!$canviewcohorts || count($cohorts) == 0) {
             $mform->addElement('hidden', 'cohortid');
             $mform->setType('cohortid', PARAM_INT);
             $mform->setConstant('cohortid', '0');
         }
         $mform->addElement('hidden', 'seed');
         $mform->setType('seed', PARAM_INT);
         $radioarray = array();
         $radioarray[] = $mform->createElement('radio', 'mode', '', get_string('define_amount_groups', 'grouptool'), GROUPTOOL_GROUPS_AMOUNT);
         $radioarray[] = $mform->createElement('radio', 'mode', '', get_string('define_amount_members', 'grouptool'), GROUPTOOL_MEMBERS_AMOUNT);
         $radioarray[] = $mform->createElement('radio', 'mode', '', get_string('create_1_person_groups', 'grouptool'), GROUPTOOL_1_PERSON_GROUPS);
         $radioarray[] = $mform->createElement('radio', 'mode', '', get_string('create_fromto_groups', 'grouptool'), GROUPTOOL_FROMTO_GROUPS);
         $mform->addGroup($radioarray, 'modearray', get_string('groupcreationmode', 'grouptool'), \html_writer::empty_tag('br'), false);
         $mform->setDefault('mode', GROUPTOOL_GROUPS_AMOUNT);
         $mform->addHelpButton('modearray', 'groupcreationmode', 'grouptool');
         $mform->addElement('text', 'amount', get_string('group_or_member_count', 'grouptool'), array('size' => '4'));
         $mform->disabledif('amount', 'mode', 'eq', GROUPTOOL_1_PERSON_GROUPS);
         $mform->disabledif('amount', 'mode', 'eq', GROUPTOOL_FROMTO_GROUPS);
         /*
          * We have to clean this params by ourselves afterwards otherwise we get problems
          * with texts getting mapped to 0
          */
         $mform->setType('amount', PARAM_RAW);
         $mform->setDefault('amount', 2);
         $fromto = array();
         $fromto[] = $mform->createElement('text', 'from', get_string('from'));
         $mform->setDefault('from', 0);
         /*
          * We have to clean this params by ourselves afterwards otherwise we get problems
          * with texts getting mapped to 0
          */
         $mform->setType('from', PARAM_RAW);
         $fromto[] = $mform->createElement('text', 'to', get_string('to'));
         $mform->setDefault('to', 0);
         /*
          * We have to clean this params by ourselves afterwards otherwise we get problems
          * with texts getting mapped to 0
          */
         $mform->setType('to', PARAM_RAW);
         $fromto[] = $mform->createElement('text', 'digits', get_string('digits', 'grouptool'));
         $mform->setDefault('digits', 2);
         /*
          * We have to clean this params by ourselves afterwards otherwise we get problems
          * with texts getting mapped to 0
          */
         $mform->setType('digits', PARAM_RAW);
         $mform->addGroup($fromto, 'fromto', get_string('groupfromtodigits', 'grouptool'), array(' ' . \html_writer::tag('label', '-', array('for' => 'id_from')) . ' ', ' ' . \html_writer::tag('label', get_string('digits', 'grouptool'), array('for' => 'id_digits')) . ' '), false);
         $mform->disabledif('from', 'mode', 'noteq', GROUPTOOL_FROMTO_GROUPS);
         $mform->disabledif('to', 'mode', 'noteq', GROUPTOOL_FROMTO_GROUPS);
         $mform->disabledif('digits', 'mode', 'noteq', GROUPTOOL_FROMTO_GROUPS);
         $mform->setAdvanced('fromto');
         $mform->addElement('checkbox', 'nosmallgroups', get_string('nosmallgroups', 'group'));
         $mform->addHelpButton('nosmallgroups', 'nosmallgroups', 'grouptool');
         $mform->disabledif('nosmallgroups', 'mode', 'noteq', GROUPTOOL_MEMBERS_AMOUNT);
         $mform->disabledif('nosmallgroups', 'mode', 'eq', GROUPTOOL_FROMTO_GROUPS);
         $mform->setAdvanced('nosmallgroups');
         $options = array('no' => get_string('noallocation', 'group'), 'random' => get_string('random', 'group'), 'firstname' => get_string('byfirstname', 'group'), 'lastname' => get_string('bylastname', 'group'), 'idnumber' => get_string('byidnumber', 'group'));
         $mform->addElement('select', 'allocateby', get_string('allocateby', 'group'), $options);
         if ($grouptool->allow_reg) {
             $mform->setDefault('allocateby', 'no');
         } else {
             $mform->setDefault('allocateby', 'random');
         }
         $mform->disabledif('allocateby', 'mode', 'eq', GROUPTOOL_1_PERSON_GROUPS);
         $mform->disabledif('allocateby', 'mode', 'eq', GROUPTOOL_FROMTO_GROUPS);
         $naminggrp = array();
         $naminggrp[] =& $mform->createElement('text', 'namingscheme', '', array('size' => '64'));
         $naminggrp[] =& $mform->createElement('static', 'tags', '', get_string('name_scheme_tags', 'grouptool'));
         $namingstd = get_config('mod_grouptool', 'name_scheme');
         $namingstd = !empty($namingstd) ? $namingstd : get_string('group', 'group') . ' #';
         $mform->setDefault('namingscheme', $namingstd);
         $mform->setType('namingscheme', PARAM_RAW);
         $mform->addGroup($naminggrp, 'naminggrp', get_string('namingscheme', 'grouptool'), ' ', false);
         $mform->addHelpButton('naminggrp', 'namingscheme', 'grouptool');
         // Init JS!
         $PAGE->requires->string_for_js('showmore', 'form');
         $PAGE->requires->string_for_js('showless', 'form');
         $PAGE->requires->yui_module('moodle-mod_grouptool-groupcreation', 'M.mod_grouptool.init_groupcreation', array(array('fromto_mode' => GROUPTOOL_FROMTO_GROUPS)));
         $selectgroups = $mform->createElement('selectgroups', 'grouping', get_string('createingrouping', 'group'));
         $options = array('0' => get_string('no'));
         if (has_capability('mod/grouptool:create_groupings', $this->context)) {
             $options['-1'] = get_string('onenewgrouping', 'grouptool');
         }
         $selectgroups->addOptGroup("", $options);
         if ($groupings = groups_get_all_groupings($course->id)) {
             $options = array();
             foreach ($groupings as $grouping) {
                 $options[$grouping->id] = strip_tags(format_string($grouping->name));
             }
             $selectgroups->addOptGroup("————————————————————————", $options);
         }
         $mform->addElement($selectgroups);
         if ($groupings) {
             $mform->setDefault('grouping', '0');
         }
         if (has_capability('mod/grouptool:create_groupings', $this->context)) {
             $mform->addElement('text', 'groupingname', get_string('groupingname', 'group'));
             $mform->setType('groupingname', PARAM_MULTILANG);
             $mform->disabledif('groupingname', 'grouping', 'noteq', '-1');
         }
         $mform->addElement('submit', 'createGroups', get_string('createGroups', 'grouptool'));
     }
 }