Ejemplo n.º 1
0
 function definition()
 {
     global $CFG;
     $mform =& $this->_form;
     $strrequired = get_string('required');
     //-------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     $mform->addElement('text', 'name', get_string('name'), array('size' => '64'));
     $mform->setType('name', PARAM_TEXT);
     $mform->addRule('name', null, 'required', null, 'client');
     if (!($options = get_records_menu("survey", "template", 0, "name", "id, name"))) {
         error('No survey templates found!');
     }
     foreach ($options as $id => $name) {
         $options[$id] = get_string($name, "survey");
     }
     $options = array('' => get_string('choose') . '...') + $options;
     $mform->addElement('select', 'template', get_string("surveytype", "survey"), $options);
     $mform->addRule('template', $strrequired, 'required', null, 'client');
     $mform->setHelpButton('template', array('surveys', get_string('helpsurveys', 'survey')));
     $mform->addElement('textarea', 'intro', get_string('customintro', 'survey'), 'wrap="virtual" rows="20" cols="75"');
     $mform->setType('intro', PARAM_RAW);
     $features = new stdClass();
     $features->groups = true;
     $features->groupings = true;
     $features->groupmembersonly = true;
     $this->standard_coursemodule_elements($features);
     //-------------------------------------------------------------------------------
     // buttons
     $this->add_action_buttons();
 }
Ejemplo n.º 2
0
function xmldb_ezproxy_upgrade($oldversion = 0)
{
    global $CFG, $THEME, $db;
    $result = true;
    /// And upgrade begins here. For each one, you'll need one
    /// block of code similar to the next one. Please, delete
    /// this comment lines once this file start handling proper
    /// upgrade code.
    if ($result && $oldversion < 2009042403) {
        /// Rebuild the course cache of every course which uses one of these modules in it to get
        /// the new link.
        if ($courseids = get_records_menu('ezproxy', '', '', 'course ASC', 'id, course')) {
            /// Just get the unique course ID values.
            $courseids = array_unique(array_values($courseids));
            if (!empty($courseids)) {
                require_once $CFG->dirroot . '/course/lib.php';
                foreach ($courseids as $courseid) {
                    rebuild_course_cache($courseid);
                    // Does not return a bool
                }
            }
        }
    }
    if ($result && $oldversion < 2009042404) {
        $table = new XMLDBTable('ezproxy');
        $field = new XMLDBField('serverurl');
        $field->setAttributes(XMLDB_TYPE_TEXT, 'big', null, null, null, null, null, '', 'name');
        $result = change_field_type($table, $field);
    }
    return $result;
}
Ejemplo n.º 3
0
 function data_preprocessing(&$default_values)
 {
     if (!empty($this->_instance) && ($options = get_records_menu('choice_options', 'choiceid', $this->_instance, 'id', 'id,text')) && ($options2 = get_records_menu('choice_options', 'choiceid', $this->_instance, 'id', 'id,maxanswers'))) {
         $choiceids = array_keys($options);
         $options = array_values($options);
         $options2 = array_values($options2);
         foreach (array_keys($options) as $key) {
             $default_values['option[' . $key . ']'] = $options[$key];
             $default_values['limit[' . $key . ']'] = $options2[$key];
             $default_values['optionid[' . $key . ']'] = $choiceids[$key];
         }
     }
     if (empty($default_values['timeopen'])) {
         $default_values['timerestrict'] = 0;
     } else {
         $default_values['timerestrict'] = 1;
     }
 }
