MDL-21782 reworked enrolment framework, the core infrastructure is in place, the...
authorPetr Skoda <skodak@moodle.org>
Mon, 21 Jun 2010 15:30:49 +0000 (15:30 +0000)
committerPetr Skoda <skodak@moodle.org>
Mon, 21 Jun 2010 15:30:49 +0000 (15:30 +0000)
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

225 files changed:
admin/bloglevelupgrade.php
admin/cron.php
admin/enrol.php
admin/enrol_config.php [deleted file]
admin/generator.php
admin/mnet/enr_course_enrol.php
admin/mnet/enr_courses.php
admin/mnet/enr_hosts.php
admin/report/security/lang/en/report_security.php
admin/report/security/lib.php
admin/roles/assign.php
admin/roles/check.php
admin/roles/lib.php
admin/roles/manage.php
admin/roles/override.php
admin/roles/permissions.php
admin/roles/tabs.php [deleted file]
admin/roles/usersroles.php
admin/settings/appearance.php
admin/settings/courses.php
admin/settings/frontpage.php
admin/settings/plugins.php
admin/settings/security.php
admin/settings/users.php
admin/uploaduser.php
admin/uploaduser_form.php
admin/user/user_bulk_enrol.php
admin/webservice/testclient_forms.php
auth/cas/auth.php
auth/fc/auth.php
auth/ldap/auth.php
auth/mnet/auth.php
auth/shibboleth/index.php
backup/backuplib.php
backup/moodle2/backup_course_task.class.php
backup/moodle2/backup_final_task.class.php
backup/moodle2/backup_stepslib.php
backup/restore_check.html
backup/restore_form.html
backup/restorelib.php
blocks/course_list/block_course_list.php
blocks/course_overview/block_course_overview.php
blocks/course_summary/block_course_summary.php
blocks/course_summary/db/upgrade.php
calendar/export_execute.php
calendar/lib.php
calendar/view.php
cohort/edit.php
cohort/lib.php
course/category.php
course/edit.php
course/edit_form.php
course/enrol.php
course/external.php [deleted file]
course/externallib.php
course/importstudents.html [deleted file]
course/importstudents.php [deleted file]
course/index.php
course/info.php
course/lib.php
course/pending.php
course/renderer.php
course/report/completion/lib.php
course/report/log/lib.php
course/request_form.php
course/reset_form.php
course/unenrol.php [deleted file]
course/user.php
enrol/authorize/db/upgrade.php
enrol/authorize/enrol.php
enrol/authorize/locallib.php
enrol/authorize/uploadcsv.php
enrol/category/cli/sync.php [new file with mode: 0644]
enrol/category/db/access.php [new file with mode: 0644]
enrol/category/db/events.php [new file with mode: 0644]
enrol/category/db/install.php [new file with mode: 0644]
enrol/category/lang/en/enrol_category.php [new file with mode: 0644]
enrol/category/lib.php [new file with mode: 0644]
enrol/category/locallib.php [new file with mode: 0644]
enrol/category/settings.php [new file with mode: 0644]
enrol/category/version.php [new file with mode: 0644]
enrol/cohort/addinstance.php [new file with mode: 0644]
enrol/cohort/addinstance_form.php [new file with mode: 0644]
enrol/cohort/db/access.php [new file with mode: 0644]
enrol/cohort/db/events.php [new file with mode: 0644]
enrol/cohort/lang/en/enrol_cohort.php [new file with mode: 0644]
enrol/cohort/lib.php [new file with mode: 0644]
enrol/cohort/locallib.php [new file with mode: 0644]
enrol/cohort/settings.php [new file with mode: 0644]
enrol/cohort/version.php [new file with mode: 0644]
enrol/database/cli/sync.php [new file with mode: 0644]
enrol/database/config.html [deleted file]
enrol/database/db/access.php [new file with mode: 0644]
enrol/database/db/install.php [new file with mode: 0644]
enrol/database/enrol.php [deleted file]
enrol/database/enrol_database_sync.php [deleted file]
enrol/database/lang/en/enrol_database.php
enrol/database/lib.php [new file with mode: 0644]
enrol/database/settings.php [new file with mode: 0644]
enrol/database/version.php [new file with mode: 0644]
enrol/enrol.class.php [deleted file]
enrol/externallib.php
enrol/flatfile/enrol.php
enrol/guest/addinstance.php [new file with mode: 0644]
enrol/guest/db/access.php [new file with mode: 0644]
enrol/guest/lang/en/enrol_guest.php [new file with mode: 0644]
enrol/guest/lib.php [new file with mode: 0644]
enrol/guest/locallib.php [new file with mode: 0644]
enrol/guest/settings.php [new file with mode: 0644]
enrol/guest/version.php [new file with mode: 0644]
enrol/imsenterprise/enrol.php
enrol/index.html [deleted file]
enrol/index.php [new file with mode: 0644]
enrol/instances.php [new file with mode: 0644]
enrol/ldap/enrol.php
enrol/ldap/enrol_ldap_sync.php
enrol/manual/addinstance.php [new file with mode: 0644]
enrol/manual/config.html [deleted file]
enrol/manual/db/access.php [new file with mode: 0644]
enrol/manual/db/install.php [new file with mode: 0644]
enrol/manual/enrol.html [deleted file]
enrol/manual/enrol.php [deleted file]
enrol/manual/lang/en/enrol_manual.php
enrol/manual/lib.php [new file with mode: 0644]
enrol/manual/locallib.php [new file with mode: 0644]
enrol/manual/manage.php [new file with mode: 0644]
enrol/manual/settings.php [new file with mode: 0644]
enrol/manual/unenrolself.php [new file with mode: 0644]
enrol/manual/version.php [new file with mode: 0644]
enrol/meta/addinstance.php [new file with mode: 0644]
enrol/meta/addinstance_form.php [new file with mode: 0644]
enrol/meta/db/access.php [new file with mode: 0644]
enrol/meta/db/events.php [new file with mode: 0644]
enrol/meta/db/install.php [new file with mode: 0644]
enrol/meta/lang/en/enrol_meta.php [new file with mode: 0644]
enrol/meta/lib.php [new file with mode: 0644]
enrol/meta/locallib.php [new file with mode: 0644]
enrol/meta/settings.php [new file with mode: 0644]
enrol/meta/version.php [new file with mode: 0644]
enrol/mnet/enrol.php
enrol/otherusers.php [new file with mode: 0644]
enrol/paypal/enrol.php
enrol/paypal/ipn.php
enrol/paypal/return.php
enrol/self/addinstance.php [new file with mode: 0644]
enrol/self/db/access.php [new file with mode: 0644]
enrol/self/db/install.php [new file with mode: 0644]
enrol/self/lang/en/enrol_self.php [new file with mode: 0644]
enrol/self/lib.php [new file with mode: 0644]
enrol/self/locallib.php [new file with mode: 0644]
enrol/self/settings.php [new file with mode: 0644]
enrol/self/unenrolself.php [new file with mode: 0644]
enrol/self/version.php [new file with mode: 0644]
enrol/users.php [new file with mode: 0644]
enrol/users_forms.php [new file with mode: 0644]
grade/querylib.php
grade/report/overview/lib.php
group/assign.php
group/autogroup_form.php
group/group_form.php
group/index.php
group/lib.php
index.php
lang/en/admin.php
lang/en/enrol.php [new file with mode: 0644]
lang/en/error.php
lang/en/group.php
lang/en/moodle.php
lang/en/role.php
lib/accesslib.php
lib/adminlib.php
lib/completion/completion_criteria_duration.php
lib/completion/cron.php
lib/datalib.php
lib/db/access.php
lib/db/events.php
lib/db/install.php
lib/db/install.xml
lib/db/services.php
lib/db/upgrade.php
lib/ddl/mysql_sql_generator.php
lib/deprecatedlib.php
lib/enrollib.php [new file with mode: 0644]
lib/eventslib.php
lib/externallib.php
lib/file/file_browser.php
lib/file/file_info_course.php
lib/gradelib.php
lib/moodlelib.php
lib/navigationlib.php
lib/outputrequirementslib.php
lib/sessionlib.php
lib/setup.php
lib/setuplib.php
lib/simpletest/broken_testfilelib.php
lib/simpletest/testaccesslib.php
lib/upgradelib.php
message/lib.php
mod/assignment/db/events.php [new file with mode: 0644]
mod/choice/view.php
mod/feedback/show_entries.php
mod/feedback/show_nonrespondents.php
mod/forum/db/events.php [new file with mode: 0644]
mod/forum/db/upgrade.php
mod/forum/lib.php
mod/forum/post.php
notes/index.php
pluginfile.php
question/type/randomsamatch/questiontype.php
repository/lib.php
rss/file.php
search/documents/label_document.php
search/documents/resource_document.php
search/querylib.php
tag/coursetagslib.php
tag/locallib.php
user/action_redir.php
user/extendenrol.php [deleted file]
user/groupextendenrol.php [deleted file]
user/index.php
user/lib.php
user/profile.php
user/selector/lib.php
user/view.php
version.php

