Merge branch 'MDL-32027-master-1' of git://git.luns.net.uk/moodle
authorSam Hemelryk <sam@moodle.com>
Sun, 25 Mar 2012 22:06:34 +0000 (11:06 +1300)
committerSam Hemelryk <sam@moodle.com>
Sun, 25 Mar 2012 22:06:34 +0000 (11:06 +1300)
485 files changed:
.gitignore
admin/cron.php
admin/index.php
admin/mnet/peer_forms.php
admin/roles/override.php
admin/settings/appearance.php
admin/settings/plugins.php
admin/settings/security.php
admin/tool/phpunit/cli/util.php [new file with mode: 0644]
admin/tool/phpunit/index.php [new file with mode: 0644]
admin/tool/phpunit/lang/en/tool_phpunit.php [new file with mode: 0644]
admin/tool/phpunit/settings.php [new file with mode: 0644]
admin/tool/phpunit/version.php [new file with mode: 0644]
admin/tool/unittest/dbtest.php
admin/tool/unittest/index.php
admin/tool/xmldb/actions/XMLDBAction.class.php
admin/tool/xmldb/actions/edit_field/edit_field.js
admin/tool/xmldb/actions/edit_field_save/edit_field_save.class.php
admin/tool/xmldb/actions/main_view/main_view.class.php
admin/tool/xmldb/actions/view_table_php/view_table_php.class.php
admin/tool/xmldb/lang/en/tool_xmldb.php
auth/cas/auth.php
auth/cas/config.html
auth/db/config.html
auth/db/lang/en/auth_db.php
auth/email/auth.php
auth/email/config.html
auth/fc/config.html
auth/imap/config.html
auth/ldap/config.html
auth/manual/config.html
auth/mnet/config.html
auth/nntp/config.html
auth/none/config.html
auth/pam/config.html
auth/pop3/config.html
auth/shibboleth/config.html
backup/moodle2/backup_stepslib.php
backup/moodle2/restore_stepslib.php
backup/util/settings/base_setting.class.php
backup/util/settings/simpletest/testsettings.php
blocks/glossary_random/block_glossary_random.php
blocks/quiz_results/block_quiz_results.php
blocks/rss_client/db/install.xml
calendar/event_form.php
calendar/export_execute.php
calendar/lib.php
calendar/renderer.php
comment/lib.php
config-dist.php
course/category.php
course/completion.js
course/edit.php
course/edit_form.php
course/editcategory.php
course/index.php
course/lib.php
course/modedit.php
course/recent.php
course/reset_form.php
course/search.php
course/view.php
enrol/authorize/localfuncs.php
enrol/database/lang/en/enrol_database.php
enrol/database/lib.php
enrol/database/settings.php
enrol/database/version.php
enrol/locallib.php
enrol/manual/version.php
enrol/manual/yui/quickenrolment/quickenrolment.js
enrol/otherusers.php
enrol/paypal/ipn.php
enrol/users.php
filter/glossary/filter.php
grade/edit/tree/lib.php
grade/export/grade_export_form.php
grade/import/grade_import_form.php
grade/report/grader/index.php
grade/report/grader/lib.php
grade/report/user/lib.php
grade/report/user/styles.css
group/group.php
group/members.php
index.php
install/lang/he/install.php
install/lang/pt/admin.php
install/lang/zh_cn/install.php
lang/en/admin.php
lang/en/blog.php
lang/en/calendar.php
lang/en/completion.php
lang/en/message.php
lang/en/moodle.php
lib/accesslib.php
lib/adminlib.php
lib/authlib.php
lib/blocklib.php
lib/completion/completion_aggregation.php
lib/completion/completion_completion.php
lib/completion/completion_criteria.php
lib/completion/completion_criteria_activity.php
lib/completion/completion_criteria_completion.php
lib/completion/completion_criteria_course.php
lib/completion/completion_criteria_date.php
lib/completion/completion_criteria_duration.php
lib/completion/completion_criteria_grade.php
lib/completion/completion_criteria_role.php
lib/completion/completion_criteria_self.php
lib/completion/completion_criteria_unenrol.php
lib/completion/cron.php
lib/completion/data_object.php
lib/completionlib.php
lib/cronlib.php
lib/csslib.php
lib/csvlib.class.php
lib/datalib.php
lib/db/install.xml
lib/db/upgrade.php
lib/db/upgradelib.php
lib/ddl/database_manager.php
lib/ddl/mssql_sql_generator.php
lib/ddl/mysql_sql_generator.php
lib/ddl/oracle_sql_generator.php
lib/ddl/postgres_sql_generator.php
lib/ddl/simpletest/testddl.php
lib/ddl/sql_generator.php
lib/ddl/sqlite_sql_generator.php
lib/deprecatedlib.php
lib/dml/database_column_info.php
lib/dml/moodle_database.php
lib/dml/mssql_native_moodle_database.php
lib/dml/mysqli_native_moodle_database.php
lib/dml/oci_native_moodle_database.php
lib/dml/pdo_moodle_database.php
lib/dml/pgsql_native_moodle_database.php
lib/dml/simpletest/testdml.php
lib/dml/sqlite3_pdo_moodle_database.php
lib/dml/sqlsrv_native_moodle_database.php
lib/enrollib.php
lib/filebrowser/file_info_context_course.php
lib/filebrowser/file_info_context_system.php
lib/form/dateselector.php
lib/form/datetimeselector.php
lib/form/duration.php
lib/form/editor.php
lib/form/header.php
lib/form/simpletest/testduration.php
lib/form/tags.php
lib/form/yui/checkboxcontroller/checkboxcontroller.js [new file with mode: 0644]
lib/formslib.php
lib/grade/constants.php
lib/grade/grade_category.php
lib/grade/grade_grade.php
lib/grade/grade_scale.php
lib/gradelib.php
lib/html2text.php
lib/html2text_readme.txt
lib/javascript.php
lib/minify/README.txt [deleted file]
lib/minify/builder/_index.js [deleted file]
lib/minify/builder/bm.js [deleted file]
lib/minify/builder/index.php [deleted file]
lib/minify/builder/ocCheck.php [deleted file]
lib/minify/builder/rewriteTest.js [deleted file]
lib/minify/config.php
lib/minify/groupsConfig.php
lib/minify/lib/FirePHP.php
lib/minify/lib/HTTP/ConditionalGet.php
lib/minify/lib/HTTP/Encoder.php
lib/minify/lib/JSMin.php
lib/minify/lib/JSMinPlus.php
lib/minify/lib/Minify.php
lib/minify/lib/Minify/CSS.php
lib/minify/lib/Minify/CSS/Compressor.php
lib/minify/lib/Minify/CSS/UriRewriter.php
lib/minify/lib/Minify/Cache/APC.php
lib/minify/lib/Minify/Cache/File.php
lib/minify/lib/Minify/Cache/Memcache.php
lib/minify/lib/Minify/Cache/ZendPlatform.php [new file with mode: 0644]
lib/minify/lib/Minify/CommentPreserver.php
lib/minify/lib/Minify/Controller/Base.php
lib/minify/lib/Minify/Controller/Groups.php
lib/minify/lib/Minify/Controller/MinApp.php
lib/minify/lib/Minify/Controller/Page.php
lib/minify/lib/Minify/Controller/Version1.php
lib/minify/lib/Minify/DebugDetector.php [new file with mode: 0644]
lib/minify/lib/Minify/HTML.php
lib/minify/lib/Minify/HTML/Helper.php [new file with mode: 0644]
lib/minify/lib/Minify/ImportProcessor.php
lib/minify/lib/Minify/JS/ClosureCompiler.php [new file with mode: 0644]
lib/minify/lib/Minify/Lines.php
lib/minify/lib/Minify/Logger.php
lib/minify/lib/Minify/YUI/CssCompressor.java [new file with mode: 0644]
lib/minify/lib/Minify/YUI/CssCompressor.php [new file with mode: 0644]
lib/minify/lib/Minify/YUICompressor.php
lib/minify/lib/MrClay/Cli.php [new file with mode: 0644]
lib/minify/lib/MrClay/Cli/Arg.php [new file with mode: 0644]
lib/minify/lib/Solar/Dir.php [deleted file]
lib/minify/readme_moodle.txt
lib/minify/utils.php
lib/moodlelib.php
lib/navigationlib.php
lib/outputlib.php
lib/outputrequirementslib.php
lib/pear/HTML/QuickForm.php
lib/pear/HTML/QuickForm/RuleRegistry.php
lib/pear/HTML/QuickForm/advcheckbox.php
lib/pear/HTML/QuickForm/header.php
lib/pear/HTML/QuickForm/hidden.php
lib/pear/HTML/QuickForm/hiddenselect.php
lib/pear/HTML/QuickForm/html.php
lib/phpunit/bootstrap.php [new file with mode: 0644]
lib/phpunit/lib.php [new file with mode: 0644]
lib/phpunit/readme.md [new file with mode: 0644]
lib/pluginlib.php
lib/portfolio/forms.php
lib/searchlib.php
lib/setup.php
lib/setuplib.php
lib/simpletest/testcomponentlib.php
lib/simpletest/testcsslib.php
lib/simpletest/testexternallib.php
lib/simpletest/testfilelib.php
lib/simpletest/testformslib.php
lib/simpletest/testhtml2text.php [new file with mode: 0644]
lib/simpletest/testhtmlwriter.php
lib/simpletest/testmoodlelib.php
lib/simpletest/testnavigationlib.php
lib/simpletest/testoutputcomponents.php
lib/simpletest/testquestionlib.php
lib/simpletest/testrss.php
lib/simpletest/testweblib.php
lib/tests/htmlpurifier_test.php [new file with mode: 0644]
lib/tests/phpunit_test.php [new file with mode: 0644]
lib/tests/textlib_test.php [new file with mode: 0644]
lib/thirdpartylibs.xml
lib/upgrade.txt
lib/upgradelib.php
lib/weblib.php
lib/xmldb/xmldb.dtd
lib/xmldb/xmldb.xsd
lib/xmldb/xmldb_field.php
lib/xmldb/xmldb_index.php
lib/xmldb/xmldb_key.php
lib/xmldb/xmldb_table.php
login/signup_form.php
message/edit.php
message/index.php
message/lib.php
mnet/service/enrol/db/install.xml
mod/assignment/db/access.php
mod/assignment/db/install.xml
mod/assignment/lang/en/assignment.php
mod/assignment/lib.php
mod/assignment/type/offline/assignment.class.php
mod/assignment/type/online/assignment.class.php
mod/assignment/type/upload/assignment.class.php
mod/assignment/type/uploadsingle/assignment.class.php
mod/assignment/version.php
mod/chat/db/access.php
mod/chat/db/install.xml
mod/chat/lang/en/chat.php
mod/chat/lib.php
mod/chat/version.php
mod/choice/db/access.php
mod/choice/db/install.xml
mod/choice/lang/en/choice.php
mod/choice/lib.php
mod/choice/mod_form.php
mod/choice/version.php
mod/data/db/access.php
mod/data/db/install.xml
mod/data/edit.php
mod/data/export_form.php
mod/data/lang/en/data.php
mod/data/lib.php
mod/data/version.php
mod/feedback/db/access.php
mod/feedback/db/install.xml
mod/feedback/edit.php
mod/feedback/item/multichoice/lib.php
mod/feedback/item/multichoicerated/lib.php
mod/feedback/lang/en/feedback.php
mod/feedback/lib.php
mod/feedback/pix/multichoice/0.gif [moved from mod/feedback/pics/0.gif with 100% similarity]
mod/feedback/pix/multichoice/1.gif [moved from mod/feedback/pics/1.gif with 100% similarity]
mod/feedback/pix/multichoice/2.gif [moved from mod/feedback/pics/2.gif with 100% similarity]
mod/feedback/pix/multichoice/3.gif [moved from mod/feedback/pics/3.gif with 100% similarity]
mod/feedback/pix/multichoice/4.gif [moved from mod/feedback/pics/4.gif with 100% similarity]
mod/feedback/pix/multichoice/5.gif [moved from mod/feedback/pics/5.gif with 100% similarity]
mod/feedback/pix/multichoice/6.gif [moved from mod/feedback/pics/6.gif with 100% similarity]
mod/feedback/pix/multichoice/7.gif [moved from mod/feedback/pics/7.gif with 100% similarity]
mod/feedback/pix/multichoice/8.gif [moved from mod/feedback/pics/8.gif with 100% similarity]
mod/feedback/pix/multichoice/9.gif [moved from mod/feedback/pics/9.gif with 100% similarity]
mod/feedback/pix/notrequired.gif [moved from mod/feedback/pics/notrequired.gif with 100% similarity]
mod/feedback/pix/required.gif [moved from mod/feedback/pics/required.gif with 100% similarity]
mod/feedback/version.php
mod/folder/db/access.php
mod/folder/db/install.xml
mod/folder/edit.php
mod/folder/lang/en/folder.php
mod/folder/version.php
mod/forum/db/access.php
mod/forum/db/install.xml
mod/forum/index.php
mod/forum/lang/en/forum.php
mod/forum/lib.php
mod/forum/version.php
mod/glossary/db/access.php
mod/glossary/db/install.xml
mod/glossary/lang/en/glossary.php
mod/glossary/lib.php
mod/glossary/rsslib.php
mod/glossary/version.php
mod/glossary/view.php
mod/imscp/db/access.php
mod/imscp/db/install.xml
mod/imscp/lang/en/imscp.php
mod/imscp/version.php
mod/label/db/access.php [new file with mode: 0644]
mod/label/db/install.xml
mod/label/lang/en/label.php
mod/label/version.php
mod/lesson/db/access.php
mod/lesson/db/install.xml
mod/lesson/essay.php
mod/lesson/lang/en/lesson.php
mod/lesson/locallib.php
mod/lesson/pagetypes/branchtable.php
mod/lesson/pagetypes/endofbranch.php
mod/lesson/pagetypes/endofcluster.php
mod/lesson/pagetypes/essay.php
mod/lesson/pagetypes/matching.php
mod/lesson/pagetypes/multichoice.php
mod/lesson/pagetypes/truefalse.php
mod/lesson/version.php
mod/lti/db/access.php
mod/lti/db/install.xml
mod/lti/lang/en/lti.php
mod/lti/servicelib.php
mod/lti/simpletest/testlocallib.php
mod/lti/version.php
mod/page/db/access.php
mod/page/db/install.xml
mod/page/lang/en/page.php
mod/page/version.php
mod/quiz/attempt.php
mod/quiz/attemptlib.php
mod/quiz/backup/moodle2/backup_quiz_stepslib.php
mod/quiz/db/access.php
mod/quiz/db/install.xml
mod/quiz/db/upgrade.php
mod/quiz/lang/en/quiz.php
mod/quiz/lib.php
mod/quiz/locallib.php
mod/quiz/mod_form.php
mod/quiz/module.js
mod/quiz/renderer.php
mod/quiz/report/grading/report.php
mod/quiz/report/statistics/db/install.xml
mod/quiz/settings.php
mod/quiz/styles.css
mod/quiz/version.php
mod/resource/db/access.php
mod/resource/db/install.xml
mod/resource/lang/en/resource.php
mod/resource/version.php
mod/scorm/backup/moodle2/backup_scorm_stepslib.php
mod/scorm/db/access.php
mod/scorm/db/install.xml
mod/scorm/db/upgrade.php
mod/scorm/lang/en/scorm.php
mod/scorm/lib.php
mod/scorm/locallib.php
mod/scorm/mod_form.php
mod/scorm/report/graphs/graph.php [new file with mode: 0644]
mod/scorm/report/graphs/lang/en/scormreport_graphs.php [new file with mode: 0644]
mod/scorm/report/graphs/report.php [new file with mode: 0644]
mod/scorm/report/graphs/version.php [new file with mode: 0644]
mod/scorm/simpletest/test_formatduration.php
mod/scorm/styles.css
mod/scorm/version.php
mod/survey/db/access.php
mod/survey/db/install.xml
mod/survey/lang/en/survey.php
mod/survey/version.php
mod/upgrade.txt
mod/url/db/access.php
mod/url/db/install.xml
mod/url/lang/en/url.php
mod/url/locallib.php
mod/url/simpletest/testlib.php
mod/url/tests/lib_test.php [new file with mode: 0644]
mod/url/version.php
mod/wiki/admin.php
mod/wiki/comments.php
mod/wiki/create.php
mod/wiki/db/access.php
mod/wiki/db/install.xml
mod/wiki/diff.php
mod/wiki/edit.php
mod/wiki/history.php
mod/wiki/index.php
mod/wiki/instancecomments.php
mod/wiki/lang/en/wiki.php
mod/wiki/lib.php
mod/wiki/lock.php
mod/wiki/map.php
mod/wiki/overridelocks.php
mod/wiki/pagelib.php
mod/wiki/prettyview.php
mod/wiki/restoreversion.php
mod/wiki/simpletest/testwikiparser.php
mod/wiki/version.php
mod/wiki/view.php
mod/wiki/viewversion.php
mod/workshop/db/access.php
mod/workshop/db/install.xml
mod/workshop/lang/en/workshop.php
mod/workshop/lib.php
mod/workshop/version.php
phpunit.xml.dist [new file with mode: 0644]
question/behaviour/deferredcbm/behaviour.php
question/behaviour/immediatecbm/behaviour.php
question/category_class.php
question/editlib.php
question/engine/bank.php
question/engine/questionattempt.php
question/engine/simpletest/testquestionattempt.php
question/format/aiken/format.php
question/format/blackboard/format.php
question/format/blackboard_six/format.php
question/format/examview/format.php
question/format/learnwise/format.php
question/format/multianswer/format.php
question/format/webct/format.php
question/format/xml/format.php
question/qbank.js
question/type/calculated/db/install.xml
question/type/calculated/edit_calculated_form.php
question/type/calculatedmulti/edit_calculatedmulti_form.php
question/type/essay/db/install.xml
question/type/match/db/install.xml
question/type/multianswer/db/install.xml
question/type/multianswer/questiontype.php
question/type/multichoice/db/install.xml
question/type/numerical/db/simpletest/testupgradelibnewqe.php
question/type/numerical/edit_numerical_form.php
question/type/random/db/simpletest/testupgradelibnewqe.php
question/type/shortanswer/question.php
question/type/shortanswer/renderer.php
question/type/shortanswer/simpletest/helper.php
question/type/shortanswer/simpletest/testquestion.php
report/completion/index.php
report/progress/index.php
repository/coursefiles/lib.php
repository/filepicker.js
repository/filepicker.php
repository/lib.php
repository/local/lib.php
repository/merlot/lib.php
repository/recent/lib.php
repository/repository_ajax.php
repository/s3/lib.php
repository/upload/lib.php
repository/user/lib.php
repository/wikimedia/lib.php
repository/wikimedia/wikimedia.php
repository/youtube/lib.php
rss/file.php
tag/index.php
theme/base/layout/frontpage.php
theme/base/layout/general.php
theme/base/layout/report.php
theme/base/style/core.css
theme/base/style/course.css
theme/binarius/style/pagelayout.css
theme/formal_white/style/core.css
theme/fusion/layout/frontpage.php
theme/fusion/settings.php
theme/fusion/style/core.css
theme/index.php
user/filters/checkbox.php
version.php
webservice/xmlrpc/lib.php

index 5a12349..a57c23f 100644 (file)
@@ -25,3 +25,4 @@ CVS
 /.project
 /.buildpath
 /.cache
+/phpunit.xml
\ No newline at end of file
index 5b473a3..cce8ae3 100644 (file)
@@ -81,6 +81,9 @@ if (check_browser_version('MSIE')) {
     @header('Content-Type: text/plain; charset=utf-8');
 }
 
+// we do not want html markup in emulated CLI
+@ini_set('html_errors', 'off');
+
 // execute the cron
 cron_run();
 
index 70dcafa..5baad8c 100644 (file)
@@ -307,7 +307,8 @@ if (during_initial_install()) {
     }
 
     // at this stage there can be only one admin unless more were added by install - users may change username, so do not rely on that
