Пример #1
0
 function definition()
 {
     global $CFG;
     $mform =& $this->_form;
     // get list of categories to use as parents, with site as the first one
     $options = array(get_string('top'));
     $parents = array();
     make_categories_list($options, $parents);
     $mform->addElement('select', 'parent', get_string('parentcategory'), $options);
     $mform->addElement('text', 'name', get_string('categoryname'), array('size' => '30'));
     $mform->addRule('name', get_string('required'), 'required', null);
     $mform->addElement('htmleditor', 'description', get_string('description'));
     $mform->setType('description', PARAM_RAW);
     if (!empty($CFG->allowcategorythemes)) {
         $themes = array();
         $themes[''] = get_string('forceno');
         $themes += get_list_of_themes();
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $mform->setHelpButton('description', array('writing', 'richtext'), false, 'editorhelpbutton');
     $mform->addElement('hidden', 'id', null);
     $mform->addElement('hidden', 'categoryadd', 0);
     $mform->setType('id', PARAM_INT);
     $this->add_action_buttons(true, get_string('savechanges'));
 }
 function definition()
 {
     global $CFG;
     $mform =& $this->_form;
     $category = $this->_customdata;
     // get list of categories to use as parents, with site as the first one
     $options = array(get_string('top'));
     $parents = array();
     if ($category->id) {
         // Editing an existing category.
         make_categories_list($options, $parents, 'moodle/category:manage', $category->id);
         $strsubmit = get_string('savechanges');
     } else {
         // Making a new category
         make_categories_list($options, $parents, 'moodle/category:manage');
         $strsubmit = get_string('createcategory');
     }
     $mform->addElement('select', 'parent', get_string('parentcategory'), $options);
     $mform->addElement('text', 'name', get_string('categoryname'), array('size' => '30'));
     $mform->addRule('name', get_string('required'), 'required', null);
     $mform->addElement('htmleditor', 'description', get_string('description'));
     $mform->setType('description', PARAM_RAW);
     if (!empty($CFG->allowcategorythemes)) {
         $themes = array();
         $themes[''] = get_string('forceno');
         $themes += get_list_of_themes();
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $mform->setHelpButton('description', array('writing', 'richtext2'), false, 'editorhelpbutton');
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     $mform->setDefault('id', $category->id);
     $this->add_action_buttons(true, $strsubmit);
 }
Пример #3
0
 function get_options($dataobject)
 {
     $result = get_list_of_themes();
     //option for not setting a cluster theme
     $unset_option = array('' => get_string('unset_theme_option', 'crlm_manual'));
     return $unset_option + $result;
 }
Пример #4
0
 function get_options($dataobject)
 {
     $result = array();
     //get list of theme objects
     $themes = get_list_of_themes();
     foreach ($themes as $theme) {
         //we just need the name of each theme
         $result[$theme->name] = $theme->name;
     }
     //option for not setting a cluster theme
     $unset_option = array('' => get_string('unset_theme_option', 'elisfields_manual'));
     return $unset_option + $result;
 }
Пример #5
0
    function definition() {
        global $CFG, $DB;
        $mform =& $this->_form;
        $category = $this->_customdata['category'];
        $editoroptions = $this->_customdata['editoroptions'];

        // get list of categories to use as parents, with site as the first one
        $options = array();
        if (has_capability('moodle/category:manage', context_system::instance()) || $category->parent == 0) {
            $options[0] = get_string('top');
        }
        if ($category->id) {
            // Editing an existing category.
            $options += coursecat::make_categories_list('moodle/category:manage', $category->id);
            if (empty($options[$category->parent])) {
                $options[$category->parent] = $DB->get_field('course_categories', 'name', array('id'=>$category->parent));
            }
            $strsubmit = get_string('savechanges');
        } else {
            // Making a new category
            $options += coursecat::make_categories_list('moodle/category:manage');
            $strsubmit = get_string('createcategory');
        }

        $mform->addElement('select', 'parent', get_string('parentcategory'), $options);
        $mform->addElement('text', 'name', get_string('categoryname'), array('size'=>'30'));
        $mform->addRule('name', get_string('required'), 'required', null);
        $mform->setType('name', PARAM_TEXT);
        $mform->addElement('text', 'idnumber', get_string('idnumbercoursecategory'),'maxlength="100"  size="10"');
        $mform->addHelpButton('idnumber', 'idnumbercoursecategory');
        $mform->setType('idnumber', PARAM_RAW);
        $mform->addElement('editor', 'description_editor', get_string('description'), null, $editoroptions);
        $mform->setType('description_editor', PARAM_RAW);
        if (!empty($CFG->allowcategorythemes)) {
            $themes = array(''=>get_string('forceno'));
            $allthemes = get_list_of_themes();
            foreach ($allthemes as $key=>$theme) {
                if (empty($theme->hidefromselector)) {
                    $themes[$key] = get_string('pluginname', 'theme_'.$theme->name);
                }
            }
            $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
        }

        $mform->addElement('hidden', 'id', 0);
        $mform->setType('id', PARAM_INT);
        $mform->setDefault('id', $category->id);

        $this->add_action_buttons(true, $strsubmit);
    }
 function get_content()
 {
     global $CFG, $ME, $COURSE;
     //get list of themes
     $themes = get_list_of_themes();
     if ($this->content !== NULL) {
         return $this->content;
     }
     $this->content->footer = '';
     $this->content->text = '';
     $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id);
     if (has_capability('block/session_theme:switchthemes', $context)) {
         $this->content->text .= popup_form($ME . '?id=' . $COURSE->id . '&theme=', $themes, 'sessionthemeform', current_theme(), 'choose', '', '', true);
         $this->content->footer .= '';
     } else {
         $this->content = '';
     }
     return $this->content;
 }
 function definition()
 {
     global $CFG, $DB;
     $mform =& $this->_form;
     $category = $this->_customdata['category'];
     $editoroptions = $this->_customdata['editoroptions'];
     // get list of categories to use as parents, with site as the first one
     $options = array();
     if (has_capability('moodle/category:manage', get_system_context()) || $category->parent == 0) {
         $options[0] = get_string('top');
     }
     $parents = array();
     if ($category->id) {
         // Editing an existing category.
         //make_categories_list($options, $parents, 'moodle/category:manage', $category->id);
         if (empty($options[$category->parent])) {
             $options[$category->parent] = $DB->get_field('course_categories', 'name', array('id' => $category->parent));
         }
         $strsubmit = get_string('savechanges');
     } else {
         // Making a new category
         //make_categories_list($options, $parents, 'moodle/category:manage');
         $strsubmit = 'Crear materia';
     }
     $mform->addElement('select', 'parent', 'Materia padre', $options);
     $mform->addElement('text', 'name', 'Nombre de la materia', array('size' => '30'));
     $mform->addRule('name', get_string('required'), 'required', null);
     $mform->addElement('editor', 'description_editor', get_string('description'), null, $editoroptions);
     $mform->setType('description_editor', PARAM_RAW);
     if (!empty($CFG->allowcategorythemes)) {
         $themes = array('' => get_string('forceno'));
         $allthemes = get_list_of_themes();
         foreach ($allthemes as $key => $theme) {
             $themes[$key] = $theme->name;
         }
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     $mform->setDefault('id', $category->id);
     $this->add_action_buttons(true, $strsubmit);
 }
Пример #8
0
 function definition()
 {
     global $USER, $CFG, $DB, $PAGE;
     $mform = $this->_form;
     $PAGE->requires->yui_module('moodle-course-formatchooser', 'M.course.init_formatchooser', array(array('formid' => $mform->getAttribute('id'))));
     $course = $this->_customdata['course'];
     // this contains the data of this form
     $category = $this->_customdata['category'];
     $editoroptions = $this->_customdata['editoroptions'];
     $returnto = $this->_customdata['returnto'];
     $systemcontext = context_system::instance();
     $categorycontext = context_coursecat::instance($category->id);
     if (!empty($course->id)) {
         $coursecontext = context_course::instance($course->id);
         $context = $coursecontext;
     } else {
         $coursecontext = null;
         $context = $categorycontext;
     }
     $courseconfig = get_config('moodlecourse');
     $this->course = $course;
     $this->context = $context;
     /// form definition with new course defaults
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     $mform->addElement('hidden', 'returnto', null);
     $mform->setType('returnto', PARAM_ALPHANUM);
     $mform->setConstant('returnto', $returnto);
     $mform->addElement('text', 'fullname', get_string('fullnamecourse'), 'maxlength="254" size="50"');
     $mform->addHelpButton('fullname', 'fullnamecourse');
     $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
     $mform->setType('fullname', PARAM_TEXT);
     if (!empty($course->id) and !has_capability('moodle/course:changefullname', $coursecontext)) {
         $mform->hardFreeze('fullname');
         $mform->setConstant('fullname', $course->fullname);
     }
     $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
     $mform->addHelpButton('shortname', 'shortnamecourse');
     $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
     $mform->setType('shortname', PARAM_TEXT);
     if (!empty($course->id) and !has_capability('moodle/course:changeshortname', $coursecontext)) {
         $mform->hardFreeze('shortname');
         $mform->setConstant('shortname', $course->shortname);
     }
     // Verify permissions to change course category or keep current.
     if (empty($course->id)) {
         if (has_capability('moodle/course:create', $categorycontext)) {
             $displaylist = coursecat::make_categories_list('moodle/course:create');
             $mform->addElement('select', 'category', get_string('coursecategory'), $displaylist);
             $mform->addHelpButton('category', 'coursecategory');
             $mform->setDefault('category', $category->id);
         } else {
             $mform->addElement('hidden', 'category', null);
             $mform->setType('category', PARAM_INT);
             $mform->setConstant('category', $category->id);
         }
     } else {
         if (has_capability('moodle/course:changecategory', $coursecontext)) {
             $displaylist = coursecat::make_categories_list('moodle/course:create');
             if (!isset($displaylist[$course->category])) {
                 //always keep current
                 $displaylist[$course->category] = coursecat::get($course->category)->get_formatted_name();
             }
             $mform->addElement('select', 'category', get_string('coursecategory'), $displaylist);
             $mform->addHelpButton('category', 'coursecategory');
         } else {
             //keep current
             $mform->addElement('hidden', 'category', null);
             $mform->setType('category', PARAM_INT);
             $mform->setConstant('category', $course->category);
         }
     }
     $choices = array();
     $choices['0'] = get_string('hide');
     $choices['1'] = get_string('show');
     $mform->addElement('select', 'visible', get_string('visible'), $choices);
     $mform->addHelpButton('visible', 'visible');
     $mform->setDefault('visible', $courseconfig->visible);
     if (!has_capability('moodle/course:visibility', $context)) {
         $mform->hardFreeze('visible');
         if (!empty($course->id)) {
             $mform->setConstant('visible', $course->visible);
         } else {
             $mform->setConstant('visible', $courseconfig->visible);
         }
     }
     $mform->addElement('date_selector', 'startdate', get_string('startdate'));
     $mform->addHelpButton('startdate', 'startdate');
     $mform->setDefault('startdate', time() + 3600 * 24);
     $mform->addElement('text', 'idnumber', get_string('idnumbercourse'), 'maxlength="100"  size="10"');
     $mform->addHelpButton('idnumber', 'idnumbercourse');
     $mform->setType('idnumber', PARAM_RAW);
     if (!empty($course->id) and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
         $mform->hardFreeze('idnumber');
         $mform->setConstants('idnumber', $course->idnumber);
     }
     // Description.
     $mform->addElement('header', 'descriptionhdr', get_string('description'));
     $mform->setExpanded('descriptionhdr');
     $mform->addElement('editor', 'summary_editor', get_string('coursesummary'), null, $editoroptions);
     $mform->addHelpButton('summary_editor', 'coursesummary');
     $mform->setType('summary_editor', PARAM_RAW);
     $summaryfields = 'summary_editor';
     if ($overviewfilesoptions = course_overviewfiles_options($course)) {
         $mform->addElement('filemanager', 'overviewfiles_filemanager', get_string('courseoverviewfiles'), null, $overviewfilesoptions);
         $mform->addHelpButton('overviewfiles_filemanager', 'courseoverviewfiles');
         $summaryfields .= ',overviewfiles_filemanager';
     }
     if (!empty($course->id) and !has_capability('moodle/course:changesummary', $coursecontext)) {
         // Remove the description header it does not contain anything any more.
         $mform->removeElement('descriptionhdr');
         $mform->hardFreeze($summaryfields);
     }
     // Course format.
     $mform->addElement('header', 'courseformathdr', get_string('type_format', 'plugin'));
     $courseformats = get_sorted_course_formats(true);
     $formcourseformats = array();
     foreach ($courseformats as $courseformat) {
         $formcourseformats[$courseformat] = get_string('pluginname', "format_{$courseformat}");
     }
     if (isset($course->format)) {
         $course->format = course_get_format($course)->get_format();
         // replace with default if not found
         if (!in_array($course->format, $courseformats)) {
             // this format is disabled. Still display it in the dropdown
             $formcourseformats[$course->format] = get_string('withdisablednote', 'moodle', get_string('pluginname', 'format_' . $course->format));
         }
     }
     $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
     $mform->addHelpButton('format', 'format');
     $mform->setDefault('format', $courseconfig->format);
     // Button to update format-specific options on format change (will be hidden by JavaScript).
     $mform->registerNoSubmitButton('updatecourseformat');
     $mform->addElement('submit', 'updatecourseformat', get_string('courseformatudpate'));
     // Just a placeholder for the course format options.
     $mform->addElement('hidden', 'addcourseformatoptionshere');
     $mform->setType('addcourseformatoptionshere', PARAM_BOOL);
     // Appearance.
     $mform->addElement('header', 'appearancehdr', get_string('appearance'));
     if (!empty($CFG->allowcoursethemes)) {
         $themeobjects = get_list_of_themes();
         $themes = array();
         $themes[''] = get_string('forceno');
         foreach ($themeobjects as $key => $theme) {
             if (empty($theme->hidefromselector)) {
                 $themes[$key] = get_string('pluginname', 'theme_' . $theme->name);
             }
         }
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $languages = array();
     $languages[''] = get_string('forceno');
     $languages += get_string_manager()->get_list_of_translations();
     $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
     $mform->setDefault('lang', $courseconfig->lang);
     $options = range(0, 10);
     $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
     $mform->addHelpButton('newsitems', 'newsitemsnumber');
     $mform->setDefault('newsitems', $courseconfig->newsitems);
     $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
     $mform->addHelpButton('showgrades', 'showgrades');
     $mform->setDefault('showgrades', $courseconfig->showgrades);
     $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
     $mform->addHelpButton('showreports', 'showreports');
     $mform->setDefault('showreports', $courseconfig->showreports);
     // Files and uploads.
     $mform->addElement('header', 'filehdr', get_string('filesanduploads'));
     if (!empty($course->legacyfiles) or !empty($CFG->legacyfilesinnewcourses)) {
         if (empty($course->legacyfiles)) {
             //0 or missing means no legacy files ever used in this course - new course or nobody turned on legacy files yet
             $choices = array('0' => get_string('no'), '2' => get_string('yes'));
         } else {
             $choices = array('1' => get_string('no'), '2' => get_string('yes'));
         }
         $mform->addElement('select', 'legacyfiles', get_string('courselegacyfiles'), $choices);
         $mform->addHelpButton('legacyfiles', 'courselegacyfiles');
         if (!isset($courseconfig->legacyfiles)) {
             // in case this was not initialised properly due to switching of $CFG->legacyfilesinnewcourses
             $courseconfig->legacyfiles = 0;
         }
         $mform->setDefault('legacyfiles', $courseconfig->legacyfiles);
     }
     // Handle non-existing $course->maxbytes on course creation.
     $coursemaxbytes = !isset($course->maxbytes) ? null : $course->maxbytes;
     // Let's prepare the maxbytes popup.
     $choices = get_max_upload_sizes($CFG->maxbytes, 0, 0, $coursemaxbytes);
     $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
     $mform->addHelpButton('maxbytes', 'maximumupload');
     $mform->setDefault('maxbytes', $courseconfig->maxbytes);
     // Completion tracking.
     if (completion_info::is_enabled_for_site()) {
         $mform->addElement('header', 'completionhdr', get_string('completion', 'completion'));
         $mform->addElement('selectyesno', 'enablecompletion', get_string('enablecompletion', 'completion'));
         $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);
         $mform->addHelpButton('enablecompletion', 'enablecompletion', 'completion');
     } else {
         $mform->addElement('hidden', 'enablecompletion');
         $mform->setType('enablecompletion', PARAM_INT);
         $mform->setDefault('enablecompletion', 0);
     }
     //--------------------------------------------------------------------------------
     enrol_course_edit_form($mform, $course, $context);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'groups', get_string('groups', 'group'));
     $choices = array();
     $choices[NOGROUPS] = get_string('groupsnone', 'group');
     $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
     $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
     $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $choices);
     $mform->addHelpButton('groupmode', 'groupmode', 'group');
     $mform->setDefault('groupmode', $courseconfig->groupmode);
     $mform->addElement('selectyesno', 'groupmodeforce', get_string('groupmodeforce', 'group'));
     $mform->addHelpButton('groupmodeforce', 'groupmodeforce', 'group');
     $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);
     //default groupings selector
     $options = array();
     $options[0] = get_string('none');
     $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);
     //--------------------------------------------------------------------------------
     /// customizable role names in this course
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'rolerenaming', get_string('rolerenaming'));
     $mform->addHelpButton('rolerenaming', 'rolerenaming');
     if ($roles = get_all_roles()) {
         $roles = role_fix_names($roles, null, ROLENAME_ORIGINAL);
         $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE);
         foreach ($roles as $role) {
             $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->localname));
             $mform->setType('role_' . $role->id, PARAM_TEXT);
         }
     }
     //--------------------------------------------------------------------------------
     $this->add_action_buttons();
     //--------------------------------------------------------------------------------
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
     /// finally set the current form data
     //--------------------------------------------------------------------------------
     $this->set_data($course);
 }
