MDL-21782 reworked enrolment framework, the core infrastructure is in place, the basic plugins are all implemented; see the tracker issue for list of unfinished bits, expect more changes and improvements during the next week

AMOS START
    MOV [sendcoursewelcomemessage,core_admin],[sendcoursewelcomemessage,enrol_self]
    MOV [configsendcoursewelcomemessage,core_admin],[sendcoursewelcomemessage_desc,enrol_self]
    MOV [enrolstartdate,core],[enrolstartdate,enrol_self]
    MOV [enrolenddate,core],[enrolenddate,enrol_self]
    CPY [welcometocourse,core],[welcometocourse,enrol_self]
    CPY [welcometocoursetext,core],[welcometocoursetext,enrol_self]
    MOV [notenrollable,core],[notenrollable,core_enrol]
    MOV [enrolenddaterror,core],[enrolenddaterror,enrol_self]
    MOV [enrolmentkeyhint,core],[passwordinvalidhint,enrol_self]
    MOV [coursemanager,core_admin],[coursecontact,core_admin]
    MOV [configcoursemanager,core_admin],[coursecontact_desc,core_admin]
    MOV [enrolledincourserole,core],[enrolledincourserole,enrol_manual]
    MOV [enrolme,core],[enrolme,core_enrol]
    MOV [unenrol,core],[unenrol,core_enrol]
    MOV [unenrolme,core],[unenrolme,core_enrol]
    MOV [enrolmentnew,core],[enrolmentnew,core_enrol]
    MOV [enrolmentnewuser,core],[enrolmentnewuser,core_enrol]
    MOV [enrolments,core],[enrolments,core_enrol]
    MOV [enrolperiod,core],[enrolperiod,core_enrol]
    MOV [unenrolroleusers,core],[unenrolroleusers,core_enrol]
AMOS END
This commit is contained in:
Petr Skoda 2010-06-21 15:30:49 +00:00
parent 2c9bb9c327
commit df997f841f
225 changed files with 11062 additions and 7646 deletions

View File