-    $adminuser = get_complete_user_data('id', reset(explode(',', $CFG->siteadmins)));
+    $adminids = explode(',', $CFG->siteadmins);
+    $adminuser = get_complete_user_data('id', reset($adminids));
 
     if ($adminuser->password === 'adminsetuppending') {
         // prevent installation hijacking
index 4c5243b..4725e1f 100644 (file)
@@ -141,10 +141,10 @@ class mnet_review_host_form extends moodleform {
 
         if ($mnet_peer && !empty($mnet_peer->deleted)) {
             $radioarray = array();
-            $radioarray[] = MoodleQuickForm::createElement('static', 'deletedinfo', '',
+            $radioarray[] = $mform->createElement('static', 'deletedinfo', '',
                 $OUTPUT->container(get_string('deletedhostinfo', 'mnet'), 'deletedhostinfo'));
-            $radioarray[] = MoodleQuickForm::createElement('radio', 'deleted', '', get_string('yes'), 1);
-            $radioarray[] = MoodleQuickForm::createElement('radio', 'deleted', '', get_string('no'), 0);
+            $radioarray[] = $mform->createElement('radio', 'deleted', '', get_string('yes'), 1);
+            $radioarray[] = $mform->createElement('radio', 'deleted', '', get_string('no'), 0);
             $mform->addGroup($radioarray, 'radioar', get_string('deleted'), array(' ', ' '), false);
         } else {
             $mform->addElement('hidden', 'deleted');
index 9cd3ce5..ff6848d 100644 (file)
@@ -50,8 +50,10 @@ if ($course) {
 
 // security first
 require_login($course, false, $cm);
+$safeoverridesonly = false;
 if (!has_capability('moodle/role:override', $context)) {
     require_capability('moodle/role:safeoverride', $context);
+    $safeoverridesonly = true;
 }
 $PAGE->set_url($url);
 $PAGE->set_context($context);
@@ -119,7 +121,7 @@ if (empty($overridableroles[$roleid])) {
 }
 
 // If we are actually overriding a role, create the table object, and save changes if appropriate.
-$overridestable = new override_permissions_table_advanced($context, $roleid, false);
+$overridestable = new override_permissions_table_advanced($context, $roleid, $safeoverridesonly);
 $overridestable->read_submitted_permissions();
 
 if (optional_param('savechanges', false, PARAM_BOOL) && confirm_sesskey()) {
index 9c86f4f..c791205 100644 (file)
@@ -97,6 +97,7 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page
     );
     $temp->add(new admin_setting_configselect('defaulthomepage', new lang_string('defaulthomepage', 'admin'), new lang_string('configdefaulthomepage', 'admin'), HOMEPAGE_SITE, $choices));
     $temp->add(new admin_setting_configcheckbox('navshowcategories', new lang_string('navshowcategories', 'admin'), new lang_string('confignavshowcategories', 'admin'), 1));
+    $temp->add(new admin_setting_configcheckbox('navshowmycoursecategories', new lang_string('navshowmycoursecategories', 'admin'), new lang_string('navshowmycoursecategories_help', 'admin'), 0));
     $temp->add(new admin_setting_configcheckbox('navshowallcourses', new lang_string('navshowallcourses', 'admin'), new lang_string('confignavshowallcourses', 'admin'), 0));
     $temp->add(new admin_setting_configtext('navcourselimit',new lang_string('navcourselimit','admin'),new lang_string('confignavcourselimit', 'admin'),20,PARAM_INT));
     $temp->add(new admin_setting_configcheckbox('navlinkcoursesections', new lang_string('navlinkcoursesections', 'admin'), new lang_string('navlinkcoursesections_help', 'admin'), 0));
index 6ed9402..6d192b6 100644 (file)
@@ -477,6 +477,13 @@ foreach ($pages as $page) {
     $ADMIN->add('reportplugins', $page);
 }
 
+/// Add all admin tools
+if ($hassiteconfig) {
+    $ADMIN->add('modules', new admin_category('tools', new lang_string('tools', 'admin')));
+    $ADMIN->add('tools', new admin_externalpage('managetools', new lang_string('toolsmanage', 'admin'),
+                                                     $CFG->wwwroot . '/' . $CFG->admin . '/tools.php'));
+}
+
 // Now add various admin tools
 foreach (get_plugin_list('tool') as $plugin => $plugindir) {
     $settings_path = "$plugindir/settings.php";
@@ -485,13 +492,6 @@ foreach (get_plugin_list('tool') as $plugin => $plugindir) {
     }
 }
 
-/// Add all admin tools
-if ($hassiteconfig) {
-    $ADMIN->add('modules', new admin_category('tools', new lang_string('tools', 'admin')));
-    $ADMIN->add('tools', new admin_externalpage('managetools', new lang_string('toolsmanage', 'admin'),
-                                                     $CFG->wwwroot . '/' . $CFG->admin . '/tools.php'));
-}
-
 /// Add all local plugins - must be always last!
 if ($hassiteconfig) {
     $ADMIN->add('modules', new admin_category('localplugins', new lang_string('localplugins')));
index 6e499ac..189bf87 100644 (file)
@@ -86,19 +86,6 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page
     $ADMIN->add('security', $temp);
 
 
-    // "modulesecurity" settingpage
-    $temp = new admin_settingpage('modulesecurity', new lang_string('modulesecurity', 'admin'));
-    $temp->add(new admin_setting_configselect('restrictmodulesfor', new lang_string('restrictmodulesfor', 'admin'), new lang_string('configrestrictmodulesfor', 'admin'), 'none', array('none' => new lang_string('nocourses'),
-                                                                                                                                                                              'all' => new lang_string('fulllistofcourses'),
-                                                                                                                                                                              'requested' => new lang_string('requestedcourses'))));
-    $temp->add(new admin_setting_configcheckbox('restrictbydefault', new lang_string('restrictbydefault', 'admin'), new lang_string('configrestrictbydefault', 'admin'), 0));
-    $temp->add(new admin_setting_configmultiselect_modules('defaultallowedmodules',
-            new lang_string('defaultallowedmodules', 'admin'),
-            new lang_string('configdefaultallowedmodules', 'admin')));
-    $ADMIN->add('security', $temp);
-
-
-
     // "notifications" settingpage
     $temp = new admin_settingpage('notifications', new lang_string('notifications', 'admin'));
     $temp->add(new admin_setting_configselect('displayloginfailures', new lang_string('displayloginfailures', 'admin'), new lang_string('configdisplayloginfailures', 'admin'), '', array('' => new lang_string('nobody'),
diff --git a/admin/tool/phpunit/cli/util.php b/admin/tool/phpunit/cli/util.php
new file mode 100644 (file)
index 0000000..c270e17
--- /dev/null
@@ -0,0 +1,93 @@
+<?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/>.
+
+/**
+ * PHPUnit related utilities.
+ *
+ * Exit codes:
+ *  0   - success
+ *  1   - general error
+ *  130 - coding error
+ *  131 - configuration problem
+ *  133 - drop existing data before installing
+ *
+ * @package    tool_phpunit
+ * @copyright  2012 Petr Skoda {@link http://skodak.org}
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+define('PHPUNIT_CLI_UTIL', true);
+
+require(__DIR__ . '/../../../../lib/phpunit/bootstrap.php');
+require_once($CFG->libdir.'/phpunit/lib.php');
+require_once($CFG->libdir.'/adminlib.php');
+require_once($CFG->libdir.'/upgradelib.php');
+require_once($CFG->libdir.'/clilib.php');
+require_once($CFG->libdir.'/pluginlib.php');
+require_once($CFG->libdir.'/installlib.php');
+
+// now get cli options
+list($options, $unrecognized) = cli_get_params(
+    array(
+        'drop'        => false,
+        'install'     => false,
+        'buildconfig' => false,
+        'help'        => false,
+    ),
+    array(
+        'h' => 'help'
+    )
+);
+
+if ($unrecognized) {
+    $unrecognized = implode("\n  ", $unrecognized);
+    cli_error(get_string('cliunknowoption', 'admin', $unrecognized));
+}
+
+$drop = $options['drop'];
+$install = $options['install'];
+$buildconfig = $options['buildconfig'];
+
+if ($options['help'] or (!$drop and !$install and !$buildconfig)) {
+    $help = "Various PHPUnit utility functions
+
+Options:
+--drop                Drop database and dataroot
+--install             Install database
+--buildconfig         Build /phpunit.xml from /phpunit.xml.dist that includes suites for all plugins and core
+
+-h, --help            Print out this help
+
+Example:
+\$/usr/bin/php lib/phpunit/tool.php
+";
+    echo $help;
+    die;
+}
+
+if ($buildconfig) {
+    phpunit_util::build_config_file();
+    exit(0);
+
+} else if ($drop) {
+    phpunit_util::drop_site();
+    // note: we must stop here because $CFG is messed up and we can not reinstall, sorry
+    exit(0);
+
+} else if ($install) {
+    phpunit_util::install_site();
+    exit(0);
+}
diff --git a/admin/tool/phpunit/index.php b/admin/tool/phpunit/index.php
new file mode 100644 (file)
index 0000000..1dbaded
--- /dev/null
@@ -0,0 +1,40 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * PHPUnit info
+ *
+ * @package    tool_phpunit
+ * @copyright  2012 Petr Skoda {@link http://skodak.org}
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+define('NO_OUTPUT_BUFFERING', true);
+
+require(dirname(__FILE__) . '/../../../config.php');
+require_once($CFG->libdir.'/adminlib.php');
+
+admin_externalpage_setup('toolphpunit');
+
+echo $OUTPUT->header();
+echo $OUTPUT->heading(get_string('pluginname', 'tool_phpunit'));
+echo $OUTPUT->box_start();
+
+$info = file_get_contents("$CFG->libdir/phpunit/readme.md");
+echo markdown_to_html($info);
+
+echo $OUTPUT->box_end();
+echo $OUTPUT->footer();
\ No newline at end of file
diff --git a/admin/tool/phpunit/lang/en/tool_phpunit.php b/admin/tool/phpunit/lang/en/tool_phpunit.php
new file mode 100644 (file)
index 0000000..08dbbbd
--- /dev/null
@@ -0,0 +1,25 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Strings for component 'tool_phpunit'
+ *
+ * @package    tool_phpunit
+ * @copyright  2012 Petr Skoda {@link http://skodak.org}
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+$string['pluginname'] = 'PHPUnit tests';
diff --git a/admin/tool/phpunit/settings.php b/admin/tool/phpunit/settings.php
new file mode 100644 (file)
index 0000000..8e06b2f
--- /dev/null
@@ -0,0 +1,28 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * PHPunit integration
+ *
+ * @package    tool_phpunit
+ * @copyright  2012 Petr Skoda {@link http://skodak.org}
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+defined('MOODLE_INTERNAL') || die;
+
+$ADMIN->add('development', new admin_externalpage('toolphpunit', get_string('pluginname', 'tool_phpunit'), "$CFG->wwwroot/$CFG->admin/tool/phpunit/index.php"));
diff --git a/admin/tool/phpunit/version.php b/admin/tool/phpunit/version.php
new file mode 100644 (file)
index 0000000..e745026
--- /dev/null
@@ -0,0 +1,30 @@
+<?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/>.
+
+/**
+ * Plugin version info
+ *
+ * @package    tool_phpunit
+ * @copyright  2012 Petr Skoda {@link http://skodak.org}
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+$plugin->version   = 2012030800; // The current plugin version (Date: YYYYMMDDXX)
+$plugin->requires  = 2012030100; // Requires this Moodle version
+$plugin->component = 'tool_phpunit'; // Full name of the plugin (used for diagnostics)
+
index 8a0a60c..e5e2eb1 100644 (file)
@@ -27,6 +27,11 @@ define('NO_OUTPUT_BUFFERING', true);
 
 require(dirname(__FILE__) . '/../../../config.php');
 require_once($CFG->libdir.'/adminlib.php');
+
+// unfortunately outdated SimpleTest is not E_STRICT compatible
+$CFG->debug = ($CFG->debug & ~E_STRICT);
+error_reporting($CFG->debug);
+
 require_once('simpletestlib.php');
 require_once('simpletestcoveragelib.php');
 require_once('ex_simple_test.php');
index 4deef62..62a60a7 100644 (file)
@@ -28,16 +28,18 @@ define('NO_OUTPUT_BUFFERING', true);
 
 require(dirname(__FILE__) . '/../../../config.php');
 require_once($CFG->libdir.'/adminlib.php');
-require_once('simpletestlib.php');
-require_once('simpletestcoveragelib.php');
-require_once('ex_simple_test.php');
-require_once('ex_reporter.php');
 
 // Always run the unit tests in developer debug mode.
-$CFG->debug = DEBUG_DEVELOPER;
+// unfortunately outdated SimpleTest is not E_STRICT compatible
+$CFG->debug = (DEBUG_DEVELOPER & ~E_STRICT);
 error_reporting($CFG->debug);
 raise_memory_limit(MEMORY_EXTRA);
 
+require_once('simpletestlib.php');
+require_once('simpletestcoveragelib.php');
+require_once('ex_simple_test.php');
+require_once('ex_reporter.php');
+
 // page parameters
 $path         = optional_param('path', null, PARAM_PATH);
 $showpasses   = optional_param('showpasses', false, PARAM_BOOL);
index b853a7e..d984894 100644 (file)
@@ -54,18 +54,11 @@ class XMLDBAction {
 
     var $sesskey_protected; // Actions must be protected by sesskey mechanism
 
-    /**
-     * Constructor
-     */
-    function XMLDBAction() {
-        $this->init();
-    }
-
     /**
      * Constructor to keep PHP5 happy
      */
     function __construct() {
-        $this->XMLDBAction();
+        $this->init();
     }
 
     /**
index b5a45c1..57dcfca 100644 (file)
@@ -75,20 +75,24 @@ function transformForm(event) {
     switch (typeField.value) {
         case '1':  // XMLDB_TYPE_INTEGER
             lengthTip.innerHTML = ' 1...20';
+            lengthField.disabled = false;
             decimalsTip.innerHTML = '';
             decimalsField.disabled = true;
             decimalsField.value = '';
             break;
         case '2':  // XMLDB_TYPE_NUMBER
             lengthTip.innerHTML = ' 1...20';
+            lengthField.disabled = false;
             decimalsTip.innerHTML = ' 0...length or empty';
             break;
         case '3':  // XMLDB_TYPE_FLOAT
             lengthTip.innerHTML = ' 1...20 or empty';
+            lengthField.disabled = false;
             decimalsTip.innerHTML = ' 0...length or empty';
             break;
         case '4':  // XMLDB_TYPE_CHAR
             lengthTip.innerHTML = ' 1...1333'; // Hardcoded, yes!
+            lengthField.disabled = false;
             decimalsTip.innerHTML = '';
             decimalsField.disabled = true;
             decimalsField.value = '';
@@ -96,7 +100,8 @@ function transformForm(event) {
             sequenceField.value = '0';
             break;
         case '5':  // XMLDB_TYPE_TEXT
-            lengthTip.innerHTML = ' small, medium, big';
+            lengthTip.innerHTML = '';
+            lengthField.disabled = true;
             decimalsTip.innerHTML = '';
             decimalsField.disabled = true;
             decimalsField.value = '';
@@ -106,7 +111,8 @@ function transformForm(event) {
             defaultField.value = '';
             break;
         case '6':  // XMLDB_TYPE_BINARY
-            lengthTip.innerHTML = ' small, medium, big';
+            lengthTip.innerHTML = '';
+            lengthField.disabled = true;
             decimalsTip.innerHTML = '';
             decimalsField.disabled = true;
             decimalsField.value = '';
index a1b4a80..90b1433 100644 (file)
@@ -49,8 +49,6 @@ class edit_field_save extends XMLDBAction {
             'numberincorrectlength' => 'tool_xmldb',
             'floatincorrectlength' => 'tool_xmldb',
             'charincorrectlength' => 'tool_xmldb',
-            'textincorrectlength' => 'tool_xmldb',
-            'binaryincorrectlength' => 'tool_xmldb',
             'numberincorrectdecimals' => 'tool_xmldb',
             'floatincorrectdecimals' => 'tool_xmldb',
             'defaultincorrect' => 'tool_xmldb',
@@ -201,28 +199,8 @@ class edit_field_save extends XMLDBAction {
                 }
             }
         }
-        // Text checks
-        if ($type == XMLDB_TYPE_TEXT) {
-            if ($length != 'small' &&
-                $length != 'medium' &&
-                $length != 'big') {
-                $errors[] = $this->str['textincorrectlength'];
-            }
-            if ($default !== NULL && $default !== '') {
-                if (substr($default, 0, 1) == "'" ||
-                    substr($default, -1, 1) == "'") {
-                    $errors[] = $this->str['defaultincorrect'];
-                }
-            }
-        }
-        // Binary checks
-        if ($type == XMLDB_TYPE_BINARY) {
-            if ($length != 'small' &&
-                $length != 'medium' &&
-                $length != 'big') {
-                $errors[] = $this->str['binaryincorrectlength'];
-            }
-        }
+        // No text checks
+        // No binary checks
 
         if (!empty($errors)) {
             $tempfield = new xmldb_field($name);
index c8feb61..30af587 100644 (file)
@@ -277,40 +277,6 @@ class main_view extends XMLDBAction {
                         }
                     }
                 }
-                // TODO: Drop this check in Moodle 2.1
-                // Intercept loaded structure here and look for ENUM fields
-                if (isset($dbdir->xml_file)) {
-                    if ($structure =& $dbdir->xml_file->getStructure()) {
-                        if ($tables = $structure->getTables()) {
-                            foreach ($tables as $table) {
-                                if ($fields = $table->getFields()) {
-                                    foreach ($fields as $field) {
-                                        if (!empty($field->hasenums)) {
-                                            if ($hithis) {
-                                                $o .= '<tr class="highlight"><td class="error cell" colspan="10">';
-                                            } else {
-                                                $o .= '<tr class="r' . $row . '"><td class="error cell" colspan="10">';
-                                            }
-                                            $o .= 'Table ' . $table->getName() . ', field ' . $field->getName() . ' has ENUM info';
-                                            if (!empty($field->hasenumsenabled)) {
-                                                $o .= ' that seems to be active (true). ENUMs support has been dropped in Moodle 2.0, '  .
-                                                      ' the XMLDB Editor will delete any ENUM reference next time you save this file' .
-                                                      ' and you MUST provide  one upgrade block in your code to drop them from DB. See' .
-                                                      ' <a href="http://docs.moodle.org/dev/DB_layer_2.0_migration_docs#The_changes">' .
-                                                      ' Moodle Docs</a> for more info and examples.';
-                                            } else {
-                                                $o .= ' that seem to be inactive (false). ENUMs support has been dropped in Moodle 2.0,' .
-                                                      ' the XMLDB Editor will, simply, delete any ENUM reference next time you save this file.' .
-                                                      ' No further action is necessary.';
-                                            }
-                                            $o .= '</td></tr>';
-                                        }
-                                    }
-                                }
-                            }
-                        }
-                    }
-                }
                 // If there are changes pending to be saved, but the file cannot be written... inform here
                 if ($dbdir->path_exists &&
                     file_exists($key . '/install.xml') &&
index 57c0bd3..7ce2157 100644 (file)
@@ -127,7 +127,6 @@ class view_table_php extends XMLDBAction {
                          $optionspacer . 'change_field_precision',
                          $optionspacer . 'change_field_notnull',
                          $optionspacer . 'change_field_default',
-                         $optionspacer . 'drop_enum_from_field', // TODO: Moodle 2.1 - Drop drop_enum_from_field
                          'Keys',
                          $optionspacer . 'add_key',
                          $optionspacer . 'drop_key',
@@ -224,13 +223,6 @@ class view_table_php extends XMLDBAction {
                         $o.= $this->str['mustselectonefield'];
                     }
                     break;
-                case 'drop_enum_from_field': // TODO: Moodle 2.1 - Drop drop_enum_from_field
-                    if ($fieldkeyindexinitial == 'f') { // Only if we have got one field
-                        $o.= s($this->drop_enum_from_field_php($structure, $tableparam, $fieldkeyindexparam));
-                    } else {
-                        $o.= $this->str['mustselectonefield'];
-                    }
-                    break;
                 case 'change_field_default':
                     if ($fieldkeyindexinitial == 'f') { // Only if we have got one field
                         $o.= s($this->change_field_default_php($structure, $tableparam, $fieldkeyindexparam));
@@ -593,57 +585,6 @@ class view_table_php extends XMLDBAction {
         return $result;
     }
 
-    /**
-     * This function will generate all the PHP code needed to
-     * drop the enum values (check constraint) of one field
-     * using XMLDB objects and functions
-     *
-     * Note this function is here as part of the process of
-     * dropping enums completely from Moodle 2.0: MDL-18577
-     * and will be out in Moodle 2.1
-     * TODO: Moodle 2.1 - Drop drop_enum_from_field_php
-     *
-     * @param xmldb_structure structure object containing all the info
-     * @param string table table name
-     * @param string field field name to change its enum
-     */
-    function drop_enum_from_field_php($structure, $table, $field) {
-
-        $result = '';
-        // Validate if we can do it
-        if (!$table = $structure->getTable($table)) {
-            return false;
-        }
-        if (!$field = $table->getField($field)) {
-            return false;
-        }
-        if ($table->getAllErrors()) {
-            return false;
-        }
-
-        // Add the standard PHP header
-        $result .= XMLDB_PHP_HEADER;
-
-        // Add contents
-        $result .= XMLDB_LINEFEED;
-        $result .= '        // Drop list of values (enum) from field ' . $field->getName() . ' on table ' . $table->getName() . XMLDB_LINEFEED;
-        $result .= '        $table = new xmldb_table(' . "'" . $table->getName() . "'" . ');' . XMLDB_LINEFEED;
-        $result .= '        $field = new xmldb_field(' . "'" . $field->getName() . "', " . $field->getPHP(true) . ');' . XMLDB_LINEFEED;
-
-        // Launch the proper DDL
-        $result .= XMLDB_LINEFEED;
-        $result .= '        // Launch drop of list of values from field ' . $field->getName() . XMLDB_LINEFEED;
-        $result .= '        $dbman->drop_enum_from_field($table, $field);' . XMLDB_LINEFEED;
-
-        // Add the proper upgrade_xxxx_savepoint call
-        $result .= $this->upgrade_savepoint_php ($structure);
-
-        // Add standard PHP footer
-        $result .= XMLDB_PHP_FOOTER;
-
-        return $result;
-    }
-
     /**
      * This function will generate all the PHP code needed to
      * change the default of one field using XMLDB objects and functions
index ebb4878..a378c26 100644 (file)
@@ -27,7 +27,6 @@ $string['actual'] = 'Actual';
 $string['aftertable'] = 'After table:';
 $string['back'] = 'Back';
 $string['backtomainview'] = 'Back to main';
-$string['binaryincorrectlength'] = 'Incorrect length for binary field';
 $string['cannotuseidfield'] = 'Cannot insert the "id" field. It is an autonumeric column';
 $string['completelogbelow'] = '(see the complete log of the search below)';
 $string['confirmdeletefield'] = 'Are you absolutely sure that you want to delete the field:';
@@ -159,7 +158,6 @@ $string['selecttable'] = 'Select table:';
 $string['table'] = 'Table';
 $string['tablenameempty'] = 'The table name cannot be empty';
 $string['tables'] = 'Tables';
-$string['textincorrectlength'] = 'Incorrect length for text field';
 $string['unload'] = 'Unload';
 $string['up'] = 'Up';
 $string['view'] = 'View';
index fa6fb0f..d8c9523 100644 (file)
@@ -215,7 +215,7 @@ class auth_plugin_cas extends auth_plugin_ldap {
      * @param object object with submitted configuration settings (without system magic quotes)
      * @param array $err array of error messages
      */
-    function validate_form(&$form, &$err) {
+    function validate_form($form, &$err) {
         $certificate_path = trim($form->certificate_path);
         if ($form->certificate_check && empty($certificate_path)) {
             $err['certificate_path'] = get_string('auth_cas_certificate_path_empty', 'auth_cas');
index 81894ea..4781cb9 100644 (file)
@@ -437,6 +437,6 @@ $help .= get_string('auth_updateremote_expl', 'auth');
 $help .= '<hr />';
 $help .= get_string('auth_updateremote_ldap', 'auth');
 
-print_auth_lock_options('cas', $user_fields, $help, true, true);
+print_auth_lock_options($this->authtype, $user_fields, $help, true, true);
 ?>
 </table>
index 63d014c..94d981b 100644 (file)
 
 <?php
 
-print_auth_lock_options('db', $user_fields, get_string('auth_dbextrafields', 'auth_db'), true, true);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_dbextrafields', 'auth_db'), true, true);
 
 ?>
 </table>
index 2443235..6f42064 100644 (file)
@@ -57,7 +57,7 @@ $string['auth_dbsybasequoting'] = 'Use sybase quotes';
 $string['auth_dbsybasequotinghelp'] = 'Sybase style single quote escaping - needed for Oracle, MS SQL and some other databases. Do not use for MySQL!';
 $string['auth_dbtable'] = 'Name of the table in the database';
 $string['auth_dbtable_key'] = 'Table';
-$string['auth_dbtype'] = 'The database type (See the <a href="../lib/adodb/readme.htm#drivers">ADOdb documentation</a> for details)';
+$string['auth_dbtype'] = 'The database type (See the <a href="http://phplens.com/adodb/supported.databases.html" target="_blank">ADOdb documentation</a> for details)';
 $string['auth_dbtype_key'] = 'Database';
 $string['auth_dbupdatinguser'] = 'Updating user {$a->name} id {$a->id}';
 $string['auth_dbuser'] = 'Username with read access to the database';
index 4436097..0051aaf 100644 (file)
@@ -127,7 +127,7 @@ class auth_plugin_email extends auth_plugin_base {
             if ($user->confirmed) {
                 return AUTH_CONFIRM_ALREADY;
 
-            } else if ($user->auth != 'email') {
+            } else if ($user->auth != $this->authtype) {
                 return AUTH_CONFIRM_ERROR;
 
             } else if ($user->secret == $confirmsecret) {   // They have provided the secret key to get in
index 095171e..1b26e3f 100644 (file)
@@ -25,7 +25,7 @@
 </tr>
 <?php
 
-print_auth_lock_options('email', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
 
 ?>
 </table>
index 9f44af1..91dd8c8 100644 (file)
@@ -97,7 +97,7 @@
 
 <?php
 
-print_auth_lock_options('fc', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
 
 ?>
 </table>
index d604b47..d88ad3a 100644 (file)
@@ -87,7 +87,7 @@ if (!isset($config->changepasswordurl)) {
 
 <?php
 
-print_auth_lock_options('imap', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
 
 ?>
 </table>
index 25c6786..72519c7 100644 (file)
@@ -547,6 +547,6 @@ $help .= get_string('auth_updateremote_expl', 'auth');
 $help .= '<hr />';
 $help .= get_string('auth_updateremote_ldap', 'auth');
 
-print_auth_lock_options('ldap', $user_fields, $help, true, true);
+print_auth_lock_options($this->authtype, $user_fields, $help, true, true);
 ?>
 </table>
index 9caa591..8c03ce0 100644 (file)
@@ -1,5 +1,5 @@
 <table cellspacing="0" cellpadding="5" border="0">
 <?php
-print_auth_lock_options('manual', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
 ?>
 </table>
index 5fc988b..2dbba3f 100644 (file)
@@ -88,7 +88,7 @@ foreach($service_providers as $host) {
 <?php
 }
 
-// print_auth_lock_options('mnet', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+// print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
 
 ?>
 </table>
index 5d50324..179efdd 100644 (file)
@@ -68,7 +68,7 @@ if (!isset($config->changepasswordurl)) {
 
 <?php
 
-print_auth_lock_options('nntp', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
 
 ?>
 </table>
index abeada0..0068836 100644 (file)
@@ -4,7 +4,7 @@
 <table cellspacing="0" cellpadding="5" border="0">
 <?php
 
-print_auth_lock_options('none', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
 
 ?>
 </table>
index f2f6f1a..0068836 100644 (file)
@@ -4,7 +4,7 @@
 <table cellspacing="0" cellpadding="5" border="0">
 <?php
 
-print_auth_lock_options('pam', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
 
 ?>
 </table>
index 8726b28..e2d7e7a 100644 (file)
@@ -105,7 +105,7 @@ if (!isset($config->changepasswordurl)) {
 
 <?php
 
-print_auth_lock_options('pop3', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
 
 ?>
 </table>
index b15b17a..8eff5f2 100644 (file)
@@ -138,7 +138,7 @@ urn:mace:organization2:providerID, Example Organization 2, /Shibboleth.sso/WAYF/
 
 <?php
 
-print_auth_lock_options('shibboleth', $user_fields, '<!-- empty help -->', true, false);
+print_auth_lock_options($this->authtype, $user_fields, '<!-- empty help -->', true, false);
 
 ?>
 </table>
index 78d2721..e22ff35 100644 (file)
@@ -403,7 +403,7 @@ class backup_course_structure_step extends backup_structure_step {
             'visible', 'hiddensections', 'groupmode', 'groupmodeforce',
             'defaultgroupingid', 'lang', 'theme',
             'timecreated', 'timemodified',
-            'requested', 'restrictmodules',
+            'requested',
             'enablecompletion', 'completionstartonenrol', 'completionnotify'));
 
         $category = new backup_nested_element('category', array('id'), array(
@@ -414,10 +414,6 @@ class backup_course_structure_step extends backup_structure_step {
         $tag = new backup_nested_element('tag', array('id'), array(
             'name', 'rawname'));
 
-        $allowedmodules = new backup_nested_element('allowed_modules');
-
-        $module = new backup_nested_element('module', array(), array('modulename'));
-
         // attach format plugin structure to $course element, only one allowed
         $this->add_plugin_structure('format', $course, false);
 
@@ -444,9 +440,6 @@ class backup_course_structure_step extends backup_structure_step {
         $course->add_child($tags);
         $tags->add_child($tag);
 
-        $course->add_child($allowedmodules);
-        $allowedmodules->add_child($module);
-
         // Set the sources
 
         $courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
@@ -466,11 +459,6 @@ class backup_course_structure_step extends backup_structure_step {
                                      backup_helper::is_sqlparam('course'),
                                      backup::VAR_PARENTID));
 
-        $module->set_source_sql('SELECT m.name AS modulename
-                                   FROM {modules} m
-                                   JOIN {course_allowed_modules} cam ON m.id = cam.module
-                                  WHERE course = ?', array(backup::VAR_COURSEID));
-
         // Some annotations
 
         $course->annotate_ids('grouping', 'defaultgroupingid');
index 58048ec..6dd757e 100644 (file)
@@ -1069,6 +1069,21 @@ class restore_section_structure_step extends restore_structure_step {
  * the course record (never inserting)
  */
 class restore_course_structure_step extends restore_structure_step {
+    /**
+     * @var bool this gets set to true by {@link process_course()} if we are
+     * restoring an old coures that used the legacy 'module security' feature.
+     * If so, we have to do more work in {@link after_execute()}.
+     */
+    protected $legacyrestrictmodules = false;
+
+    /**
+     * @var array Used when {@link $legacyrestrictmodules} is true. This is an
+     * array with array keys the module names ('forum', 'quiz', etc.). These are
+     * the modules that are allowed according to the data in the backup file.
+     * In {@link after_execute()} we then have to prevent adding of all the other
+     * types of activity.
+     */
+    protected $legacyallowedmodules = array();
 
     protected function define_structure() {
 
@@ -1131,8 +1146,9 @@ class restore_course_structure_step extends restore_structure_step {
             $data->hiddensections = 0;
         }
 
-        // Only restrict modules if original course was and target site too for new courses
-        $data->restrictmodules = $data->restrictmodules && !empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all';
+        // Set legacyrestrictmodules to true if the course was resticting modules. If so
+        // then we will need to process restricted modules after execution.
+        $this->legacyrestrictmodules = !empty($data->restrictmodules);
 
         $data->startdate= $this->apply_date_offset($data->startdate);
         if ($data->defaultgroupingid) {
@@ -1187,31 +1203,44 @@ class restore_course_structure_step extends restore_structure_step {
     }
 
     public function process_allowed_module($data) {
-        global $CFG, $DB;
-
         $data = (object)$data;
 
-        // only if enabled by admin setting
-        if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all') {
-            $available = get_plugin_list('mod');
-            $mname = $data->modulename;
-            if (array_key_exists($mname, $available)) {
-                if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
-                    $rec = new stdclass();
-                    $rec->course = $this->get_courseid();
-                    $rec->module = $module->id;
-                    if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
-                        $DB->insert_record('course_allowed_modules', $rec);
-                    }
-                }
-            }
+        // Backwards compatiblity support for the data that used to be in the
+        // course_allowed_modules table.
+        if ($this->legacyrestrictmodules) {
+            $this->legacyallowedmodules[$data->modulename] = 1;
         }
     }
 
     protected function after_execute() {
+        global $DB;
+
         // Add course related files, without itemid to match
         $this->add_related_files('course', 'summary', null);
         $this->add_related_files('course', 'legacy', null);
+
+        // Deal with legacy allowed modules.
+        if ($this->legacyrestrictmodules) {
+            $context = context_course::instance($this->get_courseid());
+
+            list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
+            list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
+            foreach ($managerroleids as $roleid) {
+                unset($roleids[$roleid]);
+            }
+
+            foreach (get_plugin_list('mod') as $modname => $notused) {
+                if (isset($this->legacyallowedmodules[$modname])) {
+                    // Module is allowed, no worries.
+                    continue;
+                }
+
+                $capability = 'mod/' . $modname . ':addinstance';
+                foreach ($roleids as $roleid) {
+                    assign_capability($capability, CAP_PREVENT, $roleid, $context);
+                }
+            }
+        }
     }
 }
 
index 558b0c2..765c6ac 100644 (file)
@@ -303,7 +303,7 @@ abstract class base_setting {
         if ($this->is_circular_reference($dependency->get_dependent_setting())) {
             $a = new stdclass();
             $a->alreadydependent = $this->name;
-            $a->main = $dependentsetting->get_name();
+            $a->main = $dependency->get_dependent_setting()->get_name();
             throw new base_setting_exception('setting_circular_reference', $a);
         }
         $this->dependencies[$dependency->get_dependent_setting()->get_name()] = $dependency;
index fd079cc..7d0d8a7 100644 (file)
@@ -32,10 +32,12 @@ require_once($CFG->dirroot . '/backup/util/interfaces/checksumable.class.php');
 require_once($CFG->dirroot . '/backup/backup.class.php');
 require_once($CFG->dirroot . '/backup/util/settings/base_setting.class.php');
 require_once($CFG->dirroot . '/backup/util/settings/backup_setting.class.php');
+require_once($CFG->dirroot . '/backup/util/settings/setting_dependency.class.php');
 require_once($CFG->dirroot . '/backup/util/settings/root/root_backup_setting.class.php');
 require_once($CFG->dirroot . '/backup/util/settings/activity/activity_backup_setting.class.php');
 require_once($CFG->dirroot . '/backup/util/settings/section/section_backup_setting.class.php');
 require_once($CFG->dirroot . '/backup/util/settings/course/course_backup_setting.class.php');
+require_once($CFG->dirroot . '/backup/util/ui/backup_ui_setting.class.php');
 
 /*
  * setting tests (all)
@@ -209,6 +211,21 @@ class setting_test extends UnitTestCase {
             $this->assertEqual($e->a->alreadydependent, 'test4');
         }
 
+        $bs1 = new mock_base_setting('test1', base_setting::IS_INTEGER, null);
+        $bs2 = new mock_base_setting('test2', base_setting::IS_INTEGER, null);
+        $bs1->register_dependency(new setting_dependency_disabledif_empty($bs1, $bs2));
+        try {
+            // $bs1 is already dependent on $bs2 so this should fail.
+            $bs2->register_dependency(new setting_dependency_disabledif_empty($bs2, $bs1));
+            $this->assertTrue(false, 'base_setting_exception expected');
+        } catch (exception $e) {
+            $this->assertTrue($e instanceof base_setting_exception);
+            $this->assertEqual($e->errorcode, 'setting_circular_reference');
+            $this->assertTrue($e->a instanceof stdclass);
+            $this->assertEqual($e->a->main, 'test1');
+            $this->assertEqual($e->a->alreadydependent, 'test2');
+        }
+
         // Create 3 settings and observe between them, last one must
         // automatically inherit all the settings defined in the main one
         $bs1 = new mock_base_setting('test1', base_setting::IS_INTEGER, null);
index 649cd77..dac296a 100644 (file)
@@ -125,12 +125,15 @@ class block_glossary_random extends block_base {
             return $this->content;
         }
 
-        $glossaryid = $this->config->glossary;
-
-        $course = $this->page->course;
-
         require_once($CFG->dirroot.'/course/lib.php');
+        $course = $this->page->course;
         $modinfo = get_fast_modinfo($course);
+        $glossaryid = $this->config->glossary;
+        $cm = $modinfo->instances['glossary'][$glossaryid];
+
+        if (!has_capability('mod/glossary:view', get_context_instance(CONTEXT_MODULE, $cm->id))) {
+            return '';
+        }
 
         if (!isset($modinfo->instances['glossary'][$glossaryid])) {
             // we can get here if the glossary has been deleted, so
@@ -144,8 +147,6 @@ class block_glossary_random extends block_base {
             return $this->content;
         }
 
-        $cm = $modinfo->instances['glossary'][$glossaryid];
-
         if (empty($this->config->cache)) {
             $this->config->cache = '';
         }
index a8d24e5..7ea73f0 100644 (file)
@@ -76,7 +76,7 @@ class block_quiz_results extends block_base {
         return $cm->instance;
     }
 
-    function instance_config_save($data) {
+    function instance_config_save($data, $nolongerused = false) {
         if (empty($data->quizid)) {
             $data->quizid = $this->get_owning_quiz();
         }
index dbd1f14..90096d3 100644 (file)
@@ -8,9 +8,9 @@
       <FIELDS>
         <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true" NEXT="userid"/>
         <FIELD NAME="userid" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="id" NEXT="title"/>
-        <FIELD NAME="title" TYPE="text" LENGTH="small" NOTNULL="true" SEQUENCE="false" PREVIOUS="userid" NEXT="preferredtitle"/>
+        <FIELD NAME="title" TYPE="text" NOTNULL="true" SEQUENCE="false" PREVIOUS="userid" NEXT="preferredtitle"/>
         <FIELD NAME="preferredtitle" TYPE="char" LENGTH="64" NOTNULL="true" SEQUENCE="false" PREVIOUS="title" NEXT="description"/>
-        <FIELD NAME="description" TYPE="text" LENGTH="small" NOTNULL="true" SEQUENCE="false" PREVIOUS="preferredtitle" NEXT="shared"/>
+        <FIELD NAME="description" TYPE="text" NOTNULL="true" SEQUENCE="false" PREVIOUS="preferredtitle" NEXT="shared"/>
         <FIELD NAME="shared" TYPE="int" LENGTH="2" NOTNULL="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="description" NEXT="url"/>
         <FIELD NAME="url" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" PREVIOUS="shared"/>
       </FIELDS>
index 1dd18d1..9bbae6c 100644 (file)
@@ -133,14 +133,16 @@ class event_form extends moodleform {
             $mform->setDefault('repeats', 1);
             $mform->disabledIf('repeats','repeat','notchecked');
 
-        } else if ($repeatedevents > 0) {
+        } else if ($repeatedevents) {
 
             $mform->addElement('hidden', 'repeatid');
             $mform->setType('repeatid', PARAM_INT);
 
             $mform->addElement('header', 'repeatedevents', get_string('repeatedevents', 'calendar'));
-            $mform->addElement('checkbox', 'repeateditall', null, get_string('repeateditall', 'calendar', $repeatedevents), 'repeat');
-            $mform->setDefault('repeateditall', 'checked');
+            $mform->addElement('radio', 'repeateditall', null, get_string('repeateditall', 'calendar', $this->_customdata->event->eventrepeats), 1);
+            $mform->addElement('radio', 'repeateditall', null, get_string('repeateditthis', 'calendar'), 0);
+
+            $mform->setDefault('repeateditall', 1);
 
         }
 
index 7f195be..ee0bed8 100644 (file)
@@ -152,7 +152,7 @@ foreach($events as $event) {
     $ev = new iCalendar_event;
     $ev->add_property('uid', $event->id.'@'.$hostaddress);
     $ev->add_property('summary', $event->name);
-    $ev->add_property('description', $event->description);
+    $ev->add_property('description', clean_param($event->description, PARAM_NOTAGS));
     $ev->add_property('class', 'PUBLIC'); // PUBLIC / PRIVATE / CONFIDENTIAL
     $ev->add_property('last-modified', Bennu::timestamp_to_datetime($event->timemodified));
     $ev->add_property('dtstamp', Bennu::timestamp_to_datetime()); // now
index 645ae18..7280f14 100644 (file)
@@ -497,7 +497,7 @@ function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxeve
 
     if ($events !== false) {
 
-        $modinfo =& get_fast_modinfo($COURSE);
+        $modinfo = get_fast_modinfo($COURSE);
 
         foreach($events as $event) {
 
index 312c572..ade2f63 100644 (file)
@@ -413,6 +413,8 @@ class core_calendar_renderer extends plugin_renderer_base {
 
         $table = new html_table();
         $table->attributes = array('class'=>'calendarmonth calendartable');
+        $time = make_timestamp($calendar->year, $calendar->month);
+        $table->summary = get_string('calendarheading', 'calendar', userdate($time, get_string('strftimemonthyear')));
         $table->data = array();
 
         $header = new html_table_row();
index 171e619..d770e16 100644 (file)
@@ -514,7 +514,7 @@ class comment {
             $c->format      = $u->cformat;
             $c->timecreated = $u->ctimecreated;
             $url = new moodle_url('/user/view.php', array('id'=>$u->id, 'course'=>$this->courseid));
-            $c->profileurl = $url->out();
+            $c->profileurl = $url->out(false);
             $c->fullname = fullname($u);
             $c->time = userdate($c->timecreated, get_string('strftimerecent', 'langconfig'));
             $c->content = format_text($c->content, $c->format, $formatoptions);
index dbc732c..4919ed1 100644 (file)
@@ -353,6 +353,10 @@ $CFG->admin = 'admin';
 //     $CFG->tempdir = '/var/www/moodle/temp';
 //     $CFG->cachedir = '/var/www/moodle/cache';
 //
+// Some filesystems such as NFS may not support file locking operations.
+// Locking resolves race conditions and is strongly recommended for production servers.
+//     $CFG->preventfilelocking = false;
+//
 // If $CFG->langstringcache is enabled (which should always be in production
 // environment), Moodle keeps aggregated strings in its own internal format
 // optimised for performance. By default, this on-disk cache is created in
@@ -383,7 +387,7 @@ $CFG->admin = 'admin';
 // memory limit to something higher.
 // The value for the settings should be a valid PHP memory value. e.g. 512M, 1G
 //
-//     $CFG->extramemorylimit = 1G;
+//     $CFG->extramemorylimit = '1G';
 //
 // The CSS files the Moodle produces can be extremely large and complex, especially
 // if you are using a custom theme that builds upon several other themes.
@@ -479,7 +483,13 @@ $CFG->admin = 'admin';
 // Example:
 //   $CFG->forced_plugin_settings = array('pluginname'  => array('settingname' => 'value', 'secondsetting' => 'othervalue'),
 //                                        'otherplugin' => array('mysetting' => 'myvalue', 'thesetting' => 'thevalue'));
-
+//
+//=========================================================================
+// 9. PHPUNIT SUPPORT
+//=========================================================================
+// $CFG->phpunit_prefix = 'phpu_';
+// $CFG->phpunit_dataroot = '/home/example/phpu_moodledata';
+// $CFG->phpunit_directorypermissions = 02777; // optional
 
 //=========================================================================
 // ALL DONE!  To continue installation, visit your main page with a browser
index 27f4653..6f4f57c 100644 (file)
 <?php
-      // Displays the top level category or all courses
-      // In editing mode, allows the admin to edit a category,
-      // and rearrange courses
-
-    require_once("../config.php");
-    require_once("lib.php");
-
-    $id = required_param('id', PARAM_INT); // Category id
-    $page = optional_param('page', 0, PARAM_INT); // which page to show
-    $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT); // how many per page
-    $categoryedit = optional_param('categoryedit', -1, PARAM_BOOL);
-    $hide = optional_param('hide', 0, PARAM_INT);
-    $show = optional_param('show', 0, PARAM_INT);
-    $moveup = optional_param('moveup', 0, PARAM_INT);
-    $movedown = optional_param('movedown', 0, PARAM_INT);
-    $moveto = optional_param('moveto', 0, PARAM_INT);
-    $resort = optional_param('resort', 0, PARAM_BOOL);
-
-    $site = get_site();
-
-    if (empty($id)) {
-        print_error("unknowcategory");
-    }
-
-    $PAGE->set_category_by_id($id);
-    $urlparams = array('id' => $id);
-    if ($page) {
-        $urlparams['page'] = $page;
-    }
-    if ($perpage) {
-        $urlparams['perpage'] = $perpage;
+// 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/>.
+
+/**
+ * Displays the top level category or all courses
+ * In editing mode, allows the admin to edit a category,
+ * and rearrange courses
+ *
+ * @package    core
+ * @subpackage course
+ * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+require_once("../config.php");
+require_once($CFG->dirroot.'/course/lib.php');
+
+$id = required_param('id', PARAM_INT); // Category id
+$page = optional_param('page', 0, PARAM_INT); // which page to show
+$perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT); // how many per page
+$categoryedit = optional_param('categoryedit', -1, PARAM_BOOL);
+$hide = optional_param('hide', 0, PARAM_INT);
+$show = optional_param('show', 0, PARAM_INT);
+$moveup = optional_param('moveup', 0, PARAM_INT);
+$movedown = optional_param('movedown', 0, PARAM_INT);
+$moveto = optional_param('moveto', 0, PARAM_INT);
+$resort = optional_param('resort', 0, PARAM_BOOL);
+$sesskey = optional_param('sesskey', '', PARAM_RAW);
+
+if (empty($id)) {
+    print_error("unknowcategory");
+}
+
+$PAGE->set_category_by_id($id);
+$PAGE->set_url(new moodle_url('/course/category.php', array('id' => $id)));
+// This is sure to be the category context
+$context = $PAGE->context;
+// And the object has been loaded for us no need for another DB call
+$category = $PAGE->category;
+
+$canedit = can_edit_in_category($category->id);
+if ($canedit) {
+    if ($categoryedit !== -1) {
+        $USER->editing = $categoryedit;
     }
-    $PAGE->set_url(new moodle_url('/course/category.php', array('id' => $id)));
-    navigation_node::override_active_url($PAGE->url);
-    $context = $PAGE->context;
-    $category = $PAGE->category;
-
-    $canedit = can_edit_in_category($category->id);
-    if ($canedit) {
-        if ($categoryedit !== -1) {
-            $USER->editing = $categoryedit;
-        }
+    require_login();
+    $editingon = $PAGE->user_is_editing();
+} else {
+    if ($CFG->forcelogin) {
         require_login();
-        $editingon = $PAGE->user_is_editing();
-    } else {
-        if ($CFG->forcelogin) {
-            require_login();
+    }
+    $editingon = false;
+}
+
+if (!$category->visible) {
+    require_capability('moodle/category:viewhiddencategories', $context);
+}
+
+$canmanage = has_capability('moodle/category:manage', $context);
+$sesskeyprovided = !empty($sesskey) && confirm_sesskey($sesskey);
+
+// Process any category actions.
+if ($canmanage && $resort && $sesskeyprovided) {
+    // Resort the category if requested
+    if ($courses = get_courses($category->id, "fullname ASC", 'c.id,c.fullname,c.sortorder')) {
+        $i = 1;
+        foreach ($courses as $course) {
+            $DB->set_field('course', 'sortorder', $category->sortorder+$i, array('id'=>$course->id));
+            $i++;
         }
-        $editingon = false;
+        fix_course_sortorder(); // should not be needed
     }
+}
 
-    if (!$category->visible) {
-        require_capability('moodle/category:viewhiddencategories', $context);
-    }
+// Process any course actions.
+if ($editingon && $sesskeyprovided) {
 
-    // Process any category actions.
-    if (has_capability('moodle/category:manage', $context)) {
-        /// Resort the category if requested
-        if ($resort and confirm_sesskey()) {
-            if ($courses = get_courses($category->id, "fullname ASC", 'c.id,c.fullname,c.sortorder')) {
-                $i = 1;
-                foreach ($courses as $course) {
-                    $DB->set_field('course', 'sortorder', $category->sortorder+$i, array('id'=>$course->id));
-                    $i++;
-                }
-                fix_course_sortorder(); // should not be needed
-            }
+    // Move a specified course to a new category
+    if (!empty($moveto) and $data = data_submitted()) {
+        // Some courses are being moved
+        // user must have category update in both cats to perform this
+        require_capability('moodle/category:manage', $context);
+        require_capability('moodle/category:manage', get_context_instance(CONTEXT_COURSECAT, $moveto));
+
+        if (!$destcategory = $DB->get_record('course_categories', array('id' => $data->moveto))) {
+            print_error('cannotfindcategory', '', '', $data->moveto);
         }
-    }
 
-    // Process any course actions.
-    if ($editingon) {
-    /// Move a specified course to a new category
-        if (!empty($moveto) and $data = data_submitted() and confirm_sesskey()) {   // Some courses are being moved
-            // user must have category update in both cats to perform this
-            require_capability('moodle/category:manage', $context);
-            require_capability('moodle/category:manage', get_context_instance(CONTEXT_COURSECAT, $moveto));
-
-            if (!$destcategory = $DB->get_record('course_categories', array('id' => $data->moveto))) {
-                print_error('cannotfindcategory', '', '', $data->moveto);
-            }
+        $courses = array();
+        foreach ($data as $key => $value) {
+            if (preg_match('/^c\d+$/', $key)) {
+                $courseid = substr($key, 1);
+                array_push($courses, $courseid);
 
-            $courses = array();
-            foreach ($data as $key => $value) {
-                if (preg_match('/^c\d+$/', $key)) {
-                    $courseid = substr($key, 1);
-                    array_push($courses, $courseid);
-
-                    // check this course's category
-                    if ($movingcourse = $DB->get_record('course', array('id'=>$courseid))) {
-                        if ($movingcourse->category != $id ) {
-                            print_error('coursedoesnotbelongtocategory');
-                        }
-                    } else {
-                        print_error('cannotfindcourse');
+                // check this course's category
+                if ($movingcourse = $DB->get_record('course', array('id'=>$courseid))) {
+                    if ($movingcourse->category != $id ) {
+                        print_error('coursedoesnotbelongtocategory');
                     }
+                } else {
+                    print_error('cannotfindcourse');
                 }
             }
-            move_courses($courses, $data->moveto);
         }
+        move_courses($courses, $data->moveto);
+    }
 
-    /// Hide or show a course
-        if ((!empty($hide) or !empty($show)) and confirm_sesskey()) {
-            if (!empty($hide)) {
-                $course = $DB->get_record('course', array('id' => $hide));
-                $visible = 0;
-            } else {
-                $course = $DB->get_record('course', array('id' => $show));
-                $visible = 1;
-            }
+    // Hide or show a course
+    if (!empty($hide) or !empty($show)) {
+        if (!empty($hide)) {
+            $course = $DB->get_record('course', array('id' => $hide));
+            $visible = 0;
+        } else {
+            $course = $DB->get_record('course', array('id' => $show));
+            $visible = 1;
+        }
 
-            if ($course) {
-                $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
-                require_capability('moodle/course:visibility', $coursecontext);
-                $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
-            }
+        if ($course) {
+            $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
+            require_capability('moodle/course:visibility', $coursecontext);
+            // Set the visibility of the course
+            $DB->set_field('course', 'visible', $visible, array('id' => $course->id));
+            // we set the old flag when user manually changes visibility of course
+            $DB->set_field('course', 'visibleold', $visible, array('id' => $course->id));
         }
+    }
 
 
-    /// Move a course up or down
-        if ((!empty($moveup) or !empty($movedown)) and confirm_sesskey()) {
-            require_capability('moodle/category:manage', $context);
+    // Move a course up or down
+    if (!empty($moveup) or !empty($movedown)) {
+        require_capability('moodle/category:manage', $context);
 
-            // Ensure the course order has continuous ordering
-            fix_course_sortorder();
-            $swapcourse = NULL;
+        // Ensure the course order has continuous ordering
+        fix_course_sortorder();
+        $swapcourse = NULL;
 
-            if (!empty($moveup)) {
-                if ($movecourse = $DB->get_record('course', array('id' => $moveup))) {
-                    $swapcourse = $DB->get_record('course', array('sortorder' => $movecourse->sortorder - 1));
-                }
-            } else {
-                if ($movecourse = $DB->get_record('course', array('id' => $movedown))) {
-                    $swapcourse = $DB->get_record('course', array('sortorder' => $movecourse->sortorder + 1));
-                }
+        if (!empty($moveup)) {
+            if ($movecourse = $DB->get_record('course', array('id' => $moveup))) {
+                $swapcourse = $DB->get_record('course', array('sortorder' => $movecourse->sortorder - 1));
             }
-            if ($swapcourse and $movecourse) {
-                // check course's category
-                if ($movecourse->category != $id) {
-                    print_error('coursedoesnotbelongtocategory');
-                }
-                $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $movecourse->id));
-                $DB->set_field('course', 'sortorder', $movecourse->sortorder, array('id' => $swapcourse->id));
+        } else {
+            if ($movecourse = $DB->get_record('course', array('id' => $movedown))) {
+                $swapcourse = $DB->get_record('course', array('sortorder' => $movecourse->sortorder + 1));
             }
         }
-
-    } // End of editing stuff
-
-    // Print headings
-    $numcategories = $DB->count_records('course_categories');
-
-    $stradministration = get_string('administration');
-    $strcategories = get_string('categories');
-    $strcategory = get_string('category');
-    $strcourses = get_string('courses');
-
-    if ($editingon && can_edit_in_category()) {
-        // Integrate into the admin tree only if the user can edit categories at the top level,
-        // otherwise the admin block does not appear to this user, and you get an error.
-        require_once($CFG->libdir . '/adminlib.php');
-        admin_externalpage_setup('coursemgmt', '', $urlparams, $CFG->wwwroot . '/course/category.php');
-        $PAGE->set_context($context);   // Ensure that we are actually showing blocks etc for the cat context
-
-        $settingsnode = $PAGE->settingsnav->find_active_node();
-        if ($settingsnode) {
-            $settingsnode->make_inactive();
-            $settingsnode->force_open();
-            $PAGE->navbar->add($settingsnode->text, $settingsnode->action);
+        if ($swapcourse and $movecourse) {
+            // check course's category
+            if ($movecourse->category != $id) {
+                print_error('coursedoesnotbelongtocategory');
+            }
+            $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $movecourse->id));
+            $DB->set_field('course', 'sortorder', $movecourse->sortorder, array('id' => $swapcourse->id));
         }
-        echo $OUTPUT->header();
-    } else {
-        $PAGE->set_title("$site->shortname: $category->name");
-        $PAGE->set_heading($site->fullname);
-        $PAGE->set_button(print_course_search('', true, 'navbar'));
-        $PAGE->set_pagelayout('coursecategory');
-        echo $OUTPUT->header();
     }
 
+} // End of editing stuff
+
+// Prepare the standard URL params for this page. We'll need them later.
+$urlparams = array('id' => $id);
+if ($page) {
+    $urlparams['page'] = $page;
+}
+if ($perpage) {
+    $urlparams['perpage'] = $perpage;
+}
+
+// Begin output
+if ($editingon && can_edit_in_category()) {
+    // Integrate into the admin tree only if the user can edit categories at the top level,
+    // otherwise the admin block does not appear to this user, and you get an error.
+    require_once($CFG->libdir . '/adminlib.php');
+    admin_externalpage_setup('coursemgmt', '', $urlparams, $CFG->wwwroot . '/course/category.php');
+    $PAGE->set_context($context);   // Ensure that we are actually showing blocks etc for the cat context
+
+    $settingsnode = $PAGE->settingsnav->find_active_node();
+    if ($settingsnode) {
+        $settingsnode->make_inactive();
+        $settingsnode->force_open();
+        $PAGE->navbar->add($settingsnode->text, $settingsnode->action);
+    }
+    echo $OUTPUT->header();
+} else {
+    $site = get_site();
+    $PAGE->set_title("$site->shortname: $category->name");
+    $PAGE->set_heading($site->fullname);
+    $PAGE->set_button(print_course_search('', true, 'navbar'));
+    $PAGE->set_pagelayout('coursecategory');
+    echo $OUTPUT->header();
+}
+
 /// Print the category selector
-    $displaylist = array();
-    $notused = array();
-    make_categories_list($displaylist, $notused);
+$displaylist = array();
+$notused = array();
+make_categories_list($displaylist, $notused);
 
-    echo '<div class="categorypicker">';
-    $select = new single_select(new moodle_url('category.php'), 'id', $displaylist, $category->id, null, 'switchcategory');
-    $select->set_label($strcategories.':');
-    echo $OUTPUT->render($select);
-    echo '</div>';
+echo '<div class="categorypicker">';
+$select = new single_select(new moodle_url('/course/category.php'), 'id', $displaylist, $category->id, null, 'switchcategory');
+$select->set_label(get_string('categories').':');
+echo $OUTPUT->render($select);
+echo '</div>';
 
 /// Print current category description
-    if (!$editingon && $category->description) {
-        echo $OUTPUT->box_start();
-        $options = new stdClass;
-        $options->noclean = true;
-        $options->para = false;
-        $options->overflowdiv = true;
-        if (!isset($category->descriptionformat)) {
-            $category->descriptionformat = FORMAT_MOODLE;
-        }
-        $text = file_rewrite_pluginfile_urls($category->description, 'pluginfile.php', $context->id, 'coursecat', 'description', null);
-        echo format_text($text, $category->descriptionformat, $options);
-        echo $OUTPUT->box_end();
+if (!$editingon && $category->description) {
+    echo $OUTPUT->box_start();
+    $options = new stdClass;
+    $options->noclean = true;
+    $options->para = false;
+    $options->overflowdiv = true;
+    if (!isset($category->descriptionformat)) {
+        $category->descriptionformat = FORMAT_MOODLE;
     }
-
-    if ($editingon && has_capability('moodle/category:manage', $context)) {
-        echo $OUTPUT->container_start('buttons');
-
-        // Print button to update this category
-        $options = array('id' => $category->id);
-        echo $OUTPUT->single_button(new moodle_url('/course/editcategory.php', $options), get_string('editcategorythis'), 'get');
-
-        // Print button for creating new categories
-        $options = array('parent' => $category->id);
-        echo $OUTPUT->single_button(new moodle_url('/course/editcategory.php', $options), get_string('addsubcategory'), 'get');
-
-        echo $OUTPUT->container_end();
+    $text = file_rewrite_pluginfile_urls($category->description, 'pluginfile.php', $context->id, 'coursecat', 'description', null);
+    echo format_text($text, $category->descriptionformat, $options);
+    echo $OUTPUT->box_end();
+}
+
+if ($editingon && $canmanage) {
+    echo $OUTPUT->container_start('buttons');
+
+    // Print button to update this category
+    $url = new moodle_url('/course/editcategory.php', array('id' => $category->id));
+    echo $OUTPUT->single_button($url, get_string('editcategorythis'), 'get');
+
+    // Print button for creating new categories
+    $url = new moodle_url('/course/editcategory.php', array('parent' => $category->id));
+    echo $OUTPUT->single_button($url, get_string('addsubcategory'), 'get');
+
+    echo $OUTPUT->container_end();
+}
+
+// Print out all the sub-categories
+// In order to view hidden subcategories the user must have the viewhiddencategories
+// capability in the current category.
+if (has_capability('moodle/category:viewhiddencategories', $context)) {
+    $categorywhere = '';
+} else {
+    $categorywhere = 'AND cc.visible = 1';
+}
+// We're going to preload the context for the subcategory as we know that we
+// need it later on for formatting.
+
+$ctxselect = context_helper::get_preload_record_columns_sql('ctx');
+$sql = "SELECT cc.*, $ctxselect
+          FROM {course_categories} cc
+          JOIN {context} ctx ON cc.id = ctx.instanceid
+         WHERE cc.parent = :parentid AND
+               ctx.contextlevel = :contextlevel
+               $categorywhere
+      ORDER BY cc.sortorder ASC";
+$subcategories = $DB->get_recordset_sql($sql, array('parentid' => $category->id, 'contextlevel' => CONTEXT_COURSECAT));
+// Prepare a table to display the sub categories.
+$table = new html_table;
+$table->attributes = array('border' => '0', 'cellspacing' => '2', 'cellpadding' => '4', 'class' => 'generalbox boxaligncenter category_subcategories');
+$table->head = array(new lang_string('subcategories'));
+$table->data = array();
+$baseurl = new moodle_url('/course/category.php');
+foreach ($subcategories as $subcategory) {
+    // Preload the context we will need it to format the category name shortly.
+    context_helper::preload_from_record($subcategory);
+    $context = get_context_instance(CONTEXT_COURSECAT, $subcategory->id);
+    // Prepare the things we need to create a link to the subcategory
+    $attributes = $subcategory->visible ? array() : array('class' => 'dimmed');
+    $text = format_string($subcategory->name, true, array('context' => $context));
+    // Add the subcategory to the table
+    $baseurl->param('id', $subcategory->id);
+    $table->data[] = array(html_writer::link($baseurl, $text, $attributes));
+}
+
+$subcategorieswereshown = (count($table->data) > 0);
+if ($subcategorieswereshown) {
+    echo html_writer::table($table);
+}
+
+// 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',
+        $totalcount, $page*$perpage, $perpage);
+$numcourses = count($courses);
+
+if (!$courses) {
+    if (empty($subcategorieswereshown)) {
+        echo $OUTPUT->heading(get_string("nocoursesyet"));
     }
 
-/// Print out all the sub-categories
-    if ($subcategories = $DB->get_records('course_categories', array('parent' => $category->id), 'sortorder ASC')) {
-        $firstentry = true;
-        foreach ($subcategories as $subcategory) {
-            if ($subcategory->visible || has_capability('moodle/category:viewhiddencategories', $context)) {
-                $subcategorieswereshown = true;
-                if ($firstentry) {
-                    echo '<table border="0" cellspacing="2" cellpadding="4" class="generalbox boxaligncenter">';
-                    echo '<tr><th scope="col">'.get_string('subcategories').'</th></tr>';
-                    echo '<tr><td style="white-space: nowrap">';
-                    $firstentry = false;
-                }
-                $catlinkcss = $subcategory->visible ? '' : ' class="dimmed" ';
-                echo '<a '.$catlinkcss.' href="category.php?id='.$subcategory->id.'">'.
-                     format_string($subcategory->name, true, array('context' => get_context_instance(CONTEXT_COURSECAT, $subcategory->id))).'</a><br />';
-            }
-        }
-        if (!$firstentry) {
-            echo '</td></tr></table>';
-            echo '<br />';
-        }
-    }
+} else if ($numcourses <= COURSE_MAX_SUMMARIES_PER_PAGE and !$page and !$editingon) {
+    echo $OUTPUT->box_start('courseboxes');
+    print_courses($category);
+    echo $OUTPUT->box_end();
 
-/// 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',
-            $totalcount, $page*$perpage, $perpage);
-    $numcourses = count($courses);
+} else {
+    echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "/course/category.php?id=$category->id&perpage=$perpage");
 
-    if (!$courses) {
-        if (empty($subcategorieswereshown)) {
-            echo $OUTPUT->heading(get_string("nocoursesyet"));
-        }
+    echo '<form id="movecourses" action="category.php" method="post"><div>';
+    echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
+    echo '<table border="0" cellspacing="2" cellpadding="4" class="generalbox boxaligncenter"><tr>';
+    echo '<th class="header" scope="col">'.get_string('courses').'</th>';
+    if ($editingon) {
+        echo '<th class="header" scope="col">'.get_string('edit').'</th>';
+        echo '<th class="header" scope="col">'.get_string('select').'</th>';
+    } else {
+        echo '<th class="header" scope="col">&nbsp;</th>';
+    }
+    echo '</tr>';
 
-    } else if ($numcourses <= COURSE_MAX_SUMMARIES_PER_PAGE and !$page and !$editingon) {
-        echo $OUTPUT->box_start('courseboxes');
-        print_courses($category);
-        echo $OUTPUT->box_end();
+    $count = 0;
+    $abletomovecourses = false;  // for now
 
-    } else {
-        echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "/course/category.php?id=$category->id&perpage=$perpage");
-
-        $strcourses = get_string('courses');
-        $strselect = get_string('select');
-        $stredit = get_string('edit');
-        $strdelete = get_string('delete');
-        $strbackup = get_string('backup');
-        $strrestore = get_string('restore');
-        $strmoveup = get_string('moveup');
-        $strmovedown = get_string('movedown');
-        $strupdate = get_string('update');
-        $strhide = get_string('hide');
-        $strshow = get_string('show');
-        $strsummary = get_string('summary');
-        $strsettings = get_string('settings');
-
-
-        echo '<form id="movecourses" action="category.php" method="post"><div>';
-        echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
-        echo '<table border="0" cellspacing="2" cellpadding="4" class="generalbox boxaligncenter"><tr>';
-        echo '<th class="header" scope="col">'.$strcourses.'</th>';
-        if ($editingon) {
-            echo '<th class="header" scope="col">'.$stredit.'</th>';
-            echo '<th class="header" scope="col">'.$strselect.'</th>';
+    // Checking if we are at the first or at the last page, to allow courses to
+    // be moved up and down beyond the paging border
+    if ($totalcount > $perpage) {
+        $atfirstpage = ($page == 0);
+        if ($perpage > 0) {
+            $atlastpage = (($page + 1) == ceil($totalcount / $perpage));
         } else {
-            echo '<th class="header" scope="col">&nbsp;</th>';
+            $atlastpage = true;
         }
-        echo '</tr>';
+    } else {
+        $atfirstpage = true;
+        $atlastpage = true;
+    }
 
+    $baseurl = new moodle_url('/course/category.php', $urlparams + array('sesskey' => sesskey()));
+    foreach ($courses as $acourse) {
+        $coursecontext = get_context_instance(CONTEXT_COURSE, $acourse->id);
 
-        $count = 0;
-        $abletomovecourses = false;  // for now
+        $count++;
+        $up = ($count > 1 || !$atfirstpage);
+        $down = ($count < $numcourses || !$atlastpage);
 
-        // Checking if we are at the first or at the last page, to allow courses to
-        // be moved up and down beyond the paging border
-        if ($totalcount > $perpage) {
-            $atfirstpage = ($page == 0);
-            if ($perpage > 0) {
-                $atlastpage = (($page + 1) == ceil($totalcount / $perpage));
-            } else {
-                $atlastpage = true;
+        $linkcss = $acourse->visible ? '' : ' class="dimmed" ';
+        echo '<tr>';
+        $coursename = get_course_display_name_for_list($acourse);
+        echo '<td><a '.$linkcss.' href="view.php?id='.$acourse->id.'">'. format_string($coursename) .'</a></td>';
+        if ($editingon) {
+            echo '<td>';
+            if (has_capability('moodle/course:update', $coursecontext)) {
+                $url = new moodle_url('/course/edit.php', array('id' => $acourse->id, 'category' => $id, 'returnto' => 'category'));
+                echo $OUTPUT->action_icon($url, new pix_icon('t/edit', get_string('settings')));
             }
-        } else {
-            $atfirstpage = true;
-            $atlastpage = true;
-        }
 
-        foreach ($courses as $acourse) {
-            $coursecontext = get_context_instance(CONTEXT_COURSE, $acourse->id);
-
-            $count++;
-            $up = ($count > 1 || !$atfirstpage);
-            $down = ($count < $numcourses || !$atlastpage);
-
-            $linkcss = $acourse->visible ? '' : ' class="dimmed" ';
-            echo '<tr>';
-            $coursename = get_course_display_name_for_list($acourse);
-            echo '<td><a '.$linkcss.' href="view.php?id='.$acourse->id.'">'. format_string($coursename) .'</a></td>';
-            if ($editingon) {
-                echo '<td>';
-                if (has_capability('moodle/course:update', $coursecontext)) {
-                    echo $OUTPUT->action_icon(new moodle_url('/course/edit.php',
-                            array('id' => $acourse->id, 'category' => $id, 'returnto' => 'category')),
-                            new pix_icon('t/edit', $strsettings));
-                }
+            // role assignment link
+            if (has_capability('moodle/course:enrolreview', $coursecontext)) {
+                $url = new moodle_url('/enrol/users.php', array('id' => $acourse->id));
+                echo $OUTPUT->action_icon($url, new pix_icon('i/users', get_string('enrolledusers', 'enrol')));
+            }
 
-                // role assignment link
-                if (has_capability('moodle/course:enrolreview', $coursecontext)) {
-                    echo $OUTPUT->action_icon(new moodle_url('/enrol/users.php', array('id' => $acourse->id)),
-                            new pix_icon('i/users', get_string('enrolledusers', 'enrol')));
-                }
+            if (can_delete_course($acourse->id)) {
+                $url = new moodle_url('/course/delete.php', array('id' => $acourse->id));
+                echo $OUTPUT->action_icon($url, new pix_icon('t/delete', get_string('delete')));
+            }
 
-                if (can_delete_course($acourse->id)) {
-                    echo $OUTPUT->action_icon(new moodle_url('/course/delete.php', array('id' => $acourse->id)),
-                            new pix_icon('t/delete', $strdelete));
+            // MDL-8885, users with no capability to view hidden courses, should not be able to lock themselves out
+            if (has_capability('moodle/course:visibility', $coursecontext) && has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
+                if (!empty($acourse->visible)) {
+                    $url = new moodle_url($baseurl, array('hide' => $acourse->id));
+                    echo $OUTPUT->action_icon($url, new pix_icon('t/hide', get_string('hide')));
+                } else {
+                    $url = new moodle_url($baseurl, array('show' => $acourse->id));
+                    echo $OUTPUT->action_icon($url, new pix_icon('t/show', get_string('show')));
                 }
+            }
 
-                // MDL-8885, users with no capability to view hidden courses, should not be able to lock themselves out
-                if (has_capability('moodle/course:visibility', $coursecontext) && has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
-                    if (!empty($acourse->visible)) {
-                        echo $OUTPUT->action_icon(new moodle_url('/course/category.php',
-                                array('id' => $category->id, 'page' => $page, 'perpage' => $perpage,
-                                        'hide' => $acourse->id, 'sesskey' => sesskey())),
-                                new pix_icon('t/hide', $strhide));
-                    } else {
-                        echo $OUTPUT->action_icon(new moodle_url('/course/category.php',
-                                array('id' => $category->id, 'page' => $page, 'perpage' => $perpage,
-                                        'show' => $acourse->id, 'sesskey' => sesskey())),
-                                new pix_icon('t/show', $strshow));
-                    }
-                }
+            if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
+                $url = new moodle_url('/backup/backup.php', array('id' => $acourse->id));
+                echo $OUTPUT->action_icon($url, new pix_icon('t/backup', get_string('backup')));
+            }
 
-                if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
-                    echo $OUTPUT->action_icon(new moodle_url('/backup/backup.php', array('id' => $acourse->id)),
-                            new pix_icon('t/backup', $strbackup));
-                }
+            if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
+                $url = new moodle_url('/backup/restorefile.php', array('contextid' => $coursecontext->id));
+                echo $OUTPUT->action_icon($url, new pix_icon('t/restore', get_string('restore')));
+            }
 
-                if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
-                    echo $OUTPUT->action_icon(new moodle_url('/backup/restorefile.php', array('contextid' => $coursecontext->id)),
-                            new pix_icon('t/restore', $strrestore));
+            if ($canmanage) {
+                if ($up) {
+                    $url = new moodle_url($baseurl, array('moveup' => $acourse->id));
+                    echo $OUTPUT->action_icon($url, new pix_icon('t/up', get_string('moveup')));
                 }
 
-                if (has_capability('moodle/category:manage', $context)) {
-                    if ($up) {
-                        echo $OUTPUT->action_icon(new moodle_url('/course/category.php',
-                                array('id' => $category->id, 'page' => $page, 'perpage' => $perpage,
-                                        'moveup' => $acourse->id, 'sesskey' => sesskey())),
-                                new pix_icon('t/up', $strmoveup));
-                    }
-
-                    if ($down) {
-                        echo $OUTPUT->action_icon(new moodle_url('/course/category.php',
-                                array('id' => $category->id, 'page' => $page, 'perpage' => $perpage,
-                                        'movedown' => $acourse->id, 'sesskey' => sesskey())),
-                                new pix_icon('t/down', $strmovedown));
-                    }
-                    $abletomovecourses = true;
+                if ($down) {
+                    $url = new moodle_url($baseurl, array('movedown' => $acourse->id));
+                    echo $OUTPUT->action_icon($url, new pix_icon('t/down', get_string('movedown')));
                 }
+                $abletomovecourses = true;
+            }
 
-                echo '</td>';
-                echo '<td align="center">';
-                echo '<input type="checkbox" name="c'.$acourse->id.'" />';
-                echo '</td>';
-            } else {
-                echo '<td align="right">';
-                // print enrol info
-                if ($icons = enrol_get_course_info_icons($acourse)) {
-                    foreach ($icons as $pix_icon) {
-                        echo $OUTPUT->render($pix_icon);
-                    }
-                }
-                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') . '" />',
-                        new popup_action('click', $link, 'courseinfo'), array('title'=>$strsummary));
+            echo '</td>';
+            echo '<td align="center">';
+            echo '<input type="checkbox" name="c'.$acourse->id.'" />';
+            echo '</td>';
+        } else {
+            echo '<td align="right">';
+            // print enrol info
+            if ($icons = enrol_get_course_info_icons($acourse)) {
+                foreach ($icons as $pix_icon) {
+                    echo $OUTPUT->render($pix_icon);
                 }
-                echo "</td>";
             }
-            echo "</tr>";
-        }
-
-        if ($abletomovecourses) {
-            $movetocategories = array();
-            $notused = array();
-            make_categories_list($movetocategories, $notused, 'moodle/category:manage');
-            $movetocategories[$category->id] = get_string('moveselectedcoursesto');
-            echo '<tr><td colspan="3" align="right">';
-            echo html_writer::select($movetocategories, 'moveto', $category->id, null, array('id'=>'movetoid'));
-            $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('movecourses', 'movetoid', false));
-            echo '<input type="hidden" name="id" value="'.$category->id.'" />';
-            echo '</td></tr>';
+            if (!empty($acourse->summary)) {
+                $url = new moodle_url("/course/info.php?id=$acourse->id");
+                echo $OUTPUT->action_link($url, '<img alt="'.get_string('info').'" class="icon" src="'.$OUTPUT->pix_url('i/info') . '" />',
+                    new popup_action('click', $url, 'courseinfo'), array('title'=>get_string('summary')));
+            }
+            echo "</td>";
         }
-
-        echo '</table>';
-        echo '</div></form>';
-        echo '<br />';
+        echo "</tr>";
     }
 
-    echo '<div class="buttons">';
-    if (has_capability('moodle/category:manage', $context) and $numcourses > 1) {
-    /// Print button to re-sort courses by name
-        unset($options);
-        $options['id'] = $category->id;
-        $options['resort'] = 'name';
-        $options['sesskey'] = sesskey();
-        echo $OUTPUT->single_button(new moodle_url('category.php', $options), get_string('resortcoursesbyname'), 'get');
+    if ($abletomovecourses) {
+        $movetocategories = array();
+        $notused = array();
+        make_categories_list($movetocategories, $notused, 'moodle/category:manage');
+        $movetocategories[$category->id] = get_string('moveselectedcoursesto');
+        echo '<tr><td colspan="3" align="right">';
+        echo html_writer::select($movetocategories, 'moveto', $category->id, null, array('id'=>'movetoid'));
+        $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('movecourses', 'movetoid', false));
+        echo '<input type="hidden" name="id" value="'.$category->id.'" />';
+        echo '</td></tr>';
     }
 
-    if (has_capability('moodle/course:create', $context)) {
-    /// Print button to create a new course
-        unset($options);
-        $options['category'] = $category->id;
-        $options['returnto'] = 'category';
-        echo $OUTPUT->single_button(new moodle_url('edit.php', $options), get_string('addnewcourse'), 'get');
-    }
+    echo '</table>';
+    echo '</div></form>';
+    echo '<br />';
+}
 
-    if (!empty($CFG->enablecourserequests) && $category->id == $CFG->defaultrequestcategory) {
-        print_course_request_buttons(get_context_instance(CONTEXT_SYSTEM));
-    }
-    echo '</div>';
+echo '<div class="buttons">';
+if ($canmanage and $numcourses > 1) {
+    // Print button to re-sort courses by name
+    $url = new moodle_url('/course/category.php', array('id' => $category->id, 'resort' => 'name', 'sesskey' => sesskey()));
+    echo $OUTPUT->single_button($url, get_string('resortcoursesbyname'), 'get');
+}
+
+if (has_capability('moodle/course:create', $context)) {
+    // Print button to create a new course
+    $url = new moodle_url('/course/edit.php', array('category' => $category->id, 'returnto' => 'category'));
+    echo $OUTPUT->single_button($url, get_string('addnewcourse'), 'get');
+}
 
-    print_course_search();
+if (!empty($CFG->enablecourserequests) && $category->id == $CFG->defaultrequestcategory) {
+    print_course_request_buttons(get_context_instance(CONTEXT_SYSTEM));
+}
+echo '</div>';
 
-    echo $OUTPUT->footer();
+print_course_search();
 
+echo $OUTPUT->footer();
index 3be2c38..4d9542a 100644 (file)
@@ -18,17 +18,21 @@ M.core_completion.init = function(Y) {
 
         } else {
             var current = args.state.get('value');
-
+            var modulename = args.modulename.get('value');
             if (current == 1) {
+                var altstr = M.str.completion['completion-alt-manual-y'].replace('{$a}', modulename);
+                var titlestr = M.str.completion['completion-title-manual-y'].replace('{$a}', modulename);
                 args.state.set('value', 0);
                 args.image.set('src', M.util.image_url('i/completion-manual-y', 'moodle'));
-                args.image.set('alt', M.str.completion['completion-alt-manual-y']);
-                args.image.set('title', M.str.completion['completion-title-manual-y']);
+                args.image.set('alt', altstr);
+                args.image.set('title', titlestr);
             } else {
+                var altstr = M.str.completion['completion-alt-manual-n'].replace('{$a}', modulename);
+                var titlestr = M.str.completion['completion-title-manual-n'].replace('{$a}', modulename);
                 args.state.set('value', 1);
                 args.image.set('src', M.util.image_url('i/completion-manual-n', 'moodle'));
-                args.image.set('alt', M.str.completion['completion-alt-manual-n']);
-                args.image.set('title', M.str.completion['completion-title-manual-n']);
+                args.image.set('alt', altstr);
+                args.image.set('title', titlestr);
             }
         }
 
@@ -48,6 +52,7 @@ M.core_completion.init = function(Y) {
         var completionstate = 0;
         var state = null;
         var image = null;
+        var modulename = null;
 
         var inputs = Y.Node.getDOMNode(form).getElementsByTagName('input');
         for (var i=0; i<inputs.length; i++) {
@@ -59,6 +64,9 @@ M.core_completion.init = function(Y) {
                      completionstate = inputs[i].value;
                      state = Y.one(inputs[i]);
                      break;
+                  case 'modulename':
+                     modulename = Y.one(inputs[i]);
+                     break;
             }
             if (inputs[i].type == 'image') {
                 image = Y.one(inputs[i]);
@@ -76,7 +84,7 @@ M.core_completion.init = function(Y) {
                 success: handle_success,
                 failure: handle_failure
             },
-            arguments: {state: state, image: image, ajax: ajax}
+            arguments: {state: state, image: image, ajax: ajax, modulename: modulename}
         };
 
         Y.use('io-base', function(Y) {
index 053d8bb..174872c 100644 (file)
@@ -65,18 +65,6 @@ if ($id) { // editing course
 // Prepare course and the editor
 $editoroptions = array('maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes'=>$CFG->maxbytes, 'trusttext'=>false, 'noclean'=>true);
 if (!empty($course)) {
-    $allowedmods = array();
-    if ($am = $DB->get_records('course_allowed_modules', array('course'=>$course->id))) {
-        foreach ($am as $m) {
-            $allowedmods[] = $m->module;
-        }
-    } else {
-        // 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;
     //add context for editor
     $editoroptions['context'] = $coursecontext;
     $course = file_prepare_standard_editor($course, 'summary', $editoroptions, $coursecontext, 'course', 'summary', 0);
index d87c9d1..44ed742 100644 (file)
@@ -256,48 +256,6 @@ class course_edit_form extends moodleform {
             $mform->setDefault('completionstartonenrol',0);
         }
 
-//--------------------------------------------------------------------------------
-        if (has_capability('moodle/site:config', $systemcontext)) {
-            if (((!empty($course->requested) && $CFG->restrictmodulesfor == 'requested') || $CFG->restrictmodulesfor == 'all')) {
-                $mform->addElement('header', '', get_string('restrictmodules'));
-
-                $options = array();
-                $options['0'] = get_string('no');
-                $options['1'] = get_string('yes');
-                $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
-                if (!empty($CFG->restrictbydefault)) {
-                    $mform->setDefault('restrictmodules', 1);
-                }
-
-                $mods = array(0=>get_string('allownone'));
-                $allmods = $DB->get_records_menu('modules', array('visible' => 1),
-                        'name', 'id, name');
-                foreach ($allmods as $key => $value) {
-                    // Add module to list unless it cannot be added by users anyway
-                    if (plugin_supports('mod', $value, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER) !==
-                            MOD_ARCHETYPE_SYSTEM) {
-                        $mods[$key] = get_string('pluginname', $value);
-                    }
-                }
-                $mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple'=>'multiple', 'size'=>'10'));
-                $mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0);
-                // defaults are already in $course
-            } else {
-                // remove any mod restriction
-                $mform->addElement('hidden', 'restrictmodules', 0);
-                $mform->setType('restrictmodules', PARAM_INT);
-            }
-        } else {
-            $mform->addElement('hidden', 'restrictmodules');
-            $mform->setType('restrictmodules', PARAM_INT);
-            if (empty($course->id)) {
-                $mform->setConstant('restrictmodules', (int)($CFG->restrictmodulesfor == 'all'));
-            } else {
-                // keep previous
-                $mform->setConstant('restrictmodules', $course->restrictmodules);
-            }
-        }
-
 /// customizable role names in this course
 //--------------------------------------------------------------------------------
         $mform->addElement('header','rolerenaming', get_string('rolerenaming'));
index 9752cce..ff4bad5 100644 (file)
@@ -1,9 +1,29 @@
 <?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/>.
+
 /**
  * Page for creating or editing course category name/parent/description.
  * When called with an id parameter, edits the category with that id.
  * Otherwise it creates a new category with default parent from the parent
  * parameter, which may be 0.
+ *
+ * @package    core
+ * @subpackage course
+ * @copyright  2007 Nicolas Connault
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  */
 
 require_once('../config.php');
@@ -108,6 +128,21 @@ if ($mform->is_cancelled()) {
     redirect('category.php?id='.$newcategory->id.'&categoryedit=on');
 }
 
+// Unfortunately the navigation never generates correctly for this page because technically
+// this page doesn't actually exist on the navigation you get here through the course
+// management page.
+try {
+    // First up we'll try to make the course management page active seeing as that is
+    // where the user thinks they are.
+    // The big prolem here is that the course management page is a common page
+    // for both editing users and common users.
+    $PAGE->settingsnav->get('root')->get('courses')->get('coursemgmt')->make_active();
+} catch (Exception $ex) {
+    // Failing that we'll override the URL, not as accurate and chances are things
+    // won't be 100% correct all the time but should work most times.
+    navigation_node::override_active_url(new moodle_url('/course/index.php', array('categoryedit' => 'on')));
+}
+
 $PAGE->set_title($title);
 $PAGE->set_heading($fullname);
 echo $OUTPUT->header();
index e873128..ce1466a 100644 (file)
@@ -177,6 +177,7 @@ if (!$categories = get_categories()) {    /// No category yet!
     $tempcat->context = get_context_instance(CONTEXT_COURSECAT, $tempcat->id);
     mark_context_dirty('/'.SYSCONTEXTID);
     fix_course_sortorder(); // Required to build course_categories.depth and .path.
+    set_config('defaultrequestcategory', $tempcat->id);
 }
 
 /// Move a category to a new parent if required
@@ -394,4 +395,4 @@ function print_category_edit($category, $displaylist, $parentslist, $depth=-1, $
             print_category_edit($cat, $displaylist, $parentslist, $depth+1, $up, $down);
         }
     }
-}
\ No newline at end of file
+}
index f35bbfa..dfc33df 100644 (file)
@@ -932,7 +932,7 @@ function print_recent_activity($course) {
 
 /// Next, have there been any modifications to the course structure?
 
-    $modinfo =& get_fast_modinfo($course);
+    $modinfo = get_fast_modinfo($course);
 
     $changelist = array();
 
@@ -1730,9 +1730,9 @@ function print_section($course, $section, $mods, $modnamesused, $absolute=false,
                 }
                 if ($completionicon) {
                     $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
-                    $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion'));
+                    $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion', $mod->name));
                     if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
-                        $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion'));
+                        $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion', $mod->name));
                         $newstate =
                             $completiondata->completionstate==COMPLETION_COMPLETE
                             ? COMPLETION_INCOMPLETE
@@ -1751,6 +1751,7 @@ function print_section($course, $section, $mods, $modnamesused, $absolute=false,
                         echo "
 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
 <input type='hidden' name='id' value='{$mod->id}' />
+<input type='hidden' name='modulename' value='".s($mod->name)."' />
 <input type='hidden' name='sesskey' value='".sesskey()."' />
 <input type='hidden' name='completionstate' value='$newstate' />
 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
@@ -1815,65 +1816,49 @@ function print_section_add_menus($course, $section, $modnames, $vertical=false,
         return false;
     }
 
-    $urlbase = "/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey().'&add=';
+    // Retrieve all modules with associated metadata
+    $modules = get_module_metadata($course, $modnames);
 
+    // We'll sort resources and activities into two lists
     $resources = array();
     $activities = array();
 
-    foreach($modnames as $modname=>$modnamestr) {
-        if (!course_allowed_module($course, $modname)) {
-            continue;
-        }
+    // We need to add the section section to the link for each module
+    $sectionlink = '&section=' . $section;
 
-        $libfile = "$CFG->dirroot/mod/$modname/lib.php";
-        if (!file_exists($libfile)) {
-            continue;
-        }
-        include_once($libfile);
-        $gettypesfunc =  $modname.'_get_types';
-        if (function_exists($gettypesfunc)) {
+    foreach ($modules as $module) {
+        if (isset($module->types)) {
+            // This module has a subtype
             // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
-            if ($types = $gettypesfunc()) {
-                $menu = array();
-                $atype = null;
-                $groupname = null;
-                foreach($types as $type) {
-                    if ($type->typestr === '--') {
-                        continue;
-                    }
-                    if (strpos($type->typestr, '--') === 0) {
-                        $groupname = str_replace('--', '', $type->typestr);
-                        continue;
-                    }
-                    $type->type = str_replace('&amp;', '&', $type->type);
-                    if ($type->modclass == MOD_CLASS_RESOURCE) {
-                        $atype = MOD_CLASS_RESOURCE;
-                    }
-                    $menu[$urlbase.$type->type] = $type->typestr;
+            $subtypes = array();
+            foreach ($module->types as $subtype) {
+                $subtypes[$subtype->link . $sectionlink] = $subtype->title;
+            }
+
+            // Sort module subtypes into the list
+            if (!empty($module->title)) {
+                // This grouping has a name
+                if ($module->archetype == MOD_CLASS_RESOURCE) {
+                    $resources[] = array($module->title=>$subtypes);
+                } else {
+                    $activities[] = array($module->title=>$subtypes);
                 }
-                if (!is_null($groupname)) {
-                    if ($atype == MOD_CLASS_RESOURCE) {
-                        $resources[] = array($groupname=>$menu);
-                    } else {
-                        $activities[] = array($groupname=>$menu);
-                    }
+            } else {
+                // This grouping does not have a name
+                if ($module->archetype == MOD_CLASS_RESOURCE) {
+                    $resources = array_merge($resources, $subtypes);
                 } else {
-                    if ($atype == MOD_CLASS_RESOURCE) {
-                        $resources = array_merge($resources, $menu);
-                    } else {
-                        $activities = array_merge($activities, $menu);
-                    }
+                    $activities = array_merge($activities, $subtypes);
                 }
             }
         } else {
-            $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
-            if ($archetype == MOD_ARCHETYPE_RESOURCE) {
-                $resources[$urlbase.$modname] = $modnamestr;
-            } else if ($archetype === MOD_ARCHETYPE_SYSTEM) {
+            // This module has no subtypes
+            if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
+                $resources[$module->link . $sectionlink] = $module->title;
+            } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
                 // System modules cannot be added by user, do not add to dropdown
             } else {
-                // all other archetypes are considered activity
-                $activities[$urlbase.$modname] = $modnamestr;
+                $activities[$module->link . $sectionlink] = $module->title;
             }
         }
     }
@@ -1912,6 +1897,96 @@ function print_section_add_menus($course, $section, $modnames, $vertical=false,
     }
 }
 
+/**
+ * Retrieve all metadata for the requested modules
+ *
+ * @param object $course The Course
+ * @param array $modnames An array containing the list of modules and their
+ * names
+ * @return array A list of stdClass objects containing metadata about each
+ * module
+ */
+function get_module_metadata($course, $modnames) {
+    global $CFG, $OUTPUT;
+
+    // get_module_metadata will be called once per section on the page and courses may show
+    // different modules to one another
+    static $modlist = array();
+    if (!isset($modlist[$course->id])) {
+        $modlist[$course->id] = array();
+    }
+
+    $return = array();
+    $urlbase = "/course/mod.php?id=$course->id&sesskey=".sesskey().'&add=';
+    foreach($modnames as $modname => $modnamestr) {
+        if (!course_allowed_module($course, $modname)) {
+            continue;
+        }
+        if (isset($modlist[$modname])) {
+            // This module is already cached
+            $return[$modname] = $modlist[$course->id][$modname];
+            continue;
+        }
+
+        // Include the module lib
+        $libfile = "$CFG->dirroot/mod/$modname/lib.php";
+        if (!file_exists($libfile)) {
+            continue;
+        }
+        include_once($libfile);
+
+        // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
+        $gettypesfunc =  $modname.'_get_types';
+        if (function_exists($gettypesfunc)) {
+            if ($types = $gettypesfunc()) {
+                $group = new stdClass();
+                $group->name = $modname;
+                $group->icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
+                foreach($types as $type) {
+                    if ($type->typestr === '--') {
+                        continue;
+                    }
+                    if (strpos($type->typestr, '--') === 0) {
+                        $group->title = str_replace('--', '', $type->typestr);
+                        continue;
+                    }
+                    // Set the Sub Type metadata
+                    $subtype = new stdClass();
+                    $subtype->title = $type->typestr;
+                    $subtype->type = str_replace('&amp;', '&', $type->type);
+                    $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
+                    $subtype->archetype = $type->modclass;
+
+                    // The group archetype should match the subtype archetypes and all subtypes
+                    // should have the same archetype
+                    $group->archetype = $subtype->archetype;
+
+                    if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
+                        $subtype->help = get_string('help' . $subtype->name, $modname);
+                    }
+                    $subtype->link = $urlbase . $subtype->type;
+                    $group->types[] = $subtype;
+                }
+                $modlist[$course->id][$modname] = $group;
+            }
+        } else {
+            $module = new stdClass();
+            $module->title = get_string('modulename', $modname);
+            $module->name = $modname;
+            $module->link = $urlbase . $modname;
+            $module->icon = $OUTPUT->pix_icon('icon', '', $module->name, array('class' => 'icon'));
+            if (get_string_manager()->string_exists('modulename_help', $modname)) {
+                $module->help = get_string('modulename_help', $modname);
+            }
+            $module->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
+            $modlist[$course->id][$modname] = $module;
+        }
+        $return[$modname] = $modlist[$course->id][$modname];
+    }
+
+    return $return;
+}
+
 /**
  * Return the course category context for the category with id $categoryid, except
  * that if $categoryid is 0, return the system context.
@@ -3316,58 +3391,37 @@ function course_format_name ($course,$max=100) {
     }
 }
 
-function update_restricted_mods($course, $mods) {
-    global $DB;
-
-/// Delete all the current restricted list
-    $DB->delete_records('course_allowed_modules', array('course'=>$course->id));
-
-    if (empty($course->restrictmodules)) {
-        return;   // We're done
-    }
-
-/// Insert the new list of restricted mods
-    foreach ($mods as $mod) {
-        if ($mod == 0) {
-            continue; // this is the 'allow none' option
-        }
-        $am = new stdClass();
-        $am->course = $course->id;
-        $am->module = $mod;
-        $DB->insert_record('course_allowed_modules',$am);
-    }
-}
-
 /**
- * This function will take an int (module id) or a string (module name)
- * and return true or false, whether it's allowed in the given course (object)
- * $mod is not allowed to be an object, as the field for the module id is inconsistent
- * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
+ * Is the user allowed to add this type of module to this course?
+ * @param object $course the course settings. Only $course->id is used.
+ * @param string $modname the module name. E.g. 'forum' or 'quiz'.
+ * @return bool whether the current user is allowed to add this type of module to this course.
  */
-
-function course_allowed_module($course,$mod) {
+function course_allowed_module($course, $modname) {
     global $DB;
 
-    if (empty($course->restrictmodules)) {
-        return true;
+    if (is_numeric($modname)) {
+        throw new coding_exception('Function course_allowed_module no longer
+                supports numeric module ids. Please update your code to pass the module name.');
     }
 
-    // Admins and admin-like people who can edit everything can also add anything.
-    // Originally there was a course: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;
-    }
+    $capability = 'mod/' . $modname . ':addinstance';
+    if (!get_capability_info($capability)) {
+        // Debug warning that the capability does not exist, but no more than once per page.
+        static $warned = array();
+        $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
+        if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
+            debugging('The module ' . $modname . ' does not define the standard capability ' .
+                    $capability , DEBUG_DEVELOPER);
+            $warned[$modname] = 1;
+        }
 
-    if (is_numeric($mod)) {
-        $modid = $mod;
-    } else if (is_string($mod)) {
-        $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
-    }
-    if (empty($modid)) {
-        return false;
+        // If the capability does not exist, the module can always be added.
+        return true;
     }
 
-    return $DB->record_exists('course_allowed_modules', array('course'=>$course->id, 'module'=>$modid));
+    $coursecontext = context_course::instance($course->id);
+    return has_capability($capability, $coursecontext);
 }
 
 /**
@@ -3835,17 +3889,6 @@ function create_course($data, $editoroptions = NULL) {
 
     fix_course_sortorder();
 
-    // update module restrictions
-    if ($course->restrictmodules) {
-        if (isset($data->allowedmods)) {
-            update_restricted_mods($course, $data->allowedmods);
-        } else {
-            if (!empty($CFG->defaultallowedmodules)) {
-                update_restricted_mods($course, explode(',', $CFG->defaultallowedmodules));
-            }
-        }
-    }
-
     // new context created - better mark it as dirty
     mark_context_dirty($context->path);
 
@@ -3924,11 +3967,6 @@ function update_course($data, $editoroptions = NULL) {
     // 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, $data->allowedmods);
-    }
-
     // Save any custom role names.
     save_local_role_names($course->id, $data);
 
@@ -4241,9 +4279,6 @@ class course_request {
 
         // Set misc settings
         $data->requested = 1;
-        if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) {
-            $data->restrictmodules = 1;
-        }
 
         // Apply course default settings
         $data->format             = $courseconfig->format;
index 9ed3f5d..63ea832 100644 (file)
@@ -59,7 +59,7 @@ if (!empty($add)) {
 
     $cw = get_course_section($section, $course->id);
 
-    if (!course_allowed_module($course, $module->id)) {
+    if (!course_allowed_module($course, $module->name)) {
         print_error('moduledisable');
     }
 
index 134cce0..f33ef54 100644 (file)
@@ -78,11 +78,11 @@ $PAGE->navbar->add($userinfo);
 $PAGE->set_title("$course->shortname: $strrecentactivity");
 $PAGE->set_heading($course->fullname);
 echo $OUTPUT->header();
-echo $OUTPUT->heading(format_string($course->fullname) . ": $userinfo", 3);
+echo $OUTPUT->heading(format_string($course->fullname) . ": $userinfo", 2);
 
 $mform->display();
 
-$modinfo =& get_fast_modinfo($course);
+$modinfo = get_fast_modinfo($course);
 get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
 
 if (has_capability('moodle/course:viewhiddensections', $context)) {
@@ -238,8 +238,8 @@ if (!empty($activities)) {
                 $modfullname = $modnames[$cm->modname];
 
                 $image = "<img src=\"" . $OUTPUT->pix_url('icon', $cm->modname) . "\" class=\"icon\" alt=\"$modfullname\" />";
-                echo "<h4>$image $modfullname".
-                     " <a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id=$cm->id\" $linkformat>$name</a></h4>";
+                echo "<h3>$image $modfullname".
+                     " <a href=\"$CFG->wwwroot/mod/$cm->modname/view.php?id=$cm->id\" $linkformat>$name</a></h3>";
            }
 
         } else {
@@ -269,7 +269,7 @@ if (!empty($activities)) {
 
 } else {
 
-    echo '<h4><center>' . get_string('norecentactivity') . '</center></h2>';
+    echo '<h3><center>' . get_string('norecentactivity') . '</center></h3>';
 
 }
 
index ce8b0f7..cb899f0 100644 (file)
@@ -27,6 +27,9 @@ class course_reset_form extends moodleform {
         $mform->addElement('header', 'rolesheader', get_string('roles'));
 
         $roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, $COURSE->id));
+        $roles[0] = get_string('noroles', 'role');
+        $roles = array_reverse($roles, true);
+
         $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');
index 1e191a3..246577c 100644 (file)
 <?php
-
-/// Displays external information about a course
-
-    require_once("../config.php");
-    require_once("lib.php");
-
-    $search    = optional_param('search', '', PARAM_RAW);  // search words
-    $page      = optional_param('page', 0, PARAM_INT);     // which page to show
-    $perpage   = optional_param('perpage', 10, PARAM_INT); // how many per page
-    $moveto    = optional_param('moveto', 0, PARAM_INT);   // move to category
-    $edit      = optional_param('edit', -1, PARAM_BOOL);
-    $hide      = optional_param('hide', 0, PARAM_INT);
-    $show      = optional_param('show', 0, PARAM_INT);
-    $blocklist = optional_param('blocklist', 0, PARAM_INT);
-    $modulelist= optional_param('modulelist', '', PARAM_PLUGIN);
-
-    $PAGE->set_url('/course/search.php', compact('search', 'page', 'perpage', 'blocklist', 'modulelist', 'edit'));
-    $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM));
-    $search = trim(strip_tags($search)); // trim & clean raw searched string
-
-    if ($search) {
-        $searchterms = explode(" ", $search);    // Search for words independently
-        foreach ($searchterms as $key => $searchterm) {
-            if (strlen($searchterm) < 2) {
-                unset($searchterms[$key]);
-            }
+// 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/>.
+
+/**
+ * Displays external information about a course
+ * @package    core
+ * @category   course
+ * @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($CFG->dirroot.'/course/lib.php');
+
+$search    = optional_param('search', '', PARAM_RAW);  // search words
+$page      = optional_param('page', 0, PARAM_INT);     // which page to show
+$perpage   = optional_param('perpage', 10, PARAM_INT); // how many per page
+$moveto    = optional_param('moveto', 0, PARAM_INT);   // move to category
+$edit      = optional_param('edit', -1, PARAM_BOOL);
+$hide      = optional_param('hide', 0, PARAM_INT);
+$show      = optional_param('show', 0, PARAM_INT);
+$blocklist = optional_param('blocklist', 0, PARAM_INT);
+$modulelist= optional_param('modulelist', '', PARAM_PLUGIN);
+
+// List of minimum capabilities which user need to have for editing/moving course
+$capabilities = array('moodle/course:create', 'moodle/category:manage');
+
+// List of category id's in which current user has course:create and category:manage capability.
+$usercatlist = array();
+
+// List of parent category id's
+$catparentlist = array();
+
+// Populate usercatlist with list of category id's with required capabilities.
+make_categories_list($usercatlist, $catparentlist, $capabilities);
+
+$search = trim(strip_tags($search)); // trim & clean raw searched string
+if ($search) {
+    $searchterms = explode(" ", $search);    // Search for words independently
+    foreach ($searchterms as $key => $searchterm) {
+        if (strlen($searchterm) < 2) {
+            unset($searchterms[$key]);
         }
-        $search = trim(implode(" ", $searchterms));
     }
+    $search = trim(implode(" ", $searchterms));
+}
 
-    $site = get_site();
+$site = get_site();
 
-    $urlparams = array();
-    foreach (array('search', 'page', 'blocklist', 'modulelist') as $param) {
-        if (!empty($$param)) {
-            $urlparams[$param] = $$param;
-        }
+$urlparams = array();
+foreach (array('search', 'page', 'blocklist', 'modulelist', 'edit') as $param) {
+    if (!empty($$param)) {
+        $urlparams[$param] = $$param;
     }
-    if ($perpage != 10) {
-        $urlparams['perpage'] = $perpage;
+}
+if ($perpage != 10) {
+    $urlparams['perpage'] = $perpage;
+}
+$PAGE->set_url('/course/search.php', $urlparams);
+$PAGE->set_context(context_system::instance());
+$PAGE->set_pagelayout('standard');
+
+if ($CFG->forcelogin) {
+    require_login();
+}
+
+// Editing is possible if user has system or category level create and manage capability
+if (can_edit_in_category() || !empty($usercatlist)) {
+    if ($edit !== -1) {
+        $USER->editing = $edit;
     }
-    $PAGE->set_url('/course/search.php', $urlparams);
-    $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM));
-    $PAGE->set_pagelayout('standard');
+    $adminediting = $PAGE->user_is_editing();
 
-    if ($CFG->forcelogin) {
-        require_login();
+    // Set perpage if user can edit in category
+    if ($perpage != 99999) {
+        $perpage = 30;
     }
-
-    if (can_edit_in_category()) {
-        if ($edit !== -1) {
-            $USER->editing = $edit;
+} else {
+    $adminediting = false;
+}
+
+// Editing functions
+if (has_capability('moodle/course:visibility', context_system::instance())) {
+    // Hide or show a course
+    if (($hide || $show) && confirm_sesskey()) {
+        if ($hide) {
+            $course = $DB->get_record("course", array("id" => $hide));
+            $visible = 0;
+        } else {
+            $course = $DB->get_record("course", array("id" => $show));
+            $visible = 1;
         }
-        $adminediting = $PAGE->user_is_editing();
-    } else {
-        $adminediting = false;
-    }
-
-/// Editing functions
-    if (has_capability('moodle/course:visibility', get_context_instance(CONTEXT_SYSTEM))) {
-    /// Hide or show a course
-        if ($hide or $show and confirm_sesskey()) {
-            if ($hide) {
-                $course = $DB->get_record("course", array("id"=>$hide));
-                $visible = 0;
-            } else {
-                $course = $DB->get_record("course", array("id"=>$show));
-                $visible = 1;
-            }
-            if ($course) {
-                $DB->set_field("course", "visible", $visible, array("id"=>$course->id));
-            }
+        if ($course) {
+            $DB->set_field("course", "visible", $visible, array("id" => $course->id));
         }
     }
+}
+
+$displaylist = array();
+$parentlist = array();
+make_categories_list($displaylist, $parentlist);
+
+$strcourses = new lang_string("courses");
+$strsearch = new lang_string("search");
+$strsearchresults = new lang_string("searchresults");
+$strcategory = new lang_string("category");
+$strselect   = new lang_string("select");
+$strselectall = new lang_string("selectall");
+$strdeselectall = new lang_string("deselectall");
+$stredit = new lang_string("edit");
+$strfrontpage = new lang_string('frontpage', 'admin');
+$strnovalidcourses = new lang_string('novalidcourses');
+
+if (empty($search) and empty($blocklist) and empty($modulelist) and empty($moveto) and ($edit != -1)) {
+    $PAGE->navbar->add($strcourses, new moodle_url('/course/index.php'));
+    $PAGE->navbar->add($strsearch);
+    $PAGE->set_title("$site->fullname : $strsearch");
+    $PAGE->set_heading($site->fullname);
 
-    $capabilities = array('moodle/course:create', 'moodle/category:manage');
-    if (has_any_capability($capabilities, get_context_instance(CONTEXT_SYSTEM)) && ($perpage != 99999)) {
-        $perpage = 30;
-    }
+    echo $OUTPUT->header();
+    echo $OUTPUT->box_start();
+    echo "<center>";
+    echo "<br />";
+    print_course_search("", false, "plain");
+    echo "<br /><p>";
+    print_string("searchhelp");
+    echo "</p>";
+    echo "</center>";
+    echo $OUTPUT->box_end();
+    echo $OUTPUT->footer();
+    exit;
+}
 
-    $displaylist = array();
-    $parentlist = array();
-    make_categories_list($displaylist, $parentlist);
-
-    $strcourses = get_string("courses");
-    $strsearch = get_string("search");
-    $strsearchresults = get_string("searchresults");
-    $strcategory = get_string("category");
-    $strselect   = get_string("select");
-    $strselectall = get_string("selectall");
-    $strdeselectall = get_string("deselectall");
-    $stredit = get_string("edit");
-    $strfrontpage = get_string('frontpage', 'admin');
-    $strnovalidcourses = get_string('novalidcourses');
-
-    if (empty($search) and empty($blocklist) and empty($modulelist)) {
-        $PAGE->navbar->add($strcourses, new moodle_url('/course/index.php'));
-        $PAGE->navbar->add($strsearch);
-        $PAGE->set_title("$site->fullname : $strsearch");
-        $PAGE->set_heading($site->fullname);
-
-        echo $OUTPUT->header();
-        echo $OUTPUT->box_start();
-        echo "<center>";
-        echo "<br />";
-        print_course_search("", false, "plain");
-        echo "<br /><p>";
-        print_string("searchhelp");
-        echo "</p>";
-        echo "</center>";
-        echo $OUTPUT->box_end();
-        echo $OUTPUT->footer();
-        exit;
+$courses = array();
+if (!empty($moveto) and $data = data_submitted() and confirm_sesskey()) {   // Some courses are being moved
+    if (!$destcategory = $DB->get_record("course_categories", array("id" => $moveto))) {
+        print_error('cannotfindcategory', '', '', $moveto);
     }
 
-    if (!empty($moveto) and $data = data_submitted() and confirm_sesskey()) {   // Some courses are being moved
-        if (! $destcategory = $DB->get_record("course_categories", array("id"=>$data->moveto))) {
-            print_error('cannotfindcategory', '', '', $data->moveto);
-        }
-
-        $courses = array();
-        foreach ( $data as $key => $value ) {
-            if (preg_match('/^c\d+$/', $key)) {
-                array_push($courses, substr($key, 1));
+    // User should have manage and create capablity on destination category.
+    require_capability('moodle/category:manage', context_coursecat::instance($moveto));
+    require_capability('moodle/course:create', context_coursecat::instance($moveto));
+
+    foreach ( $data as $key => $value ) {
+        if (preg_match('/^c\d+$/', $key)) {
+            $courseid = substr($key, 1);
+            // user must have category:manage and course:create capability for the course to be moved.
+            $coursecontext = context_course::instance($courseid);
+            foreach ($capabilities as $capability) {
+                // Require capability here will result in a fatal error should the user not
+                // have the requried category ensuring that no moves occur if they are
+                // trying to move multiple courses.
+                require_capability($capability, $coursecontext);
+                array_push($courses, $courseid);
             }
         }
-        move_courses($courses, $data->moveto);
     }
-
-    // get list of courses containing blocks if required
-    if (!empty($blocklist) and confirm_sesskey()) {
-        $blockname = $DB->get_field('block', 'name', array('id' => $blocklist));
-        $courses = array();
-        $courses = $DB->get_records_sql("
-                SELECT * FROM {course} WHERE id IN (
-                    SELECT DISTINCT ctx.instanceid
-                    FROM {context} ctx
-                    JOIN {block_instances} bi ON bi.parentcontextid = ctx.id
-                    WHERE ctx.contextlevel = " . CONTEXT_COURSE . " AND bi.blockname = ?)",
-                array($blockname));
-        $totalcount = count($courses);
-        //Keep only chunk of array which you want to display
-        if ($totalcount > $perpage) {
-            $courses = array_chunk($courses, $perpage, true);
-            $courses = $courses[$page];
-        }
-        foreach ($courses as $course) {
-            $courses[$course->id] = $course;
-        }
+    move_courses($courses, $moveto);
+}
+
+// get list of courses containing blocks if required
+if (!empty($blocklist) and confirm_sesskey()) {
+    $blockname = $DB->get_field('block', 'name', array('id' => $blocklist));
+    $courses = array();
+    $courses = $DB->get_records_sql("
+            SELECT * FROM {course} WHERE id IN (
+                SELECT DISTINCT ctx.instanceid
+                FROM {context} ctx
+                JOIN {block_instances} bi ON bi.parentcontextid = ctx.id
+                WHERE ctx.contextlevel = " . CONTEXT_COURSE . " AND bi.blockname = ?)",
+            array($blockname));
+    $totalcount = count($courses);
+    // Keep only chunk of array which you want to display
+    if ($totalcount > $perpage) {
+        $courses = array_chunk($courses, $perpage, true);
+        $courses = $courses[$page];
     }
-    // get list of courses containing modules if required
-    elseif (!empty($modulelist) and confirm_sesskey()) {
-        $modulename = $modulelist;
-        $sql =  "SELECT DISTINCT c.id FROM {".$modulelist."} module, {course} c"
-            ." WHERE module.course=c.id";
-
-        $courseids = $DB->get_records_sql($sql);
-        $courses = array();
-        if (!empty($courseids)) {
-            $firstcourse = $page*$perpage;
-            $lastcourse = $page*$perpage + $perpage -1;
-            $i = 0;
-            foreach ($courseids as $courseid) {
-                if ($i>= $firstcourse && $i<=$lastcourse) {
-                    $courses[$courseid->id] = $DB->get_record('course', array('id'=> $courseid->id));
-                }
-                $i++;
+    foreach ($courses as $course) {
+        $courses[$course->id] = $course;
+    }
+} elseif (!empty($modulelist) and confirm_sesskey()) { // get list of courses containing modules
+    $modulename = $modulelist;
+    $sql =  "SELECT DISTINCT c.id FROM {".$modulelist."} module, {course} c"
+        ." WHERE module.course=c.id";
+
+    $courseids = $DB->get_records_sql($sql);
+    $courses = array();
+    if (!empty($courseids)) {
+        $firstcourse = $page*$perpage;
+        $lastcourse = $page*$perpage + $perpage -1;
+        $i = 0;
+        foreach ($courseids as $courseid) {
+            if ($i >= $firstcourse && $i <= $lastcourse) {
+                $courses[$courseid->id] = $DB->get_record('course', array('id'=> $courseid->id));
             }
-            $totalcount = count($courseids);
-        }
-        else {
-            $totalcount = 0;
+            $i++;
         }
+        $totalcount = count($courseids);
     }
     else {
-        $courses = get_courses_search($searchterms, "fullname ASC",
-            $page, $perpage, $totalcount);
+        $totalcount = 0;
     }
-
-    $searchform = print_course_search($search, true, "navbar");
-
-    if (!empty($courses) && has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM))) {
-        $searchform = '';
-        // not sure if this capability is the best  here
-        if (has_capability('moodle/category:manage', get_context_instance(CONTEXT_SYSTEM))) {
-            if ($PAGE->user_is_editing()) {
-                $string = get_string("turneditingoff");
-                $edit = "off";
-            } else {
-                $string = get_string("turneditingon");
-                $edit = "on";
-            }
-
-            $aurl = new moodle_url("$CFG->wwwroot/course/search.php", array(
-                    'edit' => $edit,
-                    'sesskey' => sesskey(),
-                    'search' => $search,
-                    'page' => $page,
-                    'perpage' => $perpage));
-            $searchform = $OUTPUT->single_button($aurl, $string, 'get');
-        }
+} else if (!empty($searchterm)) {
+    // Donot do search for empty search request.
+    $courses = get_courses_search($searchterms, "fullname ASC", $page, $perpage, $totalcount);
+}
+
+$searchform = '';
+// Turn editing should be visible if user have system or category level capability
+if (!empty($courses) && (can_edit_in_category() || !empty($usercatlist))) {
+    if ($PAGE->user_is_editing()) {
+        $string = new lang_string("turneditingoff");
+        $edit = "off";
+    } else {
+        $string = new lang_string("turneditingon");
+        $edit = "on";
     }
-
-    $PAGE->navbar->add($strcourses, new moodle_url('/course/index.php'));
-    $PAGE->navbar->add($strsearch, new moodle_url('/course/search.php'));
-    if (!empty($search)) {
-        $PAGE->navbar->add(s($search));
+    $params = array_merge($urlparams, array('sesskey' => sesskey(), 'edit' => $edit));
+    $aurl = new moodle_url("$CFG->wwwroot/course/search.php", $params);
+    $searchform = $OUTPUT->single_button($aurl, $string, 'get');
+} else {
+    $searchform = print_course_search($search, true, "navbar");
+}
+
+$PAGE->navbar->add($strcourses, new moodle_url('/course/index.php'));
+$PAGE->navbar->add($strsearch, new moodle_url('/course/search.php'));
+if (!empty($search)) {
+    $PAGE->navbar->add(s($search));
+}
+$PAGE->set_title("$site->fullname : $strsearchresults");
+$PAGE->set_heading($site->fullname);
+$PAGE->set_button($searchform);
+
+echo $OUTPUT->header();
+
+$lastcategory = -1;
+if ($courses) {
+    echo $OUTPUT->heading("$strsearchresults: $totalcount");
+    $encodedsearch = urlencode($search);
+
+    // add the module/block parameter to the paging bar if they exists
+    $modulelink = "";
+    if (!empty($modulelist) and confirm_sesskey()) {
+        $modulelink = "&amp;modulelist=".$modulelist."&amp;sesskey=".sesskey();
+    } else if (!empty($blocklist) and confirm_sesskey()) {
+        $modulelink = "&amp;blocklist=".$blocklist."&amp;sesskey=".sesskey();
     }
-    $PAGE->set_title("$site->fullname : $strsearchresults");
-    $PAGE->set_heading($site->fullname);
-    $PAGE->set_button($searchform);
 
-    echo $OUTPUT->header();
+    print_navigation_bar($totalcount, $page, $perpage, $encodedsearch, $modulelink);
 
-    $lastcategory = -1;
-    if ($courses) {
-        echo $OUTPUT->heading("$strsearchresults: $totalcount");
-        $encodedsearch = urlencode($search);
-
-        // add the module/block parameter to the paging bar if they exists
-        $modulelink = "";
+    // Show list of courses
+    if (!$adminediting) { //Not editing mode
+        foreach ($courses as $course) {
+            // front page don't belong to any category and block can exist.
+            if ($course->category > 0) {
+                $course->summary .= "<br /><p class=\"category\">";
+                $course->summary .= "$strcategory: <a href=\"category.php?id=$course->category\">";
+                $course->summary .= $displaylist[$course->category];
+                $course->summary .= "</a></p>";
+            }
+            print_course($course, $search);
+            echo $OUTPUT->spacer(array('height'=>5, 'width'=>5, 'br'=>true)); // should be done with CSS instead
+        }
+    } else {
+        // Editing mode
+        echo "<form id=\"movecourses\" action=\"search.php\" method=\"post\">\n";
+        echo "<div><input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />\n";
+        echo "<input type=\"hidden\" name=\"search\" value=\"".s($search)."\" />\n";
+        echo "<input type=\"hidden\" name=\"page\" value=\"$page\" />\n";
+        echo "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" /></div>\n";
         if (!empty($modulelist) and confirm_sesskey()) {
-            $modulelink = "&amp;modulelist=".$modulelist."&amp;sesskey=".sesskey();
+            echo "<input type=\"hidden\" name=\"modulelist\" value=\"$modulelist\" /></div>\n";
         } else if (!empty($blocklist) and confirm_sesskey()) {
-            $modulelink = "&amp;blocklist=".$blocklist."&amp;sesskey=".sesskey();
+            echo "<input type=\"hidden\" name=\"blocklist\" value=\"$blocklist\" /></div>\n";
         }
+        echo "<table border=\"0\" cellspacing=\"2\" cellpadding=\"4\" class=\"generalbox boxaligncenter\">\n<tr>\n";
+        echo "<th scope=\"col\">$strcourses</th>\n";
+        echo "<th scope=\"col\">$strcategory</th>\n";
+        echo "<th scope=\"col\">$strselect</th>\n";
+        echo "<th scope=\"col\">$stredit</th></tr>\n";
 
-        print_navigation_bar($totalcount, $page, $perpage, $encodedsearch, $modulelink);
+        foreach ($courses as $course) {
 
-        if (!$adminediting) {
-            foreach ($courses as $course) {
+            $coursecontext = context_course::instance($course->id);
 
-                $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
+            $linkcss = $course->visible ? "" : " class=\"dimmed\" ";
 
-                $course->summary .= "<br /><p class=\"category\">";
-                $course->summary .= "$strcategory: <a href=\"category.php?id=$course->category\">";
-                $course->summary .= $displaylist[$course->category];
-                $course->summary .= "</a></p>";
-                print_course($course, $search);
-                echo $OUTPUT->spacer(array('height'=>5, 'width'=>5, 'br'=>true)); // should be done with CSS instead
+            // are we displaying the front page (courseid=1)?
+            if ($course->id == 1) {
+                echo "<tr>\n";
+                echo "<td><a href=\"$CFG->wwwroot\">$strfrontpage</a></td>\n";
+
+                // can't do anything else with the front page
+                echo "  <td>&nbsp;</td>\n"; // category place
+                echo "  <td>&nbsp;</td>\n"; // select place
+                echo "  <td>&nbsp;</td>\n"; // edit place
+                echo "</tr>\n";
+                continue;
             }
-        } else {
-        /// Show editing UI.
-            echo "<form id=\"movecourses\" action=\"search.php\" method=\"post\">\n";
-            echo "<div><input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />\n";
-            echo "<input type=\"hidden\" name=\"search\" value=\"".s($search)."\" />\n";
-            echo "<input type=\"hidden\" name=\"page\" value=\"$page\" />\n";
-            echo "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" /></div>\n";
-            echo "<table border=\"0\" cellspacing=\"2\" cellpadding=\"4\" class=\"generalbox boxaligncenter\">\n<tr>\n";
-            echo "<th scope=\"col\">$strcourses</th>\n";
-            echo "<th scope=\"col\">$strcategory</th>\n";
-            echo "<th scope=\"col\">$strselect</th>\n";
-            echo "<th scope=\"col\">$stredit</th></tr>\n";
-
-            foreach ($courses as $course) {
-
-                $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
-
-                $linkcss = $course->visible ? "" : " class=\"dimmed\" ";
-
-                // are we displaying the front page (courseid=1)?
-                if ($course->id == 1) {
-                    echo "<tr>\n";
-                    echo "<td><a href=\"$CFG->wwwroot\">$strfrontpage</a></td>\n";
-
-                    // can't do anything else with the front page
-                    echo "  <td>&nbsp;</td>\n"; // category place
-                    echo "  <td>&nbsp;</td>\n"; // select place
-                    echo "  <td>&nbsp;</td>\n"; // edit place
-                    echo "</tr>\n";
-                    continue;
-                }
 
-                echo "<tr>\n";
-                echo "<td><a $linkcss href=\"view.php?id=$course->id\">"
-                    . highlight($search, format_string($course->fullname)) . "</a></td>\n";
-                echo "<td>".$displaylist[$course->category]."</td>\n";
-                echo "<td>\n";
-
-                // this is ok since this will get inherited from course category context
-                // if it is set
-                if (has_capability('moodle/category:manage', $coursecontext)) {
-                    echo "<input type=\"checkbox\" name=\"c$course->id\" />\n";
-                } else {
-                    echo "<input type=\"checkbox\" name=\"c$course->id\" disabled=\"disabled\" />\n";
-                }
+            echo "<tr>\n";
+            echo "<td><a $linkcss href=\"view.php?id=$course->id\">"
+                . highlight($search, format_string($course->fullname)) . "</a></td>\n";
+            echo "<td>".$displaylist[$course->category]."</td>\n";
+            echo "<td>\n";
 
-                echo "</td>\n";
-                echo "<td>\n";
+            // If user has all required capabilities to move course then show selectable checkbox
+            if (has_all_capabilities($capabilities, $coursecontext)) {
+                echo "<input type=\"checkbox\" name=\"c$course->id\" />\n";
+            } else {
+                echo "<input type=\"checkbox\" name=\"c$course->id\" disabled=\"disabled\" />\n";
+            }
 
-                // checks whether user can update course settings
-                if (has_capability('moodle/course:update', $coursecontext)) {
-                    echo "<a title=\"".get_string("settings")."\" href=\"$CFG->wwwroot/course/edit.php?id=$course->id\">\n<img".
-                        " src=\"" . $OUTPUT->pix_url('t/edit') . "\" class=\"iconsmall\" alt=\"".get_string("settings")."\" /></a>\n ";
-                }
+            echo "</td>\n";
+            echo "<td>\n";
 
-                // checks whether user can do role assignment
-                if (has_capability('moodle/course:enrolreview', $coursecontext)) {
-                    echo'<a title="'.get_string('enrolledusers', 'enrol').'" href="'.$CFG->wwwroot.'/enrol/users.php?id='.$course->id.'">';
-                    echo '<img src="'.$OUTPUT->pix_url('i/users') . '" class="iconsmall" alt="'.get_string('enrolledusers', 'enrol').'" /></a> ' . "\n";
-                }
+            // checks whether user can update course settings
+            if (has_capability('moodle/course:update', $coursecontext)) {
+                echo "<a title=\"".get_string("settings")."\" href=\"$CFG->wwwroot/course/edit.php?id=$course->id\">\n<img".
+                    " src=\"" . $OUTPUT->pix_url('t/edit') . "\" class=\"iconsmall\" alt=\"".get_string("settings")."\" /></a>\n ";
+            }
 
-                // checks whether user can delete course
-                if (has_capability('moodle/course:delete', $coursecontext)) {
-                    echo "<a title=\"".get_string("delete")."\" href=\"delete.php?id=$course->id\">\n<img".
-                        " src=\"" . $OUTPUT->pix_url('t/delete') . "\" class=\"iconsmall\" alt=\"".get_string("delete")."\" /></a>\n ";
-                }
+            // checks whether user can do role assignment
+            if (has_capability('moodle/course:enrolreview', $coursecontext)) {
+                echo'<a title="'.get_string('enrolledusers', 'enrol').'" href="'.$CFG->wwwroot.'/enrol/users.php?id='.$course->id.'">';
+                echo '<img src="'.$OUTPUT->pix_url('i/users') . '" class="iconsmall" alt="'.get_string('enrolledusers', 'enrol').'" /></a> ' . "\n";
+            }
 
-                // checks whether user can change visibility
-                if (has_capability('moodle/course:visibility', $coursecontext)) {
-                    if (!empty($course->visible)) {
-                        echo "<a title=\"".get_string("hide")."\" href=\"search.php?search=$encodedsearch&amp;perpage=$perpage&amp;page=$page&amp;hide=$course->id&amp;sesskey=".sesskey()."\">\n<img".
-                            " src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"".get_string("hide")."\" /></a>\n ";
-                    } else {
-                        echo "<a title=\"".get_string("show")."\" href=\"search.php?search=$encodedsearch&amp;perpage=$perpage&amp;page=$page&amp;show=$course->id&amp;sesskey=".sesskey()."\">\n<img".
-                            " src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"".get_string("show")."\" /></a>\n ";
-                    }
-                }
+            // checks whether user can delete course
+            if (has_capability('moodle/course:delete', $coursecontext)) {
+                echo "<a title=\"".get_string("delete")."\" href=\"delete.php?id=$course->id\">\n<img".
+                    " src=\"" . $OUTPUT->pix_url('t/delete') . "\" class=\"iconsmall\" alt=\"".get_string("delete")."\" /></a>\n ";
+            }
 
-                // checks whether user can do site backup
-                if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
-                    echo "<a title=\"".get_string("backup")."\" href=\"../backup/backup.php?id=$course->id\">\n<img".
-                        " src=\"" . $OUTPUT->pix_url('t/backup') . "\" class=\"iconsmall\" alt=\"".get_string("backup")."\" /></a>\n ";
+            // checks whether user can change visibility
+            if (has_capability('moodle/course:visibility', $coursecontext)) {
+                if (!empty($course->visible)) {
+                    echo "<a title=\"".get_string("hide")."\" href=\"search.php?search=$encodedsearch&amp;perpage=$perpage&amp;page=$page&amp;hide=$course->id&amp;sesskey=".sesskey()."\">\n<img".
+                        " src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"".get_string("hide")."\" /></a>\n ";
+                } else {
+                    echo "<a title=\"".get_string("show")."\" href=\"search.php?search=$encodedsearch&amp;perpage=$perpage&amp;page=$page&amp;show=$course->id&amp;sesskey=".sesskey()."\">\n<img".
+                        " src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"".get_string("show")."\" /></a>\n ";
                 }
+            }
 
-                // checks whether user can do restore
-                if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
-                    echo "<a title=\"".get_string("restore")."\" href=\"../files/index.php?id=$course->id&amp;wdir=/backupdata\">\n<img".
-                        " src=\"" . $OUTPUT->pix_url('t/restore') . "\" class=\"iconsmall\" alt=\"".get_string("restore")."\" /></a>\n ";
-                }
+            // checks whether user can do site backup
+            if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
+                $backupurl = new moodle_url('/backup/backup.php', array('id' => $course->id));
+                echo "<a title=\"".get_string("backup")."\" href=\"".$backupurl."\">\n<img".
+                    " src=\"" . $OUTPUT->pix_url('t/backup') . "\" class=\"iconsmall\" alt=\"".get_string("backup")."\" /></a>\n ";
+            }
 
-                echo "</td>\n</tr>\n";
+            // checks whether user can do restore
+            if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
+                $restoreurl = new moodle_url('/backup/restorefile.php', array('contextid' => $coursecontext->id));
+                echo "<a title=\"".get_string("restore")."\" href=\"".$restoreurl."\">\n<img".
+                    " src=\"" . $OUTPUT->pix_url('t/restore') . "\" class=\"iconsmall\" alt=\"".get_string("restore")."\" /></a>\n ";
             }
-            echo "<tr>\n<td colspan=\"4\" style=\"text-align:center\">\n";
-            echo "<br />";
-            echo "<input type=\"button\" onclick=\"checkall()\" value=\"$strselectall\" />\n";
-            echo "<input type=\"button\" onclick=\"checknone()\" value=\"$strdeselectall\" />\n";
-            echo html_writer::select($displaylist, 'moveto', '', array(''=>get_string('moveselectedcoursesto')), array('id'=>'movetoid'));
-            $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('movecourses', 'movetoid', false));
-            echo "</td>\n</tr>\n";
-            echo "</table>\n</form>";
 
+            echo "</td>\n</tr>\n";
         }
+        echo "<tr>\n<td colspan=\"4\" style=\"text-align:center\">\n";
+        echo "<br />";
+        echo "<input type=\"button\" onclick=\"checkall()\" value=\"$strselectall\" />\n";
+        echo "<input type=\"button\" onclick=\"checknone()\" value=\"$strdeselectall\" />\n";
+        // Select box should only show categories in which user has min capability to move course.
+        echo html_writer::select($usercatlist, 'moveto', '', array(''=>get_string('moveselectedcoursesto')), array('id'=>'movetoid'));
+        $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('movecourses', 'movetoid', false));
+        echo "</td>\n</tr>\n";
+        echo "</table>\n</form>";
 
-        print_navigation_bar($totalcount,$page,$perpage,$encodedsearch,$modulelink);
-
-    } else {
-        if (!empty($search)) {
-            echo $OUTPUT->heading(get_string("nocoursesfound",'', s($search)));
-        }
-        else {
-            echo $OUTPUT->heading( $strnovalidcourses );
-        }
     }
 
-    echo "<br /><br />";
-
-    print_course_search($search);
+    print_navigation_bar($totalcount,$page,$perpage,$encodedsearch,$modulelink);
 
-    echo $OUTPUT->footer();
-
-   /**
-     * Print a list navigation bar
-     * Display page numbers, and a link for displaying all entries
-     * @param integer $totalcount - number of entry to display
-     * @param integer $page - page number
-     * @param integer $perpage - number of entry per page
-     * @param string $encodedsearch
-     * @param string $modulelink - module name
-     */
-    function print_navigation_bar($totalcount,$page,$perpage,$encodedsearch,$modulelink) {
-        global $OUTPUT;
-        echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "search.php?search=$encodedsearch".$modulelink."&perpage=$perpage");
-
-        //display
-        if ($perpage != 99999 && $totalcount > $perpage) {
-            echo "<center><p>";
-            echo "<a href=\"search.php?search=$encodedsearch".$modulelink."&amp;perpage=99999\">".get_string("showall", "", $totalcount)."</a>";
-            echo "</p></center>";
-        } else if ($perpage === 99999) {
-            $defaultperpage = 10;
-            //If user has course:create or category:manage capability the show 30 records.
-            $capabilities = array('moodle/course:create', 'moodle/category:manage');
-            if (has_any_capability($capabilities, get_context_instance(CONTEXT_SYSTEM))) {
-                $defaultperpage = 30;
-            }
-
-            echo "<center><p>";
-            echo "<a href=\"search.php?search=$encodedsearch".$modulelink."&amp;perpage=".$defaultperpage."\">".get_string("showperpage", "", $defaultperpage)."</a>";
-            echo "</p></center>";
-        }
+} else {
+    if (!empty($search)) {
+        echo $OUTPUT->heading(get_string("nocoursesfound",'', s($search)));
     }
+    else {
+        echo $OUTPUT->heading($strnovalidcourses);
+    }
+}
+
+echo "<br /><br />";
+
+print_course_search($search);
+
+echo $OUTPUT->footer();
+
+/**
+ * Print a list navigation bar
+ * Display page numbers, and a link for displaying all entries
+ * @param int $totalcount number of entry to display
+ * @param int $page page number
+ * @param int $perpage number of entry per page
+ * @param string $encodedsearch
+ * @param string $modulelink module name
+ */
+function print_navigation_bar($totalcount, $page, $perpage, $encodedsearch, $modulelink) {
+    global $OUTPUT;
+    echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "search.php?search=$encodedsearch".$modulelink."&perpage=$perpage");
+
+    // display
+    if ($perpage != 99999 && $totalcount > $perpage) {
+        echo "<center><p>";
+        echo "<a href=\"search.php?search=$encodedsearch".$modulelink."&amp;perpage=99999\">".get_string("showall", "", $totalcount)."</a>";
+        echo "</p></center>";
+    } else if ($perpage === 99999) {
+        $defaultperpage = 10;
+        // If user has course:create or category:manage capability the show 30 records.
+        $capabilities = array('moodle/course:create', 'moodle/category:manage');
+        if (has_any_capability($capabilities, context_system::instance())) {
+            $defaultperpage = 30;
+        }
 
-
+        echo "<center><p>";
+        echo "<a href=\"search.php?search=$encodedsearch".$modulelink."&amp;perpage=".$defaultperpage."\">".get_string("showperpage", "", $defaultperpage)."</a>";
+        echo "</p></center>";
+    }
+}
\ No newline at end of file
index 8b2621f..49bbbe8 100644 (file)
     // Course wrapper start.
     echo html_writer::start_tag('div', array('class'=>'course-content'));
 
-    $modinfo =& get_fast_modinfo($COURSE);
+    $modinfo = get_fast_modinfo($COURSE);
     get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
     foreach($mods as $modid=>$unused) {
         if (!isset($modinfo->cms[$modid])) {
             rebuild_course_cache($course->id);
-            $modinfo =& get_fast_modinfo($COURSE);
+            $modinfo = get_fast_modinfo($COURSE);
             debugging('Rebuilding course cache', DEBUG_DEVELOPER);
             break;
         }
index 98634ed..6a5a1e5 100644 (file)
@@ -233,7 +233,7 @@ function send_welcome_messages($orderdata) {
                 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$lastuserid";
                 $a->paymenturl = "$CFG->wwwroot/enrol/authorize/index.php?user=$lastuserid";
                 $emailmessage = get_string('welcometocoursesemail', 'enrol_authorize', $a);
-                $subject = get_string("enrolmentnew", '', format_string($SITE->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID))));
+                $subject = get_string("enrolmentnew", 'enrol', format_string($SITE->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID))));
 
                 $eventdata = new stdClass();
                 $eventdata->modulename        = 'moodle';
index 18f6420..b423c7b 100644 (file)
@@ -44,12 +44,13 @@ $string['defaultrole'] = 'Default role';
 $string['defaultrole_desc'] = 'The role that will be assigned by default if no other role is specified in external table.';
 $string['ignorehiddencourses'] = 'Ignore hidden courses';
 $string['ignorehiddencourses_desc'] = 'If enabled users will not be enrolled on courses that are set to be unavailable to students.';
+$string['localcategoryfield'] = 'Local category field';
 $string['localcoursefield'] = 'Local course field';
 $string['localrolefield'] = 'Local role field';
 $string['localuserfield'] = 'Local user field';
 $string['newcoursetable'] = 'Remote new courses table';
 $string['newcoursetable_desc'] = 'Specify of the name of the table that contains list of courses that should be created automatically. Empty means no courses are created.';
-$string['newcoursecategory'] = 'New course category id field';
+$string['newcoursecategory'] = 'New course category field';
 $string['newcoursefullname'] = 'New course full name field';
 $string['newcourseidnumber'] = 'New course ID number field';
 $string['newcourseshortname'] = 'New course short name field';
index f0aa364..62b44f9 100644 (file)
@@ -81,7 +81,7 @@ class enrol_database_plugin extends enrol_plugin {
         $instance = $ue->enrolmentinstance;
         $params = $manager->get_moodlepage()->url->params();
         $params['ue'] = $ue->id;
-        if ($this->allow_unenrol_user($instance, $ue) && has_capability('enrol/meta:unenrol', $context)) {
+        if ($this->allow_unenrol_user($instance, $ue) && has_capability('enrol/database:unenrol', $context)) {
             $url = new moodle_url('/enrol/unenroluser.php', $params);
             $actions[] = new user_enrolment_action(new pix_icon('t/delete', ''), get_string('unenrol', 'enrol'), $url, array('class'=>'unenrollink', 'rel'=>$ue->id));
         }
@@ -354,9 +354,7 @@ class enrol_database_plugin extends enrol_plugin {
         }
         $preventfullunenrol = empty($externalcourses);
         if ($preventfullunenrol and $unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
-            if ($verbose) {
-                mtrace('  Preventing unenrolment of all current users, because it might result in major data loss, there has to be at least one record in external enrol table, sorry.');
-            }
+            mtrace('  Preventing unenrolment of all current users, because it might result in major data loss, there has to be at least one record in external enrol table, sorry.');
         }
 
         // first find all existing courses with enrol instance
@@ -622,6 +620,8 @@ class enrol_database_plugin extends enrol_plugin {
         $idnumber  = strtolower($this->get_config('newcourseidnumber'));
         $category  = strtolower($this->get_config('newcoursecategory'));
 
+        $localcategoryfield = $this->get_config('localcategoryfield', 'id');
+
         $sqlfields = array($fullname, $shortname);
         if ($category) {
             $sqlfields[] = $category;
@@ -653,17 +653,17 @@ class enrol_database_plugin extends enrol_plugin {
                         }
                         continue;
                     }
-                    if ($category and !$DB->record_exists('course_categories', array('id'=>$fields[$category]))) {
+                    if ($category and !$coursecategory = $DB->get_record('course_categories', array($localcategoryfield=>$fields[$category]), 'id')) {
                         if ($verbose) {
-                            mtrace('  error: invalid category id, can not create course: '.$fields[$shortname]);
+                            mtrace('  error: invalid category '.$localcategoryfield.', can not create course: '.$fields[$shortname]);
                         }
                         continue;
                     }
                     $course = new stdClass();
                     $course->fullname  = $fields[$fullname];
                     $course->shortname = $fields[$shortname];
-                    $course->idnumber  = $idnumber ? $fields[$idnumber] : NULL;
-                    $course->category  = $category ? $fields[$category] : NULL;
+                    $course->idnumber  = $idnumber ? $fields[$idnumber] : '';
+                    $course->category  = $category ? $coursecategory->id : NULL;
                     $createcourses[] = $course;
                 }
             }
index f75afe6..369bd39 100644 (file)
@@ -66,6 +66,8 @@ if ($ADMIN->fulltree) {
     $options = array('id'=>'id', 'shortname'=>'shortname', 'fullname'=>'fullname');
     $settings->add(new admin_setting_configselect('enrol_database/localrolefield', get_string('localrolefield', 'enrol_database'), '', 'shortname', $options));
 
+    $options = array('id'=>'id', 'idnumber'=>'idnumber');
+    $settings->add(new admin_setting_configselect('enrol_database/localcategoryfield', get_string('localcategoryfield', 'enrol_database'), '', 'id', $options));
 
 
     $settings->add(new admin_setting_heading('enrol_database_remoteheader', get_string('settingsheaderremote', 'enrol_database'), ''));
index c1a2820..6f085ff 100644 (file)
@@ -25,7 +25,7 @@
 
 defined('MOODLE_INTERNAL') || die();
 
-$plugin->version   = 2012022700;        // The current plugin version (Date: YYYYMMDDXX)
+$plugin->version   = 2012031000;        // The current plugin version (Date: YYYYMMDDXX)
 $plugin->requires  = 2012022300;        // Requires this Moodle version
 $plugin->component = 'enrol_database';  // Full name of the plugin (used for diagnostics)
 //TODO: should we add cron sync?
\ No newline at end of file
index e7cdf29..f7d5030 100644 (file)
@@ -764,20 +764,14 @@ class course_enrolment_manager {
         $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
         $roles = $this->get_all_roles();
 
-        $courseid   = $this->get_course()->id;
         $context    = $this->get_context();
+        $now = time();
+        $extrafields = get_extra_user_fields($context);
 
         $users = array();
         foreach ($userroles as $userrole) {
             if (!array_key_exists($userrole->id, $users)) {
-                $users[$userrole->id] = array(
-                    'userid'     => $userrole->id,
-                    'courseid'   => $courseid,
-                    'picture'    => new user_picture($userrole),
-                    'firstname'  => fullname($userrole, true),
-                    'email'      => $userrole->email,
-                    'roles'      => array()
-                );
+                $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
             }
             $a = new stdClass;
             $a->role = $roles[$userrole->roleid]->localname;
@@ -800,6 +794,7 @@ class course_enrolment_manager {
                         break;
                 }
             }
+            $users[$userrole->id]['roles'] = array();
             $users[$userrole->id]['roles'][$userrole->roleid] = array(
                 'text' => $roletext,
                 'unchangeable' => !$changeable
@@ -825,7 +820,6 @@ class course_enrolment_manager {
         $users = $this->get_users($sort, $direction, $page, $perpage);
 
         $now = time();
-        $strnever = get_string('never');
         $straddgroup = get_string('addgroup', 'group');
         $strunenrol = get_string('unenrol', 'enrol');
         $stredit = get_string('edit');
@@ -833,7 +827,6 @@ class course_enrolment_manager {
         $allroles   = $this->get_all_roles();
         $assignable = $this->get_assignable_roles();
         $allgroups  = $this->get_all_groups();
-        $courseid   = $this->get_course()->id;
         $context    = $this->get_context();
         $canmanagegroups = has_capability('moodle/course:managegroups', $context);
 
@@ -842,36 +835,23 @@ class course_enrolment_manager {
 
         $userdetails = array();
         foreach ($users as $user) {
-            $details = array(
-                'userid'     => $user->id,
-                'courseid'   => $courseid,
-                'picture'    => new user_picture($user),
-                'firstname'  => fullname($user, true),
-                'lastseen'   => $strnever,
-                'roles'      => array(),
-                'groups'     => array(),
-                'enrolments' => array()
-            );
-            foreach ($extrafields as $field) {
-                $details[$field] = $user->{$field};
-            }
-
-            if ($user->lastaccess) {
-                $details['lastseen'] = format_time($now - $user->lastaccess);
-            }
+            $details = $this->prepare_user_for_display($user, $extrafields, $now);
 
             // Roles
+            $details['roles'] = array();
             foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
                 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname, 'unchangeable'=>(!$rassignable || !isset($assignable[$rid])));
             }
 
             // Users
             $usergroups = $this->get_user_groups($user->id);
+            $details['groups'] = array();
             foreach($usergroups as $gid=>$unused) {
                 $details['groups'][$gid] = $allgroups[$gid]->name;
             }
 
             // Enrolments
+            $details['enrolments'] = array();
             foreach ($this->get_user_enrolments($user->id) as $ue) {
                 if ($ue->timestart and $ue->timeend) {
                     $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
@@ -898,6 +878,39 @@ class course_enrolment_manager {
         return $userdetails;
     }
 
+    /**
+     * Prepare a user record for display
+     *
+     * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
+     * prepare user fields for display
+     *
+     * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
+     *
+     * @param object $user The user record
+     * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
+     * additional fields may be displayed
+     * @param int $now The time used for lastaccess calculation
+     * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any
+     * additional fields from $extrafields
+     */
+    private function prepare_user_for_display($user, $extrafields, $now) {
+        $details = array(
+            'userid'    => $user->id,
+            'courseid'  => $this->get_course()->id,
+            'picture'   => new user_picture($user),
+            'firstname' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
+            'lastseen'  => get_string('never'),
+        );
+        foreach ($extrafields as $field) {
+            $details[$field] = $user->{$field};
+        }
+
+        if ($user->lastaccess) {
+            $details['lastseen'] = format_time($now - $user->lastaccess);
+        }
+        return $details;
+    }
+
     public function get_manual_enrol_buttons() {
         $plugins = $this->get_enrolment_plugins();
         $buttons = array();
index 5ed2012..4a7b760 100644 (file)
@@ -25,6 +25,6 @@
 
 defined('MOODLE_INTERNAL') || die();
 
-$plugin->version   = 2011112900;        // The current plugin version (Date: YYYYMMDDXX)
+$plugin->version   = 2011112901;        // The current plugin version (Date: YYYYMMDDXX)
 $plugin->requires  = 2011112900;        // Requires this Moodle version
 $plugin->component = 'enrol_manual';    // Full name of the plugin (used for diagnostics)
index d5658b4..88c09ea 100644 (file)
@@ -380,7 +380,11 @@ YUI.add('moodle-enrol_manual-quickenrolment', function(Y) {
             params['role'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.ROLE+' select').get('value');
             params['startdate'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.STARTDATE+' select').get('value');
             params['duration'] = this.get(UEP.BASE).one('.'+CSS.ENROLMENTOPTION+'.'+CSS.DURATION+' select').get('value');
-            params['recovergrades'] = this.get(UEP.BASE).one('#'+CSS.RECOVERGRADES).get('checked')?1:0;
+            if (this.get(UEP.DISABLEGRADEHISTORY) != true) {
+                params['recovergrades'] = this.get(UEP.BASE).one('#'+CSS.RECOVERGRADES).get('checked')?1:0;
+            } else {
+                params['recovergrades'] = 0;
+            }
 
             Y.io(M.cfg.wwwroot+this.get(UEP.AJAXURL), {
                 method:'POST',
index 8769fc4..52b34bf 100644 (file)
@@ -48,33 +48,30 @@ $manager = new course_enrolment_manager($PAGE, $course, $filter);
 $table = new course_enrolment_other_users_table($manager, $PAGE);
 $PAGE->set_url('/enrol/otherusers.php', $manager->get_url_params()+$table->get_url_params());
 
-/***
- * Actions will go here
- */
+$userdetails = array (
+    'picture' => false,
+    'firstname' => get_string('firstname'),
+    'lastname' => get_string('lastname'),
+);
+$extrafields = get_extra_user_fields($context);
+foreach ($extrafields as $field) {
+    $userdetails[$field] = get_user_field_name($field);
+}
 
-/*$fields = array(
-    'userdetails' => array (
-        'picture' => false,
-        'firstname' => get_string('firstname'),
-        'lastname' => get_string('lastname'),
-        'email' => get_string('email')
-    ),
-    'lastseen' => get_string('lastaccess'),
-    'role' => array(
-        'roles' => get_string('roles', 'role'),
-        'context' => get_string('context')
-    )
-);*/
 $fields = array(
-    'userdetails' => array (
-        'picture' => false,
-        'firstname' => get_string('firstname'),
-        'lastname' => get_string('lastname'),
-        'email' => get_string('email')
-    ),
+    'userdetails' => $userdetails,
     'lastseen' => get_string('lastaccess'),
     'role' => get_string('roles', 'role')
 );
+
+// Remove hidden fields if the user has no access
+if (!has_capability('moodle/course:viewhiddenuserfields', $context)) {
+    $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
+    if (isset($hiddenfields['lastaccess'])) {
+        unset($fields['lastseen']);
+    }
+}
+
 $table->set_fields($fields, $OUTPUT);
 
 //$users = $manager->get_other_users($table->sort, $table->sortdirection, $table->page, $table->perpage);
index 8c5f014..b4a6bf4 100644 (file)
@@ -243,7 +243,7 @@ while (!feof($fp)) {
             $eventdata->name              = 'paypal_enrolment';
             $eventdata->userfrom          = $teacher;
             $eventdata->userto            = $user;
-            $eventdata->subject           = get_string("enrolmentnew", '', $shortname);
+            $eventdata->subject           = get_string("enrolmentnew", 'enrol', $shortname);
             $eventdata->fullmessage       = get_string('welcometocoursetext', '', $a);
             $eventdata->fullmessageformat = FORMAT_PLAIN;
             $eventdata->fullmessagehtml   = '';
@@ -262,8 +262,8 @@ while (!feof($fp)) {
             $eventdata->name              = 'paypal_enrolment';
             $eventdata->userfrom          = $user;
             $eventdata->userto            = $teacher;
-            $eventdata->subject           = get_string("enrolmentnew", '', $shortname);
-            $eventdata->fullmessage       = get_string('enrolmentnewuser', '', $a);
+            $eventdata->subject           = get_string("enrolmentnew", 'enrol', $shortname);
+            $eventdata->fullmessage       = get_string('enrolmentnewuser', 'enrol', $a);
             $eventdata->fullmessageformat = FORMAT_PLAIN;
             $eventdata->fullmessagehtml   = '';
             $eventdata->smallmessage      = '';
@@ -281,8 +281,8 @@ while (!feof($fp)) {
                 $eventdata->name              = 'paypal_enrolment';
                 $eventdata->userfrom          = $user;
                 $eventdata->userto            = $admin;
-                $eventdata->subject           = get_string("enrolmentnew", '', $shortname);
-                $eventdata->fullmessage       = get_string('enrolmentnewuser', '', $a);
+                $eventdata->subject           = get_string("enrolmentnew", 'enrol', $shortname);
+                $eventdata->fullmessage       = get_string('enrolmentnewuser', 'enrol', $a);
                 $eventdata->fullmessageformat = FORMAT_PLAIN;
                 $eventdata->fullmessagehtml   = '';
                 $eventdata->smallmessage      = '';
index 8ff9c26..2ebbab5 100644 (file)
@@ -183,6 +183,18 @@ $fields = array(
     'group' => get_string('groups', 'group'),
     'enrol' => get_string('enrolmentinstances', 'enrol')
 );
+
+// Remove hidden fields if the user has no access
+if (!has_capability('moodle/course:viewhiddenuserfields', $context)) {
+    $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
+    if (isset($hiddenfields['lastaccess'])) {
+        unset($fields['lastseen']);
+    }
+    if (isset($hiddenfields['groups'])) {
+        unset($fields['group']);
+    }
+}
+
 $table->set_fields($fields, $renderer);
 
 $canassign = has_capability('moodle/role:assign', $manager->get_context());
@@ -202,4 +214,4 @@ $PAGE->set_heading($PAGE->title);
 echo $OUTPUT->header();
 echo $OUTPUT->heading(get_string('enrolledusers', 'enrol'));
 echo $renderer->render($table);
-echo $OUTPUT->footer();
\ No newline at end of file
+echo $OUTPUT->footer();
index 8592626..20879d9 100644 (file)
@@ -57,7 +57,7 @@ class filter_glossary extends moodle_text_filter {
             $nothingtodo = false;
         }
 
-        if ($nothingtodo === true) {
+        if (($nothingtodo === true) || (!has_capability('mod/glossary:view', $this->context))) {
             return $text;
         }
 
index 6057831..5a268b4 100644 (file)
@@ -355,7 +355,7 @@ class grade_edit_tree {
      * @param string type "extra" or "weight": the type of the column hosting the weight input
      * @return string&nbs