Пример #9
0
function restore_create_users($restore, $xml_file)
{
    global $CFG, $db;
    require_once $CFG->dirroot . '/tag/lib.php';
    $authcache = array();
    // Cache to get some bits from authentication plugins
    $status = true;
    // Users have already been checked by restore_precheck_users() so they are loaded
    // in backup_ids table. They don't need to be loaded (parsed) from XML again. Also, note
    // the same function has performed the needed modifications in the $user->mnethostid field
    // so we don't need to do it again here at all. Just some checks.
    // Get users ids from backup_ids table
    $userids = get_fieldset_select('backup_ids', 'old_id', "backup_code = {$restore->backup_unique_code} AND table_name = 'user'");
    // Have users to process, proceed with them
    if (!empty($userids)) {
        /// Get languages for quick search later
        $languages = get_list_of_languages();
        /// Iterate over all users loaded from xml
        $counter = 0;
        /// Init trailing messages
        $messages = array();
        foreach ($userids as $userid) {
            // Defaults
            $user_exists = false;
            // By default user does not exist
            $newid = null;
            // By default, there is not newid
            // Get record from backup_ids
            $useridsdbrec = backup_getid($restore->backup_unique_code, 'user', $userid);
            // Based in restore_precheck_users() calculations, if the user exists
            // new_id must contain the id of the matching user
            if (!empty($useridsdbrec->new_id)) {
                $user_exists = true;
                $newid = $useridsdbrec->new_id;
            }
            $user = $useridsdbrec->info;
            foreach (array_keys(get_object_vars($user)) as $field) {
                if (!is_array($user->{$field})) {
                    $user->{$field} = backup_todb($user->{$field}, false);
                    if (is_null($user->{$field})) {
                        $user->{$field} = '';
                    }
                }
            }
            //Now, recode some languages (Moodle 1.5)
            if ($user->lang == 'ma_nt') {
                $user->lang = 'mi_nt';
            }
            //Country list updates - MDL-13060
            //Any user whose country code has been deleted or modified needs to be assigned a valid one.
            $country_update_map = array('ZR' => 'CD', 'TP' => 'TL', 'FX' => 'FR', 'KO' => 'RS', 'CS' => 'RS', 'WA' => 'GB');
            if (array_key_exists($user->country, $country_update_map)) {
                $user->country = $country_update_map[$user->country];
            }
            //If language does not exist here - use site default
            if (!array_key_exists($user->lang, $languages)) {
                $user->lang = $CFG->lang;
            }
            //Check if it's admin and coursecreator
            $is_admin = !empty($user->roles['admin']);
            $is_coursecreator = !empty($user->roles['coursecreator']);
            //Check if it's teacher and student
            $is_teacher = !empty($user->roles['teacher']);
            $is_student = !empty($user->roles['student']);
            //Check if it's needed
            $is_needed = !empty($user->roles['needed']);
            //Calculate if it is a course user
            //Has role teacher or student or needed
            $is_course_user = ($is_teacher or $is_student or $is_needed);
            // Only try to perform mnethost/auth modifications if restoring to another server
            // or if, while restoring to same server, the user doesn't exists yet (rebuilt site)
            //
            // So existing user data in same server *won't be modified by restore anymore*,
            // under any circumpstance. If somehting is wrong with existing data, it's server fault.
            if (!backup_is_same_site($restore) || backup_is_same_site($restore) && !$user_exists) {
                //Arriving here, any user with mnet auth and using $CFG->mnet_localhost_id is wrong
                //as own server cannot be accesed over mnet. Change auth to manual and inform about the switch
                if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) {
                    // Respect registerauth
                    if ($CFG->registerauth == 'email') {
                        $user->auth = 'email';
                    } else {
                        $user->auth = 'manual';
                    }
                    // inform about the automatic switch of authentication/host
                    if (empty($user->mnethosturl)) {
                        $user->mnethosturl = '----';
                    }
                    $messages[] = get_string('mnetrestore_extusers_switchuserauth', 'admin', $user);
                }
            }
            unset($user->mnethosturl);
            //Flags to see what parts are we going to restore
            $create_user = true;
            $create_roles = true;
            $create_custom_profile_fields = true;
            $create_tags = true;
            $create_preferences = true;
            //If we are restoring course users and it isn't a course user
            if ($restore->users == 1 and !$is_course_user) {
                //If only restoring course_users and user isn't a course_user, inform to $backup_ids
                $status = backup_putid($restore->backup_unique_code, "user", $userid, null, 'notincourse');
                $create_user = false;
                $create_roles = false;
                $create_custom_profile_fields = false;
                $create_tags = false;
                $create_preferences = false;
            }
            if ($user_exists and $create_user) {
                //If user exists mark its newid in backup_ids (the same than old)
                $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, 'exists');
                $create_user = false;
                $create_custom_profile_fields = false;
                $create_tags = false;
                $create_preferences = false;
            }
            //Here, if create_user, do it
            if ($create_user) {
                //Unset the id because it's going to be inserted with a new one
                unset($user->id);
                /// Disable pictures based on global setting or existing empty value (old backups can contain wrong empties)
                if (!empty($CFG->disableuserimages) || empty($user->picture)) {
                    $user->picture = 0;
                }
                //We need to analyse the AUTH field to recode it:
                //   - if the field isn't set, we are in a pre 1.4 backup and $CFG->registerauth will decide
                //   - if the auth isn't enabled in target site, $CFG->registerauth will decide
                //   - finally, if the auth resulting isn't enabled, default to 'manual'
                if (empty($user->auth) || !is_enabled_auth($user->auth)) {
                    if ($CFG->registerauth == 'email') {
                        $user->auth = 'email';
                    } else {
                        $user->auth = 'manual';
                    }
                }
                if (!is_enabled_auth($user->auth)) {
                    // Final auth check verify, default to manual if not enabled
                    $user->auth = 'manual';
                }
                // Now that we know the auth method, for users to be created without pass
                // if password handling is internal and reset password is available
                // we set the password to "restored" (plain text), so the login process
                // will know how to handle that situation in order to allow the user to
                // recover the password. MDL-20846
                if (empty($user->password)) {
                    // Only if restore comes without password
                    if (!array_key_exists($user->auth, $authcache)) {
                        // Not in cache
                        $userauth = new stdClass();
                        $authplugin = get_auth_plugin($user->auth);
                        $userauth->preventpassindb = $authplugin->prevent_local_passwords();
                        $userauth->isinternal = $authplugin->is_internal();
                        $userauth->canresetpwd = $authplugin->can_reset_password();
                        $authcache[$user->auth] = $userauth;
                    } else {
                        $userauth = $authcache[$user->auth];
                        // Get from cache
                    }
                    // Most external plugins do not store passwords locally
                    if (!empty($userauth->preventpassindb)) {
                        $user->password = '******';
                        // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark
                    } else {
                        if ($userauth->isinternal and $userauth->canresetpwd) {
                            $user->password = '******';
                        }
                    }
                }
                //We need to process the POLICYAGREED field to recalculate it:
                //    - if the destination site is different (by wwwroot) reset it.
                //    - if the destination site is the same (by wwwroot), leave it unmodified
                if (!backup_is_same_site($restore)) {
                    $user->policyagreed = 0;
                } else {
                    //Nothing to do, we are in the same server
                }
                //Check if the theme exists in destination server
                $themes = get_list_of_themes();
                if (!in_array($user->theme, $themes)) {
                    $user->theme = '';
                }
                //We are going to create the user
                //The structure is exactly as we need
                $newid = insert_record("user", addslashes_recursive($user));
                //Put the new id
                $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, "new");
            }
            ///TODO: This seccion is to support pre 1.7 course backups, using old roles
            ///      teacher, coursecreator, student.... providing a basic mapping to new ones.
            ///      Someday we'll drop support for them and this section will be safely deleted (2.0?)
            //Here, if create_roles, do it as necessary
            if ($create_roles) {
                //Get the newid and current info from backup_ids
                $data = backup_getid($restore->backup_unique_code, "user", $userid);
                $newid = $data->new_id;
                $currinfo = $data->info . ",";
                //Now, depending of the role, create records in user_studentes and user_teacher
                //and/or mark it in backup_ids
                if ($is_admin) {
                    //If the record (user_admins) doesn't exists
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "admin,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_coursecreator) {
                    //If the record (user_coursecreators) doesn't exists
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "coursecreator,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_needed) {
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "needed,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_teacher) {
                    //If the record (teacher) doesn't exists
                    //Put status in backup_ids
                    $currinfo = $currinfo . "teacher,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    //Set course and user
                    $user->roles['teacher']->course = $restore->course_id;
                    $user->roles['teacher']->userid = $newid;
                    //Need to analyse the enrol field
                    //    - if it isn't set, set it to $CFG->enrol
                    //    - if we are in a different server (by wwwroot), set it to $CFG->enrol
                    //    - if we are in the same server (by wwwroot), maintain it unmodified.
                    if (empty($user->roles['teacher']->enrol)) {
                        $user->roles['teacher']->enrol = $CFG->enrol;
                    } else {
                        if (!backup_is_same_site($restore)) {
                            $user->roles['teacher']->enrol = $CFG->enrol;
                        } else {
                            //Nothing to do. Leave it unmodified
                        }
                    }
                    $rolesmapping = $restore->rolesmapping;
                    $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
                    if ($user->roles['teacher']->editall) {
                        role_assign($rolesmapping['defaultteacheredit'], $newid, 0, $context->id, $user->roles['teacher']->timestart, $user->roles['teacher']->timeend, 0, $user->roles['teacher']->enrol);
                        // editting teacher
                    } else {
                        // non editting teacher
                        role_assign($rolesmapping['defaultteacher'], $newid, 0, $context->id, $user->roles['teacher']->timestart, $user->roles['teacher']->timeend, 0, $user->roles['teacher']->enrol);
                    }
                }
                if ($is_student) {
                    //Put status in backup_ids
                    $currinfo = $currinfo . "student,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    //Set course and user
                    $user->roles['student']->course = $restore->course_id;
                    $user->roles['student']->userid = $newid;
                    //Need to analyse the enrol field
                    //    - if it isn't set, set it to $CFG->enrol
                    //    - if we are in a different server (by wwwroot), set it to $CFG->enrol
                    //    - if we are in the same server (by wwwroot), maintain it unmodified.
                    if (empty($user->roles['student']->enrol)) {
                        $user->roles['student']->enrol = $CFG->enrol;
                    } else {
                        if (!backup_is_same_site($restore)) {
                            $user->roles['student']->enrol = $CFG->enrol;
                        } else {
                            //Nothing to do. Leave it unmodified
                        }
                    }
                    $rolesmapping = $restore->rolesmapping;
                    $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
                    role_assign($rolesmapping['defaultstudent'], $newid, 0, $context->id, $user->roles['student']->timestart, $user->roles['student']->timeend, 0, $user->roles['student']->enrol);
                }
                if (!$is_course_user) {
                    //If the record (user) doesn't exists
                    if (!record_exists("user", "id", $newid)) {
                        //Put status in backup_ids
                        $currinfo = $currinfo . "user,";
                        $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    }
                }
            }
            /// Here, if create_custom_profile_fields, do it as necessary
            if ($create_custom_profile_fields) {
                if (isset($user->user_custom_profile_fields)) {
                    foreach ($user->user_custom_profile_fields as $udata) {
                        /// If the profile field has data and the profile shortname-datatype is defined in server
                        if ($udata->field_data) {
                            if ($field = get_record('user_info_field', 'shortname', $udata->field_name, 'datatype', $udata->field_type)) {
                                /// Insert the user_custom_profile_field
                                $rec = new object();
                                $rec->userid = $newid;
                                $rec->fieldid = $field->id;
                                $rec->data = $udata->field_data;
                                insert_record('user_info_data', $rec);
                            }
                        }
                    }
                }
            }
            /// Here, if create_tags, do it as necessary
            if ($create_tags) {
                /// if tags are enabled and there are user tags
                if (!empty($CFG->usetags) && isset($user->user_tags)) {
                    $tags = array();
                    foreach ($user->user_tags as $user_tag) {
                        $tags[] = $user_tag->rawname;
                    }
                    tag_set('user', $newid, $tags);
                }
            }
            //Here, if create_preferences, do it as necessary
            if ($create_preferences) {
                if (isset($user->user_preferences)) {
                    foreach ($user->user_preferences as $user_preference) {
                        //We check if that user_preference exists in DB
                        if (!record_exists("user_preferences", "userid", $newid, "name", $user_preference->name)) {
                            //Prepare the record and insert it
                            $user_preference->userid = $newid;
                            $status = insert_record("user_preferences", $user_preference);
                        }
                    }
                }
            }
            //Do some output
            $counter++;
            if ($counter % 10 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if ($counter % 200 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
        /// End of loop over all the users loaded from backup_ids table
        /// Inform about all the messages geerated while restoring users
        if (!defined('RESTORE_SILENTLY')) {
            if ($messages) {
                echo '<ul>';
                foreach ($messages as $message) {
                    echo '<li>' . $message . '</li>';
                }
                echo '</ul>';
            }
        }
    }
    return $status;
}
Пример #10
0
    function definition() {
        global $USER, $CFG, $DB;

        $mform    = $this->_form;

        $course        = $this->_customdata['course']; // this contains the data of this form
        $category      = $this->_customdata['category'];
        $editoroptions = $this->_customdata['editoroptions'];
        $returnto = $this->_customdata['returnto'];

        $systemcontext   = get_context_instance(CONTEXT_SYSTEM);
        $categorycontext = get_context_instance(CONTEXT_COURSECAT, $category->id);

        if (!empty($course->id)) {
            $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
            $context = $coursecontext;
        } else {
            $coursecontext = null;
            $context = $categorycontext;
        }

        $courseconfig = get_config('moodlecourse');

        $this->course  = $course;
        $this->context = $context;

/// form definition with new course defaults
//--------------------------------------------------------------------------------
        $mform->addElement('header','general', get_string('general', 'form'));

        $mform->addElement('hidden', 'returnto', null);
        $mform->setType('returnto', PARAM_ALPHANUM);
        $mform->setConstant('returnto', $returnto);

        // verify permissions to change course category or keep current
        if (empty($course->id)) {
            if (has_capability('moodle/course:create', $categorycontext)) {
                $displaylist = array();
                $parentlist = array();
                make_categories_list($displaylist, $parentlist, 'moodle/course:create');
                $mform->addElement('select', 'category', get_string('category'), $displaylist);
                $mform->addHelpButton('category', 'category');
                $mform->setDefault('category', $category->id);
            } else {
                $mform->addElement('hidden', 'category', null);
                $mform->setType('category', PARAM_INT);
                $mform->setConstant('category', $category->id);
            }
        } else {
            if (has_capability('moodle/course:changecategory', $coursecontext)) {
                $displaylist = array();
                $parentlist = array();
                make_categories_list($displaylist, $parentlist, 'moodle/course:create');
                if (!isset($displaylist[$course->category])) {
                    //always keep current
                    $displaylist[$course->category] = format_string($DB->get_field('course_categories', 'name', array('id'=>$course->category)));
                }
                $mform->addElement('select', 'category', get_string('category'), $displaylist);
                $mform->addHelpButton('category', 'category');
            } else {
                //keep current
                $mform->addElement('hidden', 'category', null);
                $mform->setType('category', PARAM_INT);
                $mform->setConstant('category', $course->category);
            }
        }

        $mform->addElement('text','fullname', get_string('fullnamecourse'),'maxlength="254" size="50"');
        $mform->addHelpButton('fullname', 'fullnamecourse');
        $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
        $mform->setType('fullname', PARAM_MULTILANG);
        if (!empty($course->id) and !has_capability('moodle/course:changefullname', $coursecontext)) {
            $mform->hardFreeze('fullname');
            $mform->setConstant('fullname', $course->fullname);
        }

        $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
        $mform->addHelpButton('shortname', 'shortnamecourse');
        $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
        $mform->setType('shortname', PARAM_MULTILANG);
        if (!empty($course->id) and !has_capability('moodle/course:changeshortname', $coursecontext)) {
            $mform->hardFreeze('shortname');
            $mform->setConstant('shortname', $course->shortname);
        }

        $mform->addElement('text','idnumber', get_string('idnumbercourse'),'maxlength="100"  size="10"');
        $mform->addHelpButton('idnumber', 'idnumbercourse');
        $mform->setType('idnumber', PARAM_RAW);
        if (!empty($course->id) and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
            $mform->hardFreeze('idnumber');
            $mform->setConstants('idnumber', $course->idnumber);
        }


        $mform->addElement('editor','summary_editor', get_string('coursesummary'), null, $editoroptions);
        $mform->addHelpButton('summary_editor', 'coursesummary');
        $mform->setType('summary_editor', PARAM_RAW);

        if (!empty($course->id) and !has_capability('moodle/course:changesummary', $coursecontext)) {
            $mform->hardFreeze('summary_editor');
        }

        $courseformats = get_plugin_list('format');
        $formcourseformats = array();
        foreach ($courseformats as $courseformat => $formatdir) {
            $formcourseformats[$courseformat] = get_string('pluginname', "format_$courseformat");
        }
        $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
        $mform->addHelpButton('format', 'format');
        $mform->setDefault('format', $courseconfig->format);

        for ($i=1; $i<=52; $i++) {
          $sectionmenu[$i] = "$i";
        }
        $mform->addElement('select', 'numsections', get_string('numberweeks'), $sectionmenu);
        $mform->setDefault('numsections', $courseconfig->numsections);

        $mform->addElement('date_selector', 'startdate', get_string('startdate'));
        $mform->addHelpButton('startdate', 'startdate');
        $mform->setDefault('startdate', time() + 3600 * 24);

        $choices = array();
        $choices['0'] = get_string('hiddensectionscollapsed');
        $choices['1'] = get_string('hiddensectionsinvisible');
        $mform->addElement('select', 'hiddensections', get_string('hiddensections'), $choices);
        $mform->addHelpButton('hiddensections', 'hiddensections');
        $mform->setDefault('hiddensections', $courseconfig->hiddensections);

        $options = range(0, 10);
        $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
        $mform->addHelpButton('newsitems', 'newsitemsnumber');
        $mform->setDefault('newsitems', $courseconfig->newsitems);

        $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
        $mform->addHelpButton('showgrades', 'showgrades');
        $mform->setDefault('showgrades', $courseconfig->showgrades);

        $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
        $mform->addHelpButton('showreports', 'showreports');
        $mform->setDefault('showreports', $courseconfig->showreports);

        $choices = get_max_upload_sizes($CFG->maxbytes);
        $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
        $mform->addHelpButton('maxbytes', 'maximumupload');
        $mform->setDefault('maxbytes', $courseconfig->maxbytes);

        if (!empty($course->legacyfiles) or !empty($CFG->legacyfilesinnewcourses)) {
            if (empty($course->legacyfiles)) {
                //0 or missing means no legacy files ever used in this course - new course or nobody turned on legacy files yet
                $choices = array('0'=>get_string('no'), '2'=>get_string('yes'));
            } else {
                $choices = array('1'=>get_string('no'), '2'=>get_string('yes'));
            }
            $mform->addElement('select', 'legacyfiles', get_string('courselegacyfiles'), $choices);
            $mform->addHelpButton('legacyfiles', 'courselegacyfiles');
            if (!isset($courseconfig->legacyfiles)) {
                // in case this was not initialised properly due to switching of $CFG->legacyfilesinnewcourses
                $courseconfig->legacyfiles = 0;
            }
            $mform->setDefault('legacyfiles', $courseconfig->legacyfiles);
        }

        if (!empty($CFG->allowcoursethemes)) {
            $themeobjects = get_list_of_themes();
            $themes=array();
            $themes[''] = get_string('forceno');
            foreach ($themeobjects as $key=>$theme) {
                $themes[$key] = $theme->name;
            }
            $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
        }

//--------------------------------------------------------------------------------
        enrol_course_edit_form($mform, $course, $context);

//--------------------------------------------------------------------------------
        $mform->addElement('header','', get_string('groups', 'group'));

        $choices = array();
        $choices[NOGROUPS] = get_string('groupsnone', 'group');
        $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
        $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
        $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $choices);
        $mform->addHelpButton('groupmode', 'groupmode', 'group');
        $mform->setDefault('groupmode', $courseconfig->groupmode);

        $choices = array();
        $choices['0'] = get_string('no');
        $choices['1'] = get_string('yes');
        $mform->addElement('select', 'groupmodeforce', get_string('groupmodeforce', 'group'), $choices);
        $mform->addHelpButton('groupmodeforce', 'groupmodeforce', 'group');
        $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);

        //default groupings selector
        $options = array();
        $options[0] = get_string('none');
        $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);

//--------------------------------------------------------------------------------
        $mform->addElement('header','', get_string('availability'));

        $choices = array();
        $choices['0'] = get_string('courseavailablenot');
        $choices['1'] = get_string('courseavailable');
        $mform->addElement('select', 'visible', get_string('availability'), $choices);
        $mform->addHelpButton('visible', 'availability');
        $mform->setDefault('visible', $courseconfig->visible);
        if (!has_capability('moodle/course:visibility', $context)) {
            $mform->hardFreeze('visible');
            if (!empty($course->id)) {
                $mform->setConstant('visible', $course->visible);
            } else {
                $mform->setConstant('visible', $category->visible);
            }
        }

//--------------------------------------------------------------------------------
        $mform->addElement('header','', get_string('language'));

        $languages=array();
        $languages[''] = get_string('forceno');
        $languages += get_string_manager()->get_list_of_translations();
        $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
        $mform->setDefault('lang', $courseconfig->lang);

//--------------------------------------------------------------------------------
        if (completion_info::is_enabled_for_site()) {
            $mform->addElement('header','', get_string('progress','completion'));
            $mform->addElement('select', 'enablecompletion', get_string('completion','completion'),
                array(0=>get_string('completiondisabled','completion'), 1=>get_string('completionenabled','completion')));
            $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);

            $mform->addElement('checkbox', 'completionstartonenrol', get_string('completionstartonenrol', 'completion'));
            $mform->setDefault('completionstartonenrol', $courseconfig->completionstartonenrol);
            $mform->disabledIf('completionstartonenrol', 'enablecompletion', 'eq', 0);
        } else {
            $mform->addElement('hidden', 'enablecompletion');
            $mform->setType('enablecompletion', PARAM_INT);
            $mform->setDefault('enablecompletion',0);

            $mform->addElement('hidden', 'completionstartonenrol');
            $mform->setType('completionstartonenrol', PARAM_INT);
            $mform->setDefault('completionstartonenrol',0);
        }

//--------------------------------------------------------------------------------
        if (has_capability('moodle/site:config', $systemcontext)) {
            if (((!empty($course->requested) && $CFG->restrictmodulesfor == 'requested') || $CFG->restrictmodulesfor == 'all')) {
                $mform->addElement('header', '', get_string('restrictmodules'));

                $options = array();
                $options['0'] = get_string('no');
                $options['1'] = get_string('yes');
                $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
                if (!empty($CFG->restrictbydefault)) {
                    $mform->setDefault('restrictmodules', 1);
                }

                $mods = array(0=>get_string('allownone'));
                $mods += $DB->get_records_menu('modules', array('visible'=>1), 'name', 'id, name');
                $mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple'=>'multiple', 'size'=>'10'));
                $mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0);
                // defaults are already in $course
            } else {
                // remove any mod restriction
                $mform->addElement('hidden', 'restrictmodules', 0);
                $mform->setType('restrictmodules', PARAM_INT);
            }
        } else {
            $mform->addElement('hidden', 'restrictmodules');
            $mform->setType('restrictmodules', PARAM_INT);
            if (empty($course->id)) {
                $mform->setConstant('restrictmodules', (int)($CFG->restrictmodulesfor == 'all'));
            } else {
                // keep previous
                $mform->setConstant('restrictmodules', $course->restrictmodules);
            }
        }

/// customizable role names in this course
//--------------------------------------------------------------------------------
        $mform->addElement('header','rolerenaming', get_string('rolerenaming'));
        $mform->addHelpButton('rolerenaming', 'rolerenaming');

        if ($roles = get_all_roles()) {
            if ($coursecontext) {
                $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS_RAW);
            }
            $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE);
            foreach ($roles as $role) {
                $mform->addElement('text', 'role_'.$role->id, get_string('yourwordforx', '', $role->name));
                if (isset($role->localname)) {
                    $mform->setDefault('role_'.$role->id, $role->localname);
                }
                $mform->setType('role_'.$role->id, PARAM_TEXT);
                if (!in_array($role->id, $assignableroles)) {
                    $mform->setAdvanced('role_'.$role->id);
                }
            }
        }

//--------------------------------------------------------------------------------
        $this->add_action_buttons();
//--------------------------------------------------------------------------------
        $mform->addElement('hidden', 'id', null);
        $mform->setType('id', PARAM_INT);

/// finally set the current form data
//--------------------------------------------------------------------------------
        $this->set_data($course);
    }