index f833c17..b04d1dc 100644 (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) {
index ef41ce0..79def22 100644 (file)
     }
     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.');
     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)) {
         }
         flush();
 
-        sync_metacourses();
-        mtrace('Synchronised metacourses');
-
         //
         // generate new password emails for users
         //
         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();
-        }
-        if (!empty($enrol->log)) {
-            mtrace($enrol->log);
+    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;
         }
-        unset($enrol);
+        mtrace("Running cron for enrol_$ename...");
+        $enrol->cron();
+        $enrol->set_config('lastcron', time());
     }
 
     if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
index 0bd4866..26e430e 100644 (file)
 <?php
-       // enrol.php - allows admin to edit all enrollment variables
-       //             Yes, enrol is correct English spelling.
-
-    require_once('../config.php');
-    require_once($CFG->libdir.'/adminlib.php');
-
-    $enrol        = optional_param('enrol', $CFG->enrol, PARAM_SAFEDIR);
-    $savesettings = optional_param('savesettings', 0, PARAM_BOOL);
-
-    admin_externalpage_setup('enrolment');
-
-    if (!isset($CFG->sendcoursewelcomemessage)) {
-        set_config('sendcoursewelcomemessage', 1);
-    }
-
-
-    require_once("$CFG->dirroot/enrol/enrol.class.php");   /// Open the factory class
-
-/// Save settings
-
-    if ($frm = data_submitted() and !$savesettings) {
-        if (!confirm_sesskey()) {
-            print_error('confirmsesskeybad', 'error');
+// 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/>.
+
+/**
+ * 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
+ */
+
+require_once('../config.php');
+require_once($CFG->libdir.'/adminlib.php');
+
+$action  = required_param('action', PARAM_ACTION);
+$enrol   = required_param('enrol', PARAM_SAFEDIR);
+$confirm = optional_param('confirm', 0, PARAM_BOOL);
+
+$PAGE->set_url('/admin/enrol.php');
+
+require_login();
+require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM));
+require_sesskey();
+
+$enabled = enrol_get_plugins(true);
+$all     = enrol_get_plugins(false);
+
+$return = new moodle_url('/admin/settings.php', array('section'=>'manageenrols'));
+
+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 = '';
-        }
-        if ($frm->default && $frm->default != 'manual' && !in_array($frm->default, $frm->enable)) {
-            $frm->enable[] = $frm->default;
-        }
-        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');
-        }
-        set_config('sendcoursewelcomemessage', required_param('sendcoursewelcomemessage', PARAM_BOOL));
-    }
-
-/// Print the form
-
-    $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;
+        $enabled = array_keys($enabled);
+        $enabled = array_flip($enabled);
+        $current = $enabled[$enrol];
+        if ($current == 0) {
+            break; //already at the top
         }
