Merge branch 'mdl26_MDL-29004_wiki-fix-images-in-printer-friendly-view' of https...
authorDamyon Wiese <damyon@moodle.com>
Mon, 26 Aug 2013 05:50:20 +0000 (13:50 +0800)
committerDamyon Wiese <damyon@moodle.com>
Mon, 26 Aug 2013 05:50:20 +0000 (13:50 +0800)
381 files changed:
admin/cli/automated_backups.php
admin/cli/install.php
admin/purgecaches.php
admin/qbehaviours.php
admin/qtypes.php
admin/roles/allow.php
admin/roles/assign.php
admin/roles/define.php
admin/roles/manage.php
admin/roles/override.php
admin/settings/server.php
admin/tool/behat/tests/behat/data_generators.feature
admin/tool/generator/classes/backend.php [new file with mode: 0644]
admin/tool/generator/classes/make_form.php [new file with mode: 0644]
admin/tool/generator/cli/generate.php
admin/tool/generator/cli/maketestcourse.php [new file with mode: 0644]
admin/tool/generator/index.php
admin/tool/generator/lang/en/tool_generator.php
admin/tool/generator/maketestcourse.php [new file with mode: 0644]
admin/tool/generator/settings.php [new file with mode: 0644]
admin/tool/generator/tests/maketestcourse_test.php [new file with mode: 0644]
admin/tool/generator/version.php
admin/tool/phpunit/webrunner.php
admin/tool/uploadcourse/classes/helper.php
admin/tool/uploadcourse/classes/processor.php
admin/tool/uploadcourse/classes/step2_form.php
admin/tool/uploadcourse/index.php
admin/tool/uploadcourse/tests/course_test.php
admin/tool/uploadcourse/tests/helper_test.php
admin/webservice/forms.php
auth/cas/cli/sync_users.php
auth/ldap/cli/sync_users.php
backup/backup.php
backup/import.php
backup/moodle2/restore_qtype_plugin.class.php
backup/moodle2/restore_stepslib.php
backup/restore.php
backup/util/factories/backup_factory.class.php
backup/util/factories/tests/factories_test.php
backup/util/plan/restore_plan.class.php
badges/classes/observer.php [new file with mode: 0644]
badges/lib/awardlib.php
badges/renderer.php
badges/tests/badgeslib_test.php
blocks/calendar_upcoming/block_calendar_upcoming.php
blocks/moodleblock.class.php
blocks/tags/block_tags.php
blog/locallib.php
blog/tests/bloglib_test.php
cache/classes/loaders.php
cache/locallib.php
cache/stores/file/lib.php
cache/stores/session/lib.php
cache/stores/session/tests/session_test.php
cache/testperformance.php
cache/tests/administration_helper_test.php
cache/tests/cache_test.php
cache/tests/fixtures/lib.php
calendar/lib.php
calendar/tests/lib_test.php [new file with mode: 0644]
cohort/lib.php
cohort/tests/cohortlib_test.php
completion/completion_completion.php
config-dist.php
course/completion.php
course/delete.php
course/editsection.php
course/format/renderer.php
course/lib.php
course/loginas.php
course/manage.php
course/moodleform_mod.php
course/tests/courselib_test.php
course/yui/dragdrop/dragdrop.js
enrol/flatfile/lib.php
enrol/ldap/cli/sync.php
enrol/tests/enrollib_test.php
enrol/yui/rolemanager/assets/skins/sam/rolemanager.css
enrol/yui/rolemanager/rolemanager.js
files/externallib.php
files/renderer.php
files/tests/externallib_test.php
grade/edit/tree/action.php
grade/edit/tree/lib.php
grade/lib.php
install.php
install/lang/hi/admin.php [new file with mode: 0644]
lang/en/auth.php
lang/en/blog.php
lang/en/cache.php
lang/en/cohort.php
lang/en/completion.php
lang/en/form.php
lang/en/moodle.php
lang/en/role.php
lang/en/webservice.php
lib/accesslib.php
lib/adminlib.php
lib/badgeslib.php
lib/behat/behat_files.php
lib/classes/component.php
lib/classes/event/assessable_submitted.php [new file with mode: 0644]
lib/classes/event/assessable_uploaded.php [new file with mode: 0644]
lib/classes/event/base.php
lib/classes/event/blog_entry_created.php
lib/classes/event/blog_entry_deleted.php [new file with mode: 0644]
lib/classes/event/cohort_created.php [new file with mode: 0644]
lib/classes/event/cohort_deleted.php [new file with mode: 0644]
lib/classes/event/cohort_member_added.php [new file with mode: 0644]
lib/classes/event/cohort_member_removed.php [new file with mode: 0644]
lib/classes/event/cohort_updated.php [new file with mode: 0644]
lib/classes/event/course_category_deleted.php [new file with mode: 0644]
lib/classes/event/course_completed.php [new file with mode: 0644]
lib/classes/event/course_completion_updated.php [new file with mode: 0644]
lib/classes/event/course_content_deleted.php [new file with mode: 0644]
lib/classes/event/course_created.php [new file with mode: 0644]
lib/classes/event/course_deleted.php [new file with mode: 0644]
lib/classes/event/course_module_completion_updated.php [new file with mode: 0644]
lib/classes/event/course_restored.php [new file with mode: 0644]
lib/classes/event/course_section_updated.php [new file with mode: 0644]
lib/classes/event/course_updated.php [new file with mode: 0644]
lib/classes/event/role_allow_assign_updated.php [new file with mode: 0644]
lib/classes/event/role_allow_override_updated.php [new file with mode: 0644]
lib/classes/event/role_allow_switch_updated.php [new file with mode: 0644]
lib/classes/event/role_assigned.php
lib/classes/event/role_capabilities_updated.php [new file with mode: 0644]
lib/classes/event/role_deleted.php [new file with mode: 0644]
lib/classes/event/role_unassigned.php
lib/classes/event/user_loggedin.php
lib/classes/event/user_loggedinas.php [new file with mode: 0644]
lib/classes/string_manager.php [new file with mode: 0644]
lib/classes/string_manager_install.php [new file with mode: 0644]
lib/classes/string_manager_standard.php [new file with mode: 0644]
lib/completionlib.php
lib/coursecatlib.php
lib/cronlib.php
lib/csslib.php
lib/db/caches.php
lib/db/events.php
lib/db/install.xml
lib/db/services.php
lib/db/upgrade.php
lib/ddl/tests/ddl_test.php
lib/ddl/tests/fixtures/invalid.xml
lib/ddl/tests/fixtures/xmldb_table.xml
lib/deprecatedlib.php
lib/dml/mssql_native_moodle_database.php
lib/dml/pdo_moodle_database.php
lib/dml/sqlsrv_native_moodle_database.php
lib/dml/tests/dml_test.php
lib/editor/tinymce/classes/plugin.php
lib/editor/tinymce/cli/update_lang_files.php
lib/editor/tinymce/lib.php
lib/editor/tinymce/module.js
lib/editor/tinymce/plugins/managefiles/tinymce/editor_plugin.js
lib/editor/tinymce/plugins/pdw/readme_moodle.txt
lib/editor/tinymce/plugins/pdw/tinymce/editor_plugin.js
lib/editor/tinymce/styles.css
lib/editor/tinymce/version.php
lib/editor/tinymce/yui/build/moodle-editor_tinymce-collapse/moodle-editor_tinymce-collapse-debug.js [deleted file]
lib/editor/tinymce/yui/build/moodle-editor_tinymce-collapse/moodle-editor_tinymce-collapse-min.js [deleted file]
lib/editor/tinymce/yui/build/moodle-editor_tinymce-collapse/moodle-editor_tinymce-collapse.js [deleted file]
lib/editor/tinymce/yui/src/collapse/build.json [deleted file]
lib/editor/tinymce/yui/src/collapse/js/collapse.js [deleted file]
lib/editor/tinymce/yui/src/collapse/meta/collapse.json [deleted file]
lib/enrollib.php
lib/external/tests/external_test.php
lib/filestorage/file_storage.php
lib/filestorage/tests/file_storage_test.php
lib/filestorage/tests/zip_packer_test.php
lib/form/editor.php
lib/form/filemanager.js
lib/form/tests/dateselector_test.php
lib/form/tests/datetimeselector_test.php
lib/form/tests/duration_test.php
lib/formslib.php
lib/grade/grade_category.php
lib/grade/grade_item.php
lib/grade/grade_object.php
lib/grade/tests/fixtures/lib.php
lib/grade/tests/grade_category_test.php
lib/grade/tests/grade_grade_test.php
lib/grade/tests/grade_item_test.php
lib/grade/tests/grade_scale_test.php
lib/installlib.php
lib/minify/config.php
lib/modinfolib.php
lib/moodlelib.php
lib/navigationlib.php
lib/outputlib.php
lib/outputrenderers.php
lib/outputrequirementslib.php
lib/phpmailer/moodle_phpmailer.php
lib/phpunit/bootstrap.php
lib/phpunit/classes/advanced_testcase.php
lib/phpunit/classes/phpmailer_sink.php [new file with mode: 0644]
lib/phpunit/classes/util.php
lib/phpunit/lib.php
lib/phpunit/tests/advanced_test.php
lib/phpunit/tests/basic_test.php
lib/pluginlib.php
lib/portfoliolib.php
lib/sessionlib.php
lib/setup.php
lib/setuplib.php
lib/simplepie/moodle_simplepie.php
lib/testing/classes/util.php
lib/testing/tests/generator_test.php
lib/tests/accesslib_test.php
lib/tests/behat/behat_data_generators.php
lib/tests/behat/behat_hooks.php
lib/tests/completionlib_test.php
lib/tests/component_test.php
lib/tests/csslib_test.php
lib/tests/environment_test.php
lib/tests/event_test.php
lib/tests/fixtures/event_fixtures.php
lib/tests/sessionlib_test.php [new file with mode: 0644]
lib/tests/statslib_test.php
lib/tests/string_manager_standard_test.php [moved from lib/tests/string_manager_test.php with 95% similarity]
lib/tests/weblib_test.php
lib/upgrade.txt
lib/upgradelib.php
lib/weblib.php
lib/xhprof/xhprof_moodle.php
lib/yui/build/moodle-core-blocks/moodle-core-blocks-debug.js
lib/yui/build/moodle-core-blocks/moodle-core-blocks-min.js
lib/yui/build/moodle-core-blocks/moodle-core-blocks.js
lib/yui/build/moodle-core-chooserdialogue/moodle-core-chooserdialogue-debug.js
lib/yui/build/moodle-core-chooserdialogue/moodle-core-chooserdialogue-min.js
lib/yui/build/moodle-core-chooserdialogue/moodle-core-chooserdialogue.js
lib/yui/build/moodle-core-notification-dialogue/moodle-core-notification-dialogue-debug.js
lib/yui/build/moodle-core-notification-dialogue/moodle-core-notification-dialogue-min.js
lib/yui/build/moodle-core-notification-dialogue/moodle-core-notification-dialogue.js
lib/yui/dragdrop/dragdrop.js
lib/yui/src/blocks/js/blockregion.js
lib/yui/src/blocks/js/blocks.js
lib/yui/src/blocks/js/manager.js
lib/yui/src/chooserdialogue/js/chooserdialogue.js
lib/yui/src/notification/js/dialogue.js
mod/assign/adminlib.php
mod/assign/backup/moodle2/restore_assign_stepslib.php
mod/assign/classes/event/assessable_submitted.php [new file with mode: 0644]
mod/assign/lang/en/assign.php
mod/assign/locallib.php
mod/assign/submission/file/classes/event/assessable_uploaded.php [new file with mode: 0644]
mod/assign/submission/file/lang/en/assignsubmission_file.php
mod/assign/submission/file/locallib.php
mod/assign/submission/file/tests/events_test.php [new file with mode: 0644]
mod/assign/submission/onlinetext/classes/event/assessable_uploaded.php [new file with mode: 0644]
mod/assign/submission/onlinetext/lang/en/assignsubmission_onlinetext.php
mod/assign/submission/onlinetext/locallib.php
mod/assign/submission/onlinetext/tests/events_test.php [new file with mode: 0644]
mod/assign/tests/generator/lib.php
mod/assign/tests/lib_test.php
mod/assignment/type/online/assignment.class.php
mod/assignment/type/online/classes/event/assessable_uploaded.php [new file with mode: 0644]
mod/assignment/type/online/lang/en/assignment_online.php
mod/assignment/type/upload/assignment.class.php
mod/assignment/type/upload/classes/event/assessable_submitted.php [new file with mode: 0644]
mod/assignment/type/upload/classes/event/assessable_uploaded.php [new file with mode: 0644]
mod/assignment/type/upload/lang/en/assignment_upload.php
mod/chat/gui_ajax/index.php
mod/chat/gui_ajax/module.js
mod/chat/gui_ajax/theme/bubble/chat.css
mod/chat/gui_ajax/theme/bubble/config.php
mod/chat/gui_basic/index.php
mod/chat/lib.php
mod/chat/styles.css
mod/data/field/file/field.class.php
mod/data/field/picture/field.class.php
mod/data/lang/en/data.php
mod/data/lib.php
mod/data/module.js [new file with mode: 0644]
mod/data/templates.php
mod/data/tests/lib_test.php [new file with mode: 0644]
mod/data/view.php
mod/forum/backup/moodle2/backup_forum_stepslib.php
mod/forum/backup/moodle2/restore_forum_stepslib.php
mod/forum/classes/event/assessable_uploaded.php [new file with mode: 0644]
mod/forum/classes/post_form.php [new file with mode: 0644]
mod/forum/db/install.xml
mod/forum/db/upgrade.php
mod/forum/index.php
mod/forum/lang/en/forum.php
mod/forum/lib.php
mod/forum/maildigest.php [new file with mode: 0644]
mod/forum/post.php
mod/forum/post_form.php
mod/forum/tests/lib_test.php [new file with mode: 0644]
mod/forum/tests/maildigest_test.php [new file with mode: 0644]
mod/forum/upgrade.txt
mod/forum/version.php
mod/lesson/essay.php
mod/quiz/editlib.php
mod/quiz/lib.php
mod/quiz/mod_form.php
mod/quiz/renderer.php
mod/quiz/report/statistics/report.php
mod/quiz/report/statistics/tests/fixtures/qstats00.csv [new file with mode: 0644]
mod/quiz/report/statistics/tests/fixtures/questions00.csv [new file with mode: 0644]
mod/quiz/report/statistics/tests/fixtures/results00.csv [new file with mode: 0644]
mod/quiz/report/statistics/tests/fixtures/steps00.csv [new file with mode: 0644]
mod/quiz/report/statistics/tests/stats_from_steps_walkthrough_test.php [new file with mode: 0644]
mod/quiz/settings.php
mod/quiz/styles.css
mod/quiz/tests/attempt_walkthrough_from_csv_test.php
mod/resource/tests/generator/lib.php [new file with mode: 0644]
mod/resource/tests/generator_test.php [new file with mode: 0644]
mod/scorm/datamodels/aicc.js.php
mod/scorm/datamodels/aicclib.php
mod/scorm/datamodels/scorm_12.js.php
mod/scorm/datamodels/scorm_13.js.php
mod/scorm/db/upgrade.php
mod/scorm/version.php
mod/workshop/classes/event/assessable_uploaded.php [new file with mode: 0644]
mod/workshop/lang/en/workshop.php
mod/workshop/locallib.php
mod/workshop/renderer.php
mod/workshop/submission.php
phpunit.xml.dist
question/behaviour/manualgraded/tests/walkthrough_test.php
question/category.php
question/category_class.php
question/category_form.php
question/engine/datalib.php
question/engine/lib.php
question/engine/questionattempt.php
question/engine/questionattemptstep.php
question/engine/tests/questionattempt_test.php
question/format.php
question/format/webct/TODO.txt [deleted file]
question/format/webct/format.php
question/format/webct/lang/en/qformat_webct.php
question/format/webct/tests/fixtures/sample_webct.txt [new file with mode: 0644]
question/format/webct/tests/webctformat_test.php [new file with mode: 0644]
question/format/webct/version.php
question/format/xhtml/format.php
question/format/xhtml/lib.php [new file with mode: 0644]
question/type/edit_question_form.php
question/type/essay/question.php
question/type/essay/tests/helper.php
question/type/essay/tests/question_test.php
question/type/essay/tests/walkthrough_test.php
question/type/match/db/upgrade.php
question/type/multianswer/module.js
question/type/multianswer/styles.css
question/type/multichoice/questiontype.php
question/type/numerical/edit_numerical_form.php
question/type/numerical/styles.css
question/type/questionbase.php
question/type/upgrade.txt
report/performance/locallib.php
repository/filepicker.js
repository/skydrive/lib.php
repository/tests/behat/cancel_add_file.feature
tag/coursetags_more.php
tag/coursetagslib.php
tag/locallib.php
tag/upgrade.txt
theme/base/style/admin.css
theme/base/style/core.css
theme/base/style/course.css
theme/base/style/filemanager.css
theme/base/version.php
theme/bootstrapbase/less/moodle/core.less
theme/bootstrapbase/less/moodle/filemanager.less
theme/bootstrapbase/less/moodle/forms.less
theme/bootstrapbase/less/moodle/question.less
theme/bootstrapbase/less/moodle/responsive.less
theme/bootstrapbase/style/moodle.css
theme/bootstrapbase/version.php
theme/upgrade.txt
user/editlib.php
user/externallib.php
user/tests/externallib_test.php
version.php
webservice/externallib.php
webservice/tests/externallib_test.php
webservice/upgrade.txt [new file with mode: 0644]
webservice/upload.php

index dc80c7a..3c3841e 100644 (file)
@@ -75,8 +75,7 @@ if (!empty($CFG->showcronsql)) {
     $DB->set_debug(true);
 }
 if (!empty($CFG->showcrondebugging)) {
-    $CFG->debug = DEBUG_DEVELOPER;
-    $CFG->debugdisplay = true;
+    set_debugging(DEBUG_DEVELOPER, true);
 }
 
 $starttime = microtime();
index 2d992b5..fcd25b2 100644 (file)
@@ -162,6 +162,9 @@ $CFG->running_installer    = true;
 $CFG->early_install_lang   = true;
 $CFG->ostype               = (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) ? 'WINDOWS' : 'UNIX';
 $CFG->dboptions            = array();
+$CFG->debug                = (E_ALL | E_STRICT);
+$CFG->debugdisplay         = true;
+$CFG->debugdeveloper       = true;
 
 $parts = explode('/', str_replace('\\', '/', dirname(dirname(__FILE__))));
 $CFG->admin                = array_pop($parts);
@@ -172,6 +175,9 @@ ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include
 
 require_once($CFG->libdir.'/classes/component.php');
 require_once($CFG->libdir.'/classes/text.php');
+require_once($CFG->libdir.'/classes/string_manager.php');
+require_once($CFG->libdir.'/classes/string_manager_install.php');
+require_once($CFG->libdir.'/classes/string_manager_standard.php');
 require_once($CFG->libdir.'/installlib.php');
 require_once($CFG->libdir.'/clilib.php');
 require_once($CFG->libdir.'/setuplib.php');
index 006bb0d..c2247dc 100644 (file)
@@ -27,37 +27,37 @@ require_once('../config.php');
 require_once($CFG->libdir.'/adminlib.php');
 
 $confirm = optional_param('confirm', 0, PARAM_BOOL);
+$returnurl = optional_param('returnurl', null, PARAM_LOCALURL);
 