Пример #11
0
function useredit_shared_definition(&$mform, $editoroptions = null, $filemanageroptions = null)
{
    global $CFG, $USER, $DB;
    $user = $DB->get_record('user', array('id' => $USER->id));
    useredit_load_preferences($user, false);
    $strrequired = get_string('required');
    // Add the necessary names.
    foreach (useredit_get_required_name_fields() as $fullname) {
        $mform->addElement('text', $fullname, get_string($fullname), 'maxlength="100" size="30"');
        $mform->addRule($fullname, $strrequired, 'required', null, 'client');
        $mform->setType($fullname, PARAM_NOTAGS);
    }
    $enabledusernamefields = useredit_get_enabled_name_fields();
    // Add the enabled additional name fields.
    foreach ($enabledusernamefields as $addname) {
        $mform->addElement('text', $addname, get_string($addname), 'maxlength="100" size="30"');
        $mform->setType($addname, PARAM_NOTAGS);
    }
    // Do not show email field if change confirmation is pending
    if (!empty($CFG->emailchangeconfirmation) and !empty($user->preference_newemail)) {
        $notice = get_string('emailchangepending', 'auth', $user);
        $notice .= '<br /><a href="edit.php?cancelemailchange=1&amp;id=' . $user->id . '">' . get_string('emailchangecancel', 'auth') . '</a>';
        $mform->addElement('static', 'emailpending', get_string('email'), $notice);
    } else {
        $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"');
        $mform->addRule('email', $strrequired, 'required', null, 'client');
        $mform->setType('email', PARAM_EMAIL);
    }
    $choices = array();
    $choices['0'] = get_string('emaildisplayno');
    $choices['1'] = get_string('emaildisplayyes');
    $choices['2'] = get_string('emaildisplaycourse');
    $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
    $mform->setDefault('maildisplay', 2);
    $choices = array();
    $choices['0'] = get_string('textformat');
    $choices['1'] = get_string('htmlformat');
    $mform->addElement('select', 'mailformat', get_string('emailformat'), $choices);
    $mform->setDefault('mailformat', 1);
    if (!empty($CFG->allowusermailcharset)) {
        $choices = array();
        $charsets = get_list_of_charsets();
        if (!empty($CFG->sitemailcharset)) {
            $choices['0'] = get_string('site') . ' (' . $CFG->sitemailcharset . ')';
        } else {
            $choices['0'] = get_string('site') . ' (UTF-8)';
        }
        $choices = array_merge($choices, $charsets);
        $mform->addElement('select', 'preference_mailcharset', get_string('emailcharset'), $choices);
    }
    $choices = array();
    $choices['0'] = get_string('emaildigestoff');
    $choices['1'] = get_string('emaildigestcomplete');
    $choices['2'] = get_string('emaildigestsubjects');
    $mform->addElement('select', 'maildigest', get_string('emaildigest'), $choices);
    $mform->setDefault('maildigest', 0);
    $mform->addHelpButton('maildigest', 'emaildigest');
    $choices = array();
    $choices['1'] = get_string('autosubscribeyes');
    $choices['0'] = get_string('autosubscribeno');
    $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
    $mform->setDefault('autosubscribe', 1);
    if (!empty($CFG->forum_trackreadposts)) {
        $choices = array();
        $choices['0'] = get_string('trackforumsno');
        $choices['1'] = get_string('trackforumsyes');
        $mform->addElement('select', 'trackforums', get_string('trackforums'), $choices);
        $mform->setDefault('trackforums', 0);
    }
    $editors = editors_get_enabled();
    if (count($editors) > 1) {
        $choices = array('' => get_string('defaulteditor'));
        $firsteditor = '';
        foreach (array_keys($editors) as $editor) {
            if (!$firsteditor) {
                $firsteditor = $editor;
            }
            $choices[$editor] = get_string('pluginname', 'editor_' . $editor);
        }
        $mform->addElement('select', 'preference_htmleditor', get_string('textediting'), $choices);
        $mform->setDefault('preference_htmleditor', '');
    } else {
        // Empty string means use the first chosen text editor.
        $mform->addElement('hidden', 'preference_htmleditor');
        $mform->setDefault('preference_htmleditor', '');
        $mform->setType('preference_htmleditor', PARAM_PLUGIN);
    }
    $mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="21"');
    $mform->setType('city', PARAM_TEXT);
    if (!empty($CFG->defaultcity)) {
        $mform->setDefault('city', $CFG->defaultcity);
    }
    $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', $CFG->country);
    }
    $choices = get_list_of_timezones();
    $choices['99'] = get_string('serverlocaltime');
    if ($CFG->forcetimezone != 99) {
        $mform->addElement('static', 'forcedtimezone', get_string('timezone'), $choices[$CFG->forcetimezone]);
    } else {
        $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
        $mform->setDefault('timezone', '99');
    }
    $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations());
    $mform->setDefault('lang', $CFG->lang);
    // Multi-Calendar Support - see MDL-18375.
    $calendartypes = \core_calendar\type_factory::get_list_of_calendar_types();
    // We do not want to show this option unless there is more than one calendar type to display.
    if (count($calendartypes) > 1) {
        $mform->addElement('select', 'calendartype', get_string('preferredcalendar', 'calendar'), $calendartypes);
    }
    if (!empty($CFG->allowuserthemes)) {
        $choices = array();
        $choices[''] = get_string('default');
        $themes = get_list_of_themes();
        foreach ($themes as $key => $theme) {
            if (empty($theme->hidefromselector)) {
                $choices[$key] = get_string('pluginname', 'theme_' . $theme->name);
            }
        }
        $mform->addElement('select', 'theme', get_string('preferredtheme'), $choices);
    }
    $mform->addElement('editor', 'description_editor', get_string('userdescription'), null, $editoroptions);
    $mform->setType('description_editor', PARAM_CLEANHTML);
    $mform->addHelpButton('description_editor', 'userdescription');
    if (empty($USER->newadminuser)) {
        $mform->addElement('header', 'moodle_picture', get_string('pictureofuser'));
        if (!empty($CFG->enablegravatar)) {
            $mform->addElement('html', html_writer::tag('p', get_string('gravatarenabled')));
        }
        $mform->addElement('static', 'currentpicture', get_string('currentpicture'));
        $mform->addElement('checkbox', 'deletepicture', get_string('delete'));
        $mform->setDefault('deletepicture', 0);
        $mform->addElement('filemanager', 'imagefile', get_string('newpicture'), '', $filemanageroptions);
        $mform->addHelpButton('imagefile', 'newpicture');
        $mform->addElement('text', 'imagealt', get_string('imagealt'), 'maxlength="100" size="30"');
        $mform->setType('imagealt', PARAM_TEXT);
    }
    // Display user name fields that are not currenlty enabled here if there are any.
    $disabledusernamefields = useredit_get_disabled_name_fields($enabledusernamefields);
    if (count($disabledusernamefields) > 0) {
        $mform->addElement('header', 'moodle_additional_names', get_string('additionalnames'));
        foreach ($disabledusernamefields as $allname) {
            $mform->addElement('text', $allname, get_string($allname), 'maxlength="100" size="30"');
            $mform->setType($allname, PARAM_NOTAGS);
        }
    }
    if (!empty($CFG->usetags) and empty($USER->newadminuser)) {
        $mform->addElement('header', 'moodle_interests', get_string('interests'));
        $mform->addElement('tags', 'interests', get_string('interestslist'), array('display' => 'noofficial'));
        $mform->addHelpButton('interests', 'interestslist');
    }
    /// Moodle optional fields
    $mform->addElement('header', 'moodle_optional', get_string('optional', 'form'));
    $mform->addElement('text', 'url', get_string('webpage'), 'maxlength="255" size="50"');
    $mform->setType('url', PARAM_URL);
    $mform->addElement('text', 'icq', get_string('icqnumber'), 'maxlength="15" size="25"');
    $mform->setType('icq', PARAM_NOTAGS);
    $mform->addElement('text', 'skype', get_string('skypeid'), 'maxlength="50" size="25"');
    $mform->setType('skype', PARAM_NOTAGS);
    $mform->addElement('text', 'aim', get_string('aimid'), 'maxlength="50" size="25"');
    $mform->setType('aim', PARAM_NOTAGS);
    $mform->addElement('text', 'yahoo', get_string('yahooid'), 'maxlength="50" size="25"');
    $mform->setType('yahoo', PARAM_NOTAGS);
    $mform->addElement('text', 'msn', get_string('msnid'), 'maxlength="50" size="25"');
    $mform->setType('msn', PARAM_NOTAGS);
    $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
    $mform->setType('idnumber', PARAM_NOTAGS);
    $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="255" size="25"');
    $mform->setType('institution', PARAM_TEXT);
    $mform->addElement('text', 'department', get_string('department'), 'maxlength="255" size="25"');
    $mform->setType('department', PARAM_TEXT);
    $mform->addElement('text', 'phone1', get_string('phone'), 'maxlength="20" size="25"');
    $mform->setType('phone1', PARAM_NOTAGS);
    $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
    $mform->setType('phone2', PARAM_NOTAGS);
    $mform->addElement('text', 'address', get_string('address'), 'maxlength="255" size="25"');
    $mform->setType('address', PARAM_TEXT);
}
Пример #12
0
function useredit_shared_definition(&$mform)
{
    global $CFG, $USER;
    $user = get_record('user', 'id', $USER->id);
    useredit_load_preferences($user, false);
    $strrequired = get_string('required');
    $nameordercheck = new object();
    $nameordercheck->firstname = 'a';
    $nameordercheck->lastname = 'b';
    if (fullname($nameordercheck) == 'b a') {
        // See MDL-4325
        $mform->addElement('text', 'lastname', get_string('lastname'), 'maxlength="100" size="30"');
        $mform->addElement('text', 'firstname', get_string('firstname'), 'maxlength="100" size="30"');
    } else {
        $mform->addElement('text', 'firstname', get_string('firstname'), 'maxlength="100" size="30"');
        $mform->addElement('text', 'lastname', get_string('lastname'), 'maxlength="100" size="30"');
    }
    $mform->addRule('firstname', $strrequired, 'required', null, 'client');
    $mform->setType('firstname', PARAM_NOTAGS);
    $mform->addRule('lastname', $strrequired, 'required', null, 'client');
    $mform->setType('lastname', PARAM_NOTAGS);
    // Do not show email field if change confirmation is pending
    if ($CFG->emailchangeconfirmation && !empty($user->preference_newemail)) {
        $notice = get_string('auth_emailchangepending', 'auth', $user);
        $notice .= '<br /><a href="edit.php?cancelemailchange=1&amp;id=' . $user->id . '">' . get_string('auth_emailchangecancel', 'auth') . '</a>';
        $mform->addElement('static', 'emailpending', get_string('email'), $notice);
    } else {
        $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"');
        $mform->addRule('email', $strrequired, 'required', null, 'client');
    }
    $choices = array();
    $choices['0'] = get_string('emaildisplayno');
    $choices['1'] = get_string('emaildisplayyes');
    $choices['2'] = get_string('emaildisplaycourse');
    $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
    $mform->setDefault('maildisplay', 2);
    $choices = array();
    $choices['0'] = get_string('emailenable');
    $choices['1'] = get_string('emaildisable');
    $mform->addElement('select', 'emailstop', get_string('emailactive'), $choices);
    $mform->setDefault('emailenable', 1);
    $choices = array();
    $choices['0'] = get_string('textformat');
    $choices['1'] = get_string('htmlformat');
    $mform->addElement('select', 'mailformat', get_string('emailformat'), $choices);
    $mform->setDefault('mailformat', 1);
    $mform->setAdvanced('mailformat');
    if (!empty($CFG->allowusermailcharset)) {
        $choices = array();
        $charsets = get_list_of_charsets();
        if (!empty($CFG->sitemailcharset)) {
            $choices['0'] = get_string('site') . ' (' . $CFG->sitemailcharset . ')';
        } else {
            $choices['0'] = get_string('site') . ' (UTF-8)';
        }
        $choices = array_merge($choices, $charsets);
        $mform->addElement('select', 'preference_mailcharset', get_string('emailcharset'), $choices);
        $mform->setAdvanced('preference_mailcharset');
    }
    $choices = array();
    $choices['0'] = get_string('emaildigestoff');
    $choices['1'] = get_string('emaildigestcomplete');
    $choices['2'] = get_string('emaildigestsubjects');
    $mform->addElement('select', 'maildigest', get_string('emaildigest'), $choices);
    $mform->setDefault('maildigest', 0);
    $mform->setAdvanced('maildigest');
    $choices = array();
    $choices['1'] = get_string('autosubscribeyes');
    $choices['0'] = get_string('autosubscribeno');
    $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
    $mform->setDefault('autosubscribe', 1);
    $mform->setAdvanced('autosubscribe');
    if (!empty($CFG->forum_trackreadposts)) {
        $choices = array();
        $choices['0'] = get_string('trackforumsno');
        $choices['1'] = get_string('trackforumsyes');
        $mform->addElement('select', 'trackforums', get_string('trackforums'), $choices);
        $mform->setDefault('trackforums', 0);
        $mform->setAdvanced('trackforums');
    }
    if ($CFG->htmleditor) {
        $choices = array();
        $choices['0'] = get_string('texteditor');
        $choices['1'] = get_string('htmleditor');
        $mform->addElement('select', 'htmleditor', get_string('textediting'), $choices);
        $mform->setDefault('htmleditor', 1);
        $mform->setAdvanced('htmleditor');
    }
    if (empty($CFG->enableajax)) {
        $mform->addElement('static', 'ajaxdisabled', get_string('ajaxuse'), get_string('ajaxno'));
        $mform->setAdvanced('ajaxdisabled');
    } else {
        $choices = array();
        $choices['0'] = get_string('ajaxno');
        $choices['1'] = get_string('ajaxyes');
        $mform->addElement('select', 'ajax', get_string('ajaxuse'), $choices);
        $mform->setDefault('ajax', 0);
        $mform->setAdvanced('ajax');
    }
    $choices = array();
    $choices['0'] = get_string('screenreaderno');
    $choices['1'] = get_string('screenreaderyes');
    $mform->addElement('select', 'screenreader', get_string('screenreaderuse'), $choices);
    $mform->setDefault('screenreader', 0);
    $mform->setAdvanced('screenreader');
    $mform->addElement('text', 'city', get_string('city'), 'maxlength="20" size="21"');
    $mform->setType('city', PARAM_MULTILANG);
    $mform->addRule('city', $strrequired, 'required', null, 'client');
    $choices = get_list_of_countries();
    $choices = array('' => get_string('selectacountry') . '...') + $choices;
    $mform->addElement('select', 'country', get_string('selectacountry'), $choices);
    $mform->addRule('country', $strrequired, 'required', null, 'client');
    if (!empty($CFG->country)) {
        $mform->setDefault('country', $CFG->country);
    }
    $choices = get_list_of_timezones();
    $choices['99'] = get_string('serverlocaltime');
    if ($CFG->forcetimezone != 99) {
        $mform->addElement('static', 'forcedtimezone', get_string('timezone'), $choices[$CFG->forcetimezone]);
    } else {
        $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
        $mform->setDefault('timezone', '99');
    }
    $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_list_of_languages());
    $mform->setDefault('lang', $CFG->lang);
    if (!empty($CFG->allowuserthemes)) {
        $choices = array();
        $choices[''] = get_string('default');
        $choices += get_list_of_themes();
        $mform->addElement('select', 'theme', get_string('preferredtheme'), $choices);
        $mform->setAdvanced('theme');
    }
    $mform->addElement('htmleditor', 'description', get_string('userdescription'));
    $mform->setType('description', PARAM_CLEAN);
    $mform->setHelpButton('description', array('text', get_string('helptext')));
    if (!empty($CFG->gdversion)) {
        $mform->addElement('header', 'moodle_picture', get_string('pictureof'));
        //TODO: Accessibility fix fieldset legend
        $mform->addElement('static', 'currentpicture', get_string('currentpicture'));
        $mform->addElement('checkbox', 'deletepicture', get_string('delete'));
        $mform->setDefault('deletepicture', false);
        $mform->addElement('file', 'imagefile', get_string('newpicture'));
        $mform->setHelpButton('imagefile', array('picture', get_string('helppicture')));
        $mform->addElement('text', 'imagealt', get_string('imagealt'), 'maxlength="100" size="30"');
        $mform->setType('imagealt', PARAM_MULTILANG);
    }
    if (!empty($CFG->usetags)) {
        $mform->addElement('header', 'moodle_interests', get_string('interests'));
        $mform->addElement('textarea', 'interests', get_string('interestslist'), 'cols="45" rows="3"');
        $mform->setHelpButton('interests', array('interestslist', get_string('helpinterestslist'), false, true, false));
    }
    /// Moodle optional fields
    $mform->addElement('header', 'moodle_optional', get_string('optional', 'form'));
    $mform->setAdvanced('moodle_optional');
    $mform->addElement('text', 'url', get_string('webpage'), 'maxlength="255" size="50"');
    $mform->setType('url', PARAM_URL);
    $mform->addElement('text', 'icq', get_string('icqnumber'), 'maxlength="15" size="25"');
    $mform->setType('icq', PARAM_CLEAN);
    $mform->addElement('text', 'skype', get_string('skypeid'), 'maxlength="50" size="25"');
    $mform->setType('skype', PARAM_CLEAN);
    $mform->addElement('text', 'aim', get_string('aimid'), 'maxlength="50" size="25"');
    $mform->setType('aim', PARAM_CLEAN);
    $mform->addElement('text', 'yahoo', get_string('yahooid'), 'maxlength="50" size="25"');
    $mform->setType('yahoo', PARAM_CLEAN);
    $mform->addElement('text', 'msn', get_string('msnid'), 'maxlength="50" size="25"');
    $mform->setType('msn', PARAM_CLEAN);
    $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
    $mform->setType('idnumber', PARAM_CLEAN);
    $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="40" size="25"');
    $mform->setType('institution', PARAM_MULTILANG);
    $mform->addElement('text', 'department', get_string('department'), 'maxlength="30" size="25"');
    $mform->setType('department', PARAM_MULTILANG);
    $mform->addElement('text', 'phone1', get_string('phone'), 'maxlength="20" size="25"');
    $mform->setType('phone1', PARAM_CLEAN);
    $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
    $mform->setType('phone2', PARAM_CLEAN);
    $mform->addElement('text', 'address', get_string('address'), 'maxlength="70" size="25"');
    $mform->setType('address', PARAM_MULTILANG);
}
Пример #13
0
 /**
  * Given one restoreid, create in DB all the users present
  * in backup_ids having newitemid = 0, as far as
  * precheck_included_users() have left them there
  * ready to be created. Also, annotate their newids
  * once created for later reference
  */
 public static function create_included_users($basepath, $restoreid, $userid)
 {
     global $CFG, $DB;
     $authcache = array();
     // Cache to get some bits from authentication plugins
     $languages = get_string_manager()->get_list_of_translations();
     // Get languages for quick search later
     $themes = get_list_of_themes();
     // Get themes for quick search later
     // Iterate over all the included users with newitemid = 0, have to create them
     $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'user', 'newitemid' => 0), '', 'itemid, parentitemid');
     foreach ($rs as $recuser) {
         $user = (object) self::get_backup_ids_record($restoreid, 'user', $recuser->itemid)->info;
         // if user lang doesn't exist here, use site default
         if (!array_key_exists($user->lang, $languages)) {
             $user->lang = $CFG->lang;
         }
         // if user theme isn't available on target site or they are disabled, reset theme
         if (!empty($user->theme)) {
             if (empty($CFG->allowuserthemes) || !in_array($user->theme, $themes)) {
                 $user->theme = '';
             }
         }
         // if user to be created has mnet auth and its mnethostid is $CFG->mnet_localhost_id
         // that's 100% impossible as own server cannot be accesed over mnet. Change auth to email/manual
         if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) {
             // Respect registerauth
             if ($CFG->registerauth == 'email') {
                 $user->auth = 'email';
             } else {
                 $user->auth = 'manual';
             }
         }
         unset($user->mnethosturl);
         // Not needed anymore
         // Disable pictures based on global setting
         if (!empty($CFG->disableuserimages)) {
             $user->picture = 0;
         }
         // We need to analyse the AUTH field to recode it:
         //   - if the auth isn't enabled in target site, $CFG->registerauth will decide
         //   - finally, if the auth resulting isn't enabled, default to 'manual'
         if (!is_enabled_auth($user->auth)) {
             if ($CFG->registerauth == 'email') {
                 $user->auth = 'email';
             } else {
                 $user->auth = 'manual';
             }
         }
         if (!is_enabled_auth($user->auth)) {
             // Final auth check verify, default to manual if not enabled
             $user->auth = 'manual';
         }
         // Now that we know the auth method, for users to be created without pass
         // if password handling is internal and reset password is available
         // we set the password to "restored" (plain text), so the login process
         // will know how to handle that situation in order to allow the user to
         // recover the password. MDL-20846
         if (empty($user->password)) {
             // Only if restore comes without password
             if (!array_key_exists($user->auth, $authcache)) {
                 // Not in cache
                 $userauth = new stdClass();
                 $authplugin = get_auth_plugin($user->auth);
                 $userauth->preventpassindb = $authplugin->prevent_local_passwords();
                 $userauth->isinternal = $authplugin->is_internal();
                 $userauth->canresetpwd = $authplugin->can_reset_password();
                 $authcache[$user->auth] = $userauth;
             } else {
                 $userauth = $authcache[$user->auth];
                 // Get from cache
             }
             // Most external plugins do not store passwords locally
             if (!empty($userauth->preventpassindb)) {
                 $user->password = '******';
                 // If Moodle is responsible for storing/validating pwd and reset functionality is available, mark
             } else {
                 if ($userauth->isinternal and $userauth->canresetpwd) {
                     $user->password = '******';
                 }
             }
         }
         // Creating new user, we must reset the policyagreed always
         $user->policyagreed = 0;
         // Set time created if empty
         if (empty($user->timecreated)) {
             $user->timecreated = time();
         }
         // Done, let's create the user and annotate its id
         $newuserid = $DB->insert_record('user', $user);
         self::set_backup_ids_record($restoreid, 'user', $recuser->itemid, $newuserid);
         // Let's create the user context and annotate it (we need it for sure at least for files)
         // but for deleted users that don't have a context anymore (MDL-30192). We are done for them
         // and nothing else (custom fields, prefs, tags, files...) will be created.
         if (empty($user->deleted)) {
             $newuserctxid = $user->deleted ? 0 : get_context_instance(CONTEXT_USER, $newuserid)->id;
             self::set_backup_ids_record($restoreid, 'context', $recuser->parentitemid, $newuserctxid);
             // Process custom fields
             if (isset($user->custom_fields)) {
                 // if present in backup
                 foreach ($user->custom_fields['custom_field'] as $udata) {
                     $udata = (object) $udata;
                     // If the profile field has data and the profile shortname-datatype is defined in server
                     if ($udata->field_data) {
                         if ($field = $DB->get_record('user_info_field', array('shortname' => $udata->field_name, 'datatype' => $udata->field_type))) {
                             /// Insert the user_custom_profile_field
                             $rec = new stdClass();
                             $rec->userid = $newuserid;
                             $rec->fieldid = $field->id;
                             $rec->data = $udata->field_data;
                             $DB->insert_record('user_info_data', $rec);
                         }
                     }
                 }
             }
             // Process tags
             if (!empty($CFG->usetags) && isset($user->tags)) {
                 // if enabled in server and present in backup
                 $tags = array();
                 foreach ($user->tags['tag'] as $usertag) {
                     $usertag = (object) $usertag;
                     $tags[] = $usertag->rawname;
                 }
                 tag_set('user', $newuserid, $tags);
             }
             // Process preferences
             if (isset($user->preferences)) {
                 // if present in backup
                 foreach ($user->preferences['preference'] as $preference) {
                     $preference = (object) $preference;
                     // Prepare the record and insert it
                     $preference->userid = $newuserid;
                     $status = $DB->insert_record('user_preferences', $preference);
                 }
             }
             // Create user files in pool (profile, icon, private) by context
             restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'icon', $recuser->parentitemid, $userid);
             restore_dbops::send_files_to_pool($basepath, $restoreid, 'user', 'profile', $recuser->parentitemid, $userid);
         }
     }
     $rs->close();
 }