-
-        $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"';
+        $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;
         }
-        if ($module == 'manual') {
-            $enable .= ' disabled="disabled"';
+        $enabled = array_keys($enabled);
+        $enabled = array_flip($enabled);
+        $current = $enabled[$enrol];
+        if ($current == count($enabled) - 1) {
+            break; //already at the end
         }
-        $enable .= ' />';
-        if (method_exists($plugin, 'print_entry')) {
-            $default = '<input type="radio" name="default" value="'.$module.'"';
-            if ($CFG->enrol == $module) {
-                $default .= ' checked="checked"';
-            }
-            $default .= ' />';
+        $enabled = array_flip($enabled);
+        $enabled[$current] = $enabled[$current + 1];
+        $enabled[$current + 1] = $enrol;
+        set_config('enrol_plugins_enabled', implode(',', $enabled));
+        break;
+
+    case 'uninstall':
+        echo $OUTPUT->header();
+        echo $OUTPUT->heading(get_string('enrolments', 'enrol'));
+
+        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);
-
-    echo "<div style=\"text-align:center\"><input type=\"submit\" value=\"".get_string("savechanges")."\" /></div>\n";
-    echo "</div>";
-    echo "</form>";
 
-    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();
+        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;
+
+        } else {  // Delete everything!!
+            uninstall_plugin('enrol', $enrol);
+
+            $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);
\ No newline at end of file
diff --git a/admin/enrol_config.php b/admin/enrol_config.php
deleted file mode 100644 (file)
index cf8e60a..0000000
+++ /dev/null
@@ -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;
-
index 315d44e..96e3b35 100755 (executable)
@@ -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.");
                 }
             }
 