-admin_externalpage_setup('purgecaches');
-
-require_login();
-require_capability('moodle/site:config', context_system::instance());
-
-if ($confirm) {
-    require_sesskey();
+// If we have got here as a confirmed aciton, do it.
+if ($confirm && isloggedin() && confirm_sesskey()) {
+    require_capability('moodle/site:config', context_system::instance());
 
-    // Valid request. Purge, and redisplay the form so it is easy to purge again
-    // in the near future.
+    // Valid request. Purge, and redirect the user back to where they came from.
     purge_all_caches();
-    redirect(new moodle_url('/admin/purgecaches.php'), get_string('purgecachesfinished', 'admin'));
-
-} else {
-    // Show a confirm form.
-    echo $OUTPUT->header();
-    echo $OUTPUT->heading(get_string('purgecaches', 'admin'));
-
-    $url = new moodle_url('/admin/purgecaches.php', array('sesskey'=>sesskey(), 'confirm'=>1));
-    $button = new single_button($url, get_string('purgecaches','admin'), 'post');
-
-    // Cancel button takes them back to the page the were on, if possible,
-    // otherwise to the site home page.
-    $return = new moodle_url('/');
-    if (isset($_SERVER['HTTP_REFERER']) and !empty($_SERVER['HTTP_REFERER'])) {
-        if ($_SERVER['HTTP_REFERER'] !== "$CFG->wwwroot/$CFG->admin/purgecaches.php") {
-            $return = $_SERVER['HTTP_REFERER'];
-        }
+
+    if ($returnurl) {
+        $returnurl = $CFG->wwwroot . $returnurl;
+    } else {
+        $returnurl = new moodle_url('/admin/purgecaches.php');
     }
+    redirect($returnurl, get_string('purgecachesfinished', 'admin'));
+}
 
-    echo $OUTPUT->confirm(get_string('purgecachesconfirm', 'admin'), $button, $return);
-    echo $OUTPUT->footer();
+// Otherwise, show a button to actually purge the caches.
+admin_externalpage_setup('purgecaches');
+
+$actionurl = new moodle_url('/admin/purgecaches.php', array('sesskey'=>sesskey(), 'confirm'=>1));
+if ($returnurl) {
+    $actionurl->param('returnurl', $returnurl);
 }
+
+echo $OUTPUT->header();
+echo $OUTPUT->heading(get_string('purgecaches', 'admin'));
+
+echo $OUTPUT->box_start('generalbox', 'notice');
+echo html_writer::tag('p', get_string('purgecachesconfirm', 'admin'));
+echo $OUTPUT->single_button($actionurl, get_string('purgecaches', 'admin'), 'post');
+echo $OUTPUT->box_end();
+
+echo $OUTPUT->footer();
index cb59976..85f0c8e 100644 (file)
@@ -143,7 +143,7 @@ if (($delete = optional_param('delete', '', PARAM_PLUGIN)) && confirm_sesskey())
         print_error('cannotdeletemissingbehaviour', 'question', $thispageurl);
     }
 
-    if (!isset($behaviours[$delete])) {
+    if (!isset($behaviours[$delete]) && !get_config('qbehaviour_' . $delete, 'version')) {
         print_error('unknownbehaviour', 'question', $thispageurl, $delete);
     }
 
@@ -171,10 +171,7 @@ if (($delete = optional_param('delete', '', PARAM_PLUGIN)) && confirm_sesskey())
     echo $OUTPUT->header();
     echo $OUTPUT->heading(get_string('deletingbehaviour', 'question', $behaviourname));
 
-    // Delete any configuration records.
-    if (!unset_all_config_for_plugin('qbehaviour_' . $delete)) {
-        echo $OUTPUT->notification(get_string('errordeletingconfig', 'admin', 'qbehaviour_' . $delete));
-    }
+    // Remove this behaviour from configurations where it might appear.
     if (($key = array_search($delete, $disabledbehaviours)) !== false) {
         unset($disabledbehaviours[$key]);
         set_config('disabledbehaviours', implode(',', $disabledbehaviours), 'question');
@@ -185,12 +182,10 @@ if (($delete = optional_param('delete', '', PARAM_PLUGIN)) && confirm_sesskey())
         set_config('behavioursortorder', implode(',', $behaviourorder), 'question');
     }
 
-    // Then the tables themselves
-    drop_plugin_tables($delete, core_component::get_plugin_directory('qbehaviour', $delete) . '/db/install.xml', false);
-
-    // Remove event handlers and dequeue pending events
-    events_uninstall('qbehaviour_' . $delete);
+    // Then uninstall the plugin.
+    uninstall_plugin('qbehaviour', $delete);
 
+    // Display a message.
     $a = new stdClass();
     $a->behaviour = $behaviourname;
     $a->directory = core_component::get_plugin_directory('qbehaviour', $delete);
index e12d3cc..3e865d1 100644 (file)
@@ -129,7 +129,7 @@ if (($delete = optional_param('delete', '', PARAM_PLUGIN)) && confirm_sesskey())
         print_error('cannotdeletemissingqtype', 'question', $thispageurl);
     }
 
-    if (!isset($qtypes[$delete])) {
+    if (!isset($qtypes[$delete]) && !get_config('qtype_' . $delete, 'version')) {
         print_error('unknownquestiontype', 'question', $thispageurl, $delete);
     }
 
@@ -158,18 +158,12 @@ if (($delete = optional_param('delete', '', PARAM_PLUGIN)) && confirm_sesskey())
     echo $OUTPUT->header();
     echo $OUTPUT->heading(get_string('deletingqtype', 'question', $qtypename));
 
-    // Delete any configuration records.
-    if (!unset_all_config_for_plugin('qtype_' . $delete)) {
-        echo $OUTPUT->notification(get_string('errordeletingconfig', 'admin', 'qtype_' . $delete));
-    }
+    // Delete any questoin configuration records mentioning this plugin.
     unset_config($delete . '_disabled', 'question');
     unset_config($delete . '_sortorder', 'question');
 
-    // Then the tables themselves
-    drop_plugin_tables($delete, $qtypes[$delete]->plugin_dir() . '/db/install.xml', false);
-
-    // Remove event handlers and dequeue pending events
-    events_uninstall('qtype_' . $delete);
+    // Then uninstall the plugin.
+    uninstall_plugin('qtype', $delete);
 
     $a = new stdClass();
     $a->qtype = $qtypename;
index 9b7e709..8ffd54d 100644 (file)
@@ -46,7 +46,22 @@ $controller = new $classformode[$mode]();
 if (optional_param('submit', false, PARAM_BOOL) && data_submitted() && confirm_sesskey()) {
     $controller->process_submission();
     $syscontext->mark_dirty();
-    add_to_log(SITEID, 'role', 'edit allow ' . $mode, str_replace($CFG->wwwroot . '/', '', $baseurl), '', '', $USER->id);
+    $event = null;
+    // Create event depending on mode.
+    switch ($mode) {
+        case 'assign':
+            $event = \core\event\role_allow_assign_updated::create(array('context' => $syscontext));
+            break;
+        case 'override':
+            $event = \core\event\role_allow_override_updated::create(array('context' => $syscontext));
+            break;
+        case 'switch':
+            $event = \core\event\role_allow_switch_updated::create(array('context' => $syscontext));
+            break;
+    }
+    if ($event) {
+        $event->trigger();
+    }
     redirect($baseurl);
 }
 
index 8346640..cce2334 100644 (file)
@@ -110,8 +110,6 @@ if ($roleid) {
             $potentialuserselector->invalidate_selected_users();
             $currentuserselector->invalidate_selected_users();
 
-            $rolename = $assignableroles[$roleid];
-            add_to_log($course->id, 'role', 'assign', 'admin/roles/assign.php?contextid='.$context->id.'&roleid='.$roleid, $rolename, '', $USER->id);
             // Counts have changed, so reload.
             list($assignableroles, $assigncounts, $nameswithcounts) = get_assignable_roles($context, ROLENAME_BOTH, true);
         }
@@ -130,8 +128,6 @@ if ($roleid) {
             $potentialuserselector->invalidate_selected_users();
             $currentuserselector->invalidate_selected_users();
 
-            $rolename = $assignableroles[$roleid];
-            add_to_log($course->id, 'role', 'unassign', 'admin/roles/assign.php?contextid='.$context->id.'&roleid='.$roleid, $rolename, '', $USER->id);
             // Counts have changed, so reload.
             list($assignableroles, $assigncounts, $nameswithcounts) = get_assignable_roles($context, ROLENAME_BOTH, true);
         }
index f588d1a..265b100 100644 (file)
@@ -196,8 +196,22 @@ if (optional_param('cancel', false, PARAM_BOOL)) {
 // Process submission in necessary.
 if (optional_param('savechanges', false, PARAM_BOOL) && confirm_sesskey() && $definitiontable->is_submission_valid()) {
     $definitiontable->save_changes();
-    add_to_log(SITEID, 'role', $action, 'admin/roles/define.php?action=view&roleid=' .
-            $definitiontable->get_role_id(), $definitiontable->get_role_name(), '', $USER->id);
+    $tableroleid = $definitiontable->get_role_id();
+    // Trigger event.
+    $event = \core\event\role_capabilities_updated::create(
+        array(
+            'context' => $systemcontext,
+            'objectid' => $roleid,
+            'other' => array('name' => $definitiontable->get_role_name())
+        )
+    );
+    $event->set_legacy_logdata(array(SITEID, 'role', $action, 'admin/roles/define.php?action=view&roleid=' . $tableroleid,
+        $definitiontable->get_role_name(), '', $USER->id));
+    if (!empty($role)) {
+        $event->add_record_snapshot('role', $role);
+    }
+    $event->trigger();
+
     if ($action === 'add') {
         redirect(new moodle_url('/admin/roles/define.php', array('action'=>'view', 'roleid'=>$definitiontable->get_role_id())));
     } else {
index ec02517..e3e094a 100644 (file)
@@ -90,7 +90,6 @@ switch ($action) {
         }
         // Deleted a role sitewide...
         $systemcontext->mark_dirty();
-        add_to_log(SITEID, 'role', 'delete', 'admin/roles/manage.php', $roles[$roleid]->localname, '', $USER->id);
         redirect($baseurl);
         break;
 
index 7d27dc2..bc506f1 100644 (file)
@@ -125,7 +125,25 @@ $overridestable->read_submitted_permissions();
 if (optional_param('savechanges', false, PARAM_BOOL) && confirm_sesskey()) {
     $overridestable->save_changes();
     $rolename = $overridableroles[$roleid];
-    add_to_log($course->id, 'role', 'override', 'admin/roles/override.php?contextid='.$context->id.'&roleid='.$roleid, $rolename, '', $USER->id);
+    // Trigger event.
+    $event = \core\event\role_capabilities_updated::create(
+        array(
+            'context' => $context,
+            'objectid' => $roleid,
+            'courseid' => $courseid,
+            'other' => array('name' => $rolename)
+        )
+    );
+
+    $event->set_legacy_logdata(
+        array(
+            $course->id, 'role', 'override', 'admin/roles/override.php?contextid=' . $context->id . '&roleid=' . $roleid,
+            $rolename, '', $USER->id
+        )
+    );
+    $event->add_record_snapshot('role', $role);
+    $event->trigger();
+
     redirect($returnurl);
 }
 
index 85e3f2d..3a58d34 100644 (file)
@@ -175,16 +175,25 @@ $ADMIN->add('server', new admin_externalpage('phpinfo', new lang_string('phpinfo
 // "performance" settingpage
 $temp = new admin_settingpage('performance', new lang_string('performance', 'admin'));
 
+// Memory limit options for large administration tasks.
+$memoryoptions = array(
+    '64M' => '64M',
+    '128M' => '128M',
+    '256M' => '256M',
+    '512M' => '512M',
+    '1024M' => '1024M',
+    '2048M' => '2048M');
+
+// Allow larger memory usage for 64-bit sites only.
+if (PHP_INT_SIZE === 8) {
+    $memoryoptions['3072M'] = '3072M';
+    $memoryoptions['4096M'] = '4096M';
+}
+
 $temp->add(new admin_setting_configselect('extramemorylimit', new lang_string('extramemorylimit', 'admin'),
                                           new lang_string('configextramemorylimit', 'admin'), '512M',
-                                          // if this option is set to 0, default 128M will be used
-                                          array( '64M' => '64M',
-                                                 '128M' => '128M',
-                                                 '256M' => '256M',
-                                                 '512M' => '512M',
-                                                 '1024M' => '1024M',
-                                                 '2048M' => '2048M',
-                                             )));
+                                          $memoryoptions));
+
 $temp->add(new admin_setting_configtext('curlcache', new lang_string('curlcache', 'admin'),
                                         new lang_string('configcurlcache', 'admin'), 120, PARAM_INT));
 
index e37f9bc..c0d3665 100644 (file)
@@ -65,6 +65,37 @@ Feature: Set up contextual data for tests
     And I should see "Grouping 1"
     And I should see "Grouping 2"
 
+  @javascript
+  Scenario: Role overrides
+    Given the following "users" exists:
+      | username | firstname | lastname | email |
+      | teacher1 | Teacher | 1 | teacher1@asd.com |
+      | student1 | Student | 1 | student1@asd.com |
+    And the following "categories" exists:
+      | name | category | idnumber |
+      | Cat 1 | 0 | CAT1 |
+    And the following "courses" exists:
+      | fullname | shortname |
+      | Course 1 | C1 |
+    And the following "course enrolments" exists:
+      | user | course | role |
+      | student1 | C1 | student |
+      | teacher1 | C1 | editingteacher |
+    And the following "permission overrides" exists:
+      | capability | permission | role | contextlevel | reference |
+      | mod/forum:editanypost | Allow | student | Course | C1 |
+      | mod/forum:replynews | Prevent | editingteacher | Course | C1 |
+    When I log in as "admin"
+    And I follow "Course 1"
+    And I expand "Users" node
+    And I follow "Permissions"
+    And I select "Student (1)" from "Advanced role override"
+    Then the "mod/forum:editanypost" field should match "1" value
+    And I press "Cancel"
+    And I select "Teacher (1)" from "Advanced role override"
+    And the "mod/forum:replynews" field should match "-1" value
+    And I press "Cancel"
+
   Scenario: Add course enrolments
     Given the following "users" exists:
       | username | firstname | lastname | email |
diff --git a/admin/tool/generator/classes/backend.php b/admin/tool/generator/classes/backend.php
new file mode 100644 (file)
index 0000000..beed421
--- /dev/null
@@ -0,0 +1,606 @@
+<?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/>.
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Backend code for the 'make large course' tool.
+ *
+ * @package tool_generator
+ * @copyright 2013 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class tool_generator_backend {
+    /**
+     * @var int Lowest (smallest) size index
+     */
+    const MIN_SIZE = 0;
+    /**
+     * @var int Highest (largest) size index
+     */
+    const MAX_SIZE = 5;
+    /**
+     * @var int Default size index
+     */
+    const DEFAULT_SIZE = 3;
+
+    /**
+     * @var array Number of sections in course
+     */
+    private static $paramsections = array(1, 10, 100, 500, 1000, 2000);
+    /**
+     * @var array Number of Page activities in course
+     */
+    private static $parampages = array(1, 50, 200, 1000, 5000, 10000);
+    /**
+     * @var array Number of students enrolled in course
+     */
+    private static $paramusers = array(1, 100, 1000, 10000, 50000, 100000);
+    /**
+     * Total size of small files: 1KB, 1MB, 10MB, 100MB, 1GB, 2GB.
+     *
+     * @var array Number of small files created in a single file activity
+     */
+    private static $paramsmallfilecount = array(1, 64, 128, 1024, 16384, 32768);
+    /**
+     * @var array Size of small files (to make the totals into nice numbers)
+     */
+    private static $paramsmallfilesize = array(1024, 16384, 81920, 102400, 65536, 65536);
+    /**
+     * Total size of big files: 8KB, 8MB, 80MB, 800MB, 8GB, 16GB.
+     *
+     * @var array Number of big files created as individual file activities
+     */
+    private static $parambigfilecount = array(1, 2, 5, 10, 10, 10);
+    /**
+     * @var array Size of each large file
+     */
+    private static $parambigfilesize = array(8192, 4194304, 16777216, 83886080,
+            858993459, 1717986918);
+    /**
+     * @var array Number of forum discussions
+     */
+    private static $paramforumdiscussions = array(1, 10, 100, 500, 1000, 2000);
+    /**
+     * @var array Number of forum posts per discussion
+     */
+    private static $paramforumposts = array(2, 2, 5, 10, 10, 10);
+
+    /**
+     * @var string Course shortname
+     */
+    private $shortname;
+
+    /**
+     * @var int Size code (index in the above arrays)
+     */
+    private $size;
+
+    /**
+     * @var bool True if displaying progress
+     */
+    private $progress;
+
+    /**
+     * @var testing_data_generator Data generator
+     */
+    private $generator;
+
+    /**
+     * @var stdClass Course object
+     */
+    private $course;
+
+    /**
+     * @var int Epoch time at which last dot was displayed
+     */
+    private $lastdot;
+
+    /**
+     * @var int Epoch time at which last percentage was displayed
+     */
+    private $lastpercentage;
+
+    /**
+     * @var int Epoch time at which current step (current set of dots) started
+     */
+    private $starttime;
+
+    /**
+     * @var array Array from test user number (1...N) to userid in database
+     */
+    private $userids;
+
+    /**
+     * Constructs object ready to create course.
+     *
+     * @param string $shortname Course shortname
+     * @param int $size Size as numeric index
+     * @param bool $progress True if progress information should be displayed
+     * @return int Course id
+     * @throws coding_exception If parameters are invalid
+     */
+    public function __construct($shortname, $size, $progress = true) {
+        // Check parameter.
+        if ($size < self::MIN_SIZE || $size > self::MAX_SIZE) {
+            throw new coding_exception('Invalid size');
+        }
+
+        // Set parameters.
+        $this->shortname = $shortname;
+        $this->size = $size;
+        $this->progress = $progress;
+    }
+
+    /**
+     * Gets a list of size choices supported by this backend.
+     *
+     * @return array List of size (int) => text description for display
+     */
+    public static function get_size_choices() {
+        $options = array();
+        for ($size = self::MIN_SIZE; $size <= self::MAX_SIZE; $size++) {
+            $options[$size] = get_string('size_' . $size, 'tool_generator');
+        }
+        return $options;
+    }
+
+    /**
+     * Converts a size name into the numeric constant.
+     *
+     * @param string $sizename Size name e.g. 'L'
+     * @return int Numeric version
+     * @throws coding_exception If the size name is not known
+     */
+    public static function size_for_name($sizename) {
+        for ($size = self::MIN_SIZE; $size <= self::MAX_SIZE; $size++) {
+            if ($sizename == get_string('shortsize_' . $size, 'tool_generator')) {
+                return $size;
+            }
+        }
+        throw new coding_exception("Unknown size name '$sizename'");
+    }
+
+    /**
+     * Checks that a shortname is available (unused).
+     *
+     * @param string $shortname Proposed course shortname
+     * @return string An error message if the name is unavailable or '' if OK
+     */
+    public static function check_shortname_available($shortname) {
+        global $DB;
+        $fullname = $DB->get_field('course', 'fullname',
+                array('shortname' => $shortname), IGNORE_MISSING);
+        if ($fullname !== false) {
+            // I wanted to throw an exception here but it is not possible to
+            // use strings from moodle.php in exceptions, and I didn't want
+            // to duplicate the string in tool_generator, so I changed this to
+            // not use exceptions.
+            return get_string('shortnametaken', 'moodle', $fullname);
+        }
+        return '';
+    }
+
+    /**
+     * Runs the entire 'make' process.
+     *
+     * @return int Course id
+     */
+    public function make() {
+        global $DB, $CFG;
+        require_once($CFG->dirroot . '/lib/phpunit/classes/util.php');
+
+        raise_memory_limit(MEMORY_EXTRA);
+
+        if ($this->progress && !CLI_SCRIPT) {
+            echo html_writer::start_tag('ul');
+        }
+
+        $entirestart = microtime(true);
+
+        // Start transaction.
+        $transaction = $DB->start_delegated_transaction();
+
+        // Get generator.
+        $this->generator = phpunit_util::get_data_generator();
+
+        // Make course.
+        $this->course = $this->create_course();
+        $this->create_users();
+        $this->create_pages();
+        $this->create_small_files();
+        $this->create_big_files();
+        $this->create_forum();
+
+        // Log total time.
+        $this->log('complete', round(microtime(true) - $entirestart, 1));
+
+        if ($this->progress && !CLI_SCRIPT) {
+            echo html_writer::end_tag('ul');
+        }
+
+        // Commit transaction and finish.
+        $transaction->allow_commit();
+        return $this->course->id;
+    }
+
+    /**
+     * Creates the actual course.
+     *
+     * @return stdClass Course record
+     */
+    private function create_course() {
+        $this->log('createcourse', $this->shortname);
+        $courserecord = array('shortname' => $this->shortname,
+                'fullname' => get_string('fullname', 'tool_generator',
+                    array('size' => get_string('shortsize_' . $this->size, 'tool_generator'))),
+                'numsections' => self::$paramsections[$this->size]);
+        return $this->generator->create_course($courserecord, array('createsections' => true));
+    }
+
+    /**
+     * Creates a number of user accounts and enrols them on the course.
+     * Note: Existing user accounts that were created by this system are
+     * reused if available.
+     */
+    private function create_users() {
+        global $DB;
+
+        // Work out total number of users.
+        $count = self::$paramusers[$this->size];
+
+        // Get existing users in order. We will 'fill up holes' in this up to
+        // the required number.
+        $this->log('checkaccounts', $count);
+        $nextnumber = 1;
+        $rs = $DB->get_recordset_select('user', $DB->sql_like('username', '?'),
+                array('tool_generator_%'), 'username', 'id, username');
+        foreach ($rs as $rec) {
+            // Extract number from username.
+            $matches = array();
+            if (!preg_match('~^tool_generator_([0-9]{6})$~', $rec->username, $matches)) {
+                continue;
+            }
+            $number = (int)$matches[1];
+
+            // Create missing users in range up to this.
+            if ($number != $nextnumber) {
+                $this->create_user_accounts($nextnumber, min($number - 1, $count));
+            } else {
+                $this->userids[$number] = (int)$rec->id;
+            }
+
+            // Stop if we've got enough users.
+            $nextnumber = $number + 1;
+            if ($number >= $count) {
+                break;
+            }
+        }
+        $rs->close();
+
+        // Create users from end of existing range.
+        if ($nextnumber <= $count) {
+            $this->create_user_accounts($nextnumber, $count);
+        }
+
+        // Assign all users to course.
+        $this->log('enrol', $count, true);
+
+        $enrolplugin = enrol_get_plugin('manual');
+        $instances = enrol_get_instances($this->course->id, true);
+        foreach ($instances as $instance) {
+            if ($instance->enrol === 'manual') {
+                break;
+            }
+        }
+        if ($instance->enrol !== 'manual') {
+            throw new coding_exception('No manual enrol plugin in course');
+        }
+        $role = $DB->get_record('role', array('shortname' => 'student'), '*', MUST_EXIST);
+
+        for ($number = 1; $number <= $count; $number++) {
+            // Enrol user.
+            $enrolplugin->enrol_user($instance, $this->userids[$number], $role->id);
+            $this->dot($number, $count);
+        }
+
+        $this->end_log();
+    }
+
+    /**
+     * Creates user accounts with a numeric range.
+     *
+     * @param int $first Number of first user
+     * @param int $last Number of last user
+     */
+    private function create_user_accounts($first, $last) {
+        $this->log('createaccounts', (object)array('from' => $first, 'to' => $last), true);
+        $count = $last - $first + 1;
+        $done = 0;
+        for ($number = $first; $number <= $last; $number++, $done++) {
+            // Work out username with 6-digit number.
+            $textnumber = (string)$number;
+            while (strlen($textnumber) < 6) {
+                $textnumber = '0' . $textnumber;
+            }
+            $username = 'tool_generator_' . $textnumber;
+
+            // Create user account.
+            $record = array('firstname' => get_string('firstname', 'tool_generator'),
+                    'lastname' => $number, 'username' => $username);
+            $user = $this->generator->create_user($record);
+            $this->userids[$number] = (int)$user->id;
+            $this->dot($done, $count);
+        }
+        $this->end_log();
+    }
+
+    /**
+     * Creates a number of Page activities.
+     */
+    private function create_pages() {
+        // Set up generator.
+        $pagegenerator = $this->generator->get_plugin_generator('mod_page');
+
+        // Create pages.
+        $number = self::$parampages[$this->size];
+        $this->log('createpages', $number, true);
+        for ($i=0; $i<$number; $i++) {
+            $record = array('course' => $this->course->id);
+            $options = array('section' => $this->get_random_section());
+            $pagegenerator->create_instance($record, $options);
+            $this->dot($i, $number);
+        }
+
+        $this->end_log();
+    }
+
+    /**
+     * Creates one resource activity with a lot of small files.
+     */
+    private function create_small_files() {
+        $count = self::$paramsmallfilecount[$this->size];
+        $this->log('createsmallfiles', $count, true);
+
+        // Create resource with default textfile only.
+        $resourcegenerator = $this->generator->get_plugin_generator('mod_resource');
+        $record = array('course' => $this->course->id,
+                'name' => get_string('smallfiles', 'tool_generator'));
+        $options = array('section' => 0);
+        $resource = $resourcegenerator->create_instance($record, $options);
+
+        // Add files.
+        $fs = get_file_storage();
+        $context = context_module::instance($resource->cmid);
+        $filerecord = array('component' => 'mod_resource', 'filearea' => 'content',
+                'contextid' => $context->id, 'itemid' => 0, 'filepath' => '/');
+        for ($i = 0; $i < $count; $i++) {
+            $filerecord['filename'] = 'smallfile' . $i . '.dat';
+
+            // Generate random binary data (different for each file so it
+            // doesn't compress unrealistically).
+            $data = self::get_random_binary(self::$paramsmallfilesize[$this->size]);
+
+            $fs->create_file_from_string($filerecord, $data);
+            $this->dot($i, $count);
+        }
+
+        $this->end_log();
+    }
+
+    /**
+     * Creates a string of random binary data. The start of the string includes
+     * the current time, in an attempt to avoid large-scale repetition.
+     *
+     * @param int $length Number of bytes
+     * @return Random data
+     */
+    private static function get_random_binary($length) {
+        $data = microtime(true);
+        if (strlen($data) > $length) {
+            // Use last digits of data.
+            return substr($data, -$length);
+        }
+        $length -= strlen($data);
+        for ($j=0; $j < $length; $j++) {
+            $data .= chr(rand(1, 255));
+        }
+        return $data;
+    }
+
+    /**
+     * Creates a number of resource activities with one big file each.
+     */
+    private function create_big_files() {
+        global $CFG;
+
+        // Work out how many files and how many blocks to use (up to 64KB).
+        $count = self::$parambigfilecount[$this->size];
+        $blocks = ceil(self::$parambigfilesize[$this->size] / 65536);
+        $blocksize = floor(self::$parambigfilesize[$this->size] / $blocks);
+
+        $this->log('createbigfiles', $count, true);
+
+        // Prepare temp area.
+        $tempfolder = make_temp_directory('tool_generator');
+        $tempfile = $tempfolder . '/' . rand();
+
+        // Create resources and files.
+        $fs = get_file_storage();
+        $resourcegenerator = $this->generator->get_plugin_generator('mod_resource');
+        for ($i = 0; $i < $count; $i++) {
+            // Create resource.
+            $record = array('course' => $this->course->id,
+                    'name' => get_string('bigfile', 'tool_generator', $i));
+            $options = array('section' => $this->get_random_section());
+            $resource = $resourcegenerator->create_instance($record, $options);
+
+            // Write file.
+            $handle = fopen($tempfile, 'w');
+            if (!$handle) {
+                throw new coding_exception('Failed to open temporary file');
+            }
+            for ($j = 0; $j < $blocks; $j++) {
+                $data = self::get_random_binary($blocksize);
+                fwrite($handle, $data);
+                $this->dot($i * $blocks + $j, $count * $blocks);
+            }
+            fclose($handle);
+
+            // Add file.
+            $context = context_module::instance($resource->cmid);
+            $filerecord = array('component' => 'mod_resource', 'filearea' => 'content',
+                    'contextid' => $context->id, 'itemid' => 0, 'filepath' => '/',
+                    'filename' => 'bigfile' . $i . '.dat');
+            $fs->create_file_from_pathname($filerecord, $tempfile);
+        }
+
+        unlink($tempfile);
+        $this->end_log();
+    }
+
+    /**
+     * Creates one forum activity with a bunch of posts.
+     */
+    private function create_forum() {
+        global $DB;
+
+        $discussions = self::$paramforumdiscussions[$this->size];
+        $posts = self::$paramforumposts[$this->size];
+        $totalposts = $discussions * $posts;
+
+        $this->log('createforum', $totalposts, true);
+
+        // Create empty forum.
+        $forumgenerator = $this->generator->get_plugin_generator('mod_forum');
+        $record = array('course' => $this->course->id,
+                'name' => get_string('pluginname', 'forum'));
+        $options = array('section' => 0);
+        $forum = $forumgenerator->create_instance($record, $options);
+
+        // Add discussions and posts.
+        $sofar = 0;
+        for ($i=0; $i < $discussions; $i++) {
+            $record = array('forum' => $forum->id, 'course' => $this->course->id,
+                    'userid' => $this->get_random_user());
+            $discussion = $forumgenerator->create_discussion($record);
+            $parentid = $DB->get_field('forum_posts', 'id', array('discussion' => $discussion->id), MUST_EXIST);
+            $sofar++;
+            for ($j=0; $j < $posts - 1; $j++, $sofar++) {
+                $record = array('discussion' => $discussion->id,
+                        'userid' => $this->get_random_user(), 'parent' => $parentid);
+                $forumgenerator->create_post($record);
+                $this->dot($sofar, $totalposts);
+            }
+        }
+
+        $this->end_log();
+    }
+
+    /**
+     * Gets a random section number.
+     *
+     * @return int A section number from 1 to the number of sections
+     */
+    private function get_random_section() {
+        return rand(1, self::$paramsections[$this->size]);
+    }
+
+    /**
+     * Gets a random user id.
+     *
+     * @return int A user id for a random created user
+     */
+    private function get_random_user() {
+        return $this->userids[rand(1, self::$paramusers[$this->size])];
+    }
+
+    /**
+     * Displays information as part of progress.
+     * @param string $langstring Part of langstring (after progress_)
+     * @param mixed $a Optional lang string parameters
+     * @param bool $leaveopen If true, doesn't close LI tag (ready for dots)
+     */
+    private function log($langstring, $a = null, $leaveopen = false) {
+        if (!$this->progress) {
+            return;
+        }
+        if (CLI_SCRIPT) {
+            echo '* ';
+        } else {
+            echo html_writer::start_tag('li');
+        }
+        echo get_string('progress_' . $langstring, 'tool_generator', $a);
+        if (!$leaveopen) {
+            if (CLI_SCRIPT) {
+                echo "\n";
+            } else {
+                echo html_writer::end_tag('li');
+            }
+        } else {
+            echo ': ';
+            $this->lastdot = time();
+            $this->lastpercentage = $this->lastdot;
+            $this->starttime = microtime(true);
+        }
+    }
+
+    /**
+     * Outputs dots. There is up to one dot per second. Once a minute, it
+     * displays a percentage.
+     * @param int $number Number of completed items
+     * @param int $total Total number of items to complete
+     */
+    private function dot($number, $total) {
+        if (!$this->progress) {
+            return;
+        }
+        $now = time();
+        if ($now == $this->lastdot) {
+            return;
+        }
+        $this->lastdot = $now;
+        if (CLI_SCRIPT) {
+            echo '.';
+        } else {
+            echo ' . ';
+        }
+        if ($now - $this->lastpercentage >= 30) {
+            echo round(100.0 * $number / $total, 1) . '%';
+            $this->lastpercentage = $now;
+        }
+
+        // Update time limit so PHP doesn't time out.
+        if (!CLI_SCRIPT) {
+            set_time_limit(120);
+        }
+    }
+
+    /**
+     * Ends a log string that was started using log function with $leaveopen.
+     */
+    private function end_log() {
+        if (!$this->progress) {
+            return;
+        }
+        echo get_string('done', 'tool_generator', round(microtime(true) - $this->starttime, 1));
+        if (CLI_SCRIPT) {
+            echo "\n";
+        } else {
+            echo html_writer::end_tag('li');
+        }
+    }
+}
diff --git a/admin/tool/generator/classes/make_form.php b/admin/tool/generator/classes/make_form.php
new file mode 100644 (file)
index 0000000..25c8350
--- /dev/null
@@ -0,0 +1,59 @@
+<?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/>.
+
+defined('MOODLE_INTERNAL') || die();
+
+require_once($CFG->libdir . '/formslib.php');
+
+/**
+ * Form with options for creating large course.
+ *
+ * @package tool_generator
+ * @copyright 2013 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class tool_generator_make_form extends moodleform {
+
+    public function definition() {
+        $mform = $this->_form;
+
+        $mform->addElement('select', 'size', get_string('size', 'tool_generator'),
+                tool_generator_backend::get_size_choices());
+        $mform->setDefault('size', tool_generator_backend::DEFAULT_SIZE);
+
+        $mform->addElement('text', 'shortname', get_string('shortnamecourse'));
+        $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
+        $mform->setType('shortname', PARAM_TEXT);
+
+        $mform->addElement('submit', 'submit', get_string('createcourse', 'tool_generator'));
+    }
+
+    public function validation($data, $files) {
+        global $DB;
+        $errors = array();
+
+        // Check course doesn't already exist.
+        if (!empty($data['shortname'])) {
+            // Check shortname.
+            $error =  tool_generator_backend::check_shortname_available($data['shortname']);
+            if ($error) {
+                $errors['shortname'] = $error;
+            }
+        }
+
+        return $errors;
+    }
+}
index 4514fd7..353883e 100644 (file)
@@ -28,7 +28,7 @@ define('CLI_SCRIPT', true);
 require(dirname(__FILE__) . '/../../../../config.php');
 require_once(dirname(__FILE__) . '/../locallib.php');
 
-if (!debugging('', DEBUG_DEVELOPER)) {
+if (!$CFG->debugdeveloper) {
     echo("This script is for developers only!!!\n");
     exit(1);
 }
diff --git a/admin/tool/generator/cli/maketestcourse.php b/admin/tool/generator/cli/maketestcourse.php
new file mode 100644 (file)
index 0000000..b646e2f
--- /dev/null
@@ -0,0 +1,94 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * CLI interface for creating a test course.
+ *
+ * @package tool_generator
+ * @copyright 2013 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+define('CLI_SCRIPT', true);
+define('NO_OUTPUT_BUFFERING', true);
+
+require(dirname(__FILE__) . '/../../../../config.php');
+require_once($CFG->libdir. '/clilib.php');
+
+// CLI options.
+list($options, $unrecognized) = cli_get_params(
+    array(
+        'help' => false,
+        'shortname' => false,
+        'size' => false,
+        'bypasscheck' => false,
+        'quiet' => false
+    ),
+    array(
+        'h' => 'help'
+    )
+);
+
+// Display help.
+if (!empty($options['help']) || empty($options['shortname']) || empty($options['size'])) {
+    echo "
+Utility to create standard test course. (Also available in GUI interface.)
+
+Not for use on live sites; only normally works if debugging is set to DEVELOPER
+level.
+
+Options:
+--shortname    Shortname of course to create (required)
+--size         Size of course to create XS, S, M, L, XL, or XXL (required)
+--bypasscheck  Bypasses the developer-mode check (be careful!)
+--quiet        Do not show any output
+
+-h, --help     Print out this help
+
+Example from Moodle root directory:
+\$ php admin/tool/generator/cli/maketestcourse.php --shortname=SIZE_S --size=S
+";
+    // Exit with error unless we're showing this because they asked for it.
+    exit(empty($options['help']) ? 1 : 0);
+}
+
+// Check debugging is set to developer level.
+if (empty($options['bypasscheck']) && !debugging('', DEBUG_DEVELOPER)) {
+    cli_error(get_string('error_notdebugging', 'tool_generator'));
+}
+
+// Get options.
+$shortname = $options['shortname'];
+$sizename = $options['size'];
+
+// Check size.
+try {
+    $size = tool_generator_backend::size_for_name($sizename);
+} catch (coding_exception $e) {
+    cli_error("Invalid size ($sizename). Use --help for help.");
+}
+
+// Check shortname.
+if ($error = tool_generator_backend::check_shortname_available($shortname)) {
+    cli_error($error);
+}
+
+// Switch to admin user account.
+session_set_user(get_admin());
+
+// Do backend code to generate course.
+$backend = new tool_generator_backend($shortname, $size, empty($options['quiet']));
+$id = $backend->make();
index f77c8e0..7a917e9 100644 (file)
@@ -34,7 +34,7 @@ if (!is_siteadmin()) {
     error('Only for admins');
 }
 
-if (!debugging('', DEBUG_DEVELOPER)) {
+if (!$CFG->debugdeveloper) {
     error('This script is for developers only!!!');
 }
 
index 051d04f..103a4fd 100644 (file)
 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
 
 /**
- * Strings for component 'tool_generator', language 'en', branch 'MOODLE_22_STABLE'
+ * Language strings.
  *
- * @package    tool
- * @subpackage generator
- * @copyright  2011 Petr Skoda
- * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @package tool_generator
+ * @copyright 2013 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  */
 
+$string['bigfile'] = 'Big file {$a}';
+$string['createcourse'] = 'Create course';
+$string['creating'] = 'Creating course';
+$string['done'] = 'done ({$a}s)';
+$string['explanation'] = 'This tool creates standard test courses that include many
+sections, activities, and files.
+
+This is intended to provide a standardised measure for checking the reliability
+and performance of various system components (such as backup and restore).
+
+This test is important because there have been many cases previously where,
+faced with real-life use cases (e.g. a course with 1,000 activities), the system
+does not work.
+
+Courses created using this feature can occupy a large amount of database and
+filesystem space (tens of gigabytes). You will need to delete the courses
+(and wait for various cleanup runs) to release this space again.
+
+**Do not use this feature on a live system**. Use only on a developer server.
+(To avoid accidental use, this feature is disabled unless you have also selected
+DEVELOPER debugging level.)';
+
+$string['error_notdebugging'] = 'Not available on this server because debugging is not set to DEVELOPER';
+$string['firstname'] = 'Test course user';
+$string['fullname'] = 'Test course: {$a->size}';
+$string['maketestcourse'] = 'Make test course';
 $string['pluginname'] = 'Random course generator';
+$string['progress_createcourse'] = 'Creating course {$a}';
+$string['progress_checkaccounts'] = 'Checking user accounts ({$a})';
+$string['progress_createaccounts'] = 'Creating user accounts ({$a->from} - {$a->to})';
+$string['progress_createbigfiles'] = 'Creating big files ({$a})';
+$string['progress_createforum'] = 'Creating forum ({$a} posts)';
+$string['progress_createpages'] = 'Creating pages ({$a})';
+$string['progress_createsmallfiles'] = 'Creating small files ({$a})';
+$string['progress_enrol'] = 'Enrolling users into course ({$a})';
+$string['progress_complete'] = 'Complete ({$a}s)';
+$string['shortsize_0'] = 'XS';
+$string['shortsize_1'] = 'S';
+$string['shortsize_2'] = 'M';
+$string['shortsize_3'] = 'L';
+$string['shortsize_4'] = 'XL';
+$string['shortsize_5'] = 'XXL';
+$string['size'] = 'Size of course';
+$string['size_0'] = 'XS (~10KB; create in ~1 second)';
+$string['size_1'] = 'S (~10MB; create in ~30 seconds)';
+$string['size_2'] = 'M (~100MB; create in ~5 minutes)';
+$string['size_3'] = 'L (~1GB; create in ~1 hour)';
+$string['size_4'] = 'XL (~10GB; create in ~4 hours)';
+$string['size_5'] = 'XXL (~20GB; create in ~8 hours)';
+$string['smallfiles'] = 'Small files';
diff --git a/admin/tool/generator/maketestcourse.php b/admin/tool/generator/maketestcourse.php
new file mode 100644 (file)
index 0000000..f3ff9f7
--- /dev/null
@@ -0,0 +1,70 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Script creates a standardised large course for testing reliability and
+ * performance.
+ *
+ * @package tool_generator
+ * @copyright 2013 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+// Disable buffering so that the progress output displays gradually without
+// needing to call flush().
+define('NO_OUTPUT_BUFFERING', true);
+
+require('../../../config.php');
+
+require_once($CFG->libdir . '/adminlib.php');
+
+// Initialise page and check permissions.
+admin_externalpage_setup('toolgenerator');
+
+// Start page.
+echo $OUTPUT->header();
+echo $OUTPUT->heading(get_string('maketestcourse', 'tool_generator'));
+
+// Information message.
+$context = context_system::instance();
+echo $OUTPUT->box(format_text(get_string('explanation', 'tool_generator'),
+        FORMAT_MARKDOWN, array('context' => $context)));
+
+// Check debugging is set to DEVELOPER.
+if (!debugging('', DEBUG_DEVELOPER)) {
+    echo $OUTPUT->notification(get_string('error_notdebugging', 'tool_generator'));
+    echo $OUTPUT->footer();
+    exit;
+}
+
+// Set up the form.
+$mform = new tool_generator_make_form('maketestcourse.php');
+if ($data = $mform->get_data()) {
+    // Do actual work.
+    echo $OUTPUT->heading(get_string('creating', 'tool_generator'));
+    $backend = new tool_generator_backend($data->shortname, $data->size);
+    $id = $backend->make();
+
+    echo html_writer::div(
+            html_writer::link(new moodle_url('/course/view.php', array('id' => $id)),
+                get_string('continue')));
+} else {
+    // Display form.
+    $mform->display();
+}
+
+// Finish page.
+echo $OUTPUT->footer();
diff --git a/admin/tool/generator/settings.php b/admin/tool/generator/settings.php
new file mode 100644 (file)
index 0000000..39a40ae
--- /dev/null
@@ -0,0 +1,32 @@
+<?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/>.
+
+/**
+ * Admin settings.
+ *
+ * @package tool_generator
+ * @copyright 2013 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die;
+
+if ($hassiteconfig) {
+    $ADMIN->add('development', new admin_externalpage('toolgenerator',
+            get_string('maketestcourse', 'tool_generator'),
+            $CFG->wwwroot . '/' . $CFG->admin . '/tool/generator/maketestcourse.php'));
+}
+
diff --git a/admin/tool/generator/tests/maketestcourse_test.php b/admin/tool/generator/tests/maketestcourse_test.php
new file mode 100644 (file)
index 0000000..3b2244d
--- /dev/null
@@ -0,0 +1,110 @@
+<?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/>.
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Automated unit testing. This tests the 'make large course' backend,
+ * using the 'XS' option so that it completes quickly.
+ *
+ * @package tool_generator
+ * @copyright 2013 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class tool_generator_maketestcourse_testcase extends advanced_testcase {
+    /**
+     * Creates a small test course and checks all the components have been put in place.
+     */
+    public function test_make_xs_course() {
+        global $DB;
+
+        $this->resetAfterTest();
+        $this->setAdminUser();
+
+        // Create the XS course.
+        $backend = new tool_generator_backend('TOOL_MAKELARGECOURSE_XS', 0, false);
+        $courseid = $backend->make();
+
+        // Get course details.
+        $course = get_course($courseid);
+        $context = context_course::instance($courseid);
+        $modinfo = get_fast_modinfo($course);
+
+        // Check sections (just section 0 plus one other).
+        $this->assertEquals(2, count($modinfo->get_section_info_all()));
+
+        // Check user is enrolled.
+        $users = get_enrolled_users($context);
+        $this->assertEquals(1, count($users));
+        $this->assertEquals('tool_generator_000001', reset($users)->username);
+
+        // Check there's a page on the course.
+        $pages = $modinfo->get_instances_of('page');
+        $this->assertEquals(1, count($pages));
+
+        // Check there are small files.
+        $resources = $modinfo->get_instances_of('resource');
+        $ok = false;
+        foreach ($resources as $resource) {
+            if ($resource->sectionnum == 0) {
+                // The one in section 0 is the 'small files' resource.
+                $ok = true;
+                break;
+            }
+        }
+        $this->assertTrue($ok);
+
+        // Check it contains 2 files (the default txt and a dat file).
+        $fs = get_file_storage();
+        $resourcecontext = context_module::instance($resource->id);
+        $files = $fs->get_area_files($resourcecontext->id, 'mod_resource', 'content', false, 'filename', false);
+        $files = array_values($files);
+        $this->assertEquals(2, count($files));
+        $this->assertEquals('resource1.txt', $files[0]->get_filename());
+        $this->assertEquals('smallfile0.dat', $files[1]->get_filename());
+
+        // Check there's a single 'big' file (it's actually only 8KB).
+        $ok = false;
+        foreach ($resources as $resource) {
+            if ($resource->sectionnum == 1) {
+                $ok = true;
+                break;
+            }
+        }
+        $this->assertTrue($ok);
+
+        // Check it contains 2 files.
+        $resourcecontext = context_module::instance($resource->id);
+        $files = $fs->get_area_files($resourcecontext->id, 'mod_resource', 'content', false, 'filename', false);
+        $files = array_values($files);
+        $this->assertEquals(2, count($files));
+        $this->assertEquals('bigfile0.dat', $files[0]->get_filename());
+        $this->assertEquals('resource2.txt', $files[1]->get_filename());
+
+        // Get forum and count the number of posts on it.
+        $forums = $modinfo->get_instances_of('forum');
+        $forum = reset($forums);
+        $posts = $DB->count_records_sql("
+                SELECT
+                    COUNT(1)
+                FROM
+                    {forum_posts} fp
+                    JOIN {forum_discussions} fd ON fd.id = fp.discussion
+                WHERE
+                    fd.forum = ?", array($forum->instance));
+        $this->assertEquals(2, $posts);
+    }
+}
index 0e01250..66aa662 100644 (file)
 /**
  * Version details.
  *
- * @package    tool
- * @subpackage generator
- * @copyright  2009 Nicolas Connault
- * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @package tool_generator
+ * @copyright 2013 The Open University
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  */
 
 defined('MOODLE_INTERNAL') || die();
 
-$plugin->version   = 2013050100; // The current plugin version (Date: YYYYMMDDXX)
-$plugin->requires  = 2013050100; // Requires this Moodle version
-$plugin->component = 'tool_generator'; // Full name of the plugin (used for diagnostics)
-
-$plugin->maturity  = MATURITY_ALPHA; // this version's maturity level
+$plugin->version = 2013080700;
+$plugin->requires = 2013080200;
+$plugin->component = 'tool_generator';
index f697f7e..f52bf6b 100644 (file)
@@ -34,7 +34,7 @@ $execute   = optional_param('execute', 0, PARAM_BOOL);
 navigation_node::override_active_url(new moodle_url('/admin/tool/phpunit/index.php'));
 admin_externalpage_setup('toolphpunitwebrunner');
 
-if (!debugging('', DEBUG_DEVELOPER)) {
+if (!$CFG->debugdeveloper) {
     error('Not available on production sites, sorry.');
 }
 
@@ -82,7 +82,7 @@ if ($execute) {
         if ($code != 0) {
             tool_phpunit_problem('Can not initialize database');
         }
-        $CFG->debug = 0; // no pesky redirect warning, we really want to redirect
+        set_debugging(DEBUG_NONE, false); // Hack: no redirect warning, we really want to redirect.
         redirect(new moodle_url($PAGE->url, array('execute'=>1, 'tespath'=>$testpath, 'testclass'=>$testclass, 'sesskey'=>sesskey())), 'Reloading page');
         echo $OUTPUT->footer();
         die();
@@ -103,7 +103,7 @@ if ($execute) {
         if ($code != 0) {
             tool_phpunit_problem('Can not initialize database');
         }
-        $CFG->debug = 0; // no pesky redirect warning, we really want to redirect
+        set_debugging(DEBUG_NONE, false); // Hack: no redirect warning, we really want to redirect.
         redirect(new moodle_url($PAGE->url, array('execute'=>1, 'tespath'=>$testpath, 'testclass'=>$testclass, 'sesskey'=>sesskey())), 'Reloading page');
         die();
 
index ebd0b75..2873f3b 100644 (file)
@@ -37,31 +37,6 @@ require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
  */
 class tool_uploadcourse_helper {
 
-    /**
-     * Remove the restore content from disk and cache.
-     *
-     * @return void
-     */
-    public static function clean_restore_content() {
-        global $CFG;
-
-        // There are some sloppy unclosed file handles in backup/restore code,
-        // let's hope somebody unset all controllers before calling this
-        // and destroy magic will close all remaining open file handles,
-        // otherwise Windows will fail deleting the directory.
-        gc_collect_cycles();
-
-        if (!empty($CFG->keeptempdirectoriesonbackup)) {
-            $cache = cache::make('tool_uploadcourse', 'helper');
-            $backupids = (array) $cache->get('backupids');
-            foreach ($backupids as $cachekey => $backupid) {
-                $cache->delete($cachekey);
-                fulldelete("$CFG->tempdir/backup/$backupid/");
-            }
-            $cache->delete('backupids');
-        }
-    }
-
     /**
      * Generate a shortname based on a template.
      *
@@ -216,7 +191,9 @@ class tool_uploadcourse_helper {
      * Get the restore content tempdir.
      *
      * The tempdir is the sub directory in which the backup has been extracted.
-     * This caches the result for better performance.
+     *
+     * This caches the result for better performance, but $CFG->keeptempdirectoriesonbackup
+     * needs to be enabled, otherwise the cache is ignored.
      *
      * @param string $backupfile path to a backup file.
      * @param string $shortname shortname of a course.
@@ -229,6 +206,10 @@ class tool_uploadcourse_helper {
         $cachekey = null;
         if (!empty($backupfile)) {
             $backupfile = realpath($backupfile);
+            if (empty($backupfile) || !is_readable($backupfile)) {
+                $errors['cannotreadbackupfile'] = new lang_string('cannotreadbackupfile', 'tool_uploadcourse');
+                return false;
+            }
             $cachekey = 'backup_path:' . $backupfile;
         } else if (!empty($shortname) || is_numeric($shortname)) {
             $cachekey = 'backup_sn:' . $shortname;
@@ -238,23 +219,27 @@ class tool_uploadcourse_helper {
             return false;
         }
 
-        $cache = cache::make('tool_uploadcourse', 'helper');
-        if (($backupid = $cache->get($cachekey)) === false) {
-            // Use false instead of null because it would consider that the cache
-            // key has not been set.
-            $backupid = false;
+        // If $CFG->keeptempdirectoriesonbackup is not set to true, any restore happening would
+        // automatically delete the backup directory... causing the cache to return an unexisting directory.
+        $usecache = !empty($CFG->keeptempdirectoriesonbackup);
+        if ($usecache) {
+            $cache = cache::make('tool_uploadcourse', 'helper');
+        }
+
+        // If we don't use the cache, or if we do and not set, or the directory doesn't exist any more.
+        if (!$usecache || (($backupid = $cache->get($cachekey)) === false || !is_dir("$CFG->tempdir/backup/$backupid"))) {
+
+            // Use null instead of false because it would consider that the cache key has not been set.
+            $backupid = null;
+
             if (!empty($backupfile)) {
-                if (!is_readable($backupfile)) {
-                    $errors['cannotreadbackupfile'] = new lang_string('cannotreadbackupfile', 'tool_uploadcourse');
-                } else {
-                    // Extracting the backup file.
-                    $packer = get_file_packer('application/vnd.moodle.backup');
-                    $backupid = restore_controller::get_tempdir_name(SITEID, $USER->id);
-                    $path = "$CFG->tempdir/backup/$backupid/";
-                    $result = $packer->extract_to_pathname($backupfile, $path);
-                    if (!$result) {
-                        $errors['invalidbackupfile'] = new lang_string('invalidbackupfile', 'tool_uploadcourse');
-                    }
+                // Extracting the backup file.
+                $packer = get_file_packer('application/vnd.moodle.backup');
+                $backupid = restore_controller::get_tempdir_name(SITEID, $USER->id);
+                $path = "$CFG->tempdir/backup/$backupid/";
+                $result = $packer->extract_to_pathname($backupfile, $path);
+                if (!$result) {
+                    $errors['invalidbackupfile'] = new lang_string('invalidbackupfile', 'tool_uploadcourse');
                 }
             } else if (!empty($shortname) || is_numeric($shortname)) {
                 // Creating restore from an existing course.
@@ -270,14 +255,15 @@ class tool_uploadcourse_helper {
                         new lang_string('coursetorestorefromdoesnotexist', 'tool_uploadcourse');
                 }
             }
-            $cache->set($cachekey, $backupid);
 
-            // Store all the directories to be able to remove them in self::clean_restore_content().
-            $backupids = (array) $cache->get('backupids');
-            $backupids[$cachekey] = $backupid;
-            $cache->set('backupids', $backupids);
+            if ($usecache) {
+                $cache->set($cachekey, $backupid);
+            }
         }
 
+        if ($backupid === null) {
+            $backupid = false;
+        }
         return $backupid;
     }
 
index 94ab8a7..79b10ed 100644 (file)
@@ -223,8 +223,6 @@ class tool_uploadcourse_processor {
 
         $tracker->finish();
         $tracker->results($total, $created, $updated, $deleted, $errors);
-
-        $this->remove_restore_content();
     }
 
     /**
@@ -349,20 +347,10 @@ class tool_uploadcourse_processor {
         }
 
         $tracker->finish();
-        $this->remove_restore_content();
 
         return $preview;
     }
 
-    /**
-     * Delete the restore object.
-     *
-     * @return void
-     */
-    protected function remove_restore_content() {
-        tool_uploadcourse_helper::clean_restore_content();
-    }
-
     /**
      * Reset the current process.
      *
index 7464e4e..32886ef 100644 (file)
@@ -58,11 +58,12 @@ class tool_uploadcourse_step2_form extends tool_uploadcourse_base_form {
         $mform->disabledIf('options[shortnametemplate]', 'options[mode]', 'eq', tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE);
         $mform->disabledIf('options[shortnametemplate]', 'options[mode]', 'eq', tool_uploadcourse_processor::MODE_UPDATE_ONLY);
 
+        // Restore file is not in the array options on purpose, because formslib can't handle it!
         $contextid = $this->_customdata['contextid'];
         $mform->addElement('hidden', 'contextid', $contextid);
         $mform->setType('contextid', PARAM_INT);
-        $mform->addElement('filepicker', 'options[restorefile]', get_string('templatefile', 'tool_uploadcourse'));
-        $mform->addHelpButton('options[restorefile]', 'templatefile', 'tool_uploadcourse');
+        $mform->addElement('filepicker', 'restorefile', get_string('templatefile', 'tool_uploadcourse'));
+        $mform->addHelpButton('restorefile', 'templatefile', 'tool_uploadcourse');
 
         $mform->addElement('text', 'options[templatecourse]', get_string('coursetemplatename', 'tool_uploadcourse'));
         $mform->setType('options[templatecourse]', PARAM_TEXT);
@@ -188,33 +189,4 @@ class tool_uploadcourse_step2_form extends tool_uploadcourse_base_form {
         $mform->closeHeaderBefore('buttonar');
     }
 
-    /**
-     * Server side validation.
-     * @param array $data - form data
-     * @param object $files  - form files
-     * @return array $errors - form errors
-     */
-    public function validation($data, $files) {
-        $errors = parent::validation($data, $files);
-        $columns = $this->_customdata['columns'];
-        $optype  = $data['options']['mode'];
-
-        // Look for other required data.
-        if ($optype != tool_uploadcourse_processor::MODE_UPDATE_ONLY) {
-            if (!in_array('fullname', $columns)) {
-                if (isset($errors['mode'])) {
-                    $errors['mode'] .= ' ';
-                }
-                $errors['mode'] .= get_string('missingfield', 'error', 'fullname');
-            }
-            if (!in_array('summary', $columns)) {
-                if (isset($errors['mode'])) {
-                    $errors['mode'] .= ' ';
-                }
-                $errors['mode'] .= get_string('missingfield', 'error', 'summary');
-            }
-        }
-
-        return $errors;
-    }
 }
index 667551e..0f290e2 100644 (file)
@@ -78,6 +78,13 @@ if ($form2data = $mform2->is_cancelled()) {
 
     $options = (array) $form2data->options;
     $defaults = (array) $form2data->defaults;
+
+    // Restorefile deserves its own logic because formslib does not really appreciate
+    // when the name of a filepicker is an array...
+    $options['restorefile'] = '';
+    if (!empty($form2data->restorefile)) {
+        $options['restorefile'] = $mform2->save_temp_file('restorefile');
+    }
     $processor = new tool_uploadcourse_processor($cir, $options, $defaults);
 
     echo $OUTPUT->header();
@@ -91,6 +98,11 @@ if ($form2data = $mform2->is_cancelled()) {
         echo $OUTPUT->continue_button($returnurl);
     }
 
+    // Deleting the file after processing or preview.
+    if (!empty($options['restorefile'])) {
+        @unlink($options['restorefile']);
+    }
+
 } else {
     $processor = new tool_uploadcourse_processor($cir, $form1data->options, array());
     echo $OUTPUT->header();
index ee979b4..3459c4a 100644 (file)
@@ -635,6 +635,23 @@ class tool_uploadcourse_course_testcase extends advanced_testcase {
         }
         $this->assertTrue($found);
 
+        // Restoring twice from the same course should work.
+        $data = array('shortname' => 'B1', 'templatecourse' => $c1->shortname, 'summary' => 'B', 'category' => 1,
+            'fullname' => 'B1');
+        $co = new tool_uploadcourse_course($mode, $updatemode, $data);
+        $this->assertTrue($co->prepare());
+        $co->proceed();
+        $course = $DB->get_record('course', array('shortname' => 'B1'));
+        $modinfo = get_fast_modinfo($course);
+        $found = false;
+        foreach ($modinfo->get_cms() as $cmid => $cm) {
+            if ($cm->modname == 'forum' && $cm->name == $c1f1->name) {
+                $found = true;
+                break;
+            }
+        }
+        $this->assertTrue($found);
+
         // Restore the time limit to prevent warning.
         set_time_limit(0);
     }
@@ -668,6 +685,25 @@ class tool_uploadcourse_course_testcase extends advanced_testcase {
         }
         $this->assertTrue($found);
 
+        // Restoring twice from the same file should work.
+        $data = array('shortname' => 'B1', 'backupfile' => __DIR__ . '/fixtures/backup.mbz',
+            'summary' => 'B', 'category' => 1, 'fullname' => 'B1');
+        $co = new tool_uploadcourse_course($mode, $updatemode, $data);
+        $this->assertTrue($co->prepare());
+        $co->proceed();
+        $course = $DB->get_record('course', array('shortname' => 'B1'));
+        $modinfo = get_fast_modinfo($course);
+        $found = false;
+        foreach ($modinfo->get_cms() as $cmid => $cm) {
+            if ($cm->modname == 'glossary' && $cm->name == 'Imported Glossary') {
+                $found = true;
+            } else if ($cm->modname == 'forum' && $cm->name == $c1f1->name) {
+                // We should not find this!
+                $this->assertTrue(false);
+            }
+        }
+        $this->assertTrue($found);
+
         // Restore the time limit to prevent warning.
         set_time_limit(0);
     }
index 31e53e0..ae42a1e 100644 (file)
@@ -141,6 +141,9 @@ class tool_uploadcourse_helper_testcase extends advanced_testcase {
         $bc->destroy();
         unset($bc); // File logging is a mess, we can only try to rely on gc to close handles.
 
+        $oldcfg = isset($CFG->keeptempdirectoriesonbackup) ? $CFG->keeptempdirectoriesonbackup : false;
+        $CFG->keeptempdirectoriesonbackup = true;
+
         // Checking restore dir.
         $dir = tool_uploadcourse_helper::get_restore_content_dir($c1backupfile, null);
         $bcinfo = backup_general_helper::get_backup_information($dir);
@@ -179,18 +182,26 @@ class tool_uploadcourse_helper_testcase extends advanced_testcase {
         $this->assertFalse($dir);
         $this->assertArrayHasKey('coursetorestorefromdoesnotexist', $errors);
 
-        // Cleaning content directories.
-        $oldcfg = isset($CFG->keeptempdirectoriesonbackup) ? $CFG->keeptempdirectoriesonbackup : false;
-        $dir = "$CFG->tempdir/backup/$dir";
-        $this->assertTrue(file_exists($dir));
-
+        // Trying again without caching. $CFG->keeptempdirectoriesonbackup is required for caching.
         $CFG->keeptempdirectoriesonbackup = false;
-        tool_uploadcourse_helper::clean_restore_content();
-        $this->assertTrue(file_exists($dir));
 
-        $CFG->keeptempdirectoriesonbackup = true;
-        tool_uploadcourse_helper::clean_restore_content();
-        $this->assertFalse(file_exists($dir));
+        // Checking restore dir.
+        $dir = tool_uploadcourse_helper::get_restore_content_dir($c1backupfile, null);
+        $dir2 = tool_uploadcourse_helper::get_restore_content_dir($c1backupfile, null);
+        $this->assertNotEquals($dir, $dir2);
+
+        // Checking with a shortname.
+        $dir = tool_uploadcourse_helper::get_restore_content_dir(null, $c1->shortname);
+        $dir2 = tool_uploadcourse_helper::get_restore_content_dir(null, $c1->shortname);
+        $this->assertNotEquals($dir, $dir2);
+
+        // Get a course that does not exist.
+        $errors = array();
+        $dir = tool_uploadcourse_helper::get_restore_content_dir(null, 'DoesNotExist', $errors);
+        $this->assertFalse($dir);
+        $this->assertArrayHasKey('coursetorestorefromdoesnotexist', $errors);
+        $dir2 = tool_uploadcourse_helper::get_restore_content_dir(null, 'DoesNotExist', $errors);
+        $this->assertEquals($dir, $dir2);
 
         $CFG->keeptempdirectoriesonbackup = $oldcfg;
 
index b1c09ae..3aef57c 100644 (file)
@@ -73,12 +73,17 @@ class external_service_form extends moodleform {
         $mform->addHelpButton('restrictedusers', 'restrictedusers', 'webservice');
         $mform->setType('restrictedusers', PARAM_BOOL);
 
-        //can users download files
+        // Can users download files?
         $mform->addElement('advcheckbox', 'downloadfiles', get_string('downloadfiles', 'webservice'));
         $mform->setAdvanced('downloadfiles');
         $mform->addHelpButton('downloadfiles', 'downloadfiles', 'webservice');
         $mform->setType('downloadfiles', PARAM_BOOL);
 
+        // Can users upload files?
+        $mform->addElement('advcheckbox', 'uploadfiles', get_string('uploadfiles', 'webservice'));
+        $mform->setAdvanced('uploadfiles');
+        $mform->addHelpButton('uploadfiles', 'uploadfiles', 'webservice');
+
         /// needed to select automatically the 'No required capability" option
         $currentcapabilityexist = false;
         if (empty($service->requiredcapability)) {
@@ -297,4 +302,4 @@ class web_service_token_form extends moodleform {
         return $errors;
     }
 
-}
\ No newline at end of file
+}
index 33cf33a..a02c32f 100644 (file)
@@ -48,7 +48,7 @@ require(dirname(dirname(dirname(dirname(__FILE__)))).'/config.php');
 require_once($CFG->dirroot.'/course/lib.php');
 
 // Ensure errors are well explained
-$CFG->debug = DEBUG_NORMAL;
+set_debugging(DEBUG_DEVELOPER, true);
 
 if (!is_enabled_auth('cas')) {
     error_log('[AUTH CAS] '.get_string('pluginnotenabled', 'auth_ldap'));
index ee15538..6898293 100644 (file)
@@ -52,7 +52,7 @@ require(dirname(dirname(dirname(dirname(__FILE__)))).'/config.php'); // global m
 require_once($CFG->dirroot.'/course/lib.php');
 
 // Ensure errors are well explained
-$CFG->debug = DEBUG_NORMAL;
+set_debugging(DEBUG_DEVELOPER, true);
 
 if (!is_enabled_auth('ldap')) {
     error_log('[AUTH LDAP] '.get_string('pluginnotenabled', 'auth_ldap'));
index 2847665..cfe16ef 100644 (file)
@@ -79,6 +79,10 @@ switch ($type) {
         print_error('unknownbackuptype');
 }
 
+// Backup of large courses requires extra memory. Use the amount configured
+// in admin settings.
+raise_memory_limit(MEMORY_EXTRA);
+
 if (!($bc = backup_ui::load_controller($backupid))) {
     $bc = new backup_controller($type, $id, backup::FORMAT_MOODLE,
                             backup::INTERACTIVE_YES, backup::MODE_GENERAL, $USER->id);
index 6dd5038..fbd919a 100644 (file)
@@ -113,31 +113,46 @@ if ($backup->get_stage() == backup_ui::STAGE_FINAL) {
     // Mark the UI finished.
     $rc->finish_ui();
     // Execute prechecks
+    $warnings = false;
     if (!$rc->execute_precheck()) {
         $precheckresults = $rc->get_precheck_results();
-        if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
-            fulldelete($tempdestination);
-
-            echo $OUTPUT->header();
-            echo $renderer->precheck_notices($precheckresults);
-            echo $OUTPUT->continue_button(new moodle_url('/course/view.php', array('id'=>$course->id)));
-            echo $OUTPUT->footer();
-            die();
+        if (is_array($precheckresults)) {
+            if (!empty($precheckresults['errors'])) { // If errors are found, terminate the import.
+                fulldelete($tempdestination);
+
+                echo $OUTPUT->header();
+                echo $renderer->precheck_notices($precheckresults);
+                echo $OUTPUT->continue_button(new moodle_url('/course/view.php', array('id'=>$course->id)));
+                echo $OUTPUT->footer();
+                die();
+            }
+            if (!empty($precheckresults['warnings'])) { // If warnings are found, go ahead but display warnings later.
+                $warnings = $precheckresults['warnings'];
+            }
         }
-    } else {
-        if ($restoretarget == backup::TARGET_CURRENT_DELETING || $restoretarget == backup::TARGET_EXISTING_DELETING) {
-            restore_dbops::delete_course_content($course->id);
-        }
-        // Execute the restore
-        $rc->execute_plan();
     }
+    if ($restoretarget == backup::TARGET_CURRENT_DELETING || $restoretarget == backup::TARGET_EXISTING_DELETING) {
+        restore_dbops::delete_course_content($course->id);
+    }
+    // Execute the restore.
+    $rc->execute_plan();
 
     // Delete the temp directory now
     fulldelete($tempdestination);
 
     // Display a notification and a continue button
     echo $OUTPUT->header();
-    echo $OUTPUT->notification(get_string('importsuccess', 'backup'),'notifysuccess');
+    if ($warnings) {
+        echo $OUTPUT->box_start();
+        echo $OUTPUT->notification(get_string('warning'), 'notifywarning');
+        echo html_writer::start_tag('ul', array('class'=>'list'));
+        foreach ($warnings as $warning) {
+            echo html_writer::tag('li', $warning);
+        }
+        echo html_writer::end_tag('ul');
+        echo $OUTPUT->box_end();
+    }
+    echo $OUTPUT->notification(get_string('importsuccess', 'backup'), 'notifysuccess');
     echo $OUTPUT->continue_button(new moodle_url('/course/view.php', array('id'=>$course->id)));
     echo $OUTPUT->footer();
 
index 99365ba..60f599a 100644 (file)
@@ -35,6 +35,18 @@ defined('MOODLE_INTERNAL') || die();
  */
 abstract class restore_qtype_plugin extends restore_plugin {
 
+    /*
+     * A simple answer to id cache for a single questions answers.
+     * @var array
+     */
+    private $questionanswercache = array();
+
+    /*
+     * The id of the current question in the questionanswercache.
+     * @var int
+     */
+    private $questionanswercacheid = null;
+
     /**
      * Add to $paths the restore_path_elements needed
      * to handle question_answers for a given question
@@ -147,38 +159,32 @@ abstract class restore_qtype_plugin extends restore_plugin {
 
         // The question existed, we need to map the existing question_answers
         } else {
-            // Look in question_answers by answertext matching
-            $sql = 'SELECT id
-                      FROM {question_answers}
-                     WHERE question = ?
-                       AND ' . $DB->sql_compare_text('answer', 255) . ' = ' . $DB->sql_compare_text('?', 255);
-            $params = array($newquestionid, $data->answertext);
-            $newitemid = $DB->get_field_sql($sql, $params);
-
-            // Not able to find the answer, let's try cleaning the answertext
-            // of all the question answers in DB as slower fallback. MDL-30018.
-            if (!$newitemid) {
+            // Have we cached the current question?
+            if ($this->questionanswercacheid !== $newquestionid) {
+                // The question changed, purge and start again!
+                $this->questionanswercache = array();
                 $params = array('question' => $newquestionid);
                 $answers = $DB->get_records('question_answers', $params, '', 'id, answer');
+                $this->questionanswercacheid = $newquestionid;
+                // Cache all cleaned answers for a simple text match.
                 foreach ($answers as $answer) {
-                    // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
+                    // MDL-30018: Clean in the same way as {@link xml_writer::xml_safe_utf8()}.
                     $clean = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $answer->answer); // Clean CTRL chars.
                     $clean = preg_replace("/\r\n|\r/", "\n", $clean); // Normalize line ending.
-                    if ($clean === $data->answertext) {
-                        $newitemid = $data->id;
-                    }
+                    $this->questionanswercache[$clean] = $answer->id;
                 }
             }
 
-            // If we haven't found the newitemid, something has gone really wrong, question in DB
-            // is missing answers, exception
-            if (!$newitemid) {
+            if (!isset($this->questionanswercache[$data->answertext])) {
+                // If we haven't found the matching answer, something has gone really wrong, the question in the DB
+                // is missing answers, throw an exception.
                 $info = new stdClass();
                 $info->filequestionid = $oldquestionid;
                 $info->dbquestionid   = $newquestionid;
                 $info->answer         = $data->answertext;
                 throw new restore_step_exception('error_question_answers_missing_in_db', $info);
             }
+            $newitemid = $this->questionanswercache[$data->answertext];
         }
         // Create mapping (we'll use this intensively when restoring question_states. And also answerfeedback files)
         $this->set_mapping('question_answer', $oldid, $newitemid);
index 2b6cdab..92d00c7 100644 (file)
@@ -3624,7 +3624,7 @@ class restore_process_file_aliases_queue extends restore_execution_step {
 
         // Iterate over aliases in the queue.
         foreach ($rs as $record) {
-            $info = restore_dbops::decode_backup_temp_info($record->info);
+            $info = backup_controller_dbops::decode_backup_temp_info($record->info);
 
             // Try to pick a repository instance that should serve the alias.
             $repository = $this->choose_repository($info);
index 6091c09..cd51cae 100644 (file)
@@ -17,6 +17,10 @@ $PAGE->set_pagelayout('standard');
 require_login($course, null, $cm);
 require_capability('moodle/restore:restorecourse', $context);
 
+// Restore of large courses requires extra memory. Use the amount configured
+// in admin settings.
+raise_memory_limit(MEMORY_EXTRA);
+
 if ($stage & restore_ui::STAGE_CONFIRM + restore_ui::STAGE_DESTINATION) {
     $restore = restore_ui::engage_independent_stage($stage, $contextid);
 } else {
index e2143cd..6f8ba31 100644 (file)
@@ -40,7 +40,7 @@ abstract class backup_factory {
         global $CFG;
 
         $dfltloglevel = backup::LOG_WARNING; // Default logging level
-        if (debugging('', DEBUG_DEVELOPER)) { // Debug developer raises default logging level
+        if ($CFG->debugdeveloper) { // Debug developer raises default logging level
             $dfltloglevel = backup::LOG_DEBUG;
         }
 
index 54dc4e9..2a3fa1a 100644 (file)
@@ -94,7 +94,6 @@ class backup_factories_testcase extends advanced_testcase {
 
         // Instantiate with debugging enabled and $CFG->backup_error_log_logger_level not set
         $CFG->debugdisplay = true;
-        $CFG->debug = DEBUG_DEVELOPER;
         unset($CFG->backup_error_log_logger_level);
         $logger1 = backup_factory::get_logger_chain(backup::INTERACTIVE_YES, backup::EXECUTION_INMEDIATE, 'test');
         $this->assertTrue($logger1 instanceof error_log_logger);  // 1st logger is error_log_logger
index 9943e0b..c9dd8fb 100644 (file)
@@ -157,15 +157,18 @@ class restore_plan extends base_plan implements loggable {
         parent::execute();
         $this->controller->set_status(backup::STATUS_FINISHED_OK);
 
-        events_trigger('course_restored', (object) array(
-            'courseid'  => $this->get_courseid(), // The new course
-            'userid'    => $this->get_userid(), // User doing the restore
-            'type'      => $this->controller->get_type(), // backup::TYPE_* constant
-            'target'    => $this->controller->get_target(), // backup::TARGET_* constant
-            'mode'      => $this->controller->get_mode(), // backup::MODE_* constant
-            'operation' => $this->controller->get_operation(), // backup::OPERATION_* constant
-            'samesite'  => $this->controller->is_samesite(),
+        // Trigger a course restored event.
+        $event = \core\event\course_restored::create(array(
+            'objectid' => $this->get_courseid(),
+            'userid' => $this->get_userid(),
+            'context' => context_course::instance($this->get_courseid()),
+            'other' => array('type' => $this->controller->get_type(),
+                             'target' => $this->controller->get_target(),
+                             'mode' => $this->controller->get_mode(),
+                             'operation' => $this->controller->get_operation(),
+                             'samesite' => $this->controller->is_samesite())
         ));
+        $event->trigger();
     }
 
     /**
diff --git a/badges/classes/observer.php b/badges/classes/observer.php
new file mode 100644 (file)
index 0000000..6d7b054
--- /dev/null
@@ -0,0 +1,108 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Local stuff for category enrolment plugin.
+ *
+ * @package    core_badges
+ * @copyright  2013 Rajesh Taneja <rajesh@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Event observer for badges.
+ */
+class core_badges_observer {
+    /**
+     * Triggered when 'course_module_completion_updated' event is triggered.
+     *
+     * @param \core\event\course_module_completion_updated $event
+     */
+    public static function course_module_criteria_review(\core\event\course_module_completion_updated $event) {
+        global $DB, $CFG;
+
+        if (!empty($CFG->enablebadges)) {
+            require_once($CFG->dirroot.'/lib/badgeslib.php');
+
+            $eventdata = $event->get_record_snapshot('course_modules_completion', $event->objectid);
+            $userid = $event->other['relateduserid'];
+            $mod = $eventdata->coursemoduleid;
+
+            if ($eventdata->completionstate == COMPLETION_COMPLETE
+                || $eventdata->completionstate == COMPLETION_COMPLETE_PASS
+                || $eventdata->completionstate == COMPLETION_COMPLETE_FAIL) {
+                // Need to take into account that there can be more than one badge with the same activity in its criteria.
+                if ($rs = $DB->get_records('badge_criteria_param', array('name' => 'module_' . $mod, 'value' => $mod))) {
+                    foreach ($rs as $r) {
+                        $bid = $DB->get_field('badge_criteria', 'badgeid', array('id' => $r->critid), MUST_EXIST);
+                        $badge = new badge($bid);
+                        if (!$badge->is_active() || $badge->is_issued($userid)) {
+                            continue;
+                        }
+
+                        if ($badge->criteria[BADGE_CRITERIA_TYPE_ACTIVITY]->review($userid)) {
+                            $badge->criteria[BADGE_CRITERIA_TYPE_ACTIVITY]->mark_complete($userid);
+
+                            if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
+                                $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
+                                $badge->issue($userid);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * Triggered when 'course_completed' event is triggered.
+     *
+     * @param   \core\event\course_completed $event
+     */
+    public static function course_criteria_review(\core\event\course_completed $event) {
+        global $DB, $CFG;
+
+        if (!empty($CFG->enablebadges)) {
+            require_once($CFG->dirroot.'/lib/badgeslib.php');
+
+            $eventdata = $event->get_record_snapshot('course_completions', $event->objectid);
+            $userid = $event->other['relateduserid'];
+            $courseid = $event->courseid;
+
+            // Need to take into account that course can be a part of course_completion and courseset_completion criteria.
+            if ($rs = $DB->get_records('badge_criteria_param', array('name' => 'course_' . $courseid, 'value' => $courseid))) {
+                foreach ($rs as $r) {
+                    $crit = $DB->get_record('badge_criteria', array('id' => $r->critid), 'badgeid, criteriatype', MUST_EXIST);
+                    $badge = new badge($crit->badgeid);
+                    if (!$badge->is_active() || $badge->is_issued($userid)) {
+                        continue;
+                    }
+
+                    if ($badge->criteria[$crit->criteriatype]->review($userid)) {
+                        $badge->criteria[$crit->criteriatype]->mark_complete($userid);
+
+                        if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
+                            $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
+                            $badge->issue($userid);
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
index 30987e0..8bccf53 100644 (file)
@@ -26,7 +26,6 @@
 
 defined('MOODLE_INTERNAL') || die();
 
-require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
 require_once($CFG->libdir . '/badgeslib.php');
 require_once($CFG->dirroot . '/user/selector/lib.php');
 
index f6abcb6..088b443 100644 (file)
@@ -26,7 +26,6 @@
 
 require_once($CFG->libdir . '/badgeslib.php');
 require_once($CFG->libdir . '/tablelib.php');
-require_once($CFG->dirroot . '/user/filters/lib.php');
 
 /**
  * Standard HTML output renderer for badges
index 9ccafc1..fa7b7cb 100644 (file)
@@ -31,9 +31,13 @@ require_once($CFG->libdir . '/badgeslib.php');
 
 class core_badgeslib_testcase extends advanced_testcase {
     protected $badgeid;
+    protected $course;
+    protected $user;
+    protected $module;
+    protected $coursebadge;
 
     protected function setUp() {
-        global $DB;
+        global $DB, $CFG;
         $this->resetAfterTest(true);
 
         $user = $this->getDataGenerator()->create_user();
@@ -59,6 +63,29 @@ class core_badgeslib_testcase extends advanced_testcase {
         $fordb->status = BADGE_STATUS_INACTIVE;
 
         $this->badgeid = $DB->insert_record('badge', $fordb, true);
+
+        // Create a course with activity and auto completion tracking.
+        $this->course = $this->getDataGenerator()->create_course();
+        $this->user = $this->getDataGenerator()->create_user();
+        $studentrole = $DB->get_record('role', array('shortname' => 'student'));
+        $this->assertNotEmpty($studentrole);
+
+        // Get manual enrolment plugin and enrol user.
+        require_once($CFG->dirroot.'/enrol/manual/locallib.php');
+        $manplugin = enrol_get_plugin('manual');
+        $maninstance = $DB->get_record('enrol', array('courseid' => $this->course->id, 'enrol' => 'manual'), '*', MUST_EXIST);
+        $manplugin->enrol_user($maninstance, $this->user->id, $studentrole->id);
+        $this->assertEquals(1, $DB->count_records('user_enrolments'));
+
+        $completionauto = array('completion' => COMPLETION_TRACKING_AUTOMATIC);
+        $this->module = $this->getDataGenerator()->create_module('forum', array('course' => $this->course->id), $completionauto);
+
+        // Build badge and criteria.
+        $fordb->type = BADGE_TYPE_COURSE;
+        $fordb->courseid = $this->course->id;
+        $fordb->status = BADGE_STATUS_ACTIVE;
+
+        $this->coursebadge = $DB->insert_record('badge', $fordb, true);
     }
 
     public function test_create_badge() {
@@ -183,4 +210,54 @@ class core_badgeslib_testcase extends advanced_testcase {
         $this->assertEquals(badge_message_from_template($message, $params), $result);
     }
 
+    /**
+     * Test badges observer when course module completion event id fired.
+     */
+    public function test_badges_observer_course_module_criteria_review() {
+        $badge = new badge($this->coursebadge);
+        $this->assertFalse($badge->is_issued($this->user->id));
+
+        $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
+        $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
+        $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_ACTIVITY, 'badgeid' => $badge->id));
+        $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY, 'module_'.$this->module->id => $this->module->id));
+
+        // Set completion for forum activity.
+        $c = new completion_info($this->course);
+        $activities = $c->get_activities();
+        $this->assertEquals(1, count($activities));
+        $this->assertTrue(isset($activities[$this->module->cmid]));
+        $this->assertEquals($activities[$this->module->cmid]->name, $this->module->name);
+
+        $current = $c->get_data($activities[$this->module->cmid], false, $this->user->id);
+        $current->completionstate = COMPLETION_COMPLETE;
+        $current->timemodified = time();
+        $c->internal_set_data($activities[$this->module->cmid], $current);
+
+        // Check if badge is awarded.
+        $this->assertDebuggingCalled('Error baking badge image!');
+        $this->assertTrue($badge->is_issued($this->user->id));
+    }
+
+    /**
+     * Test badges observer when course_completed event is fired.
+     */
+    public function test_badges_observer_course_criteria_review() {
+        $badge = new badge($this->coursebadge);
+        $this->assertFalse($badge->is_issued($this->user->id));
+
+        $criteria_overall = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_OVERALL, 'badgeid' => $badge->id));
+        $criteria_overall->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY));
+        $criteria_overall1 = award_criteria::build(array('criteriatype' => BADGE_CRITERIA_TYPE_COURSE, 'badgeid' => $badge->id));
+        $criteria_overall1->save(array('agg' => BADGE_CRITERIA_AGGREGATION_ANY, 'course_'.$this->course->id => $this->course->id));
+
+        $ccompletion = new completion_completion(array('course' => $this->course->id, 'userid' => $this->user->id));
+
+        // Mark course as complete.
+        $ccompletion->mark_complete();
+
+        // Check if badge is awarded.
+        $this->assertDebuggingCalled('Error baking badge image!');
+        $this->assertTrue($badge->is_issued($this->user->id));
+    }
 }
index 1655178..a387294 100644 (file)
@@ -60,7 +60,9 @@ class block_calendar_upcoming extends block_base {
         $events = calendar_get_upcoming($courses, $group, $user, $lookahead, $maxevents);
 
         if (!empty($this->instance)) {
-            $this->content->text = calendar_get_block_upcoming($events, 'view.php?view=day&amp;course='.$courseshown.'&amp;');
+            $link = 'view.php?view=day&amp;course='.$courseshown.'&amp;';
+            $showcourselink = ($this->page->course->id == SITEID);
+            $this->content->text = calendar_get_block_upcoming($events, $link, $showcourselink);
         }
 
         if (empty($this->content->text)) {
index 9d9b289..461baf1 100644 (file)
@@ -416,6 +416,9 @@ class block_base {
             'class' => 'block_' . $this->name(). '  block',
             'role' => $this->get_aria_role()
         );
+        if ($this->hide_header()) {
+            $attributes['class'] .= ' no-header';
+        }
         if ($this->instance_can_be_docked() && get_user_preferences('docked_block_instance_'.$this->instance->id, 0)) {
             $attributes['class'] .= ' dock_on_load';
         }
index 1035614..6b1a793 100644 (file)
@@ -110,12 +110,12 @@ class block_tags extends block_base {
             $content = '';
             $moretags = new moodle_url('/tag/coursetags_more.php', array('show'=>$tagtype));
             if ($tagtype == 'all') {
-                $tags = coursetag_get_tags(0, 0, $this->config->tagtype, $this->config->numberoftags, 'name');
+                $tags = coursetag_get_tags(0, 0, $this->config->tagtype, $this->config->numberoftags);
             } else if ($tagtype == 'course') {
-                $tags = coursetag_get_tags($this->page->course->id, 0, $this->config->tagtype, $this->config->numberoftags, 'name');
+                $tags = coursetag_get_tags($this->page->course->id, 0, $this->config->tagtype, $this->config->numberoftags);
                 $moretags->param('courseid', $this->page->course->id);
             } else if ($tagtype == 'my') {
-                $tags = coursetag_get_tags(0, $USER->id, $this->config->tagtype, $this->config->numberoftags, 'name');
+                $tags = coursetag_get_tags(0, $USER->id, $this->config->tagtype, $this->config->numberoftags);
             }
             $tagcloud = tag_print_cloud($tags, 150, true);
             if (!$tagcloud) {
index 7038060..d743f70 100644 (file)
@@ -316,11 +316,18 @@ class blog_entry implements renderable {
         $this->delete_attachments();
         $this->remove_associations();
 
+        // Get record to pass onto the event.
+        $record = $DB->get_record('post', array('id' => $this->id));
         $DB->delete_records('post', array('id' => $this->id));
         tag_set('post', $this->id, array());
 
-        add_to_log(SITEID, 'blog', 'delete', 'index.php?userid='. $this->userid, 'deleted blog entry with entry id# '. $this->id);
-        events_trigger('blog_entry_deleted', $this);
+        $event = \core\event\blog_entry_deleted::create(array('objectid' => $this->id,
+                                                            'userid'   => $this->userid,
+                                                            'other'   => array("record" => (array)$record)
+                                                      ));
+        $event->add_record_snapshot("post", $record);
+        $event->set_custom_data($this);
+        $event->trigger();
     }
 
     /**
index 6ed0658..60e5858 100644 (file)
@@ -155,7 +155,7 @@ class core_bloglib_testcase extends advanced_testcase {
      * Test various blog related events.
      */
     public function test_blog_entry_events() {
-        global $USER;
+        global $USER, $DB;
 
         $this->setAdminUser();
         $this->resetAfterTest();
@@ -178,5 +178,21 @@ class core_bloglib_testcase extends advanced_testcase {
         $this->assertEquals($blog->id, $event->objectid);
         $this->assertEquals($USER->id, $event->userid);
         $this->assertEquals("post", $event->objecttable);
+
+        // Delete a blog entry.
+        $record = $DB->get_record('post', array('id' => $blog->id));
+        $blog->delete();
+        $events = $sink->get_events();
+        $event = array_pop($events);
+
+        // Validate event data.
+        $this->assertInstanceOf('\core\event\blog_entry_deleted', $event);
+        $this->assertEquals(context_system::instance()->id, $event->contextid);
+        $this->assertEquals($blog->id, $event->objectid);
+        $this->assertEquals($USER->id, $event->userid);
+        $this->assertEquals("post", $event->objecttable);
+        $this->assertEquals($record, $event->get_record_snapshot("post", $blog->id));
+        $this->assertSame('blog_entry_deleted', $event->get_legacy_eventname());
+
     }
 }
index da8fe67..6de94e2 100644 (file)
@@ -271,7 +271,7 @@ class cache implements cache_loader {
      *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
      * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
      * @return mixed|false The data from the cache or false if the key did not exist within the cache.
-     * @throws moodle_exception
+     * @throws coding_exception
      */
     public function get($key, $strictness = IGNORE_MISSING) {
         // 1. Parse the key.
@@ -329,7 +329,7 @@ class cache implements cache_loader {
         }
         // 5. Validate strictness.
         if ($strictness === MUST_EXIST && $result === false) {
-            throw new moodle_exception('Requested key did not exist in any cache stores and could not be loaded.');
+            throw new coding_exception('Requested key did not exist in any cache stores and could not be loaded.');
         }
         // 6. Set it to the store if we got it from the loader/datasource.
         if ($setaftervalidation) {
@@ -363,7 +363,7 @@ class cache implements cache_loader {
      * @return array An array of key value pairs for the items that could be retrieved from the cache.
      *      If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
      *      Otherwise any key that did not exist will have a data value of false within the results.
-     * @throws moodle_exception
+     * @throws coding_exception
      */
     public function get_many(array $keys, $strictness = IGNORE_MISSING) {
 
@@ -420,7 +420,7 @@ class cache implements cache_loader {
             $missingkeys = array();
             foreach ($result as $key => $value) {
                 if ($value === false) {
-                    $missingkeys[] = ($usingloader) ? $key : $parsedkeys[$key];
+                    $missingkeys[] = $parsedkeys[$key];
                 }
             }
             if (!empty($missingkeys)) {
@@ -430,11 +430,9 @@ class cache implements cache_loader {
                     $resultmissing = $this->datasource->load_many_for_cache($missingkeys);
                 }
                 foreach ($resultmissing as $key => $value) {
-                    $pkey = ($usingloader) ? $key : $keysparsed[$key];
-                    $realkey = ($usingloader) ? $parsedkeys[$key] : $key;
-                    $result[$pkey] = $value;
+                    $result[$keysparsed[$key]] = $value;
                     if ($value !== false) {
-                        $this->set($realkey, $value);
+                        $this->set($key, $value);
                     }
                 }
                 unset($resultmissing);
@@ -453,7 +451,7 @@ class cache implements cache_loader {
         if ($strictness === MUST_EXIST) {
             foreach ($keys as $key) {
                 if (!array_key_exists($key, $fullresult)) {
-                    throw new moodle_exception('Not all the requested keys existed within the cache stores.');
+                    throw new coding_exception('Not all the requested keys existed within the cache stores.');
                 }
             }
         }
@@ -483,6 +481,11 @@ class cache implements cache_loader {
         if ($this->perfdebug) {
             cache_helper::record_cache_set($this->storetype, $this->definition->get_id());
         }
+        if ($this->loader !== false) {
+            // We have a loader available set it there as well.
+            // We have to let the loader do its own parsing of data as it may be unique.
+            $this->loader->set($key, $data);
+        }
         if (is_object($data) && $data instanceof cacheable_object) {
             $data = new cache_cached_object($data);
         } else if (!is_scalar($data)) {
@@ -506,6 +509,7 @@ class cache implements cache_loader {
      * Removes references where required.
      *
      * @param stdClass|array $data
+     * @return mixed What ever was put in but without any references.
      */
     protected function unref($data) {
         if ($this->definition->uses_simple_data()) {
@@ -593,6 +597,11 @@ class cache implements cache_loader {
      *      ... if they care that is.
      */
     public function set_many(array $keyvaluearray) {
+        if ($this->loader !== false) {
+            // We have a loader available set it there as well.
+            // We have to let the loader do its own parsing of data as it may be unique.
+            $this->loader->set_many($keyvaluearray);
+        }
         $data = array();
         $simulatettl = $this->has_a_ttl() && !$this->store_supports_native_ttl();
         $usepersistcache = $this->is_using_persist_cache();
@@ -858,7 +867,7 @@ class cache implements cache_loader {
      * Returns the loader associated with this instance.
      *
      * @since 2.4.4
-     * @return cache_loader|false
+     * @return cache|false
      */
     protected function get_loader() {
         return $this->loader;
@@ -1340,7 +1349,6 @@ class cache_application extends cache implements cache_loader_with_locking {
      * @param string|int $key The key for the data being requested.
      * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
      * @return mixed|false The data from the cache or false if the key did not exist within the cache.
-     * @throws moodle_exception
      */
     public function get($key, $strictness = IGNORE_MISSING) {
         if ($this->requirelockingread && $this->check_lock_state($key) === false) {
@@ -1364,7 +1372,7 @@ class cache_application extends cache implements cache_loader_with_locking {
      * @return array An array of key value pairs for the items that could be retrieved from the cache.
      *      If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
      *      Otherwise any key that did not exist will have a data value of false within the results.
-     * @throws moodle_exception
+     * @throws coding_exception
      */
     public function get_many(array $keys, $strictness = IGNORE_MISSING) {
         if ($this->requirelockingread) {
@@ -1458,6 +1466,7 @@ class cache_application extends cache implements cache_loader_with_locking {
  * @todo we should support locking in the session as well. Should be pretty simple to set up.
  *
  * @internal don't use me directly.
+ * @method cache_store|cache_is_searchable get_store() Returns the cache store which must implement both cache_is_searchable.
  *
  * @package    core
  * @category   cache
@@ -1494,6 +1503,11 @@ class cache_session extends cache {
      */
     const KEY_PREFIX = 'sess_';
 
+    /**
+     * This is the key used to track last access.
+     */
+    const LASTACCESS = '__lastaccess__';
+
     /**
      * Override the cache::construct method.
      *
@@ -1507,12 +1521,15 @@ class cache_session extends cache {
      * @param cache_definition $definition
      * @param cache_store $store
      * @param cache_loader|cache_data_source $loader
-     * @return void
      */
     public function __construct(cache_definition $definition, cache_store $store, $loader = null) {
         // First up copy the loadeduserid to the current user id.
         $this->currentuserid = self::$loadeduserid;
         parent::__construct($definition, $store, $loader);
+
+        // This will trigger check tracked user. If this gets removed a call to that will need to be added here in its place.
+        $this->set(self::LASTACCESS, cache::now());
+
         if ($definition->has_invalidation_events()) {
             $lastinvalidation = $this->get('lastsessioninvalidation');
             if ($lastinvalidation === false) {
@@ -1561,6 +1578,21 @@ class cache_session extends cache {
         }
     }
 
+    /**
+     * Sets the session id for the loader.
+     */
+    protected function set_session_id() {
+        $this->sessionid = preg_replace('#[^a-zA-Z0-9_]#', '_', session_id());
+    }
+
+    /**
+     * Returns the prefix used for all keys.
+     * @return string
+     */
+    protected function get_key_prefix() {
+        return 'u'.$this->currentuserid.'_'.$this->sessionid;
+    }
+
     /**
      * Parses the key turning it into a string (or array is required) suitable to be passed to the cache store.
      *
@@ -1573,17 +1605,18 @@ class cache_session extends cache {
      * @return string|array String unless the store supports multi-identifiers in which case an array if returned.
      */
     protected function parse_key($key) {
-        if ($key === 'lastaccess') {
-            $key = '__lastaccess__';
+        $prefix = $this->get_key_prefix();
+        if ($key === self::LASTACCESS) {
+            return $key.$prefix;
         }
-        return 'sess_'.parent::parse_key($key);
+        return $prefix.'_'.parent::parse_key($key);
     }
 
     /**
      * Check that this cache instance is tracking the current user.
      */
     protected function check_tracked_user() {
-        if (isset($_SESSION['USER']->id)) {
+        if (isset($_SESSION['USER']->id) && $_SESSION['USER']->id !== null) {
             // Get the id of the current user.
             $new = $_SESSION['USER']->id;
         } else {
@@ -1597,55 +1630,25 @@ class cache_session extends cache {
                 // This way we don't bloat the session.
                 $this->purge();
                 // Update the session id just in case!
-                $this->sessionid = session_id();
+                $this->set_session_id();
             }
             self::$loadeduserid = $new;
             $this->currentuserid = $new;
         } else if ($new !== $this->currentuserid) {
             // The current user matches the loaded user but not the user last used by this cache.
-            $this->purge();
+            $this->purge_current_user();
             $this->currentuserid = $new;
             // Update the session id just in case!
-            $this->sessionid = session_id();
+            $this->set_session_id();
         }
     }
 
     /**
-     * Gets the session data.
-     *
-     * @param bool $force If true the session data will be loaded from the store again.
-     * @return array An array of session data.
-     */
-    protected function get_session_data($force = false) {
-        if ($this->sessionid === null) {
-            $this->sessionid = session_id();
-        }
-        if (is_array($this->session) && !$force) {
-            return $this->session;
-        }
-        $session = parent::get($this->sessionid);
-        if ($session === false) {
-            $session = array();
-        }
-        // We have to write here to ensure that the lastaccess time is recorded.
-        // And also in order to ensure the session entry exists as when we save it on __destruct
-        // $CFG is likely to have already been destroyed.
-        $this->save_session($session);
-        return $this->session;
-    }
-
-    /**
-     * Saves the session data.
-     *
-     * This function also updates the last access time.
-     *
-     * @param array $session
-     * @return bool
+     * Purges the session cache of all data belonging to the current user.
      */
-    protected function save_session(array $session) {
-        $session['lastaccess'] = time();
-        $this->session = $session;
-        return parent::set($this->sessionid, $this->session);
+    public function purge_current_user() {
+        $keys = $this->get_store()->find_all($this->get_key_prefix());
+        $this->get_store()->delete_many($keys);
     }
 
     /**
@@ -1656,7 +1659,7 @@ class cache_session extends cache {
      *      In advanced cases an array may be useful such as in situations requiring the multi-key functionality.
      * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
      * @return mixed|false The data from the cache or false if the key did not exist within the cache.
-     * @throws moodle_exception
+     * @throws coding_exception
      */
     public function get($key, $strictness = IGNORE_MISSING) {
         // Check the tracked user.
@@ -1664,10 +1667,8 @@ class cache_session extends cache {
         // 2. Parse the key.
         $parsedkey = $this->parse_key($key);
         // 3. Get it from the store.
-        $result = false;
-        $session = $this->get_session_data();
-        if (array_key_exists($parsedkey, $session)) {
-            $result = $session[$parsedkey];
+        $result = $this->get_store()->get($parsedkey);
+        if ($result !== false) {
             if ($result instanceof cache_ttl_wrapper) {
                 if ($result->has_expired()) {
                     $this->get_store()->delete($parsedkey);
@@ -1681,10 +1682,9 @@ class cache_session extends cache {
             }
         }
         // 4. Load if from the loader/datasource if we don't already have it.
-        $setaftervalidation = false;
         if ($result === false) {
             if ($this->perfdebug) {
-                cache_helper::record_cache_miss('**static session**', $this->get_definition()->get_id());
+                cache_helper::record_cache_miss($this->storetype, $this->get_definition()->get_id());
             }
             if ($this->get_loader() !== false) {
                 // We must pass the original (unparsed) key to the next loader in the chain.
@@ -1694,19 +1694,18 @@ class cache_session extends cache {
             } else if ($this->get_datasource() !== false) {
                 $result = $this->get_datasource()->load_for_cache($key);
             }
-            $setaftervalidation = ($result !== false);
+            // 5. Set it to the store if we got it from the loader/datasource.
+            if ($result !== false) {
+                $this->set($key, $result);
+            }
         } else if ($this->perfdebug) {
-            cache_helper::record_cache_hit('**static session**', $this->get_definition()->get_id());
+            cache_helper::record_cache_hit($this->storetype, $this->get_definition()->get_id());
         }
         // 5. Validate strictness.
         if ($strictness === MUST_EXIST && $result === false) {
-            throw new moodle_exception('Requested key did not exist in any cache stores and could not be loaded.');
-        }
-        // 6. Set it to the store if we got it from the loader/datasource.
-        if ($setaftervalidation) {
-            $this->set($key, $result);
+            throw new coding_exception('Requested key did not exist in any cache stores and could not be loaded.');
         }
-        // 7. Make sure we don't pass back anything that could be a reference.
+        // 6. Make sure we don't pass back anything that could be a reference.
         //    We don't want people modifying the data in the cache.
         if (!is_scalar($result)) {
             // If data is an object it will be a reference.
@@ -1737,8 +1736,14 @@ class cache_session extends cache {
      */
     public function set($key, $data) {
         $this->check_tracked_user();
+        $loader = $this->get_loader();
+        if ($loader !== false) {
+            // We have a loader available set it there as well.
+            // We have to let the loader do its own parsing of data as it may be unique.
+            $loader->set($key, $data);
+        }
         if ($this->perfdebug) {
-            cache_helper::record_cache_set('**static session**', $this->get_definition()->get_id());
+            cache_helper::record_cache_set($this->storetype, $this->get_definition()->get_id());
         }
         if (is_object($data) && $data instanceof cacheable_object) {
             $data = new cache_cached_object($data);
@@ -1750,12 +1755,10 @@ class cache_session extends cache {
             $data = $this->unref($data);
         }
         // We dont' support native TTL here as we consolidate data for sessions.
-        if ($this->has_a_ttl()) {
+        if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
             $data = new cache_ttl_wrapper($data, $this->get_definition()->get_ttl());
         }
-        $session = $this->get_session_data();
-        $session[$this->parse_key($key)] = $data;
-        return $this->save_session($session);
+        return $this->get_store()->set($this->parse_key($key), $data);
     }
 
     /**
@@ -1767,15 +1770,12 @@ class cache_session extends cache {
      * @return bool True of success, false otherwise.
      */
     public function delete($key, $recurse = true) {
-        $this->check_tracked_user();
         $parsedkey = $this->parse_key($key);
         if ($recurse && $this->get_loader() !== false) {
             // Delete from the bottom of the stack first.
             $this->get_loader()->delete($key, $recurse);
         }
-        $session = $this->get_session_data();
-        unset($session[$parsedkey]);
-        return $this->save_session($session);
+        return $this->get_store()->delete($parsedkey);
     }
 
     /**
@@ -1794,15 +1794,72 @@ class cache_session extends cache {
      * @return array An array of key value pairs for the items that could be retrieved from the cache.
      *      If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
      *      Otherwise any key that did not exist will have a data value of false within the results.
-     * @throws moodle_exception
+     * @throws coding_exception
      */
     public function get_many(array $keys, $strictness = IGNORE_MISSING) {
         $this->check_tracked_user();
-        $return = array();
+        $parsedkeys = array();
+        $keymap = array();
         foreach ($keys as $key) {
-            $return[$key] = $this->get($key, $strictness);
+            $parsedkey = $this->parse_key($key);
+            $parsedkeys[$key] = $parsedkey;
+            $keymap[$parsedkey] = $key;
+        }
+        $result = $this->get_store()->get_many($parsedkeys);
+        $return = array();
+        $missingkeys = array();
+        $hasmissingkeys = false;
+        foreach ($result as $parsedkey => $value) {
+            $key = $keymap[$parsedkey];
+            if ($value instanceof cache_ttl_wrapper) {
+                /* @var cache_ttl_wrapper $value */
+                if ($value->has_expired()) {
+                    $this->delete($keymap[$parsedkey]);
+                    $value = false;
+                } else {
+                    $value = $value->data;
+                }
+            }
+            if ($value instanceof cache_cached_object) {
+                /* @var cache_cached_object $value */
+                $value = $value->restore_object();
+            }
+            $return[$key] = $value;
+            if ($value === false) {
+                $hasmissingkeys = true;
+                $missingkeys[$parsedkey] = $key;
+            }
+        }
+        if ($hasmissingkeys) {
+            // We've got missing keys - we've got to check any loaders or data sources.
+            $loader = $this->get_loader();
+            $datasource = $this->get_datasource();
+            if ($loader !== false) {
+                foreach ($loader->get_many($missingkeys) as $key => $value) {
+                    if ($value !== false) {
+                        $return[$key] = $value;
+                        unset($missingkeys[$parsedkeys[$key]]);
+                    }
+                }
+            }
+            $hasmissingkeys = count($missingkeys) > 0;
+            if ($datasource !== false && $hasmissingkeys) {
+                // We're still missing keys but we've got a datasource.
+                foreach ($datasource->load_many_for_cache($missingkeys) as $key => $value) {
+                    if ($value !== false) {
+                        $return[$key] = $value;
+                        unset($missingkeys[$parsedkeys[$key]]);
+                    }
+                }
+                $hasmissingkeys = count($missingkeys) > 0;
+            }
         }
+        if ($hasmissingkeys && $strictness === MUST_EXIST) {
+            throw new coding_exception('Requested key did not exist in any cache stores and could not be loaded.');
+        }
+
         return $return;
+
     }
 
     /**
@@ -1814,18 +1871,12 @@ class cache_session extends cache {
      * @return int The number of items successfully deleted.
      */
     public function delete_many(array $keys, $recurse = true) {
-        $this->check_tracked_user();
         $parsedkeys = array_map(array($this, 'parse_key'), $keys);
         if ($recurse && $this->get_loader() !== false) {
             // Delete from the bottom of the stack first.
             $this->get_loader()->delete_many($keys, $recurse);
         }
-        $session = $this->get_session_data();
-        foreach ($parsedkeys as $parsedkey) {
-            unset($session[$parsedkey]);
-        }
-        $this->save_session($session);
-        return count($keys);
+        return $this->get_store()->delete_many($parsedkeys);
     }
 
     /**
@@ -1853,8 +1904,15 @@ class cache_session extends cache {
      */
     public function set_many(array $keyvaluearray) {
         $this->check_tracked_user();
-        $session = $this->get_session_data();
-        $simulatettl = $this->has_a_ttl();
+        $loader = $this->get_loader();
+        if ($loader !== false) {
+            // We have a loader available set it there as well.
+            // We have to let the loader do its own parsing of data as it may be unique.
+            $loader->set_many($keyvaluearray);
+        }
+        $data = array();
+        $definitionid = $this->get_definition()->get_ttl();
+        $simulatettl = $this->has_a_ttl() && !$this->store_supports_native_ttl();
         foreach ($keyvaluearray as $key => $value) {
             if (is_object($value) && $value instanceof cacheable_object) {
                 $value = new cache_cached_object($value);
@@ -1866,16 +1924,17 @@ class cache_session extends cache {
                 $value = $this->unref($value);
             }
             if ($simulatettl) {
-                $value = new cache_ttl_wrapper($value, $this->get_definition()->get_ttl());
+                $value = new cache_ttl_wrapper($value, $definitionid);
             }
-            $parsedkey = $this->parse_key($key);
-            $session[$parsedkey] = $value;
+            $data[$key] = array(
+                'key' => $this->parse_key($key),
+                'value' => $value
+            );
         }
         if ($this->perfdebug) {
-            cache_helper::record_cache_set($this->storetype, $this->get_definition()->get_id());
+            cache_helper::record_cache_set($this->storetype, $definitionid);
         }
-        $this->save_session($session);
-        return count($keyvaluearray);
+        return $this->get_store()->set_many($data);
     }
 
     /**
@@ -1884,13 +1943,9 @@ class cache_session extends cache {
      * @return bool True on success, false otherwise
      */
     public function purge() {
-        // 1. Purge the session object.
-        $this->session = array();
-        // 2. Delete the record for this users session from the store.
-        $this->get_store()->delete($this->sessionid);
-        // 3. Optionally purge any stacked loaders in the same way.
+        $this->get_store()->purge();
         if ($this->get_loader()) {
-            $this->get_loader()->delete($this->sessionid);
+            $this->get_loader()->purge();
         }
         return true;
     }
@@ -1919,21 +1974,27 @@ class cache_session extends cache {
     public function has($key, $tryloadifpossible = false) {
         $this->check_tracked_user();
         $parsedkey = $this->parse_key($key);
-        $session = $this->get_session_data();
-        $has = false;
-        if ($this->has_a_ttl()) {
+        $store = $this->get_store();
+        if ($this->has_a_ttl() && !$this->store_supports_native_ttl()) {
             // The data has a TTL and the store doesn't support it natively.
             // We must fetch the data and expect a ttl wrapper.
-            if (array_key_exists($parsedkey, $session)) {
-                $data = $session[$parsedkey];
-                $has = ($data instanceof cache_ttl_wrapper && !$data->has_expired());
-            }
+            $data = $store->get($parsedkey);
+            $has = ($data instanceof cache_ttl_wrapper && !$data->has_expired());
+        } else if (!$this->store_supports_key_awareness()) {
+            // The store doesn't support key awareness, get the data and check it manually... puke.
+            // Either no TTL is set of the store supports its handling natively.
+            $data = $store->get($parsedkey);
+            $has = ($data !== false);
         } else {
-            $has = array_key_exists($parsedkey, $session);
+            // The store supports key awareness, this is easy!
+            // Either no TTL is set of the store supports its handling natively.
+            /* @var cache_store|cache_is_key_aware $store */
+            $has = $store->has($parsedkey);
         }
         if (!$has && $tryloadifpossible) {
+            $result = null;
             if ($this->get_loader() !== false) {
-                $result = $this->get_loader()->get($key);
+                $result = $this->get_loader()->get($parsedkey);
             } else if ($this->get_datasource() !== null) {
                 $result = $this->get_datasource()->load_for_cache($key);
             }
@@ -1960,25 +2021,18 @@ class cache_session extends cache {
      */
     public function has_all(array $keys) {
         $this->check_tracked_user();
-        $session = $this->get_session_data();
-        foreach ($keys as $key) {
-            $has = false;
-            $parsedkey = $this->parse_key($key);
-            if ($this->has_a_ttl()) {
-                // The data has a TTL and the store doesn't support it natively.
-                // We must fetch the data and expect a ttl wrapper.
-                if (array_key_exists($parsedkey, $session)) {
-                    $data = $session[$parsedkey];
-                    $has = ($data instanceof cache_ttl_wrapper && !$data->has_expired());
+        if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
+            foreach ($keys as $key) {
+                if (!$this->has($key)) {
+                    return false;
                 }
-            } else {
-                $has = array_key_exists($parsedkey, $session);
-            }
-            if (!$has) {
-                return false;
             }
+            return true;
         }
-        return true;
+        // The cache must be key aware and if support native ttl if it a ttl is set.
+        /* @var cache_store|cache_is_key_aware $store */
+        $store = $this->get_store();
+        return $store->has_all(array_map(array($this, 'parse_key'), $keys));
     }
 
     /**
@@ -1995,26 +2049,17 @@ class cache_session extends cache {
      * @return bool True if the cache has at least one of the given keys
      */
     public function has_any(array $keys) {
-        $this->check_tracked_user();
-        $session = $this->get_session_data();
-        foreach ($keys as $key) {
-            $has = false;
-            $parsedkey = $this->parse_key($key);
-            if ($this->has_a_ttl()) {
-                // The data has a TTL and the store doesn't support it natively.
-                // We must fetch the data and expect a ttl wrapper.
-                if (array_key_exists($parsedkey, $session)) {
-                    $data = $session[$parsedkey];
-                    $has = ($data instanceof cache_ttl_wrapper && !$data->has_expired());
+        if (($this->has_a_ttl() && !$this->store_supports_native_ttl()) || !$this->store_supports_key_awareness()) {
+            foreach ($keys as $key) {
+                if ($this->has($key)) {
+                    return true;
                 }
-            } else {
-                $has = array_key_exists($parsedkey, $session);
-            }
-            if ($has) {
-                return true;
             }
+            return false;
         }
-        return false;
+        /* @var cache_store|cache_is_key_aware $store */
+        $store = $this->get_store();
+        return $store->has_any(array_map(array($this, 'parse_key'), $keys));
     }
 
     /**
index 71fce81..c72c52c 100644 (file)
@@ -149,7 +149,7 @@ class cache_config_writer extends cache_config {
         }
         $class = 'cachestore_'.$plugin;
         if (!class_exists($class)) {
-            $plugins = get_plugin_list_with_file('cachestore', 'lib.php');
+            $plugins = core_component::get_plugin_list_with_file('cachestore', 'lib.php');
             if (!array_key_exists($plugin, $plugins)) {
                 throw new cache_exception('Invalid plugin name specified. The plugin does not exist or is not valid.');
             }
@@ -204,7 +204,7 @@ class cache_config_writer extends cache_config {
         }
         $class = 'cachelock_'.$plugin;
         if (!class_exists($class)) {
-            $plugins = get_plugin_list_with_file('cachelock', 'lib.php');
+            $plugins = core_component::get_plugin_list_with_file('cachelock', 'lib.php');
             if (!array_key_exists($plugin, $plugins)) {
                 throw new cache_exception('Invalid lock name specified. The plugin does not exist or is not valid.');
             }
@@ -315,7 +315,7 @@ class cache_config_writer extends cache_config {
         if (!array_key_exists($name, $this->configstores)) {
             throw new cache_exception('The requested instance does not exist.');
         }
-        $plugins = get_plugin_list_with_file('cachestore', 'lib.php');
+        $plugins = core_component::get_plugin_list_with_file('cachestore', 'lib.php');
         if (!array_key_exists($plugin, $plugins)) {
             throw new cache_exception('Invalid plugin name specified. The plugin either does not exist or is not valid.');
         }
@@ -523,7 +523,7 @@ class cache_config_writer extends cache_config {
         if (!$coreonly) {
             $plugintypes = core_component::get_plugin_types();
             foreach ($plugintypes as $type => $location) {
-                $plugins = get_plugin_list_with_file($type, 'db/caches.php');
+                $plugins = core_component::get_plugin_list_with_file($type, 'db/caches.php');
                 foreach ($plugins as $plugin => $filepath) {
                     $component = clean_param($type.'_'.$plugin, PARAM_COMPONENT); // Standardised plugin name.
                     $files[$component] = $filepath;
@@ -738,7 +738,7 @@ abstract class cache_administration_helper extends cache_helper {
      */
     public static function get_store_plugin_summaries() {
         $return = array();
-        $plugins = get_plugin_list_with_file('cachestore', 'lib.php', true);
+        $plugins = core_component::get_plugin_list_with_file('cachestore', 'lib.php', true);
         foreach ($plugins as $plugin => $path) {
             $class = 'cachestore_'.$plugin;
             $return[$plugin] = array(
index adc1a9b..4830d71 100644 (file)
@@ -336,6 +336,7 @@ class cachestore_file extends cache_store implements cache_is_key_aware, cache_i
         $filename = $key.'.cache';
         $file = $this->file_path_for_key($key);
         $ttl = $this->definition->get_ttl();
+        $maxtime = 0;
         if ($ttl) {
             $maxtime = cache::now() - $ttl;
         }
index 8221502..d5e245e 100644 (file)
@@ -118,7 +118,7 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
 
     /**
      * The maximum size for the store, or false if there isn't one.
-     * @var bool
+     * @var bool|int
      */
     protected $maxsize = false;
 
@@ -202,7 +202,7 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
      */
     public function initialise(cache_definition $definition) {
         $this->storeid = $definition->generate_definition_hash();
-        $this->store = &self::register_store_id($definition->get_id());
+        $this->store = &self::register_store_id($this->name.'-'.$definition->get_id());
         $this->ttl = $definition->get_ttl();
         $maxsize = $definition->get_maxsize();
         if ($maxsize !== null) {
@@ -210,6 +210,7 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
             $this->maxsize = abs((int)$maxsize);
             $this->storecount = count($this->store);
         }
+        $this->check_ttl();
     }
 
     /**
@@ -238,9 +239,17 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
     public function get($key) {
         if (isset($this->store[$key])) {
             if ($this->ttl == 0) {
-                return $this->store[$key][0];
+                $value = $this->store[$key][0];
+                if ($this->maxsize !== false) {
+                    // Make sure the element is now in the end of array.
+                    $this->set($key, $value);
+                }
+                return $value;
             } else if ($this->store[$key][1] >= (cache::now() - $this->ttl)) {
                 return $this->store[$key][0];
+            } else {
+                // Element is present but has expired.
+                $this->check_ttl();
             }
         }
         return false;
@@ -257,20 +266,32 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
      */
     public function get_many($keys) {
         $return = array();
+        $maxtime = 0;
         if ($this->ttl != 0) {
             $maxtime = cache::now() - $this->ttl;
         }
 
+        $hasexpiredelements = false;
         foreach ($keys as $key) {
             $return[$key] = false;
             if (isset($this->store[$key])) {
                 if ($this->ttl == 0) {
                     $return[$key] = $this->store[$key][0];
+                    if ($this->maxsize !== false) {
+                        // Make sure the element is now in the end of array.
+                        $this->set($key, $return[$key], false);
+                    }
                 } else if ($this->store[$key][1] >= $maxtime) {
                     $return[$key] = $this->store[$key][0];
+                } else {
+                    $hasexpiredelements = true;
                 }
             }
         }
+        if ($hasexpiredelements) {
+            // There are some elements that are present but have expired.
+            $this->check_ttl();
+        }
         return $return;
     }
 
@@ -279,24 +300,27 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
      *
      * @param string $key The key to use.
      * @param mixed $data The data to set.
-     * @param bool $testmaxsize If set to true then we test the maxsize arg and reduce if required.
+     * @param bool $testmaxsize If set to true then we test the maxsize arg and reduce if required. If this is set to false you will
+     *      need to perform these checks yourself. This allows for bulk set's to be performed and maxsize tests performed once.
      * @return bool True if the operation was a success false otherwise.
      */
     public function set($key, $data, $testmaxsize = true) {
         $testmaxsize = ($testmaxsize && $this->maxsize !== false);
-        if ($testmaxsize) {
-            $increment = (!isset($this->store[$key]));
+        $increment = $this->maxsize !== false && !isset($this->store[$key]);
+        if (($this->maxsize !== false && !$increment) || $this->ttl != 0) {
+            // Make sure the element is added to the end of $this->store array.
+            unset($this->store[$key]);
         }
-        if ($this->ttl == 0) {
-            $this->store[$key][0] = $data;
+        if ($this->ttl === 0) {
+            $this->store[$key] = array($data, 0);
         } else {
             $this->store[$key] = array($data, cache::now());
         }
-        if ($testmaxsize && $increment) {
+        if ($increment) {
             $this->storecount++;
-            if ($this->storecount > $this->maxsize) {
-                $this->reduce_for_maxsize();
-            }
+        }
+        if ($testmaxsize && $this->storecount > $this->maxsize) {
+            $this->reduce_for_maxsize();
         }
         return true;
     }
@@ -311,12 +335,26 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
      */
     public function set_many(array $keyvaluearray) {
         $count = 0;
+        $increment = 0;
         foreach ($keyvaluearray as $pair) {
-            $this->set($pair['key'], $pair['value'], false);
+            $key = $pair['key'];
+            $data = $pair['value'];
             $count++;
+            if ($this->maxsize !== false || $this->ttl !== 0) {
+                // Make sure the element is added to the end of $this->store array.
+                $this->delete($key);
+                $increment++;
+            } else if (!isset($this->store[$key])) {
+                $increment++;
+            }
+            if ($this->ttl === 0) {
+                $this->store[$key] = array($data, 0);
+            } else {
+                $this->store[$key] = array($data, cache::now());
+            }
         }
         if ($this->maxsize !== false) {
-            $this->storecount += $count;
+            $this->storecount += $increment;
             if ($this->storecount > $this->maxsize) {
                 $this->reduce_for_maxsize();
             }
@@ -348,6 +386,7 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
      * @return bool
      */
     public function has_all(array $keys) {
+        $maxtime = 0;
         if ($this->ttl != 0) {
             $maxtime = cache::now() - $this->ttl;
         }
@@ -370,6 +409,7 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
      * @return bool
      */
     public function has_any(array $keys) {
+        $maxtime = 0;
         if ($this->ttl != 0) {
             $maxtime = cache::now() - $this->ttl;
         }
@@ -389,12 +429,14 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
      * @return bool Returns true if the operation was a success, false otherwise.
      */
     public function delete($key) {
-        $result = isset($this->store[$key]);
+        if (!isset($this->store[$key])) {
+            return false;
+        }
         unset($this->store[$key]);
         if ($this->maxsize !== false) {
             $this->storecount--;
         }
-        return $result;
+        return true;
     }
 
     /**
@@ -404,17 +446,18 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
      * @return int The number of items successfully deleted.
      */
     public function delete_many(array $keys) {
-        $count = 0;
+        // The number of items that have actually being removed.
+        $reduction = 0;
         foreach ($keys as $key) {
             if (isset($this->store[$key])) {
-                $count++;
+                $reduction++;
             }
             unset($this->store[$key]);
         }
         if ($this->maxsize !== false) {
-            $this->storecount -= $count;
+            $this->storecount -= $reduction;
         }
-        return $count;
+        return $reduction;
     }
 
     /**
@@ -489,12 +532,40 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
         return $this->name;
     }
 
+    /**
+     * Removes expired elements.
+     * @return int number of removed elements
+     */
+    protected function check_ttl() {
+        if ($this->ttl === 0) {
+            return 0;
+        }
+        $maxtime = cache::now() - $this->ttl;
+        $count = 0;
+        for ($value = reset($this->store); $value !== false; $value = next($this->store)) {
+            if ($value[1] >= $maxtime) {
+                // We know that elements are sorted by ttl so no need to continue.
+                break;
+            }
+            $count++;
+        }
+        if ($count) {
+            // Remove first $count elements as they are expired.
+            $this->store = array_slice($this->store, $count, null, true);
+            if ($this->maxsize !== false) {
+                $this->storecount -= $count;
+            }
+        }
+        return $count;
+    }
+
     /**
      * Finds all of the keys being stored in the cache store instance.
      *
      * @return array
      */
     public function find_all() {
+        $this->check_ttl();
         return array_keys($this->store);
     }
 
@@ -502,6 +573,7 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
      * Finds all of the keys whose keys start with the given prefix.
      *
      * @param string $prefix
+     * @return array An array of keys.
      */
     public function find_by_prefix($prefix) {
         $return = array();
@@ -512,4 +584,12 @@ class cachestore_session extends session_data_store implements cache_is_key_awar
         }
         return $return;
     }
+
+    /**
+     * This store supports native TTL handling.
+     * @return bool
+     */
+    public function store_supports_native_ttl() {
+        return true;
+    }
 }
index 3ee20f2..ebf7059 100644 (file)
@@ -49,60 +49,66 @@ class cachestore_session_test extends cachestore_tests {
      * Test the maxsize option.
      */
     public function test_maxsize() {
-        $defid = 'phpunit/testmaxsize';
         $config = cache_config_phpunittest::instance();
-        $config->phpunit_add_definition($defid, array(
+        $config->phpunit_add_definition('phpunit/one', array(
             'mode' => cache_store::MODE_SESSION,
             'component' => 'phpunit',
-            'area' => 'testmaxsize',
+            'area' => 'one',
             'maxsize' => 3
         ));
-        $definition = cache_definition::load($defid, $config->get_definition_by_id($defid));
-        $instance = cachestore_session::initialise_test_instance($definition);
 
-        $this->assertTrue($instance->set('key1', 'value1'));
-        $this->assertTrue($instance->set('key2', 'value2'));
-        $this->assertTrue($instance->set('key3', 'value3'));
+        $config->phpunit_add_definition('phpunit/two', array(
+            'mode' => cache_store::MODE_SESSION,
+            'component' => 'phpunit',
+            'area' => 'two',
+            'maxsize' => 3
+        ));
+
+        $cacheone = cache::make('phpunit', 'one');
 
-        $this->assertTrue($instance->has('key1'));
-        $this->assertTrue($instance->has('key2'));
-        $this->assertTrue($instance->has('key3'));
+        $this->assertTrue($cacheone->set('key1', 'value1'));
+        $this->assertTrue($cacheone->set('key2', 'value2'));
+        $this->assertTrue($cacheone->set('key3', 'value3'));
 
-        $this->assertTrue($instance->set('key4', 'value4'));
-        $this->assertTrue($instance->set('key5', 'value5'));
+        $this->assertTrue($cacheone->has('key1'));
+        $this->assertTrue($cacheone->has('key2'));
+        $this->assertTrue($cacheone->has('key3'));
 
-        $this->assertFalse($instance->has('key1'));
-        $this->assertFalse($instance->has('key2'));
-        $this->assertTrue($instance->has('key3'));
-        $this->assertTrue($instance->has('key4'));
-        $this->assertTrue($instance->has('key5'));
+        $this->assertTrue($cacheone->set('key4', 'value4'));
+        $this->assertTrue($cacheone->set('key5', 'value5'));
 
-        $this->assertFalse($instance->get('key1'));
-        $this->assertFalse($instance->get('key2'));
-        $this->assertEquals('value3', $instance->get('key3'));
-        $this->assertEquals('value4', $instance->get('key4'));
-        $this->assertEquals('value5', $instance->get('key5'));
+        $this->assertFalse($cacheone->has('key1'));
+        $this->assertFalse($cacheone->has('key2'));
+        $this->assertTrue($cacheone->has('key3'));
+        $this->assertTrue($cacheone->has('key4'));
+        $this->assertTrue($cacheone->has('key5'));
+
+        $this->assertFalse($cacheone->get('key1'));
+        $this->assertFalse($cacheone->get('key2'));
+        $this->assertEquals('value3', $cacheone->get('key3'));
+        $this->assertEquals('value4', $cacheone->get('key4'));
+        $this->assertEquals('value5', $cacheone->get('key5'));
 
         // Test adding one more.
-        $this->assertTrue($instance->set('key6', 'value6'));
-        $this->assertFalse($instance->get('key3'));
+        $this->assertTrue($cacheone->set('key6', 'value6'));
+        $this->assertFalse($cacheone->get('key3'));
 
         // Test reducing and then adding to make sure we don't lost one.
-        $this->assertTrue($instance->delete('key6'));
-        $this->assertTrue($instance->set('key7', 'value7'));
-        $this->assertEquals('value4', $instance->get('key4'));
+        $this->assertTrue($cacheone->delete('key6'));
+        $this->assertTrue($cacheone->set('key7', 'value7'));
+        $this->assertEquals('value4', $cacheone->get('key4'));
 
         // Set the same key three times to make sure it doesn't count overrides.
         for ($i = 0; $i < 3; $i++) {
-            $this->assertTrue($instance->set('key8', 'value8'));
+            $this->assertTrue($cacheone->set('key8', 'value8'));
         }
-        $this->assertEquals('value7', $instance->get('key7'), 'Overrides are incorrectly incrementing size');
+        $this->assertEquals('value7', $cacheone->get('key7'), 'Overrides are incorrectly incrementing size');
 
         // Test adding many.
-        $this->assertEquals(3, $instance->set_many(array(
-            array('key' => 'keyA', 'value' => 'valueA'),
-            array('key' => 'keyB', 'value' => 'valueB'),
-            array('key' => 'keyC', 'value' => 'valueC')
+        $this->assertEquals(3, $cacheone->set_many(array(
+            'keyA' => 'valueA',
+            'keyB' => 'valueB',
+            'keyC' => 'valueC'
         )));
         $this->assertEquals(array(
             'key4' => false,
@@ -112,8 +118,82 @@ class cachestore_session_test extends cachestore_tests {
             'keyA' => 'valueA',
             'keyB' => 'valueB',
             'keyC' => 'valueC'
-        ), $instance->get_many(array(
+        ), $cacheone->get_many(array(
             'key4', 'key5', 'key6', 'key7', 'keyA', 'keyB', 'keyC'
         )));
+
+        $cachetwo = cache::make('phpunit', 'two');
+
+        // Test adding many.
+        $this->assertEquals(3, $cacheone->set_many(array(
+            'keyA' => 'valueA',
+            'keyB' => 'valueB',
+            'keyC' => 'valueC'
+        )));
+
+        $this->assertEquals(3, $cachetwo->set_many(array(
+            'key1' => 'value1',
+            'key2' => 'value2',
+            'key3' => 'value3'
+        )));
+
+        $this->assertEquals(array(
+            'keyA' => 'valueA',
+            'keyB' => 'valueB',
+            'keyC' => 'valueC'
+        ), $cacheone->get_many(array(
+            'keyA', 'keyB', 'keyC'
+        )));
+
+        $this->assertEquals(array(
+            'key1' => 'value1',
+            'key2' => 'value2',
+            'key3' => 'value3'
+        ), $cachetwo->get_many(array(
+            'key1', 'key2', 'key3'
+        )));
+
+        // Test that that cache deletes element that was least recently accessed.
+        $this->assertEquals('valueA', $cacheone->get('keyA'));
+        $cacheone->set('keyD', 'valueD');
+        $this->assertEquals('valueA', $cacheone->get('keyA'));
+        $this->assertFalse($cacheone->get('keyB'));
+        $this->assertEquals(array('keyD' => 'valueD', 'keyC' => 'valueC'), $cacheone->get_many(array('keyD', 'keyC')));
+        $cacheone->set('keyE', 'valueE');
+        $this->assertFalse($cacheone->get('keyB'));
+        $this->assertFalse($cacheone->get('keyA'));
+        $this->assertEquals(array('keyA' => false, 'keyE' => 'valueE', 'keyD' => 'valueD', 'keyC' => 'valueC'),
+                $cacheone->get_many(array('keyA', 'keyE', 'keyD', 'keyC')));
+        // Overwrite keyE (moves it to the end of array), and set keyF.
+        $cacheone->set_many(array('keyE' => 'valueE', 'keyF' => 'valueF'));
+        $this->assertEquals(array('keyC' => 'valueC', 'keyE' => 'valueE', 'keyD' => false, 'keyF' => 'valueF'),
+                $cacheone->get_many(array('keyC', 'keyE', 'keyD', 'keyF')));
+    }
+
+    public function test_ttl() {
+        $config = cache_config_phpunittest::instance();
+        $config->phpunit_add_definition('phpunit/three', array(
+            'mode' => cache_store::MODE_SESSION,
+            'component' => 'phpunit',
+            'area' => 'three',
+            'maxsize' => 3,
+            'ttl' => 3
+        ));
+
+        $cachethree = cache::make('phpunit', 'three');
+
+        // Make sure that when cache with ttl is full the elements that were added first are deleted first regardless of access time.
+        $cachethree->set('key1', 'value1');
+        $cachethree->set('key2', 'value2');
+        $cachethree->set('key3', 'value3');
+        $cachethree->set('key4', 'value4');
+        $this->assertFalse($cachethree->get('key1'));
+        $this->assertEquals('value4', $cachethree->get('key4'));
+        $cachethree->set('key5', 'value5');
+        $this->assertFalse($cachethree->get('key2'));
+        $this->assertEquals('value4', $cachethree->get('key4'));
+        $cachethree->set_many(array('key6' => 'value6', 'key7' => 'value7'));
+        $this->assertEquals(array('key3' => false, 'key4' => false, 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7'),
+                $cachethree->get_many(array('key3', 'key4', 'key5', 'key6', 'key7')));
     }
 }
\ No newline at end of file
index 301bee1..4592e41 100644 (file)
@@ -57,7 +57,7 @@ $struntestable = new lang_string('untestable', 'cache');
 $strtested = new lang_string('tested', 'cache');
 $strnotready = new lang_string('storenotready', 'cache');
 
-foreach (get_plugin_list_with_file('cachestore', 'lib.php', true) as $plugin => $path) {
+foreach (core_component::get_plugin_list_with_file('cachestore', 'lib.php', true) as $plugin => $path) {
 
     $class = 'cachestore_'.$plugin;
     $plugin = get_string('pluginname', 'cachestore_'.$plugin);
index 6a1630d..c30ae0c 100644 (file)
@@ -189,11 +189,8 @@ class core_cache_administration_helper_testcase extends advanced_testcase {
      * Test the hash_key functionality.
      */
     public function test_hash_key() {
-        global $CFG;
-
-        $currentdebugging = $CFG->debug;
-
-        $CFG->debug = E_ALL;
+        $this->resetAfterTest();
+        set_debugging(DEBUG_ALL);
 
         // First with simplekeys
         $instance = cache_config_phpunittest::instance(true);
@@ -230,7 +227,5 @@ class core_cache_administration_helper_testcase extends advanced_testcase {
 
         $result = cache_helper::hash_key('test/test', $definition);
         $this->assertEquals(sha1($definition->generate_single_key_prefix().'-test/test'), $result);
-
-        $CFG->debug = $currentdebugging;
     }
 }
index e7f4cdc..23df737 100644 (file)
@@ -1126,9 +1126,9 @@ class core_cache_testcase extends advanced_testcase {
     }
 
     /**
-     * Test that multiple loaders work ok.
+     * Test that multiple application loaders work ok.
      */
-    public function test_multiple_loaders() {
+    public function test_multiple_application_loaders() {
         $instance = cache_config_phpunittest::instance(true);
         $instance->phpunit_add_file_store('phpunittest1');
         $instance->phpunit_add_file_store('phpunittest2');
@@ -1173,6 +1173,93 @@ class core_cache_testcase extends advanced_testcase {
         $this->assertFalse($result['a']);
         $this->assertEquals('B', $result['b']);
         $this->assertFalse($result['c']);
+
+        // Test non-recursive deletes.
+        $this->assertTrue($cache->set('test', 'test'));
+        $this->assertSame('test', $cache->get('test'));
+        $this->assertTrue($cache->delete('test', false));
+        // We should still have it on a deeper loader.
+        $this->assertSame('test', $cache->get('test'));
+        // Test non-recusive with many functions.
+        $this->assertSame(3, $cache->set_many(array(
+            'one' => 'one',
+            'two' => 'two',
+            'three' => 'three'
+        )));
+        $this->assertSame('one', $cache->get('one'));
+        $this->assertSame(array('two' => 'two', 'three' => 'three'), $cache->get_many(array('two', 'three')));
+        $this->assertSame(3, $cache->delete_many(array('one', 'two', 'three'), false));
+        $this->assertSame('one', $cache->get('one'));
+        $this->assertSame(array('two' => 'two', 'three' => 'three'), $cache->get_many(array('two', 'three')));
+    }
+
+    /**
+     * Test that multiple application loaders work ok.
+     */
+    public function test_multiple_session_loaders() {
+        /* @var cache_config_phpunittest $instance */
+        $instance = cache_config_phpunittest::instance(true);
+        $instance->phpunit_add_session_store('phpunittest1');
+        $instance->phpunit_add_session_store('phpunittest2');
+        $instance->phpunit_add_definition('phpunit/multi_loader', array(
+            'mode' => cache_store::MODE_SESSION,
+            'component' => 'phpunit',
+            'area' => 'multi_loader'
+        ));
+        $instance->phpunit_add_definition_mapping('phpunit/multi_loader', 'phpunittest1', 3);
+        $instance->phpunit_add_definition_mapping('phpunit/multi_loader', 'phpunittest2', 2);
+
+        $cache = cache::make('phpunit', 'multi_loader');
+        $this->assertInstanceOf('cache_session', $cache);
+        $this->assertFalse($cache->get('test'));
+        $this->assertTrue($cache->set('test', 'test'));
+        $this->assertEquals('test', $cache->get('test'));
+        $this->assertTrue($cache->delete('test'));
+        $this->assertFalse($cache->get('test'));
+        $this->assertTrue($cache->set('test', 'test'));
+        $this->assertTrue($cache->purge());
+        $this->assertFalse($cache->get('test'));
+
+        // Test the many commands.
+        $this->assertEquals(3, $cache->set_many(array('a' => 'A', 'b' => 'B', 'c' => 'C')));
+        $result = $cache->get_many(array('a', 'b', 'c'));
+        $this->assertInternalType('array', $result);
+        $this->assertCount(3, $result);
+        $this->assertArrayHasKey('a', $result);
+        $this->assertArrayHasKey('b', $result);
+        $this->assertArrayHasKey('c', $result);
+        $this->assertEquals('A', $result['a']);
+        $this->assertEquals('B', $result['b']);
+        $this->assertEquals('C', $result['c']);
+        $this->assertEquals($result, $cache->get_many(array('a', 'b', 'c')));
+        $this->assertEquals(2, $cache->delete_many(array('a', 'c')));
+        $result = $cache->get_many(array('a', 'b', 'c'));
+        $this->assertInternalType('array', $result);
+        $this->assertCount(3, $result);
+        $this->assertArrayHasKey('a', $result);
+        $this->assertArrayHasKey('b', $result);
+        $this->assertArrayHasKey('c', $result);
+        $this->assertFalse($result['a']);
+        $this->assertEquals('B', $result['b']);
+        $this->assertFalse($result['c']);
+
+        // Test non-recursive deletes.
+        $this->assertTrue($cache->set('test', 'test'));
+        $this->assertSame('test', $cache->get('test'));
+        $this->assertTrue($cache->delete('test', false));
+        // We should still have it on a deeper loader.
+        $this->assertSame('test', $cache->get('test'));
+        // Test non-recusive with many functions.
+        $this->assertSame(3, $cache->set_many(array(
+            'one' => 'one',
+            'two' => 'two',
+            'three' => 'three'
+        )));
+        $this->assertSame('one', $cache->get('one'));
+        $this->assertSame(array('two' => 'two', 'three' => 'three'), $cache->get_many(array('two', 'three')));
+        $this->assertSame(3, $cache->delete_many(array('one', 'two', 'three'), false));
+        $this->assertSame('one', $cache->get('one'));
+        $this->assertSame(array('two' => 'two', 'three' => 'three'), $cache->get_many(array('two', 'three')));
     }
 
     /**
@@ -1448,4 +1535,4 @@ class core_cache_testcase extends advanced_testcase {
         $this->assertInstanceOf('cache_request', $cache);
         $this->assertArrayHasKey('cache_is_searchable', $cache->phpunit_get_store_implements());
     }
-}
+}
\ No newline at end of file
index f03a66c..b6d7358 100644 (file)
@@ -94,6 +94,24 @@ class cache_config_phpunittest extends cache_config_writer {
         );
     }
 
+    /**
+     * Forcefully adds a session store.
+     *
+     * @param string $name
+     */
+    public function phpunit_add_session_store($name) {
+        $this->configstores[$name] = array(
+            'name' => $name,
+            'plugin' => 'session',
+            'configuration' => array(),
+            'features' => 14,
+            'modes' => 2,
+            'default' => true,
+            'class' => 'cachestore_session',
+            'lock' => 'cachelock_file_default',
+        );
+    }
+
     /**
      * Forcefully injects a definition => store mapping.
      *
index 50ef3a6..7fed0c0 100644 (file)
@@ -607,6 +607,29 @@ function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxeve
     return $output;
 }
 
+
+/**
+ * Get a HTML link to a course.
+ *
+ * @param int $courseid the course id
+ * @return string a link to the course (as HTML); empty if the course id is invalid
+ */
+function calendar_get_courselink($courseid) {
+
+    if (!$courseid) {
+        return '';
+    }
+
+    calendar_get_course_cached($coursecache, $courseid);
+    $context = context_course::instance($courseid);
+    $fullname = format_string($coursecache[$courseid]->fullname, true, array('context' => $context));
+    $url = new moodle_url('/course/view.php', array('id' => $courseid));
+    $link = html_writer::link($url, $fullname);
+
+    return $link;
+}
+
+
 /**
  * Add calendar event metadata
  *
@@ -638,29 +661,21 @@ function calendar_add_event_metadata($event) {
         }
         $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
 
-        $context = context_course::instance($module->course);
-        $fullname = format_string($coursecache[$module->course]->fullname, true, array('context' => $context));
-
         $event->icon = '<img src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" class="icon" />';
         $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
-        $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$fullname.'</a>';
+        $event->courselink = calendar_get_courselink($module->course);
         $event->cmid = $module->id;
 
-
     } else if($event->courseid == SITEID) {                              // Site event
         $event->icon = '<img src="'.$OUTPUT->pix_url('i/siteevent') . '" alt="'.get_string('globalevent', 'calendar').'" class="icon" />';
         $event->cssclass = 'calendar_event_global';
     } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {          // Course event
-        calendar_get_course_cached($coursecache, $event->courseid);
-
-        $context = context_course::instance($event->courseid);
-        $fullname = format_string($coursecache[$event->courseid]->fullname, true, array('context' => $context));
-
         $event->icon = '<img src="'.$OUTPUT->pix_url('i/courseevent') . '" alt="'.get_string('courseevent', 'calendar').'" class="icon" />';
-        $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$fullname.'</a>';
+        $event->courselink = calendar_get_courselink($event->courseid);
         $event->cssclass = 'calendar_event_course';
     } else if ($event->groupid) {                                    // Group event
         $event->icon = '<img src="'.$OUTPUT->pix_url('i/groupevent') . '" alt="'.get_string('groupevent', 'calendar').'" class="icon" />';
+        $event->courselink = calendar_get_courselink($event->courseid);
         $event->cssclass = 'calendar_event_group';
     } else if($event->userid) {                                      // User event
         $event->icon = '<img src="'.$OUTPUT->pix_url('i/userevent') . '" alt="'.get_string('userevent', 'calendar').'" class="icon" />';
@@ -1193,9 +1208,10 @@ function calendar_days_in_month($month, $year) {
  *
  * @param array $events list of events
  * @param moodle_url|string $linkhref link to event referer
+ * @param boolean $showcourselink whether links to courses should be shown
  * @return string|null $content html block content
  */
-function calendar_get_block_upcoming($events, $linkhref = NULL) {
+function calendar_get_block_upcoming($events, $linkhref = NULL, $showcourselink = false) {
     $content = '';
     $lines = count($events);
     if (!$lines) {
@@ -1223,6 +1239,9 @@ function calendar_get_block_upcoming($events, $linkhref = NULL) {
             }
         }
         $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
+        if ($showcourselink && !empty($events[$i]->courselink)) {
+            $content .= html_writer::div($events[$i]->courselink, 'course');
+        }
         $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
         if ($i < $lines - 1) $content .= '<hr />';
     }
@@ -1391,14 +1410,8 @@ function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
  * @return stdClass $coursecache[$courseid] return the specific course cache
  */
 function calendar_get_course_cached(&$coursecache, $courseid) {
-    global $COURSE, $DB;
-
     if (!isset($coursecache[$courseid])) {
-        if ($courseid == $COURSE->id) {
-            $coursecache[$courseid] = $COURSE;
-        } else {
-            $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
-        }
+        $coursecache[$courseid] = get_course($courseid);
     }
     return $coursecache[$courseid];
 }
diff --git a/calendar/tests/lib_test.php b/calendar/tests/lib_test.php
new file mode 100644 (file)
index 0000000..c405b96
--- /dev/null
@@ -0,0 +1,71 @@
+<?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/>.
+
+/**
+ * Calendar lib unit tests
+ *
+ * @package    core_calendar
+ * @copyright  2013 Dan Poltawski <dan@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+global $CFG;
+require_once($CFG->dirroot . '/calendar/lib.php');
+
+/**
+ * Unit tests for calendar lib
+ *
+ * @package    core_calendar
+ * @copyright  2013 Dan Poltawski <dan@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class core_calendar_lib_testcase extends advanced_testcase {
+
+    public function test_calendar_get_course_cached() {
+        $this->resetAfterTest(true);
+
+        // Setup some test courses.
+        $course1 = $this->getDataGenerator()->create_course();
+        $course2 = $this->getDataGenerator()->create_course();
+        $course3 = $this->getDataGenerator()->create_course();
+
+        // Load courses into cache.
+        $coursecache = null;
+        calendar_get_course_cached($coursecache, $course1->id);
+        calendar_get_course_cached($coursecache, $course2->id);
+        calendar_get_course_cached($coursecache, $course3->id);
+
+        // Verify the cache.
+        $this->assertArrayHasKey($course1->id, $coursecache);
+        $cachedcourse1 = $coursecache[$course1->id];
+        $this->assertEquals($course1->id, $cachedcourse1->id);
+        $this->assertEquals($course1->shortname, $cachedcourse1->shortname);
+        $this->assertEquals($course1->fullname, $cachedcourse1->fullname);
+
+        $this->assertArrayHasKey($course2->id, $coursecache);
+        $cachedcourse2 = $coursecache[$course2->id];
+        $this->assertEquals($course2->id, $cachedcourse2->id);
+        $this->assertEquals($course2->shortname, $cachedcourse2->shortname);
+        $this->assertEquals($course2->fullname, $cachedcourse2->fullname);
+
+        $this->assertArrayHasKey($course3->id, $coursecache);
+        $cachedcourse3 = $coursecache[$course3->id];
+        $this->assertEquals($course3->id, $cachedcourse3->id);
+        $this->assertEquals($course3->shortname, $cachedcourse3->shortname);
+        $this->assertEquals($course3->fullname, $cachedcourse3->fullname);
+    }
+}
index 61d56c9..51ac01c 100644 (file)
@@ -57,7 +57,12 @@ function cohort_add_cohort($cohort) {
 
     $cohort->id = $DB->insert_record('cohort', $cohort);
 
-    events_trigger('cohort_added', $cohort);
+    $event = \core\event\cohort_created::create(array(
+        'context' => context::instance_by_id($cohort->contextid),
+        'objectid' => $cohort->id,
+    ));
+    $event->add_record_snapshot('cohort', $cohort);
+    $event->trigger();
 
     return $cohort->id;
 }
@@ -76,7 +81,12 @@ function cohort_update_cohort($cohort) {
     $cohort->timemodified = time();
     $DB->update_record('cohort', $cohort);
 
-    events_trigger('cohort_updated', $cohort);
+    $event = \core\event\cohort_updated::create(array(
+        'context' => context::instance_by_id($cohort->contextid),
+        'objectid' => $cohort->id,
+    ));
+    $event->add_record_snapshot('cohort', $cohort);
+    $event->trigger();
 }
 
 /**
@@ -94,7 +104,12 @@ function cohort_delete_cohort($cohort) {
     $DB->delete_records('cohort_members', array('cohortid'=>$cohort->id));
     $DB->delete_records('cohort', array('id'=>$cohort->id));
 
-    events_trigger('cohort_deleted', $cohort);
+    $event = \core\event\cohort_deleted::create(array(
+        'context' => context::instance_by_id($cohort->contextid),
+        'objectid' => $cohort->id,
+    ));
+    $event->add_record_snapshot('cohort', $cohort);
+    $event->trigger();
 }
 
 /**
@@ -141,7 +156,15 @@ function cohort_add_member($cohortid, $userid) {
     $record->timeadded = time();
     $DB->insert_record('cohort_members', $record);
 
-    events_trigger('cohort_member_added', (object)array('cohortid'=>$cohortid, 'userid'=>$userid));
+    $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
+
+    $event = \core\event\cohort_member_added::create(array(
+        'context' => context::instance_by_id($cohort->contextid),
+        'objectid' => $cohortid,
+        'relateduserid' => $userid,
+    ));
+    $event->add_record_snapshot('cohort', $cohort);
+    $event->trigger();
 }
 
 /**
@@ -154,7 +177,15 @@ function cohort_remove_member($cohortid, $userid) {
     global $DB;
     $DB->delete_records('cohort_members', array('cohortid'=>$cohortid, 'userid'=>$userid));
 
-    events_trigger('cohort_member_removed', (object)array('cohortid'=>$cohortid, 'userid'=>$userid));
+    $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
+
+    $event = \core\event\cohort_member_removed::create(array(
+        'context' => context::instance_by_id($cohort->contextid),
+        'objectid' => $cohortid,
+        'relateduserid' => $userid,
+    ));
+    $event->add_record_snapshot('cohort', $cohort);
+    $event->trigger();
 }
 
 /**
index e6446e7..64f40c7 100644 (file)
@@ -62,20 +62,50 @@ class core_cohort_cohortlib_testcase extends advanced_testcase {
         $this->assertNotEmpty($newcohort->timecreated);
         $this->assertSame($newcohort->component, '');
         $this->assertSame($newcohort->timecreated, $newcohort->timemodified);
+    }
+
+    public function test_cohort_add_cohort_missing_name() {
+        $cohort = new stdClass();
+        $cohort->contextid = context_system::instance()->id;
+        $cohort->name = null;
+        $cohort->idnumber = 'testid';
+        $cohort->description = 'test cohort desc';
+        $cohort->descriptionformat = FORMAT_HTML;
+
+        $this->setExpectedException('coding_exception', 'Missing cohort name in cohort_add_cohort().');
+        cohort_add_cohort($cohort);
+    }
+
+    public function test_cohort_add_cohort_event() {
+        $this->resetAfterTest();
+
+        // Setup cohort data structure.
+        $cohort = new stdClass();
+        $cohort->contextid = context_system::instance()->id;
+        $cohort->name = 'test cohort';
+        $cohort->idnumber = 'testid';
+        $cohort->description = 'test cohort desc';
+        $cohort->descriptionformat = FORMAT_HTML;
 
-        try {
-            $cohort = new stdClass();
-            $cohort->contextid = context_system::instance()->id;
-            $cohort->name = null;
-            $cohort->idnumber = 'testid';
-            $cohort->description = 'test cohort desc';
-            $cohort->descriptionformat = FORMAT_HTML;
-            cohort_add_cohort($cohort);
-
-            $this->fail('Exception expected when trying to add cohort without name');
-        } catch (Exception $e) {
-            $this->assertInstanceOf('coding_exception', $e);
-        }
+        // Catch Events.
+        $sink = $this->redirectEvents();
+
+        // Perform the add operation.
+        $id = cohort_add_cohort($cohort);
+
+        // Capture the event.
+        $events = $sink->get_events();
+        $sink->close();
+
+        // Validate the event.
+        $this->assertCount(1, $events);
+        $event = $events[0];
+        $this->assertInstanceOf('\core\event\cohort_created', $event);
+        $this->assertEquals('cohort', $event->objecttable);
+        $this->assertEquals($id, $event->objectid);
+        $this->assertEquals($cohort->contextid, $event->contextid);
+        $this->assertEquals($cohort, $event->get_record_snapshot('cohort', $id));
+        $this->assertEventLegacyData($cohort, $event);
     }
 
     public function test_cohort_update_cohort() {
@@ -110,6 +140,44 @@ class core_cohort_cohortlib_testcase extends advanced_testcase {
         $this->assertLessThanOrEqual(time(), $newcohort->timemodified);
     }
 
+    public function test_cohort_update_cohort_event() {
+        global $DB;
+
+        $this->resetAfterTest();
+
+        // Setup the cohort data structure.
+        $cohort = new stdClass();
+        $cohort->contextid = context_system::instance()->id;
+        $cohort->name = 'test cohort';
+        $cohort->idnumber = 'testid';
+        $cohort->description = 'test cohort desc';
+        $cohort->descriptionformat = FORMAT_HTML;
+        $id = cohort_add_cohort($cohort);
+        $this->assertNotEmpty($id);
+
+        $cohort->name = 'test cohort 2';
+
+        // Catch Events.
+        $sink = $this->redirectEvents();
+
+        // Peform the update.
+        cohort_update_cohort($cohort);
+
+        $events = $sink->get_events();
+        $sink->close();
+
+        // Validate the event.
+        $this->assertCount(1, $events);
+        $event = $events[0];
+        $updatedcohort = $DB->get_record('cohort', array('id'=>$id));
+        $this->assertInstanceOf('\core\event\cohort_updated', $event);
+        $this->assertEquals('cohort', $event->objecttable);
+        $this->assertEquals($updatedcohort->id, $event->objectid);
+        $this->assertEquals($updatedcohort->contextid, $event->contextid);
+        $this->assertEquals($cohort, $event->get_record_snapshot('cohort', $id));
+        $this->assertEventLegacyData($cohort, $event);
+    }
+
     public function test_cohort_delete_cohort() {
         global $DB;
 
@@ -122,6 +190,31 @@ class core_cohort_cohortlib_testcase extends advanced_testcase {
         $this->assertFalse($DB->record_exists('cohort', array('id'=>$cohort->id)));
     }
 
+    public function test_cohort_delete_cohort_event() {
+
+        $this->resetAfterTest();
+
+        $cohort = $this->getDataGenerator()->create_cohort();
+
+        // Capture the events.
+        $sink = $this->redirectEvents();
+
+        // Perform the delete.
+        cohort_delete_cohort($cohort);
+
+        $events = $sink->get_events();
+        $sink->close();
+
+        // Validate the event structure.
+        $this->assertCount(1, $events);
+        $event = $events[0];
+        $this->assertInstanceOf('\core\event\cohort_deleted', $event);
+        $this->assertEquals('cohort', $event->objecttable);
+        $this->assertEquals($cohort->id, $event->objectid);
+        $this->assertEquals($cohort, $event->get_record_snapshot('cohort', $cohort->id));
+        $this->assertEventLegacyData($cohort, $event);
+    }
+
     public function test_cohort_delete_category() {
         global $DB;
 
@@ -151,6 +244,34 @@ class core_cohort_cohortlib_testcase extends advanced_testcase {
         $this->assertTrue($DB->record_exists('cohort_members', array('cohortid'=>$cohort->id, 'userid'=>$user->id)));
     }
 
+    public function test_cohort_add_member_event() {
+        global $USER;
+        $this->resetAfterTest();
+
+        // Setup the data.
+        $cohort = $this->getDataGenerator()->create_cohort();
+        $user = $this->getDataGenerator()->create_user();
+
+        // Capture the events.
+        $sink = $this->redirectEvents();
+
+        // Peform the add member operation.
+        cohort_add_member($cohort->id, $user->id);
+
+        $events = $sink->get_events();
+        $sink->close();
+
+        // Validate the event.
+        $this->assertCount(1, $events);
+        $event = $events[0];
+        $this->assertInstanceOf('\core\event\cohort_member_added', $event);
+        $this->assertEquals('cohort', $event->objecttable);
+        $this->assertEquals($cohort->id, $event->objectid);
+        $this->assertEquals($user->id, $event->relateduserid);
+        $this->assertEquals($USER->id, $event->userid);
+        $this->assertEventLegacyData((object) array('cohortid' => $cohort->id, 'userid' => $user->id), $event);
+    }
+
     public function test_cohort_remove_member() {
         global $DB;
 
@@ -166,6 +287,34 @@ class core_cohort_cohortlib_testcase extends advanced_testcase {
         $this->assertFalse($DB->record_exists('cohort_members', array('cohortid'=>$cohort->id, 'userid'=>$user->id)));
     }
 
+    public function test_cohort_remove_member_event() {
+        global $USER;
+        $this->resetAfterTest();
+
+        // Setup the data.
+        $cohort = $this->getDataGenerator()->create_cohort();
+        $user = $this->getDataGenerator()->create_user();
+        cohort_add_member($cohort->id, $user->id);
+
+        // Capture the events.
+        $sink = $this->redirectEvents();
+
+        // Peform the remove operation.
+        cohort_remove_member($cohort->id, $user->id);
+        $events = $sink->get_events();
+        $sink->close();
+
+        // Validate the event.
+        $this->assertCount(1, $events);
+        $event = $events[0];
+        $this->assertInstanceOf('\core\event\cohort_member_removed', $event);
+        $this->assertEquals('cohort', $event->objecttable);
+        $this->assertEquals($cohort->id, $event->objectid);
+        $this->assertEquals($user->id, $event->relateduserid);
+        $this->assertEquals($USER->id, $event->userid);
+        $this->assertEventLegacyData((object) array('cohortid' => $cohort->id, 'userid' => $user->id), $event);
+    }
+
     public function test_cohort_is_member() {
         global $DB;
 
index dab34d8..52619b2 100644 (file)
@@ -143,23 +143,35 @@ class completion_completion extends data_object {
      * @return void
      */
     public function mark_complete($timecomplete = null) {
+        global $USER;
 
-        // Never change a completion time
+        // Never change a completion time.
         if ($this->timecompleted) {
             return;
         }
 
-        // Use current time if nothing supplied
+        // Use current time if nothing supplied.
         if (!$timecomplete) {
             $timecomplete = time();
         }
 
-        // Set time complete
+        // Set time complete.
         $this->timecompleted = $timecomplete;
 
-        // Save record
+        // Save record.
         if ($result = $this->_save()) {
-            events_trigger('course_completed', $this->get_record_data());
+            $data = $this->get_record_data();
+            $event = \core\event\course_completed::create(
+                array(
+                    'objectid' => $data->id,
+                    'userid' => $USER->id,
+                    'context' => context_course::instance($data->course),
+                    'courseid' => $data->course,
+                    'other' => array('relateduserid' => $data->userid)
+                    )
+                );
+            $event->add_record_snapshot('course_completions', $data);
+            $event->trigger();
         }
 
         return $result;
index 2022649..0b2a9b1 100644 (file)
@@ -365,25 +365,6 @@ $CFG->admin = 'admin';
 // 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
-// $CFG->cachedir/lang. In cluster environment, you may wish to specify
-// an alternative location of this cache so that each web server in the cluster
-// uses its own local cache and does not need to access the shared dataroot.
-// Make sure that the web server process has write permission to this location
-// and that it has permission to remove the folder, too (so that the cache can
-// be pruned).
-//
-//     $CFG->langcacheroot = '/var/www/moodle/htdocs/altcache/lang';
-//
-// If $CFG->langcache is enabled (which should always be in production
-// environment), Moodle stores the list of available languages in a cache file.
-// By default, the file $CFG->dataroot/languages is used. You may wish to
-// specify an alternative location of this cache file.
-//
-//     $CFG->langmenucachefile = '/var/www/moodle/htdocs/altcache/languages';
-//
 // Site default language can be set via standard administration interface. If you
 // want to have initial error messages for eventual database connection problems
 // localized too, you have to set your language code here.
@@ -483,12 +464,12 @@ $CFG->admin = 'admin';
 // $CFG->debugusers = '2';
 //
 // Prevent theme caching
-// $CFG->themerev = -1; // NOT FOR PRODUCTION SERVERS!
+// $CFG->themedesignermode = true; // NOT FOR PRODUCTION SERVERS!
 //
 // Prevent JS caching
-// $CFG->jsrev = -1; // NOT FOR PRODUCTION SERVERS!
+// $CFG->cachejs = false; // NOT FOR PRODUCTION SERVERS!
 //
-// Prevent core_string_manager on-disk cache
+// Prevent core_string_manager application caching
 // $CFG->langstringcache = false; // NOT FOR PRODUCTION SERVERS!
 //
 // When working with production data on test servers, no emails or other messages
index 8c16a87..12e4859 100644 (file)
@@ -134,8 +134,14 @@ if ($form->is_cancelled()){
     $aggregation->setMethod($data->role_aggregation);
     $aggregation->save();
 
-    // Log changes.
-    add_to_log($course->id, 'course', 'completion updated', 'completion.php?id='.$course->id);
+    // Trigger an event for course module completion changed.
+    $event = \core\event\course_completion_updated::create(
+            array(
+                'courseid' => $course->id,
+                'context' => context_course::instance($course->id)
+                )
+            );
+    $event->trigger();
 
     // Redirect to the course main page.
     $url = new moodle_url('/course/view.php', array('id' => $course->id));
index 71bafca..26c3de2 100644 (file)
         print_error('confirmsesskeybad', 'error');
     }
 
-    // OK checks done, delete the course now.
-
-    add_to_log(SITEID, "course", "delete", "view.php?id=$course->id", "$course->fullname (ID $course->id)");
-
     $strdeletingcourse = get_string("deletingcourse", "", $courseshortname);
 
     $PAGE->navbar->add($strdeletingcourse);
index c75e3dc..54db939 100644 (file)
@@ -25,6 +25,7 @@
 
 require_once("../config.php");
 require_once("lib.php");
+require_once($CFG->libdir . '/formslib.php');
 require_once($CFG->libdir . '/conditionlib.php');
 
 $id = required_param('id', PARAM_INT);    // course_sections.id
@@ -40,7 +41,7 @@ require_login($course);
 $context = context_course::instance($course->id);
 require_capability('moodle/course:update', $context);
 
-// get section_info object with all availability options
+// Get section_info object with all availability options.
 $sectioninfo = get_fast_modinfo($course)->get_section_info($sectionnum);
 
 $editoroptions = array('context'=>$context ,'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes'=>$CFG->maxbytes, 'trusttext'=>false, 'noclean'=>true);
@@ -51,31 +52,44 @@ $mform = course_get_format($course->id)->editsection_form($PAGE->url,
 $mform->set_data(convert_to_array($sectioninfo));
 
 if ($mform->is_cancelled()){
-    // form cancelled, return to course
+    // Form cancelled, return to course.
     redirect(course_get_url($course, $section, array('sr' => $sectionreturn)));
 } else if ($data = $mform->get_data()) {
-    // data submitted and validated, update and return to course
+    // Data submitted and validated, update and return to course.
     $DB->update_record('course_sections', $data);
     rebuild_course_cache($course->id, true);
     if (isset($data->section)) {
-        // usually edit form does not change relative section number but just in case
+        // Usually edit form does not change relative section number but just in case.
         $sectionnum = $data->section;
     }
     if (!empty($CFG->enableavailability)) {
-        // Update grade and completion conditions
+        // Update grade and completion conditions.
         $sectioninfo = get_fast_modinfo($course)->get_section_info($sectionnum);
         condition_info_section::update_section_from_form($sectioninfo, $data);
         rebuild_course_cache($course->id, true);
     }
     course_get_format($course->id)->update_section_format_options($data);
 
-    add_to_log($course->id, "course", "editsection", "editsection.php?id=$id", "$sectionnum");
+    // Set section info, as this might not be present in form_data.
+    if (!isset($data->section))  {
+        $data->section = $sectionnum;
+    }
+    // Trigger an event for course section update.
+    $event = \core\event\course_section_updated::create(
+            array(
+                'objectid' => $data->id,
+                'courseid' => $course->id,
+                'context' => $context,
+                'other' => array('sectionnum' => $data->section)
+            )
+        );
+    $event->trigger();
+
     $PAGE->navigation->clear_cache();
     redirect(course_get_url($course, $section, array('sr' => $sectionreturn)));
 }
 
-// the edit form is displayed for the first time or there was a validation
-// error on the previous step. Display the edit form:
+// The edit form is displayed for the first time or if there was validation error on the previous step.
 $sectionname  = get_section_name($course, $sectionnum);
 $stredit      = get_string('edita', '', " $sectionname");
 $strsummaryof = get_string('summaryof', '', " $sectionname");
index fe69315..bfc5641 100644 (file)
@@ -172,9 +172,11 @@ abstract class format_section_renderer_base extends plugin_renderer_base {
         // When on a section page, we only display the general section title, if title is not the default one
         $hasnamesecpg = ($onsectionpage && ($section->section == 0 && !is_null($section->name)));
 
+        $classes = ' accesshide';
         if ($hasnamenotsecpg || $hasnamesecpg) {
-            $o.= $this->output->heading($this->section_title($section, $course), 3, 'sectionname');
+            $classes = '';
         }
+        $o.= $this->output->heading($this->section_title($section, $course), 3, 'sectionname' . $classes);
 
         $o.= html_writer::start_tag('div', array('class' => 'summary'));
         $o.= $this->format_summary_text($section);
index 6092350..e1e1240 100644 (file)
@@ -28,7 +28,6 @@ defined('MOODLE_INTERNAL') || die;
 
 require_once($CFG->libdir.'/completionlib.php');
 require_once($CFG->libdir.'/filelib.php');
-require_once($CFG->dirroot.'/course/dnduploadlib.php');
 require_once($CFG->dirroot.'/course/format/lib.php');
 
 define('COURSE_MAX_LOGS_PER_PAGE', 1000);       // records
@@ -959,7 +958,9 @@ function get_array_of_activities($courseid) {
                                    $mod[$seq]->extraclasses = $info->extraclasses;
                                }
                                if (!empty($info->iconurl)) {
-                                   $mod[$seq]->iconurl = $info->iconurl;
+                                   // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
+                                   $url = new moodle_url($info->iconurl);
+                                   $mod[$seq]->iconurl = $url->out(false);
                                }
                                if (!empty($info->onclick)) {
                                    $mod[$seq]->onclick = $info->onclick;
@@ -1236,9 +1237,10 @@ function get_category_or_system_context($categoryid) {
 function make_categories_options() {
     global $CFG;
     require_once($CFG->libdir. '/coursecatlib.php');
-    $cats = coursecat::make_categories_list();
+    $cats = coursecat::make_categories_list('', 0, ' / ');
     foreach ($cats as $key => $value) {
-        $cats[$key] = str_repeat('&nbsp;', coursecat::get($key)->depth - 1). $value;
+        // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
+        $cats[$key] = str_repeat('&nbsp;', substr_count($value, ' / ')). $value;
     }
     return $cats;
 }
@@ -1328,6 +1330,10 @@ function course_create_sections_if_missing($courseorid, $sections) {
  *
  * Updates both tables {course_sections} and {course_modules}
  *
+ * Note: This function does not use modinfo PROVIDED that the section you are
+ * adding the module to already exists. If the section does not exist, it will
+ * build modinfo if necessary and create the section.
+ *
  * @param int|stdClass $courseorid course id or course object
  * @param int $cmid id of the module already existing in course_modules table
  * @param int $sectionnum relative number of the section (field course_sections.section)
@@ -1347,9 +1353,16 @@ function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod =
     } else {
         $courseid = $courseorid;
     }
-    course_create_sections_if_missing($courseorid, $sectionnum);
     // Do not try to use modinfo here, there is no guarantee it is valid!
-    $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST);
+    $section = $DB->get_record('course_sections',
+            array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
+    if (!$section) {
+        // This function call requires modinfo.
+        course_create_sections_if_missing($courseorid, $sectionnum);
+        $section = $DB->get_record('course_sections',
+                array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
+    }
+
     $modarray = explode(",", trim($section->sequence));
     if (empty($section->sequence)) {
         $newsequence = "$cmid";
@@ -1939,7 +1952,7 @@ function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
                 array('class' => 'editing_'. $actionname, 'data-action' => $actionname, 'data-nextgroupmode' => $nextgroupmode)
             );
         } else {
-            $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => '', 'class' => 'iconsmall'));
+            $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('class' => 'iconsmall'));
         }
     }
 
@@ -2014,14 +2027,14 @@ function course_allowed_module($course, $modname) {
  * @return bool success
  */
 function move_courses($courseids, $categoryid) {
-    global $CFG, $DB, $OUTPUT;
+    global $DB;
 
     if (empty($courseids)) {
-        // nothing to do
+        // Nothing to do.
         return;
     }
 
-    if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
+    if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
         return false;
     }
 
@@ -2030,21 +2043,37 @@ function move_courses($courseids, $categoryid) {
     $i = 1;
 
     foreach ($courseids as $courseid) {
-        if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
+        if ($dbcourse = $DB->get_record('course', array('id' => $courseid))) {
             $course = new stdClass();
             $course->id = $courseid;
             $course->category  = $category->id;
             $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
             if ($category->visible == 0) {
-                // hide the course when moving into hidden category,
-                // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
+                // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
+                // to previous state if somebody unhides the category.
                 $course->visible = 0;
             }
 
             $DB->update_record('course', $course);
-            add_to_log($course->id, "course", "move", "edit.php?id=$course->id", $course->id);
 
-            $context   = context_course::instance($course->id);
+            // Store the context.
+            $context = context_course::instance($course->id);
+
+            // Update the course object we are passing to the event.
+            $dbcourse->category = $course->category;
+            $dbcourse->sortorder = $course->sortorder;
+
+            // Trigger a course updated event.
+            $event = \core\event\course_updated::create(array(
+                'objectid' => $course->id,
+                'context' => $context,
+                'other' => array('shortname' => $dbcourse->shortname,
+                                 'fullname' => $dbcourse->fullname)
+            ));
+            $event->add_record_snapshot('course', $dbcourse);
+            $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
+            $event->trigger();
+
             $context->update_moved($newparent);
         }
     }
@@ -2217,7 +2246,7 @@ function course_overviewfiles_options($course) {
  * @return object new course instance
  */
 function create_course($data, $editoroptions = NULL) {
-    global $CFG, $DB;
+    global $DB;
 
     //check the categoryid - must be given for all new courses
     $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
@@ -2292,10 +2321,15 @@ function create_course($data, $editoroptions = NULL) {
     // set up enrolments
     enrol_course_updated(true, $course, $data);
 
-    add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
-
-    // Trigger events
-    events_trigger('course_created', $course);
+    // Trigger a course created event.
+    $event = \core\event\course_created::create(array(
+        'objectid' => $course->id,
+        'context' => context_course::instance($course->id),
+        'other' => array('shortname' => $course->shortname,
+                         'fullname' => $course->fullname)
+    ));
+    $event->add_record_snapshot('course', $course);
+    $event->trigger();
 
     return $course;
 }
@@ -2311,7 +2345,7 @@ function create_course($data, $editoroptions = NULL) {
  * @return void
  */
 function update_course($data, $editoroptions = NULL) {
-    global $CFG, $DB;
+    global $DB;
 
     $data->timemodified = time();
 
@@ -2381,10 +2415,16 @@ function update_course($data, $editoroptions = NULL) {
     // update enrol settings
     enrol_course_updated(false, $course, $data);
 
-    add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
-
-    // Trigger events
-    events_trigger('course_updated', $course);
+    // Trigger a course updated event.
+    $event = \core\event\course_updated::create(array(
+        'objectid' => $course->id,
+        'context' => $context,
+        'other' => array('shortname' => $course->shortname,
+                         'fullname' => $course->fullname)
+    ));
+    $event->add_record_snapshot('course', $course);
+    $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
+    $event->trigger();
 
     if ($oldcourse->format !== $course->format) {
         // Remove all options stored for the previous format
@@ -2886,7 +2926,7 @@ function course_ajax_enabled($course) {
  * @return bool
  */
 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
-    global $PAGE, $SITE;
+    global $CFG, $PAGE, $SITE;
 
     // Ensure that ajax should be included
     if (!course_ajax_enabled($course)) {
@@ -2965,6 +3005,9 @@ function include_course_ajax($course, $usedmodules = array(), $enabledmodules =
             'markedthistopic',
             'move',
             'movesection',
+            'movecontent',
+            'tocontent',
+            'emptydragdropregion'
         ), 'moodle');
 
     // Include format-specific strings
@@ -2981,6 +3024,7 @@ function include_course_ajax($course, $usedmodules = array(), $enabledmodules =
     }
 
     // Load drag and drop upload AJAX.
+    require_once($CFG->dirroot.'/course/dnduploadlib.php');
     dndupload_add_to_course($course, $enabledmodules);
 
     return true;
index 0c1ec26..97f7d2a 100644 (file)
@@ -1,5 +1,5 @@
 <?php
-// Allows a teacher/admin to login as another user (in stealth mode)
+// Allows a teacher/admin to login as another user (in stealth mode).
 
 require_once('../config.php');
 require_once('lib.php');
@@ -10,7 +10,7 @@ $redirect = optional_param('redirect', 0, PARAM_BOOL);
 $url = new moodle_url('/course/loginas.php', array('id'=>$id));
 $PAGE->set_url($url);
 
-/// Reset user back to their real self if needed, for security reasons you need to log out and log in again
+// Reset user back to their real self if needed, for security reasons you need to log out and log in again.
 if (session_is_loggedinas()) {
     require_sesskey();
     require_logout();
@@ -29,15 +29,13 @@ if ($redirect) {
     redirect(get_login_url());
 }
 
-///-------------------------------------
-/// We are trying to log in as this user in the first place
-
-$userid = required_param('user', PARAM_INT);         // login as this user
+// Try log in as this user.
+$userid = required_param('user', PARAM_INT);
 
 require_sesskey();
 $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST);
 
-/// User must be logged in
+// User must be logged in.
 
 $systemcontext = context_system::instance();
 $coursecontext = context_course::instance($course->id);
@@ -62,13 +60,10 @@ if (has_capability('moodle/user:loginas', $systemcontext)) {
     $context = $coursecontext;
 }
 
-/// Login as this user and return to course home page.
-$oldfullname = fullname($USER, true);
+// Login as this user and return to course home page.
 session_loginas($userid, $context);
 $newfullname = fullname($USER, true);
 
-add_to_log($course->id, "course", "loginas", "../user/view.php?id=$course->id&amp;user=$userid", "$oldfullname -> $newfullname");
-
 $strloginas    = get_string('loginas');
 $strloggedinas = get_string('loggedinas', '', $newfullname);
 
index d4a9054..4888c0a 100644 (file)
@@ -249,7 +249,22 @@ if ((!empty($hide) or !empty($show)) && confirm_sesskey()) {
     $params = array('id' => $course->id, 'visible' => $visible, 'visibleold' => $visible, 'timemodified' => time());
     $DB->update_record('course', $params);
     cache_helper::purge_by_event('changesincourse');
-    add_to_log($course->id, "course", ($visible ? 'show' : 'hide'), "edit.php?id=$course->id", $course->id);
+
+    // Update the course object we pass to the event class.
+    $course->visible = $params['visible'];
+    $course->visibleold = $params['visibleold'];
+    $course->timemodified = $params['timemodified'];
+
+    // Trigger a course updated event.
+    $event = \core\event\course_updated::create(array(
+        'objectid' => $course->id,
+        'context' => $coursecontext,
+        'other' => array('shortname' => $course->shortname,
+                         'fullname' => $course->fullname)
+    ));
+    $event->add_record_snapshot('course', $course);
+    $event->set_legacy_logdata(array($course->id, 'course', ($visible ? 'show' : 'hide'), 'edit.php?id=' . $course->id, $course->id));
+    $event->trigger();
 }
 
 if ((!empty($moveup) or !empty($movedown)) && confirm_sesskey()) {
@@ -277,7