Пример #14
0
function restore_create_users($restore, $xml_file)
{
    global $CFG, $db;
    $status = true;
    //Check it exists
    if (!file_exists($xml_file)) {
        $status = false;
    }
    //Get info from xml
    if ($status) {
        //info will contain the old_id of every user
        //in backup_ids->info will be the real info (serialized)
        $info = restore_read_xml_users($restore, $xml_file);
    }
    //Now, get evey user_id from $info and user data from $backup_ids
    //and create the necessary records (users, user_students, user_teachers
    //user_course_creators and user_admins
    if (!empty($info->users)) {
        // Grab mnethosts keyed by wwwroot, to map to id
        $mnethosts = get_records('mnet_host', '', '', 'wwwroot', 'wwwroot, id');
        $languages = get_list_of_languages();
        foreach ($info->users as $userid) {
            $rec = backup_getid($restore->backup_unique_code, "user", $userid);
            $user = $rec->info;
            //Now, recode some languages (Moodle 1.5)
            if ($user->lang == 'ma_nt') {
                $user->lang = 'mi_nt';
            }
            //If language does not exist here - use site default
            if (!array_key_exists($user->lang, $languages)) {
                $user->lang = $CFG->lang;
            }
            //Check if it's admin and coursecreator
            $is_admin = !empty($user->roles['admin']);
            $is_coursecreator = !empty($user->roles['coursecreator']);
            //Check if it's teacher and student
            $is_teacher = !empty($user->roles['teacher']);
            $is_student = !empty($user->roles['student']);
            //Check if it's needed
            $is_needed = !empty($user->roles['needed']);
            //Calculate if it is a course user
            //Has role teacher or student or needed
            $is_course_user = ($is_teacher or $is_student or $is_needed);
            //Calculate mnethostid
            if (empty($user->mnethosturl) || $user->mnethosturl === $CFG->wwwroot) {
                $user->mnethostid = $CFG->mnet_localhost_id;
            } else {
                // fast url-to-id lookups
                if (isset($mnethosts[$user->mnethosturl])) {
                    $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
                } else {
                    // should not happen, as we check in restore_chech.php
                    // but handle the error if it does
                    error("This backup file contains external Moodle Network Hosts that are not configured locally.");
                }
            }
            unset($user->mnethosturl);
            //To store new ids created
            $newid = null;
            //check if it exists (by username) and get its id
            $user_exists = true;
            $user_data = get_record("user", "username", addslashes($user->username), 'mnethostid', $user->mnethostid);
            if (!$user_data) {
                $user_exists = false;
            } else {
                $newid = $user_data->id;
            }
            //Flags to see if we have to create the user, roles and preferences
            $create_user = true;
            $create_roles = true;
            $create_preferences = true;
            //If we are restoring course users and it isn't a course user
            if ($restore->users == 1 and !$is_course_user) {
                //If only restoring course_users and user isn't a course_user, inform to $backup_ids
                $status = backup_putid($restore->backup_unique_code, "user", $userid, null, 'notincourse');
                $create_user = false;
                $create_roles = false;
                $create_preferences = false;
            }
            if ($user_exists and $create_user) {
                //If user exists mark its newid in backup_ids (the same than old)
                $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, 'exists');
                $create_user = false;
            }
            //Here, if create_user, do it
            if ($create_user) {
                //Unset the id because it's going to be inserted with a new one
                unset($user->id);
                //We addslashes to necessary fields
                $user->username = addslashes($user->username);
                $user->firstname = addslashes($user->firstname);
                $user->lastname = addslashes($user->lastname);
                $user->email = addslashes($user->email);
                $user->institution = addslashes($user->institution);
                $user->department = addslashes($user->department);
                $user->address = addslashes($user->address);
                $user->city = addslashes($user->city);
                $user->url = addslashes($user->url);
                $user->description = backup_todb($user->description);
                //We need to analyse the AUTH field to recode it:
                //   - if the field isn't set, we are in a pre 1.4 backup and we'll
                //     use manual
                if (empty($user->auth)) {
                    if ($CFG->registerauth == 'email') {
                        $user->auth = 'email';
                    } else {
                        $user->auth = 'manual';
                    }
                }
                //We need to process the POLICYAGREED field to recalculate it:
                //    - if the destination site is different (by wwwroot) reset it.
                //    - if the destination site is the same (by wwwroot), leave it unmodified
                if ($restore->original_wwwroot != $CFG->wwwroot) {
                    $user->policyagreed = 0;
                } else {
                    //Nothing to do, we are in the same server
                }
                //Check if the theme exists in destination server
                $themes = get_list_of_themes();
                if (!in_array($user->theme, $themes)) {
                    $user->theme = '';
                }
                //We are going to create the user
                //The structure is exactly as we need
                $newid = insert_record("user", $user);
                //Put the new id
                $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, "new");
            }
            //Here, if create_roles, do it as necessary
            if ($create_roles) {
                //Get the newid and current info from backup_ids
                $data = backup_getid($restore->backup_unique_code, "user", $userid);
                $newid = $data->new_id;
                $currinfo = $data->info . ",";
                //Now, depending of the role, create records in user_studentes and user_teacher
                //and/or mark it in backup_ids
                if ($is_admin) {
                    //If the record (user_admins) doesn't exists
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "admin,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_coursecreator) {
                    //If the record (user_coursecreators) doesn't exists
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "coursecreator,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_needed) {
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "needed,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_teacher) {
                    //If the record (teacher) doesn't exists
                    //Put status in backup_ids
                    $currinfo = $currinfo . "teacher,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    //Set course and user
                    $user->roles['teacher']->course = $restore->course_id;
                    $user->roles['teacher']->userid = $newid;
                    //Need to analyse the enrol field
                    //    - if it isn't set, set it to $CFG->enrol
                    //    - if we are in a different server (by wwwroot), set it to $CFG->enrol
                    //    - if we are in the same server (by wwwroot), maintain it unmodified.
                    if (empty($user->roles['teacher']->enrol)) {
                        $user->roles['teacher']->enrol = $CFG->enrol;
                    } else {
                        if ($restore->original_wwwroot != $CFG->wwwroot) {
                            $user->roles['teacher']->enrol = $CFG->enrol;
                        } else {
                            //Nothing to do. Leave it unmodified
                        }
                    }
                    $rolesmapping = $restore->rolesmapping;
                    $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
                    if ($user->roles['teacher']->editall) {
                        role_assign($rolesmapping['defaultteacheredit'], $newid, 0, $context->id, $user->roles['teacher']->timestart, $user->roles['teacher']->timeend, 0, $user->roles['teacher']->enrol);
                        // editting teacher
                    } else {
                        // non editting teacher
                        role_assign($rolesmapping['defaultteacher'], $newid, 0, $context->id, $user->roles['teacher']->timestart, $user->roles['teacher']->timeend, 0, $user->roles['teacher']->enrol);
                    }
                }
                if ($is_student) {
                    //Put status in backup_ids
                    $currinfo = $currinfo . "student,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    //Set course and user
                    $user->roles['student']->course = $restore->course_id;
                    $user->roles['student']->userid = $newid;
                    //Need to analyse the enrol field
                    //    - if it isn't set, set it to $CFG->enrol
                    //    - if we are in a different server (by wwwroot), set it to $CFG->enrol
                    //    - if we are in the same server (by wwwroot), maintain it unmodified.
                    if (empty($user->roles['student']->enrol)) {
                        $user->roles['student']->enrol = $CFG->enrol;
                    } else {
                        if ($restore->original_wwwroot != $CFG->wwwroot) {
                            $user->roles['student']->enrol = $CFG->enrol;
                        } else {
                            //Nothing to do. Leave it unmodified
                        }
                    }
                    $rolesmapping = $restore->rolesmapping;
                    $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
                    role_assign($rolesmapping['defaultstudent'], $newid, 0, $context->id, $user->roles['student']->timestart, $user->roles['student']->timeend, 0, $user->roles['student']->enrol);
                }
                if (!$is_course_user) {
                    //If the record (user) doesn't exists
                    if (!record_exists("user", "id", $newid)) {
                        //Put status in backup_ids
                        $currinfo = $currinfo . "user,";
                        $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    }
                }
            }
            //Here, if create_preferences, do it as necessary
            if ($create_preferences) {
                //echo "Checking for preferences of user ".$user->username."<br />";         //Debug
                //Get user new id from backup_ids
                $data = backup_getid($restore->backup_unique_code, "user", $userid);
                $newid = $data->new_id;
                if (isset($user->user_preferences)) {
                    //echo "Preferences exist in backup file<br />";                         //Debug
                    foreach ($user->user_preferences as $user_preference) {
                        //echo $user_preference->name." = ".$user_preference->value."<br />";    //Debug
                        //We check if that user_preference exists in DB
                        if (!record_exists("user_preferences", "userid", $newid, "name", $user_preference->name)) {
                            //echo "Creating it<br />";                                              //Debug
                            //Prepare the record and insert it
                            $user_preference->userid = $newid;
                            $status = insert_record("user_preferences", $user_preference);
                        }
                    }
                }
            }
        }
    }
    return $status;
}
Пример #15
0
 /**
  * Processing functions go here
  *
  * @global moodledatabase $DB
  * @param stdClass $data
  */
 public function process_course($data)
 {
     global $CFG, $DB;
     $data = (object) $data;
     $coursetags = isset($data->tags['tag']) ? $data->tags['tag'] : array();
     $coursemodules = isset($data->allowed_modules['module']) ? $data->allowed_modules['module'] : array();
     $oldid = $data->id;
     // We'll need this later
     $fullname = $this->get_setting_value('course_fullname');
     $shortname = $this->get_setting_value('course_shortname');
     $startdate = $this->get_setting_value('course_startdate');
     // Calculate final course names, to avoid dupes
     list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
     // Need to change some fields before updating the course record
     $data->id = $this->get_courseid();
     $data->fullname = $fullname;
     $data->shortname = $shortname;
     $data->idnumber = '';
     // Category is set by UI when choosing the destination
     unset($data->category);
     $data->startdate = $this->apply_date_offset($data->startdate);
     if ($data->defaultgroupingid) {
         $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
     }
     if (empty($CFG->enablecompletion)) {
         $data->enablecompletion = 0;
         $data->completionstartonenrol = 0;
         $data->completionnotify = 0;
     }
     $languages = get_string_manager()->get_list_of_translations();
     // Get languages for quick search
     if (!array_key_exists($data->lang, $languages)) {
         $data->lang = '';
     }
     $themes = get_list_of_themes();
     // Get themes for quick search later
     if (!in_array($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
         $data->theme = '';
     }
     // Course record ready, update it
     $DB->update_record('course', $data);
     // Course tags
     if (!empty($CFG->usetags) && isset($coursetags)) {
         // if enabled in server and present in backup
         $tags = array();
         foreach ($coursetags as $coursetag) {
             $coursetag = (object) $coursetag;
             $tags[] = $coursetag->rawname;
         }
         tag_set('course', $this->get_courseid(), $tags);
     }
     // Course allowed modules
     if (!empty($data->restrictmodules) && !empty($coursemodules)) {
         $available = get_plugin_list('mod');
         foreach ($coursemodules as $coursemodule) {
             $mname = $coursemodule['modulename'];
             if (array_key_exists($mname, $available)) {
                 if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
                     $rec = new stdclass();
                     $rec->course = $this->get_courseid();
                     $rec->module = $module->id;
                     if (!$DB->record_exists('course_allowed_modules', (array) $rec)) {
                         $DB->insert_record('course_allowed_modules', $rec);
                     }
                 }
             }
         }
     }
     // Role name aliases
     restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
 }
function useredit_shared_definition(&$mform, $editoroptions = null)
{
    global $CFG, $USER, $DB;
    $user = $DB->get_record('user', array('id' => $USER->id));
    useredit_load_preferences($user, false);
    $strrequired = get_string('required');
    $nameordercheck = new stdClass();
    $nameordercheck->firstname = 'a';
    $nameordercheck->lastname = 'b';
    if (fullname($nameordercheck) == 'b a') {
        // See MDL-4325
        $mform->addElement('text', 'lastname', get_string('lastname'), 'maxlength="100" size="30"');
        $mform->addElement('text', 'firstname', get_string('firstname'), 'maxlength="100" size="30"');
    } else {
        $mform->addElement('text', 'firstname', get_string('firstname'), 'maxlength="100" size="30"');
        $mform->addElement('text', 'lastname', get_string('lastname'), 'maxlength="100" size="30"');
    }
    $mform->addRule('firstname', $strrequired, 'required', null, 'client');
    $mform->setType('firstname', PARAM_NOTAGS);
    $mform->addRule('lastname', $strrequired, 'required', null, 'client');
    $mform->setType('lastname', PARAM_NOTAGS);
    // Do not show email field if change confirmation is pending
    if (!empty($CFG->emailchangeconfirmation) and !empty($user->preference_newemail)) {
        $notice = get_string('emailchangepending', 'auth', $user);
        $notice .= '<br /><a href="edit.php?cancelemailchange=1&amp;id=' . $user->id . '">' . get_string('emailchangecancel', 'auth') . '</a>';
        $mform->addElement('static', 'emailpending', get_string('email'), $notice);
    } else {
        $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"');
        $mform->addRule('email', $strrequired, 'required', null, 'client');
    }
    $choices = array();
    $choices['0'] = get_string('emaildisplayno');
    $choices['1'] = get_string('emaildisplayyes');
    $choices['2'] = get_string('emaildisplaycourse');
    $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
    $mform->setDefault('maildisplay', 2);
    $choices = array();
    $choices['0'] = get_string('textformat');
    $choices['1'] = get_string('htmlformat');
    $mform->addElement('select', 'mailformat', get_string('emailformat'), $choices);
    $mform->setDefault('mailformat', 1);
    if (!empty($CFG->allowusermailcharset)) {
        $choices = array();
        $charsets = get_list_of_charsets();
        if (!empty($CFG->sitemailcharset)) {
            $choices['0'] = get_string('site') . ' (' . $CFG->sitemailcharset . ')';
        } else {
            $choices['0'] = get_string('site') . ' (UTF-8)';
        }
        $choices = array_merge($choices, $charsets);
        $mform->addElement('select', 'preference_mailcharset', get_string('emailcharset'), $choices);
    }
    $choices = array();
    $choices['0'] = get_string('emaildigestoff');
    $choices['1'] = get_string('emaildigestcomplete');
    $choices['2'] = get_string('emaildigestsubjects');
    $mform->addElement('select', 'maildigest', get_string('emaildigest'), $choices);
    $mform->setDefault('maildigest', 0);
    $choices = array();
    $choices['1'] = get_string('autosubscribeyes');
    $choices['0'] = get_string('autosubscribeno');
    $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
    $mform->setDefault('autosubscribe', 1);
    if (!empty($CFG->forum_trackreadposts)) {
        $choices = array();
        $choices['0'] = get_string('trackforumsno');
        $choices['1'] = get_string('trackforumsyes');
        $mform->addElement('select', 'trackforums', get_string('trackforums'), $choices);
        $mform->setDefault('trackforums', 0);
    }
    $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', 'ajaxdisabled', get_string('ajaxuse'), get_string('ajaxno'));
    } else {
        $choices = array();
        $choices['0'] = get_string('ajaxno');
        $choices['1'] = get_string('ajaxyes');
        $mform->addElement('select', 'ajax', get_string('ajaxuse'), $choices);
        $mform->setDefault('ajax', 0);
    }
    $choices = array();
    $choices['0'] = get_string('screenreaderno');
    $choices['1'] = get_string('screenreaderyes');
    $mform->addElement('select', 'screenreader', get_string('screenreaderuse'), $choices);
    $mform->setDefault('screenreader', 0);
    $mform->addHelpButton('screenreader', 'screenreaderuse');
    $mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="21"');
    $mform->setType('city', PARAM_MULTILANG);
    $mform->addRule('city', $strrequired, 'required', null, 'client');
    if (!empty($CFG->defaultcity)) {
        $mform->setDefault('city', $CFG->defaultcity);
    }
    $choices = get_string_manager()->get_list_of_countries();
    $choices = array('' => get_string('selectacountry') . '...') + $choices;
    $mform->addElement('select', 'country', get_string('selectacountry'), $choices);
    $mform->addRule('country', $strrequired, 'required', null, 'client');
    if (!empty($CFG->country)) {
        $mform->setDefault('country', $CFG->country);
    }
    $choices = get_list_of_timezones();
    $choices['99'] = get_string('serverlocaltime');
    if ($CFG->forcetimezone != 99) {
        $mform->addElement('static', 'forcedtimezone', get_string('timezone'), $choices[$CFG->forcetimezone]);
    } else {
        $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
        $mform->setDefault('timezone', '99');
    }
    $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations());
    $mform->setDefault('lang', $CFG->lang);
    if (!empty($CFG->allowuserthemes)) {
        $choices = array();
        $choices[''] = get_string('default');
        $themes = get_list_of_themes();
        foreach ($themes as $key => $theme) {
            if (empty($theme->hidefromselector)) {
                $choices[$key] = $theme->name;
            }
        }
        $mform->addElement('select', 'theme', get_string('preferredtheme'), $choices);
    }
    $mform->addElement('editor', 'description_editor', get_string('userdescription'), null, $editoroptions);
    $mform->setType('description_editor', PARAM_CLEANHTML);
    $mform->addHelpButton('description_editor', 'userdescription');
    if (!empty($CFG->gdversion) and empty($USER->newadminuser)) {
        $mform->addElement('header', 'moodle_picture', get_string('pictureofuser'));
        $mform->addElement('static', 'currentpicture', get_string('currentpicture'));
        $mform->addElement('checkbox', 'deletepicture', get_string('delete'));
        $mform->setDefault('deletepicture', 0);
        $mform->addElement('filepicker', 'imagefile', get_string('newpicture'), '', array('maxbytes' => get_max_upload_file_size($CFG->maxbytes)));
        $mform->addHelpButton('imagefile', 'newpicture');
        $mform->addElement('text', 'imagealt', get_string('imagealt'), 'maxlength="100" size="30"');
        $mform->setType('imagealt', PARAM_MULTILANG);
    }
    if (!empty($CFG->usetags) and empty($USER->newadminuser)) {
        $mform->addElement('header', 'moodle_interests', get_string('interests'));
        $mform->addElement('tags', 'interests', get_string('interestslist'), array('display' => 'noofficial'));
        $mform->addHelpButton('interests', 'interestslist');
    }
    /// Moodle optional fields
    $mform->addElement('header', 'moodle_optional', get_string('optional', 'form'));
    $mform->addElement('text', 'url', get_string('webpage'), 'maxlength="255" size="50"');
    $mform->setType('url', PARAM_URL);
    $mform->addElement('text', 'icq', get_string('icqnumber'), 'maxlength="15" size="25"');
    $mform->setType('icq', PARAM_NOTAGS);
    $mform->addElement('text', 'skype', get_string('skypeid'), 'maxlength="50" size="25"');
    $mform->setType('skype', PARAM_NOTAGS);
    $mform->addElement('text', 'aim', get_string('aimid'), 'maxlength="50" size="25"');
    $mform->setType('aim', PARAM_NOTAGS);
    $mform->addElement('text', 'yahoo', get_string('yahooid'), 'maxlength="50" size="25"');
    $mform->setType('yahoo', PARAM_NOTAGS);
    $mform->addElement('text', 'msn', get_string('msnid'), 'maxlength="50" size="25"');
    $mform->setType('msn', PARAM_NOTAGS);
    $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
    $mform->setType('idnumber', PARAM_NOTAGS);
    $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="40" size="25"');
    $mform->setType('institution', PARAM_MULTILANG);
    $mform->addElement('text', 'department', get_string('department'), 'maxlength="30" size="25"');
    $mform->setType('department', PARAM_MULTILANG);
    $mform->addElement('text', 'phone1', get_string('phone'), 'maxlength="20" size="25"');
    $mform->setType('phone1', PARAM_NOTAGS);
    $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
    $mform->setType('phone2', PARAM_NOTAGS);
    $mform->addElement('text', 'address', get_string('address'), 'maxlength="70" size="25"');
    $mform->setType('address', PARAM_MULTILANG);
}
Пример #17
0
 /**
  * Processing functions go here
  *
  * @global moodledatabase $DB
  * @param stdClass $data
  */
 public function process_course($data)
 {
     global $CFG, $DB;
     $data = (object) $data;
     $fullname = $this->get_setting_value('course_fullname');
     $shortname = $this->get_setting_value('course_shortname');
     $startdate = $this->get_setting_value('course_startdate');
     // Calculate final course names, to avoid dupes
     list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
     // Need to change some fields before updating the course record
     $data->id = $this->get_courseid();
     $data->fullname = $fullname;
     $data->shortname = $shortname;
     // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
     // another course on this site.
     $context = context::instance_by_id($this->task->get_contextid());
     if (!empty($data->idnumber) && has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid()) && $this->task->is_samesite() && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) {
         // Do not reset idnumber.
     } else {
         $data->idnumber = '';
     }
     // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
     // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
     if (empty($data->hiddensections)) {
         $data->hiddensections = 0;
     }
     // Set legacyrestrictmodules to true if the course was resticting modules. If so
     // then we will need to process restricted modules after execution.
     $this->legacyrestrictmodules = !empty($data->restrictmodules);
     $data->startdate = $this->apply_date_offset($data->startdate);
     if ($data->defaultgroupingid) {
         $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
     }
     if (empty($CFG->enablecompletion)) {
         $data->enablecompletion = 0;
         $data->completionstartonenrol = 0;
         $data->completionnotify = 0;
     }
     $languages = get_string_manager()->get_list_of_translations();
     // Get languages for quick search
     if (!array_key_exists($data->lang, $languages)) {
         $data->lang = '';
     }
     $themes = get_list_of_themes();
     // Get themes for quick search later
     if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
         $data->theme = '';
     }
     // Check if this is an old SCORM course format.
     if ($data->format == 'scorm') {
         $data->format = 'singleactivity';
         $data->activitytype = 'scorm';
     }
     // Course record ready, update it
     $DB->update_record('course', $data);
     course_get_format($data)->update_course_format_options($data);
     // Role name aliases
     restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
 }