index 6cea462..6404a99 100644 (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);
 /// 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');
index cee043e..0ca0159 100644 (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));
index ae964f5..b97ddd7 100644 (file)
@@ -6,11 +6,11 @@
     require_once($CFG->libdir.'/adminlib.php');
     require_once($CFG->dirroot.'/mnet/lib.php');
 
-    admin_externalpage_setup('mnetenrol');
+die('TODO: MDL-22787 mnet enrolments are not reimplemented yet, sorry.');
 
-    require_once("$CFG->dirroot/enrol/enrol.class.php");   /// Open the factory class
+    admin_externalpage_setup('mnetenrol');
 
-    $enrolment = enrolment_factory::factory('mnet');
+    $enrolment = enrol_get_plugin('mnet');
 
 /// Otherwise fill and print the form.
 
index e8c1190..e80d85f 100644 (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!';
index 2d59c76..b3053ff 100644 (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
index a03840b..6b17a60 100755 (executable)
@@ -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();
index cad9fe5..27ebd97 100755 (executable)
@@ -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);
index 203abc8..33493ac 100644 (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) {
index c0a946b..f9b0935 100755 (executable)
@@ -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();
index 2d21254..29737d5 100755 (executable)
@@ -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";
index cbd2ee6..bfdd137 100644 (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);
diff --git a/admin/roles/tabs.php b/admin/roles/tabs.php
deleted file mode 100755 (executable)
index 6c69a06..0000000
+++ /dev/null
@@ -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);
-
index a25d6dd..7412c89 100644 (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
index 4647842..65106dc 100644 (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'));
index e1e7504..2919413 100644 (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));
index 24a5376..052611b 100644 (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
index cf77a1c..6168fff 100644 (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.
index ca4102c..4d0d6aa 100644 (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);
index 36a1ecb..cade4ee 100644 (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'),
index c58c998..bc2d1d5 100755 (executable)
@@ -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 {
-                    $rid = $formdata->{'uulegacy'.$addtype};
-                }
 
-            } else {
-                // no role specified, use the default
-                if (empty($ccache[$shortname]->defaultrole)) {
-                    $rid = $CFG->defaultcourseroleid;
+                } 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 = $ccache[$shortname]->defaultrole;
+                    // no role specified, use the default from manual enrol plugin
+                    $rid = $manualcache[$courseid]->roleid;
                 }
-            }
 
-            // 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;
-                }
-            }
+                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;
+                        }
+                    }
 