Ejemplo n.º 4
0
        trusttext_prepare_edit($toform->definition, $toform->format, can_use_html_editor(), $context);
        $toform->approved = $glossary->defaultapproval or has_capability('mod/glossary:approve', $context);
        $toform->usedynalink = $fromdb->usedynalink;
        $toform->casesensitive = $fromdb->casesensitive;
        $toform->fullmatch = $fromdb->fullmatch;
        $toform->aliases = '';
        $ineditperiod = time() - $fromdb->timecreated < $CFG->maxeditingtime || $glossary->editalways;
        if (!$ineditperiod || $USER->id != $fromdb->userid and !has_capability('mod/glossary:manageentries', $context)) {
            if ($USER->id != $fromdb->userid) {
                print_error('errcannoteditothers', 'glossary');
            } elseif (!$ineditperiod) {
                print_error('erredittimeexpired', 'glossary');
            }
            die;
        }
        if ($aliases = get_records_menu("glossary_alias", "entryid", $e, '', 'id, alias')) {
            $toform->aliases = implode("\n", $aliases) . "\n";
        }
        $mform->set_data($toform);
    }
}
$stredit = empty($e) ? get_string('addentry', 'glossary') : get_string("edit");
$navigation = build_navigation($stredit, $cm);
print_header_simple(format_string($glossary->name), "", $navigation, "", "", true, "", navmenu($course, $cm));
print_heading(format_string($glossary->name));
/// Info box
///if ( $glossary->intro ) {
///    print_simple_box(format_text($glossary->intro), 'center', '70%', '', 5, 'generalbox', 'intro');
///}
/// Tabbed browsing sections
///$tab = GLOSSARY_ADDENTRY_VIEW;
Ejemplo n.º 5
0
$sort = optional_param('sort', 'username', PARAM_ALPHA);
$dir = optional_param('dir', 'ASC', PARAM_ALPHA);
$page = optional_param('page', 0, PARAM_INT);
$perpage = optional_param('perpage', 30, PARAM_INT);
$action = trim(strtolower(optional_param('action', '', PARAM_ALPHA)));
require_login();
admin_externalpage_setup('ssoaccesscontrol');
admin_externalpage_print_header();
if (!extension_loaded('openssl')) {
    print_error('requiresopenssl', 'mnet', '', NULL, true);
}
$sitecontext = get_context_instance(CONTEXT_SYSTEM);
$sesskey = sesskey();
$formerror = array();
// grab the mnet hosts and remove the localhost
$mnethosts = get_records_menu('mnet_host', '', '', 'name', 'id, name');
if (array_key_exists($CFG->mnet_localhost_id, $mnethosts)) {
    unset($mnethosts[$CFG->mnet_localhost_id]);
}
// process actions
if (!empty($action) and confirm_sesskey()) {
    // boot if insufficient permission
    if (!has_capability('moodle/user:delete', $sitecontext)) {
        error(get_string('nomodifyacl', 'mnet'));
    }
    // fetch the record in question
    $id = required_param('id', PARAM_INT);
    if (!($idrec = get_record('mnet_sso_access_control', 'id', $id))) {
        error(get_string('recordnoexists', 'mnet'), "{$CFG->wwwroot}/{$CFG->admin}/mnet/access_control.php");
    }
    switch ($action) {
Ejemplo n.º 6
0
 /**
  * Returns a block of HTML that the external video block can use to show the
  * sites for which iframes are allowed.
  */
 private static function get_valid_iframe_html()
 {
     $iframedomains = get_records_menu('iframe_source_icon', '', '', 'name');
     if (empty($iframedomains)) {
         return '';
     }
     $data = array();
     foreach ($iframedomains as $name => $host) {
         $data[$name] = array('name' => $name, 'url' => 'http://' . $host, 'icon' => favicon_display_url($host));
     }
     $smarty = smarty_core();
     $smarty->assign('data', $data);
     return $smarty->fetch('blocktype:externalvideo:sitelist.tpl');
 }
Ejemplo n.º 7
0
if ($cancreatecontrolled) {
    $elements['hidden'] = array('type' => 'switchbox', 'title' => get_string('hiddengroup', 'group'), 'description' => get_string('hiddengroupdescription1', 'group'), 'defaultvalue' => $group_data->hidden);
    $elements['hidemembers'] = array('type' => 'switchbox', 'title' => get_string('hidemembers', 'group'), 'description' => get_string('hidemembersdescription', 'group'), 'defaultvalue' => $group_data->hidemembers || $group_data->hidemembersfrommembers, 'disabled' => $group_data->hidemembersfrommembers);
    $elements['hidemembersfrommembers'] = array('type' => 'switchbox', 'title' => get_string('hidemembersfrommembers', 'group'), 'description' => get_string('hidemembersfrommembersdescription1', 'group'), 'defaultvalue' => $group_data->hidemembersfrommembers);
} else {
    $form['elements']['hidden'] = array('type' => 'hidden', 'value' => $group_data->hidden);
    $form['elements']['hidemembers'] = array('type' => 'hidden', 'value' => $group_data->hidemembers || $group_data->hidemembersfrommembers);
    $form['elements']['hidemembersfrommembers'] = array('type' => 'hidden', 'value' => $group_data->hidemembersfrommembers);
}
$elements['groupparticipationreports'] = array('type' => 'switchbox', 'title' => get_string('groupparticipationreports', 'group'), 'description' => get_string('groupparticipationreportsdesc1', 'group'), 'defaultvalue' => $group_data->groupparticipationreports);
$elements['editability'] = array('type' => 'html', 'value' => '<h4>' . get_string('editability', 'group') . '</h4>');
$currentdate = getdate();
$elements['editwindowstart'] = array('type' => 'date', 'class' => 'five-across hide-label', 'title' => get_string('windowstart', 'group'), 'defaultvalue' => $group_data->editwindowstart, 'description' => get_string('windowstartdesc', 'group'), 'minyear' => $currentdate['year'], 'maxyear' => $currentdate['year'] + 20, 'time' => true);
$elements['editwindowend'] = array('type' => 'date', 'class' => 'five-across hide-label', 'title' => get_string('windowend', 'group'), 'defaultvalue' => $group_data->editwindowend, 'description' => get_string('windowenddesc', 'group'), 'minyear' => $currentdate['year'], 'maxyear' => $currentdate['year'] + 20, 'time' => true);
$elements['general'] = array('type' => 'html', 'value' => '<h4>' . get_string('general') . '</h4>');
if (get_config('allowgroupcategories') && ($groupcategories = get_records_menu('group_category', '', '', 'displayorder', 'id,title'))) {
    $elements['category'] = array('type' => 'select', 'title' => get_string('groupcategory', 'group'), 'options' => array('0' => get_string('nocategoryselected', 'group')) + $groupcategories, 'defaultvalue' => $group_data->category);
    // If it's a new group & the category was passed as a parameter, hide it in the form.
    $groupcategoryparam = param_integer('category', 0);
    if (!$id && isset($groupcategories[$groupcategoryparam])) {
        $form['elements']['category'] = array('type' => 'hidden', 'value' => $groupcategoryparam);
    }
}
$elements['usersautoadded'] = array('type' => 'switchbox', 'title' => get_string('usersautoadded', 'group'), 'description' => get_string('usersautoaddeddescription1', 'group'), 'defaultvalue' => $group_data->usersautoadded, 'help' => true, 'ignore' => !$USER->get('admin'));
$notifyroles = array(get_string('none', 'admin')) + group_get_editroles_options(true);
$elements['viewnotify'] = array('type' => 'select', 'title' => get_string('viewnotify', 'group'), 'options' => $notifyroles, 'description' => get_string('viewnotifydescription2', 'group'), 'defaultvalue' => $group_data->viewnotify);
$elements['feedbacknotify'] = array('type' => 'select', 'title' => get_string('feedbacknotify', 'group'), 'options' => $notifyroles, 'description' => get_string('feedbacknotifydescription1', 'group'), 'defaultvalue' => $group_data->feedbacknotify);
if ($cancreatecontrolled) {
    $elements['sendnow'] = array('type' => 'switchbox', 'title' => get_string('allowsendnow', 'group'), 'description' => get_string('allowsendnowdescription1', 'group'), 'defaultvalue' => $group_data->sendnow);
} else {
    $form['elements']['sendnow'] = array('type' => 'hidden', 'value' => $group_data->sendnow);
Ejemplo n.º 8
0
 public static function get_instance_config_options($institution, $instance = 0)
 {
     $peer = new Peer();
     // TODO : switch to getrecord
     // Get a list of applications and make a dropdown from it
     $applicationset = new ApplicationSet();
     $apparray = array();
     foreach ($applicationset as $app) {
         $apparray[$app->name] = $app->displayname;
     }
     /**
      * A parent authority for XML-RPC is the data-source that a remote XML-RPC service
      * communicates with to authenticate a user, for example, the XML-RPC server that
      * we connect to might be authorising users against an LDAP store. If this is the
      * case, and we know of the LDAP store, and our users are able to log on to our
      * system and be authenticated directly against the LDAP store, then we honor that
      * association.
      *
      * In this way, the unique relationship is between the username and the authority,
      * not the username and the institution. This allows an institution to have a user
      * 'donal' on server 'LDAP-1' and a different user 'donal' on server 'LDAP-2'.
      *
      * Get a list of auth instances for this institution, and eliminate those that
      * would not be valid parents (as they themselves require a parent). These are
      * eliminated only to provide a saner interface to the admin user. In theory, it's
      * ok to chain authorities.
      */
     $instances = auth_get_auth_instances_for_institution($institution);
     $options = array('None');
     if (is_array($instances)) {
         foreach ($instances as $someinstance) {
             if ($someinstance->requires_parent == 1 || $someinstance->authname == 'none') {
                 continue;
             }
             $options[$someinstance->id] = $someinstance->instancename;
         }
     }
     // Get the current data (if any exists) for this auth instance
     if ($instance > 0) {
         $default = get_record('auth_instance', 'id', $instance);
         if ($default == false) {
             throw new SystemException(get_string('nodataforinstance', 'auth') . $instance);
         }
         $current_config = get_records_menu('auth_instance_config', 'instance', $instance, '', 'field, value');
         if ($current_config == false) {
             throw new SystemException('No config data for instance: ' . $instance);
         }
         foreach (self::$default_config as $key => $value) {
             if (array_key_exists($key, $current_config)) {
                 self::$default_config[$key] = $current_config[$key];
                 // We can use the wwwroot to create a Peer object
                 if ('wwwroot' == $key) {
                     $peer->findByWwwroot($current_config[$key]);
                     self::$default_config['wwwroot_orig'] = $current_config[$key];
                 }
             } elseif (property_exists($default, $key)) {
                 self::$default_config[$key] = $default->{$key};
             }
         }
     } else {
         $max_priority = get_field('auth_instance', 'MAX(priority)', 'institution', $institution);
         self::$default_config['priority'] = ++$max_priority;
     }
     if (empty($peer->application->name)) {
         self::$default_config['appname'] = key(current($applicationset));
     } else {
         self::$default_config['appname'] = $peer->application->name;
     }
     $elements['instancename'] = array('type' => 'text', 'title' => get_string('authname', 'auth'), 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['instancename'], 'help' => true);
     $elements['instance'] = array('type' => 'hidden', 'value' => $instance);
     $elements['institution'] = array('type' => 'hidden', 'value' => $institution);
     $elements['deleted'] = array('type' => 'hidden', 'value' => $peer->deleted);
     $elements['authname'] = array('type' => 'hidden', 'value' => 'xmlrpc');
     $elements['wwwroot'] = array('type' => 'text', 'title' => get_string('wwwroot', 'auth'), 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['wwwroot'], 'help' => true);
     $elements['wwwroot_orig'] = array('type' => 'hidden', 'value' => self::$default_config['wwwroot_orig']);
     $elements['oldwwwroot'] = array('type' => 'hidden', 'value' => 'xmlrpc');
     if ($instance) {
         $elements['publickey'] = array('type' => 'textarea', 'title' => get_string('publickey', 'admin'), 'defaultvalue' => get_field('host', 'publickey', 'wwwroot', self::$default_config['wwwroot']), 'rules' => array('required' => true), 'rows' => 15, 'cols' => 70);
         $elements['publickeyexpires'] = array('type' => 'html', 'title' => get_string('publickeyexpires', 'admin'), 'value' => format_date(get_field('host', 'publickeyexpires', 'wwwroot', self::$default_config['wwwroot'])));
     }
     $elements['name'] = array('type' => 'text', 'title' => get_string('name', 'auth'), 'rules' => array('required' => true), 'defaultvalue' => $peer->name, 'help' => true);
     /**
      * empty($peer->appname) would ALWAYS return true, because the property doesn't really
      * exist. When we try to get $peer->appname, we're actually calling the peer class's
      * __get overloader. Unfortunately, the 'empty' function seems to just check for the
      * existence of the property - it doesn't call the overloader. Bug or feature?
      */
     $tmpappname = $peer->appname;
     $elements['appname'] = array('type' => 'select', 'title' => get_string('application', 'auth'), 'collapseifoneoption' => true, 'multiple' => false, 'options' => $apparray, 'defaultvalue' => empty($tmpappname) ? 'moodle' : $tmpappname, 'help' => true);
     $elements['parent'] = array('type' => 'select', 'title' => get_string('parent', 'auth'), 'collapseifoneoption' => false, 'options' => $options, 'defaultvalue' => self::$default_config['parent'], 'help' => true);
     $elements['authloginmsg'] = array('type' => 'wysiwyg', 'rows' => 10, 'cols' => 70, 'title' => '', 'description' => get_string('authloginmsg2', 'auth'), 'defaultvalue' => self::$default_config['authloginmsg'], 'help' => true);
     $elements['ssodirection'] = array('type' => 'select', 'title' => get_string('ssodirection', 'auth'), 'options' => array(0 => '--', 'theyssoin' => get_string('theyssoin', 'auth'), 'wessoout' => get_string('wessoout', 'auth')), 'defaultvalue' => self::$default_config['wessoout'] ? 'wessoout' : 'theyssoin', 'help' => true);
     $elements['updateuserinfoonlogin'] = array('type' => 'switchbox', 'title' => get_string('updateuserinfoonlogin', 'auth'), 'defaultvalue' => self::$default_config['updateuserinfoonlogin'], 'help' => true);
     $elements['weautocreateusers'] = array('type' => 'switchbox', 'title' => get_string('weautocreateusers', 'auth'), 'defaultvalue' => self::$default_config['weautocreateusers'], 'help' => true);
     $elements['theyautocreateusers'] = array('type' => 'switchbox', 'title' => get_string('theyautocreateusers', 'auth'), 'defaultvalue' => self::$default_config['theyautocreateusers'], 'help' => true);
     $elements['weimportcontent'] = array('type' => 'switchbox', 'title' => get_string('weimportcontent', 'auth'), 'defaultvalue' => self::$default_config['weimportcontent'], 'help' => true);
     return array('elements' => $elements, 'renderer' => 'div');
 }
Ejemplo n.º 9
0
 public static function get_instance_config_options($institution, $instance = 0)
 {
     global $CFG;
     // list of user_type
     $utopt = array();
     $utopt['edir'] = 'Novell Edirectory';
     $utopt['rfc2307'] = 'posixAccount (rfc2307)';
     $utopt['rfc2307bis'] = 'posixAccount (rfc2307bis)';
     $utopt['samba'] = 'sambaSamAccount (v.3.0.7)';
     $utopt['ad'] = 'MS ActiveDirectory';
     $utopt['default'] = 'default';
     $yesnoopt = array('yes' => 'Yes', 'no' => 'No');
     $versionopt = array('2' => '2', '3' => '3');
     if ($instance > 0) {
         $default = get_record('auth_instance', 'id', $instance);
         if ($default == false) {
             throw new SystemException('Could not find data for auth instance ' . $instance);
         }
         $current_config = get_records_menu('auth_instance_config', 'instance', $instance, '', 'field, value');
         if ($current_config == false) {
             $current_config = array();
         }
         foreach (self::$default_config as $key => $value) {
             if (array_key_exists($key, $current_config)) {
                 self::$default_config[$key] = $current_config[$key];
             }
         }
     } else {
         $default = new stdClass();
         $default->instancename = '';
     }
     require_once $CFG->docroot . 'lib/group.php';
     $grouptypeopt = group_get_grouptype_options(self::$default_config['syncgroupsgrouptype']);
     $elements = array('instancename' => array('type' => 'text', 'title' => get_string('authname', 'auth'), 'rules' => array('required' => true), 'defaultvalue' => $default->instancename), 'instance' => array('type' => 'hidden', 'value' => $instance), 'institution' => array('type' => 'hidden', 'value' => $institution), 'authname' => array('type' => 'hidden', 'value' => 'ldap'), 'host_url' => array('type' => 'text', 'title' => get_string('hosturl', 'auth.ldap'), 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['host_url'], 'help' => true), 'contexts' => array('type' => 'text', 'title' => get_string('contexts', 'auth.ldap'), 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['contexts'], 'help' => true), 'user_type' => array('type' => 'select', 'title' => get_string('usertype', 'auth.ldap'), 'options' => $utopt, 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['user_type'], 'help' => true), 'user_attribute' => array('type' => 'text', 'title' => get_string('userattribute', 'auth.ldap'), 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['user_attribute'], 'help' => true), 'search_sub' => array('type' => 'select', 'title' => get_string('searchsubcontexts', 'auth.ldap'), 'options' => $yesnoopt, 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['search_sub'], 'help' => true), 'bind_dn' => array('type' => 'text', 'title' => get_string('distinguishedname', 'auth.ldap'), 'defaultvalue' => self::$default_config['bind_dn'], 'help' => true), 'bind_pw' => array('type' => 'password', 'title' => get_string('password', 'auth.ldap'), 'defaultvalue' => self::$default_config['bind_pw'], 'help' => true), 'version' => array('type' => 'select', 'title' => get_string('ldapversion', 'auth.ldap'), 'options' => $versionopt, 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['version'], 'help' => true), 'starttls' => array('type' => 'checkbox', 'title' => get_string('starttls', 'auth.ldap'), 'defaultvalue' => self::$default_config['starttls']), 'updateuserinfoonlogin' => array('type' => 'checkbox', 'title' => get_string('updateuserinfoonlogin', 'auth.ldap'), 'defaultvalue' => self::$default_config['updateuserinfoonlogin'], 'help' => true), 'weautocreateusers' => array('type' => 'checkbox', 'title' => get_string('weautocreateusers', 'auth.ldap'), 'defaultvalue' => self::$default_config['weautocreateusers'], 'help' => true), 'firstnamefield' => array('type' => 'text', 'title' => get_string('ldapfieldforfirstname', 'auth.ldap'), 'defaultvalue' => self::$default_config['firstnamefield'], 'help' => true), 'surnamefield' => array('type' => 'text', 'title' => get_string('ldapfieldforsurname', 'auth.ldap'), 'defaultvalue' => self::$default_config['surnamefield'], 'help' => true), 'emailfield' => array('type' => 'text', 'title' => get_string('ldapfieldforemail', 'auth.ldap'), 'defaultvalue' => self::$default_config['emailfield'], 'help' => true), 'studentidfield' => array('type' => 'text', 'title' => get_string('ldapfieldforstudentid', 'auth.ldap'), 'defaultvalue' => self::$default_config['studentidfield'], 'help' => true), 'preferrednamefield' => array('type' => 'text', 'title' => get_string('ldapfieldforpreferredname', 'auth.ldap'), 'defaultvalue' => self::$default_config['preferrednamefield'], 'help' => true), 'syncuserscronset' => array('type' => 'fieldset', 'legend' => get_string('syncuserssettings', 'auth.ldap'), 'collapsible' => true, 'collapsed' => !self::$default_config['syncuserscron'], 'elements' => array('syncuserscron' => array('type' => 'checkbox', 'title' => get_string('syncuserscron', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncuserscron']), 'syncusersupdate' => array('type' => 'checkbox', 'title' => get_string('syncusersupdate', 'auth.ldap'), 'defaultvalue' => self::$default_config['syncusersupdate']), 'syncuserscreate' => array('type' => 'checkbox', 'title' => get_string('syncuserscreate', 'auth.ldap'), 'defaultvalue' => self::$default_config['syncuserscreate']), 'syncusersextrafilterattribute' => array('type' => 'text', 'title' => get_string('syncusersextrafilterattribute', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncusersextrafilterattribute']), 'syncusersgonefromldap' => array('type' => 'select', 'title' => get_string('syncusersgonefromldap', 'auth.ldap'), 'help' => true, 'options' => array('' => get_string('syncusersgonefromldapdonothing', 'auth.ldap'), 'suspend' => get_string('syncusersgonefromldapsuspend', 'auth.ldap'), 'delete' => get_string('syncusersgonefromldapdelete', 'auth.ldap')), 'defaultvalue' => self::$default_config['syncusersgonefromldap']))), 'syncgroupscronset' => array('type' => 'fieldset', 'legend' => get_string('syncgroupssettings', 'auth.ldap'), 'collapsible' => true, 'collapsed' => !self::$default_config['syncgroupscron'], 'elements' => array('syncgroupscron' => array('type' => 'checkbox', 'title' => get_string('syncgroupscron', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncgroupscron']), 'syncgroupsautocreate' => array('type' => 'checkbox', 'title' => get_string('syncgroupsautocreate', 'auth.ldap'), 'defaultvalue' => self::$default_config['syncgroupsautocreate']), 'syncgroupsgrouptype' => array('type' => 'select', 'title' => get_string('syncgroupsgrouptype', 'auth.ldap'), 'options' => $grouptypeopt, 'defaultvalue' => self::$default_config['syncgroupsgrouptype']), 'syncgroupsexcludelist' => array('type' => 'text', 'title' => get_string('syncgroupsexcludelist', 'auth.ldap'), 'defaultvalue' => self::$default_config['syncgroupsexcludelist']), 'syncgroupsincludelist' => array('type' => 'text', 'title' => get_string('syncgroupsincludelist', 'auth.ldap'), 'defaultvalue' => self::$default_config['syncgroupsincludelist']), 'syncgroupshr1' => array('type' => 'html', 'value' => '<hr />'), 'syncgroupsbyclass' => array('type' => 'checkbox', 'title' => get_string('syncgroupsbyclass', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncgroupsbyclass']), 'syncgroupsgroupclass' => array('type' => 'text', 'title' => get_string('syncgroupsgroupclass', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncgroupsgroupclass']), 'syncgroupsgroupattribute' => array('type' => 'text', 'title' => get_string('syncgroupsgroupattribute', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncgroupsgroupattribute']), 'syncgroupsmemberattribute' => array('type' => 'text', 'title' => get_string('syncgroupsmemberattribute', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncgroupsmemberattribute']), 'syncgroupsmemberattributeisdn' => array('type' => 'checkbox', 'title' => get_string('syncgroupsmemberattributeisdn', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncgroupsmemberattributeisdn']), 'syncgroupsnestedgroups' => array('type' => 'checkbox', 'title' => get_string('syncgroupsnestedgroups', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncgroupsnestedgroups']), 'syncgroupscontexts' => array('type' => 'text', 'title' => get_string('syncgroupscontexts', 'auth.ldap'), 'description' => get_string('syncgroupscontextsdesc', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncgroupscontexts']), 'syncgroupssearchsub' => array('type' => 'select', 'title' => get_string('searchsubcontexts', 'auth.ldap'), 'options' => $yesnoopt, 'defaultvalue' => self::$default_config['syncgroupssearchsub']), 'syncgroupshr2' => array('type' => 'html', 'value' => '<hr />'), 'syncgroupsbyuserfield' => array('type' => 'checkbox', 'title' => get_string('syncgroupsbyuserfield', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncgroupsbyuserfield']), 'syncgroupsuserattribute' => array('type' => 'text', 'title' => get_string('syncgroupsuserattribute', 'auth.ldap'), 'defaultvalue' => self::$default_config['syncgroupsuserattribute']), 'syncgroupsusergroupnames' => array('type' => 'text', 'title' => get_string('syncgroupsusergroupnames', 'auth.ldap'), 'description' => get_string('syncgroupsusergroupnamesdesc', 'auth.ldap'), 'help' => true, 'defaultvalue' => self::$default_config['syncgroupsusergroupnames']))));
     return array('elements' => $elements, 'renderer' => 'table');
 }
Ejemplo n.º 10
0
* a controller for the play view
* 
* @package mod-poodllflashcard
* @category mod
* @author Valery Fremaux
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*
* @usecase add
* @usecase delete
* @usecase save
*/
/******************************** Add new blank fields *****************************/
if ($action == 'add') {
    $add = required_param('add', PARAM_INT);
    $card->flashcardid = $flashcard->id;
    $users = get_records_menu('poodllflashcard_card', 'flashcardid', $flashcard->id, '', 'DISTINCT userid, id');
    for ($i = 0; $i < $add; $i++) {
        if (!($newcardid = insert_record('poodllflashcard_deckdata', $card))) {
            error("Could not add card to deck");
        }
        if ($users) {
            foreach (array_keys($users) as $userid) {
                $deckcard->flashcardid = $flashcard->id;
                $deckcard->entryid = $newcardid;
                $deckcard->userid = $userid;
                $deckcard->lastaccessed = 0;
                $deckcard->deck = 1;
                $deckcard->accesscount = 0;
                if (!insert_record('poodllflashcard_card', $deckcard)) {
                    error("Could not bind card to user {$userid} deck");
                }
Ejemplo n.º 11
0
 public static function get_instance_config_options($institution, $instance = 0)
 {
     // list of user_type
     $utopt = array();
     $utopt['edir'] = 'Novell Edirectory';
     $utopt['rfc2307'] = 'posixAccount (rfc2307)';
     $utopt['rfc2307bis'] = 'posixAccount (rfc2307bis)';
     $utopt['samba'] = 'sambaSamAccount (v.3.0.7)';
     $utopt['ad'] = 'MS ActiveDirectory';
     $utopt['default'] = 'default';
     $yesnoopt = array('yes' => 'Yes', 'no' => 'No');
     $versionopt = array('2' => '2', '3' => '3');
     if ($instance > 0) {
         $default = get_record('auth_instance', 'id', $instance);
         if ($default == false) {
             throw new SystemException('Could not find data for auth instance ' . $instance);
         }
         $current_config = get_records_menu('auth_instance_config', 'instance', $instance, '', 'field, value');
         if ($current_config == false) {
             $current_config = array();
         }
         foreach (self::$default_config as $key => $value) {
             if (array_key_exists($key, $current_config)) {
                 self::$default_config[$key] = $current_config[$key];
             }
         }
     } else {
         $default = new stdClass();
         $default->instancename = '';
     }
     $elements = array('instancename' => array('type' => 'text', 'title' => get_string('authname', 'auth'), 'rules' => array('required' => true), 'defaultvalue' => $default->instancename), 'instance' => array('type' => 'hidden', 'value' => $instance), 'institution' => array('type' => 'hidden', 'value' => $institution), 'authname' => array('type' => 'hidden', 'value' => 'ldap'), 'host_url' => array('type' => 'text', 'title' => get_string('hosturl', 'auth.ldap'), 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['host_url'], 'help' => true), 'contexts' => array('type' => 'text', 'title' => get_string('contexts', 'auth.ldap'), 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['contexts'], 'help' => true), 'user_type' => array('type' => 'select', 'title' => get_string('usertype', 'auth.ldap'), 'options' => $utopt, 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['user_type'], 'help' => true), 'user_attribute' => array('type' => 'text', 'title' => get_string('userattribute', 'auth.ldap'), 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['user_attribute'], 'help' => true), 'search_sub' => array('type' => 'select', 'title' => get_string('searchsubcontexts', 'auth.ldap'), 'options' => $yesnoopt, 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['search_sub'], 'help' => true), 'bind_dn' => array('type' => 'text', 'title' => get_string('distinguishedname', 'auth.ldap'), 'defaultvalue' => self::$default_config['bind_dn'], 'help' => true), 'bind_pw' => array('type' => 'text', 'title' => get_string('password', 'auth.ldap'), 'defaultvalue' => self::$default_config['bind_pw'], 'help' => true), 'version' => array('type' => 'select', 'title' => get_string('ldapversion', 'auth.ldap'), 'options' => $versionopt, 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['version'], 'help' => true), 'weautocreateusers' => array('type' => 'checkbox', 'title' => get_string('weautocreateusers', 'auth.ldap'), 'defaultvalue' => self::$default_config['weautocreateusers'], 'help' => true), 'firstnamefield' => array('type' => 'text', 'title' => get_string('ldapfieldforfirstname', 'auth.ldap'), 'defaultvalue' => self::$default_config['firstnamefield'], 'help' => true), 'surnamefield' => array('type' => 'text', 'title' => get_string('ldapfieldforsurname', 'auth.ldap'), 'defaultvalue' => self::$default_config['surnamefield'], 'help' => true), 'emailfield' => array('type' => 'text', 'title' => get_string('ldapfieldforemail', 'auth.ldap'), 'defaultvalue' => self::$default_config['emailfield'], 'help' => true));
     return array('elements' => $elements, 'renderer' => 'table');
 }
Ejemplo n.º 12
0
Archivo: lib.php Proyecto: r007/PMoodle
function journal_grades($journalid)
{
    /// Must return an array of grades, indexed by user, and a max grade.
    if (!($journal = get_record("journal", "id", $journalid))) {
        return NULL;
    }
    $grades = get_records_menu("journal_entries", "journal", $journal->id, "", "userid,rating");
    if ($journal->assessed > 0) {
        $return->grades = $grades;
        $return->maxgrade = $journal->assessed;
    } else {
        if ($journal->assessed == 0) {
            return NULL;
        } else {
            if ($scale = get_record("scale", "id", -$journal->assessed)) {
                $scalegrades = make_menu_from_list($scale->scale);
                if ($grades) {
                    foreach ($grades as $key => $grade) {
                        $grades[$key] = $scalegrades[$grade];
                    }
                }
            }
            $return->grades = $grades;
            $return->maxgrade = "";
        }
    }
    return $return;
}
Ejemplo n.º 13
0
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
 *
 */
define('INTERNAL', 1);
define('ADMIN', 1);
define('MENUITEM', 'configextensions/iframesites');
define('SECTION_PLUGINTYPE', 'core');
define('SECTION_PLUGINNAME', 'admin');
define('SECTION_PAGE', 'iframesites');
require dirname(dirname(dirname(__FILE__))) . '/init.php';
require_once 'pieforms/pieform.php';
require_once 'upgrade.php';
define('TITLE', get_string('allowediframesites', 'admin'));
$iframesources = get_records_menu('iframe_source', '', '', 'name,prefix');
$iframedomains = get_records_menu('iframe_source_icon');
$newform = pieform(array('name' => 'newurl', 'elements' => array('url' => array('type' => 'text', 'title' => get_string('Site'), 'description' => get_string('iframeurldescription', 'admin'), 'rules' => array('minlength' => 4, 'maxlength' => 255, 'regex' => '/^[a-zA-Z0-9\\/\\._-]+$/')), 'name' => array('type' => 'text', 'title' => get_string('displayname'), 'description' => get_string('iframedisplaynamedescription', 'admin'), 'rules' => array('minlength' => 1, 'maxlength' => 100)), 'submit' => array('type' => 'submit', 'class' => 'btn-success', 'value' => get_string('add')))));
$editurls = array();
$i = 0;
foreach ($iframesources as $url => $name) {
    $elements = array('url' => array('type' => 'hidden', 'value' => $url), 'name' => array('type' => 'text', 'title' => get_string('displayname'), 'description' => get_string('iframedisplaynamedescription', 'admin'), 'defaultvalue' => $name), 'icon' => array('type' => 'text', 'title' => get_string('iframeiconhost', 'admin'), 'description' => get_string('iframeiconhostdescription', 'admin'), 'defaultvalue' => $iframedomains[$name], 'rules' => array('minlength' => 4, 'maxlength' => 253, 'regex' => '/^[a-zA-Z0-9-]{1,63}(\\.[a-zA-Z0-9-]{1,63})+$/')), 'submit' => array('type' => 'submit', 'class' => 'btn-primary btn-sm', 'value' => get_string('save')));
    $editurls[$i] = array('id' => $i, 'url' => $url, 'name' => $name, 'icon' => favicon_display_url($iframedomains[$name]), 'editform' => pieform(array('name' => 'editurl_' . $i, 'successcallback' => 'editurl_submit', 'elements' => $elements)), 'deleteform' => pieform(array('name' => 'deleteurl_' . $i, 'successcallback' => 'deleteurl_submit', 'renderer' => 'div', 'class' => 'form-inline form-as-button pull-left last', 'elements' => array('submit' => array('type' => 'button', 'class' => 'btn-default btn-sm', 'usebuttontag' => true, 'value' => '<span class="icon icon-trash icon-lg text-danger"></span><span class="sr-only">' . get_string('delete') . '</span>', 'confirm' => get_string('confirmdeletemenuitem', 'admin')), 'url' => array('type' => 'hidden', 'value' => $url)))));
    $i++;
}
function editurl_submit(Pieform $form, $values)
{
    global $iframesources, $iframedomains, $SESSION;
    if (isset($iframesources[$values['url']])) {
        $oldname = $iframesources[$values['url']];
        $newname = strip_tags($values['name']);
        $iframesources[$values['url']] = $newname;
Ejemplo n.º 14
0
 protected function populate($result)
 {
     foreach (array_keys(self::$dbfields) as $fieldname) {
         $this->{$fieldname} = $result->{$fieldname};
     }
     $this->configs = get_records_menu('institution_config', 'institution', $result->name, 'field', 'field, value');
     if (!$this->configs) {
         $this->configs = array();
     }
     $this->verifyReady();
 }
Ejemplo n.º 15
0
/**
 * This function will fix the status of the localhost/all records in the mnet_host table
 * checking they exist and adding them if missing + redefine CFG->mnet_localhost_id  and
 * CFG->mnet_all_hosts_id if needed + update all the users having non-existent mnethostid
 * to correct CFG->mnet_localhost_id
 *
 * Implemented because, at some point, specially in old installations upgraded along
 * multiple versions, sometimes the stuff above has ended being inconsistent, causing
 * problems here and there (noticeablely in backup/restore). MDL-16879
 */
function upgrade_fix_incorrect_mnethostids()
{
    global $CFG;
    /// Get current $CFG/mnet_host records
    $old_mnet_localhost_id = !empty($CFG->mnet_localhost_id) ? $CFG->mnet_localhost_id : 0;
    $old_mnet_all_hosts_id = !empty($CFG->mnet_all_hosts_id) ? $CFG->mnet_all_hosts_id : 0;
    $current_mnet_localhost_host = get_record('mnet_host', 'wwwroot', addslashes($CFG->wwwroot));
    /// By wwwroot
    $current_mnet_all_hosts_host = get_record_select('mnet_host', sql_isempty('mnet_host', 'wwwroot', false, false));
    /// By empty wwwroot
    if (!($moodleapplicationid = get_field('mnet_application', 'id', 'name', 'moodle'))) {
        $m = (object) array('name' => 'moodle', 'display_name' => 'Moodle', 'xmlrpc_server_url' => '/mnet/xmlrpc/server.php', 'sso_land_url' => '/auth/mnet/land.php', 'sso_jump_url' => '/auth/mnet/land.php');
        $moodleapplicationid = insert_record('mnet_application', $m);
    }
    /// Create localhost_host if necessary (pretty improbable but better to be 100% in the safe side)
    /// Code stolen from mnet_environment->init
    if (!$current_mnet_localhost_host) {
        $current_mnet_localhost_host = new stdClass();
        $current_mnet_localhost_host->wwwroot = $CFG->wwwroot;
        $current_mnet_localhost_host->ip_address = '';
        $current_mnet_localhost_host->public_key = '';
        $current_mnet_localhost_host->public_key_expires = 0;
        $current_mnet_localhost_host->last_connect_time = 0;
        $current_mnet_localhost_host->last_log_id = 0;
        $current_mnet_localhost_host->deleted = 0;
        $current_mnet_localhost_host->name = '';
        $current_mnet_localhost_host->applicationid = $moodleapplicationid;
        /// Get the ip of the server
        if (empty($_SERVER['SERVER_ADDR'])) {
            /// SERVER_ADDR is only returned by Apache-like webservers
            $count = preg_match("@^(?:http[s]?://)?([A-Z0-9\\-\\.]+).*@i", $current_mnet_localhost_host->wwwroot, $matches);
            $my_hostname = $count > 0 ? $matches[1] : false;
            $my_ip = gethostbyname($my_hostname);
            // Returns unmodified hostname on failure. DOH!
            if ($my_ip == $my_hostname) {
                $current_mnet_localhost_host->ip_address = 'UNKNOWN';
            } else {
                $current_mnet_localhost_host->ip_address = $my_ip;
            }
        } else {
            $current_mnet_localhost_host->ip_address = $_SERVER['SERVER_ADDR'];
        }
        $current_mnet_localhost_host->id = insert_record('mnet_host', $current_mnet_localhost_host, true);
    }
    /// Create all_hosts_host if necessary (pretty improbable but better to be 100% in the safe side)
    /// Code stolen from mnet_environment->init
    if (!$current_mnet_all_hosts_host) {
        $current_mnet_all_hosts_host = new stdClass();
        $current_mnet_all_hosts_host->wwwroot = '';
        $current_mnet_all_hosts_host->ip_address = '';
        $current_mnet_all_hosts_host->public_key = '';
        $current_mnet_all_hosts_host->public_key_expires = 0;
        $current_mnet_all_hosts_host->last_connect_time = 0;
        $current_mnet_all_hosts_host->last_log_id = 0;
        $current_mnet_all_hosts_host->deleted = 0;
        $current_mnet_all_hosts_host->name = 'All Hosts';
        $current_mnet_all_hosts_host->applicationid = $moodleapplicationid;
        $current_mnet_all_hosts_host->id = insert_record('mnet_host', $current_mnet_all_hosts_host, true);
    }
    /// Compare old_mnet_localhost_id and current_mnet_localhost_host
    if ($old_mnet_localhost_id != $current_mnet_localhost_host->id) {
        /// Different = problems
        /// Update $CFG->mnet_localhost_id to correct value
        set_config('mnet_localhost_id', $current_mnet_localhost_host->id);
        /// Delete $old_mnet_localhost_id if exists (users will be assigned to new one below)
        delete_records('mnet_host', 'id', $old_mnet_localhost_id);
    }
    /// Compare old_mnet_all_hosts_id and current_mnet_all_hosts_host
    if ($old_mnet_all_hosts_id != $current_mnet_all_hosts_host->id) {
        /// Different = problems
        /// Update $CFG->mnet_localhost_id to correct value
        set_config('mnet_all_hosts_id', $current_mnet_all_hosts_host->id);
        /// Delete $old_mnet_all_hosts_id if exists
        delete_records('mnet_host', 'id', $old_mnet_all_hosts_id);
    }
    /// Finally, update all the incorrect user->mnethostid to the correct CFG->mnet_localhost_id, preventing UIX dupes
    $hosts = get_records_menu('mnet_host', '', '', '', 'id, id AS id2');
    $hosts_str = implode(', ', $hosts);
    $sql = "SELECT id\n            FROM {$CFG->prefix}user u1\n            WHERE u1.mnethostid NOT IN ({$hosts_str})\n              AND NOT EXISTS (\n                  SELECT 'x'\n                    FROM {$CFG->prefix}user u2\n                   WHERE u2.username = u1.username\n                     AND u2.mnethostid = {$current_mnet_localhost_host->id})";
    $rs = get_recordset_sql($sql);
    while ($rec = rs_fetch_next_record($rs)) {
        set_field('user', 'mnethostid', $current_mnet_localhost_host->id, 'id', $rec->id);
    }
    rs_close($rs);
    // fix up any host records that have incorrect ids
    set_field_select('mnet_host', 'applicationid', $moodleapplicationid, "id = {$current_mnet_localhost_host->id} or id = {$current_mnet_all_hosts_host->id}");
}
Ejemplo n.º 16
0
/**
 * Must return an array of grades for a given instance of this module, 
 * indexed by user.  It also returns a maximum allowed grade.
 * 
 * Example:
 *    $return->grades = array of grades;
 *    $return->maxgrade = maximum allowed grade;
 *
 *    return $return;
 *
 * @param int $webquestscormid ID of an instance of this module
 * @return mixed Null or object with an array of grades and with the maximum grade
 **/
function webquestscorm_grades($wqid)
{
    if (!($webquestscorm = get_record('webquestscorm', 'id', $wqid))) {
        return NULL;
    }
    if ($webquestscorm->grade == 0) {
        return NULL;
    }
    $grades = get_records_menu('webquestscorm_submissions', 'webquestscorm', $webquestscorm->id, '', 'userid,grade');
    if ($webquestscorm->grade > 0) {
        if ($grades) {
            foreach ($grades as $userid => $grade) {
                if ($grade == -1) {
                    $grades[$userid] = '-';
                }
            }
        }
        $return->grades = $grades;
        $return->maxgrade = $webquestscorm->grade;
    } else {
        if ($grades) {
            $scaleid = -$webquestscorm->grade;
            $maxgrade = "";
            if ($scale = get_record('scale', 'id', $scaleid)) {
                $scalegrades = make_menu_from_list($scale->scale);
                foreach ($grades as $userid => $grade) {
                    if (empty($scalegrades[$grade])) {
                        $grades[$userid] = '-';
                    } else {
                        $grades[$userid] = $scalegrades[$grade];
                    }
                }
                $maxgrade = $scale->name;
            }
        }
        $return->grades = $grades;
        $return->maxgrade = $maxgrade;
    }
    return $return;
}
Ejemplo n.º 17
0
/**
 * Internal function used by groups_get_members_by_role to handle the
 * results of a database query that includes a list of users and possible
 * roles on a course.
 *
 * @param object $rs The record set (may be false)
 * @param object $context of course
 * @return array As described in groups_get_members_by_role 
 */
function groups_calculate_role_people($rs, $context)
{
    global $CFG;
    if (!$rs) {
        return false;
    }
    $roles = get_records_menu('role', null, 'name', 'id, name');
    $aliasnames = role_fix_names($roles, $context);
    // Array of all involved roles
    $roles = array();
    // Array of all retrieved users
    $users = array();
    // Fill arrays
    while ($rec = rs_fetch_next_record($rs)) {
        // Create information about user if this is a new one
        if (!array_key_exists($rec->userid, $users)) {
            // User data includes all the optional fields, but not any of the
            // stuff we added to get the role details
            $userdata = clone $rec;
            unset($userdata->roleid);
            unset($userdata->roleshortname);
            unset($userdata->rolename);
            unset($userdata->userid);
            $userdata->id = $rec->userid;
            // Make an array to hold the list of roles for this user
            $userdata->roles = array();
            $users[$rec->userid] = $userdata;
        }
        // If user has a role...
        if (!is_null($rec->roleid)) {
            // Create information about role if this is a new one
            if (!array_key_exists($rec->roleid, $roles)) {
                $roledata = new StdClass();
                $roledata->id = $rec->roleid;
                $roledata->shortname = $rec->roleshortname;
                if (array_key_exists($rec->roleid, $aliasnames)) {
                    $roledata->name = $aliasnames[$rec->roleid];
                } else {
                    $roledata->name = $rec->rolename;
                }
                $roledata->users = array();
                $roles[$roledata->id] = $roledata;
            }
            // Record that user has role
            $users[$rec->userid]->roles[] = $roles[$rec->roleid];
        }
    }
    rs_close($rs);
    // Return false if there weren't any users
    if (count($users) == 0) {
        return false;
    }
    // Add pseudo-role for multiple roles
    $roledata = new StdClass();
    $roledata->name = get_string('multipleroles', 'role');
    $roledata->users = array();
    $roles['*'] = $roledata;
    // Now we rearrange the data to store users by role
    foreach ($users as $userid => $userdata) {
        $rolecount = count($userdata->roles);
        if ($rolecount == 0) {
            debugging("Unexpected: user {$userid} is missing roles");
        } else {
            if ($rolecount > 1) {
                $roleid = '*';
            } else {
                $roleid = $userdata->roles[0]->id;
            }
        }
        $roles[$roleid]->users[$userid] = $userdata;
    }
    // Delete roles not used
    foreach ($roles as $key => $roledata) {
        if (count($roledata->users) === 0) {
            unset($roles[$key]);
        }
    }
    // Return list of roles containing their users
    return $roles;
}
Ejemplo n.º 18
0
/**
 * Gets a curriculum listing suitable for a select box.
 *
 * @return array Returned records.
 */
function curriculum_get_menu()
{
    return get_records_menu(CURTABLE, NULL, NULL, 'name', 'id,name');
}
Ejemplo n.º 19
0
/**
 * The CSV file is parsed here so validation errors can be returned to the
 * user. The data from a successful parsing is stored in the <var>$CVSDATA</var>
 * array so it can be accessed by the submit function
 *
 * @param Pieform  $form   The form to validate
 * @param array    $values The values submitted
 */
function uploadcsv_validate(Pieform $form, $values)
{
    global $CSVDATA, $ALLOWEDKEYS, $FORMAT, $USER, $INSTITUTIONNAME, $UPDATES;
    // Don't even start attempting to parse if there are previous errors
    if ($form->has_errors()) {
        return;
    }
    $steps_done = 0;
    $steps_total = $values['updateusers'] ? 5 : 4;
    if ($values['file']['size'] == 0) {
        $form->set_error('file', $form->i18n('rule', 'required', 'required', array()));
        return;
    }
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        $maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled');
        $maxquota = get_config_plugin('artefact', 'file', 'maxquota');
        if ($maxquotaenabled && $values['quota'] > $maxquota) {
            $form->set_error('quota', get_string('maxquotaexceededform', 'artefact.file', display_size($maxquota)));
        }
    }
    require_once 'csvfile.php';
    $authinstance = (int) $values['authinstance'];
    $institution = get_field('auth_instance', 'institution', 'id', $authinstance);
    if (!$USER->can_edit_institution($institution)) {
        $form->set_error('authinstance', get_string('notadminforinstitution', 'admin'));
        return;
    }
    $authobj = AuthFactory::create($authinstance);
    $csvusers = new CsvFile($values['file']['tmp_name']);
    $csvusers->set('allowedkeys', $ALLOWEDKEYS);
    // Now we know all of the field names are valid, we need to make
    // sure that the required fields are included
    $mandatoryfields = array('username', 'email', 'firstname', 'lastname');
    if (!$values['updateusers']) {
        $mandatoryfields[] = 'password';
    }
    $csvusers->set('mandatoryfields', $mandatoryfields);
    $csvdata = $csvusers->get_data();
    if (!empty($csvdata->errors['file'])) {
        $form->set_error('file', $csvdata->errors['file']);
        return;
    }
    $csverrors = new CSVErrors();
    $formatkeylookup = array_flip($csvdata->format);
    // First pass validates usernames & passwords in the file, and builds
    // up a list indexed by username.
    $emails = array();
    if (isset($formatkeylookup['remoteuser'])) {
        $remoteusers = array();
    }
    $num_lines = count($csvdata->data);
    $maxcsvlines = get_config('maxusercsvlines');
    if ($maxcsvlines && $maxcsvlines < $num_lines) {
        $form->set_error('file', get_string('uploadcsverrortoomanyusers', 'admin', get_string('nusers', 'mahara', $maxcsvlines)));
        return;
    }
    $existing_usernames = get_records_menu('usr', '', NULL, '', 'LOWER(username) AS username, 1 AS key2');
    $existing_usr_email_addresses = get_records_menu('usr', '', NULL, '', 'email, 1 AS key2');
    $existing_internal_email_addresses = get_records_menu('artefact_internal_profile_email', 'verified', 1, '', 'email, 1 AS key2');
    foreach ($csvdata->data as $key => $line) {
        // If headers exists, increment i = key + 2 for actual line number
        $i = $csvusers->get('headerExists') ? $key + 2 : $key + 1;
        if (!($key % 25)) {
            set_progress_info('uploaduserscsv', $key, $num_lines * $steps_total, get_string('validating', 'admin'));
        }
        // Trim non-breaking spaces -- they get left in place by File_CSV
        foreach ($line as &$field) {
            $field = preg_replace('/^(\\s|\\xc2\\xa0)*(.*?)(\\s|\\xc2\\xa0)*$/', '$2', $field);
        }
        if (count($line) != count($csvdata->format)) {
            $csverrors->add($i, get_string('uploadcsverrorwrongnumberoffields', 'admin', $i));
            continue;
        }
        // We have a line with the correct number of fields, but should validate these fields
        // Note: This validation should really be methods on each profile class, that way
        // it can be used in the profile screen as well.
        $username = $line[$formatkeylookup['username']];
        $password = isset($formatkeylookup['password']) ? $line[$formatkeylookup['password']] : null;
        $email = $line[$formatkeylookup['email']];
        if (isset($remoteusers)) {
            $remoteuser = strlen($line[$formatkeylookup['remoteuser']]) ? $line[$formatkeylookup['remoteuser']] : null;
        }
        if (method_exists($authobj, 'is_username_valid_admin')) {
            if (!$authobj->is_username_valid_admin($username)) {
                $csverrors->add($i, get_string('uploadcsverrorinvalidusername', 'admin', $i));
            }
        } else {
            if (method_exists($authobj, 'is_username_valid')) {
                if (!$authobj->is_username_valid($username)) {
                    $csverrors->add($i, get_string('uploadcsverrorinvalidusername', 'admin', $i));
                }
            }
        }
        if (!$values['updateusers']) {
            // Note: only checks for valid form are done here, none of the checks
            // like whether the password is too easy. The user is going to have to
            // change their password on first login anyway.
            if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) {
                $csverrors->add($i, get_string('uploadcsverrorinvalidpassword', 'admin', $i));
            }
        }
        if (isset($emails[$email])) {
            // Duplicate email within this file.
            $csverrors->add($i, get_string('uploadcsverroremailaddresstaken', 'admin', $i, $email));
        } else {
            if (!PHPMailer::ValidateAddress($email)) {
                $csverrors->add($i, get_string('uploadcsverrorinvalidemail', 'admin', $i, $email));
            } else {
                if (!$values['updateusers']) {
                    // The email address must be new
                    if (array_key_exists($email, $existing_usr_email_addresses) || array_key_exists($email, $existing_internal_email_addresses)) {
                        $csverrors->add($i, get_string('uploadcsverroremailaddresstaken', 'admin', $i, $email));
                    }
                }
            }
        }
        $emails[$email] = 1;
        if (isset($remoteusers) && $remoteuser) {
            if (isset($remoteusers[$remoteuser])) {
                $csverrors->add($i, get_string('uploadcsverrorduplicateremoteuser', 'admin', $i, $remoteuser));
            } else {
                if (!$values['updateusers']) {
                    if ($remoteuserowner = get_record_sql('
                    SELECT u.username
                    FROM {auth_remote_user} aru JOIN {usr} u ON aru.localusr = u.id
                    WHERE aru.remoteusername = ? AND aru.authinstance = ?', array($remoteuser, $authinstance))) {
                        $csverrors->add($i, get_string('uploadcsverrorremoteusertaken', 'admin', $i, $remoteuser, $remoteuserowner->username));
                    }
                }
            }
            $remoteusers[$remoteuser] = true;
        }
        // If we didn't even get a username, we can't check for duplicates, so move on.
        if (strlen($username) < 1) {
            continue;
        }
        if (isset($usernames[strtolower($username)])) {
            // Duplicate username within this file.
            $csverrors->add($i, get_string('uploadcsverroruseralreadyexists', 'admin', $i, $username));
        } else {
            if (!$values['updateusers'] && array_key_exists(strtolower($username), $existing_usernames)) {
                $csverrors->add($i, get_string('uploadcsverroruseralreadyexists', 'admin', $i, $username));
            }
            $usernames[strtolower($username)] = array('username' => $username, 'password' => $password, 'email' => $email, 'lineno' => $i, 'raw' => $line);
            if (!empty($remoteuser) && !empty($remoteusers[$remoteuser])) {
                $usernames[strtolower($username)]['remoteuser'] = $remoteuser;
            }
        }
    }
    // If the admin is trying to overwrite existing users, identified by username,
    // this second pass performs some additional checks
    if ($values['updateusers']) {
        $key = 0;
        foreach ($usernames as $lowerusername => $data) {
            if (!($key % 25)) {
                set_progress_info('uploaduserscsv', $num_lines + $key, $num_lines * $steps_total, get_string('checkingupdates', 'admin'));
            }
            $key++;
            $line = $data['lineno'];
            $username = $data['username'];
            $password = $data['password'];
            $email = $data['email'];
            // If the user already exists, they must already be in this institution.
            $userinstitutions = get_records_sql_assoc("\n                SELECT COALESCE(ui.institution, 'mahara') AS institution, u.id\n                FROM {usr} u LEFT JOIN {usr_institution} ui ON u.id = ui.usr\n                WHERE LOWER(u.username) = ?", array($lowerusername));
            if ($userinstitutions) {
                if (!isset($userinstitutions[$institution])) {
                    if ($institution == 'mahara') {
                        $institutiondisplay = array();
                        foreach ($userinstitutions as $i) {
                            $institutiondisplay[] = $INSTITUTIONNAME[$i->institution];
                        }
                        $institutiondisplay = join(', ', $institutiondisplay);
                        $message = get_string('uploadcsverroruserinaninstitution', 'admin', $line, $username, $institutiondisplay);
                    } else {
                        $message = get_string('uploadcsverrorusernotininstitution', 'admin', $line, $username, $INSTITUTIONNAME[$institution]);
                    }
                    $csverrors->add($line, $message);
                } else {
                    // Remember that this user is being updated
                    $UPDATES[$username] = 1;
                }
            } else {
                // New user, check the password
                if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) {
                    $csverrors->add($line, get_string('uploadcsverrorinvalidpassword', 'admin', $line));
                }
            }
            // Check if the email already exists and if it's owned by this user.  This query can return more
            // than one row when there are duplicate emails already on the site.  If that happens, things are
            // already a bit out of hand, and we'll just allow an update if this user is one of the users who
            // owns the email.
            $emailowned = get_records_sql_assoc('
                SELECT LOWER(u.username) AS lowerusername, ae.principal FROM {usr} u
                LEFT JOIN {artefact_internal_profile_email} ae ON u.id = ae.owner AND ae.verified = 1 AND ae.email = ?
                WHERE ae.owner IS NOT NULL OR u.email = ?', array($email, $email));
            // If the email is owned by someone else, it could still be okay provided
            // that other user's email is also being changed in this csv file.
            if ($emailowned && !isset($emailowned[$lowerusername])) {
                foreach ($emailowned as $e) {
                    // Only primary emails can be set in uploadcsv, so it's an error when someone else
                    // owns the email as a secondary.
                    if (!$e->principal) {
                        $csverrors->add($line, get_string('uploadcsverroremailaddresstaken', 'admin', $line, $email));
                        break;
                    }
                    // It's also an error if the email owner is not being updated in this file
                    if (!isset($usernames[$e->lowerusername])) {
                        $csverrors->add($line, get_string('uploadcsverroremailaddresstaken', 'admin', $line, $email));
                        break;
                    }
                    // If the other user is being updated in this file, but isn't changing their
                    // email address, it's ok, we've already notified duplicate emails within the file.
                }
            }
            if (isset($remoteusers) && !empty($data['remoteuser'])) {
                $remoteuser = $data['remoteuser'];
                $remoteuserowner = get_field_sql('
                    SELECT LOWER(u.username)
                    FROM {usr} u JOIN {auth_remote_user} aru ON u.id = aru.localusr
                    WHERE aru.remoteusername = ? AND aru.authinstance = ?', array($remoteuser, $authinstance));
                if ($remoteuserowner && $remoteuserowner != $lowerusername && !isset($usernames[$remoteuserowner])) {
                    // The remote username is owned by some other user who is not being updated in this file
                    $csverrors->add($line, get_string('uploadcsverrorremoteusertaken', 'admin', $line, $remoteuser, $remoteuserowner));
                }
            }
        }
    }
    if ($errors = $csverrors->process()) {
        $form->set_error('file', clean_html($errors), false);
        return;
    }
    $FORMAT = $csvdata->format;
    $CSVDATA = $csvdata->data;
}
Ejemplo n.º 20
0
 *
 * @package    moodle
 * @subpackage local
 * @author     Penny Leach <*****@*****.**>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 1999 onwards Martin Dougiamas  http://dougiamas.com
 *
 */
require_once dirname(dirname(dirname(__FILE__))) . '/config.php';
require_once $CFG->libdir . '/adminlib.php';
require_once $CFG->dirroot . '/local/forms.php';
admin_externalpage_setup('lpclassification');
admin_externalpage_print_header();
print_heading(get_string('lpclassificationheading', 'local'));
$type = optional_param('type', 0, PARAM_INT);
$types = get_records_menu('classification_type', '', '', 'name', 'id,name');
$url = $CFG->wwwroot . '/local/admin/lpclassify.php';
echo get_string('editlpclass', 'local') . ':';
popup_form($url . '?type=', $types, 'lpclassify', $type);
if (!$type) {
    admin_externalpage_print_footer();
    exit;
}
if (!($values = get_records('classification_value', 'type', $type, 'value'))) {
    $values = array();
}
$mform = new tao_adminsettings_lpclassification_form('', array('type' => $type, 'values' => $values));
if ($formdata = $mform->get_data()) {
    $todelete = array();
    foreach ((array) $formdata as $key => $value) {
        if (preg_match('/edit(\\d+)/', $key, $matches)) {
Ejemplo n.º 21
0
/**
 * Print a selection box for groups
 * * modified from forum module
 **/
function nanogong_print_groups($modid, $course, $groupmode, $groupid)
{
    global $USER;
    $context = get_context_instance(CONTEXT_MODULE, $modid);
    /// Now we need a menu for separategroups as well!
    if ($groupmode == VISIBLEGROUPS || $groupmode && has_capability('moodle/site:accessallgroups', $context)) {
        if ($groups = get_records_menu("groups", "courseid", $course->id, "name ASC", "id,name")) {
            ?>
    <form>
    <table cellpadding="2" cellspacing="0" border="0">
    <tr>
        <td>Please select the group:</td>
        <td>
            <select id="groupid" name="groupid" onchange="this.form.submit()">
<?php 
            if ($groupmode && has_capability('moodle/site:accessallgroups', $context)) {
                if ($groupid == 0) {
                    print "<option value=\"0\" selected>" . get_string('allparticipants') . "</option>";
                } else {
                    print "<option value=\"0\">" . get_string('allparticipants') . "</option>";
                }
            }
            foreach ($groups as $key => $value) {
                if ($key == $groupid) {
                    print "<option value=\"" . $key . "\" selected>";
                } else {
                    print "<option value=\"" . $key . "\">";
                }
                p($value);
                print "</option>";
            }
            ?>
            </select></td>
    </tr>
    </table>
    <input id="id" name="id" type="hidden" value="<?php 
            p($modid);
            ?>
" />
    </form>
<?php 
        }
    } else {
        if ($groupmode == SEPARATEGROUPS) {
            if (($groups = user_group($course->id, $USER->id)) && count($groups) > 1) {
                /// Extract the name and id for the group
                ?>
    <form>
    <table cellpadding="2" cellspacing="0" border="0">
    <tr>
        <td>Please select the group:</td>
        <td>
            <select id="groupid" name="groupid" onchange="this.form.submit()">
<?php 
                foreach ($groups as $group) {
                    if ($group->id == $groupid) {
                        print "<option value=\"" . $group->id . "\" selected>";
                    } else {
                        print "<option value=\"" . $group->id . "\">";
                    }
                    p($group->name);
                    print "</option>";
                }
                ?>
            </select></td>
    </tr>
    </table>
    <input id="id" name="id" type="hidden" value="<?php 
                p($modid);
                ?>
" />
    </form>
<?php 
            }
        }
    }
}
Ejemplo n.º 22
0
 public static function get_instance_config_options($institution, $instance = 0)
 {
     // TODO: put these strings in a lang file
     $options['/imap'] = 'IMAP';
     $options['/imap/ssl'] = 'IMAP/SSL';
     $options['/imap/ssl/novalidate-cert'] = 'IMAP/SSL (self-signed certificate)';
     $options['/imap/tls'] = 'IMAP/TLS';
     if ($instance > 0) {
         $current = get_records_array('auth_instance', 'id', $instance, 'priority ASC');
         if ($current == false) {
             throw new SystemException('Could not find data for auth instance ' . $instance);
         }
         $default = $current[0];
         $current_config = get_records_menu('auth_instance_config', 'instance', $instance, '', 'field, value');
         if ($current_config == false) {
             $current_config = array();
         }
         foreach (self::$default_config as $key => $value) {
             if (array_key_exists($key, $current_config)) {
                 self::$default_config[$key] = $current_config[$key];
             }
         }
     } else {
         $default = new stdClass();
         $default->instancename = '';
     }
     $elements['instancename'] = array('type' => 'text', 'title' => get_string('authname', 'auth'), 'rules' => array('required' => true), 'defaultvalue' => $default->instancename);
     $elements['instance'] = array('type' => 'hidden', 'value' => $instance);
     $elements['institution'] = array('type' => 'hidden', 'value' => $institution);
     $elements['authname'] = array('type' => 'hidden', 'value' => 'imap');
     $elements['host'] = array('type' => 'text', 'title' => get_string('host', 'auth'), 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['host']);
     $elements['port'] = array('type' => 'text', 'title' => get_string('port', 'auth'), 'rules' => array('required' => true, 'integer' => true), 'defaultvalue' => self::$default_config['port']);
     $elements['protocol'] = array('type' => 'select', 'title' => get_string('protocol', 'auth'), 'options' => $options, 'rules' => array('required' => true), 'defaultvalue' => self::$default_config['protocol']);
     $elements['changepasswordurl'] = array('type' => 'text', 'title' => get_string('changepasswordurl', 'auth'), 'rules' => array('required' => false), 'defaultvalue' => self::$default_config['changepasswordurl']);
     return array('elements' => $elements, 'renderer' => 'table');
 }
Ejemplo n.º 23
0
 public static function get_instance_config_options($institution, $instance = 0)
 {
     if ($instance > 0) {
         $current_config = get_records_menu('auth_instance_config', 'instance', $instance, '', 'field, value');
         if ($current_config == false) {
             $current_config = array();
         }
         foreach (self::$default_config as $key => $value) {
             if (array_key_exists($key, $current_config)) {
                 self::$default_config[$key] = $current_config[$key];
             }
         }
     }
     $elements = array('instance' => array('type' => 'hidden', 'value' => $instance), 'institution' => array('type' => 'hidden', 'value' => $institution), 'authname' => array('type' => 'hidden', 'value' => 'browserid'), 'instancename' => array('type' => 'hidden', 'value' => 'Persona'), 'authname' => array('type' => 'hidden', 'value' => 'browserid'), 'weautocreateusers' => array('type' => 'switchbox', 'title' => get_string('weautocreateusers', 'auth'), 'defaultvalue' => self::$default_config['weautocreateusers'], 'help' => true));
     return array('elements' => $elements, 'renderer' => 'div');
 }
Ejemplo n.º 24
0
/**
 * Verifies if given capability installed.
 *
 * @param string $capabilityname
 * @param bool $cached
 * @return book true if capability exists
 */
function is_valid_capability($capabilityname, $cached = true)
{
    static $capsnames = null;
    // one request per page only
    if (is_null($capsnames) or !$cached) {
        $capsnames = get_records_menu('capabilities', '', '', '', 'name, 1');
    }
    return array_key_exists($capabilityname, $capsnames);
}
Ejemplo n.º 25
0
/**
 * Must return an array of grades for a given instance of this module, 
 * indexed by user.  It also returns a maximum allowed grade.
 * 
 * Example:
 *    $return->grades = array of grades;
 *    $return->maxgrade = maximum allowed grade;
 *
 *    return $return;
 *
 * @param int $gameid ID of an instance of this module
 * @return mixed Null or object with an array of grades and with the maximum grade
 **/
function game_grades($gameid)
{
    /// Must return an array of grades, indexed by user, and a max grade.
    $game = get_record('game', 'id', intval($gameid));
    if (empty($game) || empty($game->grade)) {
        return NULL;
    }
    $return = new stdClass();
    $return->grades = get_records_menu('game_grades', 'gameid', $game->id, '', "userid, score * {$game->grade}");
    $return->maxgrade = $game->grade;
    return $return;
}
Ejemplo n.º 26
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'));
 }
Ejemplo n.º 27
0
            if ($authobj->needs_remote_username()) {
                $externalauthjs[] = $authinstance->id;
                $external = true;
            }
        }
    }
    // END OVERWRITE 2
    if (isset($options[$user->authinstance])) {
        $elements['authinstance'] = array('type' => 'select', 'title' => get_string('authenticatedby', 'admin'), 'description' => get_string('authenticatedbydescription', 'admin'), 'options' => $options, 'defaultvalue' => $user->authinstance, 'help' => true);
        $un = get_field('auth_remote_user', 'remoteusername', 'authinstance', $user->authinstance, 'localusr', $user->id);
        $elements['remoteusername'] = array('type' => 'text', 'title' => get_string('remoteusername', 'admin'), 'description' => get_string('remoteusernamedescription1', 'admin', hsc(get_config('sitename'))), 'help' => true);
        if ($un) {
            $elements['remoteusername']['defaultvalue'] = $un;
        }
    }
    $remoteusernames = json_encode(get_records_menu('auth_remote_user', 'localusr', $id));
    $js = "<script type='text/javascript'>\n          var externalauths = ['" . implode("','", $externalauthjs) . "'];\n          var remoteusernames = " . $remoteusernames . ";\n          jQuery(document).ready(function() {\n          // set up initial display\n          var authinstanceid = jQuery('#edituser_site_authinstance :selected').val();\n          is_external(authinstanceid);\n\n          // update display as auth method dropdown changes\n          jQuery('#edituser_site_authinstance').change(function() {\n              authinstanceid = jQuery('#edituser_site_authinstance :selected').val();\n              is_external(authinstanceid);\n          });\n\n          function is_external(id) {\n              if (jQuery.inArray(authinstanceid,externalauths) != -1) {\n                  // is external option so show external auth field and help text rows\n                  jQuery('#edituser_site_remoteusername_container').css('display','table-row');\n                  jQuery('#edituser_site_remoteusername_container').next('tr').css('display','table-row');\n                  if (remoteusernames[id]) {\n                      // if value exists in auth_remote_user display it\n                      jQuery('#edituser_site_remoteusername').val(remoteusernames[id]);\n}\n                  else {\n                      jQuery('#edituser_site_remoteusername').val('');\n                  }\n              }\n              else {\n                  // is internal option so hide external auth field and help text rows\n                  jQuery('#edituser_site_remoteusername_container').css('display','none');\n                  jQuery('#edituser_site_remoteusername_container').next('tr').css('display','none');\n              }\n          }\n      });\n      </script>";
    $elements['externalauthjs'] = array('type' => 'html', 'value' => $js);
}
$tags = get_column_sql('SELECT tag FROM {usr_tag} WHERE usr = ? AND NOT tag ' . db_ilike() . " 'lastinstitution:%'", array($user->id));
$elements['tags'] = array('defaultvalue' => $tags, 'type' => 'tags', 'title' => get_string('tags'), 'description' => get_string('tagsdesc'), 'help' => true);
$elements['submit'] = array('type' => 'submit', 'value' => get_string('savechanges', 'admin'));
$siteform = pieform(array('name' => 'edituser_site', 'renderer' => 'table', 'plugintype' => 'core', 'pluginname' => 'admin', 'elements' => $elements));
function edituser_site_validate(Pieform $form, $values)
{
    global $USER, $SESSION;
    if (!($user = get_record('usr', 'id', $values['id']))) {
        return false;
    }
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        $maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled');
Ejemplo n.º 28
0
/**
 * Function called during delete course routines to do any necessary cleanup
 *
 * @param int $courseid ID of the course being deleted
 **/
function page_delete_course($courseid)
{
    $pageids = get_records_menu('format_page', 'courseid', $courseid, '', 'id, nameone');
    if (!empty($pageids)) {
        $pagekeys = array_keys($pageids);
        delete_records_select('format_page_items', 'pageid IN (' . implode(', ', $pagekeys) . ')');
        delete_records_select('format_page', 'id IN (' . implode(', ', $pagekeys) . ')');
    }
}
Ejemplo n.º 29
0
 function definition()
 {
     global $CFG, $COURSE;
     $mform =& $this->_form;
     $glossary =& $this->_customdata['glossary'];
     $mode =& $this->_customdata['mode'];
     $cm =& $this->_customdata['cm'];
     $hook =& $this->_customdata['hook'];
     $e =& $this->_customdata['e'];
     //-------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     $mform->addElement('text', 'concept', get_string('concept', 'glossary'));
     $mform->setType('concept', PARAM_TEXT);
     $mform->addRule('concept', null, 'required', null, 'client');
     $mform->addElement('htmleditor', 'definition', get_string('definition', 'glossary'), array('rows' => 20));
     $mform->setType('definition', PARAM_RAW);
     $mform->addRule('definition', null, 'required', null, 'client');
     $mform->setHelpButton('definition', array('writing', 'richtext'), false, 'editorhelpbutton');
     $mform->addElement('format');
     $categories = array();
     if ($categories = get_records_menu('glossary_categories', 'glossaryid', $glossary->id, 'name ASC', 'id, name')) {
         $categories = array(0 => get_string('notcategorised', 'glossary')) + $categories;
     } else {
         $categories = array(0 => get_string('notcategorised', 'glossary'));
     }
     $categoriesEl =& $mform->addElement('select', 'categories', get_string('categories', 'glossary'), $categories);
     $categoriesEl->setMultiple(true);
     $categoriesEl->setSize(5);
     $mform->addElement('textarea', 'aliases', get_string('aliases', 'glossary'), 'rows="2" cols="40"');
     $mform->setType('aliases', PARAM_TEXT);
     $mform->setHelpButton('aliases', array('aliases2', strip_tags(get_string('aliases', 'glossary')), 'glossary'));
     $this->set_upload_manager(new upload_manager('attachment', true, false, $COURSE, false, 0, true, true, false));
     $mform->addElement('file', 'attachment', get_string('attachment', 'forum'));
     $mform->setHelpButton('attachment', array('attachment', get_string('attachment', 'glossary'), 'glossary'));
     if (isset($CFG->glossary_linkentries)) {
         $usedynalink = $CFG->glossary_linkentries;
     } else {
         $usedynalink = 0;
     }
     if (isset($CFG->glossary_casesensitive)) {
         $casesensitive = $CFG->glossary_casesensitive;
     } else {
         $casesensitive = 0;
     }
     if (isset($CFG->glossary_fullmatch)) {
         $fullmatch = $CFG->glossary_fullmatch;
     } else {
         $fullmatch = 0;
     }
     if (!$glossary->usedynalink) {
         $mform->addElement('hidden', 'usedynalink', $usedynalink);
         $mform->setType('usedynalink', PARAM_INT);
         $mform->addElement('hidden', 'casesensitive', $casesensitive);
         $mform->setType('casesensitive', PARAM_INT);
         $mform->addElement('hidden', 'fullmatch', $fullmatch);
         $mform->setType('fullmatch', PARAM_INT);
     } else {
         //-------------------------------------------------------------------------------
         $mform->addElement('header', 'linkinghdr', get_string('linking', 'glossary'));
         $mform->addElement('checkbox', 'usedynalink', get_string('entryusedynalink', 'glossary'));
         $mform->setHelpButton('usedynalink', array('usedynalinkentry', strip_tags(get_string('usedynalink', 'glossary')), 'glossary'));
         $mform->setDefault('usedynalink', $usedynalink);
         $mform->addElement('checkbox', 'casesensitive', get_string('casesensitive', 'glossary'));
         $mform->setHelpButton('casesensitive', array('casesensitive', strip_tags(get_string('casesensitive', 'glossary')), 'glossary'));
         $mform->disabledIf('casesensitive', 'usedynalink');
         $mform->setDefault('casesensitive', $casesensitive);
         $mform->addElement('checkbox', 'fullmatch', get_string('fullmatch', 'glossary'));
         $mform->setHelpButton('fullmatch', array('fullmatch', strip_tags(get_string('fullmatch', 'glossary')), 'glossary'));
         $mform->disabledIf('fullmatch', 'usedynalink');
         $mform->setDefault('fullmatch', $fullmatch);
     }
     $mform->addElement('hidden', 'e', $e);
     $mform->setType('e', PARAM_INT);
     $mform->addElement('hidden', 'id', $cm->id);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'mode', $mode);
     $mform->setType('mode', PARAM_ALPHA);
     $mform->addElement('hidden', 'hook', $hook);
     $mform->setType('hook', PARAM_ALPHANUM);
     //-------------------------------------------------------------------------------
     $this->add_action_buttons();
 }
Ejemplo n.º 30
0
/**
 * Print groupmode form element on module setup forms in mod/.../mod.html
 */
function print_grouping_settings($form, $course = NULL)
{
    if (empty($course)) {
        if (!($course = get_record('course', 'id', $form->course))) {
            error("This course doesn't exist");
        }
    }
    if ($form->coursemodule) {
        if (!($cm = get_record('course_modules', 'id', $form->coursemodule))) {
            error("This course module doesn't exist");
        }
    } else {
        $cm = null;
    }
    $groupings = get_records_menu('groupings', 'courseid', $course->id, 'name', 'id, name');
    if (!empty($groupings)) {
        echo '<tr valign="top">';
        echo '<td align="right"><b>' . get_string('grouping', 'group') . ':</b></td>';
        echo '<td align="left">';
        $groupings;
        $groupingid = isset($cm->groupingid) ? $cm->groupingid : 0;
        choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
        echo '</td></tr>';
        $checked = empty($cm->groupmembersonly) ? '' : 'checked="checked"';
        echo '<tr valign="top">';
        echo '<td align="right"><b>' . get_string('groupmembersonly', 'group') . ':</b></td>';
        echo '<td align="left">';
        echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" {$checked} />";
        echo '</td></tr>';
    }
}