Пример #18
0
function restore_create_users($restore, $xml_file)
{
    global $CFG, $db;
    require_once $CFG->dirroot . '/tag/lib.php';
    $status = true;
    //Check it exists
    if (!file_exists($xml_file)) {
        $status = false;
    }
    //Get info from xml
    if ($status) {
        //info will contain the old_id of every user
        //in backup_ids->info will be the real info (serialized)
        $info = restore_read_xml_users($restore, $xml_file);
    }
    //Now, get evey user_id from $info and user data from $backup_ids
    //and create the necessary db structures
    if (!empty($info->users)) {
        /// Grab mnethosts keyed by wwwroot, to map to id
        $mnethosts = get_records('mnet_host', '', '', 'wwwroot', 'wwwroot, id');
        /// Get languages for quick search later
        $languages = get_list_of_languages();
        /// Iterate over all users loaded from xml
        $counter = 0;
        /// Init trailing messages
        $messages = array();
        foreach ($info->users as $userid) {
            $rec = backup_getid($restore->backup_unique_code, "user", $userid);
            $user = $rec->info;
            foreach (array_keys(get_object_vars($user)) as $field) {
                if (!is_array($user->{$field})) {
                    $user->{$field} = backup_todb($user->{$field});
                    if (is_null($user->{$field})) {
                        $user->{$field} = '';
                    }
                }
            }
            //Now, recode some languages (Moodle 1.5)
            if ($user->lang == 'ma_nt') {
                $user->lang = 'mi_nt';
            }
            //Country list updates - MDL-13060
            //Any user whose country code has been deleted or modified needs to be assigned a valid one.
            $country_update_map = array('ZR' => 'CD', 'TP' => 'TL', 'FX' => 'FR', 'KO' => 'RS', 'CS' => 'RS', 'WA' => 'GB');
            if (array_key_exists($user->country, $country_update_map)) {
                $user->country = $country_update_map[$user->country];
            }
            //If language does not exist here - use site default
            if (!array_key_exists($user->lang, $languages)) {
                $user->lang = $CFG->lang;
            }
            //Check if it's admin and coursecreator
            $is_admin = !empty($user->roles['admin']);
            $is_coursecreator = !empty($user->roles['coursecreator']);
            //Check if it's teacher and student
            $is_teacher = !empty($user->roles['teacher']);
            $is_student = !empty($user->roles['student']);
            //Check if it's needed
            $is_needed = !empty($user->roles['needed']);
            //Calculate if it is a course user
            //Has role teacher or student or needed
            $is_course_user = ($is_teacher or $is_student or $is_needed);
            // in case we are restoring to same server, look for user by id
            // it should return record always, but in sites rebuilt from scratch
            // and being reconstructed using course backups
            $user_data = false;
            if (backup_is_same_site($restore)) {
                $user_data = get_record('user', 'id', $user->id);
            }
            // Only try to perform mnethost/auth modifications if restoring to another server
            // or if, while restoring to same server, the user doesn't exists yet (rebuilt site)
            //
            // So existing user data in same server *won't be modified by restore anymore*,
            // under any circumpstance. If somehting is wrong with existing data, it's server fault.
            if (!backup_is_same_site($restore) || backup_is_same_site($restore) && !$user_data) {
                //Calculate mnethostid
                if (empty($user->mnethosturl) || $user->mnethosturl === $CFG->wwwroot) {
                    $user->mnethostid = $CFG->mnet_localhost_id;
                } else {
                    // fast url-to-id lookups
                    if (isset($mnethosts[$user->mnethosturl])) {
                        $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
                    } else {
                        $user->mnethostid = $CFG->mnet_localhost_id;
                    }
                }
                //Arriving here, any user with mnet auth and using $CFG->mnet_localhost_id is wrong
                //as own server cannot be accesed over mnet. Change auth to manual and inform about the switch
                if ($user->auth == 'mnet' && $user->mnethostid == $CFG->mnet_localhost_id) {
                    // Respect registerauth
                    if ($CFG->registerauth == 'email') {
                        $user->auth = 'email';
                    } else {
                        $user->auth = 'manual';
                    }
                    // inform about the automatic switch of authentication/host
                    if (empty($user->mnethosturl)) {
                        $user->mnethosturl = '----';
                    }
                    $messages[] = get_string('mnetrestore_extusers_switchuserauth', 'admin', $user);
                }
            }
            unset($user->mnethosturl);
            //To store user->id along all the iteration
            $newid = null;
            //check if it exists (by username) and get its id
            $user_exists = true;
            if (!backup_is_same_site($restore)) {
                /// Restoring to another server, look for existing user based on fields
                /// If restoring to same server, look has been performed some lines above (by id)
                $user_data = get_record('user', 'username', addslashes($user->username), 'mnethostid', $user->mnethostid);
            }
            if (!$user_data) {
                $user_exists = false;
            } else {
                $newid = $user_data->id;
            }
            //Flags to see what parts are we going to restore
            $create_user = true;
            $create_roles = true;
            $create_custom_profile_fields = true;
            $create_tags = true;
            $create_preferences = true;
            //If we are restoring course users and it isn't a course user
            if ($restore->users == 1 and !$is_course_user) {
                //If only restoring course_users and user isn't a course_user, inform to $backup_ids
                $status = backup_putid($restore->backup_unique_code, "user", $userid, null, 'notincourse');
                $create_user = false;
                $create_roles = false;
                $create_custom_profile_fields = false;
                $create_tags = false;
                $create_preferences = false;
            }
            if ($user_exists and $create_user) {
                //If user exists mark its newid in backup_ids (the same than old)
                $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, 'exists');
                $create_user = false;
                $create_custom_profile_fields = false;
                $create_tags = false;
                $create_preferences = false;
            }
            //Here, if create_user, do it
            if ($create_user) {
                //Unset the id because it's going to be inserted with a new one
                unset($user->id);
                // relink the descriptions
                $user->description = stripslashes($user->description);
                /// Disable pictures based on global setting or existing empty value (old backups can contain wrong empties)
                if (!empty($CFG->disableuserimages) || empty($user->picture)) {
                    $user->picture = 0;
                }
                //We need to analyse the AUTH field to recode it:
                //   - if the field isn't set, we are in a pre 1.4 backup and we'll
                //     use manual
                if (empty($user->auth)) {
                    if ($CFG->registerauth == 'email') {
                        $user->auth = 'email';
                    } else {
                        $user->auth = 'manual';
                    }
                }
                //We need to process the POLICYAGREED field to recalculate it:
                //    - if the destination site is different (by wwwroot) reset it.
                //    - if the destination site is the same (by wwwroot), leave it unmodified
                if (!backup_is_same_site($restore)) {
                    $user->policyagreed = 0;
                } else {
                    //Nothing to do, we are in the same server
                }
                //Check if the theme exists in destination server
                $themes = get_list_of_themes();
                if (!in_array($user->theme, $themes)) {
                    $user->theme = '';
                }
                //We are going to create the user
                //The structure is exactly as we need
                $newid = insert_record("user", addslashes_recursive($user));
                //Put the new id
                $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, "new");
            }
            ///TODO: This seccion is to support pre 1.7 course backups, using old roles
            ///      teacher, coursecreator, student.... providing a basic mapping to new ones.
            ///      Someday we'll drop support for them and this section will be safely deleted (2.0?)
            //Here, if create_roles, do it as necessary
            if ($create_roles) {
                //Get the newid and current info from backup_ids
                $data = backup_getid($restore->backup_unique_code, "user", $userid);
                $newid = $data->new_id;
                $currinfo = $data->info . ",";
                //Now, depending of the role, create records in user_studentes and user_teacher
                //and/or mark it in backup_ids
                if ($is_admin) {
                    //If the record (user_admins) doesn't exists
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "admin,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_coursecreator) {
                    //If the record (user_coursecreators) doesn't exists
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "coursecreator,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_needed) {
                    //Only put status in backup_ids
                    $currinfo = $currinfo . "needed,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                }
                if ($is_teacher) {
                    //If the record (teacher) doesn't exists
                    //Put status in backup_ids
                    $currinfo = $currinfo . "teacher,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    //Set course and user
                    $user->roles['teacher']->course = $restore->course_id;
                    $user->roles['teacher']->userid = $newid;
                    //Need to analyse the enrol field
                    //    - if it isn't set, set it to $CFG->enrol
                    //    - if we are in a different server (by wwwroot), set it to $CFG->enrol
                    //    - if we are in the same server (by wwwroot), maintain it unmodified.
                    if (empty($user->roles['teacher']->enrol)) {
                        $user->roles['teacher']->enrol = $CFG->enrol;
                    } else {
                        if (!backup_is_same_site($restore)) {
                            $user->roles['teacher']->enrol = $CFG->enrol;
                        } else {
                            //Nothing to do. Leave it unmodified
                        }
                    }
                    $rolesmapping = $restore->rolesmapping;
                    $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
                    if ($user->roles['teacher']->editall) {
                        role_assign($rolesmapping['defaultteacheredit'], $newid, 0, $context->id, $user->roles['teacher']->timestart, $user->roles['teacher']->timeend, 0, $user->roles['teacher']->enrol);
                        // editting teacher
                    } else {
                        // non editting teacher
                        role_assign($rolesmapping['defaultteacher'], $newid, 0, $context->id, $user->roles['teacher']->timestart, $user->roles['teacher']->timeend, 0, $user->roles['teacher']->enrol);
                    }
                }
                if ($is_student) {
                    //Put status in backup_ids
                    $currinfo = $currinfo . "student,";
                    $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    //Set course and user
                    $user->roles['student']->course = $restore->course_id;
                    $user->roles['student']->userid = $newid;
                    //Need to analyse the enrol field
                    //    - if it isn't set, set it to $CFG->enrol
                    //    - if we are in a different server (by wwwroot), set it to $CFG->enrol
                    //    - if we are in the same server (by wwwroot), maintain it unmodified.
                    if (empty($user->roles['student']->enrol)) {
                        $user->roles['student']->enrol = $CFG->enrol;
                    } else {
                        if (!backup_is_same_site($restore)) {
                            $user->roles['student']->enrol = $CFG->enrol;
                        } else {
                            //Nothing to do. Leave it unmodified
                        }
                    }
                    $rolesmapping = $restore->rolesmapping;
                    $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
                    role_assign($rolesmapping['defaultstudent'], $newid, 0, $context->id, $user->roles['student']->timestart, $user->roles['student']->timeend, 0, $user->roles['student']->enrol);
                }
                if (!$is_course_user) {
                    //If the record (user) doesn't exists
                    if (!record_exists("user", "id", $newid)) {
                        //Put status in backup_ids
                        $currinfo = $currinfo . "user,";
                        $status = backup_putid($restore->backup_unique_code, "user", $userid, $newid, $currinfo);
                    }
                }
            }
            /// Here, if create_custom_profile_fields, do it as necessary
            if ($create_custom_profile_fields) {
                if (isset($user->user_custom_profile_fields)) {
                    foreach ($user->user_custom_profile_fields as $udata) {
                        /// If the profile field has data and the profile shortname-datatype is defined in server
                        if ($udata->field_data) {
                            if ($field = get_record('user_info_field', 'shortname', $udata->field_name, 'datatype', $udata->field_type)) {
                                /// Insert the user_custom_profile_field
                                $rec = new object();
                                $rec->userid = $newid;
                                $rec->fieldid = $field->id;
                                $rec->data = $udata->field_data;
                                insert_record('user_info_data', $rec);
                            }
                        }
                    }
                }
            }
            /// Here, if create_tags, do it as necessary
            if ($create_tags) {
                /// if tags are enabled and there are user tags
                if (!empty($CFG->usetags) && isset($user->user_tags)) {
                    $tags = array();
                    foreach ($user->user_tags as $user_tag) {
                        $tags[] = $user_tag->rawname;
                    }
                    tag_set('user', $newid, $tags);
                }
            }
            //Here, if create_preferences, do it as necessary
            if ($create_preferences) {
                if (isset($user->user_preferences)) {
                    foreach ($user->user_preferences as $user_preference) {
                        //We check if that user_preference exists in DB
                        if (!record_exists("user_preferences", "userid", $newid, "name", $user_preference->name)) {
                            //Prepare the record and insert it
                            $user_preference->userid = $newid;
                            $status = insert_record("user_preferences", $user_preference);
                        }
                    }
                }
            }
            //Do some output
            $counter++;
            if ($counter % 10 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if ($counter % 200 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }
        }
        /// End of loop over all the users loaded from xml
        /// Inform about all the messages geerated while restoring users
        if (!defined('RESTORE_SILENTLY')) {
            if ($messages) {
                echo '<ul>';
                foreach ($messages as $message) {
                    echo '<li>' . $message . '</li>';
                }
                echo '</ul>';
            }
        }
    }
    return $status;
}
Пример #19
0
    /// Print button to create a new course
    unset($options);
    $options['category'] = $category->id;
    print_single_button('new_course.php', $options, get_string('addnewcourse'), 'get');
    echo '<br />';
}
if (has_capability('moodle/category:update', $context)) {
    /// Print form to rename the category
    $strrename = get_string('rename');
    echo '<form id="renameform" action="category.php" method="post"><div>';
    echo '<input type="hidden" name="id" value="' . $category->id . '" />';
    echo '<input type="hidden" name="sesskey" value="' . $USER->sesskey . '" />';
    echo '<input type="text" size="30" name="rename" value="' . format_string($category->name) . '" alt="' . $strrename . '" />';
    echo '<input type="submit" value="' . $strrename . '" />';
    echo '</div></form>';
    echo '<br />';
    if (!empty($CFG->allowcategorythemes)) {
        $choices = array();
        $choices[''] = get_string('default');
        $choices += get_list_of_themes();
        echo '<form id="themeform" action="category.php" method="post"><div>';
        echo '<input type="hidden" name="id" value="' . $category->id . '" />';
        echo '<input type="hidden" name="sesskey" value="' . $USER->sesskey . '" />';
        choose_from_menu($choices, 'categorytheme', $category->theme);
        echo '<input type="submit" value="' . get_string('setcategorytheme') . '" />';
        echo '</div></form>';
        echo '<br />';
    }
}
print_course_search();
print_footer();
 function definition()
 {
     global $CFG, $COURSE, $DB;
     $mform = $this->_form;
     $columns = $this->_customdata['columns'];
     $data = $this->_customdata['data'];
     $courseconfig = get_config('moodlecourse');
     // I am the template course, why should it be the administrator? we have roles now, other ppl may use this script ;-)
     $templatecourse = $COURSE;
     // upload settings and file
     $mform->addElement('header', 'settingsheader', get_string('settings'));
     $choices = array(CC_COURSE_ADDNEW => get_string('ccoptype_addnew', 'tool_uploadcoursecategory'), CC_COURSE_ADDINC => get_string('ccoptype_addinc', 'tool_uploadcoursecategory'), CC_COURSE_ADD_UPDATE => get_string('ccoptype_addupdate', 'tool_uploadcoursecategory'), CC_COURSE_UPDATE => get_string('ccoptype_update', 'tool_uploadcoursecategory'));
     $mform->addElement('select', 'cctype', get_string('ccoptype', 'tool_uploadcoursecategory'), $choices);
     $choices = array(CC_UPDATE_NOCHANGES => get_string('nochanges', 'tool_uploadcoursecategory'), CC_UPDATE_FILEOVERRIDE => get_string('ccupdatefromfile', 'tool_uploadcoursecategory'), CC_UPDATE_ALLOVERRIDE => get_string('ccupdateall', 'tool_uploadcoursecategory'), CC_UPDATE_MISSING => get_string('ccupdatemissing', 'tool_uploadcoursecategory'));
     $mform->addElement('select', 'ccupdatetype', get_string('ccupdatetype', 'tool_uploadcoursecategory'), $choices);
     $mform->setDefault('ccupdatetype', CC_UPDATE_NOCHANGES);
     $mform->disabledIf('ccupdatetype', 'cctype', 'eq', CC_COURSE_ADDNEW);
     $mform->disabledIf('ccupdatetype', 'cctype', 'eq', CC_COURSE_ADDINC);
     $mform->addElement('selectyesno', 'ccallowrenames', get_string('allowrenames', 'tool_uploadcoursecategory'));
     $mform->setDefault('ccallowrenames', 0);
     $mform->disabledIf('ccallowrenames', 'cctype', 'eq', CC_COURSE_ADDNEW);
     $mform->disabledIf('ccallowrenames', 'cctype', 'eq', CC_COURSE_ADDINC);
     $mform->addElement('selectyesno', 'ccallowdeletes', get_string('allowdeletes', 'tool_uploadcoursecategory'));
     $mform->setDefault('ccallowdeletes', 0);
     $mform->disabledIf('ccallowdeletes', 'cctype', 'eq', CC_COURSE_ADDNEW);
     $mform->disabledIf('ccallowdeletes', 'cctype', 'eq', CC_COURSE_ADDINC);
     $mform->addElement('selectyesno', 'ccstandardnames', get_string('ccstandardnames', 'tool_uploadcoursecategory'));
     $mform->setDefault('ccstandardnames', 1);
     //        $choices = array(CC_BULK_NONE    => get_string('no'),
     //                         CC_BULK_NEW     => get_string('ccbulknew', 'tool_uploadcoursecategory'),
     //                         CC_BULK_UPDATED => get_string('ccbulkupdated', 'tool_uploadcoursecategory'),
     //                         CC_BULK_ALL     => get_string('ccbulkall', 'tool_uploadcoursecategory'));
     //        $mform->addElement('select', 'ccbulk', get_string('ccbulk', 'tool_uploadcoursecategory'), $choices);
     //        $mform->setDefault('ccbulk', 0);
     // default values
     $mform->addElement('header', 'defaultheader', get_string('defaultvalues', 'tool_uploadcoursecategory'));
     $mform->addElement('text', 'ccname', get_string('ccnametemplate', 'tool_uploadcoursecategory'), 'maxlength="100" size="20"');
     $mform->addHelpButton('ccname', 'namecoursecategory', 'tool_uploadcoursecategory');
     $mform->disabledIf('ccname', 'cctype', 'eq', CC_COURSE_ADD_UPDATE);
     $mform->disabledIf('ccname', 'cctype', 'eq', CC_COURSE_UPDATE);
     $mform->addElement('text', 'ccidnumber', get_string('ccidnumbertemplate', 'tool_uploadcoursecategory'), 'maxlength="100"  size="10"');
     $mform->addHelpButton('ccidnumber', 'idnumbercoursecategory');
     $mform->disabledIf('ccidnumber', 'cctype', 'eq', CC_COURSE_ADD_UPDATE);
     $mform->disabledIf('ccidnumber', 'cctype', 'eq', CC_COURSE_UPDATE);
     if (!empty($CFG->allowcategorythemes)) {
         $themeobjects = get_list_of_themes();
         $themes = array();
         $themes[''] = get_string('forceno');
         foreach ($themeobjects as $key => $theme) {
             if (empty($theme->hidefromselector)) {
                 $themes[$key] = get_string('pluginname', 'theme_' . $theme->name);
             }
         }
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('availability'));
     $choices = array();
     $choices['0'] = get_string('coursecategoryavailablenot', 'tool_uploadcoursecategory');
     $choices['1'] = get_string('coursecategoryavailable', 'tool_uploadcoursecategory');
     $mform->addElement('select', 'visible', get_string('availability'), $choices);
     $mform->addHelpButton('visible', 'coursecategoryavailability', 'tool_uploadcoursecategory');
     $mform->setDefault('visible', $courseconfig->visible);
     // 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('uploadcoursecategories', 'tool_uploadcoursecategory'));
     $this->set_data($data);
 }
Пример #21
0
 /**
  * The standard form definiton.
  * @return void.
  */
 public function definition()
 {
     global $CFG;
     $mform = $this->_form;
     $data = $this->_customdata['data'];
     $courseconfig = get_config('moodlecourse');
     // Import options.
     $this->add_import_options();
     // Course options.
     $mform->addElement('header', 'courseoptionshdr', get_string('courseprocess', 'tool_uploadcourse'));
     $mform->setExpanded('courseoptionshdr', true);
     $mform->addElement('text', 'options[shortnametemplate]', get_string('shortnametemplate', 'tool_uploadcourse'), 'maxlength="100" size="20"');
     $mform->setType('options[shortnametemplate]', PARAM_RAW);
     $mform->addHelpButton('options[shortnametemplate]', 'shortnametemplate', 'tool_uploadcourse');
     $mform->disabledIf('options[shortnametemplate]', 'options[mode]', 'eq', tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE);
     $mform->disabledIf('options[shortnametemplate]', 'options[mode]', 'eq', tool_uploadcourse_processor::MODE_UPDATE_ONLY);
     // Restore file is not in the array options on purpose, because formslib can't handle it!
     $contextid = $this->_customdata['contextid'];
     $mform->addElement('hidden', 'contextid', $contextid);
     $mform->setType('contextid', PARAM_INT);
     $mform->addElement('filepicker', 'restorefile', get_string('templatefile', 'tool_uploadcourse'));
     $mform->addHelpButton('restorefile', 'templatefile', 'tool_uploadcourse');
     $mform->addElement('text', 'options[templatecourse]', get_string('coursetemplatename', 'tool_uploadcourse'));
     $mform->setType('options[templatecourse]', PARAM_TEXT);
     $mform->addHelpButton('options[templatecourse]', 'coursetemplatename', 'tool_uploadcourse');
     $mform->addElement('selectyesno', 'options[reset]', get_string('reset', 'tool_uploadcourse'));
     $mform->setDefault('options[reset]', 0);
     $mform->disabledIf('options[reset]', 'options[mode]', 'eq', tool_uploadcourse_processor::MODE_CREATE_NEW);
     $mform->disabledIf('options[reset]', 'options[mode]', 'eq', tool_uploadcourse_processor::MODE_CREATE_ALL);
     $mform->disabledIf('options[reset]', 'options[allowresets]', 'eq', 0);
     $mform->addHelpButton('options[reset]', 'reset', 'tool_uploadcourse');
     // Default values.
     $mform->addElement('header', 'defaultheader', get_string('defaultvalues', 'tool_uploadcourse'));
     $mform->setExpanded('defaultheader', true);
     $displaylist = coursecat::make_categories_list('moodle/course:create');
     $mform->addElement('select', 'defaults[category]', get_string('coursecategory'), $displaylist);
     $mform->addHelpButton('defaults[category]', 'coursecategory');
     $choices = array();
     $choices['0'] = get_string('hide');
     $choices['1'] = get_string('show');
     $mform->addElement('select', 'defaults[visible]', get_string('visible'), $choices);
     $mform->addHelpButton('defaults[visible]', 'visible');
     $mform->setDefault('defaults[visible]', $courseconfig->visible);
     $mform->addElement('date_selector', 'defaults[startdate]', get_string('startdate'));
     $mform->addHelpButton('defaults[startdate]', 'startdate');
     $mform->setDefault('defaults[startdate]', time() + 3600 * 24);
     $mform->addElement('date_selector', 'defaults[enddate]', get_string('enddate'), array('optional' => true));
     $mform->addHelpButton('defaults[enddate]', 'enddate');
     $courseformats = get_sorted_course_formats(true);
     $formcourseformats = array();
     foreach ($courseformats as $courseformat) {
         $formcourseformats[$courseformat] = get_string('pluginname', "format_{$courseformat}");
     }
     $mform->addElement('select', 'defaults[format]', get_string('format'), $formcourseformats);
     $mform->addHelpButton('defaults[format]', 'format');
     $mform->setDefault('defaults[format]', $courseconfig->format);
     if (!empty($CFG->allowcoursethemes)) {
         $themeobjects = get_list_of_themes();
         $themes = array();
         $themes[''] = get_string('forceno');
         foreach ($themeobjects as $key => $theme) {
             if (empty($theme->hidefromselector)) {
                 $themes[$key] = get_string('pluginname', 'theme_' . $theme->name);
             }
         }
         $mform->addElement('select', 'defaults[theme]', get_string('forcetheme'), $themes);
     }
     $languages = array();
     $languages[''] = get_string('forceno');
     $languages += get_string_manager()->get_list_of_translations();
     $mform->addElement('select', 'defaults[lang]', get_string('forcelanguage'), $languages);
     $mform->setDefault('defaults[lang]', $courseconfig->lang);
     $options = range(0, 10);
     $mform->addElement('select', 'defaults[newsitems]', get_string('newsitemsnumber'), $options);
     $mform->addHelpButton('defaults[newsitems]', 'newsitemsnumber');
     $mform->setDefault('defaults[newsitems]', $courseconfig->newsitems);
     $mform->addElement('selectyesno', 'defaults[showgrades]', get_string('showgrades'));
     $mform->addHelpButton('defaults[showgrades]', 'showgrades');
     $mform->setDefault('defaults[showgrades]', $courseconfig->showgrades);
     $mform->addElement('selectyesno', 'defaults[showreports]', get_string('showreports'));
     $mform->addHelpButton('defaults[showreports]', 'showreports');
     $mform->setDefault('defaults[showreports]', $courseconfig->showreports);
     if (!empty($CFG->legacyfilesinnewcourses)) {
         $mform->addElement('select', 'defaults[legacyfiles]', get_string('courselegacyfiles'), $choices);
         $mform->addHelpButton('defaults[legacyfiles]', 'courselegacyfiles');
         if (!isset($courseconfig->legacyfiles)) {
             $courseconfig->legacyfiles = 0;
         }
         $mform->setDefault('defaults[legacyfiles]', $courseconfig->legacyfiles);
     }
     $choices = get_max_upload_sizes($CFG->maxbytes);
     $mform->addElement('select', 'defaults[maxbytes]', get_string('maximumupload'), $choices);
     $mform->addHelpButton('defaults[maxbytes]', 'maximumupload');
     $mform->setDefault('defaults[maxbytes]', $courseconfig->maxbytes);
     $choices = array();
     $choices[NOGROUPS] = get_string('groupsnone', 'group');
     $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
     $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
     $mform->addElement('select', 'defaults[groupmode]', get_string('groupmode', 'group'), $choices);
     $mform->addHelpButton('defaults[groupmode]', 'groupmode', 'group');
     $mform->setDefault('defaults[groupmode]', $courseconfig->groupmode);
     $mform->addElement('selectyesno', 'defaults[groupmodeforce]', get_string('groupmodeforce', 'group'));
     $mform->addHelpButton('defaults[groupmodeforce]', 'groupmodeforce', 'group');
     $mform->setDefault('defaults[groupmodeforce]', $courseconfig->groupmodeforce);
     // Hidden fields.
     $mform->addElement('hidden', 'importid');
     $mform->setType('importid', PARAM_INT);
     $mform->addElement('hidden', 'previewrows');
     $mform->setType('previewrows', PARAM_INT);
     $this->add_action_buttons(true, get_string('uploadcourses', 'tool_uploadcourse'));
     $this->set_data($data);
 }