-            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');
+                    $manual->enrol_user($manualcache[$courseid], $user->id, $rid, $timestart, $timeend, true);
+
+                    $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;
+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);
+}
 
-    $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);
+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 $choices;
+    return $rolecache;
 }
-
index 88a1ced..29d3cb3 100644 (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'));
     }
 }
index 4b99ef8..4660a3e 100644 (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"';
index 5f5f378..342fc35 100644 (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'));
 
index f2a498f..c2aaa3c 100644 (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');
             }
         }
     }
index ce9a593..3717dc4 100644 (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');
             }
         }
     }
index 0bac19c..f8008cf 100644 (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');
             }
         }
     }
index 55af2c5..2ee6098 100644 (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
index ddb57ff..ff8a385 100644 (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);
index f438375..0a4c3f5 100644 (file)
     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)
index 09abf4d..34eedb7 100644 (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'));
 
index ef660e5..d0461e3 100644 (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'));
index f81388a..0ab76fc 100644 (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
index 4263908..7ffff21 100644 (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);
 
             }
         }
         $restore->restoreto=$restore_restoreto;
-        $restore->metacourse=$restore_metacourse;
         $restore->users=$restore_users;
         $restore->groups=$restore_groups;
         $restore->logs=$restore_logs;
     //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();
index 97f42a2..9d8a5b7 100644 (file)
         }
     }
 
-    //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>";
index 64d75d1..a6ac3ee 100644 (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);
     }
 
index 3a1923a..0d52ebd 100644 (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>";
index 4c49417..a67a603 100644 (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
 
index 6a86866..94d7431 100644 (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) {
index 144d233..d408e84 100644 (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.
index 757dc34..1c676be 100644 (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;
index f8d8e64..d23d738 100644 (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;
 }
index a0bd998..b455c91 100644 (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]);
index 94798a1..d901575 100644 (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');
 
index caffeb7..060c601 100644 (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;
index 65db242..2b9128a 100644 (file)
             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
             }
         }
 
 
 /// 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);
 
         $strshow = get_string('show');
         $strsummary = get_string('summary');
         $strsettings = get_string('settings');
-        $strassignteachers = get_string('assignteachers');
         $strallowguests = get_string('allowguests');
         $strrequireskey = get_string('requireskey');
 
                 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') . '" />',
index 2d8a045..17882a8 100644 (file)
 <?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');
-
-    $id         = optional_param('id', 0, PARAM_INT);       // course id
-    $categoryid = optional_param('category', 0, PARAM_INT); // course category - can be changed in edit form
-
-    $PAGE->set_pagelayout('admin');
-
-/// basic access control checks
-    if ($id) { // editing course
-
-        if($id == SITEID){
-            // don't allow editing of  'site course' using this from
-            print_error('cannoteditsiteform');
-        }
-
-        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');
-    }
-
-    $PAGE->set_url('/course/edit.php');
-    if ($id !== 0) {
-        $PAGE->url->param('id',$id);
-    } else {
-        $PAGE->url->param('category',$categoryid);
+// 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/>.
+
+/**
+ * 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
+ */
+
+require_once('../config.php');
+require_once('lib.php');
+require_once('edit_form.php');
+
+$id         = optional_param('id', 0, PARAM_INT);       // course id
+$categoryid = optional_param('category', 0, PARAM_INT); // course category - can be changed in edit form
+
+$PAGE->set_pagelayout('admin');
+$PAGE->set_url('/course/edit.php');
+
+// basic access control checks
+if ($id) { // editing course
+    if ($id == SITEID){
+        // don't allow editing of  'site course' using this from
+        print_error('cannoteditsiteform');
     }
 
-    /// 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 (empty($course->restrictmodules)) {
-                    $allowedmods = explode(',',$CFG->defaultallowedmodules);
-                } // it'll be greyed out but we want these by default anyway.
-            }
-            $course->allowedmods = $allowedmods;
+    $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;
         }
-        $course = file_prepare_standard_editor($course, 'summary', $editoroptions, $coursecontext, 'course_summary', $course->id);
     } else {
-        $course = file_prepare_standard_editor($course, 'summary', $editoroptions, null, 'course_summary', null);
+        // 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);
 
-/// 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 {
+    $course = file_prepare_standard_editor($course, 'summary', $editoroptions, null, 'course_summary', null);
+}
 
-    } else if ($data = $editform->get_data()) {
+// first create the form
+$editform = new course_edit_form(NULL, array('course'=>$course, 'category'=>$category, 'editoroptions'=>$editoroptions));
 
-        $data->password = $data->enrolpassword;  // we need some other name for password field MDL-9929
-/// process data if submitted
+if ($editform->is_cancelled()) {
+    if (empty($course)) {
+        redirect($CFG->wwwroot.'/');
+    } else {
+        redirect($CFG->wwwroot.'/course/view.php?id='.$course->id);
+    }
 
-        //preprocess data
-        $data->timemodified = time();
+} else if ($data = $editform->get_data()) {
+    // process data if submitted
 
-        if (empty($course->id)) {
-            // In creating the course
-            if (!$course = create_course($data)) {
-                print_error('coursenotcreated');
-            }
+    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);
+        // Get the context of the newly created course
+        $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
 
-            // 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);
+        // 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);
+        }
 
-            // 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);
+        // 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);
+                }
             }