@ -48,7 +48,7 @@ if ($CFG->bloglevel == BLOG_COURSE_LEVEL || $CFG->bloglevel == BLOG_GROUP_LEVEL)
$a->blogcount = 0;
foreach ($bloggers as $blogger) {
$courses = get_my_courses($blogger->userid);
$courses = enrol_get_users_courses($blogger->userid, true, 'groupmode,groupmodeforce');
$blogentries = $DB->get_records('post', array('module' => 'blog', 'userid' => $blogger->userid));
foreach ($courses as $course) {

View File

@ -205,34 +205,6 @@
}
mtrace('Finished admin reports');
mtrace('Removing expired enrolments ...', ''); // See MDL-8785
$timenow = time();
$somefound = false;
// The preferred way saves memory, datablib
// find courses where limited enrolment is enabled
$sql = "SELECT ra.roleid, ra.userid, ra.contextid
FROM {course} c
JOIN {context} cx ON cx.instanceid = c.id
JOIN {role_assignments} ra ON ra.contextid = cx.id
WHERE cx.contextlevel = '".CONTEXT_COURSE."'
AND ra.timeend > 0
AND ra.timeend < ?
AND c.enrolperiod > 0";
if ($rs = $DB->get_recordset_sql($sql, array($timenow))) {
foreach ($rs as $oldenrolment) {
role_unassign($oldenrolment->roleid, $oldenrolment->userid, 0, $oldenrolment->contextid);
$somefound = true;
}
$rs->close();
}
if ($somefound) {
mtrace('Done');
} else {
mtrace('none found');
}
mtrace('Starting main gradebook job ...');
grade_cron();
mtrace('done.');
@ -270,41 +242,6 @@
if ($random100 < 20) { // Approximately 20% of the time.
mtrace("Running clean-up tasks...");
/// Unenrol users who haven't logged in for $CFG->longtimenosee
if ($CFG->longtimenosee) { // value in days
$cuttime = $timenow - ($CFG->longtimenosee * 3600 * 24);
$rs = $DB->get_recordset_sql ("SELECT id, userid, courseid
FROM {user_lastaccess}
WHERE courseid != ".SITEID."
AND timeaccess < ?", array($cuttime));
foreach ($rs as $assign) {
if ($context = get_context_instance(CONTEXT_COURSE, $assign->courseid)) {
if (role_unassign(0, $assign->userid, 0, $context->id)) {
mtrace("removing user $assign->userid from course $assign->courseid as they have not accessed the course for over $CFG->longtimenosee days");
}
}
}
$rs->close();
/// Execute the same query again, looking for remaining records and deleting them
/// if the user hasn't moodle/course:participate in the CONTEXT_COURSE context (orphan records)
$rs = $DB->get_recordset_sql ("SELECT id, userid, courseid
FROM {user_lastaccess}
WHERE courseid != ".SITEID."
AND timeaccess < ?", array($cuttime));
foreach ($rs as $assign) {
if ($context = get_context_instance(CONTEXT_COURSE, $assign->courseid)) {
if (!is_enrolled($context, $assign->userid) and !is_viewing($context, $assign->userid)) {
$DB->delete_records('user_lastaccess', array('userid'=>$assign->userid, 'courseid'=>$assign->courseid));
mtrace("Deleted orphan user_lastaccess for user $assign->userid from course $assign->courseid");
}
}
}
$rs->close();
}
flush();
/// Delete users who haven't confirmed within required period
if (!empty($CFG->deleteunconfirmed)) {
@ -370,9 +307,6 @@
}
flush();
sync_metacourses();
mtrace('Synchronised metacourses');
//
// generate new password emails for users
//
@ -464,20 +398,16 @@
unset($authplugin);
}
/// Run the enrolment cron, if any
if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
$plugins = array($CFG->enrol);
}
require_once($CFG->dirroot .'/enrol/enrol.class.php');
foreach ($plugins as $p) {
$enrol = enrolment_factory::factory($p);
if (method_exists($enrol, 'cron')) {
$enrol->cron();
mtrace("Running enrol crons if required...");
$enrols = enrol_get_plugins(true);
foreach($enrols as $ename=>$enrol) {
// do this for all plugins, disabled plugins might want to cleanup stuff such as roles
if (!$enrol->is_cron_required()) {
continue;
}
if (!empty($enrol->log)) {
mtrace($enrol->log);
}
unset($enrol);
mtrace("Running cron for enrol_$ename...");
$enrol->cron();
$enrol->set_config('lastcron', time());
}
if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {

View File

@ -1,141 +1,120 @@
<?php
// enrol.php - allows admin to edit all enrollment variables
// Yes, enrol is correct English spelling.
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once('../config.php');
require_once($CFG->libdir.'/adminlib.php');
/**
* Enrol config manipulation script.
*
* @package core
* @subpackage enrol
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$enrol = optional_param('enrol', $CFG->enrol, PARAM_SAFEDIR);
$savesettings = optional_param('savesettings', 0, PARAM_BOOL);
require_once('../config.php');
require_once($CFG->libdir.'/adminlib.php');
admin_externalpage_setup('enrolment');
$action = required_param('action', PARAM_ACTION);
$enrol = required_param('enrol', PARAM_SAFEDIR);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
if (!isset($CFG->sendcoursewelcomemessage)) {
set_config('sendcoursewelcomemessage', 1);
}
$PAGE->set_url('/admin/enrol.php');
require_login();
require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM));
require_sesskey();
require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class
$enabled = enrol_get_plugins(true);
$all = enrol_get_plugins(false);
/// Save settings
$return = new moodle_url('/admin/settings.php', array('section'=>'manageenrols'));
if ($frm = data_submitted() and !$savesettings) {
if (!confirm_sesskey()) {
print_error('confirmsesskeybad', 'error');
switch ($action) {
case 'disable':
unset($enabled[$enrol]);
set_config('enrol_plugins_enabled', implode(',', array_keys($enabled)));
break;
case 'enable':
if (!isset($all[$enrol])) {
break;
}
if (empty($frm->enable)) {
$frm->enable = array();
$enabled = array_keys($enabled);
$enabled[] = $enrol;
set_config('enrol_plugins_enabled', implode(',', $enabled));
break;
case 'up':
if (!isset($enabled[$enrol])) {
break;
}
if (empty($frm->default)) {
$frm->default = '';
$enabled = array_keys($enabled);
$enabled = array_flip($enabled);
$current = $enabled[$enrol];
if ($current == 0) {
break; //already at the top
}
if ($frm->default && $frm->default != 'manual' && !in_array($frm->default, $frm->enable)) {
$frm->enable[] = $frm->default;
$enabled = array_flip($enabled);
$enabled[$current] = $enabled[$current - 1];
$enabled[$current - 1] = $enrol;
set_config('enrol_plugins_enabled', implode(',', $enabled));
break;
case 'down':
if (!isset($enabled[$enrol])) {
break;
}
asort($frm->enable);
$frm->enable = array_merge(array('manual'), $frm->enable); // make sure manual plugin is called first
set_config('enrol_plugins_enabled', implode(',', $frm->enable));
set_config('enrol', $frm->default);
redirect("enrol.php", get_string("changessaved"), 1);
} else if ($frm = data_submitted() and $savesettings) {
if (!confirm_sesskey()) {
print_error('confirmsesskeybad', 'error');
$enabled = array_keys($enabled);
$enabled = array_flip($enabled);
$current = $enabled[$enrol];
if ($current == count($enabled) - 1) {
break; //already at the end
}
set_config('sendcoursewelcomemessage', required_param('sendcoursewelcomemessage', PARAM_BOOL));
}
$enabled = array_flip($enabled);
$enabled[$current] = $enabled[$current + 1];
$enabled[$current + 1] = $enrol;
set_config('enrol_plugins_enabled', implode(',', $enabled));
break;
/// Print the form
case 'uninstall':
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('enrolments', 'enrol'));
$str = get_strings(array('enrolmentplugins', 'users', 'administration', 'settings', 'edit'));
echo $OUTPUT->header();
$modules = get_plugin_list('enrol');
$options = array();
foreach ($modules as $module => $moduledir) {
$options[$module] = get_string("enrolname", "enrol_$module");
}
asort($options);
echo $OUTPUT->box(get_string('configenrolmentplugins', 'admin'));
echo "<form id=\"enrolmenu\" method=\"post\" action=\"enrol.php\">";
echo "<div>";
echo "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />";
$table = new html_table();
$table->head = array(get_string('name'), get_string('enable'), get_string('default'), $str->settings);
$table->align = array('left', 'center', 'center', 'center');
$table->size = array('60%', '', '', '15%');
$table->attributes['class'] = 'generaltable enrolplugintable';
$table->data = array();
$enabledplugins = explode(',', $CFG->enrol_plugins_enabled);
foreach ($modules as $module => $moduledir) {
// skip if directory is empty
if (!file_exists("$moduledir/enrol.php")) {
continue;
}
$name = get_string("enrolname", "enrol_$module");
$plugin = enrolment_factory::factory($module);
$enable = '<input type="checkbox" name="enable[]" value="'.$module.'"';
if (in_array($module, $enabledplugins)) {
$enable .= ' checked="checked"';
}
if ($module == 'manual') {
$enable .= ' disabled="disabled"';
}
$enable .= ' />';
if (method_exists($plugin, 'print_entry')) {
$default = '<input type="radio" name="default" value="'.$module.'"';
if ($CFG->enrol == $module) {
$default .= ' checked="checked"';
}
$default .= ' />';
if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
$strplugin = get_string('pluginname', 'enrol_'.$enrol);
} else {
$default = '';
$strplugin = $enrol;
}
$table->data[$name] = array($name, $enable, $default,
'<a href="enrol_config.php?enrol='.$module.'">'.$str->edit.'</a>');
}
asort($table->data);
echo html_writer::table($table);
if (!$confirm) {
$uurl = new moodle_url('/admin/enrol.php', array('action'=>'uninstall', 'enrol'=>$enrol, 'sesskey'=>sesskey(), 'confirm'=>1));
echo $OUTPUT->confirm(get_string('uninstallconfirm', 'enrol', $strplugin), $uurl, $return);
echo $OUTPUT->footer();
exit;
echo "<div style=\"text-align:center\"><input type=\"submit\" value=\"".get_string("savechanges")."\" /></div>\n";
echo "</div>";
echo "</form>";
} else { // Delete everything!!
uninstall_plugin('enrol', $enrol);
echo '<hr />';
$yesnooptions = array(0=>get_string('no'), 1=>get_string('yes'));
echo '<form id="adminsettings" method="post" action="enrol.php">';
echo '<div class="settingsform clearfix">';
echo $OUTPUT->heading(get_string('commonsettings', 'admin'));
echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
echo '<input type="hidden" name="savesettings" value="1" />';
echo '<fieldset>';
echo '<div class="form-item clearfix" id="admin-sendcoursewelcomemessage">';
echo '<div class="form-label"><label for = "menusendcoursewelcomemessage">' . get_string('sendcoursewelcomemessage', 'admin');
echo '<span class="form-shortname">sendcoursewelcomemessage</span>';
echo '</label></div>';
echo '<div class="form-setting"><div class="form-checkbox defaultsnext">';
echo html_writer::select($yesnooptions, 'sendcoursewelcomemessage', $CFG->sendcoursewelcomemessage, false);
echo '</div><div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', get_string('yes')).'</div></div>';
echo '<div class="form-description">' . get_string('configsendcoursewelcomemessage', 'admin') . '</div>';
echo '</div>';
echo '</fieldset>';
echo '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges', 'admin').'" /></div>';
echo '</div>';
echo '</form>';
echo $OUTPUT->footer();
$a->plugin = $strplugin;
$a->directory = "$CFG->dirroot/enrol/$enrol";
echo $OUTPUT->notification(get_string('uninstalldeletefiles', 'enrol', $a), 'notifysuccess');
echo $OUTPUT->continue_button($return);
echo $OUTPUT->footer();
exit;
}
}
redirect($return);

View File

@ -1,70 +0,0 @@
<?php
// enrol_config.php - allows admin to edit all enrollment variables
// Yes, enrol is correct English spelling.
require_once("../config.php");
require_once($CFG->libdir.'/adminlib.php');
admin_externalpage_setup('enrolment');
$enrol = required_param('enrol', PARAM_ALPHA);
$PAGE->set_pagetype('admin-enrol-' . $enrol);
require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class
$enrolment = enrolment_factory::factory($enrol);
/// If data submitted, then process and store.
if ($frm = data_submitted()) {
if (!confirm_sesskey()) {
print_error('confirmsesskeybad', 'error');
}
if ($enrolment->process_config($frm)) {
redirect("enrol.php?sesskey=".sesskey(), get_string("changessaved"), 1);
}
} else {
$frm = $CFG;
}
/// Otherwise fill and print the form.
/// get language strings
$str = get_strings(array('enrolmentplugins', 'configuration', 'users', 'administration'));
unset($options);
$modules = get_plugin_list('enrol');
foreach ($modules as $module => $enroldir) {
$options[$module] = get_string("enrolname", "enrol_$module");
}
asort($options);
echo $OUTPUT->header();
echo "<form id=\"enrolmenu\" method=\"post\" action=\"enrol_config.php\">";
echo "<div>";
echo "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />";
echo "<input type=\"hidden\" name=\"enrol\" value=\"".$enrol."\" />";
/// Print current enrolment type description
echo $OUTPUT->box_start();
echo $OUTPUT->heading($options[$enrol]);
echo $OUTPUT->box_start('informationbox');
print_string("description", "enrol_$enrol");
echo $OUTPUT->box_end();
echo "<hr />";
$enrolment->config_form($frm);
echo "<p class=\"centerpara\"><input type=\"submit\" value=\"".get_string("savechanges")."\" /></p>\n";
echo $OUTPUT->box_end();
echo "</div>";
echo "</form>";
echo $OUTPUT->footer();
exit;

View File

@ -709,23 +709,16 @@ class generator {
$context = get_context_instance(CONTEXT_COURSE, $courseid);
foreach ($users_to_assign as $random_user) {
$success = role_assign(5, $random_user, 0, $context->id);
role_assign(5, $random_user, $context->id);
if ($success) {
$assigned_count++;
$course_users[$courseid][] = $random_user;
if (!isset($assigned_users[$random_user])) {
$assigned_users[$random_user] = 1;
} else {
$assigned_users[$random_user]++;
}
$this->verbose("Student $random_user was assigned to course $courseid.");
$assigned_count++;
$course_users[$courseid][] = $random_user;
if (!isset($assigned_users[$random_user])) {
$assigned_users[$random_user] = 1;
} else {
$this->verbose("Could not assign student $random_user to course $courseid!");
if (!$this->get('ignore_errors')) {
die();
}
$assigned_users[$random_user]++;
}
$this->verbose("Student $random_user was assigned to course $courseid.");
}
}

View File

@ -1,7 +1,9 @@
<?PHP
// enrol_config.php - allows admin to edit all enrollment variables
// enrol_config.php - allows admin to edit all enrolment variables
// Yes, enrol is correct English spelling.
die('TODO: MDL-22787 mnet enrolments are not reimplemented yet, sorry.');
require_once(dirname(__FILE__) . "/../../config.php");
require_once($CFG->libdir.'/adminlib.php');
include_once($CFG->dirroot.'/mnet/xmlrpc/client.php');
@ -12,8 +14,7 @@
admin_externalpage_setup('mnetenrol');
require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class
$enrolment = enrolment_factory::factory('mnet');
$enrolment = enrol_get_plugin('mnet');
$mnethostid = required_param('host', PARAM_INT);
$courseid = required_param('courseid', PARAM_INT);
@ -278,7 +279,7 @@
/// Print the page
/// get language strings
$str = get_strings(array('enrolmentplugins', 'configuration', 'users', 'administration'));
$str = get_strings(array('configuration', 'users', 'administration'));
/// Get some language strings
$strpotentialusers = get_string('potentialusers', 'role');

View File

@ -1,7 +1,9 @@
<?PHP
// enrol_config.php - allows admin to edit all enrollment variables
// enrol_config.php - allows admin to edit all enrolment variables
// Yes, enrol is correct English spelling.
die('TODO: ment enrolments are not reimplemented yet, sorry.');
require_once(dirname(__FILE__) . "/../../config.php");
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->dirroot.'/mnet/lib.php');
@ -13,8 +15,7 @@
admin_externalpage_setup('mnetenrol');
require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class
$enrolment = enrolment_factory::factory('mnet');
$enrolment = enrol_get_plugin('mnet');
$mnethost = required_param('host', PARAM_INT);
$host = $DB->get_record('mnet_host', array('id'=>$mnethost));

View File

@ -6,11 +6,11 @@
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->dirroot.'/mnet/lib.php');
die('TODO: MDL-22787 mnet enrolments are not reimplemented yet, sorry.');
admin_externalpage_setup('mnetenrol');
require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class
$enrolment = enrolment_factory::factory('mnet');
$enrolment = enrol_get_plugin('mnet');
/// Otherwise fill and print the form.

View File

@ -35,24 +35,6 @@ $string['check_cookiesecure_details'] = '<p>If you enable https communication it
$string['check_cookiesecure_error'] = 'Please enable secure cookies';
$string['check_cookiesecure_name'] = 'Secure cookies';
$string['check_cookiesecure_ok'] = 'Secure cookies enabled.';
$string['check_courserole_anything'] = 'The "doanything" capability must not be allowed in this <a href="{$a}">context</a>.';
$string['check_courserole_details'] = '<p>Each course has one default enrolment role specified. Please make sure no risky capabilities are allowed for this role.</p>
<p>The only supported legacy type for the default course role is <em>Student</em>.</p>';
$string['check_courserole_error'] = 'Incorrectly defined default course roles detected!';
$string['check_courserole_name'] = 'Default roles (courses)';
$string['check_courserole_notyet'] = 'Used only default course role.';
$string['check_courserole_ok'] = 'Default course role definitions is OK.';
$string['check_courserole_risky'] = 'Risky capabilities detected in <a href="{$a}">context</a>.';
$string['check_courserole_riskylegacy'] = 'Risky legacy type detected in <a href="{$a->url}">{$a->shortname}</a>.';
$string['check_defaultcourserole_anything'] = 'The "doanything" capability must not be allowed in this <a href="{$a}">context</a>.';
$string['check_defaultcourserole_details'] = '<p>The default student role for course enrolment specifies the default role for courses. Please make sure no risky capabilities are allowed in this role.</p>
<p>The only supported legacy type for default role is <em>Student</em>.</p>';
$string['check_defaultcourserole_error'] = 'Incorrectly defined default course role "{$a}" detected!';
$string['check_defaultcourserole_legacy'] = 'Risky legacy type detected.';
$string['check_defaultcourserole_name'] = 'Default course role (global)';
$string['check_defaultcourserole_notset'] = 'Default role is not set.';
$string['check_defaultcourserole_ok'] = 'Site default role definition is OK.';
$string['check_defaultcourserole_risky'] = 'Risky capabilities detected in <a href="{$a}">context</a>.';
$string['check_defaultuserrole_details'] = '<p>All logged in users are given capabilities of the default user role. Please make sure no risky capabilities are allowed in this role.</p>
<p>The only supported legacy type for the default user role is <em>Authenticated user</em>. The course view capability must not be enabled.</p>';
$string['check_defaultuserrole_error'] = 'The default user role "{$a}" is incorrectly defined!';

View File

@ -58,8 +58,6 @@ function report_security_get_issue_list() {
'report_security_check_defaultuserrole',
'report_security_check_guestrole',
'report_security_check_frontpagerole',
'report_security_check_defaultcourserole',
'report_security_check_courserole',
);
}
@ -587,9 +585,6 @@ function report_security_check_defaultuserrole($detailed=false) {
$riskycount = $DB->count_records_sql($sql, $params);
// default role can not have view cap in all courses - this would break moodle badly
$viewcap = $DB->record_exists('role_capabilities', array('roleid'=>$default_role->id, 'permission'=>CAP_ALLOW, 'capability'=>'moodle/course:participate'));
// it may have either none or 'user' archetype - nothing else, or else it would break during upgrades badly
if ($default_role->archetype === '' or $default_role->archetype === 'user') {
$legacyok = true;
@ -597,7 +592,7 @@ function report_security_check_defaultuserrole($detailed=false) {
$legacyok = false;
}
if ($riskycount or $viewcap or !$legacyok) {
if ($riskycount or !$legacyok) {
$result->status = REPORT_SECURITY_CRITICAL;
$result->info = get_string('check_defaultuserrole_error', 'report_security', format_string($default_role->name));
@ -730,190 +725,6 @@ function report_security_check_frontpagerole($detailed=false) {
return $result;
}
/**
* Verifies sanity of site default course role.
* @param bool $detailed
* @return object result
*/
function report_security_check_defaultcourserole($detailed=false) {
global $DB, $CFG;
$problems = array();
$result = new object();
$result->issue = 'report_security_check_defaultcourserole';
$result->name = get_string('check_defaultcourserole_name', 'report_security');
$result->info = null;
$result->details = null;
$result->status = null;
$result->link = "<a href=\"$CFG->wwwroot/$CFG->admin/settings.php?section=userpolicies\">".get_string('userpolicies', 'admin').'</a>';;
if ($detailed) {
$result->details = get_string('check_defaultcourserole_details', 'report_security');
}
if (!$student_role = $DB->get_record('role', array('id'=>$CFG->defaultcourseroleid))) {
$result->status = REPORT_SECURITY_WARNING;
$result->info = get_string('check_defaultcourserole_notset', 'report_security');
$result->details = get_string('check_defaultcourserole_details', 'report_security');
return $result;
}
// risky caps - usually very dangerous
$params = array('capallow'=>CAP_ALLOW, 'roleid'=>$student_role->id);
$sql = "SELECT DISTINCT rc.contextid
FROM {role_capabilities} rc
JOIN {capabilities} cap ON cap.name = rc.capability
WHERE ".$DB->sql_bitand('cap.riskbitmask', (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))." <> 0
AND rc.permission = :capallow
AND rc.roleid = :roleid";
if ($riskycontexts = $DB->get_records_sql($sql, $params)) {
foreach($riskycontexts as $contextid=>$unused) {
if ($contextid == SYSCONTEXTID) {
$a = "$CFG->wwwroot/$CFG->admin/roles/define.php?action=view&amp;roleid=$CFG->defaultcourseroleid";
} else {
$a = "$CFG->wwwroot/$CFG->admin/roles/override.php?contextid=$contextid&amp;roleid=$CFG->defaultcourseroleid";
}
$problems[] = get_string('check_defaultcourserole_risky', 'report_security', $a);
}
}
// course creator or administrator does not make any sense here
if ($student_role->archetype === 'coursecreator' or $student_role->archetype === 'manager') {
$problems[] = get_string('check_defaultcourserole_legacy', 'report_security');
}
if ($problems) {
$result->status = REPORT_SECURITY_CRITICAL;
$result->info = get_string('check_defaultcourserole_error', 'report_security', format_string($student_role->name));
if ($detailed) {
$result->details .= "<ul>";
foreach ($problems as $problem) {
$result->details .= "<li>$problem</li>";
}
$result->details .= "</ul>";
}
} else {
$result->status = REPORT_SECURITY_OK;
$result->info = get_string('check_defaultcourserole_ok', 'report_security');
}
return $result;
}
/**
* Verifies sanity of default roles in courses.
* @param bool $detailed
* @return object result
*/
function report_security_check_courserole($detailed=false) {
global $DB, $CFG, $SITE;
$problems = array();
$result = new object();
$result->issue = 'report_security_check_courserole';
$result->name = get_string('check_courserole_name', 'report_security');
$result->info = null;
$result->details = null;
$result->status = null;
$result->link = null;
if ($detailed) {
$result->details = get_string('check_courserole_details', 'report_security');
}
// get list of all student roles selected in courses excluding the default course role
$params = array('siteid'=>$SITE->id, 'defaultcourserole'=>$CFG->defaultcourseroleid);
$sql = "SELECT r.*
FROM {role} r
JOIN {course} c ON c.defaultrole = r.id
WHERE c.id <> :siteid AND r.id <> :defaultcourserole";
if (!$student_roles = $DB->get_records_sql($sql, $params)) {
$result->status = REPORT_SECURITY_OK;
$result->info = get_string('check_courserole_notyet', 'report_security');
$result->details = get_string('check_courserole_details', 'report_security');
return $result;
}
$roleids = array_keys($student_roles);
$sql = "SELECT DISTINCT rc.roleid
FROM {role_capabilities} rc
JOIN {role} r ON r.id = rc.roleid
WHERE (r.archetype = :coursecreator OR r.archetype = :teacher OR r.archetype = :editingteacher OR r.archetype = :manager)";
$params = array('coursecreator' => 'coursecreator',
'teacher' => 'teacher',
'editingteacher' => 'editingteacher',
'manager' => 'manager');
$riskyroleids = $DB->get_records_sql($sql, $params);
$riskyroleids = array_keys($riskyroleids);
// any XSS legacy cap does not make any sense here!
list($inroles, $params) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED, 'r0', true);
$sql = "SELECT DISTINCT c.id, c.shortname
FROM {course} c
WHERE c.defaultrole $inroles
ORDER BY c.sortorder";
if ($courses = $DB->get_records_sql($sql, $params)) {
foreach ($courses as $course) {
$a = (object)array('url'=>"$CFG->wwwroot/course/edit.php?id=$course->id", 'shortname'=>$course->shortname);
$problems[] = get_string('check_courserole_riskylegacy', 'report_security', $a);
}
}
// risky caps in any level - usually very dangerous!!
if ($checkroles = array_diff($roleids, $riskyroleids)) {
list($inroles, $params) = $DB->get_in_or_equal($checkroles, SQL_PARAMS_NAMED, 'r0', true);
$params = array_merge($params, array('capallow'=>CAP_ALLOW));
$sql = "SELECT rc.roleid, rc.contextid
FROM {role_capabilities} rc
JOIN {capabilities} cap ON cap.name = rc.capability
WHERE ".$DB->sql_bitand('cap.riskbitmask', (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))." <> 0
AND rc.permission = :capallow
AND rc.roleid $inroles
GROUP BY rc.roleid, rc.contextid
ORDER BY rc.roleid, rc.contextid";
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $res) {
$roleid = $res->roleid;
$contextid = $res->contextid;
if ($contextid == SYSCONTEXTID) {
$a = "$CFG->wwwroot/$CFG->admin/roles/define.php?action=view&amp;roleid=$roleid";
} else {
$a = "$CFG->wwwroot/$CFG->admin/roles/override.php?contextid=$contextid&amp;roleid=$roleid";
}
$problems[] = get_string('check_courserole_risky', 'report_security', $a);
}
$rs->close();
}
if ($problems) {
$result->status = REPORT_SECURITY_CRITICAL;
$result->info = get_string('check_courserole_error', 'report_security');
if ($detailed) {
$result->details .= "<ul>";
foreach ($problems as $problem) {
$result->details .= "<li>$problem</li>";
}
$result->details .= "</ul>";
}
} else {
$result->status = REPORT_SECURITY_OK;
$result->info = get_string('check_courserole_ok', 'report_security');
}
return $result;
}
/**
* Lists all admins.
* @param bool $detailed

View File

@ -31,8 +31,6 @@ define("MAX_USERS_TO_LIST_PER_ROLE", 10);
$contextid = required_param('contextid',PARAM_INT);
$roleid = optional_param('roleid', 0, PARAM_INT);
$extendperiod = optional_param('extendperiod', 0, PARAM_INT);
$extendbase = optional_param('extendbase', 3, PARAM_INT);
list($context, $course, $cm) = get_context_info_array($contextid);
@ -58,7 +56,6 @@ $PAGE->set_context($context);
$contextname = print_context_name($context);
$courseid = $course->id;
$inmeta = $course->metacourse;
$isfrontpage = ($course->id == SITEID);
// These are needed early because of tabs.php
@ -87,40 +84,6 @@ if ($roleid) {
}
}
// Build the list of options for the enrolment period dropdown.
$unlimitedperiod = get_string('unlimited');
for ($i=1; $i<=365; $i++) {
$seconds = $i * 86400;
$periodmenu[$seconds] = get_string('numdays', '', $i);
}
// Work out the apropriate default setting.
if ($extendperiod) {
$defaultperiod = $extendperiod;
} else {
$defaultperiod = $course->enrolperiod;
}
// Build the list of options for the starting from dropdown.
$timeformat = get_string('strftimedatefullshort');
$today = time();
$today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
// MDL-12420, preventing course start date showing up as an option at system context and front page roles.
if ($course->startdate > 0) {
$basemenu[2] = get_string('coursestart') . ' (' . userdate($course->startdate, $timeformat) . ')';
}
if ($course->enrollable != 2 || ($course->enrolstartdate == 0 || $course->enrolstartdate <= $today) && ($course->enrolenddate == 0 || $course->enrolenddate > $today)) {
$basemenu[3] = get_string('today') . ' (' . userdate($today, $timeformat) . ')' ;
}
if ($course->enrollable == 2) {
if($course->enrolstartdate > 0) {
$basemenu[4] = get_string('courseenrolstart') . ' (' . userdate($course->enrolstartdate, $timeformat) . ')';
}
if($course->enrolenddate > 0) {
$basemenu[5] = get_string('courseenrolend') . ' (' . userdate($course->enrolenddate, $timeformat) . ')';
}
}
// Process any incoming role assignments before printing the header.
if ($roleid) {
@ -138,46 +101,9 @@ if ($roleid) {
foreach ($userstoassign as $adduser) {
$allow = true;
if ($inmeta) {
if (has_capability('moodle/course:managemetacourse', $context, $adduser->id)) {
//ok
} else {
$managerroles = get_roles_with_capability('moodle/course:managemetacourse', CAP_ALLOW, $context);
if (!empty($managerroles) and !array_key_exists($roleid, $managerroles)) {
$erruser = $DB->get_record('user', array('id'=>$adduser->id), 'id, firstname, lastname');
$errors[] = get_string('metaassignerror', 'role', fullname($erruser));
$allow = false;
}
}
}
if ($allow) {
switch($extendbase) {
case 2:
$timestart = $course->startdate;
break;
case 3:
$timestart = $today;
break;
case 4:
$timestart = $course->enrolstartdate;
break;
case 5:
$timestart = $course->enrolenddate;
break;
}
if($extendperiod > 0) {
$timeend = $timestart + $extendperiod;
} else {
$timeend = 0;
}
if (! role_assign($roleid, $adduser->id, 0, $context->id, $timestart, $timeend)) {
$a = new stdClass;
$a->role = $assignableroles[$roleid];
$a->user = fullname($adduser);
$errors[] = get_string('assignerror', 'role', $a);
}
role_assign($roleid, $adduser->id, $context->id);
}
}
@ -197,18 +123,8 @@ if ($roleid) {
if (!empty($userstounassign)) {
foreach ($userstounassign as $removeuser) {
if (! role_unassign($roleid, $removeuser->id, 0, $context->id)) {
$a = new stdClass;
$a->role = $assignableroles[$roleid];
$a->user = fullname($removeuser);
$errors[] = get_string('unassignerror', 'role', $a);
} else if ($inmeta) {
sync_metacourse($courseid);
$newroles = get_user_roles($context, $removeuser->id, false);
if (empty($newroles) || array_key_exists($roleid, $newroles)) {
$errors[] = get_string('metaunassignerror', 'role', fullname($removeuser));
}
}
//unassign only roles that are added manually, no messing with other components!!!
role_unassign($roleid, $removeuser->id, $context->id, '');
}
$potentialuserselector->invalidate_selected_users();
@ -224,14 +140,12 @@ if ($roleid) {
$PAGE->set_pagelayout('admin');
$PAGE->set_title($title);
$tabfile = $CFG->dirroot.'/'.$CFG->admin.'/roles/tabs.php';
switch ($context->contextlevel) {
case CONTEXT_SYSTEM:
admin_externalpage_setup('assignroles', '', array('contextid' => $contextid, 'roleid' => $roleid));
break;
case CONTEXT_USER:
$tabfile = null;
if ($isfrontpage) {
$fullname = fullname($user, has_capability('moodle/site:viewfullnames', $context));
$PAGE->set_heading($fullname);
@ -260,10 +174,6 @@ switch ($context->contextlevel) {
}
echo $OUTPUT->header();
if ($tabfile) {
$currenttab = 'assign';
include($tabfile);
}
// Print heading.
echo $OUTPUT->heading_with_help($title, 'assignroles', 'role');
@ -290,16 +200,6 @@ $assignurl = new moodle_url($PAGE->url, array('roleid'=>$roleid));
<td id="buttonscell">
<div id="addcontrols">
<input name="add" id="add" type="submit" value="<?php echo $OUTPUT->larrow().'&nbsp;'.get_string('add'); ?>" title="<?php print_string('add'); ?>" /><br />
<?php print_collapsible_region_start('', 'assignoptions', get_string('enrolmentoptions', 'role'),
'assignoptionscollapse', true); ?>
<p><label for="extendperiod"><?php print_string('enrolperiod') ?></label><br />
<?php echo html_writer::select($periodmenu, 'extendperiod', $defaultperiod, $unlimitedperiod); ?></p>
<p><label for="extendbase"><?php print_string('startingfrom') ?></label><br />
<?php echo html_writer::select($basemenu, 'extendbase', $extendbase, false); ?></p>
<?php print_collapsible_region_end(); ?>
</div>
<div id="removecontrols">
@ -352,11 +252,6 @@ $assignurl = new moodle_url($PAGE->url, array('roleid'=>$roleid));
// Print instruction
echo $OUTPUT->heading(get_string('chooseroletoassign', 'role'), 3);
// sync metacourse enrolments if needed
if ($inmeta) {
sync_metacourse($course);
}
// Get the names of role holders for roles with between 1 and MAX_USERS_TO_LIST_PER_ROLE users,
// and so determine whether to show the extra column.
$roleholdernames = array();

View File

@ -73,14 +73,12 @@ $title = get_string('checkpermissionsin', 'role', $contextname);
$PAGE->set_pagelayout('admin');
$PAGE->set_title($title);
$tabfile = $CFG->dirroot.'/'.$CFG->admin.'/roles/tabs.php';
switch ($context->contextlevel) {
case CONTEXT_SYSTEM:
admin_externalpage_setup('assignroles', '', array('contextid' => $contextid, 'roleid' => $roleid));
admin_externalpage_setup('assignroles', '', array('contextid' => $contextid));
break;
case CONTEXT_USER:
$tabfile = null;
if ($isfrontpage) {
$fullname = fullname($user, has_capability('moodle/site:viewfullnames', $context));
$PAGE->set_heading($fullname);
@ -112,10 +110,6 @@ echo $OUTPUT->header();
// These are needed early because of tabs.php
$assignableroles = get_assignable_roles($context, ROLENAME_BOTH);
$overridableroles = get_overridable_roles($context, ROLENAME_BOTH);
if ($tabfile) {
$currenttab = 'check';
include($tabfile);
}
// Print heading.
echo $OUTPUT->heading($title);

View File

@ -1020,56 +1020,27 @@ abstract class role_assign_user_selector_base extends user_selector_base {
* when we are assigning in a context below the course level. (CONTEXT_MODULE and
* some CONTEXT_BLOCK).
*
* In this case we replicate part of get_users_by_capability() get the users
* with moodle/course:participate. We can't use
* get_users_by_capability() becuase
* 1) get_users_by_capability() does not deal with searching by name
* 2) exceptions array can be potentially large for large courses
* This returns only enrolled users in this context.
*/
class potential_assignees_below_course extends role_assign_user_selector_base {
public function find_users($search) {
global $DB;
// Get roles with some assignement to the 'moodle/course:participate' capability.
$possibleroles = get_roles_with_capability('moodle/course:participate', CAP_ALLOW, $this->context);
if (empty($possibleroles)) {
// If there aren't any, we are done.
return array();
}
// Now exclude the admin roles, and check the actual permission on
// 'moodle/course:participate' to make sure it is allow.
$validroleids = array();
foreach ($possibleroles as $possiblerole) {
if ($caps = role_context_capabilities($possiblerole->id, $this->context, 'moodle/course:participate')) { // resolved list
if (isset($caps['moodle/course:participate']) && $caps['moodle/course:participate'] > 0) { // resolved capability > 0
$validroleids[] = $possiblerole->id;
}
}
}
// If there are no valid roles, we are done.
if (!$validroleids) {
return array();
}
list($enrolsql, $eparams) = get_enrolled_sql($this->context);
// Now we have to go to the database.
list($wherecondition, $params) = $this->search_sql($search, 'u');
$params = array_merge($params, $eparams);
if ($wherecondition) {
$wherecondition = ' AND ' . $wherecondition;
}
$roleids = '('.implode(',', $validroleids).')';
$fields = 'SELECT DISTINCT ' . $this->required_fields_sql('u');
$countfields = 'SELECT COUNT(DISTINCT u.id)';
$fields = 'SELECT ' . $this->required_fields_sql('u');
$countfields = 'SELECT COUNT(u.id)';
$sql = " FROM {user} u
JOIN {role_assignments} ra ON ra.userid = u.id
JOIN {role} r ON r.id = ra.roleid
WHERE ra.contextid " . get_related_contexts_string($this->context)."
$wherecondition
AND ra.roleid IN $roleids
WHERE u.id IN ($enrolsql) $wherecondition
AND u.id NOT IN (
SELECT u.id
FROM {role_assignments} r, {user} u
@ -1174,7 +1145,7 @@ class existing_role_holders extends role_assign_user_selector_base {
$params = array_merge($params, $ctxparams);
$params['roleid'] = $this->roleid;
$sql = "SELECT ra.id as raid," . $this->required_fields_sql('u') . ",ra.contextid
$sql = "SELECT ra.id as raid," . $this->required_fields_sql('u') . ",ra.contextid,ra.component
FROM {role_assignments} ra
JOIN {user} u ON u.id = ra.userid
JOIN {context} ctx ON ra.contextid = ctx.id
@ -1182,7 +1153,7 @@ class existing_role_holders extends role_assign_user_selector_base {
$wherecondition AND
ctx.id $ctxcondition AND
ra.roleid = :roleid
ORDER BY ctx.depth DESC, u.lastname, u.firstname";
ORDER BY ctx.depth DESC, ra.component, u.lastname, u.firstname";
$contextusers = $DB->get_records_sql($sql, $params);
// No users at all.
@ -1196,6 +1167,7 @@ class existing_role_holders extends role_assign_user_selector_base {
$dummyuser = new stdClass;
$dummyuser->contextid = 0;
$dummyuser->id = 0;
$dummyuser->component = '';
$contextusers[] = $dummyuser;
$results = array(); // The results array we are building up.
$doneusers = array(); // Ensures we only list each user at most once.
@ -1223,6 +1195,11 @@ class existing_role_holders extends role_assign_user_selector_base {
if ($currentcontextid != $this->context->id) {
$user->disabled = true;
}
if ($user->component !== '') {
// bad luck, you can tweak only manual role assignments
$user->disabled = true;
}
unset($user->component);
$currentgroup[$user->id] = $user;
}
@ -1465,8 +1442,9 @@ class role_allow_switch_page extends role_allow_role_page {
}
protected function load_required_roles() {
global $DB;
parent::load_required_roles();
$this->allowedtargetroles = get_allowed_switchable_roles();
$this->allowedtargetroles = $DB->get_records_menu('roles', NULL, 'id', 'roleid, 1');
}
protected function set_allow($fromroleid, $targetroleid) {

View File

@ -60,7 +60,6 @@
$undeletableroles[$CFG->notloggedinroleid] = 1;
$undeletableroles[$CFG->guestroleid] = 1;
$undeletableroles[$CFG->defaultuserroleid] = 1;
$undeletableroles[$CFG->defaultcourseroleid] = 1;
///.Process submitted data.
$confirmed = optional_param('confirm', false, PARAM_BOOL) && data_submitted() && confirm_sesskey();

View File

@ -65,7 +65,7 @@ if (optional_param('cancel', false, PARAM_BOOL)) {
$role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
// These are needed early
// These are needed early
$assignableroles = get_assignable_roles($context, ROLENAME_BOTH);
list($overridableroles, $overridecounts, $nameswithcounts) = get_overridable_roles($context, ROLENAME_BOTH, true);
@ -75,7 +75,6 @@ $straction = get_string('overrideroles', 'role'); // Used by tabs.php
$a = (object)array('context' => $contextname, 'role' => $overridableroles[$roleid]);
$title = get_string('overridepermissionsforrole', 'role', $a);
$tabfile = $CFG->dirroot.'/'.$CFG->admin.'/roles/tabs.php';
$currenttab = 'permissions';
$PAGE->set_pagelayout('admin');
@ -86,7 +85,6 @@ switch ($context->contextlevel) {
print_error('cannotoverridebaserole', 'error');
break;
case CONTEXT_USER:
$tabfile = null;
if ($isfrontpage) {
$fullname = fullname($user, has_capability('moodle/site:viewfullnames', $context));
$PAGE->set_heading($fullname);
@ -135,9 +133,6 @@ if (optional_param('savechanges', false, PARAM_BOOL) && confirm_sesskey()) {
// Finally start page output
echo $OUTPUT->header();
if ($tabfile) {
include($tabfile);
}
echo $OUTPUT->heading_with_help($title, 'overridepermissions', 'role');
// Show UI for overriding roles.
@ -152,7 +147,7 @@ if (!empty($capabilities)) {
echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'roleid', 'value'=>$roleid));
echo html_writer::tag('p', get_string('highlightedcellsshowinherit', 'role'), array('class'=>'overridenotice'));
$overridestable->display();
if ($overridestable->has_locked_capabiltites()) {
echo '<p class="overridenotice">' . get_string('safeoverridenotice', 'role') . "</p>\n";

View File

@ -75,7 +75,6 @@ $allowsafeoverrides = has_capability('moodle/role:safeoverride', $context);
$contextname = print_context_name($context);
$title = get_string('permissionsincontext', 'role', $contextname);
$straction = get_string('permissions', 'role'); // Used by tabs.php
$tabfile = $CFG->dirroot.'/'.$CFG->admin.'/roles/tabs.php';
$currenttab = 'permissions';
$PAGE->set_pagelayout('admin');
@ -85,7 +84,6 @@ switch ($context->contextlevel) {
print_error('cannotoverridebaserole', 'error');
break;
case CONTEXT_USER:
$tabfile = null;
if ($isfrontpage) {
$fullname = fullname($user, has_capability('moodle/site:viewfullnames', $context));
$PAGE->set_heading($fullname);
@ -143,9 +141,6 @@ if ($capability && ($allowoverrides || ($allowsafeoverrides && is_safe_capabilit
}
// Display and print
echo $OUTPUT->header();
if ($tabfile) {
include($tabfile);
}
echo $OUTPUT->heading($title);
echo $OUTPUT->confirm($message, $continueurl, $PAGE->url);
echo $OUTPUT->footer();
@ -184,9 +179,6 @@ if ($capability && ($allowoverrides || ($allowsafeoverrides && is_safe_capabilit
}
}
echo $OUTPUT->header();
if ($tabfile) {
include($tabfile);
}
echo $OUTPUT->heading($title);
echo $OUTPUT->box($message);
$mform->display();
@ -196,9 +188,6 @@ if ($capability && ($allowoverrides || ($allowsafeoverrides && is_safe_capabilit
}
echo $OUTPUT->header();
if ($tabfile) {
include($tabfile);
}
echo $OUTPUT->heading($title);
$table = new permissions_table($context, $contextname, $allowoverrides, $allowsafeoverrides, $overridableroles);

View File

@ -1,116 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Handles headers and tabs for the roles control at any level apart from SYSTEM level
* We assume that $currenttab, $assignableroles and $overridableroles are defined
*
* @package moodlecore
* @subpackage role
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); // It must be included from a Moodle page
}
if (!isset($availablefilters)) {
$availablefilters = array();
if (in_array($context->contextlevel, array(CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE)) &&
!($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) &&
has_capability('moodle/filter:manage', $context)) {
$availablefilters = filter_get_available_in_context($context);
}
}
$toprow = array();
$inactive = array();
$activetwo = array();
$secondrow = array();
$permissionsrow = array();
if ($context->contextlevel != CONTEXT_SYSTEM) { // Print tabs for anything except SYSTEM context
if ($context->contextlevel == CONTEXT_MODULE) { // Only show update button if module
$url = new moodle_url('/course/mod.php', array('update'=>$context->instanceid, 'return'=>'true', 'sesskey'=>sesskey()));
$toprow[] = new tabobject('update', $url, get_string('settings'));
}
if (!empty($assignableroles) || $currenttab=='assign') {
$url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$context->id));
$toprow[] = new tabobject('assign', $url, get_string('localroles', 'role'), '', true);
}
if (has_capability('moodle/role:review', $context) or !empty($overridableroles)) {
$url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$context->id));
$permissionsrow['permissions'] = new tabobject('permissions', $url, get_string('permissions', 'role'), '', true);
}
if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'), $context)) {
$url = new moodle_url('/admin/roles/check.php', array('contextid'=>$context->id));
$permissionsrow['check'] = new tabobject('check', $url, get_string('checkpermissions', 'role'));
}
if ($permissionsrow) {
$firstpermissionrow = reset($permissionsrow);
$toprow[] = new tabobject('toppermissions', $firstpermissionrow->link, get_string('permissions', 'role'), '', true);
if (!empty($permissionsrow[$currenttab])) {
$secondrow = array_values($permissionsrow);
$inactive = array('toppermissions');
$activetwo = array('toppermissions');
}
}
if (!empty($availablefilters)) {
$url = new moodle_url('/filter/manage.php', array('contextid'=>$context->id));
$toprow[] = new tabobject('filters', $url, get_string('filters', 'admin'));
}
}
unset($permissionsrow);
/// Here other core tabs should go (always calling tabs.php files)
/// All the logic to decide what to show must be self-contained in the tabs file
/// eg:
/// include_once($CFG->dirroot . '/grades/tabs.php');
/// Finally, we support adding some 'on-the-fly' tabs here
/// All the logic to decide what to show must be self-cointained in the tabs file
if (!empty($CFG->extratabs)) {
if ($extratabs = explode(',', $CFG->extratabs)) {
asort($extratabs);
foreach($extratabs as $extratab) {
/// Each extra tab must be one $CFG->dirroot relative file
if (file_exists($CFG->dirroot . '/' . $extratab)) {
include($CFG->dirroot . '/' . $extratab);
}
}
}
}
$inactive[] = $currenttab;
$tabs = array($toprow);
/// If there are any secondrow defined, let's introduce it
if (!empty($secondrow)) {
$tabs[] = $secondrow;
}
print_tabs($tabs, $currenttab, $inactive, $activetwo);

View File

@ -55,7 +55,7 @@ if (!$canview) {
/// Now get the role assignments for this user.
$sql = "SELECT
ra.id, ra.userid, ra.contextid, ra.roleid, ra.enrol,
ra.id, ra.userid, ra.contextid, ra.roleid, ra.component, ra.itemid
c.path,
r.name AS rolename,
COALESCE(rn.name, r.name) AS localname

View File

@ -135,9 +135,9 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page
$temp = new admin_externalpage('profilepage', get_string('myprofile', 'admin'), $CFG->wwwroot . '/user/profilesys.php');
$ADMIN->add('appearance', $temp);
// coursemanager is the person responsible for course - usually manages enrolments, receives notification, etc.
$temp = new admin_settingpage('coursemanager', get_string('coursemanager', 'admin'));
$temp->add(new admin_setting_special_coursemanager());
// coursecontact is the person responsible for course - usually manages enrolments, receives notification, etc.
$temp = new admin_settingpage('coursecontact', get_string('coursecontact', 'admin'));
$temp->add(new admin_setting_special_coursecontact());
$ADMIN->add('appearance', $temp);
$temp = new admin_settingpage('ajax', get_string('ajaxuse'));

View File

@ -11,8 +11,6 @@ if ($hassiteconfig
$ADMIN->add('courses', new admin_externalpage('coursemgmt', get_string('coursemgmt', 'admin'), $CFG->wwwroot . '/course/index.php?categoryedit=on',
array('moodle/category:manage', 'moodle/course:create')));
$ADMIN->add('courses', new admin_enrolment_page());
/// Course Default Settings Page
/// NOTE: these settings must be applied after all other settings because they depend on them
///main course settings
@ -41,45 +39,6 @@ if ($hassiteconfig
$choices = get_max_upload_sizes();
}
$temp->add(new admin_setting_configselect('moodlecourse/maxbytes', get_string('maximumupload'), get_string('coursehelpmaximumupload'), key($choices), $choices));
$temp->add(new admin_setting_configselect('moodlecourse/metacourse', get_string('metacourse'), get_string('coursehelpmetacourse'), 0,array(0 => get_string('no'), 1 => get_string('yes'))));
///enrolement course settings
$temp->add(new admin_setting_heading('enrolhdr', get_string('enrolments'), ''));
require_once($CFG->dirroot.'/enrol/enrol.class.php');
$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);
$temp->add(new admin_setting_configselect('moodlecourse/enrol', get_string('enrolmentplugins'), get_string('coursehelpenrolmentplugins'), key($choices),$choices));
$choices = array(0 => get_string('no'), 1 => get_string('yes'), 2 => get_string('enroldate'));
$temp->add(new admin_setting_configselect('moodlecourse/enrollable', get_string('enrollable'), get_string('coursehelpenrollable'), 1,$choices));
$periodmenu=array();
$periodmenu[0] = get_string('unlimited');
for ($i=1; $i<=365; $i++) {
$seconds = $i * 86400;
$periodmenu[$seconds] = get_string('numdays', '', $i);
}
$temp->add(new admin_setting_configselect('moodlecourse/enrolperiod', get_string('enrolperiod'), '', 0,$periodmenu));
///
$temp->add(new admin_setting_heading('expirynotifyhdr', get_string('expirynotify'), ''));
$temp->add(new admin_setting_configselect('moodlecourse/expirynotify', get_string('notify'), get_string('coursehelpnotify'), 0,array(0 => get_string('no'), 1 => get_string('yes'))));
$temp->add(new admin_setting_configselect('moodlecourse/notifystudents', get_string('expirynotifystudents'), get_string('coursehelpexpirynotifystudents'), 0,array(0 => get_string('no'), 1 => get_string('yes'))));
$thresholdmenu=array();
for ($i=1; $i<=30; $i++) {
$seconds = $i * 86400;
$thresholdmenu[$seconds] = get_string('numdays', '', $i);
}
$temp->add(new admin_setting_configselect('moodlecourse/expirythreshold', get_string('expirythreshold'), get_string('coursehelpexpirythreshold'), 10 * 86400,$thresholdmenu));
$temp->add(new admin_setting_heading('groups', get_string('groups', 'group'), ''));
$choices = array();
@ -95,12 +54,6 @@ if ($hassiteconfig
$choices['0'] = get_string('courseavailablenot');
$choices['1'] = get_string('courseavailable');
$temp->add(new admin_setting_configselect('moodlecourse/visible', get_string('visible'), '', 1,$choices));
$temp->add(new admin_setting_configpasswordunmask('moodlecourse/enrolpassword', get_string('enrolmentkey'), get_string('coursehelpenrolmentkey'),''));
$choices = array();
$choices['0'] = get_string('guestsno');
$choices['1'] = get_string('guestsyes');
$choices['2'] = get_string('guestskey');
$temp->add(new admin_setting_configselect('moodlecourse/guest', get_string('opentoguests'), '', 0,$choices));
$temp->add(new admin_setting_heading('language', get_string('language'), ''));
@ -151,7 +104,6 @@ if ($hassiteconfig
$temp = new admin_settingpage('scheduled', get_string('scheduledsettings','backup'), 'moodle/backup:backupcourse');
$temp->add(new admin_setting_configcheckbox('backup/backup_sche_modules', get_string('includemodules'), get_string('backupincludemoduleshelp'), 0));
$temp->add(new admin_setting_configcheckbox('backup/backup_sche_withuserdata', get_string('includemoduleuserdata'), get_string('backupincludemoduleuserdatahelp'), 0));
$temp->add(new admin_setting_configcheckbox('backup/backup_sche_metacourse', get_string('metacourse'), get_string('backupmetacoursehelp'), 0));
$temp->add(new admin_setting_configselect('backup/backup_sche_users', get_string('users'), get_string('backupusershelp'),
0, array(0 => get_string('all'), 1 => get_string('course'))));
$temp->add(new admin_setting_configcheckbox('backup/backup_sche_logs', get_string('logs'), get_string('backuplogshelp'), 0));

View File

@ -50,7 +50,6 @@ if (!during_initial_install()) { //do not use during installation
$temp->add(new admin_setting_configtext('commentsperpage', get_string('commentsperpage', 'admin'), '', 15, PARAM_INT));
$temp->add(new admin_setting_configtext('coursesperpage', get_string('coursesperpage', 'admin'), get_string('configcoursesperpage', 'admin'), 20, PARAM_INT));
$temp->add(new admin_setting_configcheckbox('allowvisiblecoursesinhiddencategories', get_string('allowvisiblecoursesinhiddencategories', 'admin'), get_string('configvisiblecourses', 'admin'), 0));
// front page default role
$roleoptions = array(0=>get_string('none')); // roles to choose from

View File

@ -50,6 +50,84 @@ if ($hassiteconfig) {
}
}
// authentication plugins
$ADMIN->add('modules', new admin_category('authsettings', get_string('authentication', 'admin')));
$temp = new admin_settingpage('manageauths', get_string('authsettings', 'admin'));
$temp->add(new admin_setting_manageauths());
$temp->add(new admin_setting_heading('manageauthscommonheading', get_string('commonsettings', 'admin'), ''));
$temp->add(new admin_setting_special_registerauth());
$temp->add(new admin_setting_configselect('guestloginbutton', get_string('guestloginbutton', 'auth'),
get_string('showguestlogin', 'auth'), '1', array('0'=>get_string('hide'), '1'=>get_string('show'))));
$temp->add(new admin_setting_configtext('alternateloginurl', get_string('alternateloginurl', 'auth'),
get_string('alternatelogin', 'auth', htmlspecialchars(get_login_url())), ''));
$temp->add(new admin_setting_configtext('forgottenpasswordurl', get_string('forgottenpasswordurl', 'auth'),
get_string('forgottenpassword', 'auth'), ''));
$temp->add(new admin_setting_confightmleditor('auth_instructions', get_string('instructions', 'auth'),
get_string('authinstructions', 'auth'), ''));
$temp->add(new admin_setting_configtext('allowemailaddresses', get_string('allowemailaddresses', 'admin'), get_string('configallowemailaddresses', 'admin'), '', PARAM_NOTAGS));
$temp->add(new admin_setting_configtext('denyemailaddresses', get_string('denyemailaddresses', 'admin'), get_string('configdenyemailaddresses', 'admin'), '', PARAM_NOTAGS));
$temp->add(new admin_setting_configcheckbox('verifychangedemail', get_string('verifychangedemail', 'admin'), get_string('configverifychangedemail', 'admin'), 1));
$temp->add(new admin_setting_configtext('recaptchapublickey', get_string('recaptchapublickey', 'admin'), get_string('configrecaptchapublickey', 'admin'), '', PARAM_NOTAGS));
$temp->add(new admin_setting_configtext('recaptchaprivatekey', get_string('recaptchaprivatekey', 'admin'), get_string('configrecaptchaprivatekey', 'admin'), '', PARAM_NOTAGS));
$ADMIN->add('authsettings', $temp);
if ($auths = get_plugin_list('auth')) {
$authsenabled = get_enabled_auth_plugins();
$authbyname = array();
foreach ($auths as $auth => $authdir) {
$strauthname = get_string('pluginname', "auth_{$auth}");
$authbyname[$strauthname] = $auth;
}
ksort($authbyname);
foreach ($authbyname as $strauthname=>$authname) {
if (file_exists($authdir.'/settings.php')) {
// do not show disabled auths in tree, keep only settings link on manage page
$settings = new admin_settingpage('authsetting'.$authname, $strauthname, 'moodle/site:config', !in_array($authname, $authsenabled));
if ($ADMIN->fulltree) {
include($authdir.'/settings.php');
}
// TODO: finish implementation of common settings - locking, etc.
$ADMIN->add('authsettings', $settings);
} else {
$ADMIN->add('authsettings', new admin_externalpage('authsetting'.$authname, $strauthname, "$CFG->wwwroot/$CFG->admin/auth_config.php?auth=$authname", 'moodle/site:config', !in_array($authname, $authsenabled)));
}
}
}
// Enrolment plugins
$ADMIN->add('modules', new admin_category('enrolments', get_string('enrolments', 'enrol')));
$temp = new admin_settingpage('manageenrols', get_string('manageenrols', 'enrol'));
$temp->add(new admin_setting_manageenrols());
if (empty($CFG->enrol_plugins_enabled)) {
$enabled = array();
} else {
$enabled = explode(',', $CFG->enrol_plugins_enabled);
}
$enrols = get_plugin_list('enrol');
$ADMIN->add('enrolments', $temp);
foreach($enrols as $enrol=>$enrolpath) {
if (!file_exists("$enrolpath/settings.php")) {
continue;
}
$settings = new admin_settingpage('enrolsettings'.$enrol, get_string('pluginname', 'enrol_'.$enrol), 'moodle/site:config', !in_array($enrol, $enabled));
// settings.php may create a subcategory or unset the settings completely
include("$enrolpath/settings.php");
if ($settings) {
$ADMIN->add('enrolments', $settings);
}
}
unset($enabled);
unset($enrols);
/// Editor plugins
$ADMIN->add('modules', new admin_category('editorsettings', get_string('editors', 'editor')));
@ -63,7 +141,7 @@ if ($hassiteconfig) {
if (file_exists($CFG->dirroot . '/lib/editor/'.$editor.'/settings.php')) {
$editor_setting = new admin_externalpage('editorsettings'.$editor, $editorstr, $url.'&amp;action=edit&amp;editor='.$editor);
$ADMIN->add('editorsettings', $editor_setting);
}
}
}
/// License types
$ADMIN->add('modules', new admin_category('licensesettings', get_string('license')));
@ -284,7 +362,7 @@ if ($hassiteconfig) {
$temp->add(new admin_setting_heading('webservicesaredisabled', '', get_string('disabledwarning', 'webservice')));
}
$ADMIN->add('webservicesettings', $temp);
if ($hassiteconfig || has_capability('moodle/question:config', $systemcontext)) {
// Question type settings.

View File

@ -67,6 +67,7 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page
$temp->add(new admin_setting_configtext('minpasswordupper', get_string('minpasswordupper', 'admin'), get_string('configminpasswordupper', 'admin'), 1, PARAM_INT));
$temp->add(new admin_setting_configtext('minpasswordnonalphanum', get_string('minpasswordnonalphanum', 'admin'), get_string('configminpasswordnonalphanum', 'admin'), 1, PARAM_INT));
$temp->add(new admin_setting_configtext('maxconsecutiveidentchars', get_string('maxconsecutiveidentchars', 'admin'), get_string('configmaxconsecutiveidentchars', 'admin'), 0, PARAM_INT));
$temp->add(new admin_setting_configcheckbox('groupenrolmentkeypolicy', get_string('groupenrolmentkeypolicy', 'admin'), get_string('groupenrolmentkeypolicy_desc', 'admin'), 1));
$temp->add(new admin_setting_configcheckbox('disableuserimages', get_string('disableuserimages', 'admin'), get_string('configdisableuserimages', 'admin'), 0));
$temp->add(new admin_setting_configcheckbox('emailchangeconfirmation', get_string('emailchangeconfirmation', 'admin'), get_string('configemailchangeconfirmation', 'admin'), 1));
$ADMIN->add('security', $temp);

View File

@ -2,7 +2,6 @@
// This file defines settingpages and externalpages under the "users" category
$ADMIN->add('users', new admin_category('authsettings', get_string('authentication','admin')));
$ADMIN->add('users', new admin_category('accounts', get_string('accounts', 'admin')));
$ADMIN->add('users', new admin_category('roles', get_string('permissions', 'role')));
@ -17,54 +16,6 @@ if ($hassiteconfig
or has_capability('moodle/cohort:view', $systemcontext)) { // speedup for non-admins, add all caps used on this page
$temp = new admin_settingpage('manageauths', get_string('authsettings', 'admin'));
$temp->add(new admin_setting_manageauths());
$temp->add(new admin_setting_heading('manageauthscommonheading', get_string('commonsettings', 'admin'), ''));
$temp->add(new admin_setting_special_registerauth());
$temp->add(new admin_setting_configselect('guestloginbutton', get_string('guestloginbutton', 'auth'),
get_string('showguestlogin', 'auth'), '1', array('0'=>get_string('hide'), '1'=>get_string('show'))));
$temp->add(new admin_setting_configtext('alternateloginurl', get_string('alternateloginurl', 'auth'),
get_string('alternatelogin', 'auth', htmlspecialchars(get_login_url())), ''));
$temp->add(new admin_setting_configtext('forgottenpasswordurl', get_string('forgottenpasswordurl', 'auth'),
get_string('forgottenpassword', 'auth'), ''));
$temp->add(new admin_setting_confightmleditor('auth_instructions', get_string('instructions', 'auth'),
get_string('authinstructions', 'auth'), ''));
$temp->add(new admin_setting_configtext('allowemailaddresses', get_string('allowemailaddresses', 'admin'), get_string('configallowemailaddresses', 'admin'), '', PARAM_NOTAGS));
$temp->add(new admin_setting_configtext('denyemailaddresses', get_string('denyemailaddresses', 'admin'), get_string('configdenyemailaddresses', 'admin'), '', PARAM_NOTAGS));
$temp->add(new admin_setting_configcheckbox('verifychangedemail', get_string('verifychangedemail', 'admin'), get_string('configverifychangedemail', 'admin'), 1));
$temp->add(new admin_setting_configtext('recaptchapublickey', get_string('recaptchapublickey', 'admin'), get_string('configrecaptchapublickey', 'admin'), '', PARAM_NOTAGS));
$temp->add(new admin_setting_configtext('recaptchaprivatekey', get_string('recaptchaprivatekey', 'admin'), get_string('configrecaptchaprivatekey', 'admin'), '', PARAM_NOTAGS));
$ADMIN->add('authsettings', $temp);
if ($auths = get_plugin_list('auth')) {
$authsenabled = get_enabled_auth_plugins();
$authbyname = array();
foreach ($auths as $auth => $authdir) {
$strauthname = get_string('pluginname', "auth_{$auth}");
$authbyname[$strauthname] = $auth;
}
ksort($authbyname);
foreach ($authbyname as $strauthname=>$authname) {
if (file_exists($authdir.'/settings.php')) {
// do not show disabled auths in tree, keep only settings link on manage page
$settings = new admin_settingpage('authsetting'.$authname, $strauthname, 'moodle/site:config', !in_array($authname, $authsenabled));
if ($ADMIN->fulltree) {
include($authdir.'/settings.php');
}
// TODO: finish implementation of common settings - locking, etc.
$ADMIN->add('authsettings', $settings);
} else {
$ADMIN->add('authsettings', new admin_externalpage('authsetting'.$authname, $strauthname, "$CFG->wwwroot/$CFG->admin/auth_config.php?auth=$authname", 'moodle/site:config', !in_array($authname, $authsenabled)));
}
}
}
if (empty($CFG->loginhttps)) {
$securewwwroot = $CFG->wwwroot;
} else {
@ -94,7 +45,7 @@ if ($hassiteconfig
$studentroles = array();
$teacherroles = array();
$creatornewroles = array();
foreach (get_all_roles() as $role) {
$rolename = strip_tags(format_string($role->name)) . ' ('. $role->shortname . ')';
$allroles[$role->id] = $rolename;
@ -135,7 +86,7 @@ if ($hassiteconfig
$defaultstudentid = key($studentroles);
reset($teacherroles);
$defaultteacherid = key($teacherroles);
if ($userroles) {
reset($userroles);
$defaultuserid = key($userroles);
@ -155,19 +106,12 @@ if ($hassiteconfig
$temp->add(new admin_setting_configcheckbox('nodefaultuserrolelists', get_string('nodefaultuserrolelists', 'admin'), get_string('confignodefaultuserrolelists', 'admin'), 0));
if (!during_initial_install()) {
$temp->add(new admin_setting_configselect('defaultcourseroleid', get_string('defaultcourseroleid', 'admin'),
get_string('configdefaultcourseroleid', 'admin'), $defaultstudentid, $allroles));
$temp->add(new admin_setting_configselect('creatornewroleid', get_string('creatornewroleid', 'admin'),
get_string('configcreatornewroleid', 'admin'), $defaultteacherid, $creatornewroles));
}
$temp->add(new admin_setting_configcheckbox('autologinguests', get_string('autologinguests', 'admin'), get_string('configautologinguests', 'admin'), 0));
if (!during_initial_install()) {
$temp->add(new admin_setting_configmultiselect('nonmetacoursesyncroleids', get_string('nonmetacoursesyncroleids', 'admin'),
get_string('confignonmetacoursesyncroleids', 'admin'), array(), $allroles));
}
$temp->add(new admin_setting_configmultiselect('hiddenuserfields', get_string('hiddenuserfields', 'admin'),
get_string('confighiddenuserfields', 'admin'), array(),
array('description' => get_string('description'),

View File

@ -162,26 +162,21 @@ if ($formdata = $mform->is_cancelled()) {
$weakpasswords = 0;
// caches
$ccache = array(); // course cache - do not fetch all courses here, we will not probably use them all anyway!
$rolecache = array(); // roles lookup cache
$ccache = array(); // course cache - do not fetch all courses here, we will not probably use them all anyway!
$rolecache = uu_allowed_roles_cache(); // roles lookup cache
$manualcacche = array(); // cache of used manual enrol plugins in each course
$allowedauths = uu_allowed_auths();
$allowedauths = array_keys($allowedauths);
$availableauths = get_plugin_list('auth');
$availableauths = array_keys($availableauths);
$allowedroles = uu_allowed_roles(true);
foreach ($allowedroles as $rid=>$rname) {
$rolecache[$rid] = new object();
$rolecache[$rid]->id = $rid;
$rolecache[$rid]->name = $rname;
if (!is_numeric($rname)) { // only non-numeric shornames are supported!!!
$rolecache[$rname] = new object();
$rolecache[$rname]->id = $rid;
$rolecache[$rname]->name = $rname;
}
// we use only manual enrol plugin here, if it is disabled no enrol is done
if (enrol_is_enabled('manual')) {
$manual = enrol_get_plugin('manual');
} else {
$manual = NULL;
}
unset($allowedroles);
// clear bulk selection
if ($bulk) {
@ -210,7 +205,7 @@ if ($formdata = $mform->is_cancelled()) {
// add fields to user object
foreach ($line as $key => $value) {
if ($value !== '') {
$key = $columns[$key];
$key = $columns[$key];
// password is special field
if ($key == 'password') {
if ($value !== '') {
@ -365,16 +360,11 @@ if ($formdata = $mform->is_cancelled()) {
$renameerrors++;
continue;
}
if ($DB->set_field('user', 'username', $user->username, array('id'=>$olduser->id))) {
$upt->track('username', '', 'normal', false); // clear previous
$upt->track('username', $oldusername.'-->'.$user->username, 'info');
$upt->track('status', $struserrenamed);
$renames++;
} else {
$upt->track('status', $strusernotrenamedexists, 'error');
$renameerrors++;
continue;
}
$DB->set_field('user', 'username', $user->username, array('id'=>$olduser->id));
$upt->track('username', '', 'normal', false); // clear previous
$upt->track('username', $oldusername.'-->'.$user->username, 'info');
$upt->track('status', $struserrenamed);
$renames++;
} else {
$upt->track('status', $strusernotrenamedmissing, 'error');
$renameerrors++;
@ -501,14 +491,9 @@ if ($formdata = $mform->is_cancelled()) {
$upt->track('auth', $struserauthunsupported, 'warning');
}
if ($DB->update_record('user', $existinguser)) {
$upt->track('status', $struserupdated);
$usersupdated++;
} else {
$upt->track('status', $strusernotupdated, 'error');
$userserrors++;
continue;
}
$DB->update_record('user', $existinguser);
$upt->track('status', $struserupdated);
$usersupdated++;
// save custom profile fields data from csv file
profile_save_data($existinguser);
}
@ -555,26 +540,21 @@ if ($formdata = $mform->is_cancelled()) {
}
}
if ($user->id = $DB->insert_record('user', $user)) {
$info = ': ' . $user->username .' (ID = ' . $user->id . ')';
$upt->track('status', $struseradded);
$upt->track('id', $user->id, 'normal', false);
$usersnew++;
if ($createpasswords and empty($user->password)) {
// passwords will be created and sent out on cron
set_user_preference('create_password', 1, $user->id);
set_user_preference('auth_forcepasswordchange', 1, $user->id);
$upt->track('password', get_string('new'));
}
if ($forcechangepassword) {
set_user_preference('auth_forcepasswordchange', 1, $user->id);
}
} else {
// Record not added -- possibly some other error
$upt->track('status', $strusernotaddederror, 'error');
$userserrors++;
continue;
$user->id = $DB->insert_record('user', $user);
$info = ': ' . $user->username .' (ID = ' . $user->id . ')';
$upt->track('status', $struseradded);
$upt->track('id', $user->id, 'normal', false);
$usersnew++;
if ($createpasswords and empty($user->password)) {
// passwords will be created and sent out on cron
set_user_preference('create_password', 1, $user->id);
set_user_preference('auth_forcepasswordchange', 1, $user->id);
$upt->track('password', get_string('new'));
}
if ($forcechangepassword) {
set_user_preference('auth_forcepasswordchange', 1, $user->id);
}
// save custom profile fields data
profile_save_data($user);
@ -595,9 +575,12 @@ if ($formdata = $mform->is_cancelled()) {
}
$i = substr($column, 6);
if (empty($user->{'course'.$i})) {
continue;
}
$shortname = $user->{'course'.$i};
if (!array_key_exists($shortname, $ccache)) {
if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname, defaultrole')) {
if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname')) {
$upt->track('enrolments', get_string('unknowncourse', 'error', $shortname), 'error');
continue;
}
@ -606,62 +589,61 @@ if ($formdata = $mform->is_cancelled()) {
}
$courseid = $ccache[$shortname]->id;
$coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
// find role
$rid = false;
if (!empty($user->{'role'.$i})) {
$addrole = $user->{'role'.$i};
if (array_key_exists($addrole, $rolecache)) {
$rid = $rolecache[$addrole]->id;
if (!isset($manualcache[$courseid])) {
if ($instances = enrol_get_instances($courseid, false)) {
$manualcache[$courseid] = reset($instances);
} else {
$upt->track('enrolments', get_string('unknownrole', 'error', $addrole), 'error');
continue;
$manualcache[$courseid] = false;
}
}
} else if (!empty($user->{'type'.$i})) {
// if no role, then find "old" enrolment type
$addtype = $user->{'type'.$i};
if ($addtype < 1 or $addtype > 3) {
$upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
continue;
} else if ($addtype == 1 and empty($formdata->uulegacy1)) {
if (empty($ccache[$shortname]->defaultrole)) {
$rid = $CFG->defaultcourseroleid;
if ($manual and $manualcache[$courseid]) {
// find role
$rid = false;
if (!empty($user->{'role'.$i})) {
$addrole = $user->{'role'.$i};
if (array_key_exists($addrole, $rolecache)) {
$rid = $rolecache[$addrole]->id;
} else {
$rid = $ccache[$shortname]->defaultrole;
$upt->track('enrolments', get_string('unknownrole', 'error', $addrole), 'error');
continue;
}
} else if (!empty($user->{'type'.$i})) {
// if no role, then find "old" enrolment type
$addtype = $user->{'type'.$i};
if ($addtype < 1 or $addtype > 3) {
$upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
continue;
} else if (empty($formdata->{'uulegacy'.$addtype})) {
continue;
} else {
$rid = $formdata->{'uulegacy'.$addtype};
}
} else {
$rid = $formdata->{'uulegacy'.$addtype};
// no role specified, use the default from manual enrol plugin
$rid = $manualcache[$courseid]->roleid;
}
} else {
// no role specified, use the default
if (empty($ccache[$shortname]->defaultrole)) {
$rid = $CFG->defaultcourseroleid;
} else {
$rid = $ccache[$shortname]->defaultrole;
}
}
if ($rid) {
// find duration
$timestart = 0;
$timeend = 0;
if (!empty($user->{'enrolperiod'.$i})) {
$duration = (int)$user->{'enrolperiod'.$i} * 86400; // convert days to seconds
if ($duration > 0) { // sanity check
$timestart = time();
$timeend = $timestart + $duration;
}
}
// find duration
$timestart = 0;
$timeend = 0;
if (!empty($user->{'enrolperiod'.$i})) {
$duration = (int)$user->{'enrolperiod'.$i} * 86400; // convert days to seconds
if ($duration > 0) { // sanity check
$timestart = time();
$timeend = $timestart + $duration;
}
}
$manual->enrol_user($manualcache[$courseid], $user->id, $rid, $timestart, $timeend, true);
if ($rid) {
$a = new object();
$a->course = $shortname;
$a->role = $rolecache[$rid]->name;
if (role_assign($rid, $user->id, 0, $coursecontext->id, $timestart, $timeend)) {
$upt->track('enrolments', get_string('enrolledincourserole', '', $a));
} else {
$upt->track('enrolments', get_string('enrolledincoursenotrole', '', $a), 'error');
$a = new object();
$a->course = $shortname;
$a->role = $rolecache[$rid]->name;
$upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
}
}
@ -708,6 +690,8 @@ if ($formdata = $mform->is_cancelled()) {
try {
if (groups_add_member($gid, $user->id)) {
$upt->track('enrolments', get_string('addedtogroup', '', $gname));
} else {
$upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
}
} catch (moodle_exception $e) {
$upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
@ -971,7 +955,7 @@ class uu_progress_tracker {
echo '<th class="header c'.$ci++.'" scope="col">'.get_string('email').'</th>';
echo '<th class="header c'.$ci++.'" scope="col">'.get_string('password').'</th>';
echo '<th class="header c'.$ci++.'" scope="col">'.get_string('authentication').'</th>';
echo '<th class="header c'.$ci++.'" scope="col">'.get_string('enrolments').'</th>';
echo '<th class="header c'.$ci++.'" scope="col">'.get_string('enrolments', 'enrol').'</th>';
echo '<th class="header c'.$ci++.'" scope="col">'.get_string('delete').'</th>';
echo '</tr>';
$this->_row = null;
@ -1149,7 +1133,7 @@ function uu_allowed_auths() {
global $CFG;
// only following plugins are guaranteed to work properly
// TODO: add support for more plguins in 2.0
// TODO: add support for more plugins in 2.0
$whitelist = array('manual', 'nologin', 'none', 'email');
$plugins = get_enabled_auth_plugins();
$choices = array();
@ -1161,21 +1145,25 @@ function uu_allowed_auths() {
}
/**
* Returns list of non administrator roles
* Returns list of roles that are assignable in courses
*/
function uu_allowed_roles($shortname=false) {
global $CFG;
$roles = get_all_roles();
$choices = array();
foreach($roles as $role) {
if ($shortname) {
$choices[$role->id] = $role->shortname;
} else {
$choices[$role->id] = format_string($role->name);
}
}
return $choices;
function uu_allowed_roles() {
// let's cheat a bit, frontpage is guaranteed to exist and has the same list of roles ;-)
$roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_ORIGINALANDSHORT);
return array_reverse($roles, true);
}
function uu_allowed_roles_cache() {
$allowedroles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_SHORT);
foreach ($allowedroles as $rid=>$rname) {
$rolecache[$rid] = new object();
$rolecache[$rid]->id = $rid;
$rolecache[$rid]->name = $rname;
if (!is_numeric($rname)) { // only non-numeric shortnames are supported!!!
$rolecache[$rname] = new object();
$rolecache[$rname]->id = $rid;
$rolecache[$rname]->name = $rname;
}
}
return $rolecache;
}

View File

@ -59,7 +59,7 @@ class admin_uploaduser_form2 extends moodleform {
// I am the template user, why should it be the administrator? we have roles now, other ppl may use this script ;-)
$templateuser = $USER;
// upload settings and file
// upload settings and file
$mform->addElement('header', 'settingsheader', get_string('settings'));
$mform->addElement('static', 'uutypelabel', get_string('uuoptype', 'admin') );
@ -105,7 +105,7 @@ class admin_uploaduser_form2 extends moodleform {
$mform->addElement('select', 'uubulk', get_string('uubulk', 'admin'), $choices);
$mform->setDefault('uubulk', 0);
// roles selection
// roles selection
$showroles = false;
foreach ($columns as $column) {
if (preg_match('/^type\d+$/', $column)) {
@ -118,31 +118,41 @@ class admin_uploaduser_form2 extends moodleform {
$choices = uu_allowed_roles(true);
$choices[0] = get_string('uucoursedefaultrole', 'admin');
$mform->addElement('select', 'uulegacy1', get_string('uulegacy1role', 'admin'), $choices);
$mform->setDefault('uulegacy1', 0);
unset($choices[0]);
if ($studentroles = get_archetype_roles('student')) {
foreach ($studentroles as $role) {
if (isset($choices[$role->id])) {
$mform->setDefault('uulegacy1', $role->id);
break;
}
}
unset($studentroles);
}
$mform->addElement('select', 'uulegacy2', get_string('uulegacy2role', 'admin'), $choices);
if ($editteacherroles = get_archetype_roles('editingteacher')) {
$editteacherrole = array_shift($editteacherroles); /// Take the first one
$mform->setDefault('uulegacy2', $editteacherrole->id);
foreach ($editteacherroles as $role) {
if (isset($choices[$role->id])) {
$mform->setDefault('uulegacy2', $role->id);
break;
}
}
unset($editteacherroles);
} else {
$mform->setDefault('uulegacy2', $CFG->defaultcourseroleid);
}
$mform->addElement('select', 'uulegacy3', get_string('uulegacy3role', 'admin'), $choices);
if ($teacherroles = get_archetype_roles('teacher')) {
$teacherrole = array_shift($teacherroles); /// Take the first one
$mform->setDefault('uulegacy3', $teacherrole->id);
foreach ($teacherroles as $role) {
if (isset($choices[$role->id])) {
$mform->setDefault('uulegacy3', $role->id);
break;
}
}
unset($teacherroles);
} else {
$mform->setDefault('uulegacy3', $CFG->defaultcourseroleid);
}
}
// default values
// default values
$mform->addElement('header', 'defaultheader', get_string('defaultvalues', 'admin'));
$mform->addElement('text', 'username', get_string('username'), 'size="20"');
@ -248,10 +258,10 @@ class admin_uploaduser_form2 extends moodleform {
$mform->setType('address', PARAM_MULTILANG);
$mform->setAdvanced('address');
/// Next the profile defaults
// Next the profile defaults
profile_definition($mform);
// hidden fields
// hidden fields
$mform->addElement('hidden', 'iid');
$mform->setType('iid', PARAM_INT);
@ -363,7 +373,7 @@ class admin_uploaduser_form2 extends moodleform {
class admin_uploaduser_form3 extends moodleform {
function definition (){
global $CFG, $USER;
$mform =& $this->_form;
$mform =& $this->_form;
$this->add_action_buttons(false, get_string('uploadnewfile'));
}
}

View File

@ -84,17 +84,13 @@ if(!empty($processed)) {
$ids = explode(',', $info);
if(!empty($ids[2])) {
$context = get_context_instance(CONTEXT_COURSE, $ids[1]);
if( role_assign(5, $ids[0], 0, $context->id) ) {
continue;
}
role_assign(5, $ids[0], $context->id);
} else {
if( empty($ids[1] ) ) {
continue;
}
$context = get_context_instance(CONTEXT_COURSE, $ids[1]);
if( role_unassign(5, $ids[0], 0, $context->id) ) {
continue;
}
role_unassign(5, $ids[0], $context->id);
}
}
redirect($return, get_string('changessaved'));
@ -104,14 +100,12 @@ if(!empty($processed)) {
echo '<form id="multienrol" name="multienrol" method="post" action="user_bulk_enrol.php">';
echo '<input type="hidden" name="processed" value="yes" />';
$count = 0;
foreach($users as $user)
{
foreach($users as $user) {
$temparray = array (
'<a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.SITEID.'">'.$user->fullname.'</a>'
);
$mycourses = get_my_courses($user->id);
foreach($courses as $acourse)
{
$mycourses = enrol_get_users_courses($user->id, false);
foreach($courses as $acourse) {
$state = '';
if (isset($mycourses[$acourse->id])) {
$state = 'checked="checked"';

View File

@ -25,129 +25,6 @@ class webservice_test_client_form extends moodleform {
// === Test client forms ===
class moodle_enrol_role_assign_form extends moodleform {
public function definition() {
global $CFG;
$mform = $this->_form;
$mform->addElement('header', 'wstestclienthdr', get_string('testclient', 'webservice'));
//note: these values are intentionally PARAM_RAW - we want users to test any rubbish as parameters
$data = $this->_customdata;
if ($data['authmethod'] == 'simple') {
$mform->addElement('text', 'wsusername', 'wsusername');
$mform->addElement('text', 'wspassword', 'wspassword');
} else if ($data['authmethod'] == 'token') {
$mform->addElement('text', 'token', 'token');
}
$mform->addElement('hidden', 'authmethod', $data['authmethod']);
$mform->setType('authmethod', PARAM_SAFEDIR);
/// specific to the create users function
$mform->addElement('text', 'userid', 'userid');
$mform->addElement('text', 'roleid', 'roleid');
$mform->addElement('text', 'contextid', 'contextid');
$mform->addElement('text', 'timestart', 'timestart');
$mform->addElement('text', 'timeend', 'timeend');
$mform->addElement('hidden', 'function');
$mform->setType('function', PARAM_SAFEDIR);
$mform->addElement('hidden', 'protocol');
$mform->setType('protocol', PARAM_SAFEDIR);
$mform->addElement('static', 'warning', '', get_string('executewarnign', 'webservice'));
$this->add_action_buttons(true, get_string('execute', 'webservice'));
}
public function get_params() {
if (!$data = $this->get_data()) {
return null;
}
// remove unused from form data
unset($data->submitbutton);
unset($data->protocol);
unset($data->function);
unset($data->wsusername);
unset($data->wspassword);
unset($data->token);
unset($data->authmethod);
$params = array();
$params['enrolments'] = array();
$params['enrolments'][] = (array)$data;
return $params;
}
}
class moodle_enrol_role_unassign_form extends moodleform {
public function definition() {
global $CFG;
$mform = $this->_form;
$mform->addElement('header', 'wstestclienthdr', get_string('testclient', 'webservice'));
//note: these values are intentionally PARAM_RAW - we want users to test any rubbish as parameters
$data = $this->_customdata;
if ($data['authmethod'] == 'simple') {
$mform->addElement('text', 'wsusername', 'wsusername');
$mform->addElement('text', 'wspassword', 'wspassword');
} else if ($data['authmethod'] == 'token') {
$mform->addElement('text', 'token', 'token');
}
$mform->addElement('hidden', 'authmethod', $data['authmethod']);
$mform->setType('authmethod', PARAM_SAFEDIR);
/// specific to the create users function
$mform->addElement('text', 'userid', 'userid');
$mform->addElement('text', 'roleid', 'roleid');
$mform->addElement('text', 'contextid', 'contextid');
$mform->addElement('hidden', 'function');
$mform->setType('function', PARAM_SAFEDIR);
$mform->addElement('hidden', 'protocol');
$mform->setType('protocol', PARAM_SAFEDIR);
$mform->addElement('static', 'warning', '', get_string('executewarnign', 'webservice'));
$this->add_action_buttons(true, get_string('execute', 'webservice'));
}
public function get_params() {
if (!$data = $this->get_data()) {
return null;
}
// remove unused from form data
unset($data->submitbutton);
unset($data->protocol);
unset($data->function);
unset($data->wsusername);
unset($data->wspassword);
unset($data->token);
unset($data->authmethod);
$params = array();
$params['unenrolments'] = array();
$params['unenrolments'][] = (array)$data;
return $params;
}
}
class moodle_user_create_users_form extends moodleform {
public function definition() {
global $CFG;
@ -273,7 +150,7 @@ class moodle_user_update_users_form extends moodleform {
if (!$data = $this->get_data()) {
return null;
}
//set customfields
if (!empty($data->customfieldtype)) {
$data->customfields = array(array('type' => $data->customfieldtype, 'value' => $data->customfieldvalue));
@ -369,7 +246,7 @@ class moodle_user_delete_users_form extends moodleform {
$params['userids'][] = $data->userids[$i];
}
/// end of specific code to the create users function
return $params;
}
}
@ -449,7 +326,7 @@ class moodle_group_create_groups_form extends moodleform {
global $CFG;
$mform = $this->_form;
$mform->addElement('header', 'wstestclienthdr', get_string('testclient', 'webservice'));
@ -476,7 +353,7 @@ class moodle_group_create_groups_form extends moodleform {
$mform->addElement('hidden', 'protocol');
$mform->setType('protocol', PARAM_SAFEDIR);
$mform->addElement('static', 'warning', '', get_string('executewarnign', 'webservice'));

View File

@ -824,9 +824,9 @@ if ( !is_object($PHPCAS_CLIENT) ) {
// update course creators if needed
if ($creatorrole !== false) {
if ($this->iscreator($user->username)) {
role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'cas');
role_assign($creatorrole->id, $user->id, $sitecontext->id, 'auth_cas');
} else {
role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id, 'cas');
role_unassign($creatorrole->id, $user->id, $sitecontext->id, 'auth_cas');
}
}
}
@ -883,7 +883,7 @@ if ( !is_object($PHPCAS_CLIENT) ) {
// add course creators if needed
if ($creatorrole !== false and $this->iscreator($user->username)) {
role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'cas');
role_assign($creatorrole->id, $user->id, $sitecontext->id, 'auth_cas');
}
}
$transaction->allow_commit();
@ -1127,10 +1127,10 @@ if (!empty($this->config->attrcreators)) {
$creatorrole = array_shift($roles); // We can only use one, let's use the first one
$systemcontext = get_context_instance(CONTEXT_SYSTEM);
if ($iscreator) { // Following calls will not create duplicates
role_assign($creatorrole->id, $user->id, 0, $systemcontext->id, 0, 0, 0, 'cas');
role_assign($creatorrole->id, $user->id, $systemcontext->id, 'auth_cas');
} else {
//unassign only if previously assigned by this plugin!
role_unassign($creatorrole->id, $user->id, 0, $systemcontext->id, 'cas');
role_unassign($creatorrole->id, $user->id, $systemcontext->id, 'auth_cas');
}
}
}

View File

@ -183,10 +183,10 @@ class auth_plugin_fc extends auth_plugin_base {
$systemcontext = get_context_instance(CONTEXT_SYSTEM);
if ($iscreator) { // Following calls will not create duplicates
role_assign($creatorrole->id, $user->id, 0, $systemcontext->id, 0, 0, 0, 'fc');
role_assign($creatorrole->id, $user->id, $systemcontext->id, 'auth_fc');
} else {
//unassign only if previously assigned by this plugin!
role_unassign($creatorrole->id, $user->id, 0, $systemcontext->id, 'fc');
role_unassign($creatorrole->id, $user->id, $systemcontext->id, 'auth_fc');
}
}
}

View File

@ -744,9 +744,9 @@ class auth_plugin_ldap extends auth_plugin_base {
// update course creators if needed
if ($creatorrole !== false) {
if ($this->iscreator($user->username)) {
role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
role_assign($creatorrole->id, $user->id, $sitecontext->id, 'auth_ldap');
} else {
role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id, 'ldap');
role_unassign($creatorrole->id, $user->id, $sitecontext->id, 'auth_ldap');
}
}
}
@ -807,7 +807,7 @@ class auth_plugin_ldap extends auth_plugin_base {
// add course creators if needed
if ($creatorrole !== false and $this->iscreator($user->username)) {
role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
role_assign($creatorrole->id, $user->id, $sitecontext->id, 'auth_ldap');
}
}
$transaction->allow_commit();
@ -1948,10 +1948,10 @@ class auth_plugin_ldap extends auth_plugin_base {
$systemcontext = get_context_instance(CONTEXT_SYSTEM);
if ($iscreator) { // Following calls will not create duplicates
role_assign($creatorrole->id, $user->id, 0, $systemcontext->id, 0, 0, 0, 'ldap');
role_assign($creatorrole->id, $user->id, $systemcontext->id, 'auth_ldap');
} else {
//unassign only if previously assigned by this plugin!
role_unassign($creatorrole->id, $user->id, 0, $systemcontext->id, 'ldap');
role_unassign($creatorrole->id, $user->id, $systemcontext->id, 'auth_ldap');
}
}
}

View File

@ -87,7 +87,7 @@ class auth_plugin_mnet extends auth_plugin_base {
}
$userdata['myhosts'] = array();
if($courses = get_my_courses($user->id, 'id', 'id, visible')) {
if ($courses = enrol_get_users_courses($user->id, false)) {
$userdata['myhosts'][] = array('name'=> $SITE->shortname, 'url' => $CFG->wwwroot, 'count' => count($courses));
}
@ -349,41 +349,33 @@ class auth_plugin_mnet extends auth_plugin_base {
// pass username and an assoc array of "my courses"
// with info so that the IDP can maintain mnet_enrol_assignments
$mnetrequest->add_param($remoteuser->username);
$fields = 'id, category, sortorder, fullname, shortname, idnumber, summary,
startdate, cost, currency, defaultrole, visible';
$courses = get_my_courses($localuser->id, 'visible DESC,sortorder ASC', $fields);
$fields = 'id, category, sortorder, fullname, shortname, idnumber, summary, startdate, visible';
$courses = enrol_get_users_courses($localuser->id, false, $fields, 'visible DESC,sortorder ASC');
if (is_array($courses) && !empty($courses)) {
// Second request to do the JOINs that we'd have done
// inside get_my_courses() if we had been allowed
// inside enrol_get_users_courses() if we had been allowed
$sql = "SELECT c.id,
cc.name AS cat_name, cc.description AS cat_description,
r.shortname as defaultrolename
cc.name AS cat_name, cc.description AS cat_description
FROM {course} c
JOIN {course_categories} cc ON c.category = cc.id
LEFT OUTER JOIN {role} r ON c.defaultrole = r.id
WHERE c.id IN (" . join(',',array_keys($courses)) . ')';
$extra = $DB->get_records_sql($sql);
$keys = array_keys($courses);
$defaultrolename = $DB->get_field('role', 'shortname', array('id'=>$CFG->defaultcourseroleid));
$defaultrole = get_default_course_role($ccache[$shortname]); //TODO: rewrite this completely, there is no default course role any more!!!
foreach ($keys AS $id) {
if ($courses[$id]->visible == 0) {
unset($courses[$id]);
continue;
}
$courses[$id]->cat_id = $courses[$id]->category;
$courses[$id]->defaultroleid = $courses[$id]->defaultrole;
$courses[$id]->defaultroleid = $defaultrole->id;
unset($courses[$id]->category);
unset($courses[$id]->defaultrole);
unset($courses[$id]->visible);
$courses[$id]->cat_name = $extra[$id]->cat_name;
$courses[$id]->cat_description = $extra[$id]->cat_description;
if (!empty($extra[$id]->defaultrolename)) {
$courses[$id]->defaultrolename = $extra[$id]->defaultrolename;
} else {
$courses[$id]->defaultrolename = $defaultrolename;
}
$courses[$id]->defaultrolename = $defaultrole->name;
// coerce to array
$courses[$id] = (array)$courses[$id];
}
@ -486,10 +478,6 @@ class auth_plugin_mnet extends auth_plugin_base {
c.idnumber,
c.summary,
c.startdate,
c.cost,
c.currency,
c.defaultroleid,
c.defaultrolename,
a.id as assignmentid
FROM
{mnet_enrol_course} c

View File

@ -76,7 +76,7 @@
}
}
check_enrolment_plugins($USER);
enrol_check_plugins($USER);
load_all_capabilities(); /// This is what lets the user do anything on the site :-)
redirect($urltogo);

View File

@ -162,10 +162,7 @@
function backup_get_enrolled_users ($courseid) {
global $CFG;
// get all users with moodle/course:participate capability, this will include people
// assigned at cat level, or site level
// but it should be ok if they have no direct assignment at course, mod, block level
return get_users_by_capability(get_context_instance(CONTEXT_COURSE, $courseid), 'moodle/course:participate', '', '', '', '', '', '', false);
return get_enrolled_users(get_context_instance(CONTEXT_COURSE, $courseid));
}
//Returns all users ids (every record in users table)

View File

@ -69,9 +69,11 @@ class backup_course_task extends backup_task {
$this->add_step(new create_taskbasepath_directory('create_course_directory'));
// Create the course.xml file with course & category information
// annotating some bits, metacourse info, tags and module restrictions
// annotating some bits, tags and module restrictions
$this->add_step(new backup_course_structure_step('course_info', 'course.xml'));
//TODO: MDL-22793 - add user_enrolments entries
// Annotate the groups used in already annotated groupings
$this->add_step(new backup_annotate_groups_from_groupings('annotate_groups'));

View File

@ -40,6 +40,8 @@ class backup_final_task extends backup_task {
$coursectxid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id;
$this->add_setting(new backup_activity_generic_setting(backup::VAR_CONTEXTID, base_setting::IS_INTEGER, $coursectxid));
//TODO: MDL-22793 add enrol instances of enabled enrol plugins in course,
// Generate the groups file with the final annotated groups and groupings
// including membership based on setting
$this->add_step(new backup_groups_structure_step('groups', 'groups.xml'));

View File

@ -202,7 +202,7 @@ class backup_section_structure_step extends backup_structure_step {
/**
* structure step that will generate the course.xml file for the course, including
* course category reference, tags, metacourse, modules restriction information
* course category reference, tags, modules restriction information
* and some annotations (files & groupings)
*/
class backup_course_structure_step extends backup_structure_step {
@ -213,16 +213,15 @@ class backup_course_structure_step extends backup_structure_step {
// Define each element separated
$course = new backup_nested_element('course', array('id', 'contextid'), array(
'shortname', 'fullname', 'idnumber', 'password',
'shortname', 'fullname', 'idnumber',
'summary', 'summaryformat', 'format', 'showgrades',
'newsitems', 'guest', 'startdate', 'enrolperiod',
'newsitems', 'startdate',
'numsections', 'marker', 'maxbytes', 'showreports',
'visible', 'hiddensections', 'groupmode', 'groupmodeforce',
'defaultgroupingid', 'lang', 'theme', 'cost',
'currency', 'timecreated', 'timemodified', 'metacourse',
'requested', 'restrictmodules', 'expirynotify', 'expirythreshold',
'notifystudents', 'enrollable', 'enrolstartdate', 'enrolenddate',
'enrol', 'defaultrole', 'enablecompletion'));
'defaultgroupingid', 'lang', 'theme',
'timecreated', 'timemodified',
'requested', 'restrictmodules',
'enablecompletion'));
$category = new backup_nested_element('category', array('id'), array(
'name', 'description'));
@ -272,7 +271,6 @@ class backup_course_structure_step extends backup_structure_step {
// Some annotations
$course->annotate_ids('role', 'defaultrole');
$course->annotate_ids('grouping', 'defaultgroupingid');
$course->annotate_files(array('course_summary', 'course_content'), null);
@ -307,8 +305,7 @@ class backup_roles_structure_step extends backup_structure_step {
$assignments = new backup_nested_element('role_assignments');
$assignment = new backup_nested_element('assignment', array('id'), array(
'roleid', 'userid', 'hidden', 'timestart',
'timeend', 'timemodified', 'modifierid', 'enrol',
'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
'sortorder'));
// Build the tree
@ -714,8 +711,7 @@ class backup_users_structure_step extends backup_structure_step {
$assignments = new backup_nested_element('role_assignments');
$assignment = new backup_nested_element('assignment', array('id'), array(
'roleid', 'userid', 'hidden', 'timestart',
'timeend', 'timemodified', 'modifierid', 'enrol',
'roleid', 'userid', 'timemodified', 'modifierid', 'component', //TODO: MDL-22793 add itemid here
'sortorder'));
// Build the tree

View File

@ -92,8 +92,6 @@
}
//restoreto
$restore_restoreto = required_param('restore_restoreto', PARAM_INT);
//restore_metacourse
$restore_metacourse = required_param('restore_metacourse', PARAM_INT);
//restore_users
$restore_users = required_param('restore_users', PARAM_INT);
@ -140,7 +138,6 @@
}
}
$restore->restoreto=$restore_restoreto;
$restore->metacourse=$restore_metacourse;
$restore->users=$restore_users;
$restore->groups=$restore_groups;
$restore->logs=$restore_logs;
@ -220,15 +217,9 @@
//Check site
$site = get_site();
// Non-cached - get accessinfo
if (isset($USER->access)) {
$accessinfo = $USER->access;
} else {
$accessinfo = get_user_access_sitewide($USER->id);
}
// Get all the courses the user is able to restore to
$mycourses = get_user_courses_bycap($USER->id, 'moodle/restore:restorecourse', $accessinfo, true, 'c.sortorder ASC', array('id', 'fullname', 'shortname', 'visible'));
//TODO: use better function which includes all courses for admins
$mycourses = get_user_courses_bycap($USER->id, 'moodle/restore:restorecourse');
// Calculate if the user can create courses
$cancreatecourses = user_can_create_courses();

View File

@ -77,11 +77,6 @@
}
}
//Check other parameters
if (!isset($restore_metacourse)) {
$restore_metacourse = 1;
}
if (!isset($restore_users)) {
$restore_users = 1;
}
@ -201,14 +196,8 @@ function selectItemInCheckboxByName(formId, checkName, checked ) {
// permission should have been checked already
// Non-cached - get accessinfo
if (isset($USER->access)) {
$accessinfo = $USER->access;
} else {
$accessinfo = get_user_access_sitewide($USER->id);
}
$mycourses = get_user_courses_bycap($USER->id, 'moodle/restore:restorecourse', $accessinfo, true);
//TODO: use better function which includes all courses for admins
$mycourses = get_user_courses_bycap($USER->id, 'moodle/restore:restorecourse');
// if the user can restore to current course, grant the "current" options
if (has_capability('moodle/restore:restorecourse', get_context_instance(CONTEXT_COURSE, $id))){
@ -418,22 +407,6 @@ function selectItemInCheckboxByName(formId, checkName, checked ) {
//Line
echo "<tr><td colspan=\"4\">$nonrestmod<hr /></td></tr>";
//Now print the Metacourse tr
echo "<tr>";
echo "<td align=\"right\" colspan=\"2\"><b>";
echo '<label for="menurestore_metacourse">'.get_string ("metacourse").'</label>';
echo "</b></td><td colspan=\"2\">";
//If metacourse are in the backup file, show menu, else fixed to no
if ($info->backup_metacourse == "true") {
$metacourse_options = array();
$metacourse_options[0] = get_string("no");
$metacourse_options[1] = get_string("yes");
echo html_writer::select($metacourse_options, "restore_metacourse", $restore_metacourse, false);
} else {
echo get_string("no");
echo "<input type=\"hidden\" id=\"menurestore_metacourse\" name=\"restore_metacourse\" value=\"0\" />";
}
echo "</td></tr>";
//Now print the Users tr
echo "<tr>";
echo "<td align=\"right\" colspan=\"2\"><b>";

View File

@ -1555,9 +1555,7 @@ define('RESTORE_GROUPS_GROUPINGS', 3);
if(!isset($restore->userswhocanviewcourse)) {
// Because this is only used here, there is no point requesting
// anything except id
$restore->userswhocanviewcourse=get_users_by_capability(
get_context_instance(CONTEXT_COURSE, $restore->course_id),
'moodle/course:participate','u.id');
$restore->userswhocanviewcourse = get_enrolled_users(get_context_instance(CONTEXT_COURSE, $restore->course_id), '', 0, 'u.id');
}
foreach($info->completiondata as $data) {
@ -9703,13 +9701,7 @@ WHERE
return true;
}
// Non-cached - get accessinfo
if (isset($USER->access)) {
$accessinfo = $USER->access;
} else {
$accessinfo = get_user_access_sitewide($USER->id);
}
$courses = get_user_courses_bycap($USER->id, 'moodle/restore:rolldates', $accessinfo, true);
$courses = get_user_courses_bycap($USER->id, 'moodle/restore:rolldates');
return !empty($courses);
}

View File

@ -36,11 +36,8 @@ class block_course_list extends block_list {
if (empty($CFG->disablemycourses) and isloggedin() and !isguestuser() and
!(has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM)) and $adminseesall)) { // Just print My Courses
if ($courses = get_my_courses($USER->id, 'visible DESC, fullname ASC')) {
if ($courses = enrol_get_my_courses(NULL, 'visible DESC, fullname ASC')) {
foreach ($courses as $course) {
if ($course->id == SITEID) {
continue;
}
$linkcss = $course->visible ? "" : " class=\"dimmed\" ";
$this->content->items[]="<a $linkcss title=\"" . format_string($course->shortname) . "\" ".
"href=\"$CFG->wwwroot/course/view.php?id=$course->id\">" . format_string($course->fullname) . "</a>";

View File

@ -65,7 +65,7 @@ class block_course_overview extends block_base {
$courses_limit = $courses_limit + 1;
}
$courses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', '*', false, $courses_limit);
$courses = enrol_get_my_courses(NULL, 'visible DESC,sortorder ASC', '*', $courses_limit);
$site = get_site();
$course = $site; //just in case we need the old global $course hack

View File

@ -27,7 +27,7 @@ class block_course_summary extends block_base {
$options = new object();
$options->noclean = true; // Don't clean Javascripts etc
$context = get_context_instance(CONTEXT_COURSE, $this->page->course->id);
$this->page->course->summary = file_rewrite_pluginfile_urls($this->page->course->summary, 'pluginfile.php', $context->id, 'course_summary', $this->page->course->id);
$this->page->course->summary = file_rewrite_pluginfile_urls($this->page->course->summary, 'pluginfile.php', $context->id, 'course_summary', NULL);
$this->content->text = format_text($this->page->course->summary, $this->page->course->summaryformat, $options);
if ($this->page->user_is_editing()) {
if($this->page->course->id == SITEID) {

View File

@ -9,7 +9,7 @@
//
// The upgrade function in this file will attempt
// to perform all the necessary actions to upgrade
// your older installtion to the current version.
// your older installation to the current version.
//
// If there's something it cannot do itself, it
// will tell you what you need to do.

View File

@ -33,7 +33,7 @@ $allowed_time = array('weeknow', 'weeknext', 'monthnow', 'monthnext', 'recentupc
if(!empty($what) && !empty($time)) {
if(in_array($what, $allowed_what) && in_array($time, $allowed_time)) {
$courses = get_my_courses($user->id, NULL, 'id, visible, shortname');
$courses = enrol_get_users_courses($user->id, true, 'id, visible, shortname');
if ($what == 'all') {
$users = $user->id;

View File

@ -1429,12 +1429,7 @@ function calendar_get_default_courses($ignoreref = false) {
}
}
if (isset($CFG->adminseesall)) {
$courses = get_my_courses($USER->id, null, null, $CFG->adminseesall);
}
else {
$courses = get_my_courses($USER->id, null, null, false);
}
$courses = enrol_get_my_courses();
return $courses;
}

View File

@ -636,7 +636,7 @@ function calendar_course_filter_selector($getvars = '') {
if (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM)) && !empty($CFG->calendar_adminseesall)) {
$courses = get_courses('all', 'c.shortname','c.id,c.shortname');
} else {
$courses = get_my_courses($USER->id, 'shortname');
$courses = enrol_get_my_courses();
}
unset($courses[SITEID]);

View File

@ -26,6 +26,7 @@
*/
require('../config.php');
require($CFG->dirroot.'/course/lib.php');
require($CFG->dirroot.'/cohort/lib.php');
require($CFG->dirroot.'/cohort/edit_form.php');

View File

@ -28,25 +28,56 @@ require_once($CFG->dirroot . '/user/selector/lib.php');
/**
* Add new cohort.
* @param object $data
* @return void
*
* @param object $cohort
* @return int
*/
function cohort_add_cohort($data) {
function cohort_add_cohort($cohort) {
global $DB;
$data->timecreated = time();
$data->timemodified = $data->timecreated;
$DB->insert_record('cohort', $data);
if (!isset($cohort->name)) {
throw new coding_excetion('Missing cohort name in cohort_add_cohort().');
}
if (!isset($cohort->idnumber)) {
$cohort->idnumber = NULL;
}
if (!isset($cohort->description)) {
$cohort->description = $DB->sql_empty();
}
if (!isset($cohort->descriptionformat)) {
$cohort->descriptionformat = FORMAT_HTML;
}
if (empty($cohort->component)) {
$cohort->component = '';
}
if (!isset($cohort->timecreated)) {
$cohort->timecreated = time();
}
if (!isset($cohort->timemodified)) {
$cohort->timemodified = $cohort->timecreated;
}
$cohort->id = $DB->insert_record('cohort', $cohort);
events_trigger('cohort_added', $cohort);
return $cohort->id;
}
/**
* Update existing cohort.
* @param object $data
* @param object $cohort
* @return void
*/
function cohort_update_cohort($data) {
function cohort_update_cohort($cohort) {
global $DB;
$data->timemodified = time();
$DB->update_record('cohort', $data);
if (isset($cohort->component) and empty($cohort->component)) {
$cohort->component = NULL;
}
$cohort->timemodified = time();
$DB->update_record('cohort', $cohort);
events_trigger('cohort_updated', $cohort);
}
/**
@ -63,6 +94,8 @@ function cohort_delete_cohort($cohort) {
$DB->delete_records('cohort_members', array('cohortid'=>$cohort->id));
$DB->delete_records('cohort', array('id'=>$cohort->id));
events_trigger('cohort_deleted', $cohort);
}
/**
@ -104,6 +137,8 @@ function cohort_add_member($cohortid, $userid) {
$record->userid = $userid;
$record->timeadded = time();
$DB->insert_record('cohort_members', $record);
events_trigger('cohort_member_added', (object)array('cohortid'=>$cohortid, 'userid'=>$userid));
}
/**
@ -115,6 +150,8 @@ function cohort_add_member($cohortid, $userid) {
function cohort_remove_member($cohortid, $userid) {
global $DB;
$DB->delete_records('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
events_trigger('cohort_member_removed', (object)array('cohortid'=>$cohortid, 'userid'=>$userid));
}
/**
@ -268,7 +305,7 @@ class cohort_existing_selector extends user_selector_base {
return array($groupname => $availableusers);
}
protected function get_options() {
$options = parent::get_options();
$options['cohortid'] = $this->cohortid;

View File

@ -112,9 +112,8 @@
if ($course) {
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
require_capability('moodle/course:visibility', $coursecontext);
if (!$DB->set_field('course', 'visible', $visible, array('id' => $course->id))) {
print_error('errorupdatingcoursevisibility');
}
$DB->set_field('course', 'visible', $visible, array('id' => $course->id));
$DB->set_field('course', 'visibleold', $visible, array('id' => $course->id)); // we set the old flag when user manually changes visibility of course
}
}
@ -244,7 +243,7 @@
/// Print out all the courses
$courses = get_courses_page($category->id, 'c.sortorder ASC',
'c.id,c.sortorder,c.shortname,c.fullname,c.summary,c.visible,c.guest,c.password',
'c.id,c.sortorder,c.shortname,c.fullname,c.summary,c.visible',
$totalcount, $page*$perpage, $perpage);
$numcourses = count($courses);
@ -274,7 +273,6 @@
$strshow = get_string('show');
$strsummary = get_string('summary');
$strsettings = get_string('settings');
$strassignteachers = get_string('assignteachers');
$strallowguests = get_string('allowguests');
$strrequireskey = get_string('requireskey');
@ -401,16 +399,7 @@
echo '</td>';
} else {
echo '<td align="right">';
if (!empty($acourse->guest)) {
echo '<a href="view.php?id='.$acourse->id.'"><img title="'.
$strallowguests.'" class="icon" src="'.
$OUTPUT->pix_url('i/guest') . '" alt="'.$strallowguests.'" /></a>';
}
if (!empty($acourse->password)) {
echo '<a href="view.php?id='.$acourse->id.'"><img title="'.
$strrequireskey.'" class="icon" src="'.
$OUTPUT->pix_url('i/key') . '" alt="'.$strrequireskey.'" /></a>';
}
//TODO: show some icons for plugins - such as guest, pasword, etc.
if (!empty($acourse->summary)) {
$link = new moodle_url("/course/info.php?id=$acourse->id");
echo $OUTPUT->action_link($link, '<img alt="'.get_string('info').'" class="icon" src="'.$OUTPUT->pix_url('i/info') . '" />',

View File

@ -1,165 +1,159 @@
<?php
// Edit course settings
require_once('../config.php');
require_once($CFG->dirroot.'/enrol/enrol.class.php');
require_once('lib.php');
require_once('edit_form.php');
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
$id = optional_param('id', 0, PARAM_INT); // course id
$categoryid = optional_param('category', 0, PARAM_INT); // course category - can be changed in edit form
/**
* Edit course settings
*
* @package moodlecore
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$PAGE->set_pagelayout('admin');
require_once('../config.php');
require_once('lib.php');
require_once('edit_form.php');
/// basic access control checks
if ($id) { // editing course
$id = optional_param('id', 0, PARAM_INT); // course id
$categoryid = optional_param('category', 0, PARAM_INT); // course category - can be changed in edit form
if($id == SITEID){
// don't allow editing of 'site course' using this from
print_error('cannoteditsiteform');
}
$PAGE->set_pagelayout('admin');
$PAGE->set_url('/course/edit.php');
if (!$course = $DB->get_record('course', array('id'=>$id))) {
print_error('invalidcourseid');
}
require_login($course->id);
$category = $DB->get_record('course_categories', array('id'=>$course->category));
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
require_capability('moodle/course:update', $coursecontext);
} else if ($categoryid) { // creating new course in this category
$course = null;
require_login();
if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
print_error('unknowcategory');
}
require_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $category->id));
} else {
require_login();
print_error('needcoursecategroyid');
// basic access control checks
if ($id) { // editing course
if ($id == SITEID){
// don't allow editing of 'site course' using this from
print_error('cannoteditsiteform');
}
$PAGE->set_url('/course/edit.php');
if ($id !== 0) {
$PAGE->url->param('id',$id);
$course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST);
require_login($course->id);
$category = $DB->get_record('course_categories', array('id'=>$course->category), '*', MUST_EXIST);
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
require_capability('moodle/course:update', $coursecontext);
$PAGE->url->param('id',$id);
} else if ($categoryid) { // creating new course in this category
$course = null;
require_login();
$category = $DB->get_record('course_categories', array('id'=>$categoryid), '*', MUST_EXIST);
require_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $category->id));
$PAGE->url->param('category',$categoryid);
} else {
require_login();
print_error('needcoursecategroyid');
}
// Prepare course and the editor
$editoroptions = array('maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes'=>$CFG->maxbytes, 'trusttext'=>false, 'noclean'=>true);
if (!empty($course)) {
$allowedmods = array();
if ($am = $DB->get_records('course_allowed_modules', array('course'=>$course->id))) {
foreach ($am as $m) {
$allowedmods[] = $m->module;
}
} else {
$PAGE->url->param('category',$categoryid);
// this happens in case we edit course created before enabling module restrictions or somebody disabled everything :-(
if (empty($course->restrictmodules) and !empty($CFG->defaultallowedmodules)) {
$allowedmods = explode(',', $CFG->defaultallowedmodules);
}
}
$course->allowedmods = $allowedmods;
$course = file_prepare_standard_editor($course, 'summary', $editoroptions, $coursecontext, 'course_summary', 0);
} else {
$course = file_prepare_standard_editor($course, 'summary', $editoroptions, null, 'course_summary', null);
}
// first create the form
$editform = new course_edit_form(NULL, array('course'=>$course, 'category'=>$category, 'editoroptions'=>$editoroptions));
if ($editform->is_cancelled()) {
if (empty($course)) {
redirect($CFG->wwwroot.'/');
} else {
redirect($CFG->wwwroot.'/course/view.php?id='.$course->id);
}
/// Prepare course and the editor
$editoroptions = array('maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes'=>$CFG->maxbytes, 'trusttext'=>false, 'noclean'=>true);
if (!empty($course)) {
$allowedmods = array();
if (!empty($course)) {
if ($am = $DB->get_records('course_allowed_modules', array('course'=>$course->id))) {
foreach ($am as $m) {
$allowedmods[] = $m->module;
} else if ($data = $editform->get_data()) {
// process data if submitted
if (empty($course->id)) {
// In creating the course
$course = create_course($data, $editoroptions);
// Get the context of the newly created course
$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
// try to deal with course creators - enrol them internally with default role
if (!empty($CFG->creatornewroleid) and !is_viewing($context, NULL, 'moodle/role:assign') and !is_enrolled($context, NULL, 'moodle/role:assign')) {
enrol_try_internal_enrol($course->id, $USER->id, $CFG->creatornewroleid);
}
// Redirect to manual enrolment page if possible
$instances = enrol_get_instances($course->id, true);
foreach($instances as $instance) {
if ($plugin = enrol_get_plugin($instance->enrol)) {
if ($link = $plugin->get_manual_enrol_link($instance)) {
redirect($link);
}
} else {
if (empty($course->restrictmodules)) {
$allowedmods = explode(',',$CFG->defaultallowedmodules);
} // it'll be greyed out but we want these by default anyway.
}
$course->allowedmods = $allowedmods;
}
$course = file_prepare_standard_editor($course, 'summary', $editoroptions, $coursecontext, 'course_summary', $course->id);
redirect($CFG->wwwroot."/course/view.php?id=$course->id");
} else {
$course = file_prepare_standard_editor($course, 'summary', $editoroptions, null, 'course_summary', null);
}
/// first create the form
$editform = new course_edit_form('edit.php', compact('course', 'category', 'editoroptions'));
// now override defaults if course already exists
if (!empty($course->id)) {
$course->enrolpassword = $course->password; // we need some other name for password field MDL-9929
$editform->set_data($course);
}
if ($editform->is_cancelled()){
if (empty($course)) {
redirect($CFG->wwwroot);
} else {
redirect($CFG->wwwroot.'/course/view.php?id='.$course->id);
}
} else if ($data = $editform->get_data()) {
$data->password = $data->enrolpassword; // we need some other name for password field MDL-9929
/// process data if submitted
//preprocess data
$data->timemodified = time();
if (empty($course->id)) {
// In creating the course
if (!$course = create_course($data)) {
print_error('coursenotcreated');
}
// Get the context of the newly created course
$context = get_context_instance(CONTEXT_COURSE, $course->id);
// Save the files used in the summary editor
$editordata = new stdClass;
$editordata->id = $course->id;
$editordata->summary_editor = $data->summary_editor;
$editordata = file_postupdate_standard_editor($editordata, 'summary', $editoroptions, $context, 'course_summary', $course->id);
$DB->update_record('course', $editordata);
// assign default role to creator if not already having permission to manage course assignments
if (!is_viewing($context, NULL, 'moodle/role:assign') and !is_enrolled($context, NULL, 'moodle/role:assign')) {
role_assign($CFG->creatornewroleid, $USER->id, 0, $context->id);
}
// ensure we can use the course right after creating it
// this means trigger a reload of accessinfo...
mark_context_dirty($context->path);
if ($data->metacourse and has_capability('moodle/course:managemetacourse', $context)) {
// Redirect users with metacourse capability to student import
redirect($CFG->wwwroot."/course/importstudents.php?id=$course->id");
} else {
// Redirect to roles assignment
redirect($CFG->wwwroot."/$CFG->admin/roles/assign.php?contextid=$context->id");
}
} else {
// Save any changes to the files used in the editor
$data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $coursecontext, 'course_summary', $data->id);
if (!update_course($data)) {
print_error('coursenotupdated');
}
redirect($CFG->wwwroot."/course/view.php?id=$course->id");
}
// Save any changes to the files used in the editor
update_course($data, $editoroptions);
redirect($CFG->wwwroot."/course/view.php?id=$course->id");
}
}
/// Print the form
// Print the form
$site = get_site();
$site = get_site();
$streditcoursesettings = get_string("editcoursesettings");
$straddnewcourse = get_string("addnewcourse");
$stradministration = get_string("administration");
$strcategories = get_string("categories");
$streditcoursesettings = get_string("editcoursesettings");
$straddnewcourse = get_string("addnewcourse");
$stradministration = get_string("administration");
$strcategories = get_string("categories");
if (!empty($course->id)) {
$PAGE->navbar->add($streditcoursesettings);
$title = $streditcoursesettings;
$fullname = $course->fullname;
} else {
$PAGE->navbar->add($stradministration, new moodle_url('/admin/index.php'));
$PAGE->navbar->add($strcategories, new moodle_url('/course/index.php'));
$PAGE->navbar->add($straddnewcourse);
$title = "$site->shortname: $straddnewcourse";
$fullname = $site->fullname;
}
if (!empty($course->id)) {
$PAGE->navbar->add($streditcoursesettings);
$title = $streditcoursesettings;
$fullname = $course->fullname;
} else {
$PAGE->navbar->add($stradministration, new moodle_url('/admin/index.php'));
$PAGE->navbar->add($strcategories, new moodle_url('/course/index.php'));
$PAGE->navbar->add($straddnewcourse);
$title = "$site->shortname: $straddnewcourse";
$fullname = $site->fullname;
}
$PAGE->set_title($title);
$PAGE->set_heading($fullname);
$PAGE->set_focuscontrol($editform->focus());
echo $OUTPUT->header();
echo $OUTPUT->heading($streditcoursesettings);
$PAGE->set_title($title);
$PAGE->set_heading($fullname);
$PAGE->set_focuscontrol($editform->focus());
$editform->display();
echo $OUTPUT->header();
echo $OUTPUT->heading($streditcoursesettings);
echo $OUTPUT->footer();
$editform->display();
echo $OUTPUT->footer();

View File

@ -1,83 +1,73 @@
<?php
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir.'/formslib.php');
class course_edit_form extends moodleform {
protected $course;
protected $context;
function definition() {
global $USER, $CFG, $DB;
$courseconfig = get_config('moodlecourse');
$mform =& $this->_form;
$mform = $this->_form;
$course = $this->_customdata['course'];
$category = $this->_customdata['category'];
$course = $this->_customdata['course']; // this contains the data of this form
$category = $this->_customdata['category'];
$editoroptions = $this->_customdata['editoroptions'];
$systemcontext = get_context_instance(CONTEXT_SYSTEM);
$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->id)) {
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$context = $coursecontext;
if (course_in_meta($course)) {
$disable_meta = get_string('metaalreadyinmeta');
} else if ($course->metacourse) {
if ($DB->count_records('course_meta', array('parent_course'=>$course->id)) > 0) {
$disable_meta = get_string('metaalreadyhascourses');
}
} else {
// if users already enrolled directly into coures, do not allow switching to meta,
// users with metacourse manage permission are exception
// please note that we do not need exact results - anything unexpected here prevents metacourse
$managers = get_users_by_capability($coursecontext, 'moodle/course:managemetacourse', 'u.id');
$enrolroles = get_roles_with_capability('moodle/course:participate', CAP_ALLOW, $coursecontext);
if ($users = get_role_users(array_keys($enrolroles), $coursecontext, false, 'u.id', 'u.id ASC')) {
foreach($users as $user) {
if (!isset($managers[$user->id])) {
$disable_meta = get_string('metaalreadyhasenrolments');
break;
}
}
}
unset($managers);
unset($users);
unset($enrolroles);
}
} else {
$coursecontext = null;
$context = $categorycontext;
}
$courseconfig = get_config('moodlecourse');
$this->course = $course;
$this->context = $context;
/// form definition with new course defaults
//--------------------------------------------------------------------------------
$mform->addElement('header','general', get_string('general', 'form'));
// Must have create course capability in both categories in order to move course
if (has_capability('moodle/course:create', $categorycontext)) {
$displaylist = array();
$parentlist = array();
make_categories_list($displaylist, $parentlist, 'moodle/course:create');
$mform->addElement('select', 'category', get_string('category'), $displaylist);
// verify permissions to change course category or keep current
if (empty($course->id)) {
if (has_capability('moodle/course:create', $categorycontext)) {
$displaylist = array();
$parentlist = array();
make_categories_list($displaylist, $parentlist, 'moodle/course:create');
$mform->addElement('select', 'category', get_string('category'), $displaylist);
$mform->addHelpButton('category', 'category');
$mform->setDefault('category', $category->id);
} else {
$mform->addElement('hidden', 'category', null);
$mform->setType('category', PARAM_INT);
$mform->setConstant('category', $category->id);
}
} else {
$mform->addElement('hidden', 'category', null);
$mform->setType('category', PARAM_INT);
}
$mform->addHelpButton('category', 'category');
$mform->setDefault('category', $category->id);
$mform->setType('category', PARAM_INT);
if (!empty($course->id) and !has_capability('moodle/course:changecategory', $coursecontext)) {
$mform->hardFreeze('category');
$mform->setConstant('category', $category->id);
if (has_capability('moodle/course:changecategory', $coursecontext)) {
$displaylist = array();
$parentlist = array();
make_categories_list($displaylist, $parentlist, 'moodle/course:create');
if (!isset($displaylist[$course->category])) {
//always keep current
$displaylist[$course->category] = format_string($DB->get_field('course_categories', 'name', array('id'=>$course->category)));
}
$mform->addElement('select', 'category', get_string('category'), $displaylist);
$mform->addHelpButton('category', 'category');
} else {
//keep current
$mform->addElement('hidden', 'category', null);
$mform->setType('category', PARAM_INT);
$mform->setConstant('category', $course->category);
}
}
$mform->addElement('text','fullname', get_string('fullnamecourse'),'maxlength="254" size="50"');
@ -175,106 +165,8 @@ class course_edit_form extends moodleform {
$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->addHelpButton('metacourse', 'managemeta');
$mform->setDefault('metacourse', $courseconfig->metacourse);
} else {
// no metacourse element - we do not want to change it anyway!
$mform->addElement('static', 'nometacourse', get_string('managemeta'),
((empty($course->metacourse)) ? $meta[0] : $meta[1]) . " - $disable_meta ");
$mform->addHelpButton('nometacourse', 'managemeta');
}
//--------------------------------------------------------------------------------
$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->addHelpButton('enrol', 'enrolmentplugins');
$mform->setDefault('enrol', $courseconfig->enrol);
$roles = get_assignable_roles($context);
if (!empty($course->id)) {
// add current default role, so that it is selectable even when user can not assign it
if ($current_role = $DB->get_record('role', array('id'=>$course->defaultrole))) {
$roles[$current_role->id] = strip_tags(format_string($current_role->name, true));
}
}
$choices = array();
if ($sitedefaultrole = $DB->get_record('role', array('id'=>$CFG->defaultcourseroleid))) {
$choices[0] = get_string('sitedefault').' ('.$sitedefaultrole->name.')';
} else {
$choices[0] = get_string('sitedefault');
}
$choices = $choices + $roles;
// fix for MDL-9197
foreach ($choices as $choiceid => $choice) {
$choices[$choiceid] = format_string($choice);
}
$mform->addElement('select', 'defaultrole', get_string('defaultrole', 'role'), $choices);
$mform->setDefault('defaultrole', 0);
$radio = array();
$radio[] = &MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('no'), 0);
$radio[] = &MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('yes'), 1);
$radio[] = &MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('enroldate'), 2);
$mform->addGroup($radio, 'enrollable', get_string('enrollable'), ' ', false);
$mform->addHelpButton('enrollable', 'enrollable');
$mform->setDefault('enrollable', $courseconfig->enrollable);
$mform->addElement('date_selector', 'enrolstartdate', get_string('enrolstartdate'), array('optional' => true));
$mform->setDefault('enrolstartdate', 0);
$mform->disabledIf('enrolstartdate', 'enrollable', 'neq', 2);
$mform->addElement('date_selector', 'enrolenddate', get_string('enrolenddate'), array('optional' => true));
$mform->setDefault('enrolenddate', 0);
$mform->disabledIf('enrolenddate', 'enrollable', 'neq', 2);
$mform->addElement('duration', 'enrolperiod', get_string('enrolperiod'), array('optional' => true, 'defaultunit' => 86400));
$mform->setDefault('enrolperiod', $courseconfig->enrolperiod);
//--------------------------------------------------------------------------------
$mform->addElement('header','expirynotifyhdr', get_string('expirynotify'));
$choices = array();
$choices['0'] = get_string('no');
$choices['1'] = get_string('yes');
$mform->addElement('select', 'expirynotify', get_string('notify'), $choices);
$mform->addHelpButton('expirynotify', 'notify');
$mform->setDefault('expirynotify', $courseconfig->expirynotify);
$mform->addElement('select', 'notifystudents', get_string('expirynotifystudents'), $choices);
$mform->addHelpButton('notifystudents', 'expirynotifystudents');
$mform->setDefault('notifystudents', $courseconfig->notifystudents);
$thresholdmenu=array();
for ($i=1; $i<=30; $i++) {
$seconds = $i * 86400;
$thresholdmenu[$seconds] = get_string('numdays', '', $i);
}
$mform->addElement('select', 'expirythreshold', get_string('expirythreshold'), $thresholdmenu);
$mform->addHelpButton('expirythreshold', 'expirythreshold');
$mform->setDefault('expirythreshold', $courseconfig->expirythreshold);
enrol_course_edit_form($mform, $course, $context);
//--------------------------------------------------------------------------------
$mform->addElement('header','', get_string('groups', 'group'));
@ -313,48 +205,6 @@ class course_edit_form extends moodleform {
$mform->setConstant('visible', $course->visible);
}
$mform->addElement('passwordunmask', 'enrolpassword', get_string('enrolmentkey'), 'size="25"');
$mform->setDefault('enrolpassword', '');
$mform->setDefault('enrolpassword', $courseconfig->enrolpassword);
$mform->setType('enrolpassword', PARAM_RAW);
if (empty($course->id) or ($course->password !== '' and $course->id != SITEID)) {
// do not require password in existing courses that do not have password yet - backwards compatibility ;-)
if (!empty($CFG->enrol_manual_requirekey)) {
$mform->addRule('enrolpassword', get_string('required'), 'required', null, 'client');
}
}
$choices = array();
$choices['0'] = get_string('guestsno');
$choices['1'] = get_string('guestsyes');
$choices['2'] = get_string('guestskey');
$mform->addElement('select', 'guest', get_string('opentoguests'), $choices);
$mform->setDefault('guest', $courseconfig->guest);
// If we are creating a course, its enrol method isn't yet chosen, BUT the site has a default enrol method which we can use here
$enrol_object = $CFG;
if (!empty($course->id)) {
$enrol_object = $course;
}
// If the print_entry method exists and the course enrol method isn't manual (both set or inherited from site), show cost
if (method_exists(enrolment_factory::factory($enrol_object->enrol), 'print_entry') && !($enrol_object->enrol == 'manual' || (empty($enrol_object->enrol) && $CFG->enrol == 'manual'))) {
$costgroup=array();
$currencies = get_string_manager()->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->setDefault('cost', '');
$mform->setDefault('currency', empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency);
}
//--------------------------------------------------------------------------------
$mform->addElement('header','', get_string('language'));
@ -386,31 +236,38 @@ class course_edit_form extends moodleform {
}
//--------------------------------------------------------------------------------
if (has_capability('moodle/site:config', $systemcontext) && ((!empty($course->requested) && $CFG->restrictmodulesfor == 'requested') || $CFG->restrictmodulesfor == 'all')) {
$mform->addElement('header', '', get_string('restrictmodules'));
if (has_capability('moodle/site:config', $systemcontext)) {
if (((!empty($course->requested) && $CFG->restrictmodulesfor == 'requested') || $CFG->restrictmodulesfor == 'all')) {
$mform->addElement('header', '', get_string('restrictmodules'));
$options = array();
$options['0'] = get_string('no');
$options['1'] = get_string('yes');
$mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
$mods = array(0=>get_string('allownone'));
$mods += $DB->get_records_menu('modules', array(), 'name', 'id, name');
$options = array();
$options['0'] = get_string('no');
$options['1'] = get_string('yes');
$mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
if (!empty($CFG->restrictbydefault)) {
$mform->setDefault('restrictmodules', 1);
}
$mform->addElement('select', 'allowedmods', get_string('to'), $mods,
array('multiple'=>'multiple', 'size'=>'10'));
$mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0);
$mods = array(0=>get_string('allownone'));
$mods += $DB->get_records_menu('modules', array('visible'=>1), 'name', 'id, name');
$mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple'=>'multiple', 'size'=>'10'));
$mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0);
// defaults are already in $course
} else {
// remove any mod restriction
$mform->addElement('hidden', 'restrictmodules', 0);
$mform->setType('restrictmodules', PARAM_INT);
}
} else {
$mform->addElement('hidden', 'restrictmodules', null);
$mform->addElement('hidden', 'restrictmodules');
$mform->setType('restrictmodules', PARAM_INT);
}
if ($CFG->restrictmodulesfor == 'all') {
$mform->setDefault('allowedmods', explode(',',$CFG->defaultallowedmodules));
if (!empty($CFG->restrictbydefault)) {
$mform->setDefault('restrictmodules', 1);
if (empty($course->id)) {
$mform->setConstant('restrictmodules', (int)($CFG->restrictmodulesfor == 'all'));
} else {
// keep previous
$mform->setConstant('restrictmodules', $course->restrictmodules);
}
}
$mform->setType('restrictmodules', PARAM_INT);
/// customizable role names in this course
//--------------------------------------------------------------------------------
@ -439,14 +296,18 @@ class course_edit_form extends moodleform {
//--------------------------------------------------------------------------------
$mform->addElement('hidden', 'id', null);
$mform->setType('id', PARAM_INT);
/// finally set the current form data
//--------------------------------------------------------------------------------
$this->set_data($course);
}
function definition_after_data() {
global $DB;
$mform =& $this->_form;
$mform = $this->_form;
// add availabe groupings
// add available groupings
if ($courseid = $mform->getElementValue('id') and $mform->elementExists('defaultgroupingid')) {
$options = array();
if ($groupings = $DB->get_records('groupings', array('courseid'=>$courseid))) {
@ -478,21 +339,7 @@ class course_edit_form extends moodleform {
}
}
if (!empty($data['enrolstartdate']) && !empty($data['enrolenddate']) &&
$data['enrolenddate'] <= $data['enrolstartdate']){
$errors['enrolenddate'] = get_string('enrolenddaterror');
}
if (!empty($CFG->enrol_manual_usepasswordpolicy) and isset($data['enrolpassword']) and $data['enrolpassword'] != '') {
$course = $this->_customdata['course'];
if ($course->password !== $data['enrolpassword']) {
// enforce password policy only if changing password - backwards compatibility
$errmsg = '';
if (!check_password_policy($data['enrolpassword'], $errmsg)) {
$errors['enrolpassword'] = $errmsg;
}
}
}
$errors = array_merge($errors, enrol_course_edit_validation($data, $this->context));
return $errors;
}

View File

@ -16,118 +16,15 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Depending on the current enrolment method, this page
* presents the user with whatever they need to know when
* they try to enrol in a course.
* Redirection of old enrol entry point.
*
* @copyright 1999 Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package course
*/
require_once("../config.php");
require_once("lib.php");
require_once("$CFG->dirroot/enrol/enrol.class.php");
require('../config.php');
$id = required_param('id', PARAM_INT);
$loginasguest = optional_param('loginasguest', 0, PARAM_BOOL); // hmm, is this still needed?
$url = new moodle_url('/course/enrol.php', array('id'=>$id));
if ($loginasguest !== 0) {
$url->param('loginasguest', $loginasguest);
}
$PAGE->set_url($url);
if (!isloggedin()) {
// do not use require_login here because we are usually comming from it
redirect(get_login_url());
}
if (!$course = $DB->get_record('course', array('id'=>$id))) {
print_error("That's an invalid course id");
}
if (! $context = get_context_instance(CONTEXT_COURSE, $course->id) ) {
print_error("That's an invalid course id");
}
/// do not use when in course login as
if (session_is_loggedinas() and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
print_error('loginasnoenrol', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
}
$enrol = enrolment_factory::factory($course->enrol); // do not use if (!$enrol... here, it can not work in PHP4 - see MDL-7529
/// Refreshing all current role assignments for the current user
load_all_capabilities();
/// Double check just in case they are actually enrolled already and
/// thus got to this script by mistake. This might occur if enrolments
/// changed during this session or something
if (has_capability('moodle/course:participate', $context)) {
if (!empty($SESSION->wantsurl)) {
$destination = $SESSION->wantsurl;
unset($SESSION->wantsurl);
} else {
$destination = "$CFG->wwwroot/course/view.php?id=$course->id";
}
redirect($destination); // Bye!
}
/// Check if the course is a meta course (bug 5734)
if ($course->metacourse) {
echo $OUTPUT->header();
notice(get_string('coursenotaccessible'), "$CFG->wwwroot/index.php");
}
/// Users can't enroll to site course
if ($course->id == SITEID) {
echo $OUTPUT->header();
notice(get_string('enrollfirst'), "$CFG->wwwroot/index.php");
}
/// Double check just in case they are enrolled to start in the future
if ($course->enrolperiod) { // Only active if the course has an enrolment period in effect
if ($roles = get_user_roles($context, $USER->id)) {
foreach ($roles as $role) {
if ($role->timestart and ($role->timestart >= time())) {
$message = get_string('enrolmentnotyet', '', userdate($student->timestart));
echo $OUTPUT->header();
notice($message, "$CFG->wwwroot/index.php");
}
}
}
}
/// Check if the course is enrollable
if (!method_exists($enrol, 'print_entry')) {
echo $OUTPUT->header();
notice(get_string('enrolmentnointernal'), "$CFG->wwwroot/index.php");
}
if (!$course->enrollable ||
($course->enrollable == 2 && $course->enrolstartdate > 0 && $course->enrolstartdate > time()) ||
($course->enrollable == 2 && $course->enrolenddate > 0 && $course->enrolenddate <= time())
) {
$PAGE->set_title($course->shortname);
$PAGE->set_heading($course->fullname);
$PAGE->navbar->add($course->shortname);
echo $OUTPUT->header();
notice(get_string('notenrollable'), "$CFG->wwwroot/index.php");
}
/// Check the submitted enrolment information if there is any (eg could be enrolment key)
if ($form = data_submitted()) {
$enrol->check_entry($form, $course); // Should terminate/redirect in here if it's all OK
}
/// Otherwise, we print the entry form.
$enrol->print_entry($course);
/// Easy!
$id = required_param('id', PARAM_INT);
redirect(new moodle_url('/enrol/index.php', array('id'=>$id)));

View File

@ -1,749 +0,0 @@
<?php
/**
* Moodle - Modular Object-Oriented Dynamic Learning Environment
* http://moodle.com
*
* LICENSE
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
*
* http://www.gnu.org/copyleft/gpl.html
*
* @category Moodle
* @package user
* @copyright Copyright (c) 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL License
*/
require_once(dirname(dirname(__FILE__)) . '/lib/moodleexternal.php');
require_once(dirname(dirname(__FILE__)) . '/course/lib.php');
/**
* course webservice api
*
* @author Jerome Mouneyrac
*/
final class course_external extends moodle_external {
/**
* Retrieve courses
* @param array|struct $params - need to be define as struct for XMLRPC
* @subparam integer $params:search->id - the id to search
* @subparam string $params:search->idnumber - the idnumber to search
* @subparam string $params:search->shortname - the shortname to search
* @return object $return
* @subreturn integer $return:course->id
* @subreturn string $return:course->idnumber
* @subreturn string $return:course->shortname
* @subreturn integer $return:course->category
* @subreturn string $return:course->fullname
* @subreturn string $return:course->summary
* @subreturn string $return:course->format
* @subreturn integer $return:course->startdate
* @subreturn integer $return:course->sortorder
* @subreturn integer $return:course->showgrades
* @subreturn string $return:course->modinfo
* @subreturn string $return:course->newsitems
* @subreturn string $return:course->guest
* @subreturn integer $return:course->metacourse
* @subreturn string $return:course->password
* @subreturn integer $return:course->enrolperiod
* @subreturn integer $return:course->defaultrole
* @subreturn integer $return:course->enrollable
* @subreturn integer $return:course->numsections
* @subreturn integer $return:course->expirynotify
* @subreturn integer $return:course->notifystudents
* @subreturn integer $return:course->expirythreshold
* @subreturn integer $return:course->marker
* @subreturn integer $return:course->maxbytes
* @subreturn integer $return:course->showreports
* @subreturn integer $return:course->visible
* @subreturn integer $return:course->hiddensections
* @subreturn integer $return:course->groupmode
* @subreturn integer $return:course->groupmodeforce
* @subreturn integer $return:course->defaultgroupingid
* @subreturn string $return:course->lang
* @subreturn string $return:course->theme
* @subreturn string $return:course->cost
* @subreturn string $return:course->currency
* @subreturn integer $return:course->timecreated
* @subreturn integer $return:course->timemodified
* @subreturn integer $return:course->requested
* @subreturn integer $return:course->restrictmodules
* @subreturn integer $return:course->enrolstartdate
* @subreturn integer $return:course->enrolenddate
* @subreturn string $return:course->enrol
* @subreturn integer $return:course->enablecompletion
*/
static function get_courses($params) {
global $USER, $DB;
if (has_capability('moodle/course:participate', get_context_instance(CONTEXT_SYSTEM))) {
$courses = array();
foreach ($params as $param) {
$course = new stdClass();
if (key_exists('id', $param)) {
$param['id'] = clean_param($param['id'], PARAM_INT);
$course = $DB->get_record('course', array('id'=>$param['id']));
} else if (key_exists('idnumber', $param)) {
$param['idnumber'] = clean_param($param['idnumber'], PARAM_ALPHANUM);
$course = $DB->get_record('course', array('idnumber'=>$param['idnumber']));
} else if (key_exists('shortname', $param)) {
$param['shortname'] = clean_param($param['shortname'], PARAM_ALPHANUM);
$course = $DB->get_record('course', array('shortname'=>$param['shortname']));
}
if (!empty($course)) {
$returnedcourse = new stdClass();
$returnedcourse->id = $course->id;
$returnedcourse->idnumber = $course->idnumber;
$returnedcourse->shortname = $course->shortname;
$returnedcourse->summary = $course->summary;
$returnedcourse->format = $course->format;
$returnedcourse->fullname = $course->fullname;
$returnedcourse->numsections = $course->numsections;
$returnedcourse->startdate = $course->startdate;
$returnedcourse->category = $course->category;
$returnedcourse->sortorder = $course->sortorder;
$returnedcourse->password = $course->password ;
$returnedcourse->showgrades = $course->showgrades;
$returnedcourse->modinfo = $course->modinfo;
$returnedcourse->newsitems = $course->newsitems;
$returnedcourse->guest = $course->guest;
$returnedcourse->enrolperiod = $course->enrolperiod;
$returnedcourse->marker = $course->marker;
$returnedcourse->maxbytes = $course->maxbytes;
$returnedcourse->showreports = $course->showreports;
$returnedcourse->visible = $course->visible;
$returnedcourse->hiddensections = $course->hiddensections;
$returnedcourse->groupmode = $course->groupmode;
$returnedcourse->groupmodeforce = $course->groupmodeforce;
$returnedcourse->defaultgroupingid = $course->defaultgroupingid;
$returnedcourse->lang = $course->lang;
$returnedcourse->theme = $course->theme;
$returnedcourse->cost = $course->cost;
$returnedcourse->currency = $course->currency;
$returnedcourse->timecreated = $course->timecreated;
$returnedcourse->timemodified = $course->timemodified;
$returnedcourse->metacourse = $course->metacourse;
$returnedcourse->requested = $course->requested;
$returnedcourse->restrictmodules = $course->restrictmodules;
$returnedcourse->expirynotify = $course->expirynotify;
$returnedcourse->expirythreshold = $course->expirythreshold;
$returnedcourse->notifystudents = $course->notifystudents;
$returnedcourse->enrollable = $course->enrollable;
$returnedcourse->enrolstartdate = $course->enrolstartdate;
$returnedcourse->enrolenddate = $course->enrolenddate;
$returnedcourse->enrol = $course->enrol;
$returnedcourse->defaultrole = $course->defaultrole;
$returnedcourse->enablecompletion = $course->enablecompletion;
$courses[] = $returnedcourse;
}
}
return $courses;
}
else {
throw new moodle_exception('wscouldnotviewcoursenopermission');
}
}
/**
* Create multiple courses
* @param array|struct $params - need to be define as struct for XMLRPC
* @subparam string $params:course->idnumber
* @subparam string $params:course->shortname
* @subparam integer $params:course->category
* @subparam string $params:course->fullname
* @subparam string $params:course->summary
* @subparam string $params:course->format
* @subparam integer $params:course->startdate
* @subparam integer $params:course->sortorder
* @subparam integer $params:course->showgrades
* @subparam string $params:course->modinfo
* @subparam string $params:course->newsitems
* @subparam string $params:course->guest
* @subparam integer $params:course->metacourse
* @subparam string $params:course->password
* @subparam integer $params:course->enrolperiod
* @subparam integer $params:course->defaultrole
* @subparam integer $params:course->enrollable
* @subparam integer $params:course->numsections
* @subparam integer $params:course->expirynotify
* @subparam integer $params:course->notifystudents
* @subparam integer $params:course->expirythreshold
* @subparam integer $params:course->marker
* @subparam integer $params:course->maxbytes
* @subparam integer $params:course->showreports
* @subparam integer $params:course->visible
* @subparam integer $params:course->hiddensections
* @subparam integer $params:course->groupmode
* @subparam integer $params:course->groupmodeforce
* @subparam integer $params:course->defaultgroupingid
* @subparam string $params:course->lang
* @subparam string $params:course->theme
* @subparam string $params:course->cost
* @subparam string $params:course->currency
* @subparam integer $params:course->timecreated
* @subparam integer $params:course->timemodified
* @subparam integer $params:course->requested
* @subparam integer $params:course->restrictmodules
* @subparam integer $params:course->enrolstartdate
* @subparam integer $params:course->enrolenddate
* @subparam string $params:course->enrol
* @subparam integer $params:course->enablecompletion
* @return array $return ids of new courses
* @subreturn integer $return:id course id
*/
static function create_courses($params) {
global $USER;
if (has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM))) {
$courses = array();
foreach ($params as $courseparams) {
$course = new stdClass();
if (array_key_exists('idnumber', $courseparams)) {
$course->idnumber = clean_param($courseparams['idnumber'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('shortname', $courseparams)) {
$course->shortname = clean_param($courseparams['shortname'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('category', $courseparams)) {
$course->category = clean_param($courseparams['category'], PARAM_INT);
}
if (array_key_exists('fullname', $courseparams)) {
$course->fullname = clean_param($courseparams['fullname'], PARAM_TEXT);
}
if (array_key_exists('summary', $courseparams)) {
$course->summary = clean_param($courseparams['summary'], PARAM_TEXT);
}
if (array_key_exists('format', $courseparams)) {
$course->format = clean_param($courseparams['format'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('startdate', $courseparams)) {
$course->startdate = clean_param($courseparams['startdate'], PARAM_INT);
}
if (array_key_exists('sortorder', $courseparams)) {
$course->sortorder = clean_param($courseparams['sortorder'], PARAM_INT);
}
if (array_key_exists('showgrades', $courseparams)) {
$course->showgrades = clean_param($courseparams['showgrades'], PARAM_INT);
}
if (array_key_exists('modinfo', $courseparams)) {
$course->modinfo = clean_param($courseparams['modinfo'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('newsitems', $courseparams)) {
$course->newsitems = clean_param($courseparams['newsitems'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('guest', $courseparams)) {
$course->guest = clean_param($courseparams['guest'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('metacourse', $courseparams)) {
$course->metacourse = clean_param($courseparams['metacourse'], PARAM_INT);
}
if (array_key_exists('password', $courseparams)) {
$course->password = clean_param($courseparams['password'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('enrolperiod', $courseparams)) {
$course->enrolperiod = clean_param($courseparams['enrolperiod'], PARAM_INT);
}
if (array_key_exists('defaultrole', $courseparams)) {
$course->defaultrole = clean_param($courseparams['defaultrole'], PARAM_INT);
}
if (array_key_exists('enrollable', $courseparams)) {
$course->enrollable = clean_param($courseparams['enrollable'], PARAM_INT);
}
if (array_key_exists('numsections', $courseparams)) {
$course->numsections = clean_param($courseparams['numsections'], PARAM_INT);
}
if (array_key_exists('expirynotify', $courseparams)) {
$course->expirynotify = clean_param($courseparams['expirynotify'], PARAM_INT);
}
if (array_key_exists('notifystudents', $courseparams)) {
$course->notifystudents = clean_param($courseparams['notifystudents'], PARAM_INT);
}
if (array_key_exists('expirythreshold', $courseparams)) {
$course->expirythreshold = clean_param($courseparams['expirythreshold'], PARAM_INT);
}
if (array_key_exists('marker', $courseparams)) {
$course->marker = clean_param($courseparams['marker'], PARAM_INT);
}
if (array_key_exists('maxbytes', $courseparams)) {
$course->maxbytes = clean_param($courseparams['maxbytes'], PARAM_INT);
}
if (array_key_exists('showreports', $courseparams)) {
$course->showreports = clean_param($courseparams['showreports'], PARAM_INT);
}
if (array_key_exists('visible', $courseparams)) {
$course->visible = clean_param($courseparams['visible'], PARAM_INT);
}
if (array_key_exists('hiddensections', $courseparams)) {
$course->hiddensections = clean_param($courseparams['hiddensections'], PARAM_INT);
}
if (array_key_exists('groupmode', $courseparams)) {
$course->groupmode = clean_param($courseparams['groupmode'], PARAM_INT);
}
if (array_key_exists('groupmodeforce', $courseparams)) {
$course->groupmodeforce = clean_param($courseparams['groupmodeforce'], PARAM_INT);
}
if (array_key_exists('defaultgroupingid', $courseparams)) {
$course->defaultgroupingid = clean_param($courseparams['defaultgroupingid'], PARAM_INT);
}
if (array_key_exists('lang', $courseparams)) {
$course->lang = clean_param($courseparams['lang'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('theme', $courseparams)) {
$course->theme = clean_param($courseparams['theme'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('cost', $courseparams)) {
$course->cost = clean_param($courseparams['cost'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('currency', $courseparams)) {
$course->currency = clean_param($courseparams['currency'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('timecreated', $courseparams)) {
$course->timecreated = clean_param($courseparams['timecreated'], PARAM_INT);
}
if (array_key_exists('timemodified', $courseparams)) {
$course->timemodified = clean_param($courseparams['timemodified'], PARAM_INT);
}
if (array_key_exists('requested', $courseparams)) {
$course->requested = clean_param($courseparams['requested'], PARAM_INT);
}
if (array_key_exists('restrictmodules', $courseparams)) {
$course->restrictmodules = clean_param($courseparams['restrictmodules'], PARAM_INT);
}
if (array_key_exists('enrolstartdate', $courseparams)) {
$course->enrolstartdate = clean_param($courseparams['enrolstartdate'], PARAM_INT);
}
if (array_key_exists('enrolenddate', $courseparams)) {
$course->enrolenddate = clean_param($courseparams['enrolenddate'], PARAM_INT);
}
if (array_key_exists('enrol', $courseparams)) {
$course->enrol = clean_param($courseparams['enrol'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('enablecompletion', $courseparams)) {
$course->enablecompletion = clean_param($courseparams['enablecompletion'], PARAM_INT);
}
$courses[] = create_course($course);
}
return $courses;
}
else {
throw new moodle_exception('wscouldnotcreateecoursenopermission');
}
}
/**
* Delete multiple courses
* @global object $DB
* @param array|struct $params - need to be define as struct for XMLRPC
* @subparam string $params:course->shortname
* @subparam integer $params:course->id
* @subparam string $params:course->shortname
* @subparam string $params:course->idnumber
* @return boolean result true if success
*/
static function delete_courses($params) {
global $DB,$USER;
if (has_capability('moodle/course:delete', get_context_instance(CONTEXT_SYSTEM))) {
$courses = array();
$result = true;
foreach ($params as $param) {
$course = new stdClass();
if (key_exists('id', $param)) {
$param['id'] = clean_param($param['id'], PARAM_INT);
if (!delete_course($param['id'], false)) {
$result = false;
}
} else if (key_exists('idnumber', $param)) {
$param['idnumber'] = clean_param($param['idnumber'], PARAM_ALPHANUM);
//it doesn't cost that much to retrieve the course here
//as it would be done into delete_course()
$course = $DB->get_record('course', array('idnumber'=>$param['idnumber']));
if (!delete_course($course, false)) {
$result = false;
}
} else if (key_exists('shortname', $param)) {
$param['shortname'] = clean_param($param['shortname'], PARAM_ALPHANUM);
$course = $DB->get_record('course', array('shortname'=>$param['shortname']));
if (!delete_course($course, false)) {
$result = false;
}
}
}
return $result;
}
else {
throw new moodle_exception('wscouldnotdeletecoursenopermission');
}
}
/**
* Update some courses information
* @global object $DB
* @param array|struct $params - need to be define as struct for XMLRPC
* @subparam integer $params:course->id
* @subparam string $params:course->idnumber
* @subparam string $params:course->shortname
* @subparam integer $params:course->category
* @subparam string $params:course->fullname
* @subparam string $params:course->summary
* @subparam string $params:course->format
* @subparam integer $params:course->startdate
* @subparam integer $params:course->sortorder
* @subparam integer $params:course->showgrades
* @subparam string $params:course->modinfo
* @subparam string $params:course->newsitems
* @subparam string $params:course->guest
* @subparam integer $params:course->metacourse
* @subparam string $params:course->password
* @subparam integer $params:course->enrolperiod
* @subparam integer $params:course->defaultrole
* @subparam integer $params:course->enrollable
* @subparam integer $params:course->numsections
* @subparam integer $params:course->expirynotify
* @subparam integer $params:course->notifystudents
* @subparam integer $params:course->expirythreshold
* @subparam integer $params:course->marker
* @subparam integer $params:course->maxbytes
* @subparam integer $params:course->showreports
* @subparam integer $params:course->visible
* @subparam integer $params:course->hiddensections
* @subparam integer $params:course->groupmode
* @subparam integer $params:course->groupmodeforce
* @subparam integer $params:course->defaultgroupingid
* @subparam string $params:course->lang
* @subparam string $params:course->theme
* @subparam string $params:course->cost
* @subparam string $params:course->currency
* @subparam integer $params:course->timecreated
* @subparam integer $params:course->timemodified
* @subparam integer $params:course->requested
* @subparam integer $params:course->restrictmodules
* @subparam integer $params:course->enrolstartdate
* @subparam integer $params:course->enrolenddate
* @subparam string $params:course->enrol
* @subparam integer $params:course->enablecompletion
* @return boolean result true if success
*/
static function update_courses($params) {
global $DB,$USER;
if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM))) {
$courses = array();
$result = true;
foreach ($params as $courseparams) {
$course = new stdClass();
if (array_key_exists('idnumber', $courseparams)) {
$course->idnumber = clean_param($courseparams['idnumber'], PARAM_ALPHANUM);
}
if (array_key_exists('shortname', $courseparams)) {
$course->shortname = clean_param($courseparams['shortname'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('category', $courseparams)) {
$course->category = clean_param($courseparams['category'], PARAM_INT);
}
if (array_key_exists('fullname', $courseparams)) {
$course->fullname = clean_param($courseparams['fullname'], PARAM_TEXT);
}
if (array_key_exists('summary', $courseparams)) {
$course->summary = clean_param($courseparams['summary'], PARAM_TEXT);
}
if (array_key_exists('format', $courseparams)) {
$course->format = clean_param($courseparams['format'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('startdate', $courseparams)) {
$course->startdate = clean_param($courseparams['startdate'], PARAM_INT);
}
if (array_key_exists('sortorder', $courseparams)) {
$course->sortorder = clean_param($courseparams['sortorder'], PARAM_INT);
}
if (array_key_exists('showgrades', $courseparams)) {
$course->showgrades = clean_param($courseparams['showgrades'], PARAM_INT);
}
if (array_key_exists('modinfo', $courseparams)) {
$course->modinfo = clean_param($courseparams['modinfo'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('newsitems', $courseparams)) {
$course->newsitems = clean_param($courseparams['newsitems'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('guest', $courseparams)) {
$course->guest = clean_param($courseparams['guest'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('metacourse', $courseparams)) {
$course->metacourse = clean_param($courseparams['metacourse'], PARAM_INT);
}
if (array_key_exists('password', $courseparams)) {
$course->password = clean_param($courseparams['password'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('enrolperiod', $courseparams)) {
$course->enrolperiod = clean_param($courseparams['enrolperiod'], PARAM_INT);
}
if (array_key_exists('defaultrole', $courseparams)) {
$course->defaultrole = clean_param($courseparams['defaultrole'], PARAM_INT);
}
if (array_key_exists('enrollable', $courseparams)) {
$course->enrollable = clean_param($courseparams['enrollable'], PARAM_INT);
}
if (array_key_exists('numsections', $courseparams)) {
$course->numsections = clean_param($courseparams['numsections'], PARAM_INT);
}
if (array_key_exists('expirynotify', $courseparams)) {
$course->expirynotify = clean_param($courseparams['expirynotify'], PARAM_INT);
}
if (array_key_exists('notifystudents', $courseparams)) {
$course->notifystudents = clean_param($courseparams['notifystudents'], PARAM_INT);
}
if (array_key_exists('expirythreshold', $courseparams)) {
$course->expirythreshold = clean_param($courseparams['expirythreshold'], PARAM_INT);
}
if (array_key_exists('marker', $courseparams)) {
$course->marker = clean_param($courseparams['marker'], PARAM_INT);
}
if (array_key_exists('maxbytes', $courseparams)) {
$course->maxbytes = clean_param($courseparams['maxbytes'], PARAM_INT);
}
if (array_key_exists('showreports', $courseparams)) {
$course->showreports = clean_param($courseparams['showreports'], PARAM_INT);
}
if (array_key_exists('visible', $courseparams)) {
$course->visible = clean_param($courseparams['visible'], PARAM_INT);
}
if (array_key_exists('hiddensections', $courseparams)) {
$course->hiddensections = clean_param($courseparams['hiddensections'], PARAM_INT);
}
if (array_key_exists('groupmode', $courseparams)) {
$course->groupmode = clean_param($courseparams['groupmode'], PARAM_INT);
}
if (array_key_exists('groupmodeforce', $courseparams)) {
$course->groupmodeforce = clean_param($courseparams['groupmodeforce'], PARAM_INT);
}
if (array_key_exists('defaultgroupingid', $courseparams)) {
$course->defaultgroupingid = clean_param($courseparams['defaultgroupingid'], PARAM_INT);
}
if (array_key_exists('lang', $courseparams)) {
$course->lang = clean_param($courseparams['lang'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('theme', $courseparams)) {
$course->theme = clean_param($courseparams['theme'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('cost', $courseparams)) {
$course->cost = clean_param($courseparams['cost'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('currency', $courseparams)) {
$course->currency = clean_param($courseparams['currency'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('timecreated', $courseparams)) {
$course->timecreated = clean_param($courseparams['timecreated'], PARAM_INT);
}
if (array_key_exists('timemodified', $courseparams)) {
$course->timemodified = clean_param($courseparams['timemodified'], PARAM_INT);
}
if (array_key_exists('requested', $courseparams)) {
$course->requested = clean_param($courseparams['requested'], PARAM_INT);
}
if (array_key_exists('restrictmodules', $courseparams)) {
$course->restrictmodules = clean_param($courseparams['restrictmodules'], PARAM_INT);
}
if (array_key_exists('enrolstartdate', $courseparams)) {
$course->enrolstartdate = clean_param($courseparams['enrolstartdate'], PARAM_INT);
}
if (array_key_exists('enrolenddate', $courseparams)) {
$course->enrolenddate = clean_param($courseparams['enrolenddate'], PARAM_INT);
}
if (array_key_exists('enrol', $courseparams)) {
$course->enrol = clean_param($courseparams['enrol'], PARAM_ALPHANUMEXT);
}
if (array_key_exists('enablecompletion', $courseparams)) {
$course->enablecompletion = clean_param($courseparams['enablecompletion'], PARAM_INT);
}
if (array_key_exists('id', $courseparams)) {
$course->id = clean_param($courseparams['id'], PARAM_INT);
}
if (!update_course($course)) {
$result = false;
}
}
return $result;
}
else {
throw new moodle_exception('wscouldnotupdatecoursenopermission');
}
}
/**
* Get course modules
* @global object $DB
* @param array|struct $params - need to be define as struct for XMLRPC
* @subparam string $params:course->id
* @return array $return course modules
* @subreturn string $return:id module id
* @subreturn string $return:name module name
* @subreturn string $return:type module type
*/
static function get_course_modules($params, $type=null) {
global $DB;
if (has_capability('moodle/course:participate', get_context_instance(CONTEXT_SYSTEM))) {
$modules = array();
foreach ($params as $courseparams) {
if (array_key_exists('id', $courseparams)) {
$id = clean_param($courseparams['id'], PARAM_INT);
}
$activities = get_array_of_activities($id);
foreach ($activities as $activity) {
if (empty($type)) {
$module = array('id' => $activity->id, 'courseid' => $id, 'name' => $activity->name, 'type' => $activity->mod);
$modules[] = $module;
}
else if ($type=="activities") {
if ($activity->mod != "resource" && $activity->mod != "label") {
$module = array('id' => $activity->id, 'courseid' => $id, 'name' => $activity->name, 'type' => $activity->mod);
$modules[] = $module;
}
}
else if ($type=="resources") {
if ($activity->mod == "resource" || $activity->mod == "label") {
$module = array('id' => $activity->id, 'courseid' => $id, 'resource' => $activity->name, 'type' => $activity->mod);
$modules[] = $module;
}
}
}
}
return $modules;
}
else {
throw new moodle_exception('wscouldnotgetcoursemodulesnopermission');
}
}
/**
* Get course activities
* @global object $DB
* @param array|struct $params - need to be define as struct for XMLRPC
* @subparam string $params:course->id
* @return array $return course activities
* @subreturn string $return:id activity id
* @subreturn string $return:name activity name
* @subreturn string $return:type activity type
*/
static function get_course_activities($params) {
course_external::get_course_modules($params, "activities");
}
/**
* Get course resources
* @global object $DB
* @param array|struct $params - need to be define as struct for XMLRPC
* @subparam string $params:course->id
* @return array $return course resources
* @subreturn integer $return:id resource id
* @subreturn string $return:name resource name
* @subreturn string $return:type resource type
*/
static function get_course_resources($params) {
course_external::get_course_modules($params, "resources");
}
}

View File

@ -18,12 +18,14 @@
/**
* External user API
*
* @package moodlecore
* @subpackage webservice
* @package core
* @subpackage course
* @copyright 2009 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
require_once("$CFG->libdir/externallib.php");
class moodle_course_external extends external_api {

View File

@ -1,80 +0,0 @@
<form id="studentform" method="post" action="importstudents.php">
<input type="hidden" name="previoussearch" value="<?php echo $previoussearch ?>" />
<input type="hidden" name="sesskey" value="<?php echo sesskey() ?>" />
<input type="hidden" name="id" value="<?php echo $id?>" />
<table summary="" align="center" border="0" cellpadding="5" cellspacing="0">
<tr>
<td valign="top">
<label for="removeselect"><?php echo count($alreadycourses) . " ". $stralreadycourses ?></label>
<br />
<select name="removeselect[]" size="20" id="removeselect" multiple="multiple"
onFocus="getElementById('studentform').add.disabled=true;
getElementById('studentform').remove.disabled=false;
getElementById('studentform').addselect.selectedIndex=-1;">
<?php
foreach ($alreadycourses as $course) {
echo "<option value=\"$course->id\">".course_format_name($course,60)."</option>\n";
}
?>
</select></td>
<td valign="top">
<p class="arrow_button">
<input name="add" id="add" type="submit" value="<?php echo '&nbsp;'.$OUTPUT->larrow().' &nbsp; &nbsp; '.get_string('add'); ?>" title="<?php print_string('add'); ?>" />
<br />
<input name="remove" id="remove" type="submit" value="<?php echo '&nbsp; '.$OUTPUT->rarrow().' &nbsp; &nbsp; '.get_string('remove'); ?>" title="<?php print_string('remove'); ?>" />
</p>
</td>
<td valign="top">
<label for="addselect"><?php echo $numcourses . " " . $strpotentialcourses ?></label>
<br />
<select name="addselect[]" size="20" id="addselect" multiple="multiple"
onFocus="getElementById('studentform').add.disabled=false;
getElementById('studentform').remove.disabled=true;
getElementById('studentform').removeselect.selectedIndex=-1;">
<?php
if (!empty($searchcourses)) {
echo "<optgroup label=\"$strsearchresults (" . count($searchcourses) . ")\">\n";
foreach ($searchcourses as $course) {
echo "<option value=\"$course->id\">".course_format_name($course,60)."</option>\n";
}
echo "</optgroup>\n";
}
if (!empty($courses)) {
if ($numcourses > MAX_COURSES_PER_PAGE) {
echo '<optgroup label="'.get_string('toomanytoshow').'"><option></option></optgroup>'."\n"
.'<optgroup label="'.get_string('trysearching').'"><option></option></optgroup>'."\n";
}
else {
foreach ($courses as $course) {
echo "<option value=\"$course->id\">".course_format_name($course,60)."</option>\n";
}
}
}
?>
</select>
<br />
<label for="searchtext" class="accesshide"><?php p($strsearch) ?></label>
<input type="text" name="searchtext" id="searchtext" size="30" value="<?php p($searchtext) ?>"
onFocus ="getElementById('studentform').add.disabled=true;
getElementById('studentform').remove.disabled=true;
getElementById('studentform').removeselect.selectedIndex=-1;
getElementById('studentform').addselect.selectedIndex=-1;"
onkeydown = "var keyCode = event.which ? event.which : event.keyCode;
if (keyCode == 13) {
getElementById('studentform').previoussearch.value=1;
getElementById('studentform').submit();
} " />
<input name="search" id="search" type="submit" value="<?php p($strsearch) ?>" />
<?php
if (!empty($searchcourses)) {
echo '<input name="showall" id="showall" type="submit" value="'.$strshowall.'" />'."\n";
}
?>
</td>
</tr>
</table>
</form>

View File

@ -1,170 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Script to assign students to a meta course by selecting which courses the meta
* course comprises. This is basically a hack of student.php that uses courses instead.
*
* @copyright 1999 Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package course
*/
require_once("../config.php");
require_once("lib.php");
define("MAX_COURSES_PER_PAGE", 1000);
$id = required_param('id',PARAM_INT); // course id
$add = optional_param('add', 0, PARAM_BOOL);
$remove = optional_param('remove', 0, PARAM_BOOL);
$showall = optional_param('showall', 0, PARAM_BOOL);
$searchtext = optional_param('searchtext', '', PARAM_RAW); // search string
$previoussearch = optional_param('previoussearch', 0, PARAM_BOOL);
$previoussearch = ($searchtext != '') or ($previoussearch) ? 1:0;
$url = new moodle_url('/course/importstudents.php', array('id'=>$id));
if ($add !== 0) {
$url->param('add', $add);
}
if ($remove !== 0) {
$url->param('remove', $remove);
}
if ($showall !== 0) {
$url->param('showall', $showall);
}
if ($searchtext !== '') {
$url->param('searchtext', $searchtext);
}
if ($previoussearch !== 0) {
$url->param('previoussearch', $previoussearch);
}
$PAGE->set_url($url);
$site = get_site();
if (!$course = $DB->get_record('course', array('id'=>$id))) {
print_error("invalidcourseid");
}
require_login($course->id);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
require_capability('moodle/course:managemetacourse', $context);
if (!$course->metacourse) {
redirect("$CFG->wwwroot/course/view.php?id=$course->id");
}
$strassigncourses = get_string('metaassigncourses');
$stralreadycourses = get_string('metaalreadycourses');
$strnoalreadycourses = get_string('metanoalreadycourses');
$strpotentialcourses = get_string('metapotentialcourses');
$strnopotentialcourses = get_string('metanopotentialcourses');
$straddcourses = get_string('metaaddcourse');
$strremovecourse = get_string('metaremovecourse');
$strsearch = get_string("search");
$strsearchresults = get_string("searchresults");
$strcourses = get_string("courses");
$strshowall = get_string("showall");
$PAGE->navbar->add($strassigncourses);
$PAGE->set_title("$course->shortname: $strassigncourses");
$PAGE->set_heading($site->fullname);
$PAGE->set_focuscontrol("searchtext");
echo $OUTPUT->header();
/// Print a help notice about the need to use this page
echo $OUTPUT->heading(get_string('childcourses'));
if (!$frm = data_submitted()) {
$note = get_string("importmetacoursenote");
echo $OUTPUT->box($note);
/// A form was submitted so process the input
} else {
if ($add and !empty($frm->addselect) and confirm_sesskey()) {
$timestart = $timeend = 0;
foreach ($frm->addselect as $addcourse) {
$addcourse = clean_param($addcourse, PARAM_INT);
set_time_limit(180);
if (!add_to_metacourse($course->id,$addcourse)) {
print_error("cannotmetacourse");
}
}
} else if ($remove and !empty($frm->removeselect) and confirm_sesskey()) {
foreach ($frm->removeselect as $removecourse) {
set_time_limit(180);
$removecourse = clean_param($removecourse, PARAM_INT);
if (! remove_from_metacourse($course->id,$removecourse)) {
print_error("cannotremovefrommeta");
}
}
} else if ($showall and confirm_sesskey()) {
$searchtext = '';
$previoussearch = 0;
}
}
/// Get all existing students and teachers for this course.
if(! $alreadycourses = get_courses_in_metacourse($course->id)) {
$alreadycourses = array();
}
$numcourses = 0;
/// Get search results excluding any users already in this course
if (($searchtext != '') and $previoussearch and confirm_sesskey()) {
if ($searchcourses = get_courses_search(explode(" ",$searchtext),'fullname ASC',0,99999,$numcourses)) {
foreach ($searchcourses as $tmp) {
if (array_key_exists($tmp->id,$alreadycourses)) {
unset($searchcourses[$tmp->id]);
}
if (!empty($tmp->metacourse)) {
unset($searchcourses[$tmp->id]);
}
}
if (array_key_exists($course->id,$searchcourses)) {
unset($searchcourses[$course->id]);
}
$numcourses = count($searchcourses);
}
}
/// If no search results then get potential students for this course excluding users already in course
if (empty($searchcourses)) {
$numcourses = count_courses_notin_metacourse($course->id);
if ($numcourses > 0 and $numcourses <= MAX_COURSES_PER_PAGE) {
$courses = get_courses_notin_metacourse($course->id);
} else {
$courses = array();
}
}
echo $OUTPUT->box_start();
include('importstudents.html');
echo $OUTPUT->box_end();
echo $OUTPUT->footer();

View File

@ -192,18 +192,19 @@ if (!empty($move) and ($moveto >= 0) and confirm_sesskey()) {
}
/// Hide or show a category
if ((!empty($hide) or !empty($show)) and confirm_sesskey()) {
if (!empty($hide)) {
$tempcat = $DB->get_record('course_categories', array('id'=>$hide));
$visible = 0;
} else {
$tempcat = $DB->get_record('course_categories', array('id'=>$show));
$visible = 1;
if ($hide and confirm_sesskey()) {
if ($tempcat = $DB->get_record('course_categories', array('id'=>$hide))) {
require_capability('moodle/category:manage', get_category_or_system_context($tempcat->parent));
if ($tempcat->visible == 1) {
course_category_hide($tempcat);
}
}
require_capability('moodle/category:manage', get_category_or_system_context($tempcat->parent));
if ($tempcat) {
$DB->set_field('course_categories', 'visible', $visible, array('id'=>$tempcat->id));
$DB->set_field('course', 'visible', $visible, array('category' => $tempcat->id));
} else if ($show and confirm_sesskey()) {
if ($tempcat = $DB->get_record('course_categories', array('id'=>$show))) {
require_capability('moodle/category:manage', get_category_or_system_context($tempcat->parent));
if ($tempcat->visible == 0) {
course_category_show($tempcat);
}
}
}

View File

@ -29,7 +29,7 @@
}
$context = get_context_instance(CONTEXT_COURSE, $course->id);
if ((!course_parent_visible($course) || (! $course->visible)) && !has_capability('moodle/course:viewhiddencourses', $context)) {
if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $context)) {
print_error('coursehidden', '', $CFG->wwwroot .'/');
}
@ -44,6 +44,8 @@
echo $OUTPUT->header();
echo $OUTPUT->heading('<a href="view.php?id='.$course->id.'">'.format_string($course->fullname) . '</a><br />(' . format_string($course->shortname) . ')');
//TODO: add enrol info
/*
if ($course->guest || $course->password) {
echo $OUTPUT->box_start('generalbox icons');
if ($course->guest) {
@ -55,17 +57,17 @@
echo "<div><img alt=\"\" class=\"icon key\" src=\"" . $OUTPUT->pix_url('i/key') . "\" />&nbsp;$strrequireskey</div>";
}
echo $OUTPUT->box_end();
}
}*/
echo $OUTPUT->box_start('generalbox info');
$course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course_summary', $course->id);
$course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course_summary', NULL);
echo format_text($course->summary, $course->summaryformat, NULL, $course->id);
if (!empty($CFG->coursemanager)) {
$coursemanagerroles = explode(',', $CFG->coursemanager);
foreach ($coursemanagerroles as $roleid) {
if (!empty($CFG->coursecontact)) {
$coursecontactroles = explode(',', $CFG->coursecontact);
foreach ($coursecontactroles as $roleid) {
$role = $DB->get_record('role', array('id'=>$roleid));
$roleid = (int) $roleid;
if ($users = get_role_users($roleid, $context, true)) {
@ -84,9 +86,7 @@
}
}
require_once("$CFG->dirroot/enrol/enrol.class.php");
$enrol = enrolment_factory::factory($course->enrol);
echo $enrol->get_access_icons($course);
// TODO: print some enrol icons
echo $OUTPUT->box_end();

View File

@ -20,9 +20,12 @@
*
* @copyright 1999 Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package course
* @package core
* @subpackage course
*/
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir.'/completionlib.php');
require_once($CFG->libdir.'/filelib.php');
@ -1915,7 +1918,7 @@ function get_course_category_tree($id = 0, $depth = 0) {
list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
$sql = "SELECT
c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.guest,c.cost,c.currency,c.category
c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
$ccselect
FROM {course} c
$ccjoin
@ -2004,13 +2007,8 @@ function make_categories_options() {
*/
function print_category_info($category, $depth, $showcourses = false) {
global $CFG, $DB, $OUTPUT;
static $strallowguests, $strrequireskey, $strsummary;
if (empty($strsummary)) {
$strallowguests = get_string('allowguests');
$strrequireskey = get_string('requireskey');
$strsummary = get_string('summary');
}
$strsummary = get_string('summary');
$catlinkcss = $category->visible ? '' : ' class="dimmed" ';
@ -2028,7 +2026,7 @@ function print_category_info($category, $depth, $showcourses = false) {
echo "\n\n".'<table class="categorylist">';
$courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.guest,c.cost,c.currency');
$courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
if ($showcourses and $coursecount) {
echo '<tr>';
@ -2061,18 +2059,7 @@ function print_category_info($category, $depth, $showcourses = false) {
echo '</td><td valign="top" class="course name">';
echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
echo '</td><td align="right" valign="top" class="course info">';
if ($course->guest ) {
echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
echo '<img alt="'.$strallowguests.'" src="'.$OUTPUT->pix_url('i/guest') . '" /></a>';
} else {
echo '<img alt="" style="width:18px;height:16px;" src="'.$OUTPUT->pix_url('spacer') . '" />';
}
if ($course->password) {
echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
echo '<img alt="'.$strrequireskey.'" src="'.$OUTPUT->pix_url('i/key') . '" /></a>';
} else {
echo '<img alt="" style="width:18px;height:16px;" src="'.$OUTPUT->pix_url('spacer') . '" />';
}
//TODO: add some guest, pay icons
if ($course->summary) {
$link = new moodle_url('/course/info.php?id='.$course->id);
echo $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
@ -2186,17 +2173,17 @@ function print_courses($category) {
$category = array_shift($categories);
$courses = get_courses_wmanagers($category->id,
'c.sortorder ASC',
array('password','summary','summaryformat','currency'));
array('summary','summaryformat'));
} else {
$courses = get_courses_wmanagers('all',
'c.sortorder ASC',
array('password','summary','summaryformat','currency'));
array('summary','summaryformat'));
}
unset($categories);
} else {
$courses = get_courses_wmanagers($category->id,
'c.sortorder ASC',
array('password','summary','summaryformat','currency'));
array('summary','summaryformat'));
}
if ($courses) {
@ -2239,7 +2226,7 @@ function print_course($course, $highlightterms = '') {
$context = get_context_instance(CONTEXT_COURSE, $course->id);
// Rewrite file URLs so that they are correct
$course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course_summary', $course->id);
$course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course_summary', NULL);
$linkcss = $course->visible ? '' : ' class="dimmed" ';
@ -2251,8 +2238,8 @@ function print_course($course, $highlightterms = '') {
/// first find all roles that are supposed to be displayed
if (!empty($CFG->coursemanager)) {
$managerroles = split(',', $CFG->coursemanager);
if (!empty($CFG->coursecontact)) {
$managerroles = split(',', $CFG->coursecontact);
$namesarray = array();
if (isset($course->managers)) {
if (count($course->managers)) {
@ -2318,9 +2305,7 @@ function print_course($course, $highlightterms = '') {
}
}
require_once("$CFG->dirroot/enrol/enrol.class.php");
$enrol = enrolment_factory::factory($course->enrol);
echo $enrol->get_access_icons($course);
// TODO: print some enrol icons
echo '</div><div class="summary">';
$options = NULL;
@ -2345,7 +2330,7 @@ function print_my_moodle() {
print_error('nopermissions', '', '', 'See My Moodle');
}
$courses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', array('summary'));
$courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
$rhosts = array();
$rcourses = array();
if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
@ -3036,15 +3021,6 @@ function course_format_name ($course,$max=100) {
}
}
/**
* This function will return true if the given course is a child course at all
*/
function course_in_meta ($course) {
global $DB;
return $DB->record_exists("course_meta", array("child_course"=>$course->id));
}
function update_restricted_mods($course, $mods) {
global $DB;
@ -3082,8 +3058,8 @@ function course_allowed_module($course,$mod) {
}
// Admins and admin-like people who can edit everything can also add anything.
// This is a bit wierd, really. I debated taking it out but it's enshrined in help for the setting.
if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM))) {
// Originally there was a coruse:update test only, but it did not match the test in course edit form
if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
return true;
}
@ -3201,33 +3177,92 @@ function category_delete_move($category, $newparentid, $showfeedback=true) {
* sortorder in order.
*
* @param $courseids is an array of course ids
* @return bool success
*/
function move_courses($courseids, $categoryid) {
global $CFG, $DB, $OUTPUT;
if (!empty($courseids) and $category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
$courseids = array_reverse($courseids);
$i = 1;
foreach ($courseids as $courseid) {
if (!$course = $DB->get_record("course", array("id"=>$courseid))) {
echo $OUTPUT->notification("Error finding course $courseid");
} else {
$course->category = $categoryid;
$course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
$DB->update_record('course', $course);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
context_moved($context, $newparent);
}
}
fix_course_sortorder();
if (empty($courseids)) {
// nothing to do
return;
}
if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
return false;
}
$courseids = array_reverse($courseids);
$i = 1;
foreach ($courseids as $courseid) {
if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
$course->category = $category->id;
$course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
if ($category->visible == 0) {
// hide the course when moving into hidden category,
// do not update the visibleold flag - we want to get to previous state if somebody unhides the category
$course->visible = 0;
}
$DB->update_record('course', $course);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
context_moved($context, $newparent);
}
}
fix_course_sortorder();
return true;
}
/**
* Hide course category and child course and subcategories
* @param $category
* @return void
*/
function course_category_hide($category) {
global $DB;
$category->visible = 0;
$DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
$DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
$DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($category->id)); // store visible flag so that we can return to it if we immediately unhide
$DB->set_field('course', 'visible', 0, array('category' => $category->id));
// get all child categories and hide too
if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
foreach ($subcats as $cat) {
$DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
$DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
$DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
$DB->set_field('course', 'visible', 0, array('category' => $cat->id));
}
}
}
/**
* Show course category and child course and subcategories
* @param $category
* @return void
*/
function course_category_show($category) {
global $DB;
$category->visible = 1;
$DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
$DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
$DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
// get all child categories and unhide too
if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
foreach ($subcats as $cat) {
if ($cat->visibleold) {
$DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
}
$DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
}
}
}
/**
* Efficiently moves a category - NOTE that this can have
* a huge impact access-control-wise...
@ -3237,6 +3272,7 @@ function move_category($category, $newparentcat) {
$context = get_context_instance(CONTEXT_COURSECAT, $category->id);
$hidecat = false;
if (empty($newparentcat->id)) {
$DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id));
@ -3245,6 +3281,11 @@ function move_category($category, $newparentcat) {
} else {
$DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id));
$newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
if (!$newparentcat->visible and $category->visible) {
// better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
$hidecat = true;
}
}
context_moved($context, $newparent);
@ -3254,6 +3295,10 @@ function move_category($category, $newparentcat) {
// and fix the sortorders
fix_course_sortorder();
if ($hidecat) {
course_category_hide($category);
}
}
/**
@ -3361,7 +3406,7 @@ function save_local_role_names($courseid, $data) {
$context = get_context_instance(CONTEXT_COURSE, $courseid);
foreach ($data as $fieldname => $value) {
if (!strstr($fieldname, 'role_')) {
if (strpos($fieldname, 'role_') !== 0) {
continue;
}
list($ignored, $roleid) = explode('_', $fieldname);
@ -3385,158 +3430,181 @@ function save_local_role_names($courseid, $data) {
}
/**
* Create a course and either return a $course object or false
* Create a course and either return a $course object
*
* Please note this functions does not verify any access control,
* the calling code is responsible for all validation (usually it is the form definition).
*
* @param array $editoroptions course description editor options
* @param object $data - all the data needed for an entry in the 'course' table
* @return object new course instance
*/
function create_course($data) {
global $CFG, $USER, $DB;
function create_course($data, $editoroptions = NULL) {
global $CFG, $DB;
//check the categoryid
if (!empty($data->category) && !$data->category==0) {
$category = $DB->get_record('course_categories', array('id'=>$data->category));
if (empty($category)) {
throw new moodle_exception('noexistingcategory');
}
}
//check the categoryid - must be given for all new courses
$category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
//check if the shortname already exist
if(!empty($data->shortname)) {
$course = $DB->get_record('course', array('shortname' => $data->shortname));
if (!empty($course)) {
if (!empty($data->shortname)) {
if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
throw new moodle_exception('shortnametaken');
}
}
//check if the id number already exist
if(!empty($data->idnumber)) {
$course = $DB->get_record('course', array('idnumber' => $data->idnumber));
if (!empty($course)) {
if (!empty($data->idnumber)) {
if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
throw new moodle_exception('idnumbertaken');
}
}
// preprocess allowed mods
$allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
unset($data->allowedmods);
if ($CFG->restrictmodulesfor == 'all') {
$data->restrictmodules = 1;
// if the user is not an admin, get the default allowed modules because
// there are no modules passed by the form
if(!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
if(!$allowedmods && $CFG->defaultallowedmodules) {
$allowedmods = explode(',', $CFG->defaultallowedmodules);
}
}
} else {
$data->restrictmodules = 0;
}
$data->timecreated = time();
$data->timecreated = time();
$data->timemodified = $data->timecreated;
// place at beginning of any category
$data->sortorder = 0;
if ($newcourseid = $DB->insert_record('course', $data)) { // Set up new course
$course = $DB->get_record('course', array('id'=>$newcourseid));
// Setup the blocks
blocks_add_default_course_blocks($course);
update_restricted_mods($course, $allowedmods);
$section = new object();
$section->course = $course->id; // Create a default section.
$section->section = 0;
$section->summaryformat = FORMAT_HTML;
$section->id = $DB->insert_record('course_sections', $section);
fix_course_sortorder();
add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
// Save any custom role names.
save_local_role_names($course->id, $data);
// Trigger events
events_trigger('course_created', $course);
return $course;
if ($editoroptions) {
// summary text is updated later, we need context to store the files first
$data->summary = '';
$data->summary_format = FORMAT_HTML;
}
return false; // error
// init visible flags
if (isset($data->visible)) {
$data->visibleold = $data->visible;
} else {
$data->visibleold = $data->visible = 1;
}
$newcourseid = $DB->insert_record('course', $data);
$context = get_context_instance(CONTEXT_COURSE, $newcourseid, MUST_EXIST);
if ($editoroptions) {
// Save the files used in the summary editor and store
$data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course_summary', 0);
$DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
$DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
}
$course = $DB->get_record('course', array('id'=>$newcourseid));
// Setup the blocks
blocks_add_default_course_blocks($course);
$section = new object();
$section->course = $course->id; // Create a default section.
$section->section = 0;
$section->summaryformat = FORMAT_HTML;
$DB->insert_record('course_sections', $section);
fix_course_sortorder();
// update module restrictions
if ($course->restrictmodules) {
if (isset($data->allowedmods)) {
update_restricted_mods($course, $allowedmods);
} else {
if (!empty($CFG->defaultallowedmodules)) {
update_restricted_mods($course, explode(',', $CFG->defaultallowedmodules));
}
}
}
// new context created - better mark it as dirty
mark_context_dirty($context->path);
// Save any custom role names.
save_local_role_names($course->id, $data);
// set up enrolments
enrol_course_updated(true, $course, $data);
add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
// Trigger events
events_trigger('course_created', $course);
return $course;
}
/**
* Update a course and return true or false
* Update a course.
*
* Please note this functions does not verify any access control,
* the calling code is responsible for all validation (usually it is the form definition).
*
* @param object $data - all the data needed for an entry in the 'course' table
* @param array $editoroptions course description editor options
* @return void
*/
function update_course($data) {
global $USER, $CFG, $DB;
function update_course($data, $editoroptions = NULL) {
global $CFG, $DB;
// Preprocess allowed mods
$allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
unset($data->allowedmods);
$data->timemodified = time();
// Normal teachers can't change setting
if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
unset($data->restrictmodules);
$oldcourse = $DB->get_record('course', array('id'=>$data->id), '*', MUST_EXIST);
$context = get_context_instance(CONTEXT_COURSE, $oldcourse->id);
if ($editoroptions) {
$data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course_summary', 0);
}
$movecat = false;
$oldcourse = $DB->get_record('course', array('id'=>$data->id)); // should not fail, already tested above
// check that course id exist
if (empty($oldcourse)) {
throw new moodle_exception('courseidnotfound');
}
if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category))
or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) {
// can not move to new category, keep the old one
if (!isset($data->category) or empty($data->category)) {
// prevent nulls and 0 in category field
unset($data->category);
}
$movecat = (isset($data->category) and $oldcourse->category != $data->category);
} elseif ($oldcourse->category != $data->category) {
$movecat = true;
// init visible flags
if (isset($data->visible)) {
$data->visible = $oldcourse->visible;
}
if ($data->visible != $oldcourse->visible) {
// reset the visibleold flag when manually hiding/unhiding course
$data->visibleold = $data->visible;
} else {
if ($movecat) {
$newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
if (empty($newcategory->visible)) {
// make sure when moving into hidden category the course is hidden automatically
$data->visible = 0;
}
}
}
// Update with the new data
if ($DB->update_record('course', $data)) {
$DB->update_record('course', $data);
$course = $DB->get_record('course', array('id'=>$data->id));
add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
// "Admins" can change allowed mods for a course
if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
update_restricted_mods($course, $allowedmods);
}
if ($movecat) {
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
context_moved($context, $newparent);
}
fix_course_sortorder();
// Test for and remove blocks which aren't appropriate anymore
blocks_remove_inappropriate($course);
// Save any custom role names.
save_local_role_names($course->id, $data);
// Trigger events
events_trigger('course_updated', $course);
return true;
$course = $DB->get_record('course', array('id'=>$data->id));
if ($movecat) {
$newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
context_moved($context, $newparent);
}
return false;
fix_course_sortorder();
// Test for and remove blocks which aren't appropriate anymore
blocks_remove_inappropriate($course);
// update module restrictions
if (isset($data->allowedmods)) {
update_restricted_mods($course, $allowedmods);
}
// Save any custom role names.
save_local_role_names($course->id, $data);
// update enrol settings
enrol_course_updated(false, $course, $data);
add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
// Trigger events
events_trigger('course_updated', $course);
}
/**
@ -3575,7 +3643,6 @@ function average_number_of_courses_modules() {
* @property-read int $summarytrust
* @property-read string $reason
* @property-read int $requester
* @property-read string $password
*/
class course_request {
@ -3845,26 +3912,22 @@ class course_request {
$course->showgrades = $courseconfig->showgrades;
$course->showreports = $courseconfig->showreports;
$course->maxbytes = $courseconfig->maxbytes;
$course->enrol = $courseconfig->enrol;
$course->enrollable = $courseconfig->enrollable;
$course->enrolperiod = $courseconfig->enrolperiod;
$course->expirynotify = $courseconfig->expirynotify;
$course->notifystudents = $courseconfig->notifystudents;
$course->expirythreshold = $courseconfig->expirythreshold;
$course->groupmode = $courseconfig->groupmode;
$course->groupmodeforce = $courseconfig->groupmodeforce;
$course->visible = $courseconfig->visible;
$course->enrolpassword = $courseconfig->enrolpassword;
$course->guest = $courseconfig->guest;
$course->visibleold = $course->visible;
$course->lang = $courseconfig->lang;
//TODO: use standard course creation function !!
// Insert the record
$course->id = $DB->insert_record('course', $course);
if ($course->id) {
$course = $DB->get_record('course', array('id' => $course->id));
blocks_add_default_course_blocks($course);
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
role_assign($CFG->creatornewroleid, $this->properties->requester, 0, $coursecontext->id); // assing teacher role
// TODO: do some real enrolment here
role_assign($CFG->creatornewroleid, $this->properties->requester, $coursecontext->id); // assing teacher role
if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) {
// if we're all or requested we're ok.
$allowedmods = explode(',',$CFG->defaultallowedmodules);
@ -3929,7 +3992,7 @@ class course_request {
foreach ($files as $file) {
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
if (!$file->is_directory()) {
$filerecord = array('contextid'=>$coursecontext->id, 'filearea'=>'course_summary', 'itemid'=>$course->id, 'filepath'=>$file->get_filepath(), 'filename'=>$file->get_filename());
$filerecord = array('contextid'=>$coursecontext->id, 'filearea'=>'course_summary', 'itemid'=>0, 'filepath'=>$file->get_filepath(), 'filename'=>$file->get_filename());
$fs->create_file_from_storedfile($filerecord, $file);
}
}

View File

@ -115,12 +115,7 @@ if (empty($pending)) {
$course->check_shortname_collision();
$row = array();
// Show an enrolment key icon in the first column if applicable.
if (!empty($course->password)) {
$row[] = $keyicon;
} else {
$row[] = '';
}
// TODO: Show an enrolment key icon in the first column if applicable.
// Info in the other columns.
$row[] = format_string($course->shortname);
$row[] = format_string($course->fullname);

View File

@ -80,7 +80,7 @@ class core_course_renderer extends plugin_renderer_base {
$content .= html_writer::tag('div', get_string('expandall'), array('class'=>'removefromall collapseall'));
$content .= html_writer::end_tag('div');
$content .= html_writer::end_tag('div');
// Return the course category tree HTML
return $content;
}
@ -128,18 +128,10 @@ class core_course_renderer extends plugin_renderer_base {
$content .= html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), $course->fullname, array('class'=>'course_link'));
$content .= html_writer::start_tag('div', array('class'=>'course_info clearfix'));
if ($course->guest ) {
$image = html_writer::empty_tag('img', array('src'=>$this->output->pix_url('i/guest'), 'alt'=>$this->strings->allowguests, 'title'=>$this->strings->allowguests));
$content .= html_writer::tag('div', $image, array('class'=>'course_info_spacer'));
} else {
$content .= html_writer::tag('div', '', array('class'=>'course_info_spacer'));
}
if ($course->password) {
$image = html_writer::empty_tag('img', array('src'=>$this->output->pix_url('i/key'), 'alt'=>$this->strings->requireskey, 'title'=>$this->strings->requireskey));
$content .= html_writer::tag('div', $image, array('class'=>'course_info_spacer'));
} else {
$content .= html_writer::tag('div', '', array('class'=>'course_info_spacer'));
}
//TODO: add enrol info
$content .= html_writer::tag('div', '', array('class'=>'course_info_spacer'));
$content .= html_writer::tag('div', '', array('class'=>'course_info_spacer'));
if ($course->summary) {
$image = html_writer::empty_tag('img', array('src'=>$this->output->pix_url('i/info'), 'alt'=>$this->strings->summary));
$content .= html_writer::link(new moodle_url('/course/info.php', array('id'=>$course->id)), $image, array('title'=>$this->strings->summary));

View File

@ -35,6 +35,8 @@ function completion_report_extend_navigation($navigation, $course, $context) {
global $CFG, $OUTPUT;
if (has_capability('coursereport/completion:view', $context)) {
require_once($CFG->libdir.'/completionlib.php');
$url = new moodle_url('/course/report/completion/index.php', array('course'=>$course->id));
$navigation->add(get_string('pluginname','coursereport_completion'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/report', ''));
}

View File

@ -88,7 +88,7 @@ function print_mnet_log_selector_form($hostid, $course, $selecteduser=0, $select
// If looking at a different host, we're interested in all our site users
if ($hostid == $CFG->mnet_localhost_id && $course->id != SITEID) {
$courseusers = get_users_by_capability($context, 'moodle/course:participate', 'u.id, u.firstname, u.lastname, u.idnumber', 'lastname ASC, firstname ASC', $limitfrom, $limitnum, $selectedgroup,'', false);
$courseusers = get_enrolled_users($context, '', $selectedgroup, 'u.id, u.firstname, u.lastname, u.idnumber', 'lastname ASC, firstname ASC', $limitfrom, $limitnum);
} else {
// this may be a lot of users :-(
$courseusers = $DB->get_records('user', array('deleted'=>0), 'lastaccess DESC', 'id, firstname, lastname, idnumber', $limitfrom, $limitnum);
@ -356,12 +356,7 @@ function print_log_selector_form($course, $selecteduser=0, $selecteddate='today'
// Get all the possible users
$users = array();
if ($course->id != SITEID) {
$courseusers = get_users_by_capability($context, 'moodle/course:participate', 'u.id, u.firstname, u.lastname, u.idnumber', 'lastname ASC, firstname ASC', '','',$selectedgroup,null, false);
} else {
// this may be a lot of users :-(
$courseusers = $DB->get_records('user', array('deleted'=>0), 'lastaccess DESC', 'id, firstname, lastname, idnumber');
}
$courseusers = get_enrolled_users($context, '', $selectedgroup, 'u.id, u.firstname, u.lastname, u.idnumber', 'lastname ASC, firstname ASC');
if (count($courseusers) < COURSE_MAX_USERS_PER_DROPDOWN && !$showusers) {
$showusers = 1;

View File

@ -72,11 +72,6 @@ class course_request_form extends moodleform {
$mform->addHelpButton('summary_editor', 'coursesummary');
$mform->setType('summary_editor', PARAM_RAW);
$mform->addElement('passwordunmask', 'password', get_string('enrolmentkey'), 'size="25"');
$mform->setHelpButton('password', array('enrolmentkey', get_string('enrolmentkey')), true);
$mform->setDefault('password', '');
$mform->setType('password', PARAM_RAW);
$mform->addElement('header','requestreason', get_string('courserequestreason'));
$mform->addElement('textarea', 'reason', get_string('courserequestsupport'), array('rows'=>'15', 'cols'=>'50'));

View File

@ -25,7 +25,7 @@ class course_reset_form extends moodleform {
$mform->addElement('header', 'rolesheader', get_string('roles'));
$roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, $COURSE->id));
$mform->addElement('select', 'reset_roles', get_string('unenrolroleusers'), $roles, array('multiple' => 'multiple'));
$mform->addElement('select', 'unenrol_users', get_string('unenrolroleusers', 'enrol'), $roles, array('multiple' => 'multiple'));
$mform->addElement('checkbox', 'reset_roles_overrides', get_string('deletecourseoverrides', 'role'));
$mform->setAdvanced('reset_roles_overrides');
$mform->addElement('checkbox', 'reset_roles_local', get_string('deletelocalroles', 'role'));
@ -102,12 +102,6 @@ class course_reset_form extends moodleform {
$defaults = array ('reset_events'=>1, 'reset_logs'=>1, 'reset_roles_local'=>1, 'reset_gradebook_grades'=>1, 'reset_notes'=>1);
if (!empty($COURSE->defaultrole)) {
$defaults['reset_roles'] = array($COURSE->defaultrole);
} else {
$defaults['reset_roles'] = array($CFG->defaultcourseroleid);
}
if ($allmods = $DB->get_records('modules') ) {
foreach ($allmods as $mod) {
$modname = $mod->name;

View File

@ -1,123 +0,0 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Remove oneself or someone else from a course, unassigning all roles one might have
*
* This will not delete any of their data from the course, but will remove them
* from the participant list and prevent any course email being sent to them.
*
* @copyright 1999 Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package course
*/
require_once("../config.php");
require_once("lib.php");
$id = required_param('id', PARAM_INT); //course
$userid = optional_param('user', 0, PARAM_INT); //course
$confirm = optional_param('confirm', 0, PARAM_BOOL);
$PAGE->set_url('/course/unenrol.php', array('id'=>$id));
if($userid == $USER->id){
// the rest of this code assumes $userid=0 means
// you are unassigning yourself, so set this for the
// correct capabiliy checks & language later
$userid = 0;
}
if (!$course = $DB->get_record('course', array('id'=>$id))) {
print_error('invalidcourseid');
}
if (! $context = get_context_instance(CONTEXT_COURSE, $course->id)) {
print_error('invalidcontext');
}
require_login($course->id);
if ($course->metacourse) {
print_error('cantunenrollfrommetacourse', '', $CFG->wwwroot.'/course/view.php?id='.$course->id);
}
if ($userid) { // Unenrolling someone else
require_capability('moodle/role:assign', $context, NULL, false);
$roles = get_user_roles($context, $userid, false);
// verify user may unassign all roles at course context
foreach($roles as $role) {
if (!user_can_assign($context, $role->roleid)) {
print_error('cannotunassignrolefrom', '', '',
$role->roleid);
}
}
} else { // Unenrol yourself
require_capability('moodle/role:unassignself', $context, NULL, false);
}
if (!empty($USER->access['rsw'][$context->path])) {
print_error('cantunenrollinthisrole', '',
$CFG->wwwroot.'/course/view.php?id='.$course->id);
}
if ($confirm and confirm_sesskey()) {
if ($userid) {
if (! role_unassign(0, $userid, 0, $context->id)) {
print_error("unenrolerror");
}
add_to_log($course->id, 'course', 'unenrol',
"view.php?id=$course->id", $course->id);
redirect($CFG->wwwroot.'/user/index.php?id='.$course->id);
} else {
if (! role_unassign(0, $USER->id, 0, $context->id)) {
print_error("unenrolerror");
}
// force a refresh of mycourses
unset($USER->mycourses);
add_to_log($course->id, 'course', 'unenrol',
"view.php?id=$course->id", $course->id);
redirect($CFG->wwwroot);
}
}
$strunenrol = get_string('unenrol');
$PAGE->navbar->add($strunenrol);
$PAGE->set_title("$course->shortname: $strunenrol");
$PAGE->set_heading($course->fullname);
echo $OUTPUT->header();
if ($userid) {
if (!$user = $DB->get_record('user', array('id'=>$userid))) {
print_error('nousers');
}
$strunenrolsure = get_string('unenrolsure', '', fullname($user, true));
echo $OUTPUT->confirm($strunenrolsure, "unenrol.php?id=$id&user=$user->id&confirm=yes", $PAGE->url);
} else {
$strunenrolsure = get_string('unenrolsure', '', get_string("yourself"));
echo $OUTPUT->confirm($strunenrolsure, "unenrol.php?id=$id&confirm=yes", $PAGE->url);
}
echo $OUTPUT->footer();

View File

@ -53,8 +53,9 @@ require_login();
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$personalcontext = get_context_instance(CONTEXT_USER, $user->id);
require_login();
$PAGE->set_pagelayout('admin');
if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext) and !has_capability('moodle/course:participate', $coursecontext)) {
if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext) and !is_enrolled($coursecontext)) {
// do not require parents to be enrolled in courses ;-)
$PAGE->set_course($course);
} else {

View File

@ -28,7 +28,7 @@ function xmldb_enrol_authorize_upgrade($oldversion) {
//===== 1.9.0 upgrade line ======//
if ($result && $oldversion < 2008020500 && is_enabled_enrol('authorize')) {
if ($result && $oldversion < 2008020500 && enrol_is_enabled('authorize')) {
require_once($CFG->dirroot.'/enrol/authorize/localfuncs.php');
if (!check_curl_available()) {
echo $OUTPUT->notification("You are using the authorize.net enrolment plugin for payment handling but cUrl is not available.

View File

@ -1,6 +1,5 @@
<?php
require_once($CFG->dirroot.'/enrol/enrol.class.php');
require_once($CFG->dirroot.'/enrol/authorize/const.php');
require_once($CFG->dirroot.'/enrol/authorize/localfuncs.php');
require_once($CFG->dirroot.'/enrol/authorize/authorizenet.class.php');
@ -49,7 +48,7 @@ class enrolment_plugin_authorize
print_error('httpsrequired', 'enrol_authorize');
} else {
$wwwsroot = str_replace('http:','https:', $CFG->wwwroot);
redirect("$wwwsroot/course/enrol.php?id=$course->id");
redirect("$wwwsroot/enrol/index.php?id=$course->id");
exit;
}
}
@ -685,7 +684,8 @@ class enrolment_plugin_authorize
$timeend = $order->settletime + $course->enrolperiod;
}
$user = $DB->get_record('user', array('id'=>$order->userid));
if (role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, 'authorize')) {
// TODO: do some real enrolment here
if (role_assign($role->id, $user->id, $context->id, 'enrol_authorize')) {
$this->log .= "User($user->id) has been enrolled to course($course->id).\n";
if (!empty($CFG->enrol_mailstudents)) {
$sendem[] = $order->id;

View File

@ -358,7 +358,7 @@ function authorize_print_order($orderid)
}
else {
if (!empty($unenrol)) {
role_unassign(0, $order->userid, 0, $coursecontext->id);
role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
}
redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid");
}
@ -383,7 +383,7 @@ function authorize_print_order($orderid)
elseif (ORDER_DELETE == $do && in_array(ORDER_DELETE, $statusandactions->actions)) {
if ($confirm && confirm_sesskey()) {
if (!empty($unenrol)) {
role_unassign(0, $order->userid, 0, $coursecontext->id);
role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
}
$DB->delete_records('enrol_authorize', array('id'=>$orderid));
redirect("$CFG->wwwroot/enrol/authorize/index.php");
@ -436,7 +436,7 @@ function authorize_print_order($orderid)
if (AN_APPROVED == AuthorizeNet::process($suborder, $message, $extra, AN_ACTION_VOID)) {
if (empty($CFG->an_test)) {
if (!empty($unenrol)) {
role_unassign(0, $order->userid, 0, $coursecontext->id);
role_unassign_all(array('userid'=>$order->userid, 'contextid'=>$coursecontext->id, 'component'=>'enrol_authorize'), true, true);
}
redirect("$CFG->wwwroot/enrol/authorize/index.php?order=$orderid");
}

View File

@ -215,7 +215,8 @@ function authorize_process_csv($filename) {
$timestart = time();
$timeend = $timestart + $course->enrolperiod;
}
if (role_assign($role->id, $user->id, 0, $coursecontext->id, $timestart, $timeend, 0, 'authorize')) {
//TODO: do some real enrolment here
if (role_assign($role->id, $user->id, $coursecontext->id, 'enrol_authorize')) {
$imported++;
if (!empty($CFG->enrol_mailstudents)) {
$sendem[] = $order->id;

View File

@ -0,0 +1,38 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* CLI sync for full category enrol synchronisation.
*
* @package enrol_category
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
if (isset($_SERVER['REMOTE_ADDR'])) {
error_log("enrol/category/cli/sync.php can not be called from web server!");
exit;
}
require(dirname(dirname(dirname(dirname(__FILE__)))).'/config.php');
require_once("$CFG->dirroot/enrol/category/locallib.php");
if (!enrol_is_enabled('category')) {
die('enrol_category plugin is disabled, sync is disabled');
}
enrol_category_sync_full();

View File

@ -0,0 +1,38 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Capabilities for category access plugin.
*
* @package enrol_category
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$capabilities = array(
// marks roles that have category role assignments synchronised to course enrolments
// overrides bellow system context are ignored (for performance reasons).
// by default his is not allowed in new installs, admins have to explicitly allow category enrolments
'enrol/category:synchronised' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
)
),
);

View File

@ -0,0 +1,40 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* category enrolment plugin event handler definition.
*
* @package enrol_category
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/* List of handlers */
$handlers = array (
'role_assigned' => array (
'handlerfile' => '/enrol/category/locallib.php',
'handlerfunction' => array('enrol_category_handler', 'role_assigned'),
'schedule' => 'instant'
),
'role_unassigned' => array (
'handlerfile' => '/enrol/category/locallib.php',
'handlerfunction' => array('enrol_category_handler', 'role_unassigned'),
'schedule' => 'instant'
),
);

View File

@ -0,0 +1,69 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* category enrolment plugin installation.
*
* @package enrol_category
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
function xmldb_enrol_category_install() {
global $CFG, $DB;
if (!$DB->record_exists_select('role_assignments', "contextid IN (SELECT id FROM {context} WHERE contextlevel = ?)", array(CONTEXT_COURSECAT))) {
// fresh install or nobody used category enrol
return;
}
// existing sites need a way to keep category role enrols, but we do not want to encourage that on new sites
// extremely ugly hack, the sync depends on the capabilities so we unfortunately force update of caps here
// note: this is not officially supported and should not be copied elsewhere! :-(
update_capabilities('enrol_category');
$syscontext = get_context_instance(CONTEXT_SYSTEM);
$archetypes = array('student', 'teacher', 'editingteacher');
$enableplugin = false;
foreach ($archetypes as $archetype) {
$roles = get_archetype_roles($archetype);
foreach ($roles as $role) {
if (!$DB->record_exists_select('role_assignments', "roleid = ? AND contextid IN (SELECT id FROM {context} WHERE contextlevel = ?)", array($role->id, CONTEXT_COURSECAT))) {
continue;
}
assign_capability('enrol/category:synchronised', CAP_ALLOW, $role->id, $syscontext->id, true);
$levels = get_role_contextlevels($role->id);
$levels[] = CONTEXT_COURSECAT;
set_role_contextlevels($role->id, $levels);
$enableplugin = true;
}
}
if (!$enableplugin) {
return;
}
// enable this plugin
$enabledplugins = explode(',', $CFG->enrol_plugins_enabled);
$enabledplugins[] = 'category';
$enabledplugins = array_unique($enabledplugins);
set_config('enrol_plugins_enabled', implode(',', $enabledplugins));
// brute force course resync, this may take a while
require_once("$CFG->dirroot/enrol/category/locallib.php");
enrol_category_sync_full();
}

View File

@ -0,0 +1,28 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'enrol_category', language 'en', branch 'MOODLE_20_STABLE'
*
* @package enrol_category
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['category:synchronised'] = 'Role assignments synchronised to course enrolment';
$string['pluginname'] = 'Category enrolments';
$string['pluginname_desc'] = 'Category enrolment plugin is a legacy solution for enrolments at the course category level via role assignments. It is recommended to use cohort synchronisation instead.';

97
enrol/category/lib.php Normal file
View File

@ -0,0 +1,97 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Category enrolment plugin.
*
* @package enrol_category
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* category enrolment plugin implementation.
* @author Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class enrol_category_plugin extends enrol_plugin {
/**
* Is it possible to delete enrol instance via standard UI?
*
* @param object $instance
* @return bool
*/
public function instance_deleteable($instance) {
global $DB;
if (!enrol_is_enabled('category')) {
return true;
}
// allow delete only when no synced users here
return !$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id));
}
/**
* Returns link to page which may be used to add new instance of enrolment plugin in course.
* @param int $courseid
* @return moodle_url page url
*/
public function get_candidate_link($courseid) {
// instances are added automatically as necessary
return NULL;
}
/**
* Called for all enabled enrol plugins that returned true from is_cron_required().
* @return void
*/
public function cron() {
global $CFG;
if (!enrol_is_enabled('category')) {
return;
}
require_once("$CFG->dirroot/enrol/category/locallib.php");
enrol_category_sync_full();
}
/**
* Called after updating/inserting course.
*
* @param bool $inserted true if course just inserted
* @param object $course
* @param object $data form data
* @return void
*/
public function course_updated($inserted, $course, $data) {
global $CFG;
if (!enrol_is_enabled('category')) {
return;
}
// sync category enrols
require_once("$CFG->dirroot/enrol/category/locallib.php");
enrol_category_sync_course($course);
}
}

323
enrol/category/locallib.php Normal file
View File

@ -0,0 +1,323 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Local stuff for category enrolment plugin.
*
* @package enrol_category
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* Event handler for category enrolment plugin.
*
* We try to keep everything in sync via listening to events,
* it may fail sometimes, so we always do a full sync in cron too.
*/
class enrol_category_handler {
public function role_assigned($ra) {
global $DB;
if (!enrol_is_enabled('category')) {
return true;
}
//only category level roles are interesting
$parentcontext = get_context_instance_by_id($ra->contextid);
if ($parentcontext->contextlevel != CONTEXT_COURSECAT) {
return true;
}
// make sure the role is to be actually synchronised
// please note we are ignoring overrides of the synchronised capability (for performance reasons in full sync)
$syscontext = get_context_instance(CONTEXT_SYSTEM);
if (!$DB->record_exists('role_capabilities', array('contextid'=>$syscontext->id, 'roleid'=>$ra->roleid, 'capability'=>'enrol/category:synchronised', 'permission'=>CAP_ALLOW))) {
return true;
}
// add necessary enrol instances
$plugin = enrol_get_plugin('category');
$sql = "SELECT c.*
FROM {course} c
JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :courselevel AND ctx.path LIKE :match)
LEFT JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'category')
WHERE e.id IS NULL";
$params = array('courselevel'=>CONTEXT_COURSE, 'match'=>$parentcontext->path.'/%');
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $course) {
$plugin->add_instance($course);
}
$rs->close();
// now look for missing enrols
$sql = "SELECT e.*
FROM {course} c
JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :courselevel AND ctx.path LIKE :match)
JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'category')
LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
WHERE ue.id IS NULL";
$params = array('courselevel'=>CONTEXT_COURSE, 'match'=>$parentcontext->path.'/%', 'userid'=>$ra->userid);
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $instance) {
$plugin->enrol_user($instance, $ra->userid);
}
$rs->close();
return true;
}
public function role_unassigned($ra) {
global $DB;
if (!enrol_is_enabled('category')) {
return true;
}
// only category level roles are interesting
$parentcontext = get_context_instance_by_id($ra->contextid);
if ($parentcontext->contextlevel != CONTEXT_COURSECAT) {
return true;
}
// now this is going to be a bit slow, take all enrolments in child courses and verify each separately
$syscontext = get_context_instance(CONTEXT_SYSTEM);
$roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext);
$plugin = enrol_get_plugin('category');
$sql = "SELECT e.*
FROM {course} c
JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :courselevel AND ctx.path LIKE :match)
JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'category')
JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)";
$params = array('courselevel'=>CONTEXT_COURSE, 'match'=>$parentcontext->path.'/%', 'userid'=>$ra->userid);
$rs = $DB->get_recordset_sql($sql, $params);
list($roleids, $params) = $DB->get_in_or_equal(array_keys($roles), SQL_PARAMS_NAMED, 'r000');
$params['userid'] = $ra->userid;
foreach ($rs as $instance) {
$coursecontext = get_context_instance(CONTEXT_COURSE, $instance->courseid);
$contextids = get_parent_contexts($coursecontext);
array_pop($contextids); // remove system context, we are interested in categories only
list($contextids, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'c000');
$params = array_merge($params, $contextparams);
$sql = "SELECT ra.id
FROM {role_assignments} ra
WHERE ra.userid = :userid AND ra.contextid $contextids AND ra.roleid $roleids";
if (!$DB->record_exists_sql($sql, $params)) {
// user does not have any interesting role in any parent context, let's unenrol
$plugin->unenrol_user($instance, $ra->userid);
}
}
$rs->close();
return true;
}
}
/**
* Sync all category enrolments in one course
* @param int $courseid course id
* @return void
*/
function enrol_category_sync_course($course) {
global $DB;
if (!enrol_is_enabled('category')) {
return;
}
$plugin = enrol_get_plugin('category');
$syscontext = get_context_instance(CONTEXT_SYSTEM);
$roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext);
// first find out if any parent category context contains interesting role assignments
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$contextids = get_parent_contexts($coursecontext);
array_pop($contextids); // remove system context, we are interested in categories only
list($roleids, $params) = $DB->get_in_or_equal(array_keys($roles), SQL_PARAMS_NAMED, 'r000');
list($contextids, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'c000');
$params = array_merge($params, $contextparams);
$params['courseid'] = $course->id;
$sql = "SELECT 'x'
FROM {role_assignments}
WHERE roleid $roleids AND contextid $contextids";
if (!$DB->record_exists_sql($sql, $params)) {
if ($instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'enrol'=>'category'))) {
// should be max one instance, but anyway
foreach ($instances as $instance) {
$plugin->delete_instance($instance);
}
}
return;
}
// make sure the enrol instance exists - there should be always only one instance
$delinstances = array();
if ($instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'enrol'=>'category'))) {
$instance = array_shift($instances);
$delinstances = $instances;
} else {
$i = $plugin->add_instance($course);
$instance = $DB->get_record('enrol', array('id'=>$i));
}
// add new enrolments
$sql = "SELECT ra.userid
FROM (SELECT DISTINCT xra.userid
FROM {role_assignments} xra
WHERE xra.roleid $roleids AND xra.contextid $contextids
) ra
LEFT JOIN {user_enrolments} ue ON (ue.enrolid = :instanceid AND ue.userid = ra.userid)
WHERE ue.id IS NULL";
$params['instanceid'] = $instance->id;
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $ra) {
$plugin->enrol_user($instance, $ra->userid);
}
$rs->close();
// remove unwanted enrolments
$sql = "SELECT DISTINCT ue.userid
FROM {user_enrolments} ue
LEFT JOIN {role_assignments} ra ON (ra.roleid $roleids AND ra.contextid $contextids AND ra.userid = ue.userid)
WHERE ue.enrolid = :instanceid AND ra.id IS NULL";
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $ra) {
$plugin->unenrol_user($instance, $ra->userid);
}
$rs->close();
if ($delinstances) {
// we have to do this as the last step in order to prevent temporary unenrolment
foreach ($delinstances as $delinstance) {
$plugin->delete_instance($delinstance);
}
}
}
function enrol_category_sync_full() {
global $DB;
if (!enrol_is_enabled('category')) {
return;
}
// we may need a lot of time here
@set_time_limit(0);
$plugin = enrol_get_plugin('category');
$syscontext = get_context_instance(CONTEXT_SYSTEM);
// any interesting roles worth synchronising?
if (!$roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext)) {
// yay, nothing to do, so let's remove all leftovers
if ($instances = $DB->get_records('enrol', array('enrol'=>'category'))) {
$plugin->delete_instance($instance);
}
}
list($roleids, $params) = $DB->get_in_or_equal(array_keys($roles), SQL_PARAMS_NAMED, 'r000');
$params['courselevel'] = CONTEXT_COURSE;
$params['catlevel'] = CONTEXT_COURSECAT;
// first of all add necessay enrol instances to all courses
$parentcat = $DB->sql_concat("cat.path", "'/%'");
$sql = "SELECT DISTINCT c.*
FROM {course} c
JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :courselevel)
JOIN (SELECT DISTINCT cctx.path
FROM {course_categories} cc
JOIN {context} cctx ON (cctx.instanceid = cc.id AND cctx.contextlevel = :catlevel)
JOIN {role_assignments} ra ON (ra.contextid = cctx.id AND ra.roleid $roleids)
) cat ON (ctx.path LIKE $parentcat)
LEFT JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'category')
WHERE e.id IS NULL";
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $course) {
$plugin->add_instance($course);
}
$rs->close();
// now look for courses that do not have any interesting roles in parent contexts,
// but still have the instance and delete them
$sql = "SELECT e.*
FROM {enrol} e
JOIN {context} ctx ON (ctx.instanceid = e.courseid AND ctx.contextlevel = :courselevel)
LEFT JOIN (SELECT DISTINCT cctx.path
FROM {course_categories} cc
JOIN {context} cctx ON (cctx.instanceid = cc.id AND cctx.contextlevel = :catlevel)
JOIN {role_assignments} ra ON (ra.contextid = cctx.id AND ra.roleid $roleids)
) cat ON (ctx.path LIKE $parentcat)
WHERE e.enrol = 'category' AND cat.path IS NULL";
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $instance) {
$plugin->delete_instance($instance);
}
$rs->close();
// add missing enrolments
$sql = "SELECT e.*, cat.userid
FROM {enrol} e
JOIN {context} ctx ON (ctx.instanceid = e.courseid AND ctx.contextlevel = :courselevel)
JOIN (SELECT DISTINCT cctx.path, ra.userid
FROM {course_categories} cc
JOIN {context} cctx ON (cctx.instanceid = cc.id AND cctx.contextlevel = :catlevel)
JOIN {role_assignments} ra ON (ra.contextid = cctx.id AND ra.roleid $roleids)
) cat ON (ctx.path LIKE $parentcat)
LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = cat.userid)
WHERE e.enrol = 'category' AND ue.id IS NULL";
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $instance) {
$userid = $instance->userid;
unset($instance->userid);
$plugin->enrol_user($instance, $userid);
}
$rs->close();
// remove stale enrolments
$sql = "SELECT e.*, ue.userid
FROM {enrol} e
JOIN {context} ctx ON (ctx.instanceid = e.courseid AND ctx.contextlevel = :courselevel)
JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
LEFT JOIN (SELECT DISTINCT cctx.path, ra.userid
FROM {course_categories} cc
JOIN {context} cctx ON (cctx.instanceid = cc.id AND cctx.contextlevel = :catlevel)
JOIN {role_assignments} ra ON (ra.contextid = cctx.id AND ra.roleid $roleids)
) cat ON (ctx.path LIKE $parentcat AND cat.userid = ue.userid)
WHERE e.enrol = 'category' AND cat.userid IS NULL";
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $instance) {
$userid = $instance->userid;
unset($instance->userid);
$plugin->unenrol_user($instance, $userid);
}
$rs->close();
}

View File

@ -0,0 +1,37 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* category enrolment plugin settings and presets.
*
* @package enrol_category
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
if ($ADMIN->fulltree) {
//--- general settings -----------------------------------------------------------------------------------
$settings->add(new admin_setting_heading('enrol_category_settings', '', get_string('pluginname_desc', 'enrol_category')));
//--- enrol instance defaults ----------------------------------------------------------------------------
}

View File

@ -0,0 +1,27 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Category enrolment plugin version specification.
*
* @package enrol_category
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$plugin->version = 2010061500;
$plugin->cron = 60;

View File

@ -0,0 +1,60 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Adds new instance of enrol_cohort to specified course.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require('../../config.php');
require_once("$CFG->dirroot/enrol/cohort/addinstance_form.php");
require_once("$CFG->dirroot/enrol/cohort/locallib.php");
$id = required_param('id', PARAM_INT); // course id
$course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST);
$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
require_login($course);
require_capability('moodle/course:enrolconfig', $context);
$enrol = enrol_get_plugin('cohort');
if (!$enrol->get_candidate_link($course->id)) {
redirect(new moodle_url('/enrol/instances.php', array('id'=>$course->id)));
}
$mform = new enrol_cohort_addinstance_form(NULL, $course);
if ($mform->is_cancelled()) {
redirect(new moodle_url('/enrol/instances.php', array('id'=>$course->id)));
} else if ($data = $mform->get_data()) {
$enrol->add_instance($course, array('customint1'=>$data->cohortid, 'roleid'=>$data->roleid));
enrol_cohort_sync($course->id);
redirect(new moodle_url('/enrol/instances.php', array('id'=>$course->id)));
}
$PAGE->set_url('/enrol/cohort/addinstance.php', array('id'=>$course->id));
echo $OUTPUT->header();
$mform->display();
echo $OUTPUT->footer();

View File

@ -0,0 +1,72 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Adds instance form
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
require_once("$CFG->libdir/formslib.php");
class enrol_cohort_addinstance_form extends moodleform {
function definition() {
global $CFG, $DB;
$mform = $this->_form;
$course = $this->_customdata;
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$enrol = enrol_get_plugin('cohort');
//TODO: add only cohorts from parent contexts of this course
$cohorts = array('' => get_string('choosedots'));
$rs = $DB->get_recordset('cohort', array(), 'name ASC', 'id, name, contextid');
foreach ($rs as $c) {
$context = get_context_instance_by_id($c->contextid);
if (!has_capability('moodle/cohort:view', $context)) {
continue;
}
$cohorts[$c->id] = format_string($c->name);
}
$rs->close();
$roles = get_assignable_roles($coursecontext);
$mform->addElement('header','general', get_string('pluginname', 'enrol_cohort'));
$mform->addElement('select', 'cohortid', get_string('cohort', 'cohort'), $cohorts);
$mform->addRule('cohortid', get_string('required'), 'required', null, 'client');
$mform->addElement('select', 'roleid', get_string('role'), $roles);
$mform->addRule('roleid', get_string('required'), 'required', null, 'client');
$mform->setDefault('roleid', $enrol->get_config('roleid'));
$mform->addElement('hidden', 'id', null);
$mform->setType('id', PARAM_INT);
$this->add_action_buttons();
$this->set_data(array('id'=>$course->id));
}
//TODO: validate duplicate role-cohort does not exist
}

View File

@ -0,0 +1,37 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Capabilities for cohort access plugin.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$capabilities = array(
// configure the cohort plugin settings in each course
'enrol/cohort:config' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'manager' => CAP_ALLOW,
)
),
);

View File

@ -0,0 +1,45 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Cohort enrolment plugin event handler definition.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/* List of handlers */
$handlers = array (
'cohort_member_added' => array (
'handlerfile' => '/enrol/cohort/locallib.php',
'handlerfunction' => array('enrol_cohort_handler', 'member_added'),
'schedule' => 'instant'
),
'cohort_member_removed' => array (
'handlerfile' => '/enrol/cohort/locallib.php',
'handlerfunction' => array('enrol_cohort_handler', 'member_removed'),
'schedule' => 'instant'
),
'cohort_deleted' => array (
'handlerfile' => '/enrol/cohort/locallib.php',
'handlerfunction' => array('enrol_cohort_handler', 'deleted'),
'schedule' => 'instant'
),
);

View File

@ -0,0 +1,28 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'enrol_cohort', language 'en', branch 'MOODLE_20_STABLE'
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['cohort:config'] = 'Configure cohort instances';
$string['pluginname'] = 'Cohort sync';
$string['pluginname_desc'] = 'Cohort enrolment plugin synchronises cohort members with course participants.';

118
enrol/cohort/lib.php Normal file
View File

@ -0,0 +1,118 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Cohort enrolment plugin.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* Cohort enrolment plugin implementation.
* @author Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class enrol_cohort_plugin extends enrol_plugin {
/**
* Returns localised name of enrol instance
*
* @param object $instance (null is accepted too)
* @return string
*/
public function get_instance_name($instance) {
global $DB;
if (empty($instance)) {
$enrol = $this->get_name();
return get_string('pluginname', 'enrol_'.$enrol);
} else if (empty($instance->name)) {
$enrol = $this->get_name();
if ($role = $DB->get_record('role', array('id'=>$instance->roleid))) {
$role = role_get_name($role, get_context_instance(CONTEXT_COURSE, $instance->courseid));
} else {
$role = get_string('error');
}
return get_string('pluginname', 'enrol_'.$enrol) . ' (' . format_string($DB->get_field('cohort', 'name', array('id'=>$instance->customint1))) . ' - ' . $role .')';
} else {
return format_string($instance->name);
}
}
/**
* Returns link to page which may be used to add new instance of enrolment plugin in course.
* @param int $courseid
* @return moodle_url page url
*/
public function get_candidate_link($courseid) {
global $DB;
if (!has_capability('moodle/course:enrolconfig', get_context_instance(CONTEXT_COURSE, $courseid, MUST_EXIST))) {
return NULL;
}
if (!$DB->record_exists('cohort', array())) {
//TODO: consider only parent contexts
return NULL;
}
// multiple instances supported - multiple parent courses linked
return new moodle_url('/enrol/cohort/addinstance.php', array('id'=>$courseid));
}
/**
* Called for all enabled enrol plugins that returned true from is_cron_required().
* @return void
*/
public function cron() {
global $CFG;
// purge all roles if cohort sync disabled, those can be recreated later here in cron
if (!enrol_is_enabled('cohort')) {
role_unassign_all(array('component'=>'cohort_enrol'));
return;
}
require_once("$CFG->dirroot/enrol/cohort/locallib.php");
enrol_cohort_sync();
}
/**
* Called after updating/inserting course.
*
* @param bool $inserted true if course just inserted
* @param object $course
* @param object $data form data
* @return void
*/
public function course_updated($inserted, $course, $data) {
global $CFG;
if (!$inserted) {
// sync cohort enrols
require_once("$CFG->dirroot/enrol/cohort/locallib.php");
enrol_cohort_sync($course->id);
} else {
// cohorts are never inserted automatically
}
}
}

189
enrol/cohort/locallib.php Normal file
View File

@ -0,0 +1,189 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Local stuff for cohort enrolment plugin.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* Event handler for cohort enrolment plugin.
*
* We try to keep everything in sync via listening to events,
* it may fail sometimes, so we always do a full sync in cron too.
*/
class enrol_cohort_handler {
public function member_added($ca) {
global $DB;
if (!enrol_is_enabled('cohort')) {
return true;
}
// does anything want to sync with this parent?
//TODO: add join to role table to make sure that roleid actually exists
if (!$enrols = $DB->get_records('enrol', array('customint1'=>$ca->cohortid, 'enrol'=>'cohort'), 'id ASC')) {
return true;
}
$plugin = enrol_get_plugin('cohort');
foreach ($enrols as $enrol) {
// no problem if already enrolled
$plugin->enrol_user($enrol, $ca->userid, $enrol->roleid);
}
return true;
}
public function member_removed($ca) {
global $DB;
// does anything want to sync with this parent?
if (!$enrols = $DB->get_records('enrol', array('customint1'=>$ca->cohortid, 'enrol'=>'cohort'), 'id ASC')) {
return true;
}
$plugin = enrol_get_plugin('cohort');
foreach ($enrols as $enrol) {
// no problem if already enrolled
$plugin->unenrol_user($enrol, $ca->userid);
}
return true;
}
public function deleted($cohort) {
global $DB;
// does anything want to sync with this parent?
if (!$enrols = $DB->get_records('enrol', array('customint1'=>$cohort->id, 'enrol'=>'cohort'), 'id ASC')) {
return true;
}
$plugin = enrol_get_plugin('cohort');
foreach ($enrols as $enrol) {
$plugin->delete_instance($enrol);
}
return true;
}
}
/**
* Sync all cohort course links.
* @param int $courseid one course, empty mean all
* @return void
*/
function enrol_cohort_sync($courseid = NULL) {
global $CFG, $DB;
// unfortunately this may take a long time
@set_time_limit(0); //if this fails during upgrade we can continue from cron, no big deal
$cohort = enrol_get_plugin('cohort');
$onecourse = $courseid ? "AND e.courseid = :courseid" : "";
// iterate through all not enrolled yet users
if (enrol_is_enabled('cohort')) {
$params = array();
$onecourse = "";
if ($courseid) {
$params['courseid'] = $courseid;
$onecourse = "AND e.courseid = :courseid";
}
$sql = "SELECT cm.userid, e.id AS enrolid
FROM {cohort_members} cm
JOIN {enrol} e ON (e.customint1 = cm.cohortid AND e.status = :statusenabled AND e.enrol = 'cohort' $onecourse)
LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = cm.userid)
WHERE ue.id IS NULL";
$params['statusenabled'] = ENROL_INSTANCE_ENABLED;
$params['courseid'] = $courseid;
$rs = $DB->get_recordset_sql($sql, $params);
$instances = array(); //cache
foreach($rs as $ue) {
if (!isset($instances[$ue->enrolid])) {
$instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
}
$cohort->enrol_user($instances[$ue->enrolid], $ue->userid);
}
$rs->close();
unset($instances);
}
// unenrol as necessary - ignore enabled flag, we want to get rid of all
$sql = "SELECT ue.userid, e.id AS enrolid
FROM {user_enrolments} ue
JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' $onecourse)
LEFT JOIN {cohort_members} cm ON (cm.cohortid = e.customint1 AND cm.userid = ue.userid)
WHERE cm.id IS NULL";
//TODO: this may use a bit of SQL optimisation
$rs = $DB->get_recordset_sql($sql, array('courseid'=>$courseid));
$instances = array(); //cache
foreach($rs as $ue) {
if (!isset($instances[$ue->enrolid])) {
$instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
}
$cohort->unenrol_user($instances[$ue->enrolid], $ue->userid);
}
$rs->close();
unset($instances);
// now assign all necessary roles
if (enrol_is_enabled('cohort')) {
$sql = "SELECT e.roleid, ue.userid, c.id AS contextid, e.id AS itemid
FROM {user_enrolments} ue
JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' AND e.status = :statusenabled $onecourse)
JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :coursecontext)
LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid AND ra.itemid = e.id AND ra.component = 'enrol_cohort' AND e.roleid = ra.roleid)
WHERE ra.id IS NULL";
$params = array();
$params['statusenabled'] = ENROL_INSTANCE_ENABLED;
$params['coursecontext'] = CONTEXT_COURSE;
$params['courseid'] = $courseid;
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $ra) {
role_assign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_cohort', $ra->itemid);
}
$rs->close();
}
// remove unwanted roles - include ignored roles and disabled plugins too
$onecourse = $courseid ? "AND c.instanceid = :courseid" : "";
$sql = "SELECT ra.roleid, ra.userid, ra.contextid, ra.itemid
FROM {role_assignments} ra
JOIN {context} c ON (c.id = ra.contextid AND c.contextlevel = :coursecontext $onecourse)
LEFT JOIN (SELECT e.id AS enrolid, e.roleid, ue.userid
FROM {user_enrolments} ue
JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort')
) x ON (x.enrolid = ra.itemid AND ra.component = 'enrol_cohort' AND x.roleid = ra.roleid AND x.userid = ra.userid)
WHERE x.userid IS NULL AND ra.component = 'enrol_cohort'";
$params = array('coursecontext' => CONTEXT_COURSE, 'courseid' => $courseid);
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $ra) {
role_unassign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_cohort', $ra->itemid);
}
$rs->close();
}

44
enrol/cohort/settings.php Normal file
View File

@ -0,0 +1,44 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Cohort enrolment plugin settings and presets.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
if ($ADMIN->fulltree) {
//--- general settings -----------------------------------------------------------------------------------
$settings->add(new admin_setting_heading('enrol_cohort_settings', '', get_string('pluginname_desc', 'enrol_cohort')));
//--- enrol instance defaults ----------------------------------------------------------------------------
if (!during_initial_install()) {
$options = get_default_enrol_roles(get_context_instance(CONTEXT_SYSTEM));
$student = get_archetype_roles('student');
$student = reset($student);
$settings->add(new admin_setting_configselect_with_advanced('enrol_cohort/roleid',
get_string('defaultrole', 'role'), '',
array('value'=>$student->id, 'adv'=>true), $options));
}
}

27
enrol/cohort/version.php Normal file
View File

@ -0,0 +1,27 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Cohort enrolment plugin version specification.
*
* @package enrol_cohort
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$plugin->version = 2010061500;
$plugin->cron = 60;

View File

@ -0,0 +1,40 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* CLI sync for full external database synchronisation.
*
* @package enrol_database
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
if (isset($_SERVER['REMOTE_ADDR'])) {
error_log("enrol/database/cli/sync.php can not be called from web server!");
exit;
}
require(dirname(dirname(dirname(dirname(__FILE__)))).'/config.php');
if (!enrol_is_enabled('database')) {
die('enrol_database plugin is disabled, sync is disabled');
}
$enrol = enrol_get_plugin('database');
$enrol->sync_courses();
$enrol->sync_enrolments();

View File

@ -1,251 +0,0 @@
<?php
$yesno = array('0'=>get_string('no'), '1'=>get_string('yes'));
?>
<table cellspacing="0" cellpadding="5" border="0" class="boxaligncenter">
<tr>
<th colspan="2" scope="col">
<?php print_string("server_settings", "enrol_database") ?>
</th>
</tr>
<tr>
<td align="right">enrol_dbtype:</td>
<td>
<?php
$dbtypes = array("access","ado_access", "ado", "ado_mssql", "borland_ibase", "csv", "db2", "fbsql", "firebird", "ibase", "informix72", "informix", "mssql", "mssql_n", "mysql", "mysqlt", "oci805", "oci8", "oci8po", "odbc", "odbc_mssql", "odbc_oracle", "oracle", "postgres64", "postgres7", "postgres", "proxy", "sqlanywhere", "sybase", "vfp");
foreach ($dbtypes as $dbtype) {
$dboptions[$dbtype] = $dbtype;
}
if (!isset($frm->enrol_dbtype)) {
$frm->enrol_dbtype = 'mysql';
}
echo html_writer::select($dboptions, "enrol_dbtype", $frm->enrol_dbtype, false);
?>
</td>
<td>
<?php print_string("dbtype","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_dbhost:</td>
<td>
<?php
if (!isset($frm->enrol_dbhost)) {
$frm->enrol_dbhost = '';
}
?>
<input size="15" type="text" name="enrol_dbhost" value="<?php p($frm->enrol_dbhost) ?>" />
</td>
<td>
<?php print_string("dbhost","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_dbuser:</td>
<td>
<input size="15" type="text" name="enrol_dbuser" value="<?php echo $frm->enrol_dbuser ?>" />
</td>
<td>
<?php print_string("dbuser","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_dbpass:</td>
<td>
<input size="15" type="password" name="enrol_dbpass" value="<?php echo $frm->enrol_dbpass ?>" />
</td>
<td>
<?php print_string("dbpass","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_dbname:</td>
<td>
<input size="15" type="text" name="enrol_dbname" value="<?php echo $frm->enrol_dbname ?>" />
</td>
<td>
<?php print_string("dbname","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_dbtable:</td>
<td>
<input size="15" type="text" name="enrol_dbtable" value="<?php echo $frm->enrol_dbtable ?>" />
</td>
<td>
<?php print_string("dbtable","enrol_database") ?>
</td>
</tr>
<tr>
<th colspan="2" scope="col">
<?php print_string("remote_fields_mapping", "enrol_database") ?>
</th>
</tr>
<tr>
<td align="right">enrol_localcoursefield:</td>
<td>
<input size="15" type="text" name="enrol_localcoursefield" value="<?php echo $frm->enrol_localcoursefield ?>" />
</td>
<td>
<?php print_string("localcoursefield","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_localuserfield:</td>
<td>
<input size="15" type="text" name="enrol_localuserfield" value="<?php echo $frm->enrol_localuserfield ?>" />
</td>
<td>
<?php print_string("localuserfield","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_db_localrolefield:</td>
<td>
<input size="15" type="text" name="enrol_db_localrolefield" value="<?php echo $frm->enrol_db_localrolefield ?>" />
</td>
<td>
<?php print_string("localrolefield","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_remotecoursefield:</td>
<td>
<input size="15" type="text" name="enrol_remotecoursefield" value="<?php echo $frm->enrol_remotecoursefield ?>" />
</td>
<td>
<?php print_string("remotecoursefield","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_remoteuserfield:</td>
<td>
<input size="15" type="text" name="enrol_remoteuserfield" value="<?php echo $frm->enrol_remoteuserfield ?>" />
</td>
<td>
<?php print_string("remoteuserfield","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_db_remoterolefield:</td>
<td>
<input size="15" type="text" name="enrol_db_remoterolefield" value="<?php echo $frm->enrol_db_remoterolefield ?>" />
</td>
<td>
<?php print_string("remoterolefield","enrol_database") ?>
</td>
</tr>
<tr>
<th colspan="2" scope="col">
<?php print_string('roles', 'role') ?>
</th>
</tr>
<tr>
<td align="right">enrol_db_defaultcourseroleid:</td>
<td>
<?php
$sitecontext = get_context_instance(CONTEXT_SYSTEM);
$assignableroles = get_assignable_roles($sitecontext);
$assignableroles = array('' => get_string('default')) + $assignableroles;
echo html_writer::select($assignableroles, 'enrol_db_defaultcourseroleid', $frm->enrol_db_defaultcourseroleid, false);
if (isset($err['enrol_db_defaultcourseroleid'])) echo $OUTPUT->error_text($err['enrol_db_defaultcourseroleid']);
?>
</td>
<td>
<?php print_string("defaultcourseroleid","enrol_database") ?>
</td>
</tr>
<tr>
<th colspan="2" scope="col">
<?php print_string("enrol_database_autocreation_settings", "enrol_database") ?>
</th>
</tr>
<tr>
<td align="right">enrol_db_autocreate:</td>
<td>
<?php
echo html_writer::select($yesno, "enrol_db_autocreate", $frm->enrol_db_autocreate, false);
if (isset($err["enrol_db_autocreate"])) echo $OUTPUT->error_text($err["enrol_db_autocreate"]);
?>
</td>
<td>
<?php print_string("autocreate","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_db_category:</td>
<td>
<?php
$displaylist = array();
$parentlist = array();
make_categories_list($displaylist, $parentlist);
echo html_writer::select($displaylist, "enrol_db_category", $frm->enrol_db_category, false);
?>
<?php if (isset($err["enrol_db_category"])) echo $OUTPUT->error_text($err["enrol_db_category"]); ?>
</td><td>
<?php print_string("category","enrol_database") ?>
</td>
</tr>
<tr>
<td align="right">enrol_db_template:</td>
<td>
<input name="enrol_db_template" type="text" size="30" value="<?php echo $frm->enrol_db_template?>" />
<?php if (isset($err["enrol_db_template"])) echo $OUTPUT->error_text($err["enrol_db_template"]); ?>
</td><td>
<?php print_string("template","enrol_database") ?>
</td>
</tr>
<tr>
<th colspan="2" scope="col">
<?php print_string("general_options", "enrol_database") ?>
</th>
</tr>
<tr>
<td align="right">enrol_db_ignorehiddencourse:</td>
<td>
<?php
echo html_writer::select($yesno, "enrol_db_ignorehiddencourse", $frm->enrol_db_ignorehiddencourse, false);
if (isset($err['enrol_db_ignorehiddencourse'])) {
echo $OUTPUT->error_text($err['enrol_db_ignorehiddencourse']);
}
?>
</td>
<td>
<?php print_string('ignorehiddencourse', 'enrol_database' ); ?>
</td>
</tr>
<tr>
<td align="right">enrol_db_disableunenrol:</td>
<td>
<?php
echo html_writer::select($yesno, "enrol_db_disableunenrol", $frm->enrol_db_disableunenrol, false);
if (isset($err['enrol_db_disableunenrol'])) {
echo $OUTPUT->error_text($err['enrol_db_disableunenrol']);
}
?>
</td>
<td>
<?php print_string('disableunenrol', 'enrol_database' ); ?>
</td>
</tr>
</table>

View File

@ -0,0 +1,45 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Capabilities for database enrolment plugin.
*
* @package enrol_database
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$capabilities = array(
'enrol/database:config' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'manager' => CAP_ALLOW,
)
),
'enrol/database:manage' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'manager' => CAP_ALLOW,
)
),
);

View File

@ -0,0 +1,107 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Database enrolment plugin installation.
*
* @package enrol_database
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
function xmldb_enrol_database_install() {
global $CFG, $DB;
// migrate old config settings first
if (isset($CFG->enrol_dbtype)) {
set_config('dbtype', $CFG->enrol_dbtype, 'enrol_database');
unset_config('enrol_dbtype');
}
if (isset($CFG->enrol_dbhost)) {
set_config('dbhost', $CFG->enrol_dbhost, 'enrol_database');
unset_config('enrol_dbhost');
}
if (isset($CFG->enrol_dbuser)) {
set_config('dbuser', $CFG->enrol_dbuser, 'enrol_database');
unset_config('enrol_dbuser');
}
if (isset($CFG->enrol_dbpass)) {
set_config('dbpass', $CFG->enrol_dbpass, 'enrol_database');
unset_config('enrol_dbpass');
}
if (isset($CFG->enrol_dbname)) {
set_config('dbname', $CFG->enrol_dbname, 'enrol_database');
unset_config('enrol_dbname');
}
if (isset($CFG->enrol_dbtable)) {
set_config('remoteenroltable', $CFG->enrol_dbtable, 'enrol_database');
unset_config('enrol_dbtable');
}
if (isset($CFG->enrol_localcoursefield)) {
set_config('localcoursefield', $CFG->enrol_localcoursefield, 'enrol_database');
unset_config('enrol_localcoursefield');
}
if (isset($CFG->enrol_localuserfield)) {
set_config('localuserfield', $CFG->enrol_localuserfield, 'enrol_database');
unset_config('enrol_localuserfield');
}
if (isset($CFG->enrol_localrolefield)) {
set_config('localrolefield', $CFG->enrol_localrolefield, 'enrol_database');
unset_config('enrol_localrolefield');
}
if (isset($CFG->enrol_remotecoursefield)) {
set_config('remotecoursefield', $CFG->enrol_remotecoursefield, 'enrol_database');
unset_config('enrol_remotecoursefield');
}
if (isset($CFG->enrol_remoteuserfield)) {
set_config('remoteuserfield', $CFG->enrol_remoteuserfield, 'enrol_database');
unset_config('enrol_remoteuserfield');
}
if (isset($CFG->enrol_remoterolefield)) {
set_config('remoterolefield', $CFG->enrol_remoterolefield, 'enrol_database');
unset_config('enrol_remoterolefield');
}
if (isset($CFG->enrol_db_defaultcourseroleid)) {
set_config('defaultrole', $CFG->enrol_db_defaultcourseroleid, 'enrol_database');
unset_config('enrol_db_defaultcourseroleid');
}
unset_config('enrol_db_autocreate'); // replaced by new coruse temple sync
if (isset($CFG->enrol_db_category)) {
set_config('defaultcategory', $CFG->enrol_db_category, 'enrol_database');
unset_config('enrol_db_category');
}
if (isset($CFG->enrol_db_template)) {
set_config('templatecourse', $CFG->enrol_db_template, 'enrol_database');
unset_config('enrol_db_template');
}
if (isset($CFG->enrol_db_ignorehiddencourse)) {
set_config('ignorehiddencourses', $CFG->enrol_db_ignorehiddencourse, 'enrol_database');
unset_config('enrol_db_ignorehiddencourse');
}
// just make sure there are no leftovers after disabled plugin
if (!$DB->record_exists('enrol', array('enrol'=>'database'))) {
role_unassign_all(array('component'=>'enrol_database'));
return;
}
}

View File

@ -1,681 +0,0 @@
<?php
require_once($CFG->libdir.'/adodb/adodb.inc.php');
require_once($CFG->dirroot.'/enrol/enrol.class.php');
class enrolment_plugin_database {
var $log;
/**
* For the given user, let's go out and look in an external database
* for an authoritative list of enrolments, and then adjust the
* local Moodle assignments to match.
*/
function setup_enrolments(&$user) {
global $CFG, $DB;
// NOTE: if $this->enrol_connect() succeeds you MUST remember to call
// $this->enrol_disconnect() as it is doing some nasty vodoo with table prefix
$enroldb = $this->enrol_connect();
if (!$enroldb) {
error_log('[ENROL_DB] Could not make a connection');
return;
}
// If we are expecting to get role information from our remote db, then
// we execute the below code for every role type. Otherwise we just
// execute it once with null (hence the dummy array).
$roles = !empty($CFG->enrol_db_remoterolefield) && !empty($CFG->enrol_db_localrolefield)
? get_all_roles()
: array(null);
//error_log('[ENROL_DB] found ' . count($roles) . ' roles:');
foreach($roles as $role) {
//error_log('[ENROL_DB] setting up enrolments for '.$role->shortname);
/// Get the authoritative list of enrolments from the external database table
/// We're using the ADOdb functions natively here and not our datalib functions
/// because we didn't want to mess with the $ db global
$useridfield = $enroldb->quote($user->{$CFG->enrol_localuserfield});
list($have_role, $remote_role_name, $remote_role_value) = $this->role_fields($enroldb, $role);
/// Check if a particular role has been forced by the plugin site-wide
/// (if we aren't doing a role-based select)
if (!$have_role && $CFG->enrol_db_defaultcourseroleid) {
$role = $DB->get_record('role', array('id'=>$CFG->enrol_db_defaultcourseroleid));
}
/// Whether to fetch the default role on a per-course basis (below) or not.
$use_default_role = !$role;
/*
if ($have_role) {
error_log('[ENROL_DB] Doing role-specific select from db for role: '.$role->shortname);
} elseif ($use_default_role) {
error_log('[ENROL_DB] Using course default for roles - assuming that database lists defaults');
} else {
error_log('[ENROL_DB] Using config default for roles: '.$role->shortname);
}*/
if ($rs = $enroldb->Execute("SELECT {$CFG->enrol_remotecoursefield} as enrolremotecoursefield
FROM {$CFG->enrol_dbtable}
WHERE {$CFG->enrol_remoteuserfield} = " . $useridfield .
(isset($remote_role_name, $remote_role_value) ? ' AND '.$remote_role_name.' = '.$remote_role_value : ''))) {
// We'll use this to see what to add and remove
$existing = $role
? $DB->get_records_sql("SELECT *
FROM {role_assignments}
WHERE userid = ? AND roleid = ?",
array($user->id, $role->id))
: $DB->get_records('role_assignments', array('userid'=>$user->id));
if (!$existing) {
$existing = array();
}
if (!$rs->EOF) { // We found some courses
//$count = 0;
$courselist = array();
while ($fields = $rs->FetchRow()) { // Make a nice little array of courses to process
$fields = array_change_key_case($fields, CASE_LOWER);
$courselist[] = $fields['enrolremotecoursefield'];
//$count++;
}
$rs->close();
//error_log('[ENROL_DB] Found '.count($existing).' existing roles and '.$count.' in external database');
foreach ($courselist as $coursefield) { /// Check the list of courses against existing
$course = $DB->get_record('course', array($CFG->enrol_localcoursefield=>$coursefield));
if (!is_object($course)) {
if (empty($CFG->enrol_db_autocreate)) { // autocreation not allowed
if (debugging('',DEBUG_ALL)) {
error_log( "Course $coursefield does not exist, skipping") ;
}
continue; // next foreach course
}
// ok, now then let's create it!
// prepare any course properties we actually have
$course = new StdClass;
$course->{$CFG->enrol_localcoursefield} = $coursefield;
$course->fullname = $coursefield;
$course->shortname = $coursefield;
if (!($newcourseid = $this->create_course($course, true)
and $course = $DB->get_record( 'course', array('id'=>$newcourseid)))) {
error_log( "Creating course $coursefield failed");
continue; // nothing left to do...
}
}
// if the course is hidden and we don't want to enrol in hidden courses
// then just skip it
if (!$course->visible and $CFG->enrol_db_ignorehiddencourse) {
continue;
}
/// If there's no role specified, we get the default course role (usually student)
if ($use_default_role) {
$role = get_default_course_role($course);
}
$context = get_context_instance(CONTEXT_COURSE, $course->id);
// Couldn't get a role or context, skip.
if (!$role || !$context) {
continue;
}
// Search the role assignments to see if this user
// already has this role in this context. If it is, we
// skip to the next course.
foreach($existing as $key => $role_assignment) {
if ($role_assignment->roleid == $role->id
&& $role_assignment->contextid == $context->id) {
unset($existing[$key]);
//error_log('[ENROL_DB] User is already enroled in course '.$course->idnumber);
continue 2;
}
}
//error_log('[ENROL_DB] Enrolling user in course '.$course->idnumber);
role_assign($role->id, $user->id, 0, $context->id, 0, 0, 0, 'database');
}
} // We've processed all external courses found
/// We have some courses left that we might need to unenrol from
/// Note: we only process enrolments that we (ie 'database' plugin) made
/// Do not unenrol anybody if the disableunenrol option is 'yes'
if (!$CFG->enrol_db_disableunenrol) {
foreach ($existing as $role_assignment) {
if ($role_assignment->enrol == 'database') {
//error_log('[ENROL_DB] Removing user from context '.$role_assignment->contextid);
role_unassign($role_assignment->roleid, $user->id, '', $role_assignment->contextid);
}
}
}
} else {
error_log('[ENROL_DB] Couldn\'t get rows from external db: '.$enroldb->ErrorMsg());
}
}
$this->enrol_disconnect($enroldb);
}
/**
* sync enrolments with database, create courses if required.
*
* @param object The role to sync for. If no role is specified, defaults are
* used.
*/
function sync_enrolments($role = null) {
global $CFG, $DB, $OUTPUT;
error_reporting(E_ALL);
// Connect to the external database
$enroldb = $this->enrol_connect();
if (!$enroldb) {
echo $OUTPUT->notification("enrol/database cannot connect to server");
return false;
}
if (isset($role)) {
echo '=== Syncing enrolments for role: '.$role->shortname." ===\n";
} else {
echo "=== Syncing enrolments for default role ===\n";
}
// first, pack the sortorder...
fix_course_sortorder();
list($have_role, $remote_role_name, $remote_role_value) = $this->role_fields($enroldb, $role);
if (!$have_role) {
if (!empty($CFG->enrol_db_defaultcourseroleid)
and $role = $DB->get_record('role', array('id'=>$CFG->enrol_db_defaultcourseroleid))) {
echo "=== Using enrol_db_defaultcourseroleid: {$role->id} ({$role->shortname}) ===\n";
} elseif (isset($role)) {
echo "!!! WARNING: Role specified by caller, but no (or invalid) role configuration !!!\n";
}
}
// get enrolments per-course
$sql = "SELECT DISTINCT {$CFG->enrol_remotecoursefield} " .
" FROM {$CFG->enrol_dbtable} " .
" WHERE {$CFG->enrol_remoteuserfield} IS NOT NULL" .
(isset($remote_role_name, $remote_role_value) ? ' AND '.$remote_role_name.' = '.$remote_role_value : '');
$rs = $enroldb->Execute($sql);
if (!$rs) {
trigger_error($enroldb->ErrorMsg() .' STATEMENT: '. $sql);
return false;
}
if ( $rs->EOF ) { // no courses! outta here...
return true;
}
$transaction = $DB->start_delegated_transaction();
$extcourses = array();
while ($rsextcourse = $rs->FetchRow()) { // there are more course records
$rsextcourse = array_change_key_case($rsextcourse, CASE_LOWER);
$extcourse = $rsextcourse[strtolower($CFG->enrol_remotecoursefield)];
array_push($extcourses, $extcourse);
// does the course exist in moodle already?
$course = false;
$course = $DB->get_record('course', array($CFG->enrol_localcoursefield=>$extcourse));
if (!is_object($course)) {
if (empty($CFG->enrol_db_autocreate)) { // autocreation not allowed
if (debugging('', DEBUG_ALL)) {
error_log( "Course $extcourse does not exist, skipping");
}
continue; // next foreach course
}
// ok, now then let's create it!
// prepare any course properties we actually have
$course = new StdClass;
$course->{$CFG->enrol_localcoursefield} = $extcourse;
$course->fullname = $extcourse;
$course->shortname = $extcourse;
if (!($newcourseid = $this->create_course($course, true)
and $course = $DB->get_record('course', array('id'=>$newcourseid)))) {
error_log( "Creating course $extcourse failed");
continue; // nothing left to do...
}
}
$context = get_context_instance(CONTEXT_COURSE, $course->id);
// If we don't have a proper role setup, then we default to the default
// role for the current course.
if (!$have_role) {
$role = get_default_course_role($course);
}
// get a list of the student ids the are enrolled
// in the external db -- hopefully it'll fit in memory...
$extenrolments = array();
$sql = "SELECT {$CFG->enrol_remoteuserfield} " .
" FROM {$CFG->enrol_dbtable} " .
" WHERE {$CFG->enrol_remotecoursefield} = " . $enroldb->quote($extcourse) .
($have_role ? ' AND '.$remote_role_name.' = '.$remote_role_value : '');
$crs = $enroldb->Execute($sql);
if (!$crs) {
trigger_error($enroldb->ErrorMsg() .' STATEMENT: '. $sql);
return false;
}
if ( $crs->EOF ) { // shouldn't happen, but cover all bases
continue;
}
// slurp results into an array
while ($rscrs = $crs->FetchRow()) {
$rscrs = array_change_key_case($rscrs, CASE_LOWER);
array_push($extenrolments, $rscrs[strtolower($CFG->enrol_remoteuserfield)]);
}
$crs->close(); // release the handle
//
// prune enrolments to users that are no longer in ext auth
// hopefully they'll fit in the max buffer size for the RDBMS
//
// TODO: This doesn't work perfectly. If we are operating without
// roles in the external DB, then this doesn't handle changes of role
// within a course (because the user is still enrolled in the course,
// so NOT IN misses the course).
//
// When the user logs in though, their role list will be updated
// correctly.
//
if (!$CFG->enrol_db_disableunenrol) {
if ($extenrolments) {
list($extlist, $params) = $DB->get_in_or_equal($extenrolments, SQL_PARAMS_NAMED, 'e0', false);
$extsql = "AND u.{$CFG->enrol_localuserfield} $extlist";
} else {
$extsql = "";
$params = array();
}
$params['roleid'] = $role->id;
$params['contextid'] = $context->id;
$to_prune = $DB->get_records_sql("
SELECT ra.*
FROM {role_assignments} ra
JOIN {user} u ON ra.userid = u.id
WHERE ra.enrol = 'database'
AND ra.contextid = :contextid
AND ra.roleid = :roleid", $params);
if ($to_prune) {
foreach ($to_prune as $role_assignment) {
if (role_unassign($role->id, $role_assignment->userid, 0, $role_assignment->contextid)){
error_log( "Unassigned {$role->shortname} assignment #{$role_assignment->id} for course {$course->id} (" . format_string($course->shortname) . "); user {$role_assignment->userid}");
} else {
error_log( "Failed to unassign {$role->shortname} assignment #{$role_assignment->id} for course {$course->id} (" . format_string($course->shortname) . "); user {$role_assignment->userid}");
}
}
}
}
//
// insert current enrolments
// bad we can't do INSERT IGNORE with postgres...
//
foreach ($extenrolments as $member) {
// Get the user id and whether is enrolled in one fell swoop
$sql = "
SELECT u.id, ra.id AS enrolmentid
FROM {user} u
LEFT JOIN {role_assignments} ra ON u.id = ra.userid
AND ra.roleid = ?
AND ra.contextid = ?
WHERE u.{$CFG->enrol_localuserfield} = ?
AND (u.deleted IS NULL OR u.deleted=0)";
$eusers = $DB->get_records($sql, array($role->id, $context->id, $member));
if ($eusers === false) {
trigger_error('error STATEMENT: '. $sql);
return false;
}
if (!$eusers) { // if this returns empty, it means we don't have the student record.
// should not happen -- but skip it anyway
trigger_error('weird! no user record entry?');
continue;
}
$userid = $user_obj->id;
$enrolmentid = $user_obj->enrolmentid;
if ($enrolmentid) { // already enrolled - skip
continue;
}
if (role_assign($role->id, $userid, 0, $context->id, 0, 0, 0, 'database')){
error_log( "Assigned role {$role->shortname} to user {$userid} in course {$course->id} (" . format_string($course->shortname) . ")");
} else {
error_log( "Failed to assign role {$role->shortname} to user {$userid} in course {$course->id} (" . format_string($course->shortname) . ")");
}
} // end foreach member
} // end while course records
$rs->close(); //Close the main course recordset
//
// prune enrolments to courses that are no longer in ext auth
//
// TODO: This doesn't work perfectly. If we are operating without
// roles in the external DB, then this doesn't handle changes of role
// within a course (because the user is still enrolled in the course,
// so NOT IN misses the course).
//
// When the user logs in though, their role list will be updated
// correctly.
//
if (!$CFG->enrol_db_disableunenrol) {
if ($extcourses) {
list($extlist, $params) = $DB->get_in_or_equal($extcourses, SQL_PARAMS_QM, 'e0', false);
$extsql = "AND u.{$CFG->enrol_localcoursefield} $extlist";
} else {
$extsql = "";
$params = array();
}
$params['roleid'] = $role->id;
$params['contextid'] = $context->id;
$sql = "
SELECT ra.roleid, ra.userid, ra.contextid
FROM {role_assignments} ra
JOIN {context} cn ON cn.id = ra.contextid
JOIN {course} c ON c.id = cn.instanceid
WHERE ra.enrol = 'database'
AND cn.contextlevel = ".CONTEXT_COURSE." " .
($have_role ? " AND ra.roleid = :roleid " : '') ."
$extsql";
if (!$ers = $DB->get_recordset_sql($sql, $params)) {
trigger_error('error STATEMENT: '. $sql);
return false;
}
foreach ($ers as $user_obj) {
$roleid = $user_obj->roleid;
$user = $user_obj->userid;
$contextid = $user_obj->contextid;
if (role_unassign($roleid, $user, 0, $contextid)){
error_log( "Unassigned role {$roleid} from user $user in context $contextid");
} else {
error_log( "Failed unassign role {$roleid} from user $user in context $contextid");
}
}
$ers->close(); // release the handle
}
$transaction->allow_commit();
// we are done now, a bit of housekeeping
fix_course_sortorder();
$this->enrol_disconnect($enroldb);
return true;
}
/// Overide the get_access_icons() function
function get_access_icons($course) {
}
/// Overide the base config_form() function
function config_form($frm) {
global $CFG, $OUTPUT;
$vars = array('enrol_dbhost', 'enrol_dbuser', 'enrol_dbpass',
'enrol_dbname', 'enrol_dbtable',
'enrol_localcoursefield', 'enrol_localuserfield',
'enrol_remotecoursefield', 'enrol_remoteuserfield',
'enrol_db_autocreate', 'enrol_db_category', 'enrol_db_template',
'enrol_db_localrolefield', 'enrol_db_remoterolefield',
'enrol_remotecoursefield', 'enrol_remoteuserfield',
'enrol_db_ignorehiddencourse', 'enrol_db_defaultcourseroleid',
'enrol_db_disableunenrol');
foreach ($vars as $var) {
if (!isset($frm->$var)) {
$frm->$var = '';
}
}
include("$CFG->dirroot/enrol/database/config.html");
}
/// Override the base process_config() function
function process_config($config) {
if (!isset($config->enrol_dbtype)) {
$config->enrol_dbtype = 'mysql';
}
set_config('enrol_dbtype', $config->enrol_dbtype);
if (!isset($config->enrol_dbhost)) {
$config->enrol_dbhost = '';
}
set_config('enrol_dbhost', $config->enrol_dbhost);
if (!isset($config->enrol_dbuser)) {
$config->enrol_dbuser = '';
}
set_config('enrol_dbuser', $config->enrol_dbuser);
if (!isset($config->enrol_dbpass)) {
$config->enrol_dbpass = '';
}
set_config('enrol_dbpass', $config->enrol_dbpass);
if (!isset($config->enrol_dbname)) {
$config->enrol_dbname = '';
}
set_config('enrol_dbname', $config->enrol_dbname);
if (!isset($config->enrol_dbtable)) {
$config->enrol_dbtable = '';
}
set_config('enrol_dbtable', $config->enrol_dbtable);
if (!isset($config->enrol_localcoursefield)) {
$config->enrol_localcoursefield = '';
}
set_config('enrol_localcoursefield', $config->enrol_localcoursefield);
if (!isset($config->enrol_localuserfield)) {
$config->enrol_localuserfield = '';
}
set_config('enrol_localuserfield', $config->enrol_localuserfield);
if (!isset($config->enrol_remotecoursefield)) {
$config->enrol_remotecoursefield = '';
}
set_config('enrol_remotecoursefield', $config->enrol_remotecoursefield);
if (!isset($config->enrol_remoteuserfield)) {
$config->enrol_remoteuserfield = '';
}
set_config('enrol_remoteuserfield', $config->enrol_remoteuserfield);
if (!isset($config->enrol_db_autocreate)) {
$config->enrol_db_autocreate = '';
}
set_config('enrol_db_autocreate', $config->enrol_db_autocreate);
if (!isset($config->enrol_db_category)) {
$config->enrol_db_category = '';
}
set_config('enrol_db_category', $config->enrol_db_category);
if (!isset($config->enrol_db_template)) {
$config->enrol_db_template = '';
}
set_config('enrol_db_template', $config->enrol_db_template);
if (!isset($config->enrol_db_defaultcourseroleid)) {
$config->enrol_db_defaultcourseroleid = '';
}
set_config('enrol_db_defaultcourseroleid', $config->enrol_db_defaultcourseroleid);
if (!isset($config->enrol_db_localrolefield)) {
$config->enrol_db_localrolefield = '';
}
set_config('enrol_db_localrolefield', $config->enrol_db_localrolefield);
if (!isset($config->enrol_db_remoterolefield)) {
$config->enrol_db_remoterolefield = '';
}
set_config('enrol_db_remoterolefield', $config->enrol_db_remoterolefield);
if (!isset($config->enrol_db_ignorehiddencourse)) {
$config->enrol_db_ignorehiddencourse = '';
}
set_config('enrol_db_ignorehiddencourse', $config->enrol_db_ignorehiddencourse );
if (!isset($config->enrol_db_disableunenrol)) {
$config->enrol_db_disableunenrol = '';
}
set_config('enrol_db_disableunenrol', $config->enrol_db_disableunenrol );
return true;
}
// will create the moodle course from the template
// course_ext is an array as obtained from ldap -- flattened somewhat
// NOTE: if you pass true for $skip_fix_course_sortorder
// you will want to call fix_course_sortorder() after your are done
// with course creation
function create_course ($course,$skip_fix_course_sortorder=0){
global $CFG, $DB, $OUTPUT;
// define a template
if (!empty($CFG->enrol_db_template)){
$template = $DB->get_record("course", array('shortname'=>$CFG->enrol_db_template));
$template = (array)$template;
} else {
$site = get_site();
$template = array(
'startdate' => time() + 3600 * 24,
'summary' => get_string("defaultcoursesummary"),
'format' => "weeks",
'password' => "",
'guest' => 0,
'numsections' => 10,
'idnumber' => '',
'cost' => '',
'newsitems' => 5,
'showgrades' => 1,
'groupmode' => 0,
'groupmodeforce' => 0,
);
}
// overlay template
foreach (array_keys($template) AS $key) {
if (empty($course->$key)) {
$course->$key = $template[$key];
}
}
$category = get_course_category($CFG->enrol_db_category);
// put at the end of category
$course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - 1;
// override with local data
$course->startdate = time() + 3600 * 24;
$course->timecreated = time();
$course->visible = 1;
// clear out id just in case
unset($course->id);
// truncate a few key fields
$course->idnumber = substr($course->idnumber, 0, 100);
$course->shortname = substr($course->shortname, 0, 100);
// store it and log
if ($newcourseid = $DB->insert_record("course", $course)) { // Set up new course
$section = new object();
$section->course = $newcourseid; // Create a default section.
$section->section = 0;
$section->summaryformat = FORMAT_HTML;
$section->id = $DB->insert_record("course_sections", $section);
$course = $DB->get_record('course', array('id' => $newcourseid));
blocks_add_default_course_blocks($course);
if (!$skip_fix_course_sortorder){
fix_course_sortorder();
}
add_to_log($newcourseid, "course", "new", "view.php?id=$newcourseid", "enrol/database auto-creation");
} else {
trigger_error("Could not create new course $extcourse from from database");
echo $OUTPUT->notification("Serious Error! Could not create the new course!");
return false;
}
return $newcourseid;
}
/// DB Connect
/// NOTE: You MUST remember to disconnect
/// when you stop using it -- as this call will
/// sometimes modify table prefix for the whole of Moodle!
function enrol_connect() {
global $CFG;
// Try to connect to the external database (forcing new connection)
$enroldb = &ADONewConnection($CFG->enrol_dbtype);
if ($enroldb->Connect($CFG->enrol_dbhost, $CFG->enrol_dbuser, $CFG->enrol_dbpass, $CFG->enrol_dbname, true)) {
$enroldb->SetFetchMode(ADODB_FETCH_ASSOC); ///Set Assoc mode always after DB connection
return $enroldb;
} else {
trigger_error("Error connecting to enrolment DB backend with: "
. "$CFG->enrol_dbhost,$CFG->enrol_dbuser,$CFG->enrol_dbpass,$CFG->enrol_dbname");
return false;
}
}
/// DB Disconnect
function enrol_disconnect($enroldb) {
global $CFG;
$enroldb->Close();
}
/**
* This function returns the name and value of the role field to query the db
* for, or null if there isn't one.
*
* @param object The ADOdb connection
* @param object The role
* @return array (boolean, string, db quoted string)
*/
function role_fields($enroldb, $role) {
global $CFG;
if ($have_role = !empty($role)
&& !empty($CFG->enrol_db_remoterolefield)
&& !empty($CFG->enrol_db_localrolefield)
&& !empty($role->{$CFG->enrol_db_localrolefield})) {
$remote_role_name = $CFG->enrol_db_remoterolefield;
$remote_role_value = $enroldb->quote($role->{$CFG->enrol_db_localrolefield});
} else {
$remote_role_name = $remote_role_value = null;
}
return array($have_role, $remote_role_name, $remote_role_value);
}
} // end of class

View File

@ -1,41 +0,0 @@
<?php
if(!empty($_SERVER['GATEWAY_INTERFACE'])){
error_log("should not be called from apache!");
exit;
}
error_reporting(E_ALL);
require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); // global moodle config file.
require_once($CFG->dirroot . '/course/lib.php');
require_once($CFG->dirroot . '/enrol/database/enrol.php');
// ensure errors are well explained
$CFG->debug=E_ALL;
if (!is_enabled_enrol('database')) {
error_log("Database enrol plugin not enabled!");
die;
}
// update enrolments -- these handlers should autocreate courses if required
$enrol = new enrolment_plugin_database();
// If we have settings to handle roles individually, through each type of
// role and update it. Otherwise, just got through once (with no role
// specified).
$roles = !empty($CFG->enrol_db_remoterolefield) && !empty($CFG->enrol_db_localrolefield)
? get_all_roles()
: array(null);
foreach ($roles as $role) {
$enrol->sync_enrolments($role);
}
// sync metacourses
if (function_exists('sync_metacourses')) {
sync_metacourses();
}

View File

@ -23,46 +23,55 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['autocreate'] = 'Courses can be created automatically if there are enrolments to a course that doesn\'t yet exist in Moodle.';
$string['autocreation_settings'] = 'Autocreation Settings';
$string['category'] = 'The category for auto-created courses.';
$string['course_fullname'] = 'The name of the field where the course fullname is stored.';
$string['course_id'] = 'The name of the field where the course ID is stored. The values of this field are used to match those in the "enrol_db_l_coursefield" field in Moodle\'s course table.';
$string['course_shortname'] = 'The name of the field where the course shortname is stored.';
$string['course_table'] = 'Then name of the table where we expect to find the course details in (short name, fullname, ID, etc.)';
$string['dbhost'] = 'Server IP name or number';
$string['database:config'] = 'Configure external database enrol instances';
$string['database:manage'] = 'Manage external database enrol instances';
$string['dbencoding'] = 'Database encoding';
$string['dbhost'] = 'Database host';
$string['dbhost_desc'] = 'Type database server IP address or host name';
$string['dbname'] = 'Database name';
$string['dbpass'] = 'Server password';
$string['dbtable'] = 'Database table';
$string['dbtype'] = 'Database type';
$string['dbuser'] = 'Server user';
$string['defaultcourseroleid'] = 'The role that will be assigned by default if no other role is specified.';
$string['description'] = 'You can use a external database (of nearly any kind) to control your enrolments. It is assumed your external database contains a field containing a course ID, and a field containing a user ID. These are compared against fields that you choose in the local course and user tables.';
$string['disableunenrol'] = 'If set to yes users previously enrolled by the external database plugin will not be unenrolled by the same plugin regardless of the database contents.';
$string['enrol_database_autocreation_settings'] = 'Auto-creation of new courses';
$string['enrolname'] = 'External Database';
$string['general_options'] = 'General Options';
$string['host'] = 'Database server hostname.';
$string['ignorehiddencourse'] = 'If set to yes users will not be enroled on courses that are set to be unavailable to students.';
$string['localcoursefield'] = 'The name of the field in the course table that we are using to match entries in the remote database (eg idnumber).';
$string['local_fields_mapping'] = 'Moodle (local) database fields';
$string['localrolefield'] = 'The name of the field in the roles table that we are using to match entries in the remote database (eg shortname).';
$string['localuserfield'] = 'The name of the field in the user table that we are using to match entries in the remote database (eg idnumber).';
$string['name'] = 'The specific database to use.';
$string['pass'] = 'Password to access the server.';
$string['remotecoursefield'] = 'The name of the field in the remote table that we are using to match entries in the course table.';
$string['remote_fields_mapping'] = 'Enrolment (remote) database fields.';
$string['remoterolefield'] = 'The name of the field in the remote table that we are using to match entries in the roles table.';
$string['remoteuserfield'] = 'The name of the field in the remote table that we are using to match entries in the user table.';
$string['server_settings'] = 'External Database Server Settings';
$string['student_coursefield'] = 'The name of the field in the student enrolment table that we expect to find the course ID in.';
$string['student_l_userfield'] = 'The name of the field in the local user table that we use to match the user to a remote record for students (eg idnumber).';
$string['student_r_userfield'] = 'The name of the field in the remote student enrolment table that we expect to find the user ID in.';
$string['student_table'] = 'The name of the table where student enrolments are stored.';
$string['teacher_coursefield'] = 'The name of the field in the teacher enrolment table that we expect to find the course ID in.';
$string['teacher_l_userfield'] = 'The name of the field in the local user table that we use to match the user to a remote record for teachers (eg idnumber).';
$string['teacher_r_userfield'] = 'The name of the field in the remote teacher enrolment table that we expect to find the user ID in.';
$string['teacher_table'] = 'The name of the table where teacher enrolments are stored.';
$string['template'] = 'Optional: auto-created courses can copy their settings from a template course. Type here the shortname of the template course.';
$string['type'] = 'Database server type.';
$string['user'] = 'Username to access the server.';
$string['dbpass'] = 'Database password';
$string['dbsetupsql'] = 'Database setup command';
$string['dbsetupsql_desc'] = 'SQL command for special database setup, often used to setup communication encoding - example for MySQL and PostgreSQL: <em>SET NAMES \'utf8\'</em>';
$string['dbsybasequoting'] = 'Use sybase quotes';
$string['dbsybasequoting_desc'] = 'Sybase style single quote escaping - needed for Oracle, MS SQL and some other databases. Do not use for MySQL!';
$string['dbtype'] = 'Database driver';
$string['dbtype_desc'] = 'ADOdb database driver name, type of the external database engine.';
$string['dbuser'] = 'Database user';
$string['debugdb'] = 'Debug ADOdb';
$string['debugdb_desc'] = 'Debug ADOdb connection to external database - use when getting empty page during login. Not suitable for production sites!';
$string['defaultcategory'] = 'Default new course category';
$string['defaultcategory_desc'] = 'The default category for auto-created courses. Used when no new category id specified or not found.';
$string['defaultrole'] = 'Default role';
$string['defaultrole_desc'] = 'The role that will be assigned by default if no other role is specified in external table.';
$string['ignorehiddencourses'] = 'Ignore hidden courses';
$string['ignorehiddencourses_desc'] = 'If enabled users will not be enrolled on courses that are set to be unavailable to students.';
$string['localcoursefield'] = 'Local course field';
$string['localrolefield'] = 'Local role field';
$string['localuserfield'] = 'Local user field';
$string['newcoursetable'] = 'Remote new courses table';
$string['newcoursetable_desc'] = 'Specify of the name of the table that contains list of courses that should be created automatically. Empty means no courses are created.';
$string['newcoursecategory'] = 'New course category id field';
$string['newcoursefullname'] = 'New course full name field';
$string['newcourseidnumber'] = 'New course ID number field';
$string['newcourseshortname'] = 'New course short name field';
$string['pluginname'] = 'External database';
$string['pluginname_desc'] = 'You can use an external database (of nearly any kind) to control your enrolments. It is assumed your external database contains at least a field containing a course ID, and a field containing a user ID. These are compared against fields that you choose in the local course and user tables.';
$string['remotecoursefield'] = 'Remote course field';
$string['remotecoursefield_desc'] = 'The name of the field in the remote table that we are using to match entries in the course table.';
$string['remoteenroltable'] = 'Remote user enrolment table';
$string['remoteenroltable_desc'] = 'Specify the name of the table that contains list of user enrolments. Empty means no user enrolment sync.';
$string['remoterolefield'] = 'Remote role field';
$string['remoterolefield_desc'] = 'The name of the field in the remote table that we are using to match entries in the roles table.';
$string['remoteuserfield'] = 'Remote user field';
$string['settingsheaderdb'] = 'External database connection';
$string['settingsheaderlocal'] = 'Local field mapping';
$string['settingsheaderremote'] = 'Remote enrolment sync';
$string['settingsheadernewcourses'] = 'Creation of new courses';
$string['remoteuserfield_desc'] = 'The name of the field in the remote table that we are using to match entries in the user table.';
$string['templatecourse'] = 'New course template';
$string['templatecourse_desc'] = 'Optional: auto-created courses can copy their settings from a template course. Type here the shortname of the template course.';
$string['unenrolaction'] = 'External unenrol action';
$string['unenrolaction_desc'] = 'Select action to carry our when user enrolment disappears from external enrolment table. Please note that some user data and settings are purged from course during course unenrolment.';
$string['unenrolactiondisable'] = 'Disable course enrolment';
$string['unenrolactionkeep'] = 'Keep user enrolled';
$string['unenrolactionunenrol'] = 'Unenrol user from course';

487
enrol/database/lib.php Normal file
View File

@ -0,0 +1,487 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Database enrolment plugin.
*
* This plugin synchronises enrolment and roles with external database table.
*
* @package enrol_database
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Database enrolment plugin implementation.
* @author Petr Skoda - based on code by Martin Dougiamas, Martin Langhoff and others
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class enrol_database_plugin extends enrol_plugin {
/**
* Is it possible to delete enrol instance via standard UI?
*
* @param object $instance
* @return bool
*/
public function instance_deleteable($instance) {
if (!enrol_is_enabled('database')) {
return true;
}
if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) {
return true;
}
//TODO: connect to external system and make sure no users are to be enrolled in this course
return false;
}
/**
* Forces synchronisation of user enrolments with external database.
*
* @param object $user user record
* @return void
*/
public function sync_user_enrolments($user = NULL) {
//TODO: full sync with external system is very expensive, it could cause big perf problems if we did that during each log-in,
// so do the sync only once in a while or rely on cron
}
/**
* Forces synchronisation of all enrolments with external database.
*
* @return void
*/
public function sync_enrolments() {
global $CFG, $DB;
// we do not create courses here intentionally because it requires full sync and is slow
if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) {
return;
}
// we may need a lot of memory here
@set_time_limit(0);
@raise_memory_limit("512M");
$extdb = $this->db_init();
// second step is to sync instances and users
$table = $this->get_config('remoteenroltable');
$coursefield = strtolower($this->get_config('remotecoursefield'));
$userfield = strtolower($this->get_config('remoteuserfield'));
$rolefield = strtolower($this->get_config('remoterolefield'));
$localrolefield = $this->get_config('localrolefield');
$localuserfield = $this->get_config('localuserfield');
$unenrolaction = $this->get_config('unenrolaction');
// create roles mapping
$allroles = get_all_roles();
$defaultrole = $this->get_config('defaultrole');
if (!isset($allroles[$defaultrole])) {
$defaultrole = 0;
}
$roles = array();
foreach ($allroles as $role) {
$roles[$role->$localrolefield] = $role->id;
}
// first find all existing courses with enrol instance
$localcoursefiled = $this->get_config('localcoursefield');
$sql = "SELECT c.id, c.visible, c.$localcoursefiled AS mapping, e.id AS enrolid
FROM {course} c
JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database')";
$existing = array();
$rs = $DB->get_recordset_sql($sql); // watch out for idnumber duplicates
foreach ($rs as $course) {
if (empty($course->mapping)) {
continue;
}
$existing[$course->mapping] = $course;
}
$rs->close();
// add necessary enrol instances that are not present yet;
$sql = $this->db_get_sql($table, array(), array($coursefield), true);
if ($rs = $extdb->Execute($sql)) {
if (!$rs->EOF) {
$sql = "SELECT c.id, c.visible
FROM {course} c
JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database')
WHERE c.$localcoursefiled = :mapping";
$params = array();
while ($mapping = $rs->FetchRow()) {
$mapping = reset($mapping);
$mapping = $this->db_decode($mapping);
if (!empty($mapping) and !isset($existing[$mapping])) {
$params['mapping'] = $mapping;
if ($course = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE)) {
$new = new object();
$new->id = $course->id;
$new->visible = $course->visible;
$new->mapping = $mapping;
$new->enrolid = $this->add_instance($course);
$existing[$mapping] = $new;
}
}
}
}
$rs->Close();
} else {
debugging('Error while communicating with external enrolment database');
$extdb->Close();
return;
}
// sync enrolments
$ignorehidden = $this->get_config('ignorehiddencourses');
$fields = array($userfield);
if ($rolefield) {
$fields[] = $rolefield;
}
foreach ($existing as $course) {
if ($ignorehidden and !$course->visible) {
continue;
}
if (!$instance = $DB->get_record('enrol', array('id'=>$course->enrolid))) {
continue; //weird
}
$context = get_context_instance(CONTEXT_COURSE, $course->id);
// get current list of enrolled users with their roles
$current_roles = array();
$current_status = array();
$user_mapping = array();
$sql = "SELECT u.$localuserfield AS mapping, u.id, ue.status, ue.userid, ra.roleid
FROM {user} u
JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.itemid = ue.enrolid AND ra.component = 'enrol_database')
WHERE u.deleted = 0";
$params = array('enrolid'=>$instance->id);
if ($localuserfield === 'username') {
$sql .= " AND u.mnethostid = :mnethostid";
$params['mnethostid'] = $CFG->mnet_localhost_id;
}
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $ue) {
$current_roles[$ue->userid][$ue->roleid] = $ue->roleid;
$current_status[$ue->userid] = $ue->status;
$user_mapping[$ue->mapping] = $ue->userid;
}
$rs->close();
// get list of users that need to be enrolled and their roles
$requested_roles = array();
$sql = $this->db_get_sql($table, array($coursefield=>$course->mapping), $fields);
if ($rs = $extdb->Execute($sql)) {
if (!$rs->EOF) {
if ($localuserfield === 'username') {
$usersearch = array('mnethostid'=>$CFG->mnet_localhost_id, 'deleted' =>0);
}
while ($fields = $rs->FetchRow()) {
$fields = array_change_key_case($fields, CASE_LOWER);
if (empty($fields[$userfield])) {
//user identification is mandatory!
}
$mapping = $fields[$userfield];
if (!isset($user_mapping[$mapping])) {
$usersearch[$localuserfield] = $mapping;
if (!$user = $DB->get_record('user', $usersearch, 'id', IGNORE_MULTIPLE)) {
// user does not exist or was deleted
continue;
}
$user_mapping[$mapping] = $user->id;
$userid = $user->id;
} else {
$userid = $user_mapping[$mapping];
}
if (empty($fields[$rolefield]) or !isset($roles[$fields[$rolefield]])) {
if (!$defaultrole) {
// role is mandatory
continue;
}
$roleid = $defaultrole;
} else {
$roleid = $roles[$fields[$rolefield]];
}
$requested_roles[$userid][$roleid] = $roleid;
}
}
$rs->Close();
} else {
debugging('Error while communicating with external enrolment database');
$extdb->Close();
return;
}
unset($user_mapping);
// enrol all users and sync roles
foreach ($requested_roles as $userid=>$roles) {
foreach ($roles as $roleid) {
if (empty($current_roles[$userid])) {
$this->enrol_user($instance, $userid, $roleid);
$current_roles[$userid][$roleid] = $roleid;
$current_status[$userid] = ENROL_USER_ACTIVE;
}
}
// unassign removed roles
foreach($current_roles[$userid] as $cr) {
if (empty($roles[$cr])) {
role_unassign($cr, $userid, $context->id, 'enrol_database', $instance->id);
unset($current_roles[$userid][$cr]);
}
}
// reenable enrolment when previously disable enrolment refreshed
if ($current_status[$userid] == ENROL_USER_SUSPENDED) {
$DB->set_field('user_enrolments', 'status', ENROL_USER_ACTIVE, array('enrolid'=>$instance->id, 'userid'=>$userid));
}
}
// deal with enrolments removed from external table
if ($unenrolaction == 0) {
// unenrol
if (!empty($requested_roles)) {
// we might get some error or connection problem, better not unenrol everybody
foreach ($current_status as $userid=>$status) {
if (isset($requested_roles[$userid])) {
continue;
}
$this->unenrol_user($instance, $userid);
}
}
} else if ($unenrolaction == 1) {
// keep - only adding enrolments
} else if ($unenrolaction == 2) {
// disable
foreach ($current_status as $userid=>$status) {
if (isset($requested_roles[$userid])) {
continue;
}
if ($status != ENROL_USER_SUSPENDED) {
$DB->set_field('user_enrolments', 'status', ENROL_USER_SUSPENDED, array('enrolid'=>$instance->id, 'userid'=>$userid));
}
}
}
}
// close db connection
$extdb->Close();
}
/**
* Performs a full sync with external database.
*
* First it creates new courses if necessary, then
* enrols and unenrols users.
* @return void
*/
public function sync_courses() {
global $CFG, $DB;
// make sure we sync either enrolments or courses
if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or $this->get_config('newcoursetable') or $this->get_config('newcoursefullname') or $this->get_config('newcourseshortname')) {
return;
}
// we may need a lot of memory here
@set_time_limit(0);
@raise_memory_limit("512M");
$extdb = $this->db_init();
// first create new courses
$table = $this->get_config('newcoursetable');
$fullname = strtolower($this->get_config('newcoursefullname'));
$shortname = strtolower($this->get_config('newcourseshortname'));
$idnumber = strtolower($this->get_config('newcourseidnumber'));
$category = strtolower($this->get_config('newcoursecategory'));
$fields = array($fullname, $shortname, $idnumber);
if ($category) {
$fields[] = $category;
}
if ($idnumber) {
$fields[] = $idnumber;
}
$sql = $this->db_get_sql($table, array(), $fields);
$createcourses = array();
if ($rs = $extdb->Execute($sql)) {
if (!$rs->EOF) {
$courselist = array();
while ($fields = $rs->FetchRow()) {
$fields = array_change_key_case($fields, CASE_LOWER);
if (empty($fields[$shortname]) or empty($fields[$fullname])) {
//invalid record - these two are mandatory
continue;
}
$fields = $this->db_decode($fields);
if ($DB->record_exists('course', array('shortname'=>$fields[$shortname]))) {
// already exists
continue;
}
if ($idnumber and $DB->record_exists('course', array('idnumber'=>$fields[$idnumber]))) {
// idnumber duplicates are not allowed
continue;
}
if ($category and !$DB->record_exists('course_categories', array('id'=>$fields[$category]))) {
// invalid category id, better to skip
continue;
}
$course = new object();
$course->fullname = $fields[$fullname];
$course->shortname = $fields[$shortname];
$course->idnumber = $idnumber ? $fields[$idnumber] : NULL;
$course->category = $category ? $fields[$category] : NULL;
$createcourses[] = $course;
}
}
$rs->Close();
} else {
debugging('Error while communicating with external enrolment database');
$extdb->Close();
return;
}
if ($createcourses) {
require_once("$CFG->dirroot/course/lib.php");
$template = $this->get_config('templatecourse');
$defaultcategory = $this->get_config('defaultcategory');
if ($template) {
if ($template = $DB->get_record('course', array('shortname'=>$template))) {
unset($template->id);
unset($template->fullname);
unset($template->shortname);
unset($template->idnumber);
} else {
$template = new object();
}
} else {
$template = new object();
}
if (!$DB->record_exists('course_categories', array('id'=>$defaultcategory))) {
$categories = $DB->get_records('course_categories', array(), 'sortorder', 'id', 0, 1);
$first = reset($categories);
$defaultcategory = $first->id;
}
foreach ($createcourses as $fields) {
$newcourse = clone($template);
$newcourse->fullname = $fields->fullname;
$newcourse->shortname = $fields->shortname;
$newcourse->idnumber = $fields->idnumber;
$newcourse->category = $fields->category ? $fields->category : $defaultcategory;
create_course($newcourse);
}
unset($createcourses);
unset($template);
}
// close db connection
$extdb->Close();
}
protected function db_get_sql($table, array $conditions, array $fields, $distinct = false, $sort = "") {
$fields = $fields ? implode(',', $fields) : "*";
$where = array();
if ($conditions) {
foreach ($conditions as $key=>$value) {
$value = $this->db_encode($this->db_addslashes($value));
$where[] = "$key = '$value'";
}
}
$where = $where ? "WHERE ".implode(" AND ", $where) : "";
$sort = $sort ? "ORDER BY $sort" : "";
$distinct = $distinct ? "DISTINCT" : "";
$sql = "SELECT $distinct $fields
FROM $table
$where
$sort";
return $sql;
}
protected function db_init() {
global $CFG;
require_once($CFG->libdir.'/adodb/adodb.inc.php');
// Connect to the external database (forcing new connection)
$extdb = ADONewConnection($this->get_config('dbtype'));
if ($this->get_config('debugdb')) {
$extdb->debug = true;
ob_start(); //start output buffer to allow later use of the page headers
}
$extdb->Connect($this->get_config('dbhost'), $this->get_config('dbuser'), $this->get_config('dbpass'), $this->get_config('dbname'), true);
$extdb->SetFetchMode(ADODB_FETCH_ASSOC);
if ($this->get_config('dbsetupsql')) {
$extdb->Execute($this->get_config('dbsetupsql'));
}
return $extdb;
}
protected function db_addslashes($text) {
// using custom made function for now
if ($this->get_config('dbsybasequoting')) {
$text = str_replace('\\', '\\\\', $text);
$text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
} else {
$text = str_replace("'", "''", $text);
}
return $text;
}
protected function db_encode($text) {
$dbenc = $this->get_config('dbencoding');
if (empty($dbenc) or $dbenc == 'utf-8') {
return $text;
}
if (is_array($text)) {
foreach($text as $k=>$value) {
$text[$k] = $this->db_encode($value);
}
return $text;
} else {
return textlib_get_instance()->convert($text, 'utf-8', $dbenc);
}
}
protected function db_decode($text) {
$dbenc = $this->get_config('dbencoding');
if (empty($dbenc) or $dbenc == 'utf-8') {
return $text;
}
if (is_array($text)) {
foreach($text as $k=>$value) {
$text[$k] = $this->db_decode($value);
}
return $text;
} else {
return textlib_get_instance()->convert($text, $dbenc, 'utf-8');
}
}
}

115
enrol/database/settings.php Normal file
View File

@ -0,0 +1,115 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Database enrolment plugin settings and presets.
*
* @package enrol_database
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
if ($ADMIN->fulltree) {
//--- general settings -----------------------------------------------------------------------------------
$settings->add(new admin_setting_heading('enrol_database_settings', '', get_string('pluginname_desc', 'enrol_database')));
$settings->add(new admin_setting_heading('enrol_database_exdbheader', get_string('settingsheaderdb', 'enrol_database'), ''));
$options = array('', "access","ado_access", "ado", "ado_mssql", "borland_ibase", "csv", "db2", "fbsql", "firebird", "ibase", "informix72", "informix", "mssql", "mssql_n", "mysql", "mysqli", "mysqlt", "oci805", "oci8", "oci8po", "odbc", "odbc_mssql", "odbc_oracle", "oracle", "postgres64", "postgres7", "postgres", "proxy", "sqlanywhere", "sybase", "vfp");
$options = array_combine($options, $options);
$settings->add(new admin_setting_configselect('enrol_database/dbtype', get_string('dbtype', 'enrol_database'), get_string('dbtype_desc', 'enrol_database'), '', $options));
$settings->add(new admin_setting_configtext('enrol_database/dbhost', get_string('dbhost', 'enrol_database'), get_string('dbhost_desc', 'enrol_database'), 'localhost'));
$settings->add(new admin_setting_configtext('enrol_database/dbuser', get_string('dbuser', 'enrol_database'), '', ''));
$settings->add(new admin_setting_configpasswordunmask('enrol_database/dbpass', get_string('dbpass', 'enrol_database'), '', ''));
$settings->add(new admin_setting_configtext('enrol_database/dbname', get_string('dbname', 'enrol_database'), '', ''));
$settings->add(new admin_setting_configtext('enrol_database/dbencoding', get_string('dbencoding', 'enrol_database'), '', 'utf-8'));
$settings->add(new admin_setting_configtext('enrol_database/dbsetupsql', get_string('dbsetupsql', 'enrol_database'), get_string('dbsetupsql_desc', 'enrol_database'), ''));
$settings->add(new admin_setting_configcheckbox('enrol_database/dbsybasequoting', get_string('dbsybasequoting', 'enrol_database'), get_string('dbsybasequoting_desc', 'enrol_database'), 0));
$settings->add(new admin_setting_configcheckbox('enrol_database/debugdb', get_string('debugdb', 'enrol_database'), get_string('debugdb_desc', 'enrol_database'), 0));
$settings->add(new admin_setting_heading('enrol_database_localheader', get_string('settingsheaderlocal', 'enrol_database'), ''));
$options = array('id'=>'id', 'idnumber'=>'idnumber', 'shortname'=>'shortname');
$settings->add(new admin_setting_configselect('enrol_database/localcoursefield', get_string('localcoursefield', 'enrol_database'), '', 'idnumber', $options));
$options = array('id'=>'id', 'idnumber'=>'idnumber', 'email'=>'email', 'username'=>'username'); // only local users if username selected, no mnet users!
$settings->add(new admin_setting_configselect('enrol_database/localuserfield', get_string('localuserfield', 'enrol_database'), '', 'idnumber', $options));
$options = array('id'=>'id', 'shortname'=>'shortname', 'fullname'=>'fullname');
$settings->add(new admin_setting_configselect('enrol_database/localrolefield', get_string('localrolefield', 'enrol_database'), '', 'shortname', $options));
$settings->add(new admin_setting_heading('enrol_database_remoteheader', get_string('settingsheaderremote', 'enrol_database'), ''));
$settings->add(new admin_setting_configtext('enrol_database/remoteenroltable', get_string('remoteenroltable', 'enrol_database'), get_string('remoteenroltable_desc', 'enrol_database'), ''));
$settings->add(new admin_setting_configtext('enrol_database/remotecoursefield', get_string('remotecoursefield', 'enrol_database'), get_string('remotecoursefield_desc', 'enrol_database'), ''));
$settings->add(new admin_setting_configtext('enrol_database/remoteuserfield', get_string('remoteuserfield', 'enrol_database'), get_string('remoteuserfield_desc', 'enrol_database'), ''));
$settings->add(new admin_setting_configtext('enrol_database/remoterolefield', get_string('remoterolefield', 'enrol_database'), get_string('remoterolefield_desc', 'enrol_database'), ''));
if (!during_initial_install()) {
$options = get_default_enrol_roles(get_context_instance(CONTEXT_SYSTEM));
$student = get_archetype_roles('student');
$student = reset($student);
$settings->add(new admin_setting_configselect('enrol_database/defaultrole', get_string('defaultrole', 'enrol_database'), get_string('defaultrole_desc', 'enrol_database'), $student->id, $options));
}
$settings->add(new admin_setting_configcheckbox('enrol_database/ignorehiddencourses', get_string('ignorehiddencourses', 'enrol_database'), get_string('ignorehiddencourses_desc', 'enrol_database'), 0));
$options = array(0=>get_string('unenrolactionunenrol', 'enrol_database'), 1=>get_string('unenrolactionkeep', 'enrol_database'), 2=>get_string('unenrolactiondisable', 'enrol_database'));
$settings->add(new admin_setting_configselect('enrol_database/unenrolaction', get_string('unenrolaction', 'enrol_database'), get_string('unenrolaction_desc', 'enrol_database'), 0, $options));
$settings->add(new admin_setting_heading('enrol_database_newcoursesheader', get_string('settingsheadernewcourses', 'enrol_database'), ''));
$settings->add(new admin_setting_configtext('enrol_database/newcoursetable', get_string('newcoursetable', 'enrol_database'), get_string('newcoursetable_desc', 'enrol_database'), ''));
$settings->add(new admin_setting_configtext('enrol_database/newcoursefullname', get_string('newcoursefullname', 'enrol_database'), '', 'fullname'));
$settings->add(new admin_setting_configtext('enrol_database/newcourseshortname', get_string('newcourseshortname', 'enrol_database'), '', 'shortname'));
$settings->add(new admin_setting_configtext('enrol_database/newcourseidnumber', get_string('newcourseidnumber', 'enrol_database'), '', 'idnumber'));
$settings->add(new admin_setting_configtext('enrol_database/newcoursecategory', get_string('newcoursecategory', 'enrol_database'), '', ''));
if (!during_initial_install()) {
$options = array();
$parentlist = array();
make_categories_list($options, $parentlist);
$settings->add(new admin_setting_configselect('enrol_database/defaultcategory', get_string('defaultcategory', 'enrol_database'), get_string('defaultcategory_desc', 'enrol_database'), 1, $options));
unset($parentlist);
}
$settings->add(new admin_setting_configtext('enrol_database/templatecourse', get_string('templatecourse', 'enrol_database'), get_string('templatecourse_desc', 'enrol_database'), ''));
}

View File

@ -0,0 +1,27 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Database enrolment plugin version specification.
*
* @package enrol_database
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$plugin->version = 2010061500;
//TODO: should we add cron sync?

Some files were not shown because too many files have changed in this diff Show More