Пример #22
0
 /**
  * Definition of user profile fields and the expected parameter type for data validation.
  *
  * array(
  *     'property_name' => array(       // The user property to be checked. Should match the field on the user table.
  *          'null' => NULL_ALLOWED,    // Defaults to NULL_NOT_ALLOWED. Takes NULL_NOT_ALLOWED or NULL_ALLOWED.
  *          'type' => PARAM_TYPE,      // Expected parameter type of the user field.
  *          'choices' => array(1, 2..) // An array of accepted values of the user field.
  *          'default' => $CFG->setting // An default value for the field.
  *     )
  * )
  *
  * The fields choices and default are optional.
  *
  * @return void
  */
 protected static function fill_properties_cache()
 {
     global $CFG;
     if (self::$propertiescache !== null) {
         return;
     }
     // Array of user fields properties and expected parameters.
     // Every new field on the user table should be added here otherwise it won't be validated.
     $fields = array();
     $fields['id'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['auth'] = array('type' => PARAM_AUTH, 'null' => NULL_NOT_ALLOWED);
     $fields['confirmed'] = array('type' => PARAM_BOOL, 'null' => NULL_NOT_ALLOWED);
     $fields['policyagreed'] = array('type' => PARAM_BOOL, 'null' => NULL_NOT_ALLOWED);
     $fields['deleted'] = array('type' => PARAM_BOOL, 'null' => NULL_NOT_ALLOWED);
     $fields['suspended'] = array('type' => PARAM_BOOL, 'null' => NULL_NOT_ALLOWED);
     $fields['mnethostid'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['username'] = array('type' => PARAM_USERNAME, 'null' => NULL_NOT_ALLOWED);
     $fields['password'] = array('type' => PARAM_RAW, 'null' => NULL_NOT_ALLOWED);
     $fields['idnumber'] = array('type' => PARAM_RAW, 'null' => NULL_NOT_ALLOWED);
     $fields['firstname'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED);
     $fields['lastname'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED);
     $fields['surname'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED);
     $fields['email'] = array('type' => PARAM_RAW_TRIMMED, 'null' => NULL_NOT_ALLOWED);
     $fields['emailstop'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['icq'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED);
     $fields['skype'] = array('type' => PARAM_NOTAGS, 'null' => NULL_ALLOWED);
     $fields['aim'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED);
     $fields['yahoo'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED);
     $fields['msn'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED);
     $fields['phone1'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED);
     $fields['phone2'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED);
     $fields['institution'] = array('type' => PARAM_TEXT, 'null' => NULL_NOT_ALLOWED);
     $fields['department'] = array('type' => PARAM_TEXT, 'null' => NULL_NOT_ALLOWED);
     $fields['address'] = array('type' => PARAM_TEXT, 'null' => NULL_NOT_ALLOWED);
     $fields['city'] = array('type' => PARAM_TEXT, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->defaultcity);
     $fields['country'] = array('type' => PARAM_ALPHA, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->country, 'choices' => array_merge(array('' => ''), get_string_manager()->get_list_of_countries(true, true)));
     $fields['lang'] = array('type' => PARAM_LANG, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->lang, 'choices' => array_merge(array('' => ''), get_string_manager()->get_list_of_translations(false)));
     $fields['calendartype'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->calendartype, 'choices' => array_merge(array('' => ''), \core_calendar\type_factory::get_list_of_calendar_types()));
     $fields['theme'] = array('type' => PARAM_THEME, 'null' => NULL_NOT_ALLOWED, 'default' => theme_config::DEFAULT_THEME, 'choices' => array_merge(array('' => ''), get_list_of_themes()));
     $fields['timezone'] = array('type' => PARAM_TIMEZONE, 'null' => NULL_NOT_ALLOWED, 'default' => core_date::get_server_timezone());
     // Must not use choices here: timezones can come and go.
     $fields['firstaccess'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['lastaccess'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['lastlogin'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['currentlogin'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['lastip'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED);
     $fields['secret'] = array('type' => PARAM_RAW, 'null' => NULL_NOT_ALLOWED);
     $fields['picture'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['url'] = array('type' => PARAM_URL, 'null' => NULL_NOT_ALLOWED);
     $fields['description'] = array('type' => PARAM_RAW, 'null' => NULL_ALLOWED);
     $fields['descriptionformat'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['mailformat'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->defaultpreference_mailformat);
     $fields['maildigest'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->defaultpreference_maildigest);
     $fields['maildisplay'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->defaultpreference_maildisplay);
     $fields['autosubscribe'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->defaultpreference_autosubscribe);
     $fields['trackforums'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => $CFG->defaultpreference_trackforums);
     $fields['timecreated'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['timemodified'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['trustbitmask'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED);
     $fields['imagealt'] = array('type' => PARAM_TEXT, 'null' => NULL_ALLOWED);
     $fields['lastnamephonetic'] = array('type' => PARAM_NOTAGS, 'null' => NULL_ALLOWED);
     $fields['firstnamephonetic'] = array('type' => PARAM_NOTAGS, 'null' => NULL_ALLOWED);
     $fields['middlename'] = array('type' => PARAM_NOTAGS, 'null' => NULL_ALLOWED);
     $fields['alternatename'] = array('type' => PARAM_NOTAGS, 'null' => NULL_ALLOWED);
     self::$propertiescache = $fields;
 }
Пример #23
0
/**
 * Powerful function that is used by edit and editadvanced to add common form elements/rules/etc.
 *
 * @param moodleform $mform
 * @param array $editoroptions
 * @param array $filemanageroptions
 * @param stdClass $user
 */
function useredit_shared_definition(&$mform, $editoroptions, $filemanageroptions, $user)
{
    global $CFG, $USER, $DB;
    if ($user->id > 0) {
        useredit_load_preferences($user, false);
    }
    $strrequired = get_string('required');
    $stringman = get_string_manager();
    // Add the necessary names.
    foreach (useredit_get_required_name_fields() as $fullname) {
        $mform->addElement('text', $fullname, get_string($fullname), 'maxlength="100" size="30"');
        if ($stringman->string_exists('missing' . $fullname, 'core')) {
            $strmissingfield = get_string('missing' . $fullname, 'core');
        } else {
            $strmissingfield = $strrequired;
        }
        $mform->addRule($fullname, $strmissingfield, 'required', null, 'client');
        $mform->setType($fullname, PARAM_NOTAGS);
    }
    $enabledusernamefields = useredit_get_enabled_name_fields();
    // Add the enabled additional name fields.
    foreach ($enabledusernamefields as $addname) {
        $mform->addElement('text', $addname, get_string($addname), 'maxlength="100" size="30"');
        $mform->setType($addname, PARAM_NOTAGS);
    }
    // Do not show email field if change confirmation is pending.
    if ($user->id > 0 and !empty($CFG->emailchangeconfirmation) and !empty($user->preference_newemail)) {
        $notice = get_string('emailchangepending', 'auth', $user);
        $notice .= '<br /><a href="edit.php?cancelemailchange=1&amp;id=' . $user->id . '">' . get_string('emailchangecancel', 'auth') . '</a>';
        $mform->addElement('static', 'emailpending', get_string('email'), $notice);
    } else {
        $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"');
        $mform->addRule('email', $strrequired, 'required', null, 'client');
        $mform->setType('email', PARAM_RAW_TRIMMED);
    }
    $choices = array();
    $choices['0'] = get_string('emaildisplayno');
    $choices['1'] = get_string('emaildisplayyes');
    $choices['2'] = get_string('emaildisplaycourse');
    $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
    $mform->setDefault('maildisplay', core_user::get_property_default('maildisplay'));
    $mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="21"');
    $mform->setType('city', PARAM_TEXT);
    if (!empty($CFG->defaultcity)) {
        $mform->setDefault('city', $CFG->defaultcity);
    }
    $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', core_user::get_property_default('country'));
    }
    if (isset($CFG->forcetimezone) and $CFG->forcetimezone != 99) {
        $choices = core_date::get_list_of_timezones($CFG->forcetimezone);
        $mform->addElement('static', 'forcedtimezone', get_string('timezone'), $choices[$CFG->forcetimezone]);
        $mform->addElement('hidden', 'timezone');
        $mform->setType('timezone', core_user::get_property_type('timezone'));
    } else {
        $choices = core_date::get_list_of_timezones($user->timezone, true);
        $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
    }
    if (!empty($CFG->allowuserthemes)) {
        $choices = array();
        $choices[''] = get_string('default');
        $themes = get_list_of_themes();
        foreach ($themes as $key => $theme) {
            if (empty($theme->hidefromselector)) {
                $choices[$key] = get_string('pluginname', 'theme_' . $theme->name);
            }
        }
        $mform->addElement('select', 'theme', get_string('preferredtheme'), $choices);
    }
    $mform->addElement('editor', 'description_editor', get_string('userdescription'), null, $editoroptions);
    $mform->setType('description_editor', PARAM_CLEANHTML);
    $mform->addHelpButton('description_editor', 'userdescription');
    if (empty($USER->newadminuser)) {
        $mform->addElement('header', 'moodle_picture', get_string('pictureofuser'));
        $mform->setExpanded('moodle_picture', true);
        if (!empty($CFG->enablegravatar)) {
            $mform->addElement('html', html_writer::tag('p', get_string('gravatarenabled')));
        }
        $mform->addElement('static', 'currentpicture', get_string('currentpicture'));
        $mform->addElement('checkbox', 'deletepicture', get_string('delete'));
        $mform->setDefault('deletepicture', 0);
        $mform->addElement('filemanager', 'imagefile', get_string('newpicture'), '', $filemanageroptions);
        $mform->addHelpButton('imagefile', 'newpicture');
        $mform->addElement('text', 'imagealt', get_string('imagealt'), 'maxlength="100" size="30"');
        $mform->setType('imagealt', PARAM_TEXT);
    }
    // Display user name fields that are not currenlty enabled here if there are any.
    $disabledusernamefields = useredit_get_disabled_name_fields($enabledusernamefields);
    if (count($disabledusernamefields) > 0) {
        $mform->addElement('header', 'moodle_additional_names', get_string('additionalnames'));
        foreach ($disabledusernamefields as $allname) {
            $mform->addElement('text', $allname, get_string($allname), 'maxlength="100" size="30"');
            $mform->setType($allname, PARAM_NOTAGS);
        }
    }
    if (core_tag_tag::is_enabled('core', 'user') and empty($USER->newadminuser)) {
        $mform->addElement('header', 'moodle_interests', get_string('interests'));
        $mform->addElement('tags', 'interests', get_string('interestslist'), array('itemtype' => 'user', 'component' => 'core'));
        $mform->addHelpButton('interests', 'interestslist');
    }
    // Moodle optional fields.
    $mform->addElement('header', 'moodle_optional', get_string('optional', 'form'));
    $mform->addElement('text', 'url', get_string('webpage'), 'maxlength="255" size="50"');
    $mform->setType('url', core_user::get_property_type('url'));
    $mform->addElement('text', 'icq', get_string('icqnumber'), 'maxlength="15" size="25"');
    $mform->setType('icq', core_user::get_property_type('icq'));
    $mform->setForceLtr('icq');
    $mform->addElement('text', 'skype', get_string('skypeid'), 'maxlength="50" size="25"');
    $mform->setType('skype', core_user::get_property_type('skype'));
    $mform->setForceLtr('skype');
    $mform->addElement('text', 'aim', get_string('aimid'), 'maxlength="50" size="25"');
    $mform->setType('aim', core_user::get_property_type('aim'));
    $mform->setForceLtr('aim');
    $mform->addElement('text', 'yahoo', get_string('yahooid'), 'maxlength="50" size="25"');
    $mform->setType('yahoo', core_user::get_property_type('yahoo'));
    $mform->setForceLtr('yahoo');
    $mform->addElement('text', 'msn', get_string('msnid'), 'maxlength="50" size="25"');
    $mform->setType('msn', core_user::get_property_type('msn'));
    $mform->setForceLtr('msn');
    $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
    $mform->setType('idnumber', core_user::get_property_type('idnumber'));
    $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="255" size="25"');
    $mform->setType('institution', core_user::get_property_type('institution'));
    $mform->addElement('text', 'department', get_string('department'), 'maxlength="255" size="25"');
    $mform->setType('department', core_user::get_property_type('department'));
    $mform->addElement('text', 'phone1', get_string('phone1'), 'maxlength="20" size="25"');
    $mform->setType('phone1', core_user::get_property_type('phone1'));
    $mform->setForceLtr('phone1');
    $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
    $mform->setType('phone2', core_user::get_property_type('phone2'));
    $mform->setForceLtr('phone2');
    $mform->addElement('text', 'address', get_string('address'), 'maxlength="255" size="25"');
    $mform->setType('address', core_user::get_property_type('address'));
}
 /**
  * Processing functions go here
  *
  * @global moodledatabase $DB
  * @param stdClass $data
  */
 public function process_course($data)
 {
     global $CFG, $DB;
     $data = (object) $data;
     $fullname = $this->get_setting_value('course_fullname');
     $shortname = $this->get_setting_value('course_shortname');
     $startdate = $this->get_setting_value('course_startdate');
     // Calculate final course names, to avoid dupes
     list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);
     // Need to change some fields before updating the course record
     $data->id = $this->get_courseid();
     $data->fullname = $fullname;
     $data->shortname = $shortname;
     $context = get_context_instance_by_id($this->task->get_contextid());
     if (has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
         $data->idnumber = '';
     } else {
         unset($data->idnumber);
     }
     // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
     // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
     if (empty($data->hiddensections)) {
         $data->hiddensections = 0;
     }
     // Only restrict modules if original course was and target site too for new courses
     $data->restrictmodules = $data->restrictmodules && !empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all';
     $data->startdate = $this->apply_date_offset($data->startdate);
     if ($data->defaultgroupingid) {
         $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
     }
     if (empty($CFG->enablecompletion)) {
         $data->enablecompletion = 0;
         $data->completionstartonenrol = 0;
         $data->completionnotify = 0;
     }
     $languages = get_string_manager()->get_list_of_translations();
     // Get languages for quick search
     if (!array_key_exists($data->lang, $languages)) {
         $data->lang = '';
     }
     $themes = get_list_of_themes();
     // Get themes for quick search later
     if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
         $data->theme = '';
     }
     // Course record ready, update it
     $DB->update_record('course', $data);
     // Role name aliases
     restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
 }
Пример #25
0
    /**
     * Processing functions go here
     *
     * @global moodledatabase $DB
     * @param stdClass $data
     */
    public function process_course($data) {
        global $CFG, $DB;

        $data = (object)$data;
        $oldid = $data->id; // We'll need this later

        $fullname  = $this->get_setting_value('course_fullname');
        $shortname = $this->get_setting_value('course_shortname');
        $startdate = $this->get_setting_value('course_startdate');

        // Calculate final course names, to avoid dupes
        list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname);

        // Need to change some fields before updating the course record
        $data->id = $this->get_courseid();
        $data->fullname = $fullname;
        $data->shortname= $shortname;
        $data->idnumber = '';

        // Only restrict modules if original course was and target site too for new courses
        $data->restrictmodules = $data->restrictmodules && !empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all';

        $data->startdate= $this->apply_date_offset($data->startdate);
        if ($data->defaultgroupingid) {
            $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
        }
        if (empty($CFG->enablecompletion)) {
            $data->enablecompletion = 0;
            $data->completionstartonenrol = 0;
            $data->completionnotify = 0;
        }
        $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
        if (!array_key_exists($data->lang, $languages)) {
            $data->lang = '';
        }

        $themes = get_list_of_themes(); // Get themes for quick search later
        if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
            $data->theme = '';
        }

        // Course record ready, update it
        $DB->update_record('course', $data);

        // Role name aliases
        restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
    }
Пример #26
0
    function moodle_course_create_courses($client) {
        global $DB, $CFG;

        ///Test data
        $courseconfig = get_config('moodlecourse');

        $themeobjects = get_list_of_themes();
        $theme = key($themeobjects);
        $categoryid = $DB->get_record('course_categories', array(), '*', IGNORE_MULTIPLE)->id;
        $categoryid = empty($categoryid) ? 0 : $categoryid;

        $course1 = new stdClass();
        $course1->fullname = 'Test Data create course 1';
        $course1->shortname = 'testdatacourse1';
        $course1->categoryid = $categoryid;
        $course1->idnumber = '328327982372342343234';
        $course1->summary = 'This is a summary';
        $course1->summaryformat = FORMAT_HTML;
        $course1->format = $courseconfig->format;
        $course1->showgrades = $courseconfig->showgrades;
        $course1->showreports = $courseconfig->showreports;
        $course1->newsitems = $courseconfig->newsitems;
        $course1->startdate = time();
        $course1->numsections = $courseconfig->numsections;
        $course1->maxbytes = $courseconfig->maxbytes;
        $course1->visible = $courseconfig->visible;
        $course1->hiddensections = $courseconfig->hiddensections;
        $course1->groupmode = $courseconfig->groupmode;
        $course1->groupmodeforce = $courseconfig->groupmodeforce;
        $course1->defaultgroupingid = 0;
        if (!empty($courseconfig->lang)) {
            $course1->lang = $courseconfig->lang;
        }
        $course1->enablecompletion = $courseconfig->enablecompletion;
        $course1->completionstartonenrol = $courseconfig->completionstartonenrol;
        $course1->completionnotify = 0;
        $course1->forcetheme = $theme;

        $course2 = new stdClass();
        $course2->fullname = 'Test Data create course 2';
        $course2->shortname = 'testdatacourse2';
        $course2->categoryid = $categoryid;

        $courses = array($course1, $course2);

        //do not run the test if course1 or course2 already exists
        $existingcourses = $DB->get_records_list('course', 'fullname',
                        array($course1->fullname, $course2->fullname));
        if (!empty($existingcourses)) {
            throw new moodle_exception('testdatacoursesalreadyexist');
        }

        $function = 'moodle_course_create_courses';
        $params = array('courses' => $courses);
        $resultcourses = $client->call($function, $params);
        $this->assertEqual(count($courses), count($resultcourses));

        //retrieve user1 from the DB and check values
        $dbcourse1 = $DB->get_record('course', array('fullname' => $course1->fullname));
        $this->assertEqual($dbcourse1->fullname, $course1->fullname);
        $this->assertEqual($dbcourse1->shortname, $course1->shortname);
        $this->assertEqual($dbcourse1->category, $course1->categoryid);
        $this->assertEqual($dbcourse1->idnumber, $course1->idnumber);
        $this->assertEqual($dbcourse1->summary, $course1->summary);
        $this->assertEqual($dbcourse1->summaryformat, $course1->summaryformat);
        $this->assertEqual($dbcourse1->format, $course1->format);
        $this->assertEqual($dbcourse1->showgrades, $course1->showgrades);
        $this->assertEqual($dbcourse1->showreports, $course1->showreports);
        $this->assertEqual($dbcourse1->newsitems, $course1->newsitems);
        $this->assertEqual($dbcourse1->startdate, $course1->startdate);
        $this->assertEqual($dbcourse1->numsections, $course1->numsections);
        $this->assertEqual($dbcourse1->maxbytes, $course1->maxbytes);
        $this->assertEqual($dbcourse1->visible, $course1->visible);
        $this->assertEqual($dbcourse1->hiddensections, $course1->hiddensections);
        $this->assertEqual($dbcourse1->groupmode, $course1->groupmode);
        $this->assertEqual($dbcourse1->groupmodeforce, $course1->groupmodeforce);
        $this->assertEqual($dbcourse1->defaultgroupingid, $course1->defaultgroupingid);
        if (!empty($courseconfig->lang)) {
            $this->assertEqual($dbcourse1->lang, $course1->lang);
        }
        if (completion_info::is_enabled_for_site()) {
            $this->assertEqual($dbcourse1->enablecompletion, $course1->enablecompletion);
            $this->assertEqual($dbcourse1->completionstartonenrol, $course1->completionstartonenrol);
        }
        $this->assertEqual($dbcourse1->completionnotify, $course1->completionnotify);
        if (!empty($CFG->allowcoursethemes)) {
            $this->assertEqual($dbcourse1->theme, $course1->forcetheme);
        }

        //retrieve user2 from the DB and check values
        $dbcourse2 = $DB->get_record('course', array('fullname' => $course2->fullname));
        $this->assertEqual($dbcourse2->fullname, $course2->fullname);
        $this->assertEqual($dbcourse2->shortname, $course2->shortname);
        $this->assertEqual($dbcourse2->category, $course2->categoryid);
        $this->assertEqual($dbcourse2->summaryformat, FORMAT_MOODLE);
        $this->assertEqual($dbcourse2->format, $courseconfig->format);
        $this->assertEqual($dbcourse2->showgrades, $courseconfig->showgrades);
        $this->assertEqual($dbcourse2->showreports, $courseconfig->showreports);
        $this->assertEqual($dbcourse2->newsitems, $courseconfig->newsitems);
        $this->assertEqual($dbcourse2->numsections, $courseconfig->numsections);
        $this->assertEqual($dbcourse2->maxbytes, $courseconfig->maxbytes);
        $this->assertEqual($dbcourse2->visible, $courseconfig->visible);
        $this->assertEqual($dbcourse2->hiddensections, $courseconfig->hiddensections);
        $this->assertEqual($dbcourse2->groupmode, $courseconfig->groupmode);
        $this->assertEqual($dbcourse2->groupmodeforce, $courseconfig->groupmodeforce);
        $this->assertEqual($dbcourse2->defaultgroupingid, 0);

        //delete users from DB
        $DB->delete_records_list('course', 'id',
                array($dbcourse1->id, $dbcourse2->id));
    }
Пример #27
0
 function definition()
 {
     global $USER, $CFG, $DB;
     $courseconfig = get_config('moodlecourse');
     $mform =& $this->_form;
     $course = $this->_customdata['course'];
     $category = $this->_customdata['category'];
     $systemcontext = get_context_instance(CONTEXT_SYSTEM);
     $categorycontext = get_context_instance(CONTEXT_COURSECAT, $category->id);
     $disable_meta = false;
     // basic meta course state protection; server-side security checks not needed
     if (!empty($course)) {
         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
         $context = $coursecontext;
         if (course_in_meta($course)) {
             $disable_meta = get_string('metaalreadyinmeta');
         } else {
             if ($course->metacourse) {
                 if ($DB->count_records('course_meta', array('parent_course' => $course->id)) > 0) {
                     $disable_meta = get_string('metaalreadyhascourses');
                 }
             } else {
                 // if users already enrolled directly into coures, do not allow switching to meta,
                 // users with metacourse manage permission are exception
                 // please note that we do not need exact results - anything unexpected here prevents metacourse
                 $managers = get_users_by_capability($coursecontext, 'moodle/course:managemetacourse', 'u.id');
                 $enrolroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $coursecontext);
                 if ($users = get_role_users(array_keys($enrolroles), $coursecontext, false, 'u.id', 'u.id ASC')) {
                     foreach ($users as $user) {
                         if (!isset($managers[$user->id])) {
                             $disable_meta = get_string('metaalreadyhasenrolments');
                             break;
                         }
                     }
                 }
                 unset($managers);
                 unset($users);
                 unset($enrolroles);
             }
         }
     } else {
         $coursecontext = null;
         $context = $categorycontext;
     }
     /// form definition with new course defaults
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     // Must have create course capability in both categories in order to move course
     if (has_capability('moodle/course:create', $categorycontext)) {
         $displaylist = array();
         $parentlist = array();
         make_categories_list($displaylist, $parentlist, 'moodle/course:create');
         $mform->addElement('select', 'category', get_string('category'), $displaylist);
     } else {
         $mform->addElement('hidden', 'category', null);
     }
     $mform->setHelpButton('category', array('coursecategory', get_string('category')));
     $mform->setDefault('category', $category->id);
     $mform->setType('category', PARAM_INT);
     $fullname = get_string('defaultcoursefullname');
     $shortname = get_string('defaultcourseshortname');
     while ($DB->record_exists('course', array('fullname' => $fullname)) or $DB->record_exists('course', array('fullname' => $fullname))) {
         $fullname++;
         $shortname++;
     }
     $mform->addElement('text', 'fullname', get_string('fullnamecourse'), 'maxlength="254" size="50"');
     $mform->setHelpButton('fullname', array('coursefullname', get_string('fullnamecourse')), true);
     $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
     $mform->setType('fullname', PARAM_MULTILANG);
     if ($course and !has_capability('moodle/course:changefullname', $coursecontext)) {
         $mform->hardFreeze('fullname');
         $mform->setConstant('fullname', $course->fullname);
     }
     $mform->setDefault('fullname', $fullname);
     $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
     $mform->setHelpButton('shortname', array('courseshortname', get_string('shortnamecourse')), true);
     $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
     $mform->setType('shortname', PARAM_MULTILANG);
     if ($course and !has_capability('moodle/course:changeshortname', $coursecontext)) {
         $mform->hardFreeze('shortname');
         $mform->setConstant('shortname', $course->shortname);
     }
     $mform->setDefault('shortname', $shortname);
     $mform->addElement('text', 'idnumber', get_string('idnumbercourse'), 'maxlength="100"  size="10"');
     $mform->setHelpButton('idnumber', array('courseidnumber', get_string('idnumbercourse')), true);
     $mform->setType('idnumber', PARAM_RAW);
     if ($course and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
         $mform->hardFreeze('idnumber');
         $mform->setConstants('idnumber', $course->idnumber);
     }
     $mform->addElement('htmleditor', 'summary', get_string('summary'), array('rows' => '10', 'cols' => '65'));
     $mform->setHelpButton('summary', array('text2', get_string('helptext')), true);
     $mform->setType('summary', PARAM_RAW);
     $courseformats = get_list_of_plugins('course/format');
     $formcourseformats = array();
     foreach ($courseformats as $courseformat) {
         $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}", "format_{$courseformat}");
         if ($formcourseformats["{$courseformat}"] == "[[format{$courseformat}]]") {
             $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}");
         }
     }
     $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
     $mform->setHelpButton('format', array('courseformats', get_string('courseformats')), true);
     $mform->setDefault('format', $courseconfig->format);
     for ($i = 1; $i <= 52; $i++) {
         $sectionmenu[$i] = "{$i}";
     }
     $mform->addElement('select', 'numsections', get_string('numberweeks'), $sectionmenu);
     $mform->setDefault('numsections', $courseconfig->numsections);
     $mform->addElement('date_selector', 'startdate', get_string('startdate'));
     $mform->setHelpButton('startdate', array('coursestartdate', get_string('startdate')), true);
     $mform->setDefault('startdate', time() + 3600 * 24);
     $choices = array();
     $choices['0'] = get_string('hiddensectionscollapsed');
     $choices['1'] = get_string('hiddensectionsinvisible');
     $mform->addElement('select', 'hiddensections', get_string('hiddensections'), $choices);
     $mform->setHelpButton('hiddensections', array('coursehiddensections', get_string('hiddensections')), true);
     $mform->setDefault('hiddensections', $courseconfig->hiddensections);
     $options = range(0, 10);
     $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
     $mform->setHelpButton('newsitems', array('coursenewsitems', get_string('newsitemsnumber')), true);
     $mform->setDefault('newsitems', $courseconfig->newsitems);
     $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
     $mform->setHelpButton('showgrades', array('coursegrades', get_string('grades')), true);
     $mform->setDefault('showgrades', $courseconfig->showgrades);
     $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
     $mform->setHelpButton('showreports', array('coursereports', get_string('activityreport')), true);
     $mform->setDefault('showreports', $courseconfig->showreports);
     $choices = get_max_upload_sizes($CFG->maxbytes);
     $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
     $mform->setHelpButton('maxbytes', array('courseuploadsize', get_string('maximumupload')), true);
     $mform->setDefault('maxbytes', $courseconfig->maxbytes);
     if (!empty($CFG->allowcoursethemes)) {
         $themes = array();
         $themes[''] = get_string('forceno');
         $themes += get_list_of_themes();
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $meta = array();
     $meta[0] = get_string('no');
     $meta[1] = get_string('yes');
     if ($disable_meta === false) {
         $mform->addElement('select', 'metacourse', get_string('managemeta'), $meta);
         $mform->setHelpButton('metacourse', array('metacourse', get_string('metacourse')), true);
         $mform->setDefault('metacourse', $courseconfig->metacourse);
     } else {
         // no metacourse element - we do not want to change it anyway!
         $mform->addElement('static', 'nometacourse', get_string('managemeta'), (empty($course->metacourse) ? $meta[0] : $meta[1]) . " - {$disable_meta} ");
         $mform->setHelpButton('nometacourse', array('metacourse', get_string('metacourse')), true);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'enrolhdr', get_string('enrolments'));
     $choices = array();
     $modules = explode(',', $CFG->enrol_plugins_enabled);
     foreach ($modules as $module) {
         $name = get_string('enrolname', "enrol_{$module}");
         $plugin = enrolment_factory::factory($module);
         if (method_exists($plugin, 'print_entry')) {
             $choices[$name] = $module;
         }
     }
     asort($choices);
     $choices = array_flip($choices);
     $choices = array_merge(array('' => get_string('sitedefault') . ' (' . get_string('enrolname', "enrol_{$CFG->enrol}") . ')'), $choices);
     $mform->addElement('select', 'enrol', get_string('enrolmentplugins'), $choices);
     $mform->setHelpButton('enrol', array('courseenrolmentplugins', get_string('enrolmentplugins')), true);
     $mform->setDefault('enrol', $courseconfig->enrol);
     $roles = get_assignable_roles($context);
     if (!empty($course)) {
         // add current default role, so that it is selectable even when user can not assign it
         if ($current_role = $DB->get_record('role', array('id' => $course->defaultrole))) {
             $roles[$current_role->id] = strip_tags(format_string($current_role->name, true));
         }
     }
     $choices = array();
     if ($sitedefaultrole = $DB->get_record('role', array('id' => $CFG->defaultcourseroleid))) {
         $choices[0] = get_string('sitedefault') . ' (' . $sitedefaultrole->name . ')';
     } else {
         $choices[0] = get_string('sitedefault');
     }
     $choices = $choices + $roles;
     // fix for MDL-9197
     foreach ($choices as $choiceid => $choice) {
         $choices[$choiceid] = format_string($choice);
     }
     $mform->addElement('select', 'defaultrole', get_string('defaultrole', 'role'), $choices);
     $mform->setDefault('defaultrole', 0);
     $radio = array();
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('no'), 0);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('yes'), 1);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('enroldate'), 2);
     $mform->addGroup($radio, 'enrollable', get_string('enrollable'), ' ', false);
     $mform->setHelpButton('enrollable', array('courseenrollable2', get_string('enrollable')), true);
     $mform->setDefault('enrollable', $courseconfig->enrollable);
     $mform->addElement('date_selector', 'enrolstartdate', get_string('enrolstartdate'), array('optional' => true));
     $mform->setDefault('enrolstartdate', 0);
     $mform->disabledIf('enrolstartdate', 'enrollable', 'neq', 2);
     $mform->addElement('date_selector', 'enrolenddate', get_string('enrolenddate'), array('optional' => true));
     $mform->setDefault('enrolenddate', 0);
     $mform->disabledIf('enrolenddate', 'enrollable', 'neq', 2);
     $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod'), array('optional' => true, 'defaultunit' => 86400));
     $mform->setDefault('enrolperiod', $courseconfig->enrolperiod);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'expirynotifyhdr', get_string('expirynotify'));
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'expirynotify', get_string('notify'), $choices);
     $mform->setHelpButton('expirynotify', array('expirynotify', get_string('expirynotify')), true);
     $mform->setDefault('expirynotify', $courseconfig->expirynotify);
     $mform->addElement('select', 'notifystudents', get_string('expirynotifystudents'), $choices);
     $mform->setHelpButton('notifystudents', array('expirynotifystudents', get_string('expirynotifystudents')), true);
     $mform->setDefault('notifystudents', $courseconfig->notifystudents);
     $thresholdmenu = array();
     for ($i = 1; $i <= 30; $i++) {
         $seconds = $i * 86400;
         $thresholdmenu[$seconds] = get_string('numdays', '', $i);
     }
     $mform->addElement('select', 'expirythreshold', get_string('expirythreshold'), $thresholdmenu);
     $mform->setHelpButton('expirythreshold', array('expirythreshold', get_string('expirythreshold')), true);
     $mform->setDefault('expirythreshold', $courseconfig->expirythreshold);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('groups', 'group'));
     $choices = array();
     $choices[NOGROUPS] = get_string('groupsnone', 'group');
     $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
     $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
     $mform->addElement('select', 'groupmode', get_string('groupmode'), $choices);
     $mform->setHelpButton('groupmode', array('groupmode', get_string('groupmode')), true);
     $mform->setDefault('groupmode', $courseconfig->groupmode);
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'groupmodeforce', get_string('force'), $choices);
     $mform->setHelpButton('groupmodeforce', array('groupmodeforce', get_string('groupmodeforce')), true);
     $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);
     if (!empty($CFG->enablegroupings)) {
         //default groupings selector
         $options = array();
         $options[0] = get_string('none');
         $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('availability'));
     $choices = array();
     $choices['0'] = get_string('courseavailablenot');
     $choices['1'] = get_string('courseavailable');
     $mform->addElement('select', 'visible', get_string('availability'), $choices);
     $mform->setHelpButton('visible', array('courseavailability', get_string('availability')), true);
     $mform->setDefault('visible', $courseconfig->visible);
     if ($course and !has_capability('moodle/course:visibility', $coursecontext)) {
         $mform->hardFreeze('visible');
         $mform->setConstant('visible', $course->visible);
     }
     $mform->addElement('passwordunmask', 'enrolpassword', get_string('enrolmentkey'), 'size="25"');
     $mform->setHelpButton('enrolpassword', array('enrolmentkey', get_string('enrolmentkey')), true);
     $mform->setDefault('enrolpassword', '');
     $mform->setDefault('enrolpassword', $courseconfig->enrolpassword);
     $mform->setType('enrolpassword', PARAM_RAW);
     if (empty($course) or $course->password !== '' and $course->id != SITEID) {
         // do not require password in existing courses that do not have password yet - backwards compatibility ;-)
         if (!empty($CFG->enrol_manual_requirekey)) {
             $mform->addRule('enrolpassword', get_string('required'), 'required', null, 'client');
         }
     }
     $choices = array();
     $choices['0'] = get_string('guestsno');
     $choices['1'] = get_string('guestsyes');
     $choices['2'] = get_string('guestskey');
     $mform->addElement('select', 'guest', get_string('opentoguests'), $choices);
     $mform->setHelpButton('guest', array('guestaccess', get_string('opentoguests')), true);
     $mform->setDefault('guest', $courseconfig->guest);
     // If we are creating a course, its enrol method isn't yet chosen, BUT the site has a default enrol method which we can use here
     $enrol_object = $CFG;
     if (!empty($course)) {
         $enrol_object = $course;
     }
     // If the print_entry method exists and the course enrol method isn't manual (both set or inherited from site), show cost
     if (method_exists(enrolment_factory::factory($enrol_object->enrol), 'print_entry') && !($enrol_object->enrol == 'manual' || empty($enrol_object->enrol) && $CFG->enrol == 'manual')) {
         $costgroup = array();
         $currencies = get_list_of_currencies();
         $costgroup[] =& MoodleQuickForm::createElement('text', 'cost', '', 'maxlength="6" size="6"');
         $costgroup[] =& MoodleQuickForm::createElement('select', 'currency', '', $currencies);
         $mform->addGroup($costgroup, 'costgrp', get_string('cost'), '&nbsp;', false);
         //defining a rule for a form element within a group :
         $costgrprules = array();
         //set the message to null to tell Moodle to use a default message
         //available for most rules, fetched from language pack (err_{rulename}).
         $costgrprules['cost'][] = array(null, 'numeric', null, 'client');
         $mform->addGroupRule('costgrp', $costgrprules);
         $mform->setHelpButton('costgrp', array('cost', get_string('cost')), true);
         $mform->setDefault('cost', '');
         $mform->setDefault('currency', empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('language'));
     $languages = array();
     $languages[''] = get_string('forceno');
     $languages += get_list_of_languages();
     $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
     $mform->setDefault('lang', $courseconfig->lang);
     //--------------------------------------------------------------------------------
     require_once $CFG->libdir . '/completionlib.php';
     if (completion_info::is_enabled_for_site()) {
         $mform->addElement('header', '', get_string('progress', 'completion'));
         $mform->addElement('select', 'enablecompletion', get_string('completion', 'completion'), array(0 => get_string('completiondisabled', 'completion'), 1 => get_string('completionenabled', 'completion')));
         $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);
     } else {
         $mform->addElement('hidden', 'enablecompletion');
         $mform->setDefault('enablecompletion', 0);
     }
     //--------------------------------------------------------------------------------
     if (has_capability('moodle/site:config', $systemcontext) && (!empty($course->requested) && $CFG->restrictmodulesfor == 'requested' || $CFG->restrictmodulesfor == 'all')) {
         $mform->addElement('header', '', get_string('restrictmodules'));
         $options = array();
         $options['0'] = get_string('no');
         $options['1'] = get_string('yes');
         $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
         $mods = array(0 => get_string('allownone'));
         $mods += $DB->get_records_menu('modules', array(), 'name', 'id, name');
         $mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple' => 'multiple', 'size' => '10'));
         $mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0);
     } else {
         $mform->addElement('hidden', 'restrictmodules', null);
     }
     if ($CFG->restrictmodulesfor == 'all') {
         $mform->setDefault('allowedmods', explode(',', $CFG->defaultallowedmodules));
         if (!empty($CFG->restrictbydefault)) {
             $mform->setDefault('restrictmodules', 1);
         }
     }
     $mform->setType('restrictmodules', PARAM_INT);
     /// customizable role names in this course
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'rolerenaming', get_string('rolerenaming'));
     $mform->setHelpButton('rolerenaming', array('rolerenaming', get_string('rolerenaming')), true);
     if ($roles = get_all_roles()) {
         if ($coursecontext) {
             $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS_RAW);
         }
         $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE);
         foreach ($roles as $role) {
             $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->name));
             if (isset($role->localname)) {
                 $mform->setDefault('role_' . $role->id, $role->localname);
             }
             $mform->setType('role_' . $role->id, PARAM_TEXT);
             if (!in_array($role->id, $assignableroles)) {
                 $mform->setAdvanced('role_' . $role->id);
             }
         }
     }
     //--------------------------------------------------------------------------------
     $this->add_action_buttons();
     //--------------------------------------------------------------------------------
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
 }