+        }
 
-            // ensure we can use the course right after creating it
-            // this means trigger a reload of accessinfo...
-            mark_context_dirty($context->path);
+        redirect($CFG->wwwroot."/course/view.php?id=$course->id");
 
-            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");
-        }
+    } else {
+        // 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());
 
-    $PAGE->set_title($title);
-    $PAGE->set_heading($fullname);
-    $PAGE->set_focuscontrol($editform->focus());
-    echo $OUTPUT->header();
-    echo $OUTPUT->heading($streditcoursesettings);
+echo $OUTPUT->header();
+echo $OUTPUT->heading($streditcoursesettings);
 
-    $editform->display();
+$editform->display();
 
-    echo $OUTPUT->footer();
+echo $OUTPUT->footer();
 
index b3ee3e2..f69f1b2 100644 (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'));
-
-            $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');
-
+        if (has_capability('moodle/site:config', $systemcontext)) {
+            if (((!empty($course->requested) && $CFG->restrictmodulesfor == 'requested') || $CFG->restrictmodulesfor == 'all')) {
+                $mform->addElement('header', '', get_string('restrictmodules'));
+
+                $options = array();
+                $options['0'] = get_string('no');
+                $options['1'] = get_string('yes');
+                $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
+                if (!empty($CFG->restrictbydefault)) {
+                    $mform->setDefault('restrictmodules', 1);
+                }
 
-            $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;
     }
index f780898..aceb88b 100644 (file)
 // 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)));
diff --git a/course/external.php b/course/external.php
deleted file mode 100644 (file)
index 660f6f8..0000000
+++ /dev/null
@@ -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");
-    }
-
-}
-
-
index 6b8c708..ec8e627 100644 (file)
 /**
  * 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 {
diff --git a/course/importstudents.html b/course/importstudents.html
deleted file mode 100644 (file)
index 5b8d742..0000000
+++ /dev/null
@@ -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>
-
-
diff --git a/course/importstudents.php b/course/importstudents.php
deleted file mode 100644 (file)
index 434abb7..0000000
+++ /dev/null
@@ -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();
-
-
index 52b70de..7725b29 100644 (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);
+        }
     }
 }
 
index fc3fc4e..9c0d32a 100644 (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) {
             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();
 
index 6aa9819..546ac6e 100644 (file)
  *
  * @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;
+    if (empty($courseids)) {
+        // nothing to do
+        return;
+    }
 
-        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++;
+    if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
+        return false;
+    }
 
-                $DB->update_record('course', $course);
+    $courseids = array_reverse($courseids);
+    $i = 1;
 
-                $context   = get_context_instance(CONTEXT_COURSE, $course->id);
-                $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
-                context_moved($context, $newparent);
+    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();
     }
+    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');
         }
     }
 
+    $data->timecreated  = time();
+    $data->timemodified = $data->timecreated;
 
-    // preprocess allowed mods
-    $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
-    unset($data->allowedmods);
-    if ($CFG->restrictmodulesfor == 'all') {
-        $data->restrictmodules = 1;
+    // place at beginning of any category
+    $data->sortorder = 0;
 
-        // 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);
-            }
-        }
+    if ($editoroptions) {
+        // summary text is updated later, we need context to store the files first
+        $data->summary = '';
+        $data->summary_format = FORMAT_HTML;
+    }
+
+    // init visible flags
+    if (isset($data->visible)) {
+        $data->visibleold = $data->visible;
     } else {
-        $data->restrictmodules = 0;
+        $data->visibleold = $data->visible = 1;
     }
 
-    $data->timecreated = time();
+    $newcourseid = $DB->insert_record('course', $data);
+    $context = get_context_instance(CONTEXT_COURSE, $newcourseid, MUST_EXIST);
 
-    // place at beginning of any category
-    $data->sortorder = 0;
+    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));
+    }
 
-    if ($newcourseid = $DB->insert_record('course', $data)) {  // Set up new course
+    $course = $DB->get_record('course', array('id'=>$newcourseid));
 
-        $course = $DB->get_record('course', array('id'=>$newcourseid));
+    // Setup the blocks
+    blocks_add_default_course_blocks($course);
 
-        // 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);
 
-        update_restricted_mods($course, $allowedmods);
+    fix_course_sortorder();
 
-        $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);
+    // 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));
+            }
+        }
+    }
 
-        fix_course_sortorder();
+    // new context created - better mark it as dirty
+    mark_context_dirty($context->path);
 
-        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);
 
-        // Save any custom role names.
-        save_local_role_names($course->id, $data);
+    // set up enrolments
+    enrol_course_updated(true, $course, $data);
 
-        // Trigger events
-        events_trigger('course_created', $course);
+    add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
 
-        return $course;
-    }
+    // Trigger events
+    events_trigger('course_created', $course);
 
-    return false;   // error
+    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);
 
-    $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 ($editoroptions) {
+        $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course_summary', 0);
     }
 
-    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);
-
-    } elseif ($oldcourse->category != $data->category) {
-        $movecat = true;
     }
+    $movecat = (isset($data->category) and $oldcourse->category != $data->category);
 
-    // Update with the new data
-    if ($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);
-        }
+    // 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) {
-            $context   = get_context_instance(CONTEXT_COURSE, $course->id);
-            $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
-            context_moved($context, $newparent);
+            $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;
+            }
         }
+    }
 
-        fix_course_sortorder();
+    // Update with the new data
+    $DB->update_record('course', $data);
 
-        // Test for and remove blocks which aren't appropriate anymore
-        blocks_remove_inappropriate($course);
+    $course = $DB->get_record('course', array('id'=>$data->id));
 
-        // Save any custom role names.
-        save_local_role_names($course->id, $data);
+    if ($movecat) {
+        $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
+        context_moved($context, $newparent);
+    }
 
-        // Trigger events
-        events_trigger('course_updated', $course);
+    fix_course_sortorder();
 
-        return true;
+    // 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);
     }
 
-    return false;
+    // 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);
                 }
             }
index 54d502e..c2b92c4 100644 (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);
index e23a9a6..eba9bc2 100644 (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));
index 3ca42ba..9b2d122 100644 (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', ''));
     }
index 7d1c920..3a7b6bc 100644 (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;
index ed91bd0..d7657b7 100644 (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'));
index 20e5f54..773bbf1 100644 (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;
diff --git a/course/unenrol.php b/course/unenrol.php
deleted file mode 100644 (file)
index 97cde2d..0000000
+++ /dev/null
@@ -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);
-}
-
-i