Пример #28
0
    /**
     * Form definition.
     */
    function definition() {
        global $CFG, $PAGE,$USER,$DB;

        $mform    = $this->_form;
        $PAGE->requires->yui_module('moodle-course-formatchooser', 'M.course.init_formatchooser',
                array(array('formid' => $mform->getAttribute('id'))));

        $course        = $this->_customdata['course']; // this contains the data of this form
        //print_object($course);
        $category      = $this->_customdata['category'];
        $editoroptions = $this->_customdata['editoroptions'];
        $returnto = $this->_customdata['returnto'];

        $systemcontext   = context_system::instance();
        $categorycontext = context_coursecat::instance($category->id);

        if (!empty($course->id)) {
            $coursecontext = context_course::instance($course->id);
            $context = $coursecontext;
        } else {
            $coursecontext = null;
            $context = $categorycontext;
        }

        $courseconfig = get_config('moodlecourse');

        $this->course  = $course;
        $this->context = $context;

        // Form definition with new course defaults.
        $mform->addElement('header','general', get_string('general', 'form'));

        $mform->addElement('hidden', 'returnto', null);
        $mform->setType('returnto', PARAM_ALPHANUM);
        $mform->setConstant('returnto', $returnto);
         /*
         * EA_NK23-02-2015
         * Added cost center field
         */
       
        $is_manager = $DB->record_exists_sql("SELECT ra.userid
                                                FROM {role_assignments} as ra
                                                JOIN {role} as r ON ra.roleid=r.id
                                               WHERE r.archetype='manager' AND ra.userid={$USER->id}");
        if(is_siteadmin()) {
        /*==================strated by raju.t for admin created courses goes to HR department on 9-11-2015=============*/    
           $admincostcenters=user_wise_department();
        //print_object($admincostcenters);
            $mform->addElement('select', 'costcenter', get_string('pluginname', 'local_costcenter'), $admincostcenters);        
       
      /*==================Ended by raju.t for admin created courses goes to HR department on 9-11-2015=============*/    
        }elseif(!is_siteadmin()){
           $admincostcenters=user_wise_department();
          
           $mform->addElement('select', 'costcenter', get_string('pluginname', 'local_costcenter'), $admincostcenters);   
        
        }
            //$costcenter = $DB->get_records_sql_menu("SELECT cc.id,cc.fullname FROM mdl_local_userdata ud JOIN mdl_local_costcenter cc ON ud.costcenterid=cc.id WHERE ud.userid={$USER->id}");
            //$mform->addElement('hidden','costcenter');
            //$mform->setDefault('costcenter',$costcenter->id);
            //$mform->addElement('static', 'costcenterid', get_string('pluginname', 'local_costcenter'), $costcenter->fullname);
        
        $mform->setType('costcenter', PARAM_RAW);
        
        /* EA_NK23-02-2015 Customization ends here */
        $mform->addElement('text','fullname', get_string('fullnamecourse'),'maxlength="254" size="50"');
        $mform->addHelpButton('fullname', 'fullnamecourse');
        $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
        $mform->setType('fullname', PARAM_TEXT);
        if (!empty($course->id) and !has_capability('moodle/course:changefullname', $coursecontext)) {
            $mform->hardFreeze('fullname');
            $mform->setConstant('fullname', $course->fullname);
        }

        $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
        $mform->addHelpButton('shortname', 'shortnamecourse');
        $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
        $mform->setType('shortname', PARAM_TEXT);
        if (!empty($course->id) and !has_capability('moodle/course:changeshortname', $coursecontext)) {
            $mform->hardFreeze('shortname');
            $mform->setConstant('shortname', $course->shortname);
        }

        // Verify permissions to change course category or keep current.
        if (empty($course->id)) {
            if (has_capability('moodle/course:create', $categorycontext)) {
                $displaylist = coursecat::make_categories_list('moodle/course:create');
                
            /*======================Started By Raju.T for Disaply Course Categories based on training manager deparment on 9-11-2015============*/   
                if(is_siteadmin()){
                    $admincoursecategory=department_category_course();
                    $mform->addElement('select', 'category', get_string('coursecategory'), $admincoursecategory);
            
             /*==================Ended by raju.t for admin created courses goes to HR department on 9-11-2015=============*/        
                }else{
    
            /*======================Ended By Raju.T for Disaply Course Categories based on training manager deparment on 9-11-2015============*/   
               $admincoursecategory=department_category_course();
                $mform->addElement('select', 'category', get_string('coursecategory'), $admincoursecategory);
            
            
                 $userdepartment_exist=$DB->record_exists('local_userdata',array('userid'=>$USER->id));
                    if($userdepartment_exist==1){
                       $userdepartment=$DB->get_record('local_userdata',array('userid'=>$USER->id));
                       if($userdepartment->lms_category=="AST" || $userdepartment->lms_category=="AST-EXT"){
                            $trainer_type_options=array(null=>'----Select to----',T=>'Trainer',SM=>'Sales Manager');
                            $mform->addElement('select', 'assignedto', get_string('assigne_to'), $trainer_type_options);
                            //$mform->setConstant('category', $category->id);
                            //$mform->setDefault('assignedto', $course->assignedto);
                       }
                    }
            /*==================strated by raju.t for admin created courses goes to HR department on 9-11-2015=============*/    
                
                }
                $mform->addHelpButton('category', 'coursecategory');
                $mform->setDefault('category', $category->id);
                
                    $mform->addElement('text','duration',get_string('course_duration'),'maxlength="100"  size="10"');
                   if(!empty($course->assignedto)){
                      $mform->setDefault('duration', $course->duration);
                   }else{
                      $mform->setDefault('duration','0');
                   }
                  
                    $mform->setType('duration', PARAM_RAW);
                    $mform->addRule('duration', get_string('possitiveonly'), 'regex', '#^(0|[1-9][0-9]*)$#');
            } else {
                $mform->addElement('hidden', 'category', null);
                $mform->setType('category', PARAM_INT);
                $mform->setConstant('category', $category->id);
            }
        } else {
            if (has_capability('moodle/course:changecategory', $coursecontext)) {
                 $admincoursecategory=department_category_course();
                $mform->addElement('select', 'category', get_string('coursecategory'), $admincoursecategory);
            } else {
                //keep current
                $mform->addElement('hidden', 'category', null);
                $mform->setType('category', PARAM_INT);
                $mform->setConstant('category', $course->category);
            }
                    $userdepartment_exist=$DB->record_exists('local_userdata',array('userid'=>$USER->id));
                    if($userdepartment_exist==1){
                       $userdepartment=$DB->get_record('local_userdata',array('userid'=>$USER->id));
                       if($userdepartment->lms_category=="AST" || $userdepartment->lms_category=="AST-EXT"){
                            $trainer_type_options=array(null=>'----Select to----',T=>'Trainer',SM=>'Sales Manager');
                            $mform->addElement('select', 'assignedto', get_string('assigne_to'), $trainer_type_options);
                            //$mform->setConstant('category', $category->id);
                            //$mform->setDefault('assignedto', $course->assignedto);
                       }
                    }
                    /*==================strated by raju.t for admin created courses goes to HR department on 9-11-2015=============*/    
                    $mform->addElement('text','duration',get_string('course_duration'),'maxlength="100"  size="10"');
                   if(!empty($course->assignedto)){
                      $mform->setDefault('duration', $course->duration);
                   }else{
                      $mform->setDefault('duration','0');
                   }
                  
                    $mform->setType('duration', PARAM_RAW);
                    $mform->addRule('duration', get_string('possitiveonly'), 'regex', '#^(0|[1-9][0-9]*)$#');
        }

        $choices = array();
        $choices['0'] = get_string('hide');
        $choices['1'] = get_string('show');
        $mform->addElement('select', 'visible', get_string('visible'), $choices);
        $mform->addHelpButton('visible', 'visible');
        $mform->setDefault('visible', $courseconfig->visible);
        if (!empty($course->id)) {
            if (!has_capability('moodle/course:visibility', $coursecontext)) {
                $mform->hardFreeze('visible');
                $mform->setConstant('visible', $course->visible);
            }
        } else {
            if (!guess_if_creator_will_have_course_capability('moodle/course:visibility', $categorycontext)) {
                $mform->hardFreeze('visible');
                $mform->setConstant('visible', $courseconfig->visible);
            }
        }

        $mform->addElement('date_selector', 'startdate', get_string('startdate'));
        $mform->addHelpButton('startdate', 'startdate');
        $mform->setDefault('startdate', time() + 3600 * 24);

        $mform->addElement('text','idnumber', get_string('idnumbercourse'),'maxlength="100"  size="10"');
        $mform->addHelpButton('idnumber', 'idnumbercourse');
        $mform->setType('idnumber', PARAM_RAW);
        if (!empty($course->id) and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
            $mform->hardFreeze('idnumber');
            $mform->setConstants('idnumber', $course->idnumber);
        }

        // Description.
        $mform->addElement('header', 'descriptionhdr', get_string('description'));
        $mform->setExpanded('descriptionhdr');

        $mform->addElement('editor','summary_editor', get_string('coursesummary'), null, $editoroptions);
        $mform->addHelpButton('summary_editor', 'coursesummary');
        $mform->setType('summary_editor', PARAM_RAW);
        $summaryfields = 'summary_editor';

        if ($overviewfilesoptions = course_overviewfiles_options($course)) {
            $mform->addElement('filemanager', 'overviewfiles_filemanager', get_string('courseoverviewfiles'), null, $overviewfilesoptions);
            $mform->addHelpButton('overviewfiles_filemanager', 'courseoverviewfiles');
            $summaryfields .= ',overviewfiles_filemanager';
        }

        if (!empty($course->id) and !has_capability('moodle/course:changesummary', $coursecontext)) {
            // Remove the description header it does not contain anything any more.
            $mform->removeElement('descriptionhdr');
            $mform->hardFreeze($summaryfields);
        }

        // Course format.
        $mform->addElement('header', 'courseformathdr', get_string('type_format', 'plugin'));

        $courseformats = get_sorted_course_formats(true);
        $formcourseformats = array();
        foreach ($courseformats as $courseformat) {
            $formcourseformats[$courseformat] = get_string('pluginname', "format_$courseformat");
        }
        if (isset($course->format)) {
            $course->format = course_get_format($course)->get_format(); // replace with default if not found
            if (!in_array($course->format, $courseformats)) {
                // this format is disabled. Still display it in the dropdown
                $formcourseformats[$course->format] = get_string('withdisablednote', 'moodle',
                        get_string('pluginname', 'format_'.$course->format));
            }
        }

        $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
        $mform->addHelpButton('format', 'format');
        $mform->setDefault('format', $courseconfig->format);

        // Button to update format-specific options on format change (will be hidden by JavaScript).
        $mform->registerNoSubmitButton('updatecourseformat');
        $mform->addElement('submit', 'updatecourseformat', get_string('courseformatudpate'));

        // Just a placeholder for the course format options.
        $mform->addElement('hidden', 'addcourseformatoptionshere');
        $mform->setType('addcourseformatoptionshere', PARAM_BOOL);

        // Appearance.
        $mform->addElement('header', 'appearancehdr', get_string('appearance'));

        if (!empty($CFG->allowcoursethemes)) {
            $themeobjects = get_list_of_themes();
            $themes=array();
            $themes[''] = get_string('forceno');
            foreach ($themeobjects as $key=>$theme) {
                if (empty($theme->hidefromselector)) {
                    $themes[$key] = get_string('pluginname', 'theme_'.$theme->name);
                }
            }
            $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
        }

        $languages=array();
        $languages[''] = get_string('forceno');
        $languages += get_string_manager()->get_list_of_translations();
        $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
        $mform->setDefault('lang', $courseconfig->lang);

        // Multi-Calendar Support - see MDL-18375.
        $calendartypes = \core_calendar\type_factory::get_list_of_calendar_types();
        // We do not want to show this option unless there is more than one calendar type to display.
        if (count($calendartypes) > 1) {
            $calendars = array();
            $calendars[''] = get_string('forceno');
            $calendars += $calendartypes;
            $mform->addElement('select', 'calendartype', get_string('forcecalendartype', 'calendar'), $calendars);
        }

        $options = range(0, 10);
        $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
        $mform->addHelpButton('newsitems', 'newsitemsnumber');
        $mform->setDefault('newsitems', $courseconfig->newsitems);

        $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
        $mform->addHelpButton('showgrades', 'showgrades');
        $mform->setDefault('showgrades', $courseconfig->showgrades);

        $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
        $mform->addHelpButton('showreports', 'showreports');
        $mform->setDefault('showreports', $courseconfig->showreports);

        // Files and uploads.
        $mform->addElement('header', 'filehdr', get_string('filesanduploads'));

        if (!empty($course->legacyfiles) or !empty($CFG->legacyfilesinnewcourses)) {
            if (empty($course->legacyfiles)) {
                //0 or missing means no legacy files ever used in this course - new course or nobody turned on legacy files yet
                $choices = array('0'=>get_string('no'), '2'=>get_string('yes'));
            } else {
                $choices = array('1'=>get_string('no'), '2'=>get_string('yes'));
            }
            $mform->addElement('select', 'legacyfiles', get_string('courselegacyfiles'), $choices);
            $mform->addHelpButton('legacyfiles', 'courselegacyfiles');
            if (!isset($courseconfig->legacyfiles)) {
                // in case this was not initialised properly due to switching of $CFG->legacyfilesinnewcourses
                $courseconfig->legacyfiles = 0;
            }
            $mform->setDefault('legacyfiles', $courseconfig->legacyfiles);
        }

        // Handle non-existing $course->maxbytes on course creation.
        $coursemaxbytes = !isset($course->maxbytes) ? null : $course->maxbytes;

        // Let's prepare the maxbytes popup.
        $choices = get_max_upload_sizes($CFG->maxbytes, 0, 0, $coursemaxbytes);
        $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
        $mform->addHelpButton('maxbytes', 'maximumupload');
        $mform->setDefault('maxbytes', $courseconfig->maxbytes);

        // Completion tracking.
        if (completion_info::is_enabled_for_site()) {
            $mform->addElement('header', 'completionhdr', get_string('completion', 'completion'));
            $mform->addElement('selectyesno', 'enablecompletion', get_string('enablecompletion', 'completion'));
            $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);
            $mform->addHelpButton('enablecompletion', 'enablecompletion', 'completion');
        } else {
            $mform->addElement('hidden', 'enablecompletion');
            $mform->setType('enablecompletion', PARAM_INT);
            $mform->setDefault('enablecompletion', 0);
        }

        enrol_course_edit_form($mform, $course, $context);

        $mform->addElement('header','groups', get_string('groupsettingsheader', 'group'));

        $choices = array();
        $choices[NOGROUPS] = get_string('groupsnone', 'group');
        $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
        $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
        $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $choices);
        $mform->addHelpButton('groupmode', 'groupmode', 'group');
        $mform->setDefault('groupmode', $courseconfig->groupmode);

        $mform->addElement('selectyesno', 'groupmodeforce', get_string('groupmodeforce', 'group'));
        $mform->addHelpButton('groupmodeforce', 'groupmodeforce', 'group');
        $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);

        //default groupings selector
        $options = array();
        $options[0] = get_string('none');
        $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);

        // Customizable role names in this course.
        $mform->addElement('header','rolerenaming', get_string('rolerenaming'));
        $mform->addHelpButton('rolerenaming', 'rolerenaming');

        if ($roles = get_all_roles()) {
            $roles = role_fix_names($roles, null, ROLENAME_ORIGINAL);
            $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE);
            foreach ($roles as $role) {
                $mform->addElement('text', 'role_'.$role->id, get_string('yourwordforx', '', $role->localname));
                $mform->setType('role_'.$role->id, PARAM_TEXT);
            }
        }

        $this->add_action_buttons();

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

        // Finally set the current form data
        $this->set_data($course);
    }
 function definition()
 {
     global $CFG, $USER;
     $mform =& $this->_form;
     $mform->updateAttributes(array('class' => ''));
     $mform->addElement('hidden', 'items');
     $mform->addElement('hidden', 'action');
     $mform->addElement('hidden', 'courseid');
     $mform->addElement('hidden', 'viewid');
     $mform->addElement('text', 'name', get_string("title", "block_exabis_eportfolio"), 'maxlength="255" size="60"');
     $mform->setType('name', PARAM_TEXT);
     $mform->addRule('name', get_string("titlenotemtpy", "block_exabis_eportfolio"), 'required', null, 'client');
     $mform->addElement('textarea', 'description', get_string("title", "block_exabis_eportfolio"), 'maxlength="65000" size="60"');
     $mform->setType('description', PARAM_TEXT);
     if (!empty($CFG->allowuserthemes)) {
         // enable Themes per porfolio (nadavkav)
         $themes = array();
         $themes[''] = get_string('forceno');
         $themes += get_list_of_themes();
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $mform->addElement('hidden', 'blocks');
     $mform->setType('blocks', PARAM_RAW);
     $mform->addElement('checkbox', 'externaccess');
     $mform->setType('externaccess', PARAM_INT);
     $mform->addElement('checkbox', 'internaccess');
     $mform->setType('internaccess', PARAM_INT);
     $mform->addElement('checkbox', 'externcomment');
     $mform->setType('externcomment', PARAM_INT);
     $mform->addElement('text', 'shareall');
     $mform->setType('shareall', PARAM_INT);
     if ($this->_customdata['view']) {
         $this->add_action_buttons(false, get_string('savechanges'));
     } else {
         $this->add_action_buttons(false, get_string('add'));
     }
 }
Пример #30
0
 function definition()
 {
     global $USER, $CFG;
     $mform =& $this->_form;
     $course = $this->_customdata['course'];
     $category = $this->_customdata['category'];
     $systemcontext = get_context_instance(CONTEXT_SYSTEM);
     $categorycontext = get_context_instance(CONTEXT_COURSECAT, $category->id);
     $disable_meta = false;
     // basic meta course state protection; server-side security checks not needed
     if (!empty($course)) {
         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
         $context = $coursecontext;
         if (course_in_meta($course)) {
             $disable_meta = get_string('metaalreadyinmeta');
         } else {
             if ($course->metacourse) {
                 if (count_records('course_meta', 'parent_course', $course->id) > 0) {
                     $disable_meta = get_string('metaalreadyhascourses');
                 }
             } else {
                 $managers = count(get_users_by_capability($coursecontext, 'moodle/course:managemetacourse'));
                 $participants = count(get_users_by_capability($coursecontext, 'moodle/course:view'));
                 if ($participants > $managers) {
                     $disable_meta = get_string('metaalreadyhasenrolments');
                 }
             }
         }
     } else {
         $coursecontext = null;
         $context = $categorycontext;
     }
     /// form definition with new course defaults
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     //must have create course capability in both categories in order to move course
     if (has_capability('moodle/course:create', $categorycontext)) {
         $displaylist = array();
         $parentlist = array();
         make_categories_list($displaylist, $parentlist);
         foreach ($displaylist as $key => $val) {
             if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $key))) {
                 unset($displaylist[$key]);
             }
         }
         $mform->addElement('select', 'category', get_string('category'), $displaylist);
     } else {
         $mform->addElement('hidden', 'category', null);
     }
     $mform->setHelpButton('category', array('coursecategory', get_string('category')));
     $mform->setDefault('category', $category->id);
     $mform->setType('category', PARAM_INT);
     $mform->addElement('text', 'fullname', get_string('fullname'), 'maxlength="254" size="50"');
     $mform->setHelpButton('fullname', array('coursefullname', get_string('fullname')), true);
     $mform->setDefault('fullname', get_string('defaultcoursefullname'));
     $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
     $mform->setType('fullname', PARAM_MULTILANG);
     $mform->addElement('text', 'shortname', get_string('shortname'), 'maxlength="100" size="20"');
     $mform->setHelpButton('shortname', array('courseshortname', get_string('shortname')), true);
     $mform->setDefault('shortname', get_string('defaultcourseshortname'));
     $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
     $mform->setType('shortname', PARAM_MULTILANG);
     $mform->addElement('text', 'idnumber', get_string('idnumbercourse'), 'maxlength="100"  size="10"');
     $mform->setHelpButton('idnumber', array('courseidnumber', get_string('idnumbercourse')), true);
     $mform->setType('idnumber', PARAM_RAW);
     $mform->addElement('htmleditor', 'summary', get_string('summary'), array('rows' => '10', 'cols' => '65'));
     $mform->setHelpButton('summary', array('text', get_string('helptext')), true);
     $mform->setDefault('summary', get_string('defaultcoursesummary'));
     $mform->addRule('summary', get_string('missingsummary'), 'required', null, 'client');
     $mform->setType('summary', PARAM_RAW);
     $courseformats = get_list_of_plugins('course/format');
     $formcourseformats = array();
     foreach ($courseformats as $courseformat) {
         $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}", "format_{$courseformat}");
         if ($formcourseformats["{$courseformat}"] == "[[format{$courseformat}]]") {
             $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}");
         }
     }
     $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
     $mform->setHelpButton('format', array('courseformats', get_string('courseformats')), true);
     $mform->setDefault('format', 'weeks');
     for ($i = 1; $i <= 52; $i++) {
         $sectionmenu[$i] = "{$i}";
     }
     $mform->addElement('select', 'numsections', get_string('numberweeks'), $sectionmenu);
     $mform->setDefault('numsections', 10);
     $mform->addElement('date_selector', 'startdate', get_string('startdate'));
     $mform->setHelpButton('startdate', array('coursestartdate', get_string('startdate')), true);
     $mform->setDefault('startdate', time() + 3600 * 24);
     $choices = array();
     $choices['0'] = get_string('hiddensectionscollapsed');
     $choices['1'] = get_string('hiddensectionsinvisible');
     $mform->addElement('select', 'hiddensections', get_string('hiddensections'), $choices);
     $mform->setHelpButton('hiddensections', array('coursehiddensections', get_string('hiddensections')), true);
     $mform->setDefault('hiddensections', 0);
     $options = range(0, 10);
     $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
     $mform->setHelpButton('newsitems', array('coursenewsitems', get_string('newsitemsnumber')), true);
     $mform->setDefault('newsitems', 5);
     $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
     $mform->setHelpButton('showgrades', array('coursegrades', get_string('grades')), true);
     $mform->setDefault('showgrades', 1);
     $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
     $mform->setHelpButton('showreports', array('coursereports', get_string('activityreport')), true);
     $mform->setDefault('showreports', 0);
     $choices = get_max_upload_sizes($CFG->maxbytes);
     $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
     $mform->setHelpButton('maxbytes', array('courseuploadsize', get_string('maximumupload')), true);
     if (!empty($CFG->allowcoursethemes)) {
         $themes = array();
         $themes[''] = get_string('forceno');
         $themes += get_list_of_themes();
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $meta = array();
     $meta[0] = get_string('no');
     $meta[1] = get_string('yes');
     if ($disable_meta === false) {
         $mform->addElement('select', 'metacourse', get_string('managemeta'), $meta);
         $mform->setHelpButton('metacourse', array('metacourse', get_string('metacourse')), true);
         $mform->setDefault('metacourse', 0);
     } else {
         // no metacourse element - we do not want to change it anyway!
         $mform->addElement('static', 'nometacourse', get_string('managemeta'), (empty($course->metacourse) ? $meta[0] : $meta[1]) . " - {$disable_meta} ");
         $mform->setHelpButton('nometacourse', array('metacourse', get_string('metacourse')), true);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'enrolhdr', get_string('enrolments'));
     $choices = array();
     $modules = explode(',', $CFG->enrol_plugins_enabled);
     foreach ($modules as $module) {
         $name = get_string('enrolname', "enrol_{$module}");
         $plugin = enrolment_factory::factory($module);
         if (method_exists($plugin, 'print_entry')) {
             $choices[$name] = $module;
         }
     }
     asort($choices);
     $choices = array_flip($choices);
     $choices = array_merge(array('' => get_string('sitedefault') . ' (' . get_string('enrolname', "enrol_{$CFG->enrol}") . ')'), $choices);
     $mform->addElement('select', 'enrol', get_string('enrolmentplugins'), $choices);
     $mform->setHelpButton('enrol', array('courseenrolmentplugins', get_string('enrolmentplugins')), true);
     $roles = get_assignable_roles($context);
     if (!empty($course)) {
         // add current default role, so that it is selectable even when user can not assign it
         if ($current_role = get_record('role', 'id', $course->defaultrole)) {
             $roles[$current_role->id] = strip_tags(format_string($current_role->name, true));
         }
     }
     $choices = array();
     if ($sitedefaultrole = get_record('role', 'id', $CFG->defaultcourseroleid)) {
         $choices[0] = get_string('sitedefault') . ' (' . $sitedefaultrole->name . ')';
     } else {
         $choices[0] = get_string('sitedefault');
     }
     $choices = $choices + $roles;
     // fix for MDL-9197
     foreach ($choices as $choiceid => $choice) {
         $choices[$choiceid] = format_string($choice);
     }
     $mform->addElement('select', 'defaultrole', get_string('defaultrole', 'role'), $choices);
     $mform->setDefault('defaultrole', 0);
     $radio = array();
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('no'), 0);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('yes'), 1);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('enroldate'), 2);
     $mform->addGroup($radio, 'enrollable', get_string('enrollable'), ' ', false);
     $mform->setHelpButton('enrollable', array('courseenrollable2', get_string('enrollable')), true);
     $mform->setDefault('enrollable', 1);
     $enroldatestartgrp = array();
     $enroldatestartgrp[] =& MoodleQuickForm::createElement('date_selector', 'enrolstartdate');
     $enroldatestartgrp[] =& MoodleQuickForm::createElement('checkbox', 'enrolstartdisabled', null, get_string('disable'));
     $mform->addGroup($enroldatestartgrp, 'enrolstartdategrp', get_string('enrolstartdate'), ' ', false);
     $mform->setDefault('enrolstartdate', 0);
     $mform->setDefault('enrolstartdisabled', 1);
     $mform->disabledIf('enrolstartdategrp', 'enrolstartdisabled', 'checked');
     $enroldateendgrp = array();
     $enroldateendgrp[] =& MoodleQuickForm::createElement('date_selector', 'enrolenddate');
     $enroldateendgrp[] =& MoodleQuickForm::createElement('checkbox', 'enrolenddisabled', null, get_string('disable'));
     $mform->addGroup($enroldateendgrp, 'enroldateendgrp', get_string('enrolenddate'), ' ', false);
     $mform->setDefault('enrolenddate', 0);
     $mform->setDefault('enrolenddisabled', 1);
     $mform->disabledIf('enroldateendgrp', 'enrolenddisabled', 'checked');
     $periodmenu = array();
     $periodmenu[0] = get_string('unlimited');
     for ($i = 1; $i <= 365; $i++) {
         $seconds = $i * 86400;
         $periodmenu[$seconds] = get_string('numdays', '', $i);
     }
     $mform->addElement('select', 'enrolperiod', get_string('enrolperiod'), $periodmenu);
     $mform->setDefault('enrolperiod', 0);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'expirynotifyhdr', get_string('expirynotify'));
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'expirynotify', get_string('notify'), $choices);
     $mform->setHelpButton('expirynotify', array('expirynotify', get_string('expirynotify')), true);
     $mform->setDefault('expirynotify', 0);
     $mform->addElement('select', 'notifystudents', get_string('expirynotifystudents'), $choices);
     $mform->setHelpButton('notifystudents', array('expirynotifystudents', get_string('expirynotifystudents')), true);
     $mform->setDefault('notifystudents', 0);
     $thresholdmenu = array();
     for ($i = 1; $i <= 30; $i++) {
         $seconds = $i * 86400;
         $thresholdmenu[$seconds] = get_string('numdays', '', $i);
     }
     $mform->addElement('select', 'expirythreshold', get_string('expirythreshold'), $thresholdmenu);
     $mform->setHelpButton('expirythreshold', array('expirythreshold', get_string('expirythreshold')), true);
     $mform->setDefault('expirythreshold', 10 * 86400);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('groups', 'group'));
     $choices = array();
     $choices[NOGROUPS] = get_string('no');
     $choices[SEPARATEGROUPS] = get_string('separate');
     $choices[VISIBLEGROUPS] = get_string('visible');
     $mform->addElement('select', 'groupmode', get_string('groupmode'), $choices);
     $mform->setHelpButton('groupmode', array('groupmode', get_string('groupmode')), true);
     $mform->setDefault('groupmode', 0);
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'groupmodeforce', get_string('force'), $choices);
     $mform->setHelpButton('groupmodeforce', array('groupmodeforce', get_string('groupmodeforce')), true);
     $mform->setDefault('groupmodeforce', 0);
     if (!empty($CFG->enablegroupings)) {
         //default groupings selector
         $options = array();
         $options[0] = get_string('none');
         $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('availability'));
     $choices = array();
     $choices['0'] = get_string('courseavailablenot');
     $choices['1'] = get_string('courseavailable');
     $mform->addElement('select', 'visible', get_string('availability'), $choices);
     $mform->setHelpButton('visible', array('courseavailability', get_string('availability')), true);
     $mform->setDefault('visible', 1);
     $mform->addElement('passwordunmask', 'enrolpassword', get_string('enrolmentkey'), 'size="25"');
     $mform->setHelpButton('enrolpassword', array('enrolmentkey', get_string('enrolmentkey')), true);
     $mform->setDefault('enrolpassword', '');
     $mform->setType('enrolpassword', PARAM_RAW);
     $choices = array();
     $choices['0'] = get_string('guestsno');
     $choices['1'] = get_string('guestsyes');
     $choices['2'] = get_string('guestskey');
     $mform->addElement('select', 'guest', get_string('opentoguests'), $choices);
     $mform->setHelpButton('guest', array('guestaccess', get_string('opentoguests')), true);
     $mform->setDefault('guest', 0);
     // If we are creating a course, its enrol method isn't yet chosen, BUT the site has a default enrol method which we can use here
     $enrol_object = $CFG;
     if (!empty($course)) {
         $enrol_object = $course;
     }
     if (method_exists(enrolment_factory::factory($enrol_object->enrol), 'print_entry') && $enrol_object->enrol != 'manual') {
         $costgroup = array();
         $currencies = get_list_of_currencies();
         $costgroup[] =& MoodleQuickForm::createElement('text', 'cost', '', 'maxlength="6" size="6"');
         $costgroup[] =& MoodleQuickForm::createElement('select', 'currency', '', $currencies);
         $mform->addGroup($costgroup, 'costgrp', get_string('cost'), '&nbsp;', false);
         //defining a rule for a form element within a group :
         $costgrprules = array();
         //set the message to null to tell Moodle to use a default message
         //available for most rules, fetched from language pack (err_{rulename}).
         $costgrprules['cost'][] = array(null, 'numeric', null, 'client');
         $mform->addGroupRule('costgrp', $costgrprules);
         $mform->setHelpButton('costgrp', array('cost', get_string('cost')), true);
         $mform->setDefault('cost', '');
         $mform->setDefault('currency', empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('language'));
     $languages = array();
     $languages[''] = get_string('forceno');
     $languages += get_list_of_languages();
     $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
     //--------------------------------------------------------------------------------
     if (has_capability('moodle/site:config', $systemcontext) && (!empty($course->requested) && $CFG->restrictmodulesfor == 'requested' || $CFG->restrictmodulesfor == 'all')) {
         $mform->addElement('header', '', get_string('restrictmodules'));
         $options = array();
         $options['0'] = get_string('no');
         $options['1'] = get_string('yes');
         $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
         $mods = array(0 => get_string('allownone'));
         $mods += get_records_menu('modules', '', '', '', 'id, name');
         $mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple' => 'multiple', 'size' => '10'));
         $mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0);
     } else {
         $mform->addElement('hidden', 'restrictmodules', null);
     }
     if ($CFG->restrictmodulesfor == 'all') {
         $mform->setDefault('allowedmods', explode(',', $CFG->defaultallowedmodules));
         if (!empty($CFG->restrictbydefault)) {
             $mform->setDefault('restrictmodules', 1);
         }
     }
     $mform->setType('restrictmodules', PARAM_INT);
     /// customizable role names in this course
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('roles'));
     if ($roles = get_records('role')) {
         foreach ($roles as $role) {
             $mform->addElement('text', 'role_' . $role->id, $role->name);
             if ($coursecontext) {
                 if ($rolename = get_record('role_names', 'roleid', $role->id, 'contextid', $coursecontext->id)) {
                     $mform->setDefault('role_' . $role->id, $rolename->text);
                 }
             }
         }
     }
     //--------------------------------------------------------------------------------
     $this->add_action_buttons();
     //--------------------------------------------------------------------------------
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
     // fill in default teacher and student names to keep backwards compatibility for a while
     $mform->addElement('hidden', 'teacher', get_string('defaultcourseteacher'));
     $mform->addElement('hidden', 'teachers', get_string('defaultcourseteachers'));
     $mform->addElement('hidden', 'student', get_string('defaultcoursestudent'));
     $mform->addElement('hidden', 'students', get_string('defaultcoursestudents'));
 }