diff --git a/admin/auth.php b/admin/auth.php index 93711ee8324..934acd371ef 100644 --- a/admin/auth.php +++ b/admin/auth.php @@ -12,13 +12,13 @@ require_once($CFG->libdir.'/adminlib.php'); require_once($CFG->libdir.'/tablelib.php'); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); $returnurl = new moodle_url('/admin/settings.php', array('section'=>'manageauths')); $PAGE->set_url($returnurl); -$action = optional_param('action', '', PARAM_ACTION); +$action = optional_param('action', '', PARAM_ALPHANUMEXT); $auth = optional_param('auth', '', PARAM_PLUGIN); get_enabled_auth_plugins(true); // fix the list of enabled auths diff --git a/admin/category.php b/admin/category.php index f9cd940e9ff..1d68207221c 100644 --- a/admin/category.php +++ b/admin/category.php @@ -32,7 +32,7 @@ $adminediting = optional_param('adminedit', -1, PARAM_BOOL); /// no guest autologin require_login(0, false); -$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_context(context_system::instance()); $PAGE->set_url('/admin/category.php', array('category' => $category)); $PAGE->set_pagetype('admin-setting-' . $category); $PAGE->set_pagelayout('admin'); diff --git a/admin/editors.php b/admin/editors.php index fbb7be5aac4..1a8f530854a 100644 --- a/admin/editors.php +++ b/admin/editors.php @@ -9,11 +9,11 @@ require_once($CFG->libdir.'/adminlib.php'); require_once($CFG->libdir.'/tablelib.php'); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); $returnurl = "$CFG->wwwroot/$CFG->admin/settings.php?section=manageeditors"; -$action = optional_param('action', '', PARAM_ACTION); +$action = optional_param('action', '', PARAM_ALPHANUMEXT); $editor = optional_param('editor', '', PARAM_PLUGIN); // get currently installed and enabled auth plugins diff --git a/admin/enrol.php b/admin/enrol.php index ab14a23440a..9fc196f54c0 100644 --- a/admin/enrol.php +++ b/admin/enrol.php @@ -26,7 +26,7 @@ require_once('../config.php'); require_once($CFG->libdir.'/adminlib.php'); -$action = required_param('action', PARAM_ACTION); +$action = required_param('action', PARAM_ALPHANUMEXT); $enrol = required_param('enrol', PARAM_PLUGIN); $confirm = optional_param('confirm', 0, PARAM_BOOL); @@ -34,7 +34,7 @@ $PAGE->set_url('/admin/enrol.php'); $PAGE->set_context(context_system::instance()); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); require_sesskey(); $enabled = enrol_get_plugins(true); diff --git a/admin/environment.php b/admin/environment.php index 1fc732ea064..5c74f7f6365 100644 --- a/admin/environment.php +++ b/admin/environment.php @@ -33,7 +33,7 @@ require_once($CFG->libdir.'/environmentlib.php'); require_once($CFG->libdir.'/componentlib.class.php'); // Parameters -$action = optional_param('action', '', PARAM_ACTION); +$action = optional_param('action', '', PARAM_ALPHANUMEXT); $version = optional_param('version', '', PARAM_FILE); // $extraurlparams = array(); diff --git a/admin/filters.php b/admin/filters.php index 0d7faa3c088..5c65c74085c 100644 --- a/admin/filters.php +++ b/admin/filters.php @@ -34,11 +34,11 @@ require_once(dirname(__FILE__) . '/../config.php'); require_once($CFG->libdir . '/adminlib.php'); - $action = optional_param('action', '', PARAM_ACTION); + $action = optional_param('action', '', PARAM_ALPHANUMEXT); $filterpath = optional_param('filterpath', '', PARAM_PATH); require_login(); - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); require_capability('moodle/site:config', $systemcontext); $returnurl = "$CFG->wwwroot/$CFG->admin/filters.php"; @@ -68,7 +68,7 @@ switch ($action) { case 'setstate': - if ($newstate = optional_param('newstate', '', PARAM_INTEGER)) { + if ($newstate = optional_param('newstate', '', PARAM_INT)) { filter_set_global_state($filterpath, $newstate); if ($newstate == TEXTFILTER_DISABLED) { filter_set_applies_to_strings($filterpath, false); diff --git a/admin/handlevirus.php b/admin/handlevirus.php index 9e32cc0b653..d7cf3cd9900 100644 --- a/admin/handlevirus.php +++ b/admin/handlevirus.php @@ -49,7 +49,7 @@ while(!feof($fd)) { $a->date = userdate($log->time); $a->action = $action; - $a->course = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))); + $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id))); $a->user = fullname($user); notify_user($user,$subject,$a); diff --git a/admin/index.php b/admin/index.php index d4a7d4e285b..410cbf6723b 100644 --- a/admin/index.php +++ b/admin/index.php @@ -104,10 +104,6 @@ if (!$version or !$release) { print_error('withoutversion', 'debug'); // without version, stop } -// Turn off xmlstrictheaders during upgrade. -$origxmlstrictheaders = !empty($CFG->xmlstrictheaders); -$CFG->xmlstrictheaders = false; - if (!core_tables_exist()) { $PAGE->set_pagelayout('maintenance'); $PAGE->set_popup_notification_allowed(false); @@ -189,7 +185,7 @@ if (!core_tables_exist()) { // and upgrade if possible. $stradministration = get_string('administration'); -$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_context(context_system::instance()); if (empty($CFG->version)) { print_error('missingconfigversion', 'debug'); @@ -380,13 +376,9 @@ if (during_initial_install()) { upgrade_finished('upgradesettings.php'); } -// Turn xmlstrictheaders back on now. -$CFG->xmlstrictheaders = $origxmlstrictheaders; -unset($origxmlstrictheaders); - // Check for valid admin user - no guest autologin require_login(0, false); -$context = get_context_instance(CONTEXT_SYSTEM); +$context = context_system::instance(); require_capability('moodle/site:config', $context); // check that site is properly customized diff --git a/admin/licenses.php b/admin/licenses.php index dfd843d009d..47d3929201c 100644 --- a/admin/licenses.php +++ b/admin/licenses.php @@ -24,11 +24,11 @@ require_once($CFG->libdir.'/adminlib.php'); require_once($CFG->libdir.'/licenselib.php'); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); $returnurl = "$CFG->wwwroot/$CFG->admin/settings.php?section=managelicenses"; -$action = optional_param('action', '', PARAM_ACTION); +$action = optional_param('action', '', PARAM_ALPHANUMEXT); $license = optional_param('license', '', PARAM_SAFEDIR); //////////////////////////////////////////////////////////////////////////////// diff --git a/admin/message.php b/admin/message.php index 45d9026c14e..88e8f856617 100644 --- a/admin/message.php +++ b/admin/message.php @@ -29,7 +29,7 @@ require_once($CFG->libdir.'/adminlib.php'); admin_externalpage_setup('managemessageoutputs'); // Require site configuration capability -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); // Get the submitted params $disable = optional_param('disable', 0, PARAM_INT); @@ -82,7 +82,7 @@ if ($disable || $enable || $uninstall) { redirect($url); } // Page settings -$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_context(context_system::instance()); // Grab the renderer $renderer = $PAGE->get_renderer('core', 'message'); diff --git a/admin/mnet/access_control.php b/admin/mnet/access_control.php index b9e436f7cc4..0354f150ac6 100644 --- a/admin/mnet/access_control.php +++ b/admin/mnet/access_control.php @@ -22,7 +22,7 @@ if (!extension_loaded('openssl')) { print_error('requiresopenssl', 'mnet'); } -$sitecontext = get_context_instance(CONTEXT_SYSTEM); +$sitecontext = context_system::instance(); $sesskey = sesskey(); $formerror = array(); diff --git a/admin/mnet/delete.php b/admin/mnet/delete.php index e3a7e3f07fb..c078b274c30 100644 --- a/admin/mnet/delete.php +++ b/admin/mnet/delete.php @@ -36,7 +36,7 @@ $hostid = required_param('hostid', PARAM_INT); require_login(); -$context = get_context_instance(CONTEXT_SYSTEM); +$context = context_system::instance(); require_capability('moodle/site:config', $context, $USER->id, true, "nopermissions"); $mnet = get_mnet_environment(); diff --git a/admin/mnet/index.php b/admin/mnet/index.php index 54a0a276a5a..d81e8a92ad6 100644 --- a/admin/mnet/index.php +++ b/admin/mnet/index.php @@ -9,7 +9,7 @@ require_login(); admin_externalpage_setup('net'); - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); require_capability('moodle/site:config', $context, $USER->id, true, "nopermissions"); diff --git a/admin/mnet/peers.php b/admin/mnet/peers.php index e7c1daf821b..40759dbc0ed 100644 --- a/admin/mnet/peers.php +++ b/admin/mnet/peers.php @@ -34,7 +34,7 @@ require_once($CFG->dirroot.'/'.$CFG->admin.'/mnet/peer_forms.php'); require_login(); -$context = get_context_instance(CONTEXT_SYSTEM); +$context = context_system::instance(); require_capability('moodle/site:config', $context, $USER->id, true, 'nopermissions'); /// Initialize variables. diff --git a/admin/mnet/profilefields.php b/admin/mnet/profilefields.php index 23443e90636..5f5fd6b1ec0 100644 --- a/admin/mnet/profilefields.php +++ b/admin/mnet/profilefields.php @@ -34,7 +34,7 @@ $hostid = required_param('hostid', PARAM_INT); $mnet_peer = new mnet_peer(); $mnet_peer->set_id($hostid); -$context = get_context_instance(CONTEXT_SYSTEM); +$context = context_system::instance(); require_capability('moodle/site:config', $context, $USER->id, true, 'nopermissions'); admin_externalpage_setup('mnetpeers'); diff --git a/admin/mnet/services.php b/admin/mnet/services.php index d496f47a6e6..cdc4fe3a5c2 100644 --- a/admin/mnet/services.php +++ b/admin/mnet/services.php @@ -33,7 +33,7 @@ $mnet = get_mnet_environment(); require_login(); admin_externalpage_setup('mnetpeers'); -$context = get_context_instance(CONTEXT_SYSTEM); +$context = context_system::instance(); require_capability('moodle/site:config', $context, $USER->id, true, "nopermissions"); $hostid = required_param('hostid', PARAM_INT); diff --git a/admin/mnet/testclient.php b/admin/mnet/testclient.php index f4d2c96053a..89734e39b14 100644 --- a/admin/mnet/testclient.php +++ b/admin/mnet/testclient.php @@ -24,7 +24,7 @@ if ($CFG->mnet_dispatcher_mode === 'off') { require_login(); admin_externalpage_setup('mnettestclient'); -$context = get_context_instance(CONTEXT_SYSTEM); +$context = context_system::instance(); require_capability('moodle/site:config', $context); error_reporting(DEBUG_ALL); diff --git a/admin/mnet/trustedhosts.php b/admin/mnet/trustedhosts.php index 8f0bef15fdf..290c0ae9212 100644 --- a/admin/mnet/trustedhosts.php +++ b/admin/mnet/trustedhosts.php @@ -8,7 +8,7 @@ require_login(); admin_externalpage_setup('trustedhosts'); - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); require_capability('moodle/site:config', $context, $USER->id, true, "nopermissions"); diff --git a/admin/oacleanup.php b/admin/oacleanup.php index 891a20af947..fe2e444472b 100644 --- a/admin/oacleanup.php +++ b/admin/oacleanup.php @@ -49,7 +49,7 @@ function online_assignment_cleanup($output=false) { /// cycle through each course foreach ($courses as $course) { context_instance_preload($course); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); if (empty($course->fullname)) { $fullname = get_string('course').': '.$course->id; diff --git a/admin/plugins.php b/admin/plugins.php index 943f23a5ea8..8da3fd7a5fe 100644 --- a/admin/plugins.php +++ b/admin/plugins.php @@ -28,7 +28,7 @@ require_once(dirname(dirname(__FILE__)) . '/config.php'); require_once($CFG->libdir . '/adminlib.php'); require_once($CFG->libdir . '/pluginlib.php'); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); admin_externalpage_setup('pluginsoverview'); $fetchremote = optional_param('fetchremote', false, PARAM_BOOL); diff --git a/admin/portfolio.php b/admin/portfolio.php index 791c79f9489..77aa8ea13a7 100644 --- a/admin/portfolio.php +++ b/admin/portfolio.php @@ -5,7 +5,7 @@ require_once($CFG->libdir . '/portfoliolib.php'); require_once($CFG->libdir . '/portfolio/forms.php'); require_once($CFG->libdir . '/adminlib.php'); -$portfolio = optional_param('pf', '', PARAM_FORMAT); +$portfolio = optional_param('pf', '', PARAM_ALPHANUMEXT); $action = optional_param('action', '', PARAM_ALPHA); $sure = optional_param('sure', '', PARAM_ALPHA); @@ -35,7 +35,7 @@ if ($action == 'newon') { admin_externalpage_setup($pagename); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); $baseurl = "$CFG->wwwroot/$CFG->admin/portfolio.php"; $sesskeyurl = "$CFG->wwwroot/$CFG->admin/portfolio.php?sesskey=" . sesskey(); diff --git a/admin/purgecaches.php b/admin/purgecaches.php index f437e8ac8a7..006bb0d9768 100644 --- a/admin/purgecaches.php +++ b/admin/purgecaches.php @@ -31,7 +31,7 @@ $confirm = optional_param('confirm', 0, PARAM_BOOL); admin_externalpage_setup('purgecaches'); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); if ($confirm) { require_sesskey(); diff --git a/admin/qbehaviours.php b/admin/qbehaviours.php index ce81b1369d2..1e72afad1aa 100644 --- a/admin/qbehaviours.php +++ b/admin/qbehaviours.php @@ -33,7 +33,7 @@ require_once($CFG->libdir . '/tablelib.php'); // Check permissions. require_login(); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); require_capability('moodle/question:config', $systemcontext); admin_externalpage_setup('manageqbehaviours'); diff --git a/admin/qtypes.php b/admin/qtypes.php index cbe828fdf10..a37725cd837 100644 --- a/admin/qtypes.php +++ b/admin/qtypes.php @@ -33,7 +33,7 @@ require_once($CFG->libdir . '/tablelib.php'); // Check permissions. require_login(); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); require_capability('moodle/question:config', $systemcontext); $canviewreports = has_capability('report/questioninstances:view', $systemcontext); diff --git a/admin/registration/forms.php b/admin/registration/forms.php index 0126722d9f9..47a450f6126 100644 --- a/admin/registration/forms.php +++ b/admin/registration/forms.php @@ -203,7 +203,7 @@ class site_registration_form extends moodleform { $cleanhuburl = clean_param($huburl, PARAM_ALPHANUMEXT); $sitename = get_config('hub', 'site_name_' . $cleanhuburl); if ($sitename === false) { - $sitename = format_string($site->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID))); + $sitename = format_string($site->fullname, true, array('context' => context_course::instance(SITEID))); } $sitedescription = get_config('hub', 'site_description_' . $cleanhuburl); if ($sitedescription === false) { diff --git a/admin/repository.php b/admin/repository.php index b3494cab5a5..0adfdc6e8e2 100644 --- a/admin/repository.php +++ b/admin/repository.php @@ -19,7 +19,7 @@ require_once($CFG->dirroot . '/repository/lib.php'); require_once($CFG->libdir . '/adminlib.php'); $repository = optional_param('repos', '', PARAM_ALPHANUMEXT); -$action = optional_param('action', '', PARAM_ACTION); +$action = optional_param('action', '', PARAM_ALPHANUMEXT); $sure = optional_param('sure', '', PARAM_ALPHA); $downloadcontents = optional_param('downloadcontents', false, PARAM_BOOL); @@ -47,7 +47,7 @@ if ($action == 'newon') { $visible = false; } -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); admin_externalpage_setup($pagename); $sesskeyurl = $CFG->wwwroot.'/'.$CFG->admin.'/repository.php?sesskey=' . sesskey(); diff --git a/admin/roles/allow.php b/admin/roles/allow.php index 52078e7f181..37ac157b5eb 100644 --- a/admin/roles/allow.php +++ b/admin/roles/allow.php @@ -28,7 +28,7 @@ require_once(dirname(__FILE__) . '/../../config.php'); require_once($CFG->libdir . '/adminlib.php'); require_once($CFG->dirroot . '/' . $CFG->admin . '/roles/lib.php'); -$mode = required_param('mode', PARAM_ACTION); +$mode = required_param('mode', PARAM_ALPHANUMEXT); $classformode = array( 'assign' => 'role_allow_assign_page', 'override' => 'role_allow_override_page', @@ -41,7 +41,7 @@ if (!isset($classformode[$mode])) { $baseurl = new moodle_url('/admin/roles/allow.php', array('mode'=>$mode)); admin_externalpage_setup('defineroles', '', array(), $baseurl); -$syscontext = get_context_instance(CONTEXT_SYSTEM); +$syscontext = context_system::instance(); require_capability('moodle/role:manage', $syscontext); $controller = new $classformode[$mode](); diff --git a/admin/roles/define.php b/admin/roles/define.php index d2f4eb5f501..d889a1065f0 100644 --- a/admin/roles/define.php +++ b/admin/roles/define.php @@ -38,7 +38,7 @@ throw new moodle_exception('invalidaccess'); } if ($action != 'add') { - $roleid = required_param('roleid', PARAM_INTEGER); + $roleid = required_param('roleid', PARAM_INT); } else { $roleid = 0; } @@ -56,7 +56,7 @@ } /// Check access permissions. - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); require_login(); require_capability('moodle/role:manage', $systemcontext); admin_externalpage_setup('defineroles', '', array('action' => $action, 'roleid' => $roleid), $defineurl); diff --git a/admin/roles/lib.php b/admin/roles/lib.php index 212cd211c6f..11341d10cfe 100644 --- a/admin/roles/lib.php +++ b/admin/roles/lib.php @@ -604,7 +604,7 @@ class define_role_table_advanced extends capability_table_with_risks { } // Role name. - $name = optional_param('name', null, PARAM_MULTILANG); + $name = optional_param('name', null, PARAM_TEXT); if (!is_null($name)) { $this->role->name = $name; // Hack: short names of standard roles are equal to archetypes, empty name means localised via lang packs. @@ -1270,7 +1270,7 @@ abstract class role_allow_role_page { */ protected function load_required_roles() { /// Get all roles - $this->roles = role_fix_names(get_all_roles(), get_context_instance(CONTEXT_SYSTEM), ROLENAME_ORIGINAL); + $this->roles = role_fix_names(get_all_roles(), context_system::instance(), ROLENAME_ORIGINAL); } /** diff --git a/admin/roles/manage.php b/admin/roles/manage.php index 85b1c0b240b..745681ee268 100644 --- a/admin/roles/manage.php +++ b/admin/roles/manage.php @@ -47,7 +47,7 @@ $defineurl = $CFG->wwwroot . '/' . $CFG->admin . '/roles/define.php'; /// Check access permissions. - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); require_login(); require_capability('moodle/role:manage', $systemcontext); admin_externalpage_setup('defineroles'); diff --git a/admin/roles/usersroles.php b/admin/roles/usersroles.php index 11b2c28caf9..d9d8cb5e8f7 100644 --- a/admin/roles/usersroles.php +++ b/admin/roles/usersroles.php @@ -36,9 +36,9 @@ $courseid = required_param('courseid', PARAM_INT); $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST); $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); -$usercontext = get_context_instance(CONTEXT_USER, $user->id); -$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$usercontext = context_user::instance($user->id); +$coursecontext = context_course::instance($course->id); +$systemcontext = context_system::instance(); $baseurl = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$userid, 'courseid'=>$courseid)); diff --git a/admin/search.php b/admin/search.php index 40fbeb4b56d..d60f09374d1 100644 --- a/admin/search.php +++ b/admin/search.php @@ -7,7 +7,7 @@ require_once($CFG->libdir.'/adminlib.php'); $query = trim(optional_param('query', '', PARAM_NOTAGS)); // Search string -$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_context(context_system::instance()); admin_externalpage_setup('search', '', array('query' => $query)); // now hidden page diff --git a/admin/settings.php b/admin/settings.php index 3e66f24d48e..c8444c51bf1 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -9,7 +9,7 @@ $adminediting = optional_param('adminedit', -1, PARAM_BOOL); /// no guest autologin require_login(0, false); -$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_context(context_system::instance()); $PAGE->set_url('/admin/settings.php', array('section' => $section)); $PAGE->set_pagetype('admin-setting-' . $section); $PAGE->set_pagelayout('admin'); diff --git a/admin/settings/appearance.php b/admin/settings/appearance.php index b0272b8c97e..9995af38048 100644 --- a/admin/settings/appearance.php +++ b/admin/settings/appearance.php @@ -185,6 +185,7 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page $setting = new admin_setting_configcheckbox('cachejs', new lang_string('cachejs', 'admin'), new lang_string('cachejs_help', 'admin'), 1); $setting->set_updatedcallback('js_reset_all_caches'); $temp->add($setting); + $temp->add(new admin_setting_configcheckbox('modchooserdefault', new lang_string('modchooserdefault', 'admin'), new lang_string('configmodchooserdefault', 'admin'), 1)); $ADMIN->add('appearance', $temp); // link to tag management interface diff --git a/admin/settings/development.php b/admin/settings/development.php index cb77515a84c..4d9cd84ab52 100644 --- a/admin/settings/development.php +++ b/admin/settings/development.php @@ -25,7 +25,6 @@ if ($hassiteconfig) { // speedup for non-admins, add all caps used on this page $temp = new admin_settingpage('debugging', new lang_string('debugging', 'admin')); $temp->add(new admin_setting_special_debug()); $temp->add(new admin_setting_configcheckbox('debugdisplay', new lang_string('debugdisplay', 'admin'), new lang_string('configdebugdisplay', 'admin'), ini_get_bool('display_errors'))); - $temp->add(new admin_setting_configcheckbox('xmlstrictheaders', new lang_string('xmlstrictheaders', 'admin'), new lang_string('configxmlstrictheaders', 'admin'), 0)); $temp->add(new admin_setting_configcheckbox('debugsmtp', new lang_string('debugsmtp', 'admin'), new lang_string('configdebugsmtp', 'admin'), 0)); $temp->add(new admin_setting_configcheckbox('perfdebug', new lang_string('perfdebug', 'admin'), new lang_string('configperfdebug', 'admin'), '7', '15', '7')); $temp->add(new admin_setting_configcheckbox('debugstringids', new lang_string('debugstringids', 'admin'), new lang_string('debugstringids_desc', 'admin'), 0)); diff --git a/admin/settings/frontpage.php b/admin/settings/frontpage.php index fd5fafa6f32..5a060a101bb 100644 --- a/admin/settings/frontpage.php +++ b/admin/settings/frontpage.php @@ -3,7 +3,7 @@ // This file defines everything related to frontpage if (!during_initial_install()) { //do not use during installation - $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID); + $frontpagecontext = context_course::instance(SITEID); if ($hassiteconfig or has_any_capability(array( 'moodle/course:update', diff --git a/admin/settings/plugins.php b/admin/settings/plugins.php index 638aa4009b7..ec274335398 100644 --- a/admin/settings/plugins.php +++ b/admin/settings/plugins.php @@ -264,13 +264,13 @@ if ($hassiteconfig) { 'portfolio_moderate_db_threshold', new lang_string('moderatedbsizethreshold', 'portfolio'), new lang_string('moderatedbsizethresholddesc', 'portfolio'), - 20, PARAM_INTEGER, 3)); + 20, PARAM_INT, 3)); $temp->add(new admin_setting_configtext( 'portfolio_high_db_threshold', new lang_string('highdbsizethreshold', 'portfolio'), new lang_string('highdbsizethresholddesc', 'portfolio'), - 50, PARAM_INTEGER, 3)); + 50, PARAM_INT, 3)); $ADMIN->add('portfoliosettings', $temp); $ADMIN->add('portfoliosettings', new admin_externalpage('portfolionew', new lang_string('addnewportfolio', 'portfolio'), $url, 'moodle/site:config', true), '', $url); diff --git a/admin/settings/top.php b/admin/settings/top.php index 147a4e56edd..cd52953d029 100644 --- a/admin/settings/top.php +++ b/admin/settings/top.php @@ -5,7 +5,7 @@ // since they need to exist *before* settingpages and externalpages // are added to them. -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); $hassiteconfig = has_capability('moodle/site:config', $systemcontext); $ADMIN->add('root', new admin_externalpage('adminnotifications', new lang_string('notifications'), "$CFG->wwwroot/$CFG->admin/index.php")); diff --git a/admin/settings/users.php b/admin/settings/users.php index fa5968c5474..b7f1e257947 100644 --- a/admin/settings/users.php +++ b/admin/settings/users.php @@ -34,7 +34,7 @@ if ($hassiteconfig $temp = new admin_settingpage('userpolicies', new lang_string('userpolicies', 'admin')); if ($ADMIN->fulltree) { if (!during_initial_install()) { - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); $otherroles = array(); $guestroles = array(); diff --git a/admin/timezone.php b/admin/timezone.php index e031be44bbe..8cfefc7b7a4 100644 --- a/admin/timezone.php +++ b/admin/timezone.php @@ -14,7 +14,7 @@ require_login(); - require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); + require_capability('moodle/site:config', context_system::instance()); $strtimezone = get_string("timezone"); $strsavechanges = get_string("savechanges"); diff --git a/admin/tool/bloglevelupgrade/index.php b/admin/tool/bloglevelupgrade/index.php index bd2a5310b37..823f2109194 100644 --- a/admin/tool/bloglevelupgrade/index.php +++ b/admin/tool/bloglevelupgrade/index.php @@ -102,8 +102,8 @@ if ($CFG->bloglevel == BLOG_COURSE_LEVEL || $CFG->bloglevel == BLOG_GROUP_LEVEL) function bloglevelupgrade_entries($blogentries, $forum, $cm, $groupid=-1) { $count = 0; - $forumcontext = get_context_instance(CONTEXT_MODULE, $cm->id); - $sitecontext = get_context_instance(CONTEXT_SYSTEM); + $forumcontext = context_module::instance($cm->id); + $sitecontext = context_system::instance(); foreach ($blogentries as $blogentry) { $discussion = new stdClass(); diff --git a/admin/tool/capability/index.php b/admin/tool/capability/index.php index 7a0f2d64a6e..3f9c58edd0c 100644 --- a/admin/tool/capability/index.php +++ b/admin/tool/capability/index.php @@ -29,12 +29,12 @@ require_once($CFG->libdir.'/adminlib.php'); // Check permissions. require_login(); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); require_capability('moodle/role:manage', $systemcontext); // Get URL parameters. $capability = optional_param('capability', '', PARAM_CAPABILITY); -$roleids = optional_param_array('roles', array('0'), PARAM_INTEGER); +$roleids = optional_param_array('roles', array('0'), PARAM_INT); // Clean the passed in list of role ids. If 'All' selected as an option, or // if none were selected, do all roles. diff --git a/admin/tool/dbtransfer/cli/migrate.php b/admin/tool/dbtransfer/cli/migrate.php new file mode 100644 index 00000000000..0d32e2ae8a5 --- /dev/null +++ b/admin/tool/dbtransfer/cli/migrate.php @@ -0,0 +1,191 @@ +. + +/** + * This script migrates data from current database to another + * + * This script is not intended for beginners! + * Potential problems: + * - su to apache account or sudo before execution + * - already broken DB scheme or invalid data + * + * @package tool_dbtransfer + * @copyright 2012 Petr Skoda {@link http://skodak.org/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +define('CLI_SCRIPT', true); + +require(__DIR__.'/../../../../config.php'); +require_once($CFG->libdir.'/clilib.php'); +require_once(__DIR__.'/../locallib.php'); + +$help = + "Database migration script. + +It is strongly recommended to turn off the web server +or enable CLI maintenance mode before starting the migration. + +Options: +--dbtype=TYPE Database type. +--dblibrary=TYPE Database library. Defaults to 'native'. +--dbhost=HOST Database host. +--dbname=NAME Database name. +--dbuser=USERNAME Database user. +--dbpass=PASSWORD Database password. +--dbport=NUMBER Database port. +--prefix=STRING Table prefix for above database tables. +--dbsocket=PATH Use database sockets. Available for some databases only. +-h, --help Print out this help. + +Example: +\$ sudo -u www-data /usr/bin/php admin/tool/dbtransfer/cli/migrate.php +"; + +// Now get cli options. +list($options, $unrecognized) = cli_get_params( + array( + 'dbtype' => null, + 'dblibrary' => 'native', + 'dbhost' => null, + 'dbname' => null, + 'dbuser' => null, + 'dbpass' => null, + 'dbport' => null, + 'prefix' => null, + 'dbsocket' => null, + 'maintenance' => null, + 'list' => false, + 'help' => false, + ), + array( + 'm' => 'maintenance', + 'l' => 'list', + 'h' => 'help', + ) +); + +if ($options['help']) { + echo $help; + exit(0); +} + +if (empty($CFG->version)) { + cli_error(get_string('missingconfigversion', 'debug')); +} + +echo "\n".get_string('cliheading', 'tool_dbtransfer')."\n\n"; + +$drivers = tool_dbtransfer_get_drivers(); + +if (!isset($options['dbtype'])) { + $choose = array(); + foreach ($drivers as $driver => $name) { + list($dbtype, $dblibrary) = explode('/', $driver); + $choose[$dbtype] = $dbtype; + } + $optionsstr = implode(', ', $choose); + cli_heading(get_string('databasetypehead', 'install')." ($optionsstr)"); + $options['dbtype'] = cli_input(get_string('clitypevalue', 'admin'), '', $choose, true); +} + +$choose = array(); +foreach ($drivers as $driver => $name) { + list($dbtype, $dblibrary) = explode('/', $driver); + if ($dbtype === $options['dbtype']) { + $choose[$dblibrary] = $dblibrary; + } +} +if (!isset($options['dblibrary']) or !isset($choose[$options['dblibrary']])) { + $optionsstr = implode(', ', $choose); + cli_heading('Database library'." ($optionsstr)"); // Note: no need to localise unless we add real PDO drivers. + $options['dblibrary'] = cli_input(get_string('clitypevalue', 'admin'), '', $choose, true); +} + +if (!isset($options['dbhost'])) { + cli_heading(get_string('databasehost', 'install')); + $options['dbhost'] = cli_input(get_string('clitypevalue', 'admin')); +} + +if (!isset($options['dbname'])) { + cli_heading(get_string('databasename', 'install')); + $options['dbname'] = cli_input(get_string('clitypevalue', 'admin')); +} + +if (!isset($options['dbuser'])) { + cli_heading(get_string('databaseuser', 'install')); + $options['dbuser'] = cli_input(get_string('clitypevalue', 'admin')); +} + +if (!isset($options['dbpass'])) { + cli_heading(get_string('databasepass', 'install')); + $options['dbpass'] = cli_input(get_string('clitypevalue', 'admin')); +} + +if (!isset($options['prefix'])) { + cli_heading(get_string('dbprefix', 'install')); + $options['prefix'] = cli_input(get_string('clitypevalue', 'admin')); +} + +if (!isset($options['dbport'])) { + cli_heading(get_string('dbport', 'install')); + $options['dbport'] = cli_input(get_string('clitypevalue', 'admin')); +} + +if ($CFG->ostype !== 'WINDOWS') { + if (!isset($options['dbsocket'])) { + cli_heading(get_string('databasesocket', 'install')); + $options['dbsocket'] = cli_input(get_string('clitypevalue', 'admin')); + } +} + +$a = (object)array('dbtypefrom' => $CFG->dbtype, 'dbtype' => $options['dbtype'], + 'dbname' => $options['dbname'], 'dbhost' => $options['dbhost']); +cli_heading(get_string('transferringdbto', 'tool_dbtransfer', $a)); + +// Try target DB connection. +$problem = ''; + +$targetdb = moodle_database::get_driver_instance($options['dbtype'], $options['dblibrary']); +$dboptions = array(); +if ($options['dbport']) { + $dboptions['dbport'] = $options['dbport']; +} +if ($options['dbsocket']) { + $dboptions['dbsocket'] = $options['dbsocket']; +} +try { + $targetdb->connect($options['dbhost'], $options['dbuser'], $options['dbpass'], $options['dbname'], + $options['prefix'], $dboptions); + if ($targetdb->get_tables()) { + $problem .= get_string('targetdatabasenotempty', 'tool_dbtransfer'); + } +} catch (moodle_exception $e) { + $problem .= $e->debuginfo."\n\n"; + $problem .= get_string('notargetconectexception', 'tool_dbtransfer'); +} + +if ($problem !== '') { + echo $problem."\n\n"; + exit(1); +} + +$feedback = new text_progress_trace(); +tool_dbtransfer_transfer_database($DB, $targetdb, $feedback); +$feedback->finished(); + +cli_heading(get_string('success')); +exit(0); diff --git a/admin/tool/dbtransfer/database_export_form.php b/admin/tool/dbtransfer/database_export_form.php index 72b7c524699..1fb8b9c2ee3 100644 --- a/admin/tool/dbtransfer/database_export_form.php +++ b/admin/tool/dbtransfer/database_export_form.php @@ -17,19 +17,28 @@ /** * Transfer form * - * @package tool - * @subpackage dbtransfer - * @copyright 2008 Petr Skoda + * @package tool_dbtransfer + * @copyright 2008 Petr Skoda {@link http://skodak.org/} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; -require_once $CFG->libdir.'/formslib.php'; +require_once($CFG->libdir.'/formslib.php'); + +/** + * Definition of db export settings form. + * + * @package tool_dbtransfer + * @copyright 2008 Petr Skoda {@link http://skodak.org/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ class database_export_form extends moodleform { - - function definition() { + /** + * Define the export form. + */ + public function definition() { $mform = $this->_form; $mform->addElement('header', 'database', get_string('dbexport', 'tool_dbtransfer')); diff --git a/admin/tool/dbtransfer/database_transfer_form.php b/admin/tool/dbtransfer/database_transfer_form.php index 9b699e911a8..d8a9923a017 100644 --- a/admin/tool/dbtransfer/database_transfer_form.php +++ b/admin/tool/dbtransfer/database_transfer_form.php @@ -17,55 +17,84 @@ /** * Transfer form * - * @package tool - * @subpackage dbtransfer - * @copyright 2008 Petr Skoda + * @package tool_dbtransfer + * @copyright 2008 Petr Skoda {@link http://skodak.org/} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; -require_once $CFG->libdir.'/formslib.php'; +require_once($CFG->libdir.'/formslib.php'); +require_once(__DIR__.'/locallib.php'); + +/** + * Definition of db transfer settings form. + * + * @copyright 2008 Petr Skoda {@link http://skodak.org/} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ class database_transfer_form extends moodleform { - function definition() { + /** + * Define transfer form. + */ + protected function definition() { + global $CFG; + $mform = $this->_form; - $mform->addElement('header', 'database', get_string('dbtransfer', 'tool_dbtransfer')); + $mform->addElement('header', 'database', get_string('targetdatabase', 'tool_dbtransfer')); - $supported = array ( - 'mysqli/native', - 'pgsql/native', - 'mssql/native', - 'oci/native', - 'sqlsrv/native', - ); - $drivers = array(); - foreach($supported as $driver) { - list($dbtype, $dblibrary) = explode('/', $driver); - $targetdb = moodle_database::get_driver_instance($dbtype, $dblibrary); - if ($targetdb->driver_installed() !== true) { - continue; - } - $drivers[$driver] = $driver; - } + $drivers = tool_dbtransfer_get_drivers(); + $drivers = array_reverse($drivers, true); + $drivers[''] = get_string('choosedots'); + $drivers = array_reverse($drivers, true); $mform->addElement('select', 'driver', get_string('dbtype', 'install'), $drivers); - $mform->addElement('text', 'dbhost', get_string('dbhost', 'install')); - $mform->addElement('text', 'dbname', get_string('database', 'install')); - $mform->addElement('text', 'dbuser', get_string('user')); - $mform->addElement('text', 'dbpass', get_string('password')); + $mform->addElement('text', 'dbhost', get_string('databasehost', 'install')); + $mform->addElement('text', 'dbname', get_string('databasename', 'install')); + $mform->addElement('text', 'dbuser', get_string('databaseuser', 'install')); + $mform->addElement('passwordunmask', 'dbpass', get_string('databasepass', 'install')); $mform->addElement('text', 'prefix', get_string('dbprefix', 'install')); $mform->addElement('text', 'dbport', get_string('dbport', 'install')); - $mform->addElement('text', 'dbsocket', get_string('databasesocket', 'install')); + if ($CFG->ostype !== 'WINDOWS') { + $mform->addElement('text', 'dbsocket', get_string('databasesocket', 'install')); + } else { + $mform->addElement('hidden', 'dbsocket'); + } + $mform->addRule('driver', get_string('required'), 'required', null); $mform->addRule('dbhost', get_string('required'), 'required', null); $mform->addRule('dbname', get_string('required'), 'required', null); $mform->addRule('dbuser', get_string('required'), 'required', null); $mform->addRule('dbpass', get_string('required'), 'required', null); - $mform->addRule('prefix', get_string('required'), 'required', null); + if (!isset($drivers['mysqli/native'])) { + $mform->addRule('prefix', get_string('required'), 'required', null); + } + + $mform->addElement('header', 'database', get_string('options', 'tool_dbtransfer')); + + $mform->addElement('advcheckbox', 'enablemaintenance', get_string('enablemaintenance', 'tool_dbtransfer')); + $mform->addHelpButton('enablemaintenance', 'enablemaintenance', 'tool_dbtransfer'); $this->add_action_buttons(false, get_string('transferdata', 'tool_dbtransfer')); } + + /** + * Validate prefix is present for non-mysql drivers. + * @param array $data + * @param array $files + * @return array + */ + public function validation($data, $files) { + $errors = parent::validation($data, $files); + if ($data['driver'] !== 'mysqli/native') { + // This is a bloody hack, let's pretend we do not need to look at db family... + if ($data['prefix'] === '') { + $errors['prefix'] = get_string('required'); + } + } + return $errors; + } } diff --git a/admin/tool/dbtransfer/dbexport.php b/admin/tool/dbtransfer/dbexport.php index 40f35ff0f25..f55b29d0312 100644 --- a/admin/tool/dbtransfer/dbexport.php +++ b/admin/tool/dbtransfer/dbexport.php @@ -17,9 +17,8 @@ /** * Export * - * @package tool - * @subpackage dbtransfer - * @copyright 2008 Petr Skoda + * @package tool_dbtransfer + * @copyright 2008 Petr Skoda {@link http://skodak.org/} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -32,15 +31,15 @@ require_once('database_export_form.php'); require_login(); admin_externalpage_setup('tooldbexport'); -//create form +// Create form. $form = new database_export_form(); if ($data = $form->get_data()) { - dbtransfer_export_xml_database($data->description, $DB); + tool_dbtransfer_export_xml_database($data->description, $DB); die; } echo $OUTPUT->header(); -// TODO: add some more info here +// TODO: add some more info here. $form->display(); echo $OUTPUT->footer(); diff --git a/admin/tool/dbtransfer/index.php b/admin/tool/dbtransfer/index.php index 2b1a2c5cf46..aa8b5b3b581 100644 --- a/admin/tool/dbtransfer/index.php +++ b/admin/tool/dbtransfer/index.php @@ -17,9 +17,8 @@ /** * Transfer tool * - * @package tool - * @subpackage dbtransfer - * @copyright 2008 Petr Skoda + * @package tool_dbtransfer + * @copyright 2008 Petr Skoda {@link http://skodak.org/} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -32,8 +31,9 @@ require_once('database_transfer_form.php'); require_login(); admin_externalpage_setup('tooldbtransfer'); -// Create the form +// Create the form. $form = new database_transfer_form(); +$problem = ''; // If we have valid input. if ($data = $form->get_data()) { @@ -47,33 +47,63 @@ if ($data = $form->get_data()) { if ($data->dbsocket) { $dboptions['dbsocket'] = $data->dbsocket; } - if (!$targetdb->connect($data->dbhost, $data->dbuser, $data->dbpass, $data->dbname, $data->prefix, $dboptions)) { - throw new dbtransfer_exception('notargetconectexception', null, "$CFG->wwwroot/$CFG->admin/tool/dbtransfer/"); - } - if ($targetdb->get_tables()) { - throw new dbtransfer_exception('targetdatabasenotempty', null, "$CFG->wwwroot/$CFG->admin/tool/dbtransfer/"); + try { + $targetdb->connect($data->dbhost, $data->dbuser, $data->dbpass, $data->dbname, $data->prefix, $dboptions); + if ($targetdb->get_tables()) { + $problem .= get_string('targetdatabasenotempty', 'tool_dbtransfer'); + } + } catch (moodle_exception $e) { + $problem .= get_string('notargetconectexception', 'tool_dbtransfer').'
'.$e->debuginfo; } - // Start output. - echo $OUTPUT->header(); - $data->dbtype = $dbtype; - echo $OUTPUT->heading(get_string('transferringdbto', 'tool_dbtransfer', $data)); + if ($problem === '') { + // Scroll down to the bottom when finished. + $PAGE->requires->js_init_code("window.scrollTo(0, 5000000);"); - // Do the transfer. - $feedback = new html_list_progress_trace(); - dbtransfer_transfer_database($DB, $targetdb, $feedback); - $feedback->finished(); + // Enable CLI maintenance mode if requested. + if ($data->enablemaintenance) { + $PAGE->set_pagelayout('maintenance'); + tool_dbtransfer_create_maintenance_file(); + } - // Finish up. - echo $OUTPUT->notification(get_string('success'), 'notifysuccess'); - echo $OUTPUT->continue_button("$CFG->wwwroot/$CFG->admin/"); - echo $OUTPUT->footer(); - die; + // Start output. + echo $OUTPUT->header(); + $data->dbtype = $dbtype; + $data->dbtypefrom = $CFG->dbtype; + echo $OUTPUT->heading(get_string('transferringdbto', 'tool_dbtransfer', $data)); + + // Do the transfer. + $CFG->tool_dbransfer_migration_running = true; + try { + $feedback = new html_list_progress_trace(); + tool_dbtransfer_transfer_database($DB, $targetdb, $feedback); + $feedback->finished(); + } catch (Exception $e) { + if ($data->enablemaintenance) { + tool_dbtransfer_maintenance_callback(); + } + unset($CFG->tool_dbransfer_migration_running); + throw $e; + } + unset($CFG->tool_dbransfer_migration_running); + + // Finish up. + echo $OUTPUT->notification(get_string('success'), 'notifysuccess'); + echo $OUTPUT->continue_button("$CFG->wwwroot/$CFG->admin/"); + echo $OUTPUT->footer(); + die; + } } // Otherwise display the settings form. echo $OUTPUT->header(); echo $OUTPUT->heading(get_string('transferdbtoserver', 'tool_dbtransfer')); -echo '

', get_string('transferdbintro', 'tool_dbtransfer'), "

\n\n"; + +$info = format_text(get_string('transferdbintro', 'tool_dbtransfer'), FORMAT_MARKDOWN); +echo $OUTPUT->box($info); + $form->display(); +if ($problem !== '') { + echo $OUTPUT->box($problem, 'generalbox error'); +} echo $OUTPUT->footer(); diff --git a/admin/tool/dbtransfer/lang/en/tool_dbtransfer.php b/admin/tool/dbtransfer/lang/en/tool_dbtransfer.php index 1279af58eee..a67a3e950f9 100644 --- a/admin/tool/dbtransfer/lang/en/tool_dbtransfer.php +++ b/admin/tool/dbtransfer/lang/en/tool_dbtransfer.php @@ -15,21 +15,29 @@ // along with Moodle. If not, see . /** - * Strings for component 'tool_generator', language 'en', branch 'MOODLE_22_STABLE' + * Strings for component 'tool_generator', language 'en'. * - * @package tool - * @subpackage dbtransfer - * @copyright 2011 Petr Skoda + * @package tool_dbtransfer + * @copyright 2011 Petr Skoda {@link http://skodak.org/} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -$string['dbexport'] = 'Database transfer'; -$string['dbtransfer'] = 'Database export'; +$string['clidriverlist'] = 'Available database drivers for migration'; +$string['cliheading'] = 'Database migration - make sure nobody is accessing the server during migration!'; +$string['climigrationnotice'] = 'Database migration in progress, please wait until the migration completes and server administrator updates configuration and deletes the $CFG->dataroot/climaintenance.html file.'; +$string['convertinglogdisplay'] = 'Converting log display actions'; +$string['dbexport'] = 'Database export'; +$string['dbtransfer'] = 'Database migration'; +$string['enablemaintenance'] = 'Enable maintenance mode'; +$string['enablemaintenance_help'] = 'This option enables maintanance mode during and after the database migration, it prevents access of all users until the migration is completed. Please note that administrator has to manually delete $CFG->dataroot/climaintenance.html file after updating config.php settings to resume normal operation.'; $string['exportdata'] = 'Export data'; $string['notargetconectexception'] = 'Can not connect target database, sorry.'; +$string['options'] = 'Options'; $string['pluginname'] = 'Database transfer'; +$string['targetdatabase'] = 'Target database'; +$string['targetdatabasenotempty'] = 'Target database must not contain any tables with given prefix!'; $string['transferdata'] = 'Transfer data'; -$string['transferdbintro'] = 'This script will transfer the entire contents of this database to another database server.'; +$string['transferdbintro'] = 'This script will transfer the entire contents of this database to another database server. It is often used for migration of data to different database type.'; $string['transferdbtoserver'] = 'Transfer this Moodle database to another server'; -$string['transferringdbto'] = 'Transferring this database to {$a->dbtype} database {$a->dbname} on {$a->dbhost}'; +$string['transferringdbto'] = 'Transferring this {$a->dbtypefrom} database to {$a->dbtype} database "{$a->dbname}" on "{$a->dbhost}"'; diff --git a/admin/tool/dbtransfer/locallib.php b/admin/tool/dbtransfer/locallib.php index f36ceef614a..8b0b0622f54 100644 --- a/admin/tool/dbtransfer/locallib.php +++ b/admin/tool/dbtransfer/locallib.php @@ -17,9 +17,8 @@ /** * Export db content to file. * - * @package tool - * @subpackage dbtransfer - * @copyright 2008 Petr Skoda {@link http://skodak.org} + * @package tool_dbtransfer + * @copyright 2008 Petr Skoda {@link http://skodak.org/} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -44,11 +43,16 @@ TODO: require_once($CFG->libdir.'/adminlib.php'); require_once($CFG->libdir.'/dtllib.php'); - -function dbtransfer_export_xml_database($description, $mdb) { +/** + * Initiate database export. + * @param string $description + * @param moodle_database $mdb + * @return does not return, calls die() + */ +function tool_dbtransfer_export_xml_database($description, $mdb) { @set_time_limit(0); - session_get_instance()->write_close(); // release session + session_get_instance()->write_close(); // Release session. header('Content-Type: application/xhtml+xml; charset=utf-8'); header('Content-Disposition: attachment; filename=database.xml'); @@ -61,16 +65,145 @@ function dbtransfer_export_xml_database($description, $mdb) { $var = new file_xml_database_exporter('php://output', $mdb); $var->export_database($description); - // no more output + // No more output. die; } - -function dbtransfer_transfer_database($sourcedb, $targetdb, $feedback = null) { +/** + * Initiate database transfer. + * @param moodle_database $sourcedb + * @param moodle_database $targetdb + * @param progress_trace $feedback + * @return void + */ +function tool_dbtransfer_transfer_database(moodle_database $sourcedb, moodle_database $targetdb, progress_trace $feedback = null) { @set_time_limit(0); - session_get_instance()->write_close(); // release session + session_get_instance()->write_close(); // Release session. $var = new database_mover($sourcedb, $targetdb, true, $feedback); $var->export_database(null); + + tool_dbtransfer_rebuild_target_log_actions($targetdb, $feedback); +} + +/** + * Very hacky function for rebuilding of log actions in target database. + * @param moodle_database $target + * @param progress_trace $feedback + * @return void + * @throws Exception on conversion error + */ +function tool_dbtransfer_rebuild_target_log_actions(moodle_database $target, progress_trace $feedback = null) { + global $DB, $CFG; + require_once("$CFG->libdir/upgradelib.php"); + + $feedback->output(get_string('convertinglogdisplay', 'tool_dbtransfer')); + + $olddb = $DB; + $DB = $target; + try { + $DB->delete_records('log_display', array('component'=>'moodle')); + log_update_descriptions('moodle'); + $plugintypes = get_plugin_types(); + foreach ($plugintypes as $type => $location) { + $plugs = get_plugin_list($type); + foreach ($plugs as $plug => $fullplug) { + $component = $type.'_'.$plug; + $DB->delete_records('log_display', array('component'=>$component)); + log_update_descriptions($component); + } + } + } catch (Exception $e) { + $DB = $olddb; + throw $e; + } + $DB = $olddb; + $feedback->output(get_string('done', 'core_dbtransfer', null), 1); +} + +/** + * Returns list of fully working database drivers present in system. + * @return array + */ +function tool_dbtransfer_get_drivers() { + global $CFG; + + $files = new RegexIterator(new DirectoryIterator("$CFG->libdir/dml"), '|^.*_moodle_database\.php$|'); + $drivers = array(); + + foreach ($files as $file) { + $matches = null; + preg_match('|^([a-z0-9]+)_([a-z]+)_moodle_database\.php$|', $file->getFilename(), $matches); + if (!$matches) { + continue; + } + $dbtype = $matches[1]; + $dblibrary = $matches[2]; + + if ($dbtype === 'sqlite3') { + // Blacklist unfinished drivers. + continue; + } + + $targetdb = moodle_database::get_driver_instance($dbtype, $dblibrary, false); + if ($targetdb->driver_installed() !== true) { + continue; + } + + $driver = $dbtype.'/'.$dblibrary; + + $drivers[$driver] = $targetdb->get_name(); + }; + + return $drivers; +} + +/** + * Create CLI maintenance file to prevent all access. + */ +function tool_dbtransfer_create_maintenance_file() { + global $CFG; + + register_shutdown_function('tool_dbtransfer_maintenance_callback'); + + $options = new stdClass(); + $options->trusted = false; + $options->noclean = false; + $options->smiley = false; + $options->filter = false; + $options->para = true; + $options->newlines = false; + + $message = format_text(get_string('climigrationnotice', 'tool_dbtransfer'), FORMAT_MARKDOWN, $options); + $message = bootstrap_renderer::early_error_content($message, '', '', array()); + $html = << + +
+$message + +OET; + + file_put_contents("$CFG->dataroot/climaintenance.html", $html); + @chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions); +} + +/** + * This callback is responsible for unsetting maintenance mode + * if the migration is interrupted. + */ +function tool_dbtransfer_maintenance_callback() { + global $CFG; + + if (empty($CFG->tool_dbransfer_migration_running)) { + // Migration was finished properly - keep the maintenance file in place. + return; + } + + if (file_exists("$CFG->dataroot/climaintenance.html")) { + // Failed migration, revert to normal site operation. + unlink("$CFG->dataroot/climaintenance.html"); + error_log('tool_dbtransfer: Interrupted database migration detected, switching off CLI maintenance mode.'); + } } diff --git a/admin/tool/dbtransfer/settings.php b/admin/tool/dbtransfer/settings.php index 13c45b880cc..47175423670 100644 --- a/admin/tool/dbtransfer/settings.php +++ b/admin/tool/dbtransfer/settings.php @@ -15,18 +15,19 @@ // along with Moodle. If not, see . /** - * Link to InnoDB conversion tool + * Add hidden links db transfer tool * - * @package tool - * @subpackage dbtransfer - * @copyright 2011 Petr Skoda {@link http://skodak.org} + * @package tool_dbtransfer + * @copyright 2011 Petr Skoda {@link http://skodak.org/} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; if ($hassiteconfig) { - // DB transfer related pages - $ADMIN->add('experimental', new admin_externalpage('tooldbtransfer', get_string('dbtransfer', 'tool_dbtransfer'), $CFG->wwwroot.'/'.$CFG->admin.'/tool/dbtransfer/index.php', 'moodle/site:config', true)); - $ADMIN->add('experimental', new admin_externalpage('tooldbexport', get_string('dbexport', 'tool_dbtransfer'), $CFG->wwwroot.'/'.$CFG->admin.'/tool/dbtransfer/dbexport.php', 'moodle/site:config', true)); -} \ No newline at end of file + $ADMIN->add('experimental', new admin_externalpage('tooldbtransfer', get_string('dbtransfer', 'tool_dbtransfer'), + $CFG->wwwroot.'/'.$CFG->admin.'/tool/dbtransfer/index.php', 'moodle/site:config', false)); + // DB export/import is not ready yet - keep it hidden for now. + $ADMIN->add('experimental', new admin_externalpage('tooldbexport', get_string('dbexport', 'tool_dbtransfer'), + $CFG->wwwroot.'/'.$CFG->admin.'/tool/dbtransfer/dbexport.php', 'moodle/site:config', true)); +} diff --git a/admin/tool/dbtransfer/version.php b/admin/tool/dbtransfer/version.php index 61aa6ec612c..59bafe585cf 100644 --- a/admin/tool/dbtransfer/version.php +++ b/admin/tool/dbtransfer/version.php @@ -17,14 +17,13 @@ /** * Version details. * - * @package tool - * @subpackage dbtransfer - * @copyright 2008 Petr Skoda + * @package tool_dbtransfer + * @copyright 2008 Petr Skoda {@link http://skodak.org/} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -$plugin->version = 2012061700; // The current plugin version (Date: YYYYMMDDXX) -$plugin->requires = 2012061700; // Requires this Moodle version -$plugin->component = 'tool_dbtransfer'; // Full name of the plugin (used for diagnostics) +$plugin->version = 2012062200; // The current plugin version (Date: YYYYMMDDXX). +$plugin->requires = 2012061700; // Requires this Moodle version. +$plugin->component = 'tool_dbtransfer'; // Full name of the plugin (used for diagnostics). diff --git a/admin/tool/generator/index.php b/admin/tool/generator/index.php index c747e311b99..577fefcf99d 100644 --- a/admin/tool/generator/index.php +++ b/admin/tool/generator/index.php @@ -28,7 +28,7 @@ require_once('locallib.php'); require_login(); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); require_capability('moodle/site:config', $systemcontext); if (!is_siteadmin()) { error('Only for admins'); diff --git a/admin/tool/generator/locallib.php b/admin/tool/generator/locallib.php index 1eceb1aaee4..169f6436319 100644 --- a/admin/tool/generator/locallib.php +++ b/admin/tool/generator/locallib.php @@ -706,7 +706,7 @@ class generator { shuffle($users); $users_to_assign = array_slice($users, 0, $this->get('students_per_course')); - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); foreach ($users_to_assign as $random_user) { role_assign(5, $random_user, $context->id); diff --git a/admin/tool/health/index.php b/admin/tool/health/index.php index cc178309ce7..3966865c242 100644 --- a/admin/tool/health/index.php +++ b/admin/tool/health/index.php @@ -39,7 +39,7 @@ $solution = optional_param('solution', 0, PARAM_PLUGIN); require_login(); - require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); + require_capability('moodle/site:config', context_system::instance()); $site = get_site(); diff --git a/admin/tool/innodb/index.php b/admin/tool/innodb/index.php index 3e57e904fdd..06f4f6a5299 100644 --- a/admin/tool/innodb/index.php +++ b/admin/tool/innodb/index.php @@ -33,7 +33,7 @@ admin_externalpage_setup('toolinnodb'); $confirm = optional_param('confirm', 0, PARAM_BOOL); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); echo $OUTPUT->header(); echo $OUTPUT->heading('Convert all MySQL tables from MYISAM to InnoDB'); diff --git a/admin/tool/qeupgradehelper/convertquiz.php b/admin/tool/qeupgradehelper/convertquiz.php index f4176fc4cee..d12fc992703 100644 --- a/admin/tool/qeupgradehelper/convertquiz.php +++ b/admin/tool/qeupgradehelper/convertquiz.php @@ -33,7 +33,7 @@ $quizid = required_param('quizid', PARAM_INT); $confirmed = optional_param('confirmed', false, PARAM_BOOL); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); tool_qeupgradehelper_require_upgraded(); admin_externalpage_setup('qeupgradehelper', '', array(), diff --git a/admin/tool/qeupgradehelper/cronsetup.php b/admin/tool/qeupgradehelper/cronsetup.php index 58280a95b3f..2523ee5c565 100644 --- a/admin/tool/qeupgradehelper/cronsetup.php +++ b/admin/tool/qeupgradehelper/cronsetup.php @@ -30,7 +30,7 @@ require_once(dirname(__FILE__) . '/cronsetup_form.php'); require_once($CFG->libdir . '/adminlib.php'); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); admin_externalpage_setup('qeupgradehelper', '', array(), tool_qeupgradehelper_url('cronsetup')); diff --git a/admin/tool/qeupgradehelper/extracttestcase.php b/admin/tool/qeupgradehelper/extracttestcase.php index d67fe6599a9..902418f1730 100644 --- a/admin/tool/qeupgradehelper/extracttestcase.php +++ b/admin/tool/qeupgradehelper/extracttestcase.php @@ -37,7 +37,7 @@ require_once($CFG->libdir . '/adminlib.php'); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); admin_externalpage_setup('qeupgradehelper', '', array(), tool_qeupgradehelper_url('extracttestcase')); diff --git a/admin/tool/qeupgradehelper/index.php b/admin/tool/qeupgradehelper/index.php index 2fe264216e7..776645a73ce 100644 --- a/admin/tool/qeupgradehelper/index.php +++ b/admin/tool/qeupgradehelper/index.php @@ -32,7 +32,7 @@ require_once(dirname(__FILE__) . '/locallib.php'); require_once($CFG->libdir . '/adminlib.php'); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); admin_externalpage_setup('qeupgradehelper'); $renderer = $PAGE->get_renderer('tool_qeupgradehelper'); diff --git a/admin/tool/qeupgradehelper/listpreupgrade.php b/admin/tool/qeupgradehelper/listpreupgrade.php index e243dc3797d..ee15a094a80 100644 --- a/admin/tool/qeupgradehelper/listpreupgrade.php +++ b/admin/tool/qeupgradehelper/listpreupgrade.php @@ -30,7 +30,7 @@ require_once(dirname(__FILE__) . '/locallib.php'); require_once($CFG->libdir . '/adminlib.php'); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); tool_qeupgradehelper_require_not_upgraded(); admin_externalpage_setup('qeupgradehelper', '', array(), tool_qeupgradehelper_url('')); diff --git a/admin/tool/qeupgradehelper/listtodo.php b/admin/tool/qeupgradehelper/listtodo.php index 6e923ecd762..83062ea7a52 100644 --- a/admin/tool/qeupgradehelper/listtodo.php +++ b/admin/tool/qeupgradehelper/listtodo.php @@ -30,7 +30,7 @@ require_once(dirname(__FILE__) . '/locallib.php'); require_once($CFG->libdir . '/adminlib.php'); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); tool_qeupgradehelper_require_upgraded(); admin_externalpage_setup('qeupgradehelper', '', array(), diff --git a/admin/tool/qeupgradehelper/listupgraded.php b/admin/tool/qeupgradehelper/listupgraded.php index 8aa3dca78c0..187f75e984d 100644 --- a/admin/tool/qeupgradehelper/listupgraded.php +++ b/admin/tool/qeupgradehelper/listupgraded.php @@ -31,7 +31,7 @@ require_once(dirname(__FILE__) . '/locallib.php'); require_once($CFG->libdir . '/adminlib.php'); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); tool_qeupgradehelper_require_upgraded(); admin_externalpage_setup('qeupgradehelper', '', array(), diff --git a/admin/tool/qeupgradehelper/resetquiz.php b/admin/tool/qeupgradehelper/resetquiz.php index a3bf94a5ba0..1029cb23e24 100644 --- a/admin/tool/qeupgradehelper/resetquiz.php +++ b/admin/tool/qeupgradehelper/resetquiz.php @@ -32,7 +32,7 @@ $quizid = required_param('quizid', PARAM_INT); $confirmed = optional_param('confirmed', false, PARAM_BOOL); require_login(); -require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); +require_capability('moodle/site:config', context_system::instance()); tool_qeupgradehelper_require_upgraded(); admin_externalpage_setup('qeupgradehelper', '', array(), diff --git a/admin/tool/unittest/coveragefile.php b/admin/tool/unittest/coveragefile.php deleted file mode 100644 index d3c8737a4e8..00000000000 --- a/admin/tool/unittest/coveragefile.php +++ /dev/null @@ -1,71 +0,0 @@ -. - -/** - * This script serves files from dataroot/codecoverage - * - * Syntax: coveragefile.php/path/to/file/file.html - * coveragefile.php?file=path/to/file/file.html - * - * @package tool - * @subpackage unittest - * @copyright 2003 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -// disable moodle specific debug messages and any errors in output -define('NO_DEBUG_DISPLAY', true); - -require(dirname(__FILE__) . '/../../../config.php'); -require_once($CFG->libdir . '/filelib.php'); - -// basic security, require login + require site config cap -require_login(); -require_capability('tool/unittest:execute', get_context_instance(CONTEXT_SYSTEM)); - -// get file requested -$relativepath = get_file_argument(); - -// basic check, start by slash -if (!$relativepath) { - print_error('invalidargorconf'); -} else if ($relativepath{0} != '/') { - print_error('pathdoesnotstartslash'); -} - -// determine which disk file is going to be served -// and how it's going to be named -$filepath = $CFG->dataroot . '/codecoverage' . $relativepath; -$filename = basename($filepath); - -// extract relative path components -$args = explode('/', ltrim($relativepath, '/')); - -// only serve from some controlled subdirs -$alloweddirs = array('dbtest', 'unittest'); -if (!isset($args[0]) || !in_array($args[0], $alloweddirs)) { - print_error('invalidarguments'); -} - -// only serve some controlled extensions/mimetypes -if (!file_extension_in_typegroup($filepath, array('web_file', 'web_image'), true)) { - print_error('invalidarguments'); -} - -// arrived here, send the file -session_get_instance()->write_close(); // unlock session during fileserving -send_file($filepath, $filename, 0, false); - diff --git a/admin/tool/unittest/db/install.php b/admin/tool/unittest/db/install.php deleted file mode 100644 index 1923960d282..00000000000 --- a/admin/tool/unittest/db/install.php +++ /dev/null @@ -1,31 +0,0 @@ -. - -/** - * Post installation and migration code. - * - * @package tool - * @subpackage unittest - * @copyright 2011 Petr Skoda {@link http://skodak.org} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die; - -function xmldb_tool_unittest_install() { - global $CFG; - -} diff --git a/admin/tool/unittest/ex_reporter.php b/admin/tool/unittest/ex_reporter.php deleted file mode 100644 index 01476d29329..00000000000 --- a/admin/tool/unittest/ex_reporter.php +++ /dev/null @@ -1,297 +0,0 @@ -. - -/** - * A SimpleTest report format for Moodle. - * - * @package tool - * @subpackage unittest - * @copyright © 2006 The Open University - * @author N.D.Freear@open.ac.uk, T.J.Hunt@open.ac.uk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page -} - -require_once($CFG->libdir . '/simpletestlib/reporter.php'); - -/** - * Extended in-browser test displayer. HtmlReporter generates - * only failure messages and a pass count. ExHtmlReporter also - * generates pass messages and a time-stamp. - * - * @package SimpleTestEx - */ -class ExHtmlReporter extends HtmlReporter { - - // Options set when the class is created. - var $showpasses; - - // Lang strings. Set in the constructor. - var $strrunonlyfolder; - var $strrunonlyfile; - - var $strseparator; - - var $timestart; - - /** - * Constructor. - * - * @param bool $showpasses Whether this reporter should output anything for passes. - */ - function __construct($showpasses) { - parent::__construct('UTF-8'); - $this->showpasses = $showpasses; - - $this->strrunonlyfolder = $this->get_string('runonlyfolder'); - $this->strrunonlyfile = $this->get_string('runonlyfile'); - $this->strseparator = get_separator(); - } - - /** - * Called when a pass needs to be output. - */ - function paintPass($message) { - //(Implicitly call grandparent, as parent not implemented.) - parent::paintPass($message); - if ($this->showpasses) { - $this->_paintPassFail('pass', $message); - } - } - - /** - * Called when a fail needs to be output. - */ - function paintFail($message) { - // Explicitly call grandparent, not parent::paintFail. - SimpleScorer::paintFail($message); - $this->_paintPassFail('fail', $message, debug_backtrace()); - } - - /** - * Called when a skip needs to be output. - */ - function paintSkip($message) { - // Explicitly call grandparent, not parent::paintFail. - SimpleScorer::paintSkip($message); - $this->_paintPassFail('skip', $message); - } - - /** - * Called when an error (uncaught exception or PHP error) needs to be output. - */ - function paintError($message) { - // Explicitly call grandparent, not parent::paintError. - SimpleScorer::paintError($message); - $this->_paintPassFail('exception', $message); - } - - /** - * Called when a caught exception needs to be output. - */ - function paintException($exception) { - // Explicitly call grandparent, not parent::paintException. - SimpleScorer::paintException($exception); - - if (is_a($exception, 'moodle_exception') && - !get_string_manager()->string_exists($exception->errorcode, $exception->module)) { - $exceptionmessage = 'Exception with missing language string {' . - $exception->errorcode . '} from language file {' . $exception->module . '}'; - - if (!empty($exception->a)) { - if (is_string($exception->a)) { - $data = $exception->a; - } else { - $data = array(); - foreach ((array)$exception->a as $name => $value) { - $data[] = $name . ' => [' . $value . ']'; - } - $data = implode(', ', $data); - } - $exceptionmessage .= ' with data {' . $data . '}'; - } - - } else { - $exceptionmessage = $exception->getMessage(); - } - $message = 'Unexpected exception of type [' . get_class($exception) . - '] with message ['. $exceptionmessage . - '] in ['. $exception->getFile() . - ' line ' . $exception->getLine() . ']'; - - $debuginfo = null; - if (!empty($exception->debuginfo)) { - $debuginfo = $exception->debuginfo; - } - - $this->_paintPassFail('exception', $message, $exception->getTrace(), $debuginfo); - } - - /** - * Private method. Used by printPass/Fail/Skip/Error. - */ - function _paintPassFail($passorfail, $message, $stacktrace = null, $debuginfo = null) { - global $CFG, $OUTPUT; - - echo $OUTPUT->box_start($passorfail . ' generalbox '); - - $url = $this->_htmlEntities($this->_stripParameterFromUrl(qualified_me(), 'path')); - echo '', $this->get_string($passorfail), ': '; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - $file = array_shift($breadcrumb); - $pathbits = preg_split('/\/|\\\\/', substr($file, strlen($CFG->dirroot) + 1)); - $file = array_pop($pathbits); - $folder = ''; - foreach ($pathbits as $pathbit) { - $folder .= $pathbit . '/'; - echo "strrunonlyfolder\">$pathbit/"; - } - echo "strrunonlyfile\">$file"; - echo $this->strseparator, implode($this->strseparator, $breadcrumb); - - echo '
', $this->_htmlEntities($message), "\n\n"; - - if (!empty($debuginfo)) { - print_object('Debug info:'); - print_object($debuginfo); - } - - if ($stacktrace) { - $dotsadded = false; - $interestinglines = 0; - $filteredstacktrace = array(); - foreach ($stacktrace as $frame) { - if (empty($frame['file']) || (strpos($frame['file'], 'simpletestlib') === false && - strpos($frame['file'], 'simpletestcoveragelib') === false - && strpos($frame['file'], 'tool/unittest') === false)) { - $filteredstacktrace[] = $frame; - $interestinglines += 1; - $dotsadded = false; - } else if (!$dotsadded) { - $filteredstacktrace[] = array('line' => '...', 'file' => '...'); - $dotsadded = true; - } - } - if ($interestinglines > 1 || ($passorfail == 'exception' && $interestinglines > 0)) { - echo '
' . format_backtrace($filteredstacktrace) . "
\n\n"; - } - } - - echo $OUTPUT->box_end(); - flush(); - } - - /** - * Called when a notice needs to be output. - */ - function paintNotice($message) { - $this->paintMessage($this->_htmlEntities($message)); - } - - /** - * Paints a simple supplementary message. - * @param string $message Text to display. - */ - function paintMessage($message) { - global $OUTPUT; - if ($this->showpasses) { - echo $OUTPUT->box_start(); - echo '', $this->get_string('notice'), ': '; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - echo implode($this->strseparator, $breadcrumb); - echo $this->strseparator, '
', $message, "\n"; - echo $OUTPUT->box_end(); - flush(); - } - } - - /** - * Output anything that should appear above all the test output. - */ - function paintHeader($test_name) { - $this->timestart = time(); - // We do this the moodle way instead. - } - - /** - * Output anything that should appear below all the test output, e.g. summary information. - */ - function paintFooter($test_name) { - $summarydata = new stdClass; - $summarydata->run = $this->getTestCaseProgress(); - $summarydata->total = $this->getTestCaseCount(); - $summarydata->passes = $this->getPassCount(); - $summarydata->fails = $this->getFailCount(); - $summarydata->exceptions = $this->getExceptionCount(); - - if ($summarydata->fails == 0 && $summarydata->exceptions == 0) { - $status = "passed"; - } else { - $status = "failed"; - } - echo '
'; - echo $this->get_string('summary', $summarydata); - echo '
'; - - echo '
', - $this->get_string('runat', userdate($this->timestart)), ' ', - $this->get_string('timetakes', format_time(time() - $this->timestart)), ' ', - $this->get_string('version', SimpleTest::getVersion()), - '
'; - } - - /** - * Strip a specified parameter from the query string of a URL, if present. - * Adds a separator to the end of the URL, so that a new parameter - * can easily be appended. For example (assuming $param = 'frog'): - * - * http://example.com/index.php -> http://example.com/index.php? - * http://example.com/index.php?frog=1 -> http://example.com/index.php? - * http://example.com/index.php?toad=1 -> http://example.com/index.php?toad=1& - * http://example.com/index.php?frog=1&toad=1 -> http://example.com/index.php?toad=1& - * - * @param string $url the URL to modify. - * @param string $param the parameter to strip from the URL, if present. - * - * @return string The modified URL. - */ - function _stripParameterFromUrl($url, $param) { - $url = preg_replace('/(\?|&)' . $param . '=[^&]*&?/', '$1', $url); - if (strpos($url, '?') === false) { - $url = $url . '?'; - } else { - $url = $url . '&'; - } - return $url; - } - - /** - * Look up a lang string in the appropriate file. - */ - function get_string($identifier, $a = NULL) { - return get_string($identifier, 'tool_unittest', $a); - } - - function _htmlEntities($message) { - // Override subclass message that breaks UTF8. - return s($message); - } -} diff --git a/admin/tool/unittest/ex_simple_test.php b/admin/tool/unittest/ex_simple_test.php deleted file mode 100644 index dd6ee8a4391..00000000000 --- a/admin/tool/unittest/ex_simple_test.php +++ /dev/null @@ -1,231 +0,0 @@ -. - -/** - * A SimpleTest GroupTest that automatically finds all the - * test files in a directory tree according to certain rules. - * - * @package tool - * @subpackage unittest - * @copyright © 2006 The Open University - * @author N.D.Freear@open.ac.uk, T.J.Hunt@open.ac.uk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page -} - -require_once($CFG->libdir . '/simpletestlib/test_case.php'); - -/** - * This is a composite test class for finding test cases and - * other RunnableTest classes in a directory tree and combining - * them into a group test. - * @package SimpleTestEx - */ -class AutoGroupTest extends TestSuite { - - var $showsearch; - - function AutoGroupTest($showsearch, $test_name = null) { - $this->TestSuite($test_name); - $this->showsearch = $showsearch; - } - - function run($reporter) { - global $UNITTEST; - - $UNITTEST->running = true; - $return = parent::run($reporter); - unset($UNITTEST->running); - return $return; - } - - function setLabel($test_name) { - //:HACK: there is no GroupTest::setLabel, so access parent::_label. - $this->_label = $test_name; - } - - function addIgnoreFolder($ignorefolder) { - $this->ignorefolders[]=$ignorefolder; - } - - function _recurseFolders($path) { - if ($this->showsearch) { - echo '
  • ' . basename(realpath($path)) . '
      '; - } - - $files = scandir($path); - static $s_count = 0; - - foreach ($files as $file) { - if ($file == '.' || $file == '..') { - continue; - } - $file_path = $path . '/' . $file; - if (is_dir($file_path)) { - if ($file != 'CVS' && $file != '.git' && !in_array($file_path, $this->ignorefolders)) { - $this->_recurseFolders($file_path); - } - } elseif (preg_match('/simpletest(\/|\\\\)test.*\.php$/', $file_path)) { - - $s_count++; - // OK, found: this shows as a 'Notice' for any 'simpletest/test*.php' file. - $this->add(new FindFileNotice($file_path, 'Found unit test file, '. $s_count)); - - // addTestFile: Unfortunately this doesn't return fail/success (bool). - $this->addTestFile($file_path, true); - } - } - - if ($this->showsearch) { - echo '
  • '; - } - return $s_count; - } - - function findTestFiles($dir) { - if ($this->showsearch) { - echo '

    Searching folder: ' . realpath($dir) . '

      '; - } - $path = $dir; - $count = $this->_recurseFolders($path); - if ($count <= 0) { - $this->add(new BadAutoGroupTest($path, 'Search complete. No unit test files found')); - } else { - $this->add(new AutoGroupTestNotice($path, 'Search complete. Total unit test files found: '. $count)); - } - if ($this->showsearch) { - echo '
    '; - } - return $count; - } - - function addTestFile($file, $internalcall = false) { - - if ($this->showsearch) { - if ($internalcall) { - echo '
  • ' . basename($file) . '
  • '; - } else { - echo '

    Adding test file: ' . realpath($file) . '

    '; - } - // Make sure that syntax errors show up suring the search, otherwise you often - // get blank screens because evil people turn down error_reporting elsewhere. - error_reporting(E_ALL); - } - if (!is_file($file) ){ - parent::add(new BadTest($file, 'Not a file or does not exist')); - } - parent::addFile($file); - } -} - - -/* ======================================================================= */ -// get_class_ex: Insert spaces to prettify the class-name. -function get_class_ex($object) { - return preg_replace('/(.?)([A-Z])/', '${1} ${2}', get_class($object)); -} - - -/** - * A failing test base-class for when a test suite has NOT loaded properly. - * See class, simple_test.php: BadGroupTest. - * @package SimpleTestEx - */ -class BadTest { - - var $label; - var $error; - - function BadTest($label, $error) { - $this->label = $label; - $this->error = $error; - } - - function getLabel() { - return $this->label; - } - - function run(&$reporter) { - $reporter->paintGroupStart(basename(__FILE__), $this->getSize()); - $reporter->paintFail(get_class_ex($this) .' [' . $this->getLabel() . - '] with error [' . $this->error . ']'); - $reporter->paintGroupEnd($this->getLabel()); - return $reporter->getStatus(); - } - - /** - * @return int the number of test cases starting. - */ - function getSize() { - return 0; - } -} - -/** - * An informational notice base-class for when a test suite is being processed. - * See class, simple_test.php: BadGroupTest. - * @package SimpleTestEx - */ -class Notice { - - var $label; - var $status; - - function Notice($label, $error) { - $this->label = $label; - $this->status = $error; - } - - function getLabel() { - return $this->label; - } - - function run(&$reporter) { - $reporter->paintGroupStart(basename(__FILE__), $this->getSize()); - $reporter->paintNotice(get_class_ex($this) . - ' ['. $this->getLabel() .'] with status [' . $this->status . ']'); - $reporter->paintGroupEnd($this->getLabel()); - return $reporter->getStatus(); - } - - function getSize() { - return 0; - } -} - -/** - * A failing folder test for when the test-user specifies an invalid directory - * (run.php?folder=woops). - * @package SimpleTestEx - */ -class BadFolderTest extends BadTest { } - -/** - * A failing auto test for when no unit test files are found. - * @package SimpleTestEx - */ -class BadAutoGroupTest extends BadTest { } - -/** - * Auto group test notices - 1. Search complete. 2. A test file has been found. - * @package SimpleTestEx - */ -class AutoGroupTestNotice extends Notice { } - -class FindFileNotice extends Notice { } diff --git a/admin/tool/unittest/index.php b/admin/tool/unittest/index.php deleted file mode 100644 index db0bbc73580..00000000000 --- a/admin/tool/unittest/index.php +++ /dev/null @@ -1,150 +0,0 @@ -. - -/** - * Run the unit tests. - * - * @package tool - * @subpackage unittest - * @copyright © 2006 The Open University - * @author N.D.Freear@open.ac.uk, T.J.Hunt@open.ac.uk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -define('NO_OUTPUT_BUFFERING', true); - -require(dirname(__FILE__) . '/../../../config.php'); -require_once($CFG->libdir.'/adminlib.php'); -require_once('simpletestlib.php'); -require_once('simpletestcoveragelib.php'); -require_once('ex_simple_test.php'); -require_once('ex_reporter.php'); - -// page parameters -$path = optional_param('path', null, PARAM_PATH); -$showpasses = optional_param('showpasses', false, PARAM_BOOL); -$codecoverage = optional_param('codecoverage', false, PARAM_BOOL); -$showsearch = optional_param('showsearch', false, PARAM_BOOL); - -admin_externalpage_setup('toolsimpletest', '', array('showpasses'=>$showpasses, 'showsearch'=>$showsearch)); - -raise_memory_limit(MEMORY_EXTRA); - -$unittest = true; - -global $UNITTEST; -$UNITTEST = new stdClass(); - -// This limit is the time allowed per individual test function. Please do not -// increase this value. If you get a PHP time limit when running unit tests, -// find the unit test which is running slowly, and either make it faster, -// split it into multiple tests, or call set_time_limit within that test. -define('TIME_ALLOWED_PER_UNIT_TEST', 60); - -// Print the header. -$strtitle = get_string('unittests', 'tool_unittest'); - -if (!is_null($path)) { - //trim so user doesn't get an error if they include a space on the end of the path (ie by pasting path) - $path = trim($path); - - // Turn off xmlstrictheaders during the unit test run. - $origxmlstrictheaders = !empty($CFG->xmlstrictheaders); - $CFG->xmlstrictheaders = false; - echo $OUTPUT->header(); - $CFG->xmlstrictheaders = $origxmlstrictheaders; - unset($origxmlstrictheaders); - - // Create the group of tests. - $test = new autogroup_test_coverage($showsearch, true, $codecoverage, 'Moodle Unit Tests Code Coverage Report', 'unittest'); - - // OU specific. We use the _nonproject folder for stuff we want to - // keep in CVS, but which is not really relevant. It does no harm - // to leave this here. - $test->addIgnoreFolder($CFG->dirroot . '/_nonproject'); - - // Make the reporter, which is what displays the results. - $reporter = new ExHtmlReporter($showpasses); - - if ($showsearch) { - echo $OUTPUT->heading('Searching for test cases'); - } - flush(); - - // Work out what to test. - if (substr($path, 0, 1) == '/') { - $path = substr($path, 1); - } - $path = $CFG->dirroot . '/' . $path; - if (substr($path, -1) == '/') { - $path = substr($path, 0, -1); - } - $displaypath = substr($path, strlen($CFG->dirroot) + 1); - $ok = true; - if (is_file($path)) { - $test->addTestFile($path); - } else if (is_dir($path)){ - $test->findTestFiles($path); - } else { - echo $OUTPUT->box(get_string('pathdoesnotexist', 'tool_unittest', $path), 'errorbox'); - $ok = false; - } - - // If we have something to test, do it. - if ($ok) { - if ($path == $CFG->dirroot) { - $title = get_string('moodleunittests', 'tool_unittest', get_string('all', 'tool_unittest')); - } else { - $title = get_string('moodleunittests', 'tool_unittest', $displaypath); - } - echo $OUTPUT->heading($title); - $test->run($reporter); - } - - $formheader = get_string('retest', 'tool_unittest'); -} else { - $displaypath = ''; - echo $OUTPUT->header(); - $formheader = get_string('rununittests', 'tool_unittest'); -} -// Print the form for adjusting options. -echo $OUTPUT->box_start('generalbox boxwidthwide boxaligncenter'); -echo $OUTPUT->heading($formheader); -echo '
    '; -echo '
    '; -echo '

    '.html_writer::checkbox('showpasses', 1, $showpasses, get_string('showpasses', 'tool_unittest')).'

    '; -echo '

    '.html_writer::checkbox('showsearch', 1, $showsearch, get_string('showsearch', 'tool_unittest')).'

    '; -if (moodle_coverage_recorder::can_run_codecoverage()) { - echo '

    '.html_writer::checkbox('codecoverage', 1, $codecoverage, get_string('codecoverageanalysis', 'tool_unittest')).'

    '; -} else { - echo '

    '; print_string('codecoveragedisabled', 'tool_unittest'); echo '

    '; -} -echo '

    '; - echo ' '; - echo ''; -echo '

    '; -echo ''; -echo '
    '; -echo '
    '; -echo $OUTPUT->box_end(); - -// Print link to latest code coverage for this report type -if (is_null($path) || !$codecoverage) { - moodle_coverage_reporter::print_link_to_latest('unittest'); -} - -// Footer. -echo $OUTPUT->footer(); diff --git a/admin/tool/unittest/lang/en/tool_unittest.php b/admin/tool/unittest/lang/en/tool_unittest.php deleted file mode 100644 index ce4bb3679c1..00000000000 --- a/admin/tool/unittest/lang/en/tool_unittest.php +++ /dev/null @@ -1,86 +0,0 @@ -. - -/** - * Strings for component 'tool_unittest', language 'en', branch 'MOODLE_22_STABLE' - * - * This file contains strings that were previously located in lang/en/simpletest.php - * - * @package tool - * @subpackage unittest - * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -$string['addconfigprefix'] = 'Add prefix to config file'; -$string['all'] = 'ALL'; -$string['codecoverageanalysis'] = 'Perform code coverage analysis.'; -$string['codecoveragecompletereport'] = '(view code coverage complete report)'; -$string['codecoveragedisabled'] = 'Cannot enable code coverage in this server (missing xdebug extension).'; -$string['codecoveragelatestdetails'] = '(on {$a->date}, with {$a->files} files, {$a->percentage} covered)'; -$string['codecoveragelatestreport'] = 'view latest code coverage complete report'; -$string['confignonwritable'] = 'The file config.php is not writeable by the web server. Either change its permissions, or edit it with the appropriate user account, and add the following line before the closing php tag:
    -$CFG->unittestprefix = \'tst_\' // Change tst_ to a prefix of your choice, different from $CFG->prefix'; -$string['coveredlines'] = 'Covered lines'; -$string['coveredpercentage'] = 'Overall code coverage'; -$string['dbtest'] = 'Functional DB tests'; -$string['deletingnoninsertedrecord'] = 'Trying to delete a record that was not inserted by these unit tests (id {$a->id} in table {$a->table}).'; -$string['deletingnoninsertedrecords'] = 'Trying to delete records that were not inserted by these unit tests (from table {$a->table}).'; -$string['droptesttables'] = 'Drop test tables'; -$string['exception'] = 'Exception'; -$string['executablelines'] = 'Executable lines'; -$string['fail'] = 'Fail'; -$string['ignorefile'] = 'Ignore tests in the file'; -$string['ignorethisfile'] = 'Re-run the tests ignoring this test file.'; -$string['installtesttables'] = 'Install test tables'; -$string['moodleunittests'] = 'Moodle unit tests: {$a}'; -$string['notice'] = 'Notice'; -$string['onlytest'] = 'Only run tests in'; -$string['othertestpages'] = 'Other test pages'; -$string['pass'] = 'Pass'; -$string['pathdoesnotexist'] = 'The path \'{$a}\' does not exist.'; -$string['pluginname'] = 'Unit tests'; -$string['prefix'] = 'Unit test tables prefix'; -$string['prefixnotset'] = 'The unit test database table prefix is not configured. Fill and submit this form to add it to config.php.'; -$string['reinstalltesttables'] = 'Reinstall test tables'; -$string['retest'] = 'Re-run the tests'; -$string['retestonlythisfile'] = 'Re-run only this test file.'; -$string['runall'] = 'Run the tests from all the test files.'; -$string['runat'] = 'Run at {$a}.'; -$string['runonlyfile'] = 'Run only the tests in this file'; -$string['runonlyfolder'] = 'Run only the tests in this folder'; -$string['runtests'] = 'Run tests'; -$string['rununittests'] = 'Run the unit tests'; -$string['showpasses'] = 'Show passes as well as fails.'; -$string['showsearch'] = 'Show the search for test files.'; -$string['skip'] = 'Skip'; -$string['stacktrace'] = 'Stack trace:'; -$string['summary'] = '{$a->run}/{$a->total} test cases complete: {$a->passes} passes, {$a->fails} fails and {$a->exceptions} exceptions.'; -$string['tablesnotsetup'] = 'Unit test tables are not yet built. Do you want to build them now?.'; -$string['testdboperations'] = 'Test database operations'; -$string['testtablescsvfileunwritable'] = 'The test tables CSV file is not writable ({$a->filename})'; -$string['testtablesneedupgrade'] = 'The test DB tables need to be upgraded. Do you wish to proceed with the upgrade now?'; -$string['testtablesok'] = 'The test DB tables were successfully installed.'; -$string['thorough'] = 'Run a thorough test (may be slow).'; -$string['timetakes'] = 'Time taken: {$a}.'; -$string['totallines'] = 'Total lines'; -$string['uncaughtexception'] = 'Uncaught exception [{$a->getMessage()}] in [{$a->getFile()}:{$a->getLine()}] TESTS ABORTED.'; -$string['uncoveredlines'] = 'Uncovered lines'; -$string['unittest:execute'] = 'Execute unit tests'; -$string['unittestprefixsetting'] = 'Unit test prefix: {$a->unittestprefix} (Edit config.php to modify this).'; -$string['unittests'] = 'Unit tests'; -$string['updatingnoninsertedrecord'] = 'Trying to update a record that was not inserted by these unit tests (id {$a->id} in table {$a->table}).'; -$string['version'] = 'Using SimpleTest version {$a}.'; diff --git a/admin/tool/unittest/settings.php b/admin/tool/unittest/settings.php deleted file mode 100644 index ee3406a7e87..00000000000 --- a/admin/tool/unittest/settings.php +++ /dev/null @@ -1,29 +0,0 @@ -. - -/** - * Unittest settings - * - * @package tool - * @subpackage unittest - * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - - -defined('MOODLE_INTERNAL') || die; - -$ADMIN->add('development', new admin_externalpage('toolsimpletest', get_string('pluginname', 'tool_unittest'), "$CFG->wwwroot/$CFG->admin/tool/unittest/index.php", 'tool/unittest:execute', true)); diff --git a/admin/tool/unittest/simpletestcoveragelib.php b/admin/tool/unittest/simpletestcoveragelib.php deleted file mode 100644 index 306bf2941e7..00000000000 --- a/admin/tool/unittest/simpletestcoveragelib.php +++ /dev/null @@ -1,606 +0,0 @@ -. - -/** - * Extend simpletest to support code coverage analysis - * - * This package contains a collection of classes that, extending standard simpletest - * ones, provide code coverage analysis to already existing tests. Also there are some - * utility functions designed to make the coverage control easier. - * - * @package tool - * @subpackage unittest - * @copyright 2003 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die(); - -/** - * Includes - */ -require_once($CFG->libdir.'/tablelib.php'); - -require_once($CFG->dirroot . '/' . $CFG->admin . '/tool/unittest/simpletestlib.php'); -require_once($CFG->dirroot . '/' . $CFG->admin . '/tool/unittest/ex_simple_test.php'); - -require_once($CFG->libdir . '/spikephpcoverage/src/CoverageRecorder.php'); -require_once($CFG->libdir . '/spikephpcoverage/src/reporter/HtmlCoverageReporter.php'); - -/** - * AutoGroupTest class extension supporting code coverage - * - * This class extends AutoGroupTest to add the funcitionalities - * necessary to run code coverage, allowing its activation and - * specifying included / excluded files to be analysed - * - * @package moodlecore - * @subpackage simpletestcoverage - * @copyright 2003 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class autogroup_test_coverage extends AutoGroupTest { - - private $performcoverage; // boolean - private $coveragename; // title of the coverage report - private $coveragedir; // dir, relative to dataroot/coverage where the report will be saved - private $includecoverage; // paths to be analysed by the coverage report - private $excludecoverage; // paths to be excluded from the coverage report - - function __construct($showsearch, $test_name = null, - $performcoverage = false, $coveragename = 'Code Coverage Report', - $coveragedir = 'report') { - parent::__construct($showsearch, $test_name); - $this->performcoverage = $performcoverage; - $this->coveragename = $coveragename; - $this->coveragedir = $coveragedir; - $this->includecoverage = array(); - $this->excludecoverage = array(); - } - - public function addTestFile($file, $internalcall = false) { - global $CFG; - - if ($this->performcoverage) { - $refinfo = moodle_reflect_file($file); - require_once($file); - if ($refinfo->classes) { - foreach ($refinfo->classes as $class) { - $reflection = new ReflectionClass($class); - if ($staticprops = $reflection->getStaticProperties()) { - if (isset($staticprops['includecoverage']) && is_array($staticprops['includecoverage'])) { - foreach ($staticprops['includecoverage'] as $toinclude) { - $this->add_coverage_include_path($toinclude); - } - } - if (isset($staticprops['excludecoverage']) && is_array($staticprops['excludecoverage'])) { - foreach ($staticprops['excludecoverage'] as $toexclude) { - $this->add_coverage_exclude_path($toexclude); - } - } - } - } - // Automatically add the test dir itself, so nothing will be covered there - $this->add_coverage_exclude_path(dirname($file)); - } - } - parent::addTestFile($file, $internalcall); - } - - public function add_coverage_include_path($path) { - global $CFG; - - $path = $CFG->dirroot . '/' . $path; // Convert to full path - if (!in_array($path, $this->includecoverage)) { - array_push($this->includecoverage, $path); - } - } - - public function add_coverage_exclude_path($path) { - global $CFG; - - $path = $CFG->dirroot . '/' . $path; // Convert to full path - if (!in_array($path, $this->excludecoverage)) { - array_push($this->excludecoverage, $path); - } - } - - /** - * Run the autogroup_test_coverage using one internally defined code coverage reporter - * automatically generating the coverage report. Only supports one instrumentation - * to be executed and reported. - */ - public function run($simpletestreporter) { - global $CFG; - - if (moodle_coverage_recorder::can_run_codecoverage() && $this->performcoverage) { - // Testing with coverage - $covreporter = new moodle_coverage_reporter($this->coveragename, $this->coveragedir); - $covrecorder = new moodle_coverage_recorder($covreporter); - $covrecorder->setIncludePaths($this->includecoverage); - $covrecorder->setExcludePaths($this->excludecoverage); - $covrecorder->start_instrumentation(); - parent::run($simpletestreporter); - $covrecorder->stop_instrumentation(); - set_time_limit(60*10); // it may take a long time to generate the report - $covrecorder->generate_report(); - moodle_coverage_reporter::print_summary_info(basename($this->coveragedir)); - } else { - // Testing without coverage - parent::run($simpletestreporter); - } - } - - /** - * Run the autogroup_test_coverage tests using one externally defined code coverage reporter - * allowing further process of coverage data once tests are over. Supports multiple - * instrumentations (code coverage gathering sessions) to be executed. - */ - public function run_with_external_coverage($simpletestreporter, $covrecorder) { - - if (moodle_coverage_recorder::can_run_codecoverage() && $this->performcoverage) { - $covrecorder->setIncludePaths($this->includecoverage); - $covrecorder->setExcludePaths($this->excludecoverage); - $covrecorder->start_instrumentation(); - parent::run($simpletestreporter); - $covrecorder->stop_instrumentation(); - } else { - // Testing without coverage - parent::run($simpletestreporter); - } - } -} - -/** - * CoverageRecorder class extension supporting multiple - * coverage instrumentations to be accumulated - * - * This class extends CoverageRecorder class in order to - * support multimple xdebug code coverage sessions to be - * executed and get acummulated info about all them in order - * to produce one unique report (default CoverageRecorder - * resets info on each instrumentation (coverage session) - * - * @package moodlecore - * @subpackage simpletestcoverage - * @copyright 2003 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class moodle_coverage_recorder extends CoverageRecorder { - - public function __construct($reporter='new moodle_coverage_reporter()') { - parent::__construct(array(), array(), $reporter); - } - - /** - * Stop gathering coverage data, saving it for later reporting - */ - public function stop_instrumentation() { - if(extension_loaded("xdebug")) { - $lastcoveragedata = xdebug_get_code_coverage(); // Get last instrumentation coverage data - xdebug_stop_code_coverage(); // Stop code coverage - $this->coverageData = self::merge_coverage_data($this->coverageData, $lastcoveragedata); // Append lastcoveragedata - $this->logger->debug("[moodle_coverage_recorder::stopInstrumentation()] Code coverage: " . print_r($this->coverageData, true), - __FILE__, __LINE__); - return true; - } else { - $this->logger->critical("[moodle_coverage_recorder::stopInstrumentation()] Xdebug not loaded.", __FILE__, __LINE__); - } - return false; - } - - /** - * Start gathering coverage data - */ - public function start_instrumentation() { - $this->startInstrumentation(); /// Simple lowercase wrap over Spike function - } - - /** - * Generate the code coverage report - */ - public function generate_report() { - $this->generateReport(); /// Simple lowercase wrap over Spike function - } - - /** - * Determines if the server is able to run code coverage analysis - * - * @return bool - */ - static public function can_run_codecoverage() { - // Only req is xdebug loaded. PEAR XML is already in place and available - if(!extension_loaded("xdebug")) { - return false; - } - return true; - } - - /** - * Merge two collections of complete code coverage data - */ - protected static function merge_coverage_data($cov1, $cov2) { - - $result = array(); - - // protection against empty coverage collections - if (!is_array($cov1)) { - $cov1 = array(); - } - if (!is_array($cov2)) { - $cov2 = array(); - } - - // Get all the files used in both coverage datas - $files = array_unique(array_merge(array_keys($cov1), array_keys($cov2))); - - // Iterate, getting results - foreach($files as $file) { - // If file exists in both coverages, let's merge their lines - if (array_key_exists($file, $cov1) && array_key_exists($file, $cov2)) { - $result[$file] = self::merge_lines_coverage_data($cov1[$file], $cov2[$file]); - // Only one of the coverages has the file - } else if (array_key_exists($file, $cov1)) { - $result[$file] = $cov1[$file]; - } else { - $result[$file] = $cov2[$file]; - } - } - return $result; - } - - /** - * Merge two collections of lines of code coverage data belonging to the same file - * - * Merge algorithm obtained from Phing: http://phing.info - */ - protected static function merge_lines_coverage_data($lines1, $lines2) { - - $result = array(); - - reset($lines1); - reset($lines2); - - while (current($lines1) && current($lines2)) { - $linenr1 = key($lines1); - $linenr2 = key($lines2); - - if ($linenr1 < $linenr2) { - $result[$linenr1] = current($lines1); - next($lines1); - } else if ($linenr2 < $linenr1) { - $result[$linenr2] = current($lines2); - next($lines2); - } else { - if (current($lines1) < 0) { - $result[$linenr2] = current($lines2); - } else if (current($lines2) < 0) { - $result[$linenr2] = current($lines1); - } else { - $result[$linenr2] = current($lines1) + current($lines2); - } - next($lines1); - next($lines2); - } - } - - while (current($lines1)) { - $result[key($lines1)] = current($lines1); - next($lines1); - } - - while (current($lines2)) { - $result[key($lines2)] = current($lines2); - next($lines2); - } - - return $result; - } -} - -/** - * HtmlCoverageReporter class extension supporting Moodle customizations - * - * This class extends the HtmlCoverageReporter class in order to - * implement Moodle look and feel, inline reporting after executing - * unit tests, proper linking and other tweaks here and there. - * - * @package moodlecore - * @subpackage simpletestcoverage - * @copyright 2003 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class moodle_coverage_reporter extends HtmlCoverageReporter { - - public function __construct($heading='Coverage Report', $dir='report') { - global $CFG; - parent::__construct($heading, '', $CFG->dataroot . '/codecoverage/' . $dir); - } - - /** - * Writes one row in the index.html table to display filename - * and coverage recording. - * - * Overrided to transform names and links to shorter format - * - * @param $fileLink link to html details file. - * @param $realFile path to real PHP file. - * @param $fileCoverage Coverage recording for that file. - * @return string HTML code for a single row. - * @access protected - */ - protected function writeIndexFileTableRow($fileLink, $realFile, $fileCoverage) { - - global $CFG; - - $fileLink = str_replace($CFG->dirroot, '', $fileLink); - $realFile = str_replace($CFG->dirroot, '', $realFile); - - return parent::writeIndexFileTableRow($fileLink, $realFile, $fileCoverage);; - } - - /** - * Mark a source code file based on the coverage data gathered - * - * Overrided to transform names and links to shorter format - * - * @param $phpFile Name of the actual source file - * @param $fileLink Link to the html mark-up file for the $phpFile - * @param &$coverageLines Coverage recording for $phpFile - * @return boolean FALSE on failure - * @access protected - */ - protected function markFile($phpFile, $fileLink, &$coverageLines) { - global $CFG; - - $fileLink = str_replace($CFG->dirroot, '', $fileLink); - - return parent::markFile($phpFile, $fileLink, $coverageLines); - } - - - /** - * Update the grand totals - * - * Overrided to avoid the call to recordFileCoverageInfo() - * because it has been already executed by writeIndexFile() and - * cause files to be duplicated in the fileCoverage property - */ - protected function updateGrandTotals(&$coverageCounts) { - $this->grandTotalLines += $coverageCounts['total']; - $this->grandTotalCoveredLines += $coverageCounts['covered']; - $this->grandTotalUncoveredLines += $coverageCounts['uncovered']; - } - - /** - * Generate the static report - * - * Overrided to generate the serialised object to be displayed inline - * with the test results. - * - * @param &$data Reference to Coverage Data - */ - public function generateReport(&$data) { - parent::generateReport($data); - - // head data - $data = new stdClass(); - $data->time = time(); - $data->title = $this->heading; - $data->output = $this->outputDir; - - // summary data - $data->totalfiles = $this->grandTotalFiles; - $data->totalln = $this->grandTotalLines; - $data->totalcoveredln = $this->grandTotalCoveredLines; - $data->totaluncoveredln = $this->grandTotalUncoveredLines; - $data->totalpercentage = $this->getGrandCodeCoveragePercentage(); - - // file details data - $data->coveragedetails = $this->fileCoverage; - - // save serialised object - file_put_contents($data->output . '/codecoverage.ser', serialize($data)); - } - - /** - * Return the html contents for the summary for the last execution of the - * given test type - * - * @param string $type of the test to return last execution summary (dbtest|unittest) - * @return string html contents of the summary - */ - static public function get_summary_info($type) { - global $CFG, $OUTPUT; - - $serfilepath = $CFG->dataroot . '/codecoverage/' . $type . '/codecoverage.ser'; - if (file_exists($serfilepath) && is_readable($serfilepath)) { - if ($data = unserialize(file_get_contents($serfilepath))) { - // return one table with all the totals (we avoid individual file results here) - $result = ''; - $table = new html_table(); - $table->align = array('right', 'left'); - $table->tablealign = 'center'; - $table->attributes['class'] = 'codecoveragetable'; - $table->id = 'codecoveragetable_' . $type; - $table->rowclasses = array('label', 'value'); - $table->data = array( - array(get_string('date') , userdate($data->time)), - array(get_string('files') , format_float($data->totalfiles, 0)), - array(get_string('totallines', 'tool_unittest') , format_float($data->totalln, 0)), - array(get_string('executablelines', 'tool_unittest') , format_float($data->totalcoveredln + $data->totaluncoveredln, 0)), - array(get_string('coveredlines', 'tool_unittest') , format_float($data->totalcoveredln, 0)), - array(get_string('uncoveredlines', 'tool_unittest') , format_float($data->totaluncoveredln, 0)), - array(get_string('coveredpercentage', 'tool_unittest'), format_float($data->totalpercentage, 2) . '%') - ); - - $url = $CFG->wwwroot . '/'.$CFG->admin.'/tool/unittest/coveragefile.php/' . $type . '/index.html'; - $result .= $OUTPUT->heading($data->title, 3, 'main codecoverageheading'); - $result .= $OUTPUT->heading('' . get_string('codecoveragecompletereport', 'tool_unittest') . '', 4, 'main codecoveragelink'); - $result .= html_writer::table($table); - - return $OUTPUT->box($result, 'generalbox boxwidthwide boxaligncenter codecoveragebox', '', true); - } - } - return false; - } - - /** - * Print the html contents for the summary for the last execution of the - * given test type - * - * @param string $type of the test to return last execution summary (dbtest|unittest) - * @return string html contents of the summary - */ - static public function print_summary_info($type) { - echo self::get_summary_info($type); - } - - /** - * Return the html code needed to browse latest code coverage complete report of the - * given test type - * - * @param string $type of the test to return last execution summary (dbtest|unittest) - * @return string html contents of the summary - */ - static public function get_link_to_latest($type) { - global $CFG, $OUTPUT; - - $serfilepath = $CFG->dataroot . '/codecoverage/' . $type . '/codecoverage.ser'; - if (file_exists($serfilepath) && is_readable($serfilepath)) { - if ($data = unserialize(file_get_contents($serfilepath))) { - $info = new stdClass(); - $info->date = userdate($data->time); - $info->files = format_float($data->totalfiles, 0); - $info->percentage = format_float($data->totalpercentage, 2) . '%'; - - $strlatestreport = get_string('codecoveragelatestreport', 'tool_unittest'); - $strlatestdetails = get_string('codecoveragelatestdetails', 'tool_unittest', $info); - - // return one link to latest complete report - $result = ''; - $url = $CFG->wwwroot . '/'.$CFG->admin.'/tool/unittest/coveragefile.php/' . $type . '/index.html'; - $result .= $OUTPUT->heading('' . $strlatestreport . '', 3, 'main codecoveragelink'); - $result .= $OUTPUT->heading($strlatestdetails, 4, 'main codecoveragedetails'); - return $OUTPUT->box($result, 'generalbox boxwidthwide boxaligncenter codecoveragebox', '', true); - } - } - return false; - } - - /** - * Print the html code needed to browse latest code coverage complete report of the - * given test type - * - * @param string $type of the test to return last execution summary (dbtest|unittest) - * @return string html contents of the summary - */ - static public function print_link_to_latest($type) { - echo self::get_link_to_latest($type); - } -} - - -/** - * Return information about classes and functions - * - * This function will parse any PHP file, extracting information about the - * classes and functions defined within it, providing "File Reflection" as - * PHP standard reflection classes don't support that. - * - * The idea and the code has been obtained from the Zend Framework Reflection API - * http://framework.zend.com/manual/en/zend.reflection.reference.html - * - * Usage: $ref_file = moodle_reflect_file($file); - * - * @param string $file full path to the php file to introspect - * @return object object with both 'classes' and 'functions' properties - */ -function moodle_reflect_file($file) { - - $contents = file_get_contents($file); - $tokens = token_get_all($contents); - - $functionTrapped = false; - $classTrapped = false; - $openBraces = 0; - - $classes = array(); - $functions = array(); - - foreach ($tokens as $token) { - /* - * Tokens are characters representing symbols or arrays - * representing strings. The keys/values in the arrays are - * - * - 0 => token id, - * - 1 => string, - * - 2 => line number - * - * Token ID's are explained here: - * http://www.php.net/manual/en/tokens.php. - */ - - if (is_array($token)) { - $type = $token[0]; - $value = $token[1]; - $lineNum = $token[2]; - } else { - // It's a symbol - // Maintain the count of open braces - if ($token == '{') { - $openBraces++; - } else if ($token == '}') { - $openBraces--; - } - - continue; - } - - switch ($type) { - // Name of something - case T_STRING: - if ($functionTrapped) { - $functions[] = $value; - $functionTrapped = false; - } elseif ($classTrapped) { - $classes[] = $value; - $classTrapped = false; - } - continue; - - // Functions - case T_FUNCTION: - if ($openBraces == 0) { - $functionTrapped = true; - } - break; - - // Classes - case T_CLASS: - $classTrapped = true; - break; - - // Default case: do nothing - default: - break; - } - } - - return (object)array('classes' => $classes, 'functions' => $functions); -} diff --git a/admin/tool/unittest/simpletestlib.php b/admin/tool/unittest/simpletestlib.php deleted file mode 100644 index e60faf73ac5..00000000000 --- a/admin/tool/unittest/simpletestlib.php +++ /dev/null @@ -1,1371 +0,0 @@ -. - -/** - * Utility functions to make unit testing easier. - * - * These functions, particularly the the database ones, are quick and - * dirty methods for getting things done in test cases. None of these - * methods should be used outside test code. - * - * Major Contirbutors - * - T.J.Hunt@open.ac.uk - * - * @package tool - * @subpackage unittest - * @copyright © 2006 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -defined('MOODLE_INTERNAL') || die(); - -/** - * Includes - */ -require_once($CFG->libdir . '/simpletestlib/simpletest.php'); -require_once($CFG->libdir . '/simpletestlib/unit_tester.php'); -require_once($CFG->libdir . '/simpletestlib/expectation.php'); -require_once($CFG->libdir . '/simpletestlib/reporter.php'); -require_once($CFG->libdir . '/simpletestlib/web_tester.php'); -require_once($CFG->libdir . '/simpletestlib/mock_objects.php'); - -/** - * Recursively visit all the files in the source tree. Calls the callback - * function with the pathname of each file found. - * - * @param $path the folder to start searching from. - * @param $callback the function to call with the name of each file found. - * @param $fileregexp a regexp used to filter the search (optional). - * @param $exclude If true, pathnames that match the regexp will be ingored. If false, - * only files that match the regexp will be included. (default false). - * @param array $ignorefolders will not go into any of these folders (optional). - */ -function recurseFolders($path, $callback, $fileregexp = '/.*/', $exclude = false, $ignorefolders = array()) { - $files = scandir($path); - - foreach ($files as $file) { - $filepath = $path .'/'. $file; - if (strpos($file, '.') === 0) { - /// Don't check hidden files. - continue; - } else if (is_dir($filepath)) { - if (!in_array($filepath, $ignorefolders)) { - recurseFolders($filepath, $callback, $fileregexp, $exclude, $ignorefolders); - } - } else if ($exclude xor preg_match($fileregexp, $filepath)) { - call_user_func($callback, $filepath); - } - } -} - -/** - * An expectation for comparing strings ignoring whitespace. - * - * @package moodlecore - * @subpackage simpletestex - * @copyright © 2006 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class IgnoreWhitespaceExpectation extends SimpleExpectation { - var $expect; - - function __construct($content, $message = '%s') { - parent::__construct($message); - $this->expect=$this->normalise($content); - } - - function test($ip) { - return $this->normalise($ip)==$this->expect; - } - - function normalise($text) { - return preg_replace('/\s+/m',' ',trim($text)); - } - - function testMessage($ip) { - return "Input string [$ip] doesn't match the required value."; - } -} - -/** - * An Expectation that two arrays contain the same list of values. - * - * @package moodlecore - * @subpackage simpletestex - * @copyright © 2006 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class ArraysHaveSameValuesExpectation extends SimpleExpectation { - var $expect; - - function __construct($expected, $message = '%s') { - parent::__construct($message); - if (!is_array($expected)) { - trigger_error('Attempt to create an ArraysHaveSameValuesExpectation ' . - 'with an expected value that is not an array.'); - } - $this->expect = $this->normalise($expected); - } - - function test($actual) { - return $this->normalise($actual) == $this->expect; - } - - function normalise($array) { - sort($array); - return $array; - } - - function testMessage($actual) { - return 'Array [' . implode(', ', $actual) . - '] does not contain the expected list of values [' . implode(', ', $this->expect) . '].'; - } -} - - -/** - * An Expectation that compares to objects, and ensures that for every field in the - * expected object, there is a key of the same name in the actual object, with - * the same value. (The actual object may have other fields to, but we ignore them.) - * - * @package moodlecore - * @subpackage simpletestex - * @copyright © 2006 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class CheckSpecifiedFieldsExpectation extends SimpleExpectation { - var $expect; - - function __construct($expected, $message = '%s') { - parent::__construct($message); - if (!is_object($expected)) { - trigger_error('Attempt to create a CheckSpecifiedFieldsExpectation ' . - 'with an expected value that is not an object.'); - } - $this->expect = $expected; - } - - function test($actual) { - foreach ($this->expect as $key => $value) { - if (isset($value) && isset($actual->$key) && $actual->$key == $value) { - // OK - } else if (is_null($value) && is_null($actual->$key)) { - // OK - } else { - return false; - } - } - return true; - } - - function testMessage($actual) { - $mismatches = array(); - foreach ($this->expect as $key => $value) { - if (isset($value) && isset($actual->$key) && $actual->$key == $value) { - // OK - } else if (is_null($value) && is_null($actual->$key)) { - // OK - } else if (!isset($actual->$key)) { - $mismatches[] = $key . ' (expected [' . $value . '] but was missing.'; - } else { - $mismatches[] = $key . ' (expected [' . $value . '] got [' . $actual->$key . '].'; - } - } - return 'Actual object does not have all the same fields with the same values as the expected object (' . - implode(', ', $mismatches) . ').'; - } -} - -abstract class XMLStructureExpectation extends SimpleExpectation { - /** - * Parse a string as XML and return a DOMDocument; - * @param $html - * @return unknown_type - */ - protected function load_xml($html) { - $prevsetting = libxml_use_internal_errors(true); - $parser = new DOMDocument(); - if (!$parser->loadXML('' . $html . '')) { - $parser = new DOMDocument(); - } - libxml_clear_errors(); - libxml_use_internal_errors($prevsetting); - return $parser; - } - - function testMessage($html) { - $parsererrors = $this->load_xml($html); - if (is_array($parsererrors)) { - foreach ($parsererrors as $key => $message) { - $parsererrors[$key] = $message->message; - } - return 'Could not parse XML [' . $html . '] errors were [' . - implode('], [', $parsererrors) . ']'; - } - return $this->customMessage($html); - } -} -/** - * An Expectation that looks to see whether some HMTL contains a tag with a certain attribute. - * - * @copyright 2009 Tim Hunt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class ContainsTagWithAttribute extends XMLStructureExpectation { - protected $tag; - protected $attribute; - protected $value; - - function __construct($tag, $attribute, $value, $message = '%s') { - parent::__construct($message); - $this->tag = $tag; - $this->attribute = $attribute; - $this->value = $value; - } - - function test($html) { - $parser = $this->load_xml($html); - if (is_array($parser)) { - return false; - } - $list = $parser->getElementsByTagName($this->tag); - - foreach ($list as $node) { - if ($node->attributes->getNamedItem($this->attribute)->nodeValue === (string) $this->value) { - return true; - } - } - return false; - } - - function customMessage($html) { - return 'Content [' . $html . '] does not contain the tag [' . - $this->tag . '] with attribute [' . $this->attribute . '="' . $this->value . '"].'; - } -} - -/** - * An Expectation that looks to see whether some HMTL contains a tag with an array of attributes. - * All attributes must be present and their values must match the expected values. - * A third parameter can be used to specify attribute=>value pairs which must not be present in a positive match. - * - * @copyright 2009 Nicolas Connault - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class ContainsTagWithAttributes extends XMLStructureExpectation { - /** - * @var string $tag The name of the Tag to search - */ - protected $tag; - /** - * @var array $expectedvalues An associative array of parameters, all of which must be matched - */ - protected $expectedvalues = array(); - /** - * @var array $forbiddenvalues An associative array of parameters, none of which must be matched - */ - protected $forbiddenvalues = array(); - /** - * @var string $failurereason The reason why the test failed: nomatch or forbiddenmatch - */ - protected $failurereason = 'nomatch'; - - function __construct($tag, $expectedvalues, $forbiddenvalues=array(), $message = '%s') { - parent::__construct($message); - $this->tag = $tag; - $this->expectedvalues = $expectedvalues; - $this->forbiddenvalues = $forbiddenvalues; - } - - function test($html) { - $parser = $this->load_xml($html); - if (is_array($parser)) { - return false; - } - - $list = $parser->getElementsByTagName($this->tag); - $foundamatch = false; - - // Iterating through inputs - foreach ($list as $node) { - if (empty($node->attributes) || !is_a($node->attributes, 'DOMNamedNodeMap')) { - continue; - } - - // For the current expected attribute under consideration, check that values match - $allattributesmatch = true; - - foreach ($this->expectedvalues as $expectedattribute => $expectedvalue) { - if ($node->getAttribute($expectedattribute) === '' && $expectedvalue !== '') { - $this->failurereason = 'nomatch'; - continue 2; // Skip this tag, it doesn't have all the expected attributes - } - if ($node->getAttribute($expectedattribute) !== (string) $expectedvalue) { - $allattributesmatch = false; - $this->failurereason = 'nomatch'; - } - } - - if ($allattributesmatch) { - $foundamatch = true; - - // Now make sure this node doesn't have any of the forbidden attributes either - $nodeattrlist = $node->attributes; - - foreach ($nodeattrlist as $domattrname => $domattr) { - if (array_key_exists($domattrname, $this->forbiddenvalues) && $node->getAttribute($domattrname) === (string) $this->forbiddenvalues[$domattrname]) { - $this->failurereason = "forbiddenmatch:$domattrname:" . $node->getAttribute($domattrname); - $foundamatch = false; - } - } - } - } - - return $foundamatch; - } - - function customMessage($html) { - $output = 'Content [' . $html . '] '; - - if (preg_match('/forbiddenmatch:(.*):(.*)/', $this->failurereason, $matches)) { - $output .= "contains the tag $this->tag with the forbidden attribute=>value pair: [$matches[1]=>$matches[2]]"; - } else if ($this->failurereason == 'nomatch') { - $output .= 'does not contain the tag [' . $this->tag . '] with attributes ['; - foreach ($this->expectedvalues as $var => $val) { - $output .= "$var=\"$val\" "; - } - $output = rtrim($output); - $output .= '].'; - } - - return $output; - } -} - -/** - * An Expectation that looks to see whether some HMTL contains a tag with an array of attributes. - * All attributes must be present and their values must match the expected values. - * A third parameter can be used to specify attribute=>value pairs which must not be present in a positive match. - * - * @copyright 2010 The Open University - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class ContainsSelectExpectation extends XMLStructureExpectation { - /** - * @var string $tag The name of the Tag to search - */ - protected $name; - /** - * @var array $expectedvalues An associative array of parameters, all of which must be matched - */ - protected $choices; - /** - * @var array $forbiddenvalues An associative array of parameters, none of which must be matched - */ - protected $selected; - /** - * @var string $failurereason The reason why the test failed: nomatch or forbiddenmatch - */ - protected $enabled; - - function __construct($name, $choices, $selected = null, $enabled = null, $message = '%s') { - parent::__construct($message); - $this->name = $name; - $this->choices = $choices; - $this->selected = $selected; - $this->enabled = $enabled; - } - - function test($html) { - $parser = $this->load_xml($html); - if (is_array($parser)) { - return false; - } - - $list = $parser->getElementsByTagName('select'); - - // Iterating through inputs - foreach ($list as $node) { - if (empty($node->attributes) || !is_a($node->attributes, 'DOMNamedNodeMap')) { - continue; - } - - if ($node->getAttribute('name') != $this->name) { - continue; - } - - if ($this->enabled === true && $node->getAttribute('disabled')) { - continue; - } else if ($this->enabled === false && $node->getAttribute('disabled') != 'disabled') { - continue; - } - - $options = $node->getElementsByTagName('option'); - reset($this->choices); - foreach ($options as $option) { - if ($option->getAttribute('value') != key($this->choices)) { - continue 2; - } - if ($option->firstChild->wholeText != current($this->choices)) { - continue 2; - } - if ($option->getAttribute('value') === $this->selected && - !$option->hasAttribute('selected')) { - continue 2; - } - next($this->choices); - } - if (current($this->choices) !== false) { - // The HTML did not contain all the choices. - return false; - } - return true; - } - return false; - } - - function customMessage($html) { - if ($this->enabled === true) { - $state = 'an enabled'; - } else if ($this->enabled === false) { - $state = 'a disabled'; - } else { - $state = 'a'; - } - $output = 'Content [' . $html . '] does not contain ' . $state . - ' "; $buttons .= ""; - if (has_capability('enrol/authorize:uploadcsv', get_context_instance(CONTEXT_USER, $USER->id))) { + if (has_capability('enrol/authorize:uploadcsv', context_user::instance($USER->id))) { $buttons .= "
    "; } @@ -275,7 +275,7 @@ function authorize_print_order($orderid) print_error('nousers', '', "$CFG->wwwroot/enrol/authorize/index.php"); } - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); if ($USER->id != $order->userid) { // Current user viewing someone else's order require_capability('enrol/authorize:managepayments', $coursecontext); } @@ -288,7 +288,7 @@ function authorize_print_order($orderid) if (empty($do)) { if (empty($statusandactions->actions)) { - if ((AN_METHOD_ECHECK == $order->paymentmethod) && has_capability('enrol/authorize:uploadcsv', get_context_instance(CONTEXT_USER, $USER->id))) { + if ((AN_METHOD_ECHECK == $order->paymentmethod) && has_capability('enrol/authorize:uploadcsv', context_user::instance($USER->id))) { $buttons .= "
    "; } } @@ -574,7 +574,7 @@ function authorize_get_status_action($order) $ret = new stdClass(); $ret->actions = array(); - $canmanage = has_capability('enrol/authorize:managepayments', get_context_instance(CONTEXT_COURSE, $order->courseid)); + $canmanage = has_capability('enrol/authorize:managepayments', context_course::instance($order->courseid)); if (floatval($order->transid) == 0) { // test transaction or new order if ($order->timecreated < $newordertime) { diff --git a/enrol/authorize/uploadcsv.php b/enrol/authorize/uploadcsv.php index 95c940bb9e0..d21cfb9a5d1 100644 --- a/enrol/authorize/uploadcsv.php +++ b/enrol/authorize/uploadcsv.php @@ -33,7 +33,7 @@ require_once('import_form.php'); /// Require capabilities require_login(); -require_capability('enrol/authorize:uploadcsv', get_context_instance(CONTEXT_SYSTEM)); +require_capability('enrol/authorize:uploadcsv', context_system::instance()); /// Print header $struploadcsv = get_string('uploadcsv', 'enrol_authorize'); @@ -202,7 +202,7 @@ function authorize_process_csv($filename) { $ignoredlines .= $transid . ": Could not find this course: " . $order->courseid . "\n"; continue; } - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id, IGNORE_MISSING); if (!$coursecontext) { $ignored++; $ignoredlines .= $transid . ": Could not find course context: " . $order->courseid . "\n"; @@ -248,7 +248,7 @@ function authorize_process_csv($filename) { $eventdata->name = 'authorize_enrolment'; $eventdata->userfrom = $admin; $eventdata->userto = $admin; - $eventdata->subject = format_string($SITE->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID))).': Authorize.net CSV ERROR LOG'; + $eventdata->subject = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID))).': Authorize.net CSV ERROR LOG'; $eventdata->fullmessage = $ignoredlines; $eventdata->fullmessageformat = FORMAT_PLAIN; $eventdata->fullmessagehtml = ''; diff --git a/enrol/bulkchange.php b/enrol/bulkchange.php index d033a56ed67..11c0324b3ab 100644 --- a/enrol/bulkchange.php +++ b/enrol/bulkchange.php @@ -32,11 +32,11 @@ require_once("$CFG->dirroot/group/lib.php"); $id = required_param('id', PARAM_INT); // course id $bulkuserop = required_param('bulkuserop', PARAM_ALPHANUMEXT); $userids = required_param_array('bulkuser', PARAM_INT); -$action = optional_param('action', '', PARAM_ACTION); +$action = optional_param('action', '', PARAM_ALPHANUMEXT); $filter = optional_param('ifilter', 0, PARAM_INT); $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); if ($course->id == SITEID) { redirect(new moodle_url('/')); diff --git a/enrol/category/locallib.php b/enrol/category/locallib.php index 6a7671b7dbd..b44f9d8323b 100644 --- a/enrol/category/locallib.php +++ b/enrol/category/locallib.php @@ -48,7 +48,7 @@ class enrol_category_handler { // make sure the role is to be actually synchronised // please note we are ignoring overrides of the synchronised capability (for performance reasons in full sync) - $syscontext = get_context_instance(CONTEXT_SYSTEM); + $syscontext = context_system::instance(); if (!$DB->record_exists('role_capabilities', array('contextid'=>$syscontext->id, 'roleid'=>$ra->roleid, 'capability'=>'enrol/category:synchronised', 'permission'=>CAP_ALLOW))) { return true; } @@ -98,7 +98,7 @@ class enrol_category_handler { } // now this is going to be a bit slow, take all enrolments in child courses and verify each separately - $syscontext = get_context_instance(CONTEXT_SYSTEM); + $syscontext = context_system::instance(); if (!$roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext)) { return true; } @@ -117,7 +117,7 @@ class enrol_category_handler { $params['userid'] = $ra->userid; foreach ($rs as $instance) { - $coursecontext = get_context_instance(CONTEXT_COURSE, $instance->courseid); + $coursecontext = context_course::instance($instance->courseid); $contextids = get_parent_contexts($coursecontext); array_pop($contextids); // remove system context, we are interested in categories only @@ -152,7 +152,7 @@ function enrol_category_sync_course($course) { $plugin = enrol_get_plugin('category'); - $syscontext = get_context_instance(CONTEXT_SYSTEM); + $syscontext = context_system::instance(); $roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext); if (!$roles) { @@ -166,7 +166,7 @@ function enrol_category_sync_course($course) { } // first find out if any parent category context contains interesting role assignments - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $contextids = get_parent_contexts($coursecontext); array_pop($contextids); // remove system context, we are interested in categories only @@ -246,7 +246,7 @@ function enrol_category_sync_full() { $plugin = enrol_get_plugin('category'); - $syscontext = get_context_instance(CONTEXT_SYSTEM); + $syscontext = context_system::instance(); // any interesting roles worth synchronising? if (!$roles = get_roles_with_capability('enrol/category:synchronised', CAP_ALLOW, $syscontext)) { diff --git a/enrol/cohort/addinstance.php b/enrol/cohort/addinstance.php index bafb7167016..ebb06fca87f 100644 --- a/enrol/cohort/addinstance.php +++ b/enrol/cohort/addinstance.php @@ -31,7 +31,7 @@ require_once("$CFG->dirroot/enrol/cohort/locallib.php"); $id = required_param('id', PARAM_INT); // course id $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login($course); require_capability('moodle/course:enrolconfig', $context); diff --git a/enrol/cohort/addinstance_form.php b/enrol/cohort/addinstance_form.php index 7e157559fb3..e9015a2883c 100644 --- a/enrol/cohort/addinstance_form.php +++ b/enrol/cohort/addinstance_form.php @@ -34,7 +34,7 @@ class enrol_cohort_addinstance_form extends moodleform { $mform = $this->_form; $course = $this->_customdata; - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $enrol = enrol_get_plugin('cohort'); diff --git a/enrol/cohort/ajax.php b/enrol/cohort/ajax.php index e65d1ed8456..b09fd4dd64d 100644 --- a/enrol/cohort/ajax.php +++ b/enrol/cohort/ajax.php @@ -35,12 +35,12 @@ require_once($CFG->dirroot.'/group/lib.php'); // Must have the sesskey $id = required_param('id', PARAM_INT); // course id -$action = required_param('action', PARAM_ACTION); +$action = required_param('action', PARAM_ALPHANUMEXT); $PAGE->set_url(new moodle_url('/enrol/cohort/ajax.php', array('id'=>$id, 'action'=>$action))); $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); if ($course->id == SITEID) { throw new moodle_exception('invalidcourse'); diff --git a/enrol/cohort/lib.php b/enrol/cohort/lib.php index 20098671f71..9f986f9e238 100644 --- a/enrol/cohort/lib.php +++ b/enrol/cohort/lib.php @@ -47,7 +47,7 @@ class enrol_cohort_plugin extends enrol_plugin { } else if (empty($instance->name)) { $enrol = $this->get_name(); if ($role = $DB->get_record('role', array('id'=>$instance->roleid))) { - $role = role_get_name($role, get_context_instance(CONTEXT_COURSE, $instance->courseid)); + $role = role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING)); return get_string('pluginname', 'enrol_'.$enrol) . ' (' . format_string($DB->get_field('cohort', 'name', array('id'=>$instance->customint1))) . ' - ' . $role .')'; } else { return get_string('pluginname', 'enrol_'.$enrol) . ' (' . format_string($DB->get_field('cohort', 'name', array('id'=>$instance->customint1))) . ')'; @@ -81,7 +81,7 @@ class enrol_cohort_plugin extends enrol_plugin { protected function can_add_new_instances($courseid) { global $DB; - $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid); + $coursecontext = context_course::instance($courseid); if (!has_capability('moodle/course:enrolconfig', $coursecontext) or !has_capability('enrol/cohort:config', $coursecontext)) { return false; } diff --git a/enrol/cohort/settings.php b/enrol/cohort/settings.php index 8bfc71c5894..db9702a7eed 100644 --- a/enrol/cohort/settings.php +++ b/enrol/cohort/settings.php @@ -33,7 +33,7 @@ if ($ADMIN->fulltree) { //--- enrol instance defaults ---------------------------------------------------------------------------- if (!during_initial_install()) { - $options = get_default_enrol_roles(get_context_instance(CONTEXT_SYSTEM)); + $options = get_default_enrol_roles(context_system::instance()); $student = get_archetype_roles('student'); $student = reset($student); $settings->add(new admin_setting_configselect('enrol_cohort/roleid', diff --git a/enrol/database/lib.php b/enrol/database/lib.php index 1755a89df19..e53600b15fb 100644 --- a/enrol/database/lib.php +++ b/enrol/database/lib.php @@ -214,7 +214,7 @@ class enrol_database_plugin extends enrol_plugin { $this->enrol_user($instance, $user->id, $roleid, 0, 0, ENROL_USER_ACTIVE); } - if (!$context = get_context_instance(CONTEXT_COURSE, $instance->courseid)) { + if (!$context = context_course::instance($instance->courseid, IGNORE_MISSING)) { //weird continue; } @@ -247,7 +247,7 @@ class enrol_database_plugin extends enrol_plugin { continue; } - if (!$context = get_context_instance(CONTEXT_COURSE, $instance->courseid)) { + if (!$context = context_course::instance($instance->courseid, IGNORE_MISSING)) { //weird continue; } @@ -416,7 +416,7 @@ class enrol_database_plugin extends enrol_plugin { if (!$instance = $DB->get_record('enrol', array('id'=>$course->enrolid))) { continue; //weird } - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); // get current list of enrolled users with their roles $current_roles = array(); diff --git a/enrol/database/settings.php b/enrol/database/settings.php index 369bd3952ea..3b45e8dc9d1 100644 --- a/enrol/database/settings.php +++ b/enrol/database/settings.php @@ -81,7 +81,7 @@ if ($ADMIN->fulltree) { $settings->add(new admin_setting_configtext('enrol_database/remoterolefield', get_string('remoterolefield', 'enrol_database'), get_string('remoterolefield_desc', 'enrol_database'), '')); if (!during_initial_install()) { - $options = get_default_enrol_roles(get_context_instance(CONTEXT_SYSTEM)); + $options = get_default_enrol_roles(context_system::instance()); $student = get_archetype_roles('student'); $student = reset($student); $settings->add(new admin_setting_configselect('enrol_database/defaultrole', get_string('defaultrole', 'enrol_database'), get_string('defaultrole_desc', 'enrol_database'), $student->id, $options)); diff --git a/enrol/externallib.php b/enrol/externallib.php index 147383c9808..cb3c7854ced 100644 --- a/enrol/externallib.php +++ b/enrol/externallib.php @@ -73,7 +73,7 @@ class core_enrol_external extends external_api { $result = array(); foreach ($courses as $course) { - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id, IGNORE_MISSING); try { self::validate_context($context); } catch (Exception $e) { @@ -195,7 +195,7 @@ class core_enrol_external extends external_api { } $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); - $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid); + $coursecontext = context_course::instance($courseid, IGNORE_MISSING); if ($courseid == SITEID) { $context = get_system_context(); } else { @@ -257,13 +257,13 @@ class core_enrol_external extends external_api { return new external_multiple_structure( new external_single_structure( array( - 'id' => new external_value(PARAM_NUMBER, 'ID of the user'), + 'id' => new external_value(PARAM_INT, 'ID of the user'), 'username' => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL), 'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL), 'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL), 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'), 'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL), - 'address' => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL), + 'address' => new external_value(PARAM_TEXT, 'Postal address', VALUE_OPTIONAL), 'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL), 'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL), 'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL), @@ -531,9 +531,9 @@ class moodle_enrol_external extends external_api { 'onlyactive'=>$onlyactive) ); - $coursecontext = get_context_instance(CONTEXT_COURSE, $params['courseid']); + $coursecontext = context_course::instance($params['courseid'], IGNORE_MISSING); if ($courseid == SITEID) { - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); } else { $context = $coursecontext; } diff --git a/enrol/flatfile/lib.php b/enrol/flatfile/lib.php index 73762e29acd..3c839d0854c 100644 --- a/enrol/flatfile/lib.php +++ b/enrol/flatfile/lib.php @@ -229,7 +229,7 @@ class enrol_flatfile_plugin extends enrol_plugin { unset($elog); // Create/resurrect a context object - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); if ($action == 'add') { $instance = $DB->get_record('enrol', diff --git a/enrol/guest/addinstance.php b/enrol/guest/addinstance.php index 156e4e70a76..ce196320ae8 100644 --- a/enrol/guest/addinstance.php +++ b/enrol/guest/addinstance.php @@ -28,7 +28,7 @@ require('../../config.php'); $id = required_param('id', PARAM_INT); // course id $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login($course); require_capability('moodle/course:enrolconfig', $context); diff --git a/enrol/guest/lib.php b/enrol/guest/lib.php index cdeab859a75..02aec702549 100644 --- a/enrol/guest/lib.php +++ b/enrol/guest/lib.php @@ -85,7 +85,7 @@ class enrol_guest_plugin extends enrol_plugin { if ($allow) { // Temporarily assign them some guest role for this context - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid); + $context = context_course::instance($instance->courseid); load_temp_course_role($context, $CFG->guestroleid); return ENROL_MAX_TIMESTAMP; } @@ -101,7 +101,7 @@ class enrol_guest_plugin extends enrol_plugin { public function get_newinstance_link($courseid) { global $DB; - $context = get_context_instance(CONTEXT_COURSE, $courseid, MUST_EXIST); + $context = context_course::instance($courseid, MUST_EXIST); if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/guest:config', $context)) { return NULL; @@ -140,7 +140,7 @@ class enrol_guest_plugin extends enrol_plugin { if ($instance->id == $instanceid) { if ($data = $form->get_data()) { // add guest role - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid); + $context = context_course::instance($instance->courseid); $USER->enrol_guest_passwords[$instance->id] = $data->guestpassword; // this is a hack, ideally we should not add stuff to $USER... if (isset($USER->enrol['tempguest'][$instance->courseid])) { remove_temp_course_roles($context); @@ -280,7 +280,7 @@ class enrol_guest_plugin extends enrol_plugin { public function course_updated($inserted, $course, $data) { global $DB; - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); if (has_capability('enrol/guest:config', $context)) { if ($inserted) { diff --git a/enrol/imsenterprise/importnow.php b/enrol/imsenterprise/importnow.php index e9379bc2225..102d038ea93 100644 --- a/enrol/imsenterprise/importnow.php +++ b/enrol/imsenterprise/importnow.php @@ -1,12 +1,12 @@ set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_context(context_system::instance()); $PAGE->set_url('/enrol/imsenterprise/importnow.php'); $PAGE->set_title(get_string('importimsfile', 'enrol_imsenterprise')); diff --git a/enrol/imsenterprise/lib.php b/enrol/imsenterprise/lib.php index 284608a7267..785d613105a 100644 --- a/enrol/imsenterprise/lib.php +++ b/enrol/imsenterprise/lib.php @@ -635,7 +635,7 @@ function process_membership_tag($tagcontents){ // The actual processing (ensuring a group record exists, etc) occurs below, in the enrol-a-student clause } - $rolecontext = get_context_instance(CONTEXT_COURSE, $ship->courseid); + $rolecontext = context_course::instance($ship->courseid); $rolecontext = $rolecontext->id; // All we really want is the ID //$this->log_line("Context instance for course $ship->courseid is..."); //print_r($rolecontext); diff --git a/enrol/imsenterprise/settings.php b/enrol/imsenterprise/settings.php index 977a61c4211..9040b21dd67 100644 --- a/enrol/imsenterprise/settings.php +++ b/enrol/imsenterprise/settings.php @@ -56,7 +56,7 @@ if ($ADMIN->fulltree) { $settings->add(new admin_setting_heading('enrol_imsenterprise_usersettings_roles', get_string('roles', 'enrol_imsenterprise'), get_string('imsrolesdescription', 'enrol_imsenterprise'))); if (!during_initial_install()) { - $coursecontext = get_context_instance(CONTEXT_COURSE, SITEID); + $coursecontext = context_course::instance(SITEID); $assignableroles = get_assignable_roles($coursecontext); $assignableroles = array('0' => get_string('ignore', 'enrol_imsenterprise')) + $assignableroles; $imsroles = new imsenterprise_roles(); diff --git a/enrol/index.php b/enrol/index.php index 5c3caa82f8e..0c66f670928 100644 --- a/enrol/index.php +++ b/enrol/index.php @@ -36,7 +36,7 @@ if (!isloggedin()) { } $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); // Everybody is enrolled on the frontpage if ($course->id == SITEID) { @@ -84,6 +84,9 @@ $PAGE->navbar->add(get_string('enrolmentoptions','enrol')); echo $OUTPUT->header(); echo $OUTPUT->heading(get_string('enrolmentoptions','enrol')); +$courserenderer = $PAGE->get_renderer('core', 'course'); +echo $courserenderer->course_info_box($course); + //TODO: find if future enrolments present and display some info foreach ($forms as $form) { diff --git a/enrol/instances.php b/enrol/instances.php index 3f8b2dbccdd..8b8d55851fb 100644 --- a/enrol/instances.php +++ b/enrol/instances.php @@ -26,12 +26,12 @@ require('../config.php'); $id = required_param('id', PARAM_INT); // course id -$action = optional_param('action', '', PARAM_ACTION); +$action = optional_param('action', '', PARAM_ALPHANUMEXT); $instanceid = optional_param('instance', 0, PARAM_INT); $confirm = optional_param('confirm', 0, PARAM_BOOL); $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); if ($course->id == SITEID) { redirect("$CFG->wwwroot/"); diff --git a/enrol/ldap/lib.php b/enrol/ldap/lib.php index f3678bc07fe..f9ab2236a4b 100644 --- a/enrol/ldap/lib.php +++ b/enrol/ldap/lib.php @@ -250,7 +250,7 @@ class enrol_ldap_plugin extends enrol_plugin { // Deal with unenrolments. $transaction = $DB->start_delegated_transaction(); foreach ($enrolments[$role->id]['current'] as $course) { - $context = get_context_instance(CONTEXT_COURSE, $course->courseid); + $context = context_course::instance($course->courseid); $instance = $DB->get_record('enrol', array('id'=>$course->enrolid)); switch ($this->get_config('unenrolaction')) { case ENROL_EXT_REMOVED_UNENROL: @@ -448,7 +448,7 @@ class enrol_ldap_plugin extends enrol_plugin { JOIN {enrol} e ON (e.id = ue.enrolid) WHERE u.deleted = 0 AND e.courseid = :courseid "; $params = array('roleid'=>$role->id, 'courseid'=>$course_obj->id); - $context = get_context_instance(CONTEXT_COURSE, $course_obj->id); + $context = context_course::instance($course_obj->id); if (!empty($ldapmembers)) { list($ldapml, $params2) = $DB->get_in_or_equal($ldapmembers, SQL_PARAMS_NAMED, 'm', false); $sql .= "AND u.idnumber $ldapml"; diff --git a/enrol/locallib.php b/enrol/locallib.php index a819ce9000f..1c71e657ad9 100644 --- a/enrol/locallib.php +++ b/enrol/locallib.php @@ -112,7 +112,7 @@ class course_enrolment_manager { */ public function __construct(moodle_page $moodlepage, $course, $instancefilter = null) { $this->moodlepage = $moodlepage; - $this->context = get_context_instance(CONTEXT_COURSE, $course->id); + $this->context = context_course::instance($course->id); $this->course = $course; $this->instancefilter = $instancefilter; } diff --git a/enrol/manual/ajax.php b/enrol/manual/ajax.php index a9d5bb7f804..140b4cd8dfe 100644 --- a/enrol/manual/ajax.php +++ b/enrol/manual/ajax.php @@ -34,12 +34,12 @@ require_once($CFG->dirroot.'/group/lib.php'); // Must have the sesskey $id = required_param('id', PARAM_INT); // course id -$action = required_param('action', PARAM_ACTION); +$action = required_param('action', PARAM_ALPHANUMEXT); $PAGE->set_url(new moodle_url('/enrol/ajax.php', array('id'=>$id, 'action'=>$action))); $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); if ($course->id == SITEID) { throw new moodle_exception('invalidcourse'); diff --git a/enrol/manual/edit.php b/enrol/manual/edit.php index 24079a93067..978a6eb4983 100644 --- a/enrol/manual/edit.php +++ b/enrol/manual/edit.php @@ -31,7 +31,7 @@ require_once('edit_form.php'); $courseid = required_param('courseid', PARAM_INT); $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login($course); require_capability('enrol/manual:config', $context); diff --git a/enrol/manual/editenrolment.php b/enrol/manual/editenrolment.php index e749fab6cdf..2d8a7003751 100644 --- a/enrol/manual/editenrolment.php +++ b/enrol/manual/editenrolment.php @@ -57,7 +57,7 @@ if ($course->id == SITEID) { // Obviously require_login($course); // Make sure the user can manage manual enrolments for this course -require_capability("enrol/manual:manage", get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST)); +require_capability("enrol/manual:manage", context_course::instance($course->id, MUST_EXIST)); // Get the enrolment manager for this course $manager = new course_enrolment_manager($PAGE, $course, $filter); diff --git a/enrol/manual/externallib.php b/enrol/manual/externallib.php index 44d90acc519..94fde810072 100644 --- a/enrol/manual/externallib.php +++ b/enrol/manual/externallib.php @@ -93,7 +93,7 @@ class enrol_manual_external extends external_api { foreach ($params['enrolments'] as $enrolment) { // Ensure the current user is allowed to run this function in the enrolment context - $context = get_context_instance(CONTEXT_COURSE, $enrolment['courseid']); + $context = context_course::instance($enrolment['courseid'], IGNORE_MISSING); self::validate_context($context); //check that the user has the permission to manual enrol diff --git a/enrol/manual/lib.php b/enrol/manual/lib.php index 9c3a5d64772..45e33affda7 100644 --- a/enrol/manual/lib.php +++ b/enrol/manual/lib.php @@ -65,7 +65,7 @@ class enrol_manual_plugin extends enrol_plugin { return NULL; } - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST); + $context = context_course::instance($instance->courseid, MUST_EXIST); if (!has_capability('enrol/manual:manage', $context) or !has_capability('enrol/manual:enrol', $context) or !has_capability('enrol/manual:unenrol', $context)) { return NULL; @@ -88,7 +88,7 @@ class enrol_manual_plugin extends enrol_plugin { throw new coding_exception('Invalid enrol instance type!'); } - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid); + $context = context_course::instance($instance->courseid); if (has_capability('enrol/manual:config', $context)) { $managelink = new moodle_url('/enrol/manual/edit.php', array('courseid'=>$instance->courseid)); $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING); @@ -106,7 +106,7 @@ class enrol_manual_plugin extends enrol_plugin { if ($instance->enrol !== 'manual') { throw new coding_exception('invalid enrol instance!'); } - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid); + $context = context_course::instance($instance->courseid); $icons = array(); @@ -130,7 +130,7 @@ class enrol_manual_plugin extends enrol_plugin { public function get_newinstance_link($courseid) { global $DB; - $context = get_context_instance(CONTEXT_COURSE, $courseid, MUST_EXIST); + $context = context_course::instance($courseid, MUST_EXIST); if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/manual:config', $context)) { return NULL; diff --git a/enrol/manual/manage.php b/enrol/manual/manage.php index 94fdc632a9a..a466f780cc6 100644 --- a/enrol/manual/manage.php +++ b/enrol/manual/manage.php @@ -33,7 +33,7 @@ $extendbase = optional_param('extendbase', 3, PARAM_INT); $instance = $DB->get_record('enrol', array('id'=>$enrolid, 'enrol'=>'manual'), '*', MUST_EXIST); $course = $DB->get_record('course', array('id'=>$instance->courseid), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login($course); require_capability('enrol/manual:enrol', $context); diff --git a/enrol/manual/settings.php b/enrol/manual/settings.php index 90bb4cb4612..5ef1b519122 100644 --- a/enrol/manual/settings.php +++ b/enrol/manual/settings.php @@ -48,7 +48,7 @@ if ($ADMIN->fulltree) { get_string('defaultperiod', 'enrol_manual'), get_string('defaultperiod_desc', 'enrol_manual'), 0, PARAM_INT)); if (!during_initial_install()) { - $options = get_default_enrol_roles(get_context_instance(CONTEXT_SYSTEM)); + $options = get_default_enrol_roles(context_system::instance()); $student = get_archetype_roles('student'); $student = reset($student); $settings->add(new admin_setting_configselect('enrol_manual/roleid', diff --git a/enrol/manual/unenrolself.php b/enrol/manual/unenrolself.php index 4431ac8ca61..fb1744de716 100644 --- a/enrol/manual/unenrolself.php +++ b/enrol/manual/unenrolself.php @@ -31,7 +31,7 @@ $confirm = optional_param('confirm', 0, PARAM_BOOL); $instance = $DB->get_record('enrol', array('id'=>$enrolid, 'enrol'=>'manual'), '*', MUST_EXIST); $course = $DB->get_record('course', array('id'=>$instance->courseid), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login(); if (!is_enrolled($context)) { diff --git a/enrol/meta/addinstance.php b/enrol/meta/addinstance.php index 448480443f0..b1bd857a7c1 100644 --- a/enrol/meta/addinstance.php +++ b/enrol/meta/addinstance.php @@ -31,7 +31,7 @@ require_once("$CFG->dirroot/enrol/meta/locallib.php"); $id = required_param('id', PARAM_INT); // course id $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); $PAGE->set_url('/enrol/meta/addinstance.php', array('id'=>$course->id)); $PAGE->set_pagelayout('admin'); diff --git a/enrol/meta/addinstance_form.php b/enrol/meta/addinstance_form.php index ee9538764ad..f2b9bbff49f 100644 --- a/enrol/meta/addinstance_form.php +++ b/enrol/meta/addinstance_form.php @@ -46,7 +46,7 @@ class enrol_meta_addinstance_form extends moodleform { if ($c->id == SITEID or $c->id == $course->id or isset($existing[$c->id])) { continue; } - $coursecontext = get_context_instance(CONTEXT_COURSE, $c->id); + $coursecontext = context_course::instance($c->id); if (!$c->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) { continue; } @@ -79,7 +79,7 @@ class enrol_meta_addinstance_form extends moodleform { if (!$c = $DB->get_record('course', array('id'=>$data['link']))) { $errors['link'] = get_string('required'); } else { - $coursecontext = get_context_instance(CONTEXT_COURSE, $c->id); + $coursecontext = context_course::instance($c->id); $existing = $DB->get_records('enrol', array('enrol'=>'meta', 'courseid'=>$this->course->id), '', 'customint1, id'); if (!$c->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) { $errors['link'] = get_string('error'); diff --git a/enrol/meta/lib.php b/enrol/meta/lib.php index c400bc32630..10f277bf138 100644 --- a/enrol/meta/lib.php +++ b/enrol/meta/lib.php @@ -58,7 +58,7 @@ class enrol_meta_plugin extends enrol_plugin { * @return moodle_url page url */ public function get_newinstance_link($courseid) { - $context = get_context_instance(CONTEXT_COURSE, $courseid, MUST_EXIST); + $context = context_course::instance($courseid, MUST_EXIST); if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/meta:config', $context)) { return NULL; } diff --git a/enrol/mnet/addinstance.php b/enrol/mnet/addinstance.php index 227bf823c5c..b7d75f4a423 100644 --- a/enrol/mnet/addinstance.php +++ b/enrol/mnet/addinstance.php @@ -31,7 +31,7 @@ require_once($CFG->dirroot.'/mnet/service/enrol/locallib.php'); $id = required_param('id', PARAM_INT); // course id $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login($course); require_capability('moodle/course:enrolconfig', $context); diff --git a/enrol/mnet/addinstance_form.php b/enrol/mnet/addinstance_form.php index 9e30ce196cb..e6d13d12a82 100644 --- a/enrol/mnet/addinstance_form.php +++ b/enrol/mnet/addinstance_form.php @@ -36,7 +36,7 @@ class enrol_mnet_addinstance_form extends moodleform { $course = $this->_customdata['course']; $enrol = $this->_customdata['enrol']; $service = $this->_customdata['service']; - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $subscribers = $service->get_remote_subscribers(); $hosts = array(0 => get_string('remotesubscribersall', 'enrol_mnet')); diff --git a/enrol/mnet/enrol.php b/enrol/mnet/enrol.php index 2fb785c5b70..58fd876a385 100644 --- a/enrol/mnet/enrol.php +++ b/enrol/mnet/enrol.php @@ -88,7 +88,7 @@ class enrol_mnet_mnetservice_enrol { // use the record if it does not exist yet or is host-specific if (empty($courses[$course->remoteid]) or ($course->customint1 > 0)) { unset($course->customint1); // the client does not need to know this - $context = get_context_instance(CONTEXT_COURSE, $course->remoteid); + $context = context_course::instance($course->remoteid); // Rewrite file URLs so that they are correct $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', false); $courses[$course->remoteid] = $course; diff --git a/enrol/mnet/lib.php b/enrol/mnet/lib.php index d49bcf4c43e..0a507293f71 100644 --- a/enrol/mnet/lib.php +++ b/enrol/mnet/lib.php @@ -47,7 +47,7 @@ class enrol_mnet_plugin extends enrol_plugin { } else if (empty($instance->name)) { $enrol = $this->get_name(); if ($role = $DB->get_record('role', array('id'=>$instance->roleid))) { - $role = role_get_name($role, get_context_instance(CONTEXT_COURSE, $instance->courseid)); + $role = role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING)); } else { $role = get_string('error'); } @@ -79,7 +79,7 @@ class enrol_mnet_plugin extends enrol_plugin { if (!$service->is_available()) { return null; } - $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid); + $coursecontext = context_course::instance($courseid); if (!has_capability('moodle/course:enrolconfig', $coursecontext)) { return null; } diff --git a/enrol/mnet/settings.php b/enrol/mnet/settings.php index acce3fed2e0..fc022046dd0 100644 --- a/enrol/mnet/settings.php +++ b/enrol/mnet/settings.php @@ -33,7 +33,7 @@ if ($ADMIN->fulltree) { //--- enrol instance defaults ---------------------------------------------------------------------------- if (!during_initial_install()) { - $options = get_default_enrol_roles(get_context_instance(CONTEXT_SYSTEM)); + $options = get_default_enrol_roles(context_system::instance()); $student = get_archetype_roles('student'); $student = reset($student); $settings->add(new admin_setting_configselect_with_advanced('enrol_mnet/roleid', diff --git a/enrol/otherusers.php b/enrol/otherusers.php index 52b34bfe829..3fd7f52d32e 100644 --- a/enrol/otherusers.php +++ b/enrol/otherusers.php @@ -29,11 +29,11 @@ require_once("$CFG->dirroot/enrol/renderer.php"); require_once("$CFG->dirroot/group/lib.php"); $id = required_param('id', PARAM_INT); // course id -$action = optional_param('action', '', PARAM_ACTION); +$action = optional_param('action', '', PARAM_ALPHANUMEXT); $filter = optional_param('ifilter', 0, PARAM_INT); $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login($course); require_capability('moodle/role:assign', $context); diff --git a/enrol/paypal/edit.php b/enrol/paypal/edit.php index 91c89e2fe24..b39e5b3146d 100644 --- a/enrol/paypal/edit.php +++ b/enrol/paypal/edit.php @@ -32,7 +32,7 @@ $courseid = required_param('courseid', PARAM_INT); $instanceid = optional_param('id', 0, PARAM_INT); // instanceid $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login($course); require_capability('enrol/paypal:config', $context); diff --git a/enrol/paypal/ipn.php b/enrol/paypal/ipn.php index b4a6bf42403..2a28c245e90 100644 --- a/enrol/paypal/ipn.php +++ b/enrol/paypal/ipn.php @@ -76,7 +76,7 @@ if (! $course = $DB->get_record("course", array("id"=>$data->courseid))) { die; } -if (! $context = get_context_instance(CONTEXT_COURSE, $course->id)) { +if (! $context = context_course::instance($course->id, IGNORE_MISSING)) { message_paypal_error_to_admin("Not a valid context id", $data); die; } @@ -187,7 +187,7 @@ while (!feof($fp)) { die; } - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id, IGNORE_MISSING); // Check that amount paid is the correct amount if ( (float) $plugin_instance->cost <= 0 ) { diff --git a/enrol/paypal/lib.php b/enrol/paypal/lib.php index d9f9d498d9b..69b9b399c78 100644 --- a/enrol/paypal/lib.php +++ b/enrol/paypal/lib.php @@ -80,7 +80,7 @@ class enrol_paypal_plugin extends enrol_plugin { throw new coding_exception('Invalid enrol instance type!'); } - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid); + $context = context_course::instance($instance->courseid); if (has_capability('enrol/paypal:config', $context)) { $managelink = new moodle_url('/enrol/paypal/edit.php', array('courseid'=>$instance->courseid, 'id'=>$instance->id)); $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING); @@ -98,7 +98,7 @@ class enrol_paypal_plugin extends enrol_plugin { if ($instance->enrol !== 'paypal') { throw new coding_exception('invalid enrol instance!'); } - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid); + $context = context_course::instance($instance->courseid); $icons = array(); @@ -116,7 +116,7 @@ class enrol_paypal_plugin extends enrol_plugin { * @return moodle_url page url */ public function get_newinstance_link($courseid) { - $context = get_context_instance(CONTEXT_COURSE, $courseid, MUST_EXIST); + $context = context_course::instance($courseid, MUST_EXIST); if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/paypal:config', $context)) { return NULL; @@ -151,7 +151,7 @@ class enrol_paypal_plugin extends enrol_plugin { } $course = $DB->get_record('course', array('id'=>$instance->courseid)); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); $shortname = format_string($course->shortname, true, array('context' => $context)); $strloginto = get_string("loginto", "", $shortname); diff --git a/enrol/paypal/return.php b/enrol/paypal/return.php index a8a65570c4c..81357161381 100644 --- a/enrol/paypal/return.php +++ b/enrol/paypal/return.php @@ -34,7 +34,7 @@ if (!$course = $DB->get_record("course", array("id"=>$id))) { redirect($CFG->wwwroot); } -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login(); diff --git a/enrol/paypal/settings.php b/enrol/paypal/settings.php index 3352d2b9713..80ac4c81bfa 100644 --- a/enrol/paypal/settings.php +++ b/enrol/paypal/settings.php @@ -61,7 +61,7 @@ if ($ADMIN->fulltree) { $settings->add(new admin_setting_configselect('enrol_paypal/currency', get_string('currency', 'enrol_paypal'), '', 'USD', $paypalcurrencies)); if (!during_initial_install()) { - $options = get_default_enrol_roles(get_context_instance(CONTEXT_SYSTEM)); + $options = get_default_enrol_roles(context_system::instance()); $student = get_archetype_roles('student'); $student = reset($student); $settings->add(new admin_setting_configselect('enrol_paypal/roleid', diff --git a/enrol/paypal/unenrolself.php b/enrol/paypal/unenrolself.php index 9984d586306..c884733ee3d 100644 --- a/enrol/paypal/unenrolself.php +++ b/enrol/paypal/unenrolself.php @@ -31,7 +31,7 @@ $confirm = optional_param('confirm', 0, PARAM_BOOL); $instance = $DB->get_record('enrol', array('id'=>$enrolid, 'enrol'=>'paypal'), '*', MUST_EXIST); $course = $DB->get_record('course', array('id'=>$instance->courseid), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login(); if (!is_enrolled($context)) { diff --git a/enrol/self/edit.php b/enrol/self/edit.php index 4affcb7979a..4b38df4daba 100644 --- a/enrol/self/edit.php +++ b/enrol/self/edit.php @@ -32,7 +32,7 @@ $courseid = required_param('courseid', PARAM_INT); $instanceid = optional_param('id', 0, PARAM_INT); // instanceid $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login($course); require_capability('enrol/self:config', $context); diff --git a/enrol/self/editenrolment.php b/enrol/self/editenrolment.php index 4449d342c00..418359ea9df 100644 --- a/enrol/self/editenrolment.php +++ b/enrol/self/editenrolment.php @@ -57,7 +57,7 @@ if ($course->id == SITEID) { // Obvioulsy require_login($course); // The user must be able to manage self enrolments within the course -require_capability("enrol/self:manage", get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST)); +require_capability("enrol/self:manage", context_course::instance($course->id, MUST_EXIST)); // Get the enrolment manager for this course $manager = new course_enrolment_manager($PAGE, $course, $filter); diff --git a/enrol/self/lib.php b/enrol/self/lib.php index 32c9d48e643..4c9246b3c2b 100644 --- a/enrol/self/lib.php +++ b/enrol/self/lib.php @@ -74,7 +74,7 @@ class enrol_self_plugin extends enrol_plugin { if (empty($instance->name)) { if (!empty($instance->roleid) and $role = $DB->get_record('role', array('id'=>$instance->roleid))) { - $role = ' (' . role_get_name($role, get_context_instance(CONTEXT_COURSE, $instance->courseid)) . ')'; + $role = ' (' . role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING)) . ')'; } else { $role = ''; } @@ -115,7 +115,7 @@ class enrol_self_plugin extends enrol_plugin { throw new coding_exception('Invalid enrol instance type!'); } - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid); + $context = context_course::instance($instance->courseid); if (has_capability('enrol/self:config', $context)) { $managelink = new moodle_url('/enrol/self/edit.php', array('courseid'=>$instance->courseid, 'id'=>$instance->id)); $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING); @@ -133,7 +133,7 @@ class enrol_self_plugin extends enrol_plugin { if ($instance->enrol !== 'self') { throw new coding_exception('invalid enrol instance!'); } - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid); + $context = context_course::instance($instance->courseid); $icons = array(); @@ -151,7 +151,7 @@ class enrol_self_plugin extends enrol_plugin { * @return moodle_url page url */ public function get_newinstance_link($courseid) { - $context = get_context_instance(CONTEXT_COURSE, $courseid, MUST_EXIST); + $context = context_course::instance($courseid, MUST_EXIST); if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/self:config', $context)) { return NULL; @@ -282,7 +282,7 @@ class enrol_self_plugin extends enrol_plugin { $subject = get_string('welcometocourse', 'enrol_self', format_string($course->fullname)); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); $rusers = array(); if (!empty($CFG->coursecontact)) { $croles = explode(',', $CFG->coursecontact); diff --git a/enrol/self/locallib.php b/enrol/self/locallib.php index 86adfbf819d..a189e7d4066 100644 --- a/enrol/self/locallib.php +++ b/enrol/self/locallib.php @@ -67,7 +67,7 @@ class enrol_self_enrol_form extends moodleform { if ($instance->password) { //change the id of self enrolment key input as there can be multiple self enrolment methods $mform->addElement('passwordunmask', 'enrolpassword', get_string('password', 'enrol_self'), - array('id' => $instance->id."_enrolpassword")); + array('id' => 'enrolpassword_'.$instance->id)); } else { $mform->addElement('static', 'nokey', '', get_string('nopassword', 'enrol_self')); } @@ -127,4 +127,4 @@ class enrol_self_enrol_form extends moodleform { return $errors; } -} \ No newline at end of file +} diff --git a/enrol/self/settings.php b/enrol/self/settings.php index dc9a874e74f..0b11ccd487c 100644 --- a/enrol/self/settings.php +++ b/enrol/self/settings.php @@ -58,7 +58,7 @@ if ($ADMIN->fulltree) { get_string('groupkey', 'enrol_self'), get_string('groupkey_desc', 'enrol_self'), 0, $options)); if (!during_initial_install()) { - $options = get_default_enrol_roles(get_context_instance(CONTEXT_SYSTEM)); + $options = get_default_enrol_roles(context_system::instance()); $student = get_archetype_roles('student'); $student = reset($student); $settings->add(new admin_setting_configselect('enrol_self/roleid', diff --git a/enrol/self/unenrolself.php b/enrol/self/unenrolself.php index 5fd6062d785..02670f6abb2 100644 --- a/enrol/self/unenrolself.php +++ b/enrol/self/unenrolself.php @@ -31,7 +31,7 @@ $confirm = optional_param('confirm', 0, PARAM_BOOL); $instance = $DB->get_record('enrol', array('id'=>$enrolid, 'enrol'=>'self'), '*', MUST_EXIST); $course = $DB->get_record('course', array('id'=>$instance->courseid), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); require_login(); if (!is_enrolled($context)) { diff --git a/enrol/users.php b/enrol/users.php index 2ebbab5ec8b..683de562427 100644 --- a/enrol/users.php +++ b/enrol/users.php @@ -30,11 +30,11 @@ require_once("$CFG->dirroot/enrol/renderer.php"); require_once("$CFG->dirroot/group/lib.php"); $id = required_param('id', PARAM_INT); // course id -$action = optional_param('action', '', PARAM_ACTION); +$action = optional_param('action', '', PARAM_ALPHANUMEXT); $filter = optional_param('ifilter', 0, PARAM_INT); $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$context = context_course::instance($course->id, MUST_EXIST); if ($course->id == SITEID) { redirect(new moodle_url('/')); diff --git a/enrol/users_forms.php b/enrol/users_forms.php index 7263688fdde..390774c0f43 100644 --- a/enrol/users_forms.php +++ b/enrol/users_forms.php @@ -36,7 +36,7 @@ class enrol_users_assign_form extends moodleform { $user = $this->_customdata['user']; $course = $this->_customdata['course']; - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); $assignable = $this->_customdata['assignable']; $assignable = array_reverse($assignable, true); // students first @@ -56,7 +56,7 @@ class enrol_users_assign_form extends moodleform { $mform->setType('user', PARAM_INT); $mform->addElement('hidden', 'action'); - $mform->setType('action', PARAM_ACTION); + $mform->setType('action', PARAM_ALPHANUMEXT); $mform->addElement('hidden', 'ifilter'); $mform->setType('ifilter', PARAM_ALPHA); @@ -87,7 +87,7 @@ class enrol_users_addmember_form extends moodleform { $user = $this->_customdata['user']; $course = $this->_customdata['course']; - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id, IGNORE_MISSING); $allgroups = $this->_customdata['allgroups']; $usergroups = groups_get_all_groups($course->id, $user->id, 0, 'g.id'); @@ -110,7 +110,7 @@ class enrol_users_addmember_form extends moodleform { $mform->setType('user', PARAM_INT); $mform->addElement('hidden', 'action'); - $mform->setType('action', PARAM_ACTION); + $mform->setType('action', PARAM_ALPHANUMEXT); $mform->addElement('hidden', 'ifilter'); $mform->setType('ifilter', PARAM_ALPHA); diff --git a/filter/algebra/algebradebug.php b/filter/algebra/algebradebug.php index 67b715cc9ab..e133df159b6 100644 --- a/filter/algebra/algebradebug.php +++ b/filter/algebra/algebradebug.php @@ -15,7 +15,7 @@ require_once($CFG->dirroot.'/filter/tex/lib.php'); require_login(); - require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); + require_capability('moodle/site:config', context_system::instance()); $query = urldecode($_SERVER['QUERY_STRING']); diff --git a/filter/algebra/filter.php b/filter/algebra/filter.php index 54ffaff5185..9ba698a55c9 100644 --- a/filter/algebra/filter.php +++ b/filter/algebra/filter.php @@ -73,7 +73,7 @@ function filter_algebra_image($imagefile, $tex= "", $height="", $width="", $alig } $anchorcontents .= "\" $style />"; - if (!file_exists("$CFG->dataroot/filter/algebra/$imagefile") && has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { + if (!file_exists("$CFG->dataroot/filter/algebra/$imagefile") && has_capability('moodle/site:config', context_system::instance())) { $link = '/filter/algebra/algebradebug.php'; $action = null; } else { diff --git a/filter/tex/filter.php b/filter/tex/filter.php index 0b62fc1e189..0999df263a4 100644 --- a/filter/tex/filter.php +++ b/filter/tex/filter.php @@ -92,7 +92,7 @@ function filter_text_image($imagefile, $tex, $height, $width, $align, $alt) { } $anchorcontents .= "\" $style/>"; - if (!file_exists("$CFG->dataroot/filter/tex/$imagefile") && has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { + if (!file_exists("$CFG->dataroot/filter/tex/$imagefile") && has_capability('moodle/site:config', context_system::instance())) { $link = '/filter/tex/texdebug.php'; $action = null; } else { diff --git a/filter/tex/texdebug.php b/filter/tex/texdebug.php index b4a08dee34c..32004492a24 100644 --- a/filter/tex/texdebug.php +++ b/filter/tex/texdebug.php @@ -40,7 +40,7 @@ $texexp = optional_param('tex', '', PARAM_RAW); require_login(); - require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM), $USER->id); /// Required cap to run this. MDL-18552 + require_capability('moodle/site:config', context_system::instance(), $USER->id); /// Required cap to run this. MDL-18552 $output = ''; diff --git a/grade/edit/outcome/course.php b/grade/edit/outcome/course.php index d23b002ed2a..b23dc998d9c 100644 --- a/grade/edit/outcome/course.php +++ b/grade/edit/outcome/course.php @@ -34,7 +34,7 @@ $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); /// Make sure they can even access this course require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('moodle/course:update', $context); /// return tracking object diff --git a/grade/edit/outcome/edit.php b/grade/edit/outcome/edit.php index d2732894c0a..dd8b8fbd48f 100644 --- a/grade/edit/outcome/edit.php +++ b/grade/edit/outcome/edit.php @@ -40,7 +40,7 @@ if ($id !== 0) { $PAGE->set_url($url); $PAGE->set_pagelayout('admin'); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); $heading = null; // a bit complex access control :-O @@ -57,7 +57,7 @@ if ($id) { print_error('invalidcourseid'); } require_login($course); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); require_capability('moodle/grade:manage', $context); $courseid = $course->id; } else { @@ -77,7 +77,7 @@ if ($id) { /// adding new outcome from course $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); require_login($course); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); require_capability('moodle/grade:manage', $context); navigation_node::override_active_url(new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid))); diff --git a/grade/edit/outcome/edit_form.php b/grade/edit/outcome/edit_form.php index fe2c6821df0..734009781c5 100644 --- a/grade/edit/outcome/edit_form.php +++ b/grade/edit/outcome/edit_form.php @@ -121,7 +121,7 @@ class edit_outcome_form extends moodleform { if (empty($courseid)) { $mform->hardFreeze('standard'); - } else if (empty($outcome->courseid) and !has_capability('moodle/grade:manage', get_context_instance(CONTEXT_SYSTEM))) { + } else if (empty($outcome->courseid) and !has_capability('moodle/grade:manage', context_system::instance())) { $mform->hardFreeze('standard'); } else if ($coursecount and empty($outcome->courseid)) { @@ -130,7 +130,7 @@ class edit_outcome_form extends moodleform { } else { - if (empty($courseid) or !has_capability('moodle/grade:manage', get_context_instance(CONTEXT_SYSTEM))) { + if (empty($courseid) or !has_capability('moodle/grade:manage', context_system::instance())) { $mform->hardFreeze('standard'); } } diff --git a/grade/edit/outcome/export.php b/grade/edit/outcome/export.php index 154db6884a5..61a2bdd3c39 100644 --- a/grade/edit/outcome/export.php +++ b/grade/edit/outcome/export.php @@ -35,7 +35,7 @@ if ($courseid) { print_error('nocourseid'); } require_login($course); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); require_capability('moodle/grade:manage', $context); if (empty($CFG->enableoutcomes)) { @@ -49,10 +49,6 @@ if ($courseid) { require_sesskey(); -// $outcome = grade_outcome::fetch(array('id'=>$outcomeid)); - -$systemcontext = get_context_instance(CONTEXT_SYSTEM); - header("Content-Type: text/csv; charset=utf-8"); // TODO: make the filename more useful, include a date, a specific name, something... header('Content-Disposition: attachment; filename=outcomes.csv'); diff --git a/grade/edit/outcome/import.php b/grade/edit/outcome/import.php index b2128773399..c10a858a4c9 100644 --- a/grade/edit/outcome/import.php +++ b/grade/edit/outcome/import.php @@ -40,7 +40,7 @@ if ($courseid) { print_error('nocourseid'); } require_login($course); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); if (empty($CFG->enableoutcomes)) { redirect('../../index.php?id='.$courseid); @@ -49,7 +49,7 @@ if ($courseid) { } else { require_once $CFG->libdir.'/adminlib.php'; admin_externalpage_setup('outcomes'); - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); } require_capability('moodle/grade:manageoutcomes', $context); @@ -79,7 +79,7 @@ if (!$upload_form->save_file('userfile', $imported_file, true)) { if (isset($courseid) && ($scope == 'custom')) { // custom scale $local_scope = true; -} elseif (($scope == 'global') && has_capability('moodle/grade:manage', get_context_instance(CONTEXT_SYSTEM))) { +} elseif (($scope == 'global') && has_capability('moodle/grade:manage', context_system::instance())) { // global scale $local_scope = false; } else { diff --git a/grade/edit/outcome/import_outcomes_form.php b/grade/edit/outcome/import_outcomes_form.php index 4a263c8693e..163e0f0a7b0 100644 --- a/grade/edit/outcome/import_outcomes_form.php +++ b/grade/edit/outcome/import_outcomes_form.php @@ -36,12 +36,12 @@ class import_outcomes_form extends moodleform { $mform =& $this->_form; $mform->addElement('hidden', 'action', 'upload'); - $mform->setType('action', PARAM_ACTION); + $mform->setType('action', PARAM_ALPHANUMEXT); $mform->addElement('hidden', 'courseid', $PAGE->course->id); $mform->setType('id', PARAM_INT); $scope = array(); - if (($PAGE->course->id > 1) && has_capability('moodle/grade:manage', get_context_instance(CONTEXT_SYSTEM))) { + if (($PAGE->course->id > 1) && has_capability('moodle/grade:manage', context_system::instance())) { $mform->addElement('radio', 'scope', get_string('importcustom', 'grades'), null, 'custom'); $mform->addElement('radio', 'scope', get_string('importstandard', 'grades'), null, 'global'); $mform->setDefault('scope', 'custom'); diff --git a/grade/edit/outcome/index.php b/grade/edit/outcome/index.php index f8df7d85d54..c1d9b5b54a8 100644 --- a/grade/edit/outcome/index.php +++ b/grade/edit/outcome/index.php @@ -36,7 +36,7 @@ $PAGE->set_pagelayout('admin'); if ($courseid) { $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); require_login($course); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); require_capability('moodle/grade:manageoutcomes', $context); if (empty($CFG->enableoutcomes)) { @@ -76,7 +76,7 @@ switch ($action) { } if (empty($outcome->courseid)) { - require_capability('moodle/grade:manage', get_context_instance(CONTEXT_SYSTEM)); + require_capability('moodle/grade:manage', context_system::instance()); } else if ($outcome->courseid != $courseid) { print_error('invalidcourseid'); } @@ -105,7 +105,7 @@ switch ($action) { break; } -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); $caneditsystemscales = has_capability('moodle/course:managescales', $systemcontext); if ($courseid) { @@ -138,7 +138,7 @@ if ($courseid and $outcomes = grade_outcome::fetch_all_local($courseid)) { } else if ($scale->courseid == $courseid) { $caneditthisscale = $caneditcoursescales; } else { - $context = get_context_instance(CONTEXT_COURSE, $scale->courseid); + $context = context_course::instance($scale->courseid); $caneditthisscale = has_capability('moodle/course:managescales', $context); } if ($caneditthisscale) { @@ -187,7 +187,7 @@ if ($outcomes = grade_outcome::fetch_all_global()) { } else if ($scale->courseid == $courseid) { $caneditthisscale = $caneditcoursescales; } else { - $context = get_context_instance(CONTEXT_COURSE, $scale->courseid); + $context = context_course::instance($scale->courseid); $caneditthisscale = has_capability('moodle/course:managescales', $context); } if ($caneditthisscale) { @@ -201,10 +201,10 @@ if ($outcomes = grade_outcome::fetch_all_global()) { $line[] = $outcome->get_item_uses_count(); $buttons = ""; - if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_SYSTEM))) { + if (has_capability('moodle/grade:manage', context_system::instance())) { $buttons .= grade_button('edit', $courseid, $outcome); } - if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_SYSTEM)) and $outcome->can_delete()) { + if (has_capability('moodle/grade:manage', context_system::instance()) and $outcome->can_delete()) { $buttons .= grade_button('delete', $courseid, $outcome); } $line[] = $buttons; diff --git a/grade/edit/outcome/tabs.php b/grade/edit/outcome/tabs.php index 50da663c529..ca86012eb1c 100644 --- a/grade/edit/outcome/tabs.php +++ b/grade/edit/outcome/tabs.php @@ -24,7 +24,7 @@ $row = $tabs = array(); - $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); $row[] = new tabobject('courseoutcomes', $CFG->wwwroot.'/grade/edit/outcome/course.php?id='.$courseid, diff --git a/grade/edit/scale/edit.php b/grade/edit/scale/edit.php index ee633c617f5..9374a9ff447 100644 --- a/grade/edit/scale/edit.php +++ b/grade/edit/scale/edit.php @@ -33,7 +33,7 @@ $id = optional_param('id', 0, PARAM_INT); $PAGE->set_url('/grade/edit/scale/edit.php', array('id' => $id, 'courseid' => $courseid)); $PAGE->set_pagelayout('admin'); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); $heading = ''; // a bit complex access control :-O @@ -50,7 +50,7 @@ if ($id) { print_error('invalidcourseid'); } require_login($course); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); require_capability('moodle/course:managescales', $context); $courseid = $course->id; } else { @@ -75,7 +75,7 @@ if ($id) { $scale_rec->standard = 0; $scale_rec->courseid = $courseid; require_login($course); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); require_capability('moodle/course:managescales', $context); } else { diff --git a/grade/edit/scale/edit_form.php b/grade/edit/scale/edit_form.php index ccb7ab1d352..8cd7d0ddad2 100644 --- a/grade/edit/scale/edit_form.php +++ b/grade/edit/scale/edit_form.php @@ -88,7 +88,7 @@ class edit_scale_form extends moodleform { if (empty($courseid)) { $mform->hardFreeze('standard'); - } else if (!has_capability('moodle/course:managescales', get_context_instance(CONTEXT_SYSTEM))) { + } else if (!has_capability('moodle/course:managescales', context_system::instance())) { //if they dont have managescales at system level the shouldnt be allowed to make scales standard (or not standard) $mform->hardFreeze('standard'); @@ -102,7 +102,7 @@ class edit_scale_form extends moodleform { } else { $mform->removeElement('used'); - if (empty($courseid) or !has_capability('moodle/course:managescales', get_context_instance(CONTEXT_SYSTEM))) { + if (empty($courseid) or !has_capability('moodle/course:managescales', context_system::instance())) { $mform->hardFreeze('standard'); } } diff --git a/grade/edit/scale/index.php b/grade/edit/scale/index.php index 7063feb3803..0b8e207ecfc 100644 --- a/grade/edit/scale/index.php +++ b/grade/edit/scale/index.php @@ -37,7 +37,7 @@ if ($courseid) { print_error('nocourseid'); } require_login($course); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); require_capability('moodle/course:managescales', $context); $PAGE->set_pagelayout('admin'); } else { @@ -69,7 +69,7 @@ switch ($action) { } if (empty($scale->courseid)) { - require_capability('moodle/course:managescales', get_context_instance(CONTEXT_SYSTEM)); + require_capability('moodle/course:managescales', context_system::instance()); } else if ($scale->courseid != $courseid) { print_error('invalidcourseid'); } @@ -147,10 +147,10 @@ if ($scales = grade_scale::fetch_all_global()) { $line[] = $used ? get_string('yes') : get_string('no'); $buttons = ""; - if (has_capability('moodle/course:managescales', get_context_instance(CONTEXT_SYSTEM))) { + if (has_capability('moodle/course:managescales', context_system::instance())) { $buttons .= grade_button('edit', $courseid, $scale); } - if (!$used and has_capability('moodle/course:managescales', get_context_instance(CONTEXT_SYSTEM))) { + if (!$used and has_capability('moodle/course:managescales', context_system::instance())) { $buttons .= grade_button('delete', $courseid, $scale); } $line[] = $buttons; diff --git a/grade/edit/settings/form.php b/grade/edit/settings/form.php index 6c9df49746b..229bb7fac81 100644 --- a/grade/edit/settings/form.php +++ b/grade/edit/settings/form.php @@ -39,7 +39,7 @@ class course_settings_form extends moodleform { $mform =& $this->_form; - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); $can_view_admin_links = false; if (has_capability('moodle/grade:manage', $systemcontext)) { $can_view_admin_links = true; diff --git a/grade/edit/settings/index.php b/grade/edit/settings/index.php index 0ac15f6c20a..fa7a81f6361 100644 --- a/grade/edit/settings/index.php +++ b/grade/edit/settings/index.php @@ -36,7 +36,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { print_error('nocourseid'); } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('moodle/grade:manage', $context); diff --git a/grade/edit/tree/action.php b/grade/edit/tree/action.php index c350dd4edba..33c702ec65a 100644 --- a/grade/edit/tree/action.php +++ b/grade/edit/tree/action.php @@ -36,7 +36,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { print_error('nocourseid'); } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); // default return url $gpr = new grade_plugin_return(); diff --git a/grade/edit/tree/calculation.php b/grade/edit/tree/calculation.php index 89d5cd28545..2d73fb6a46d 100644 --- a/grade/edit/tree/calculation.php +++ b/grade/edit/tree/calculation.php @@ -43,7 +43,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('moodle/grade:manage', $context); // default return url diff --git a/grade/edit/tree/category.php b/grade/edit/tree/category.php index 100369a87b9..852fdd55206 100644 --- a/grade/edit/tree/category.php +++ b/grade/edit/tree/category.php @@ -42,7 +42,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('moodle/grade:manage', $context); // default return url diff --git a/grade/edit/tree/grade.php b/grade/edit/tree/grade.php index d44b2ca290a..c3c8a0a73a5 100644 --- a/grade/edit/tree/grade.php +++ b/grade/edit/tree/grade.php @@ -50,7 +50,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { $PAGE->set_pagelayout('incourse'); require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); if (!has_capability('moodle/grade:manage', $context)) { require_capability('moodle/grade:edit', $context); } diff --git a/grade/edit/tree/grade_form.php b/grade/edit/tree/grade_form.php index 28355e2f869..d4611f766a1 100644 --- a/grade/edit/tree/grade_form.php +++ b/grade/edit/tree/grade_form.php @@ -139,7 +139,7 @@ class edit_grade_form extends moodleform { function definition_after_data() { global $CFG, $COURSE, $DB; - $context = get_context_instance(CONTEXT_COURSE, $COURSE->id); + $context = context_course::instance($COURSE->id); $mform =& $this->_form; $grade_item = $this->_customdata['grade_item']; diff --git a/grade/edit/tree/index.php b/grade/edit/tree/index.php index 801c9efb310..9466845fa39 100644 --- a/grade/edit/tree/index.php +++ b/grade/edit/tree/index.php @@ -47,7 +47,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('moodle/grade:manage', $context); // todo $PAGE->requires->js_module() should be used here instead @@ -272,7 +272,7 @@ if ($data = data_submitted() and confirm_sesskey()) { $aid = $matches[2]; $value = unformat_float($value); - $value = clean_param($value, PARAM_NUMBER); + $value = clean_param($value, PARAM_FLOAT); $grade_item = grade_item::fetch(array('id'=>$aid, 'courseid'=>$courseid)); diff --git a/grade/edit/tree/item.php b/grade/edit/tree/item.php index 0e80c6befce..7acf2ebe17d 100644 --- a/grade/edit/tree/item.php +++ b/grade/edit/tree/item.php @@ -43,7 +43,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('moodle/grade:manage', $context); // default return url diff --git a/grade/edit/tree/lib.php b/grade/edit/tree/lib.php index 5a268b40c0f..eee86647354 100644 --- a/grade/edit/tree/lib.php +++ b/grade/edit/tree/lib.php @@ -389,7 +389,7 @@ class grade_edit_tree { //Grader report has its own decimal place settings so they are handled elsewhere static function format_number($number) { $formatted = rtrim(format_float($number, 4),'0'); - if (substr($formatted, -1)=='.') { //if last char is the decimal point + if (substr($formatted, -1)==get_string('decsep', 'langconfig')) { //if last char is the decimal point $formatted .= '0'; } return $formatted; diff --git a/grade/edit/tree/outcomeitem.php b/grade/edit/tree/outcomeitem.php index 3112d41d711..460a379e8e5 100644 --- a/grade/edit/tree/outcomeitem.php +++ b/grade/edit/tree/outcomeitem.php @@ -41,7 +41,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('moodle/grade:manage', $context); diff --git a/grade/export/grade_export_form.php b/grade/export/grade_export_form.php index daccfa8b664..b21c3f86e0f 100644 --- a/grade/export/grade_export_form.php +++ b/grade/export/grade_export_form.php @@ -119,7 +119,7 @@ class grade_export_form extends moodleform { if ($grade_items = $gseq->items) { $needs_multiselect = false; - $canviewhidden = has_capability('moodle/grade:viewhidden', get_context_instance(CONTEXT_COURSE, $COURSE->id)); + $canviewhidden = has_capability('moodle/grade:viewhidden', context_course::instance($COURSE->id)); foreach ($grade_items as $grade_item) { // Is the grade_item hidden? If so, can the user see hidden grade_items? diff --git a/grade/export/key.php b/grade/export/key.php index cd089d17221..093f60599fa 100644 --- a/grade/export/key.php +++ b/grade/export/key.php @@ -59,7 +59,7 @@ if ($id) { $key->courseid = $course->id; require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('moodle/grade:export', $context); // extra security check diff --git a/grade/export/keymanager.php b/grade/export/keymanager.php index b6d7314b50b..697f1bbd280 100644 --- a/grade/export/keymanager.php +++ b/grade/export/keymanager.php @@ -35,7 +35,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:export', $context); diff --git a/grade/export/ods/dump.php b/grade/export/ods/dump.php index 1bca2f12312..0310ef81e1b 100644 --- a/grade/export/ods/dump.php +++ b/grade/export/ods/dump.php @@ -29,7 +29,7 @@ if (empty($CFG->gradepublishing)) { print_error('gradepubdisable'); } -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('gradeexport/ods:publish', $context); // use the same page parameters as export.php and append &key=sdhakjsahdksahdkjsahksadjksahdkjsadhksa diff --git a/grade/export/ods/export.php b/grade/export/ods/export.php index ae38b92669b..e7dac57b5d7 100644 --- a/grade/export/ods/export.php +++ b/grade/export/ods/export.php @@ -33,7 +33,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:export', $context); require_capability('gradeexport/ods:view', $context); diff --git a/grade/export/ods/grade_export_ods.php b/grade/export/ods/grade_export_ods.php index 30fe2eb46c8..d5b66d11700 100644 --- a/grade/export/ods/grade_export_ods.php +++ b/grade/export/ods/grade_export_ods.php @@ -32,7 +32,7 @@ class grade_export_ods extends grade_export { $strgrades = get_string('grades'); - $shortname = format_string($this->course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $this->course->id))); + $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id))); // Calculate file name $downloadfilename = clean_filename("$shortname $strgrades.ods"); diff --git a/grade/export/ods/index.php b/grade/export/ods/index.php index 0bb70687e40..5b1c33c260c 100644 --- a/grade/export/ods/index.php +++ b/grade/export/ods/index.php @@ -28,7 +28,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:export', $context); require_capability('gradeexport/ods:view', $context); diff --git a/grade/export/txt/dump.php b/grade/export/txt/dump.php index 305b4802e34..787a28c812c 100644 --- a/grade/export/txt/dump.php +++ b/grade/export/txt/dump.php @@ -29,7 +29,7 @@ if (empty($CFG->gradepublishing)) { print_error('gradepubdisable'); } -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('gradeexport/txt:publish', $context); // use the same page parameters as export.php and append &key=sdhakjsahdksahdkjsahksadjksahdkjsadhksa diff --git a/grade/export/txt/export.php b/grade/export/txt/export.php index 17108ee9177..3ddcb59cd10 100644 --- a/grade/export/txt/export.php +++ b/grade/export/txt/export.php @@ -34,7 +34,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:export', $context); require_capability('gradeexport/txt:view', $context); diff --git a/grade/export/txt/grade_export_txt.php b/grade/export/txt/grade_export_txt.php index 43ee3dbb1c6..2f654d673cf 100644 --- a/grade/export/txt/grade_export_txt.php +++ b/grade/export/txt/grade_export_txt.php @@ -74,7 +74,7 @@ class grade_export_txt extends grade_export { @header('Pragma: no-cache'); } header("Content-Type: application/download\n"); - $shortname = format_string($this->course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $this->course->id))); + $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id))); $downloadfilename = clean_filename("$shortname $strgrades"); header("Content-Disposition: attachment; filename=\"$downloadfilename.txt\""); diff --git a/grade/export/txt/index.php b/grade/export/txt/index.php index edda839f2b0..68370fc4688 100644 --- a/grade/export/txt/index.php +++ b/grade/export/txt/index.php @@ -28,7 +28,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:export', $context); require_capability('gradeexport/txt:view', $context); diff --git a/grade/export/xls/dump.php b/grade/export/xls/dump.php index 7c4ea4ee0db..654eb68a269 100644 --- a/grade/export/xls/dump.php +++ b/grade/export/xls/dump.php @@ -29,7 +29,7 @@ if (empty($CFG->gradepublishing)) { print_error('gradepubdisable'); } -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('gradeexport/xls:publish', $context); // use the same page parameters as export.php and append &key=sdhakjsahdksahdkjsahksadjksahdkjsadhksa diff --git a/grade/export/xls/export.php b/grade/export/xls/export.php index 16601ab9083..4cbe5bbe55f 100644 --- a/grade/export/xls/export.php +++ b/grade/export/xls/export.php @@ -33,7 +33,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:export', $context); require_capability('gradeexport/xls:view', $context); diff --git a/grade/export/xls/grade_export_xls.php b/grade/export/xls/grade_export_xls.php index e907c489613..c85dbcbd362 100644 --- a/grade/export/xls/grade_export_xls.php +++ b/grade/export/xls/grade_export_xls.php @@ -33,7 +33,7 @@ class grade_export_xls extends grade_export { $strgrades = get_string('grades'); // Calculate file name - $shortname = format_string($this->course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $this->course->id))); + $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id))); $downloadfilename = clean_filename("$shortname $strgrades.xls"); // Creating a workbook $workbook = new MoodleExcelWorkbook("-"); diff --git a/grade/export/xls/index.php b/grade/export/xls/index.php index a4ee2567d7a..41230a23f4c 100644 --- a/grade/export/xls/index.php +++ b/grade/export/xls/index.php @@ -28,7 +28,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:export', $context); require_capability('gradeexport/xls:view', $context); diff --git a/grade/export/xml/dump.php b/grade/export/xml/dump.php index 5b147f83af2..a640be857a0 100644 --- a/grade/export/xml/dump.php +++ b/grade/export/xml/dump.php @@ -29,7 +29,7 @@ if (empty($CFG->gradepublishing)) { print_error('gradepubdisable'); } -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('gradeexport/xml:publish', $context); // use the same page parameters as export.php and append &key=sdhakjsahdksahdkjsahksadjksahdkjsadhksa diff --git a/grade/export/xml/export.php b/grade/export/xml/export.php index 1424fe87079..33349f96335 100644 --- a/grade/export/xml/export.php +++ b/grade/export/xml/export.php @@ -33,7 +33,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:export', $context); require_capability('gradeexport/xml:view', $context); diff --git a/grade/export/xml/grade_export_xml.php b/grade/export/xml/grade_export_xml.php index 396a044fced..aad24e49968 100644 --- a/grade/export/xml/grade_export_xml.php +++ b/grade/export/xml/grade_export_xml.php @@ -38,7 +38,7 @@ class grade_export_xml extends grade_export { $strgrades = get_string('grades'); /// Calculate file name - $shortname = format_string($this->course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $this->course->id))); + $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id))); $downloadfilename = clean_filename("$shortname $strgrades.xml"); make_temp_directory('gradeexport'); diff --git a/grade/export/xml/index.php b/grade/export/xml/index.php index 3903846d652..d96848922a8 100644 --- a/grade/export/xml/index.php +++ b/grade/export/xml/index.php @@ -28,7 +28,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:export', $context); require_capability('gradeexport/xml:view', $context); diff --git a/grade/grading/form/rubric/rubriceditor.php b/grade/grading/form/rubric/rubriceditor.php index 92cd3be7f35..61d8307f179 100644 --- a/grade/grading/form/rubric/rubriceditor.php +++ b/grade/grading/form/rubric/rubriceditor.php @@ -42,17 +42,6 @@ class MoodleQuickForm_rubriceditor extends HTML_QuickForm_input { parent::HTML_QuickForm_input($elementName, $elementLabel, $attributes); } - /** - * set html for help button - * - * @access public - * @param array $help array of arguments to make a help button - * @param string $function function name to call to get html - */ - public function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/grade/import/csv/index.php b/grade/import/csv/index.php index 74b8c5653fe..7896f397337 100644 --- a/grade/import/csv/index.php +++ b/grade/import/csv/index.php @@ -41,7 +41,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:import', $context); require_capability('gradeimport/csv:view', $context); diff --git a/grade/import/key.php b/grade/import/key.php index 187859d18c2..96d191bf9d0 100644 --- a/grade/import/key.php +++ b/grade/import/key.php @@ -59,7 +59,7 @@ if ($id) { $key->courseid = $course->id; require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('moodle/grade:import', $context); // extra security check diff --git a/grade/import/keymanager.php b/grade/import/keymanager.php index 7d469f6e944..e09dc544fd5 100644 --- a/grade/import/keymanager.php +++ b/grade/import/keymanager.php @@ -35,7 +35,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:import', $context); diff --git a/grade/import/lib.php b/grade/import/lib.php index 3b1c7b02d30..b4cb56f7753 100644 --- a/grade/import/lib.php +++ b/grade/import/lib.php @@ -161,13 +161,13 @@ function grade_import_commit($courseid, $importcode, $importfeedback=true, $verb */ function get_unenrolled_users_in_import($importcode, $courseid) { global $CFG, $DB; - $relatedctxcondition = get_related_contexts_string(get_context_instance(CONTEXT_COURSE, $courseid)); + $relatedctxcondition = get_related_contexts_string(context_course::instance($courseid)); //users with a gradeable role list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr'); //enrolled users - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); list($enrolledsql, $enrolledparams) = get_enrolled_sql($context); $sql = "SELECT giv.id, u.firstname, u.lastname, u.idnumber AS useridnumber, diff --git a/grade/import/xml/fetch.php b/grade/import/xml/fetch.php index 68fd62e84d4..17e1dea0fcb 100644 --- a/grade/import/xml/fetch.php +++ b/grade/import/xml/fetch.php @@ -29,7 +29,7 @@ if (empty($CFG->gradepublishing)) { print_error('gradepubdisable'); } -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('gradeimport/xml:publish', $context); // use the same page parameters as import.php and append &key=sdhakjsahdksahdkjsahksadjksahdkjsadhksa diff --git a/grade/import/xml/import.php b/grade/import/xml/import.php index 3c941f090f1..92c69facb19 100644 --- a/grade/import/xml/import.php +++ b/grade/import/xml/import.php @@ -34,7 +34,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:import', $context); require_capability('gradeimport/xml:view', $context); diff --git a/grade/import/xml/index.php b/grade/import/xml/index.php index 5ce766b4331..de16555494c 100644 --- a/grade/import/xml/index.php +++ b/grade/import/xml/index.php @@ -29,7 +29,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_capability('moodle/grade:import', $context); require_capability('gradeimport/xml:view', $context); diff --git a/grade/lib.php b/grade/lib.php index e5639acd00e..1488d14105e 100644 --- a/grade/lib.php +++ b/grade/lib.php @@ -135,7 +135,7 @@ class graded_users_iterator { return false; } - $coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id); + $coursecontext = context_course::instance($this->course->id); $relatedcontexts = get_related_contexts_string($coursecontext); list($gradebookroles_sql, $params) = @@ -568,7 +568,7 @@ function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=fa function grade_get_plugin_info($courseid, $active_type, $active_plugin) { global $CFG, $SITE; - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); $plugin_info = array(); $count = 0; @@ -1674,7 +1674,7 @@ class grade_seq extends grade_structure { global $USER, $CFG; $this->courseid = $courseid; - $this->context = get_context_instance(CONTEXT_COURSE, $courseid); + $this->context = context_course::instance($courseid); // get course grade tree $top_element = grade_category::fetch_course_tree($courseid, true); @@ -1828,7 +1828,7 @@ class grade_tree extends grade_structure { $this->courseid = $courseid; $this->levels = array(); - $this->context = get_context_instance(CONTEXT_COURSE, $courseid); + $this->context = context_course::instance($courseid); if (!empty($COURSE->id) && $COURSE->id == $this->courseid) { $course = $COURSE; @@ -2459,7 +2459,7 @@ abstract class grade_helper { if (self::$managesetting !== null) { return self::$managesetting; } - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); if (has_capability('moodle/course:update', $context)) { self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course')); } else { @@ -2479,7 +2479,7 @@ abstract class grade_helper { if (self::$gradereports !== null) { return self::$gradereports; } - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); $gradereports = array(); $gradepreferences = array(); foreach (get_plugin_list('gradereport') as $plugin => $plugindir) { @@ -2539,7 +2539,7 @@ abstract class grade_helper { if (self::$scaleinfo !== null) { return self::$scaleinfo; } - if (has_capability('moodle/course:managescales', get_context_instance(CONTEXT_COURSE, $courseid))) { + if (has_capability('moodle/course:managescales', context_course::instance($courseid))) { $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid)); self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view')); } else { @@ -2558,7 +2558,7 @@ abstract class grade_helper { if (self::$outcomeinfo !== null) { return self::$outcomeinfo; } - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); $canmanage = has_capability('moodle/grade:manage', $context); $canupdate = has_capability('moodle/course:update', $context); if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) { @@ -2593,7 +2593,7 @@ abstract class grade_helper { if (self::$edittree !== null) { return self::$edittree; } - if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_COURSE, $courseid))) { + if (has_capability('moodle/grade:manage', context_course::instance($courseid))) { $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid)); self::$edittree = array( 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')), @@ -2613,7 +2613,7 @@ abstract class grade_helper { if (self::$letterinfo !== null) { return self::$letterinfo; } - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); $canmanage = has_capability('moodle/grade:manage', $context); $canmanageletters = has_capability('moodle/grade:manageletters', $context); if ($canmanage || $canmanageletters) { @@ -2638,7 +2638,7 @@ abstract class grade_helper { return self::$importplugins; } $importplugins = array(); - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); if (has_capability('moodle/grade:import', $context)) { foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) { @@ -2676,7 +2676,7 @@ abstract class grade_helper { if (self::$exportplugins !== null) { return self::$exportplugins; } - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); $exportplugins = array(); if (has_capability('moodle/grade:export', $context)) { foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) { diff --git a/grade/report/grader/ajax_callbacks.php b/grade/report/grader/ajax_callbacks.php index 034ef18c2dc..82fc9eb49a4 100644 --- a/grade/report/grader/ajax_callbacks.php +++ b/grade/report/grader/ajax_callbacks.php @@ -33,13 +33,13 @@ $userid = optional_param('userid', false, PARAM_INT); $itemid = optional_param('itemid', false, PARAM_INT); $type = optional_param('type', false, PARAM_ALPHA); $action = optional_param('action', false, PARAM_ALPHA); -$newvalue = optional_param('newvalue', false, PARAM_MULTILANG); +$newvalue = optional_param('newvalue', false, PARAM_TEXT); /// basic access checks if (!$course = $DB->get_record('course', array('id' => $courseid))) { print_error('nocourseid'); } -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_login($course); switch ($action) { diff --git a/grade/report/grader/index.php b/grade/report/grader/index.php index 4549995ad5d..a26537bb19a 100644 --- a/grade/report/grader/index.php +++ b/grade/report/grader/index.php @@ -46,7 +46,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { print_error('nocourseid'); } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('gradereport/grader:view', $context); require_capability('moodle/grade:viewall', $context); diff --git a/grade/report/grader/lib.php b/grade/report/grader/lib.php index d5dafa40a83..54c0af7f0a7 100644 --- a/grade/report/grader/lib.php +++ b/grade/report/grader/lib.php @@ -107,7 +107,7 @@ class grade_report_grader extends grade_report { global $CFG; parent::__construct($courseid, $gpr, $context, $page); - $this->canviewhidden = has_capability('moodle/grade:viewhidden', get_context_instance(CONTEXT_COURSE, $this->course->id)); + $this->canviewhidden = has_capability('moodle/grade:viewhidden', context_course::instance($this->course->id)); // load collapsed settings for this report if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) { diff --git a/grade/report/grader/preferences.php b/grade/report/grader/preferences.php index b4a7bf0f768..6d2d717a137 100644 --- a/grade/report/grader/preferences.php +++ b/grade/report/grader/preferences.php @@ -40,8 +40,8 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$context = context_course::instance($course->id); +$systemcontext = context_system::instance(); require_capability('gradereport/grader:view', $context); require('preferences_form.php'); diff --git a/grade/report/grader/preferences_form.php b/grade/report/grader/preferences_form.php index ff41d39826c..1a9709847f7 100644 --- a/grade/report/grader/preferences_form.php +++ b/grade/report/grader/preferences_form.php @@ -40,8 +40,7 @@ class grader_report_preferences_form extends moodleform { $mform =& $this->_form; $course = $this->_customdata['course']; - $context = get_context_instance(CONTEXT_COURSE, $course->id); - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $context = context_course::instance($course->id); $canviewhidden = has_capability('moodle/grade:viewhidden', $context); diff --git a/grade/report/grader/quickedit_item.php b/grade/report/grader/quickedit_item.php index ac720c21c92..076c5cb11aa 100644 --- a/grade/report/grader/quickedit_item.php +++ b/grade/report/grader/quickedit_item.php @@ -52,7 +52,7 @@ if (!$item = $DB->get_record('grade_items', array('id' => $itemid))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('gradereport/grader:view', $context); require_capability('moodle/grade:viewall', $context); diff --git a/grade/report/grader/tabs.php b/grade/report/grader/tabs.php index 610c594a1d6..d1f97174d49 100644 --- a/grade/report/grader/tabs.php +++ b/grade/report/grader/tabs.php @@ -23,7 +23,7 @@ */ $row = $tabs = array(); - $tabcontext = get_context_instance(CONTEXT_COURSE, $COURSE->id); + $tabcontext = context_course::instance($COURSE->id); $row[] = new tabobject('graderreport', $CFG->wwwroot.'/grade/report/grader/index.php?id='.$courseid, get_string('pluginname', 'gradereport_grader')); diff --git a/grade/report/index.php b/grade/report/index.php index 43aaf66f1bd..5683fcf360d 100644 --- a/grade/report/index.php +++ b/grade/report/index.php @@ -33,7 +33,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { print_error('nocourseid'); } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); /// find all accessible reports $reports = get_plugin_list('gradereport'); // Get all installed reports diff --git a/grade/report/outcomes/index.php b/grade/report/outcomes/index.php index 32068f4508a..06e4fa52979 100644 --- a/grade/report/outcomes/index.php +++ b/grade/report/outcomes/index.php @@ -35,7 +35,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('gradereport/outcomes:view', $context); diff --git a/grade/report/overview/index.php b/grade/report/overview/index.php index a1134c789f4..baae23233da 100644 --- a/grade/report/overview/index.php +++ b/grade/report/overview/index.php @@ -38,8 +38,8 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { } require_login($course); -$context = get_context_instance(CONTEXT_COURSE, $course->id); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$context = context_course::instance($course->id); +$systemcontext = context_system::instance(); require_capability('gradereport/overview:view', $context); if (empty($userid)) { @@ -64,7 +64,7 @@ if (has_capability('moodle/grade:viewall', $systemcontext)) { //ok - can view own course grades $access = true; -} else if (has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_USER, $userid)) and $course->showgrades) { +} else if (has_capability('moodle/grade:viewall', context_user::instance($userid)) and $course->showgrades) { // ok - can view grades of this user- parent most probably $access = true; } diff --git a/grade/report/overview/lib.php b/grade/report/overview/lib.php index 0cd8ff41083..a8f242a5761 100644 --- a/grade/report/overview/lib.php +++ b/grade/report/overview/lib.php @@ -122,7 +122,7 @@ class grade_report_overview extends grade_report { continue; } - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); if (!$course->visible && !has_capability('moodle/course:viewhiddencourses', $coursecontext)) { // The course is hidden and the user isn't allowed to see it diff --git a/grade/report/user/index.php b/grade/report/user/index.php index e15c4fbdb22..a509ca5b944 100644 --- a/grade/report/user/index.php +++ b/grade/report/user/index.php @@ -39,7 +39,7 @@ if (!$course = $DB->get_record('course', array('id' => $courseid))) { require_login($course); $PAGE->set_pagelayout('report'); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); require_capability('gradereport/user:view', $context); if (empty($userid)) { @@ -60,7 +60,7 @@ if (has_capability('moodle/grade:viewall', $context)) { //ok - can view own grades $access = true; -} else if (has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_USER, $userid)) and $course->showgrades) { +} else if (has_capability('moodle/grade:viewall', context_user::instance($userid)) and $course->showgrades) { // ok - can view grades of this user- parent most probably $access = true; } diff --git a/grade/report/user/lib.php b/grade/report/user/lib.php index 915aefd2525..b984a85e755 100644 --- a/grade/report/user/lib.php +++ b/grade/report/user/lib.php @@ -203,7 +203,7 @@ class grade_report_user extends grade_report { $this->tabledata = array(); - $this->canviewhidden = has_capability('moodle/grade:viewhidden', get_context_instance(CONTEXT_COURSE, $this->courseid)); + $this->canviewhidden = has_capability('moodle/grade:viewhidden', context_course::instance($this->courseid)); // get the user (for full name) $this->user = $DB->get_record('user', array('id' => $userid)); @@ -870,7 +870,7 @@ function grade_report_user_profilereport($course, $user) { global $OUTPUT; if (!empty($course->showgrades)) { - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); //first make sure we have proper final grades - this must be done before constructing of the grade tree grade_regrade_final_grades($course->id); diff --git a/group/autogroup_form.php b/group/autogroup_form.php index 5b39965de68..36343b52573 100644 --- a/group/autogroup_form.php +++ b/group/autogroup_form.php @@ -102,7 +102,7 @@ class autogroup_form extends moodleform { $mform->addElement('text', 'namingscheme', get_string('namingscheme', 'group')); $mform->addHelpButton('namingscheme', 'namingscheme', 'group'); $mform->addRule('namingscheme', get_string('required'), 'required', null, 'client'); - $mform->setType('namingscheme', PARAM_MULTILANG); + $mform->setType('namingscheme', PARAM_TEXT); // there must not be duplicate group names in course $template = get_string('grouptemplate', 'group'); $gname = groups_parse_name($template, 0); @@ -123,7 +123,7 @@ class autogroup_form extends moodleform { } $mform->addElement('text', 'groupingname', get_string('groupingname', 'group'), $options); - $mform->setType('groupingname', PARAM_MULTILANG); + $mform->setType('groupingname', PARAM_TEXT); $mform->disabledIf('groupingname', 'grouping', 'noteq', '-1'); $mform->addElement('hidden','courseid'); diff --git a/group/externallib.php b/group/externallib.php index 39db0871a1f..4e0ad27533b 100644 --- a/group/externallib.php +++ b/group/externallib.php @@ -311,7 +311,7 @@ class core_group_external extends external_api { foreach ($params['groupids'] as $groupid) { // validate params - $groupid = validate_param($groupid, PARAM_INTEGER); + $groupid = validate_param($groupid, PARAM_INT); if (!$group = groups_get_group($groupid, 'id, courseid', IGNORE_MISSING)) { // silently ignore attempts to delete nonexisting groups continue; diff --git a/group/group_form.php b/group/group_form.php index 18fe0990b25..98f2c9dda13 100644 --- a/group/group_form.php +++ b/group/group_form.php @@ -50,7 +50,7 @@ class group_form extends moodleform { $mform->addElement('text','name', get_string('groupname', 'group'),'maxlength="254" size="50"'); $mform->addRule('name', get_string('required'), 'required', null, 'client'); - $mform->setType('name', PARAM_MULTILANG); + $mform->setType('name', PARAM_TEXT); $mform->addElement('text','idnumber', get_string('idnumbergroup'), 'maxlength="100" size="10"'); $mform->addHelpButton('idnumber', 'idnumbergroup'); diff --git a/group/grouping_form.php b/group/grouping_form.php index 63248ab1805..1f15bc78b5f 100644 --- a/group/grouping_form.php +++ b/group/grouping_form.php @@ -52,7 +52,7 @@ class grouping_form extends moodleform { $mform->addElement('text','name', get_string('groupingname', 'group'),'maxlength="254" size="50"'); $mform->addRule('name', get_string('required'), 'required', null, 'server'); - $mform->setType('name', PARAM_MULTILANG); + $mform->setType('name', PARAM_TEXT); $mform->addElement('text','idnumber', get_string('idnumbergrouping'), 'maxlength="100" size="10"'); $mform->addHelpButton('idnumber', 'idnumbergrouping'); diff --git a/install/lang/ga/langconfig.php b/install/lang/ga/langconfig.php index cd9ab387d8e..9cea86ca30f 100644 --- a/install/lang/ga/langconfig.php +++ b/install/lang/ga/langconfig.php @@ -32,4 +32,4 @@ defined('MOODLE_INTERNAL') || die(); $string['parentlanguage'] = ''; $string['thisdirection'] = 'ltr'; -$string['thislanguage'] = 'Béarla'; +$string['thislanguage'] = 'Gaeilge'; diff --git a/admin/tool/unittest/db/access.php b/install/lang/sw/langconfig.php similarity index 56% rename from admin/tool/unittest/db/access.php rename to install/lang/sw/langconfig.php index 73d07dc1f6f..2c937318f36 100644 --- a/admin/tool/unittest/db/access.php +++ b/install/lang/sw/langconfig.php @@ -1,4 +1,5 @@ . /** - * Unitest caps. + * Automatically generated strings for Moodle installer * - * @package tool_unittest - * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * Do not edit this file manually! It contains just a subset of strings + * needed during the very first steps of installation. This file was + * generated automatically by export-installer.php (which is part of AMOS + * {@link http://docs.moodle.org/dev/Languages/AMOS}) using the + * list of strings defined in /install/stringnames.txt. + * + * @package installer + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -$capabilities = array( - - // Note: do not add managers here, unittests are dangerous and not intended for production sites!!! - - 'tool/unittest:execute' => array( - 'riskbitmask' => RISK_DATALOSS, - 'captype' => 'write', // it writes into database, really! - 'contextlevel' => CONTEXT_SYSTEM, - 'archetypes' => array( - ) - ) -); +$string['thisdirection'] = 'ltr'; +$string['thislanguage'] = 'Kiswahili'; diff --git a/lang/en/admin.php b/lang/en/admin.php index 30253fd9911..9c143985d96 100644 --- a/lang/en/admin.php +++ b/lang/en/admin.php @@ -253,6 +253,7 @@ $string['configminpasswordlength'] = 'Passwords must be at least these many char $string['configminpasswordlower'] = 'Passwords must have at least these many lower case letters.'; $string['configminpasswordnonalphanum'] = 'Passwords must have at least these many non-alphanumeric characters.'; $string['configminpasswordupper'] = 'Passwords must have at least these many upper case letters.'; +$string['configmodchooserdefault'] = 'Should the activity chooser be presented to users by default?'; $string['configmycoursesperpage'] = 'Maximum number of courses to display in any list of a user\'s own courses'; $string['configmymoodleredirect'] = 'This setting forces redirects to /my on login for non-admins and replaces the top level site navigation with /my'; $string['configmypagelocked'] = 'This setting prevents the default page from being edited by any non-admins'; @@ -339,7 +340,6 @@ $string['configvariables'] = 'Variables'; $string['configverifychangedemail'] = 'Enables verification of changed email addresses using allowed and denied email domains settings. If this setting is disabled the domains are enforced only when creating new users.'; $string['configvisiblecourses'] = 'Display courses in hidden categories normally'; $string['configwarning'] = 'Be careful modifying these settings - strange values could cause problems.'; -$string['configxmlstrictheaders'] = 'Set to on, each page will be generated using XML http headers and prolog, so browsers will show XHTML errors inline. This is only useful for developers.'; $string['configyuicomboloading'] = 'This options enables combined file loading optimisation for YUI libraries. This setting should be enabled on production sites for performance reasons.'; $string['configzip'] = 'Indicate the location of your zip program (Unix only, optional). If specified, this will be used to create zip archives on the server. If you leave this blank, then Moodle will use internal routines.'; $string['confirmation'] = 'Confirmation'; @@ -679,6 +679,7 @@ $string['mnetrestore_extusers_admin'] = 'Note: This backup file $string['mnetrestore_extusers_mismatch'] = 'Note: This backup file apparently originates from a different Moodle installation and contains remote Moodle Network user accounts that may fail to restore. This operation is unsupported. If you are certain that it was created on this Moodle installation, or you can ensure that all the needed Moodle Network Hosts are configured, you may want to still try the restore.'; $string['mnetrestore_extusers_noadmin'] = 'Note: This backup file seems to come from a different Moodle installation and contains remote Moodle Network user accounts. You are not allowed to execute this type of restore. Contact the administrator of the site or, alternatively, restore this course without any user information (modules, files...)'; $string['mnetrestore_extusers_switchuserauth'] = 'Remote Moodle Network user {$a->username} (coming from {$a->mnethosturl}) switched to local {$a->auth} authenticated user.'; +$string['modchooserdefault'] = 'Activity chooser default'; $string['modeditdefaults'] = 'Default values for activity settings'; $string['modsettings'] = 'Manage activities'; $string['modulesecurity'] = 'Module security'; @@ -1061,6 +1062,5 @@ $string['warningiconvbuggy'] = 'Your version of the iconv library does not suppo $string['webproxy'] = 'Web proxy'; $string['webproxyinfo'] = 'Fill in following options if your Moodle server can not access internet directly. Internet access is required for download of environment data, language packs, RSS feeds, timezones, etc.
    PHP cURL extension is highly recommended.'; $string['xmlrpcrecommended'] = 'The xmlrpc extension is needed for hub communication, and useful for web services and Moodle networking'; -$string['xmlstrictheaders'] = 'XML strict headers'; $string['yuicomboloading'] = 'YUI combo loading'; $string['ziprequired'] = 'The Zip PHP extension is now required by Moodle, info-ZIP binaries or PclZip library are not used anymore.'; diff --git a/lang/en/condition.php b/lang/en/condition.php index 5851e6e1f61..a888d8c7747 100644 --- a/lang/en/condition.php +++ b/lang/en/condition.php @@ -47,7 +47,10 @@ $string['completion_fail'] = 'must be complete with fail grade'; $string['completion_incomplete'] = 'must not be marked complete'; $string['completion_pass'] = 'must be complete with pass grade'; $string['configenableavailability'] = 'When enabled, this lets you set conditions (based on date, grade, or completion) that control whether an activity or resource can be accessed.'; +$string['contains'] = 'contains'; +$string['doesnotcontain'] = 'doesn\'t contain'; $string['enableavailability'] = 'Enable conditional access'; +$string['endswith'] = 'ends with'; $string['fielddeclaredmultipletimes'] = 'You can not declare the same field more than once per activity.'; $string['grade_atleast'] = 'must be at least'; $string['gradecondition'] = 'Grade condition'; @@ -62,6 +65,9 @@ $string['grade_upto'] = 'and less than'; $string['gradeitembutnolimits'] = 'You must enter an upper or lower limit, or both.'; $string['gradelimitsbutnoitem'] = 'You must choose a grade item.'; $string['gradesmustbenumeric'] = 'The minimum and maximum grades must be numeric (or blank).'; +$string['isempty'] = 'is empty'; +$string['isequalto'] = 'is equal to'; +$string['isnotempty'] = 'is not empty'; $string['none'] = '(none)'; $string['notavailableyet'] = 'Not available yet'; $string['requires_completion_0'] = 'Not available unless the activity {$a} is incomplete.'; @@ -76,13 +82,20 @@ $string['requires_grade_any'] = 'Not available until you have a grade in modname}\' activity could not be duplicated because the {$a->modtype} module does not support backup and restore.'; $string['duplicateparaminsql'] = 'ERROR: duplicate parameter name in query'; $string['duplicaterolename'] = 'There is already a role with this name!'; $string['duplicateroleshortname'] = 'There is already a role with this short name!'; diff --git a/lang/en/form.php b/lang/en/form.php index fbd8c9d46b5..d55667d4b3e 100644 --- a/lang/en/form.php +++ b/lang/en/form.php @@ -30,6 +30,7 @@ $string['display'] = 'Display'; $string['err_alphanumeric'] = 'You must enter only letters or numbers here.'; $string['err_email'] = 'You must enter a valid email address here.'; $string['err_lettersonly'] = 'You must enter only letters here.'; +$string['err_maxfiles'] = 'You must not attach more than {$a} files here.'; $string['err_maxlength'] = 'You must enter not more than {$a->format} characters here.'; $string['err_minlength'] = 'You must enter at least {$a->format} characters here.'; $string['err_nonzero'] = 'You must enter a number not starting with a 0 here.'; diff --git a/lang/en/question.php b/lang/en/question.php index d0cf1a45189..dfa1aeb2df3 100644 --- a/lang/en/question.php +++ b/lang/en/question.php @@ -230,6 +230,8 @@ $string['novirtualquestiontype'] = 'No virtual question type for question type { $string['numqas'] = 'No. question attempts'; $string['numquestions'] = 'No. questions'; $string['numquestionsandhidden'] = '{$a->numquestions} (+{$a->numhidden} hidden)'; +$string['orphanedquestionscategory'] = 'Questions saved from deleted categories'; +$string['orphanedquestionscategoryinfo'] = 'Occasionally, typically due to old software bugs, questions can remain in the database even though the corresponding question category has been deleted. Of course, this should not happen, it has happened in the past on this site. This category has been created automatically, and the orphaned questions moved here so that you can manage them. Note that any images or media files used by these questions have probably been lost.'; $string['page-question-x'] = 'Any question page'; $string['page-question-edit'] = 'Question editing page'; $string['page-question-category'] = 'Question category page'; diff --git a/lib/accesslib.php b/lib/accesslib.php index c1125a1db41..a75ce2f05fe 100644 --- a/lib/accesslib.php +++ b/lib/accesslib.php @@ -216,8 +216,8 @@ $ACCESSLIB_PRIVATE->capabilities = null; // detailed information about th * @return void */ function accesslib_clear_all_caches_for_unit_testing() { - global $UNITTEST, $USER; - if (empty($UNITTEST->running) and !PHPUNIT_TEST) { + global $USER; + if (!PHPUNIT_TEST) { throw new coding_exception('You must not call clear_all_caches outside of unit tests.'); } diff --git a/lib/adminlib.php b/lib/adminlib.php index 0626e662581..ece35ca87c3 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -3243,7 +3243,7 @@ class admin_setting_sitesettext extends admin_setting_configtext { * @return mixed true or message string */ public function validate($data) { - $cleaned = clean_param($data, PARAM_MULTILANG); + $cleaned = clean_param($data, PARAM_TEXT); if ($cleaned === '') { return get_string('required'); } diff --git a/lib/alfresco/README_MOODLE.txt b/lib/alfresco/README_MOODLE.txt index 308e3c3b0de..83179f07fdb 100644 --- a/lib/alfresco/README_MOODLE.txt +++ b/lib/alfresco/README_MOODLE.txt @@ -1,17 +1,46 @@ - == CHANGELOG == -1. Rename class name , see Service/Repository.php & Service/WebService/AlfrescoWebService.php -2. Change library path name -3. In Alfresco_Repository class construct function, set _port to 80 if it is not specified -4. MDL-20876 - replaced deprecated split() with explode() -== Alfresco PHP Libarary == +1. Rename class name 'Repository' to 'Alfresco_Repository' in + - Service/Repository.php + - Service/Webservice/AlfrescoWebService.php + +2. Update path for require_once() in + - Service/Logger/Logger.php + - Service/WebService/WebServiceFactory.php + - Service/ContentData.php + - Service/Functions.php + - Service/Node.php + - Service/Repository.php + - Service/Session.php + - Service/SpacesStore.php + - Service/Store.php + +3. In Alfresco_Repository::__construct(), set _port to 80 when not specified + + @@ -46,7 +46,11 @@ class Alfresco_Repository extends BaseObject + $this->_connectionUrl = $connectionUrl; + $parts = parse_url($connectionUrl); + $this->_host = $parts["host"]; + - $this->_port = $parts["port"]; + + if (empty($parts["port"])) { + + $this->_port = 80; + + } else { + + $this->_port = $parts["port"]; + + } + +4. Reapply changes from MDL-20876 Fix depreacted split() calls (bed733c) + +5. Fix strict standards in Service/WebService/AlfrescoWebService.php + - AlfrescoWebService::__soapCall() arguments do not match SoapClient::__soapCall() + - AlfrescoWebService::__doRequest() arguments do not match SoapClient::__soapCall() + +== Alfresco PHP Library == Installation and developer documentation for the Alfresco PHP Library can be found on the Alfresco Wiki. -Get the source from http://svn.alfresco.com/repos/alfresco-open-mirror/alfresco/HEAD/root/modules/php-sdk +Get the source from http://code.google.com/p/alfresco-php-sdk/ == Documentation Links == -Installation Instructions - http://wiki.alfresco.com/wiki/Alfresco_PHP_Library_Installation_Instructions -MediaWiki Integration Installation Instructions - http://wiki.alfresco.com/wiki/Alfresco_MediaWiki_Installation_Instructions -PHP API Documentation - http://wiki.alfresco.com/wiki/Alfresco_PHP_API +Installation Instructions - http://code.google.com/p/alfresco-php-sdk/wiki/AlfrescoPHPLibraryInstallationInstructions +MediaWiki Integration Installation Instructions - http://code.google.com/p/alfresco-php-sdk/wiki/AlfrescoMediaWikiInstallationInstructions +PHP API Documentation - http://code.google.com/p/alfresco-php-sdk/wiki/AlfrescoPHPAPI \ No newline at end of file diff --git a/lib/alfresco/Service/Association.php b/lib/alfresco/Service/Association.php index 74c96f5eab9..f7349a8fd00 100644 --- a/lib/alfresco/Service/Association.php +++ b/lib/alfresco/Service/Association.php @@ -1,57 +1,51 @@ -_from = $from; - $this->_to = $to; - $this->_type = $type; - } - - public function getFrom() - { - return $this->_from; - } - - public function getTo() - { - return $this->_to; - } - - public function getType() - { - return $this->_type; - } -} - -?> +. + */ + +class Association extends BaseObject +{ + private $_from; + private $_to; + private $_type; + + public function __construct($from, $to, $type) + { + $this->_from = $from; + $this->_to = $to; + $this->_type = $type; + } + + public function getFrom() + { + return $this->_from; + } + + public function getTo() + { + return $this->_to; + } + + public function getType() + { + return $this->_type; + } +} + +?> diff --git a/lib/alfresco/Service/BaseObject.php b/lib/alfresco/Service/BaseObject.php index db0d71e6ef2..427b9e1d3ae 100644 --- a/lib/alfresco/Service/BaseObject.php +++ b/lib/alfresco/Service/BaseObject.php @@ -1,147 +1,141 @@ -$methodName(); - } - } - - public function __set($name, $value) - { - $methodName = $name; - $methodName[0] = strtoupper($methodName[0]); - $methodName = 'set' . $methodName; - - if (method_exists($this, $methodName) == true) - { - return $this->$methodName($value); - } - } - - protected function resultSetToNodes($session, $store, $resultSet) - { - $return = array(); - if (isset($resultSet->rows) == true) - { - if (is_array($resultSet->rows) == true) - { - foreach($resultSet->rows as $row) - { - $id = $row->node->id; - $return[] = $session->getNode($store, $id); - } - } - else - { - $id = $resultSet->rows->node->id; - $return[] = $session->getNode($store, $id); - } - } - - return $return; - } - - protected function resultSetToMap($resultSet) - { - $return = array(); - if (isset($resultSet->rows) == true) - { - if (is_array($resultSet->rows) == true) - { - foreach($resultSet->rows as $row) - { - $return[] = $this->columnsToMap($row->columns); - } - } - else - { - $return[] = $this->columnsToMap($resultSet->rows->columns); - } - - } - - return $return; - } - - private function columnsToMap($columns) - { - $return = array(); - - foreach ($columns as $column) - { - $return[$column->name] = $column->value; - } - - return $return; - } - - protected function remove_array_value($value, &$array) - { - if ($array != null) - { - if (in_array($value, $array) == true) - { - foreach ($array as $index=>$value2) - { - if ($value == $value2) - { - unset($array[$index]); - } - } - } - } - } - - protected function isContentData($value) - { - $index = strpos($value, "contentUrl="); - if ($index === false) - { - return false; - } - else - { - if ($index == 0) - { - return true; - } - else - { - return false; - } - } - } -} +. + */ + +class BaseObject +{ + public function __get($name) + { + $methodName = $name; + $methodName[0] = strtoupper($methodName[0]); + $methodName = 'get' . $methodName; + + if (method_exists($this, $methodName) == true) + { + return $this->$methodName(); + } + } + + public function __set($name, $value) + { + $methodName = $name; + $methodName[0] = strtoupper($methodName[0]); + $methodName = 'set' . $methodName; + + if (method_exists($this, $methodName) == true) + { + return $this->$methodName($value); + } + } + + protected function resultSetToNodes($session, $store, $resultSet) + { + $return = array(); + if (isset($resultSet->rows) == true) + { + if (is_array($resultSet->rows) == true) + { + foreach($resultSet->rows as $row) + { + $id = $row->node->id; + $return[] = $session->getNode($store, $id); + } + } + else + { + $id = $resultSet->rows->node->id; + $return[] = $session->getNode($store, $id); + } + } + + return $return; + } + + protected function resultSetToMap($resultSet) + { + $return = array(); + if (isset($resultSet->rows) == true) + { + if (is_array($resultSet->rows) == true) + { + foreach($resultSet->rows as $row) + { + $return[] = $this->columnsToMap($row->columns); + } + } + else + { + $return[] = $this->columnsToMap($resultSet->rows->columns); + } + + } + + return $return; + } + + private function columnsToMap($columns) + { + $return = array(); + + foreach ($columns as $column) + { + $return[$column->name] = $column->value; + } + + return $return; + } + + protected function remove_array_value($value, &$array) + { + if ($array != null) + { + if (in_array($value, $array) == true) + { + foreach ($array as $index=>$value2) + { + if ($value == $value2) + { + unset($array[$index]); + } + } + } + } + } + + protected function isContentData($value) + { + $index = strpos($value, "contentUrl="); + if ($index === false) + { + return false; + } + else + { + if ($index == 0) + { + return true; + } + else + { + return false; + } + } + } +} ?> \ No newline at end of file diff --git a/lib/alfresco/Service/ChildAssociation.php b/lib/alfresco/Service/ChildAssociation.php index b9f4adc3af8..41c3dad5257 100644 --- a/lib/alfresco/Service/ChildAssociation.php +++ b/lib/alfresco/Service/ChildAssociation.php @@ -1,76 +1,70 @@ -_parent = $parent; - $this->_child = $child; - $this->_type = $type; - $this->_name = $name; - $this->_isPrimary = $isPrimary; - $this->_nthSibling = $nthSibling; - } - - public function getParent() - { - return $this->_parent; - } - - public function getChild() - { - return $this->_child; - } - - public function getType() - { - return $this->_type; - } - - public function getName() - { - return $this->_name; - } - - public function getIsPrimary() - { - return $this->_isPrimary; - } - - public function getNthSibling() - { - return $this->_nthSibling; - } -} -?> +. + */ + +class ChildAssociation extends BaseObject +{ + private $_parent; + private $_child; + private $_type; + private $_name; + private $_isPrimary; + private $_nthSibling; + + public function __construct($parent, $child, $type, $name, $isPrimary=false, $nthSibling=0) + { + $this->_parent = $parent; + $this->_child = $child; + $this->_type = $type; + $this->_name = $name; + $this->_isPrimary = $isPrimary; + $this->_nthSibling = $nthSibling; + } + + public function getParent() + { + return $this->_parent; + } + + public function getChild() + { + return $this->_child; + } + + public function getType() + { + return $this->_type; + } + + public function getName() + { + return $this->_name; + } + + public function getIsPrimary() + { + return $this->_isPrimary; + } + + public function getNthSibling() + { + return $this->_nthSibling; + } +} +?> diff --git a/lib/alfresco/Service/ContentData.php b/lib/alfresco/Service/ContentData.php index 25a3d78325d..a2a34d90ded 100644 --- a/lib/alfresco/Service/ContentData.php +++ b/lib/alfresco/Service/ContentData.php @@ -1,292 +1,285 @@ -libdir."/alfresco/Service/Functions.php"); - -class ContentData extends BaseObject -{ - private $_isPopulated = false; - private $_isDirty = false; - - private $_node; - private $_property; - - private $_mimetype; - private $_size; - private $_encoding; - private $_url; - private $_newContent; - private $_newFileContent; - - public function __construct($node, $property, $mimetype=null, $encoding=null, $size=-1) - { - $this->_node = $node; - $this->_property = $property; - $this->_mimetype = $mimetype; - $this->_encoding = $encoding; - if ($size != -1) - { - $this->size = $size; - } - $this->_isPopulated = false; - } - - public function setPropertyDetails($node, $property) - { - $this->_node = $node; - $this->_property = $property; - } - - public function __toString() - { - $this->populateContentData(); - return "mimetype=".$this->mimetype."|encoding=".$this->encoding."|size=".$this->size; - } - - public function getNode() - { - return $this->_node; - } - - public function getProperty() - { - return $this->_property; - } - - public function getIsDirty() - { - return $this->_isDirty; - } - - public function getMimetype() - { - $this->populateContentData(); - return $this->_mimetype; - } - - public function setMimetype($mimetype) - { - $this->populateContentData(); - $this->_mimetype = $mimetype; - } - - public function getSize() - { - $this->populateContentData(); - return $this->_size; - } - - public function getEncoding() - { - $this->populateContentData(); - return $this->_encoding; - } - - public function setEncoding($encoding) - { - $this->populateContentData(); - $this->_encoding = $encoding; - } - - public function getUrl() - { - // TODO what should be returned if the content has been updated?? - - $this->populateContentData(); - $result = null; - if ($this->_url != null) - { - $result = $this->_url."?ticket=".$this->_node->session->ticket; - } - return $result; - } - - public function getGuestUrl() - { - // TODO what should be returned if the content has been updated?? - - $this->populateContentData(); - $result = null; - if ($this->_url != null) - { - $result = $this->_url."?guest=true"; - } - return $result; - } - - public function getContent() - { - $this->populateContentData(); - - $result = null; - if ($this->_isDirty == true) - { - if ($this->_newFileContent != null) - { - $handle = fopen($this->_newFileContent, "rb"); - $result = stream_get_contents($handle); - fclose($handle); - } - else if ($this->_newContent != null) - { - $result = $this->_newContent; - } - } - else - { - if ($this->getUrl() != null) - { - $handle = fopen($this->getUrl(), "rb"); - $result = stream_get_contents($handle); - fclose($handle); - } - } - return $result; - } - - public function setContent($content) - { - $this->populateContentData(); - $this->_isDirty = true; - $this->_newContent = $content; - } - - public function writeContentFromFile($fileName) - { - $this->populateContentData(); - $this->_isDirty = true; - $this->_newFileContent = $fileName; - } - - public function readContentToFile($fileName) - { - $handle = fopen($fileName, "wb"); - fwrite($handle, $this->getContent()); - fclose($handle); - } - - public function onBeforeSave(&$statements, $where) - { - if ($this->_isDirty == true) - { - // Check mimetype has been set - if ($this->_mimetype == null) - { - throw new Exception("A mime type for the content property ".$this->_property." on node ".$this->_node->__toString()." must be set"); - } - - // If a file has been specified then read content from there - //$content = null; - if ($this->_newFileContent != null) - { - // Upload the content to the repository - $contentData = upload_file($this->node->session, $this->_newFileContent, $this->_mimetype, $this->_encoding); - - // Set the content property value - $this->addStatement( - $statements, - "update", - array("property" => array( - "name" => $this->property, - "isMultiValue" => false, - "value" => $contentData)) + $where); - } - else - { - // Add the writeContent statement - $this->addStatement( - $statements, - "writeContent", - array( - "property" => $this->_property, - "content" => $this->_newContent, - "format" => array( - "mimetype" => $this->_mimetype, - "encoding" => $this->_encoding)) + - $where); - } - } - } - - public function onAfterSave() - { - $this->_isDirty = false; - $this->_isPopulated = false; - $this->_mimetype = null; - $this->__size = null; - $this->__encoding = null; - $this->__url = null; - $this->__newContent = null; - } - - private function populateContentData() - { - //echo "isPopulated:".$this->_isPopulated."; node:".$this->_node."; property:".$this->_property."
    "; - if ($this->_isPopulated == false && $this->_node != null && $this->_property != null && $this->_node->isNewNode == false) - { - $result = $this->_node->session->contentService->read( array( - "items" => array( - "nodes" => array( - "store" => $this->_node->store->__toArray(), - "uuid" => $this->_node->id)), - "property" => $this->_property) ); - if (isset($result->content) == true) - { - if (isset($result->content->length) == true) - { - $this->_size = $result->content->length; - } - if (isset($result->content->format->mimetype) == true) - { - $this->_mimetype = $result->content->format->mimetype; - } - if (isset($result->content->format->encoding) == true) - { - $this->_encoding = $result->content->format->encoding; - } - if (isset($result->content->url) == true) - { - $this->_url = $result->content->url; - } - } - - $this->_isPopulated = true; - } - } - - private function addStatement(&$statements, $statement, $body) - { - $result = array(); - if (array_key_exists($statement, $statements) == true) - { - $result = $statements[$statement]; - } - $result[] = $body; - $statements[$statement] = $result; - } -} -?> +. + */ + +require_once($CFG->libdir."/alfresco/Service/Functions.php"); + +class ContentData extends BaseObject +{ + private $_isPopulated = false; + private $_isDirty = false; + + private $_node; + private $_property; + + private $_mimetype; + private $_size; + private $_encoding; + private $_url; + private $_newContent; + private $_newFileContent; + + public function __construct($node, $property, $mimetype=null, $encoding=null, $size=-1) + { + $this->_node = $node; + $this->_property = $property; + $this->_mimetype = $mimetype; + $this->_encoding = $encoding; + if ($size != -1) + { + $this->size = $size; + } + $this->_isPopulated = false; + } + + public function setPropertyDetails($node, $property) + { + $this->_node = $node; + $this->_property = $property; + } + + public function __toString() + { + $this->populateContentData(); + return "mimetype=".$this->mimetype."|encoding=".$this->encoding."|size=".$this->size; + } + + public function getNode() + { + return $this->_node; + } + + public function getProperty() + { + return $this->_property; + } + + public function getIsDirty() + { + return $this->_isDirty; + } + + public function getMimetype() + { + $this->populateContentData(); + return $this->_mimetype; + } + + public function setMimetype($mimetype) + { + $this->populateContentData(); + $this->_mimetype = $mimetype; + } + + public function getSize() + { + $this->populateContentData(); + return $this->_size; + } + + public function getEncoding() + { + $this->populateContentData(); + return $this->_encoding; + } + + public function setEncoding($encoding) + { + $this->populateContentData(); + $this->_encoding = $encoding; + } + + public function getUrl() + { + // TODO what should be returned if the content has been updated?? + + $this->populateContentData(); + $result = null; + if ($this->_url != null) + { + $result = $this->_url."?ticket=".$this->_node->session->ticket; + } + return $result; + } + + public function getGuestUrl() + { + // TODO what should be returned if the content has been updated?? + + $this->populateContentData(); + $result = null; + if ($this->_url != null) + { + $result = $this->_url."?guest=true"; + } + return $result; + } + + public function getContent() + { + $this->populateContentData(); + + $result = null; + if ($this->_isDirty == true) + { + if ($this->_newFileContent != null) + { + $handle = fopen($this->_newFileContent, "rb"); + $result = stream_get_contents($handle); + fclose($handle); + } + else if ($this->_newContent != null) + { + $result = $this->_newContent; + } + } + else + { + if ($this->getUrl() != null) + { + $handle = fopen($this->getUrl(), "rb"); + $result = stream_get_contents($handle); + fclose($handle); + } + } + return $result; + } + + public function setContent($content) + { + $this->populateContentData(); + $this->_isDirty = true; + $this->_newContent = $content; + } + + public function writeContentFromFile($fileName) + { + $this->populateContentData(); + $this->_isDirty = true; + $this->_newFileContent = $fileName; + } + + public function readContentToFile($fileName) + { + $handle = fopen($fileName, "wb"); + fwrite($handle, $this->getContent()); + fclose($handle); + } + + public function onBeforeSave(&$statements, $where) + { + if ($this->_isDirty == true) + { + // Check mimetype has been set + if ($this->_mimetype == null) + { + throw new Exception("A mime type for the content property ".$this->_property." on node ".$this->_node->__toString()." must be set"); + } + + // If a file has been specified then read content from there + //$content = null; + if ($this->_newFileContent != null) + { + // Upload the content to the repository + $contentData = upload_file($this->node->session, $this->_newFileContent, $this->_mimetype, $this->_encoding); + + // Set the content property value + $this->addStatement( + $statements, + "update", + array("property" => array( + "name" => $this->property, + "isMultiValue" => false, + "value" => $contentData)) + $where); + } + else + { + // Add the writeContent statement + $this->addStatement( + $statements, + "writeContent", + array( + "property" => $this->_property, + "content" => $this->_newContent, + "format" => array( + "mimetype" => $this->_mimetype, + "encoding" => $this->_encoding)) + + $where); + } + } + } + + public function onAfterSave() + { + $this->_isDirty = false; + $this->_isPopulated = false; + $this->_mimetype = null; + $this->__size = null; + $this->__encoding = null; + $this->__url = null; + $this->__newContent = null; + } + + private function populateContentData() + { + //echo "isPopulated:".$this->_isPopulated."; node:".$this->_node."; property:".$this->_property."
    "; + if ($this->_isPopulated == false && $this->_node != null && $this->_property != null && $this->_node->isNewNode == false) + { + $result = $this->_node->session->contentService->read( array( + "items" => array( + "nodes" => array( + "store" => $this->_node->store->__toArray(), + "uuid" => $this->_node->id)), + "property" => $this->_property) ); + if (isset($result->content) == true) + { + if (isset($result->content->length) == true) + { + $this->_size = $result->content->length; + } + if (isset($result->content->format->mimetype) == true) + { + $this->_mimetype = $result->content->format->mimetype; + } + if (isset($result->content->format->encoding) == true) + { + $this->_encoding = $result->content->format->encoding; + } + if (isset($result->content->url) == true) + { + $this->_url = $result->content->url; + } + } + + $this->_isPopulated = true; + } + } + + private function addStatement(&$statements, $statement, $body) + { + $result = array(); + if (array_key_exists($statement, $statements) == true) + { + $result = $statements[$statement]; + } + $result[] = $body; + $statements[$statement] = $result; + } +} +?> diff --git a/lib/alfresco/Service/Functions.php b/lib/alfresco/Service/Functions.php index fdc9b461883..d94e2412139 100644 --- a/lib/alfresco/Service/Functions.php +++ b/lib/alfresco/Service/Functions.php @@ -1,115 +1,108 @@ -libdir."/alfresco/Service/Repository.php"); - require_once($CFG->libdir."/alfresco/Service/Session.php"); - - /** - * Uploads a file into content store and returns the content data string which - * can be used to populate a content property. - * - * @param $session the session - * @param $filePath the file location - * @return String the content data that can be used to update the content property - */ - function upload_file($session, $filePath, $mimetype=null, $encoding=null) - { - $result = null; - - // Check for the existance of the file - if (file_exists($filePath) == false) - { - throw new Exception("The file ".$filePath."does no exist."); - } - - // Get the file name and size - $fileName = basename($filePath); - $fileSize = filesize($filePath); - - // Get the address and the - $host = $session->repository->host; - $port = $session->repository->port; - - // Get the IP address for the target host - $address = gethostbyname($host); - - // Create a TCP/IP socket - $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); - if ($socket === false) - { - throw new Exception ("socket_create() failed: reason: " . socket_strerror(socket_last_error())); - } - - // Connect the socket to the repository - $result = socket_connect($socket, $address, $port); - if ($result === false) - { - throw new Exception("socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket))); - } - - // Write the request header onto the socket - $url = "/alfresco/upload/".urlencode($fileName)."?ticket=".$session->ticket; - if ($mimetype != null) - { - // Add mimetype if specified - $url .= "&mimetype=".$mimetype; - } - if ($encoding != null) - { - // Add encoding if specified - $url .= "&encoding=".$encoding; - } - $in = "PUT ".$url." HTTP/1.1\r\n". - "Content-Length: ".$fileSize."\r\n". - "Host: ".$address.":".$port."\r\n". - "Connection: Keep-Alive\r\n". - "\r\n"; - socket_write($socket, $in, strlen($in)); - - // Write the content found in the file onto the socket - $handle = fopen($filePath, "r"); - while (feof($handle) == false) - { - $content = fread($handle, 1024); - socket_write($socket, $content, strlen($content)); - } - fclose($handle); - - // Read the response - $recv = socket_read ($socket, 2048, PHP_BINARY_READ); - $index = strpos($recv, "contentUrl"); - if ($index !== false) - { - $result = substr($recv, $index); - } - - // Close the socket - socket_close($socket); - - return $result; - } -?> +. + */ + + require_once($CFG->libdir."/alfresco/Service/Repository.php"); + require_once($CFG->libdir."/alfresco/Service/Session.php"); + + /** + * Uploads a file into content store and returns the content data string which + * can be used to populate a content property. + * + * @param $session the session + * @param $filePath the file location + * @return String the content data that can be used to update the content property + */ + function upload_file($session, $filePath, $mimetype=null, $encoding=null) + { + $result = null; + + // Check for the existance of the file + if (file_exists($filePath) == false) + { + throw new Exception("The file ".$filePath."does no exist."); + } + + // Get the file name and size + $fileName = basename($filePath); + $fileSize = filesize($filePath); + + // Get the address and the + $host = $session->repository->host; + $port = $session->repository->port; + + // Get the IP address for the target host + $address = gethostbyname($host); + + // Create a TCP/IP socket + $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); + if ($socket === false) + { + throw new Exception ("socket_create() failed: reason: " . socket_strerror(socket_last_error())); + } + + // Connect the socket to the repository + $result = socket_connect($socket, $address, $port); + if ($result === false) + { + throw new Exception("socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket))); + } + + // Write the request header onto the socket + $url = "/alfresco/upload/".urlencode($fileName)."?ticket=".$session->ticket; + if ($mimetype != null) + { + // Add mimetype if specified + $url .= "&mimetype=".$mimetype; + } + if ($encoding != null) + { + // Add encoding if specified + $url .= "&encoding=".$encoding; + } + $in = "PUT ".$url." HTTP/1.1\r\n". + "Content-Length: ".$fileSize."\r\n". + "Host: ".$address.":".$port."\r\n". + "Connection: Keep-Alive\r\n". + "\r\n"; + socket_write($socket, $in, strlen($in)); + + // Write the content found in the file onto the socket + $handle = fopen($filePath, "r"); + while (feof($handle) == false) + { + $content = fread($handle, 1024); + socket_write($socket, $content, strlen($content)); + } + fclose($handle); + + // Read the response + $recv = socket_read ($socket, 2048, PHP_BINARY_READ); + $index = strpos($recv, "contentUrl"); + if ($index !== false) + { + $result = substr($recv, $index); + } + + // Close the socket + socket_close($socket); + + return $result; + } +?> diff --git a/lib/alfresco/Service/Logger/Logger.php b/lib/alfresco/Service/Logger/Logger.php index 6d2645080f7..6916cb926bc 100644 --- a/lib/alfresco/Service/Logger/Logger.php +++ b/lib/alfresco/Service/Logger/Logger.php @@ -1,90 +1,84 @@ -componentName = $componentName; - } - - public function isDebugEnabled() - { - return $this->isEnabled(DEBUG); - } - - public function debug($message) - { - $this->write(DEBUG, $message); - } - - public function isWarningEnabled() - { - return $this->isEnabled(WARNING); - } - - public function warning($message) - { - $this->write(WARNING, $message); - } - - public function isInformationEnabled() - { - return $this->isEnabled(INFORMATION); - } - - public function information($message) - { - $this->write(INFORMATION, $message); - } - - private function isEnabled($logLevel) - { - global $componentLogLevels, $defaultLogLevel; - - $logLevels = $defaultLogLevel; - if ($this->componentName != null && isset($componentLogLevels[$this->componentName]) == true) - { - $logLevels = $componentLogLevels[$this->componentName]; - } - - return in_array($logLevel, $logLevels); - } - - private function write($logLevel, $message) - { - global $logFile; - - $handle = fopen($logFile, "a"); - fwrite($handle, $logLevel." ".date("G:i:s d/m/Y")." - ".$message."\r\n"); - fclose($handle); - } - } -?> +. + */ + + require_once $CFG->libdir."/alfresco/Service/Logger/LoggerConfig.php"; + + class Logger + { + private $componentName; + + public function __construct($componentName = null) + { + $this->componentName = $componentName; + } + + public function isDebugEnabled() + { + return $this->isEnabled(DEBUG); + } + + public function debug($message) + { + $this->write(DEBUG, $message); + } + + public function isWarningEnabled() + { + return $this->isEnabled(WARNING); + } + + public function warning($message) + { + $this->write(WARNING, $message); + } + + public function isInformationEnabled() + { + return $this->isEnabled(INFORMATION); + } + + public function information($message) + { + $this->write(INFORMATION, $message); + } + + private function isEnabled($logLevel) + { + global $componentLogLevels, $defaultLogLevel; + + $logLevels = $defaultLogLevel; + if ($this->componentName != null && isset($componentLogLevels[$this->componentName]) == true) + { + $logLevels = $componentLogLevels[$this->componentName]; + } + + return in_array($logLevel, $logLevels); + } + + private function write($logLevel, $message) + { + global $logFile; + + $handle = fopen($logFile, "a"); + fwrite($handle, $logLevel." ".date("G:i:s d/m/Y")." - ".$message."\r\n"); + fclose($handle); + } + } +?> diff --git a/lib/alfresco/Service/Logger/LoggerConfig.php b/lib/alfresco/Service/Logger/LoggerConfig.php index 4227098da02..d6f010a3849 100644 --- a/lib/alfresco/Service/Logger/LoggerConfig.php +++ b/lib/alfresco/Service/Logger/LoggerConfig.php @@ -1,44 +1,38 @@ - $debugLevel - ); - - -?> +. + */ + +define("DEBUG", "Debug"); +define("WARNING", "Warning"); +define("INFO", "Information"); + +$debugLevel = array(DEBUG, WARNING, INFO); +$warningLevel = array(WARNING, INFO); +$infoLevel = array(INFO); +$noneLevel = array(); + +$defaultLogLevel = $infoLevel; + +$logFile = "c:/work/AlfrescoPHPLog.txt"; +$componentLogLevels = array( + "integration.mediawiki.ExternalStoreAlfresco" => $debugLevel + ); + + +?> diff --git a/lib/alfresco/Service/NamespaceMap.php b/lib/alfresco/Service/NamespaceMap.php index c08ce590b7b..25d880a1b8a 100644 --- a/lib/alfresco/Service/NamespaceMap.php +++ b/lib/alfresco/Service/NamespaceMap.php @@ -1,121 +1,115 @@ - "http://www.alfresco.org/model/dictionary/1.0", - "sys" => "http://www.alfresco.org/model/system/1.0", - "cm" => "http://www.alfresco.org/model/content/1.0", - "app" => "http://www.alfresco.org/model/application/1.0", - "bpm" => "http://www.alfresco.org/model/bpm/1.0", - "wf" => "http://www.alfresco.org/model/workflow/1.0", - "fm" => "http://www.alfresco.org/model/forum/1.0", - "view" => "http://www.alfresco.org/view/repository/1.0", - "security" => "http://www.alfresco.org/model/security/1.0", - "wcm" => "http://www.alfresco.org/model/wcmmodel/1.0", - "wca" => "http://www.alfresco.org/model/wcmappmodel/1.0"); - - public function isShortName($shortName) - { - return ($shortName != $this->getFullName($shortName)); - } - - public function getFullName($shortName) - { - $result = $shortName; - - $index = strpos($shortName, NamespaceMap::DELIMITER); - if ($index !== false) - { - $prefix = substr($shortName, 0, $index); - - if (isset($this->namespaceMap[$prefix]) == true) - { - $url = $this->namespaceMap[$prefix]; - $name = substr($shortName, $index+1); - $name = str_replace("_", "-", $name); - if ($name != null && strlen($name) != 0) - { - $result = "{".$url."}".$name; - } - } - } - - return $result; - } - - public function getFullNames($fullNames) - { - $result = array(); - - foreach ($fullNames as $fullName) - { - $result[] = $this->getFullName($fullName); - } - return $result; - } - - public function getShortName($fullName) - { - $result = $fullName; - - $index = strpos($fullName, "}"); - if ($index !== false) - { - $url = substr($fullName, 1, $index-1); - $prefix = $this->lookupPrefix($url); - if ($prefix != null) - { - $name = substr($fullName, $index+1); - if ($name != null && strlen($name) != 0) - { - $name = str_replace("-", "_", $name); - $result = $prefix.NamespaceMap::DELIMITER.$name; - } - } - } - - return $result; - } - - private function lookupPrefix($value) - { - $result = null; - foreach($this->namespaceMap as $prefix => $url) - { - if ($url == $value) - { - $result = $prefix; - } - } - return $result; - } -} - -?> +. + */ + +class NamespaceMap +{ + const DELIMITER = "_"; + + private $namespaceMap = array( + "d" => "http://www.alfresco.org/model/dictionary/1.0", + "sys" => "http://www.alfresco.org/model/system/1.0", + "cm" => "http://www.alfresco.org/model/content/1.0", + "app" => "http://www.alfresco.org/model/application/1.0", + "bpm" => "http://www.alfresco.org/model/bpm/1.0", + "wf" => "http://www.alfresco.org/model/workflow/1.0", + "fm" => "http://www.alfresco.org/model/forum/1.0", + "view" => "http://www.alfresco.org/view/repository/1.0", + "security" => "http://www.alfresco.org/model/security/1.0", + "wcm" => "http://www.alfresco.org/model/wcmmodel/1.0", + "wca" => "http://www.alfresco.org/model/wcmappmodel/1.0"); + + public function isShortName($shortName) + { + return ($shortName != $this->getFullName($shortName)); + } + + public function getFullName($shortName) + { + $result = $shortName; + + $index = strpos($shortName, NamespaceMap::DELIMITER); + if ($index !== false) + { + $prefix = substr($shortName, 0, $index); + + if (isset($this->namespaceMap[$prefix]) == true) + { + $url = $this->namespaceMap[$prefix]; + $name = substr($shortName, $index+1); + $name = str_replace("_", "-", $name); + if ($name != null && strlen($name) != 0) + { + $result = "{".$url."}".$name; + } + } + } + + return $result; + } + + public function getFullNames($fullNames) + { + $result = array(); + + foreach ($fullNames as $fullName) + { + $result[] = $this->getFullName($fullName); + } + return $result; + } + + public function getShortName($fullName) + { + $result = $fullName; + + $index = strpos($fullName, "}"); + if ($index !== false) + { + $url = substr($fullName, 1, $index-1); + $prefix = $this->lookupPrefix($url); + if ($prefix != null) + { + $name = substr($fullName, $index+1); + if ($name != null && strlen($name) != 0) + { + $name = str_replace("-", "_", $name); + $result = $prefix.NamespaceMap::DELIMITER.$name; + } + } + } + + return $result; + } + + private function lookupPrefix($value) + { + $result = null; + foreach($this->namespaceMap as $prefix => $url) + { + if ($url == $value) + { + $result = $prefix; + } + } + return $result; + } +} + +?> diff --git a/lib/alfresco/Service/Node.php b/lib/alfresco/Service/Node.php index 9fa0fa58b1b..71bc3623ff0 100644 --- a/lib/alfresco/Service/Node.php +++ b/lib/alfresco/Service/Node.php @@ -1,815 +1,809 @@ -_session = $session; - $this->_store = $store; - $this->_id = $id; - $this->_isNewNode = false; - $this->addedChildren = array(); - $this->addedParents = array(); - $this->addedAssociations = array(); - } - - /** - * Util method to create a node from a web service node structure. - */ - public static function createFromWebServiceData($session, $webServiceNode) - { - $scheme = $webServiceNode->reference->store->scheme; - $address = $webServiceNode->reference->store->address; - $id = $webServiceNode->reference->uuid; - - $store = $session->getStore($address, $scheme); - $node = $session->getNode($store, $id); - $node->populateFromWebServiceNode($webServiceNode); - - return $node; - } - - public function setPropertyValues($properties) - { - // Check that the properties of the node have been populated - $this->populateProperties(); - - // Set the property values - foreach ($properties as $name=>$value) - { - $name = $this->_session->namespaceMap->getFullName($name); - $this->_properties[$name] = $value; - } - } - - public function updateContent($property, $mimetype, $encoding="UTF-8", $content=null) - { - list($property) = $this->_session->namespaceMap->getFullNames(array($property)); - $contentData = new ContentData($this, $property, $mimetype, $encoding); - if ($content != null) - { - $contentData->content = $content; - } - $this->_properties[$property] = $contentData; - - return $contentData; - } - - public function hasAspect($aspect) - { - list($aspect) = $this->_session->namespaceMap->getFullNames(array($aspect)); - $this->populateProperties(); - return in_array($aspect, $this->_aspects); - } - - public function addAspect($aspect, $properties = null) - { - list($aspect) = $this->_session->namespaceMap->getFullNames(array($aspect)); - $this->populateProperties(); - - if (in_array($aspect, $this->_aspects) == false) - { - $this->_aspects[] = $aspect; - if ($properties != null) - { - foreach ($properties as $name=>$value) - { - $name = $this->_session->namespaceMap->getFullName($name); - $this->_properties[$name] = $value; - } - } - - $this->remove_array_value($aspect, $this->removedAspects); - $this->addedAspects[] = $aspect; - } - } - - public function removeAspect($aspect) - { - list($aspect) = $this->_session->namespaceMap->getFullNames(array($aspect)); - $this->populateProperties(); - - if (in_array($aspect, $this->_aspects) == true) - { - $this->remove_array_value($aspect, $this->_aspects); - $this->remove_array_value($aspect, $this->addedAspects); - $this->removedAspects[] = $aspect; - } - } - - public function createChild($type, $associationType, $associationName) - { - list($type, $associationType, $associationName) = $this->_session->namespaceMap->getFullNames(array($type, $associationType, $associationName)); - - $id = $this->_session->nextSessionId(); - $newNode = new Node($this->_session, $this->_store, $id); - $childAssociation = new ChildAssociation($this, $newNode, $associationType, $associationName, true); - - $newNode->_isNewNode = true; - - $newNode->_properties = array(); - $newNode->_aspects = array(); - $newNode->_properties = array(); - $newNode->_children = array(); - $newNode->origionalProperties = array(); - $newNode->addedAspects = array(); - $newNode->removedAspects = array(); - - $newNode->_type = $type; - $newNode->_parents = array(); - $newNode->addedParents = array($this->__toString() => $childAssociation); - $newNode->_primaryParent = $this; - - $this->addedChildren[$newNode->__toString()] = $childAssociation; - - $this->_session->addNode($newNode); - - return $newNode; - } - - public function addChild($node, $associationType, $associationName) - { - list($associationType, $associationName) = $this->_session->namespaceMap->getFullNames(array($associationType, $associationName)); - - $childAssociation = new ChildAssociation($this, $node, $associationType, $associationName, false); - $this->addedChildren[$node->__toString()] = $childAssociation; - $node->addedParents[$this->__toString()] = $childAssociation; - } - - public function removeChild($childAssociation) - { - - } - - public function addAssociation($to, $associationType) - { - list($associationType) = $this->_session->namespaceMap->getFullNames(array($associationType)); - - $association = new Association($this, $to, $associationType); - $this->addedAssociations[$to->__toString()] = $association; - } - - public function removeAssociation($association) - { - - } - - public function createVersion($description=null, $major=false) - { - // We can only create a version if there are no outstanding changes for this node - if ($this->isDirty() == true) - { - throw new Exception("You must save any outstanding modifications before a new version can be created."); - } - - // TODO implement major flag ... - - $client = WebServiceFactory::getAuthoringService($this->_session->repository->connectionUrl, $this->_session->ticket); - $result = $client->createVersion( - array("items" => array("nodes" => $this->__toArray()), - "comments" => array("name" => "description", "value" => $description), - "versionChildren" => false)); - - // Clear the properties and aspects - $this->_properties = null; - $this->_aspects = null; - - // Get the version details - // TODO get some of the other details too ... - $versionId = $result->createVersionReturn->versions->id->uuid; - $versionStoreScheme = $result->createVersionReturn->versions->id->store->scheme; - $versionStoreAddress = $result->createVersionReturn->versions->id->store->address; - - // Create the version object to return - return new Version($this->_session, new Store($this->_session, $versionStoreAddress, $versionStoreScheme), $versionId); - } - - private function isDirty() - { - $result = true; - if ($this->_isNewNode == false && - count($this->getModifiedProperties()) == 0 && - ($this->addedAspects == null || count($this->addedAspects) == 0) && - ($this->removedAssociations == null || count($this->removedAssociations) == 0) && - ($this->addedChildren == null || count($this->addedChildren) == 0) && - ($this->addedAssociations == null || count($this->addedAssociations) == 0)) - { - $result = false; - } - return $result; - } - - public function __get($name) - { - $fullName = $this->_session->namespaceMap->getFullName($name); - if ($fullName != $name) - { - $this->populateProperties(); - if (array_key_exists($fullName, $this->_properties) == true) - { - return $this->_properties[$fullName]; - } - else - { - return null; - } - } - else - { - return parent::__get($name); - } - } - - public function __set($name, $value) - { - $fullName = $this->_session->namespaceMap->getFullName($name); - if ($fullName != $name) - { - $this->populateProperties(); - $this->_properties[$fullName] = $value; - - // Ensure that the node and property details are stored on the contentData object - if ($value instanceof ContentData) - { - $value->setPropertyDetails($this, $fullName); - } - } - else - { - parent::__set($name, $value); - } - } - - /** - * toString method. Returns node as a node reference style string. - */ - public function __toString() - { - return Node::__toNodeRef($this->_store, $this->id); - } - - public static function __toNodeRef($store, $id) - { - return $store->scheme . "://" . $store->address . "/" . $id; - } - - public function __toArray() - { - return array("store" => $this->_store->__toArray(), - "uuid" => $this->_id); - } - - public function getSession() - { - return $this->_session; - } - - public function getStore() - { - return $this->_store; - } - - public function getId() - { - return $this->_id; - } - - public function getIsNewNode() - { - return $this->_isNewNode; - } - - public function getType() - { - $this->populateProperties(); - return $this->_type; - } - - public function getAspects() - { - $this->populateProperties(); - return $this->_aspects; - } - - public function getProperties() - { - $this->populateProperties(); - return $this->_properties; - } - - public function setProperties($properties) - { - $this->populateProperties(); - $this->_properties = $properties; - } - - /** - * Accessor for the versionHistory property. - * - * @return VersionHistory the versionHistory for the node, null is none - */ - public function getVersionHistory() - { - if ($this->_versionHistory == null) - { - $this->_versionHistory = new VersionHistory($this); - } - return $this->_versionHistory; - } - - public function getChildren() - { - if ($this->_children == null) - { - $this->populateChildren(); - } - return $this->_children + $this->addedChildren; - } - - public function getParents() - { - if ($this->_parents == null) - { - $this->populateParents(); - } - return $this->_parents + $this->addedParents; - } - - public function getPrimaryParent() - { - if ($this->_primaryParent == null) - { - $this->populateParents(); - } - return $this->_primaryParent; - } - - public function getAssociations() - { - if ($this->_associations == null) - { - $this->populateAssociations(); - } - return $this->_associations + $this->addedAssociations; - } - - /** Methods used to populate node details from repository */ - - private function populateProperties() - { - if ($this->_isNewNode == false && $this->_properties == null) - { - $result = $this->_session->repositoryService->get(array ( - "where" => array ( - "nodes" => array( - "store" => $this->_store->__toArray(), - "uuid" => $this->_id)))); - - $this->populateFromWebServiceNode($result->getReturn); - } - } - - private function populateFromWebServiceNode($webServiceNode) - { - $this->_type = $webServiceNode->type; - - // Get the aspects - $this->_aspects = array(); - $aspects = $webServiceNode->aspects; - if (is_array($aspects) == true) - { - foreach ($aspects as $aspect) - { - $this->_aspects[] = $aspect; - } - } - else - { - $this->_aspects[] = $aspects; - } - - // Set the property values - // NOTE: do we need to be concerned with identifying whether this is an array or not when there is - // only one property on a node - $this->_properties = array(); - foreach ($webServiceNode->properties as $propertyDetails) - { - $name = $propertyDetails->name; - $isMultiValue = $propertyDetails->isMultiValue; - $value = null; - if ($isMultiValue == false) - { - $value = $propertyDetails->value; - if ($this->isContentData($value) == true) - { - $value = new ContentData($this, $name); - } - } - else - { - $value = $propertyDetails->values; - } - $this->_properties[$name] = $value; - - } - - $this->origionalProperties = $this->_properties; - $this->addedAspects = array(); - $this->removedAspects = array(); - - } - - private function populateChildren() - { - // TODO should do some sort of limited pull here - $result = $this->_session->repositoryService->queryChildren(array("node" => $this->__toArray())); - $resultSet = $result->queryReturn->resultSet; - - $children = array(); - $map = $this->resultSetToMap($resultSet); - foreach($map as $value) - { - $id = $value["{http://www.alfresco.org/model/system/1.0}node-uuid"]; - $store_scheme = $value["{http://www.alfresco.org/model/system/1.0}store-protocol"]; - $store_address = $value["{http://www.alfresco.org/model/system/1.0}store-identifier"]; - $assoc_type = $value["associationType"]; - $assoc_name = $value["associationName"]; - $isPrimary = $value["isPrimary"]; - $nthSibling = $value["nthSibling"]; - - $child = $this->_session->getNode(new Store($this->_session, $store_address, $store_scheme), $id); - $children[$child->__toString()] = new ChildAssociation($this, $child, $assoc_type, $assoc_name, $isPrimary, $nthSibling); - } - - $this->_children = $children; - } - - private function populateAssociations() - { - // TODO should do some sort of limited pull here - $result = $this->_session->repositoryService->queryAssociated(array("node" => $this->__toArray(), - "association" => array("associationType" => null, - "direction" => null))); - $resultSet = $result->queryReturn->resultSet; - - $associations = array(); - $map = $this->resultSetToMap($resultSet); - foreach($map as $value) - { - $id = $value["{http://www.alfresco.org/model/system/1.0}node-uuid"]; - $store_scheme = $value["{http://www.alfresco.org/model/system/1.0}store-protocol"]; - $store_address = $value["{http://www.alfresco.org/model/system/1.0}store-identifier"]; - $assoc_type = $value["associationType"]; - - $to = $this->_session->getNode(new Store($this->_session, $store_address, $store_scheme), $id); - $associations[$to->__toString()] = new Association($this, $to, $assoc_type); - } - - $this->_associations = $associations; - } - - private function populateParents() - { - // TODO should do some sort of limited pull here - $result = $this->_session->repositoryService->queryParents(array("node" => $this->__toArray())); - $resultSet = $result->queryReturn->resultSet; - - $parents = array(); - $map = $this->resultSetToMap($resultSet); - foreach($map as $value) - { - $id = $value["{http://www.alfresco.org/model/system/1.0}node-uuid"]; - $store_scheme = $value["{http://www.alfresco.org/model/system/1.0}store-protocol"]; - $store_address = $value["{http://www.alfresco.org/model/system/1.0}store-identifier"]; - $assoc_type = $value["associationType"]; - $assoc_name = $value["associationName"]; - $isPrimary = $value["isPrimary"]; - $nthSibling = $value["nthSibling"]; - - $parent = $this->_session->getNode(new Store($this->_session, $store_address, $store_scheme), $id); - if ($isPrimary == "true" or $isPrimary == true) - { - $this->_primaryParent = $parent; - } - $parents[$parent->__toString()] = new ChildAssociation($parent, $this, $assoc_type, $assoc_name, $isPrimary, $nthSibling); - } - - $this->_parents = $parents; - } - - public function onBeforeSave(&$statements) - { - if ($this->_isNewNode == true) - { - $childAssociation = $this->addedParents[$this->_primaryParent->__toString()]; - - $parentArray = array(); - $parent = $this->_primaryParent; - if ($parent->_isNewNode == true) - { - $parentArray["parent_id"] = $parent->id; - $parentArray["associationType"] = $childAssociation->type; - $parentArray["childName"] = $childAssociation->name; - } - else - { - $parentArray["parent"] = array( - "store" => $this->_store->__toArray(), - "uuid" => $this->_primaryParent->_id, - "associationType" => $childAssociation->type, - "childName" => $childAssociation->name); - } - - $this->addStatement($statements, "create", - array("id" => $this->_id) + - $parentArray + - array( - "type" => $this->_type, - "property" => $this->getPropertyArray($this->_properties))); - } - else - { - // Add the update statement for the modified properties - $modifiedProperties = $this->getModifiedProperties(); - if (count($modifiedProperties) != 0) - { - $this->addStatement($statements, "update", array("property" => $this->getPropertyArray($modifiedProperties)) + $this->getWhereArray()); - } - - // TODO deal with any deleted properties - } - - // Update any modified content properties - if ($this->_properties != null) - { - foreach($this->_properties as $name=>$value) - { - if (($value instanceof ContentData) && $value->isDirty == true) - { - $value->onBeforeSave($statements, $this->getWhereArray()); - } - } - } - - // Add the addAspect statements - if ($this->addedAspects != null) - { - foreach($this->addedAspects as $aspect) - { - $this->addStatement($statements, "addAspect", array("aspect" => $aspect) + $this->getWhereArray()); - } - } - - // Add the removeAspect - if ($this->removedAspects != null) - { - foreach($this->removedAspects as $aspect) - { - $this->addStatement($statements, "removeAspect", array("aspect" => $aspect) + $this->getWhereArray()); - } - } - - // Add non primary children - foreach($this->addedChildren as $childAssociation) - { - if ($childAssociation->isPrimary == false) - { - - $assocDetails = array("associationType" => $childAssociation->type, "childName" => $childAssociation->name); - - $temp = array(); - if ($childAssociation->child->_isNewNode == true) - { - $temp["to_id"] = $childAssociation->child->_id; - $temp = $temp + $assocDetails; - } - else - { - $temp["to"] = array( - "store" => $this->_store->__toArray(), - "uuid" => $childAssociation->child->_id) + - $assocDetails; - } - $temp = $temp + $this->getWhereArray(); - $this->addStatement($statements, "addChild", $temp); - } - } - - // Add associations - foreach($this->addedAssociations as $association) - { - $temp = array("association" => $association->type); - $temp = $temp + $this->getPredicateArray("from", $this) + $this->getPredicateArray("to", $association->to); - $this->addStatement($statements, "createAssociation", $temp); - } - } - - private function addStatement(&$statements, $statement, $body) - { - $result = array(); - if (array_key_exists($statement, $statements) == true) - { - $result = $statements[$statement]; - } - $result[] = $body; - $statements[$statement] = $result; - } - - private function getWhereArray() - { - return $this->getPredicateArray("where", $this); - } - - private function getPredicateArray($label, $node) - { - if ($node->_isNewNode == true) - { - return array($label."_id" => $node->_id); - } - else - { - return array( - $label => array( - "nodes" => $node->__toArray() - )); - } - } - - private function getPropertyArray($properties) - { - $result = array(); - foreach ($properties as $name=>$value) - { - // Ignore content properties - if (($value instanceof ContentData) == false) - { - // TODO need to support multi values - $result[] = array( - "name" => $name, - "isMultiValue" => false, - "value" => $value); - } - } - return $result; - } - - private function getModifiedProperties() - { - $modified = $this->_properties; - $origional = $this->origionalProperties; - $result = array(); - if ($modified != null) - { - foreach ($modified as $key=>$value) - { - // Ignore content properties - if (($value instanceof ContentData) == false) - { - if (array_key_exists($key, $origional) == true) - { - // Check to see if the value have been modified - if ($value != $origional[$key]) - { - $result[$key] = $value; - } - } - else - { - $result[$key] = $value; - } - } - } - } - return $result; - } - - public function onAfterSave($idMap) - { - if (array_key_exists($this->_id, $idMap ) == true) - { - $uuid = $idMap[$this->_id]; - if ($uuid != null) - { - $this->_id = $uuid; - } - } - - if ($this->_isNewNode == true) - { - $this->_isNewNode = false; - - // Clear the properties and aspect - $this->_properties = null; - $this->_aspects = null; - } - - // Update any modified content properties - if ($this->_properties != null) - { - foreach($this->_properties as $name=>$value) - { - if (($value instanceof ContentData) && $value->isDirty == true) - { - $value->onAfterSave(); - } - } - } - - $this->origionalProperties = $this->_properties; - - if ($this->_aspects != null) - { - // Calculate the updated aspect list - if ($this->addedAspects != null) - { - $this->_aspects = $this->_aspects + $this->addedAspects; - } - if ($this->removedAspects != null) - { - foreach ($this->_aspects as $aspect) - { - if (in_array($aspect, $this->removedAspects) == true) - { - $this->remove_array_value($aspect, $this->_aspects); - } - } - } - } - $this->addedAspects = array(); - $this->removedAspects = array(); - - if ($this->_parents != null) - { - $this->_parents = $this->_parents + $this->addedParents; - } - $this->addedParents = array(); - - if ($this->_children != null) - { - $this->_children = $this->_children + $this->addedChildren; - } - $this->addedChildren = array(); - - if ($this->_associations != null) - { - $this->_associations = $this->_associations + $this->addedAssociations; - } - $this->addedAssociations = array(); - } -} +. + */ + +require_once $CFG->libdir.'/alfresco/Service/Store.php'; +require_once $CFG->libdir.'/alfresco/Service/ChildAssociation.php'; +require_once $CFG->libdir.'/alfresco/Service/Association.php'; +require_once $CFG->libdir.'/alfresco/Service/NamespaceMap.php'; +require_once $CFG->libdir.'/alfresco/Service/ContentData.php'; +require_once $CFG->libdir.'/alfresco/Service/VersionHistory.php'; +require_once $CFG->libdir.'/alfresco/Service/Version.php'; + +class Node extends BaseObject +{ + private $_session; + private $_store; + private $_id; + private $_type; + private $_aspects; + private $_properties; + private $_children; + private $_parents; + private $_primaryParent; + private $_isNewNode; + private $_associations; + private $_versionHistory; + private $origionalProperties; + private $addedAspects; + private $removedAspects; + private $addedChildren; + private $addedParents; + private $addedAssociations; + private $removedAssociations; + + /** + * Constructor + */ + public function __construct($session, $store, $id) + { + $this->_session = $session; + $this->_store = $store; + $this->_id = $id; + $this->_isNewNode = false; + $this->addedChildren = array(); + $this->addedParents = array(); + $this->addedAssociations = array(); + } + + /** + * Util method to create a node from a web service node structure. + */ + public static function createFromWebServiceData($session, $webServiceNode) + { + $scheme = $webServiceNode->reference->store->scheme; + $address = $webServiceNode->reference->store->address; + $id = $webServiceNode->reference->uuid; + + $store = $session->getStore($address, $scheme); + $node = $session->getNode($store, $id); + $node->populateFromWebServiceNode($webServiceNode); + + return $node; + } + + public function setPropertyValues($properties) + { + // Check that the properties of the node have been populated + $this->populateProperties(); + + // Set the property values + foreach ($properties as $name=>$value) + { + $name = $this->_session->namespaceMap->getFullName($name); + $this->_properties[$name] = $value; + } + } + + public function updateContent($property, $mimetype, $encoding="UTF-8", $content=null) + { + list($property) = $this->_session->namespaceMap->getFullNames(array($property)); + $contentData = new ContentData($this, $property, $mimetype, $encoding); + if ($content != null) + { + $contentData->content = $content; + } + $this->_properties[$property] = $contentData; + + return $contentData; + } + + public function hasAspect($aspect) + { + list($aspect) = $this->_session->namespaceMap->getFullNames(array($aspect)); + $this->populateProperties(); + return in_array($aspect, $this->_aspects); + } + + public function addAspect($aspect, $properties = null) + { + list($aspect) = $this->_session->namespaceMap->getFullNames(array($aspect)); + $this->populateProperties(); + + if (in_array($aspect, $this->_aspects) == false) + { + $this->_aspects[] = $aspect; + if ($properties != null) + { + foreach ($properties as $name=>$value) + { + $name = $this->_session->namespaceMap->getFullName($name); + $this->_properties[$name] = $value; + } + } + + $this->remove_array_value($aspect, $this->removedAspects); + $this->addedAspects[] = $aspect; + } + } + + public function removeAspect($aspect) + { + list($aspect) = $this->_session->namespaceMap->getFullNames(array($aspect)); + $this->populateProperties(); + + if (in_array($aspect, $this->_aspects) == true) + { + $this->remove_array_value($aspect, $this->_aspects); + $this->remove_array_value($aspect, $this->addedAspects); + $this->removedAspects[] = $aspect; + } + } + + public function createChild($type, $associationType, $associationName) + { + list($type, $associationType, $associationName) = $this->_session->namespaceMap->getFullNames(array($type, $associationType, $associationName)); + + $id = $this->_session->nextSessionId(); + $newNode = new Node($this->_session, $this->_store, $id); + $childAssociation = new ChildAssociation($this, $newNode, $associationType, $associationName, true); + + $newNode->_isNewNode = true; + + $newNode->_properties = array(); + $newNode->_aspects = array(); + $newNode->_properties = array(); + $newNode->_children = array(); + $newNode->origionalProperties = array(); + $newNode->addedAspects = array(); + $newNode->removedAspects = array(); + + $newNode->_type = $type; + $newNode->_parents = array(); + $newNode->addedParents = array($this->__toString() => $childAssociation); + $newNode->_primaryParent = $this; + + $this->addedChildren[$newNode->__toString()] = $childAssociation; + + $this->_session->addNode($newNode); + + return $newNode; + } + + public function addChild($node, $associationType, $associationName) + { + list($associationType, $associationName) = $this->_session->namespaceMap->getFullNames(array($associationType, $associationName)); + + $childAssociation = new ChildAssociation($this, $node, $associationType, $associationName, false); + $this->addedChildren[$node->__toString()] = $childAssociation; + $node->addedParents[$this->__toString()] = $childAssociation; + } + + public function removeChild($childAssociation) + { + + } + + public function addAssociation($to, $associationType) + { + list($associationType) = $this->_session->namespaceMap->getFullNames(array($associationType)); + + $association = new Association($this, $to, $associationType); + $this->addedAssociations[$to->__toString()] = $association; + } + + public function removeAssociation($association) + { + + } + + public function createVersion($description=null, $major=false) + { + // We can only create a version if there are no outstanding changes for this node + if ($this->isDirty() == true) + { + throw new Exception("You must save any outstanding modifications before a new version can be created."); + } + + // TODO implement major flag ... + + $client = WebServiceFactory::getAuthoringService($this->_session->repository->connectionUrl, $this->_session->ticket); + $result = $client->createVersion( + array("items" => array("nodes" => $this->__toArray()), + "comments" => array("name" => "description", "value" => $description), + "versionChildren" => false)); + + // Clear the properties and aspects + $this->_properties = null; + $this->_aspects = null; + + // Get the version details + // TODO get some of the other details too ... + $versionId = $result->createVersionReturn->versions->id->uuid; + $versionStoreScheme = $result->createVersionReturn->versions->id->store->scheme; + $versionStoreAddress = $result->createVersionReturn->versions->id->store->address; + + // Create the version object to return + return new Version($this->_session, new Store($this->_session, $versionStoreAddress, $versionStoreScheme), $versionId); + } + + private function isDirty() + { + $result = true; + if ($this->_isNewNode == false && + count($this->getModifiedProperties()) == 0 && + ($this->addedAspects == null || count($this->addedAspects) == 0) && + ($this->removedAssociations == null || count($this->removedAssociations) == 0) && + ($this->addedChildren == null || count($this->addedChildren) == 0) && + ($this->addedAssociations == null || count($this->addedAssociations) == 0)) + { + $result = false; + } + return $result; + } + + public function __get($name) + { + $fullName = $this->_session->namespaceMap->getFullName($name); + if ($fullName != $name) + { + $this->populateProperties(); + if (array_key_exists($fullName, $this->_properties) == true) + { + return $this->_properties[$fullName]; + } + else + { + return null; + } + } + else + { + return parent::__get($name); + } + } + + public function __set($name, $value) + { + $fullName = $this->_session->namespaceMap->getFullName($name); + if ($fullName != $name) + { + $this->populateProperties(); + $this->_properties[$fullName] = $value; + + // Ensure that the node and property details are stored on the contentData object + if ($value instanceof ContentData) + { + $value->setPropertyDetails($this, $fullName); + } + } + else + { + parent::__set($name, $value); + } + } + + /** + * toString method. Returns node as a node reference style string. + */ + public function __toString() + { + return Node::__toNodeRef($this->_store, $this->id); + } + + public static function __toNodeRef($store, $id) + { + return $store->scheme . "://" . $store->address . "/" . $id; + } + + public function __toArray() + { + return array("store" => $this->_store->__toArray(), + "uuid" => $this->_id); + } + + public function getSession() + { + return $this->_session; + } + + public function getStore() + { + return $this->_store; + } + + public function getId() + { + return $this->_id; + } + + public function getIsNewNode() + { + return $this->_isNewNode; + } + + public function getType() + { + $this->populateProperties(); + return $this->_type; + } + + public function getAspects() + { + $this->populateProperties(); + return $this->_aspects; + } + + public function getProperties() + { + $this->populateProperties(); + return $this->_properties; + } + + public function setProperties($properties) + { + $this->populateProperties(); + $this->_properties = $properties; + } + + /** + * Accessor for the versionHistory property. + * + * @return VersionHistory the versionHistory for the node, null is none + */ + public function getVersionHistory() + { + if ($this->_versionHistory == null) + { + $this->_versionHistory = new VersionHistory($this); + } + return $this->_versionHistory; + } + + public function getChildren() + { + if ($this->_children == null) + { + $this->populateChildren(); + } + return $this->_children + $this->addedChildren; + } + + public function getParents() + { + if ($this->_parents == null) + { + $this->populateParents(); + } + return $this->_parents + $this->addedParents; + } + + public function getPrimaryParent() + { + if ($this->_primaryParent == null) + { + $this->populateParents(); + } + return $this->_primaryParent; + } + + public function getAssociations() + { + if ($this->_associations == null) + { + $this->populateAssociations(); + } + return $this->_associations + $this->addedAssociations; + } + + /** Methods used to populate node details from repository */ + + private function populateProperties() + { + if ($this->_isNewNode == false && $this->_properties == null) + { + $result = $this->_session->repositoryService->get(array ( + "where" => array ( + "nodes" => array( + "store" => $this->_store->__toArray(), + "uuid" => $this->_id)))); + + $this->populateFromWebServiceNode($result->getReturn); + } + } + + private function populateFromWebServiceNode($webServiceNode) + { + $this->_type = $webServiceNode->type; + + // Get the aspects + $this->_aspects = array(); + $aspects = $webServiceNode->aspects; + if (is_array($aspects) == true) + { + foreach ($aspects as $aspect) + { + $this->_aspects[] = $aspect; + } + } + else + { + $this->_aspects[] = $aspects; + } + + // Set the property values + // NOTE: do we need to be concerned with identifying whether this is an array or not when there is + // only one property on a node + $this->_properties = array(); + foreach ($webServiceNode->properties as $propertyDetails) + { + $name = $propertyDetails->name; + $isMultiValue = $propertyDetails->isMultiValue; + $value = null; + if ($isMultiValue == false) + { + $value = $propertyDetails->value; + if ($this->isContentData($value) == true) + { + $value = new ContentData($this, $name); + } + } + else + { + $value = $propertyDetails->value; + } + $this->_properties[$name] = $value; + + } + + $this->origionalProperties = $this->_properties; + $this->addedAspects = array(); + $this->removedAspects = array(); + + } + + private function populateChildren() + { + // TODO should do some sort of limited pull here + $result = $this->_session->repositoryService->queryChildren(array("node" => $this->__toArray())); + $resultSet = $result->queryReturn->resultSet; + + $children = array(); + $map = $this->resultSetToMap($resultSet); + foreach($map as $value) + { + $id = $value["{http://www.alfresco.org/model/system/1.0}node-uuid"]; + $store_scheme = $value["{http://www.alfresco.org/model/system/1.0}store-protocol"]; + $store_address = $value["{http://www.alfresco.org/model/system/1.0}store-identifier"]; + $assoc_type = $value["associationType"]; + $assoc_name = $value["associationName"]; + $isPrimary = $value["isPrimary"]; + $nthSibling = $value["nthSibling"]; + + $child = $this->_session->getNode(new Store($this->_session, $store_address, $store_scheme), $id); + $children[$child->__toString()] = new ChildAssociation($this, $child, $assoc_type, $assoc_name, $isPrimary, $nthSibling); + } + + $this->_children = $children; + } + + private function populateAssociations() + { + // TODO should do some sort of limited pull here + $result = $this->_session->repositoryService->queryAssociated(array("node" => $this->__toArray(), + "association" => array("associationType" => null, + "direction" => null))); + $resultSet = $result->queryReturn->resultSet; + + $associations = array(); + $map = $this->resultSetToMap($resultSet); + foreach($map as $value) + { + $id = $value["{http://www.alfresco.org/model/system/1.0}node-uuid"]; + $store_scheme = $value["{http://www.alfresco.org/model/system/1.0}store-protocol"]; + $store_address = $value["{http://www.alfresco.org/model/system/1.0}store-identifier"]; + $assoc_type = $value["associationType"]; + + $to = $this->_session->getNode(new Store($this->_session, $store_address, $store_scheme), $id); + $associations[$to->__toString()] = new Association($this, $to, $assoc_type); + } + + $this->_associations = $associations; + } + + private function populateParents() + { + // TODO should do some sort of limited pull here + $result = $this->_session->repositoryService->queryParents(array("node" => $this->__toArray())); + $resultSet = $result->queryReturn->resultSet; + + $parents = array(); + $map = $this->resultSetToMap($resultSet); + foreach($map as $value) + { + $id = $value["{http://www.alfresco.org/model/system/1.0}node-uuid"]; + $store_scheme = $value["{http://www.alfresco.org/model/system/1.0}store-protocol"]; + $store_address = $value["{http://www.alfresco.org/model/system/1.0}store-identifier"]; + $assoc_type = $value["associationType"]; + $assoc_name = $value["associationName"]; + $isPrimary = $value["isPrimary"]; + $nthSibling = $value["nthSibling"]; + + $parent = $this->_session->getNode(new Store($this->_session, $store_address, $store_scheme), $id); + if ($isPrimary == "true" or $isPrimary == true) + { + $this->_primaryParent = $parent; + } + $parents[$parent->__toString()] = new ChildAssociation($parent, $this, $assoc_type, $assoc_name, $isPrimary, $nthSibling); + } + + $this->_parents = $parents; + } + + public function onBeforeSave(&$statements) + { + if ($this->_isNewNode == true) + { + $childAssociation = $this->addedParents[$this->_primaryParent->__toString()]; + + $parentArray = array(); + $parent = $this->_primaryParent; + if ($parent->_isNewNode == true) + { + $parentArray["parent_id"] = $parent->id; + $parentArray["associationType"] = $childAssociation->type; + $parentArray["childName"] = $childAssociation->name; + } + else + { + $parentArray["parent"] = array( + "store" => $this->_store->__toArray(), + "uuid" => $this->_primaryParent->_id, + "associationType" => $childAssociation->type, + "childName" => $childAssociation->name); + } + + $this->addStatement($statements, "create", + array("id" => $this->_id) + + $parentArray + + array( + "type" => $this->_type, + "property" => $this->getPropertyArray($this->_properties))); + } + else + { + // Add the update statement for the modified properties + $modifiedProperties = $this->getModifiedProperties(); + if (count($modifiedProperties) != 0) + { + $this->addStatement($statements, "update", array("property" => $this->getPropertyArray($modifiedProperties)) + $this->getWhereArray()); + } + + // TODO deal with any deleted properties + } + + // Update any modified content properties + if ($this->_properties != null) + { + foreach($this->_properties as $name=>$value) + { + if (($value instanceof ContentData) && $value->isDirty == true) + { + $value->onBeforeSave($statements, $this->getWhereArray()); + } + } + } + + // Add the addAspect statements + if ($this->addedAspects != null) + { + foreach($this->addedAspects as $aspect) + { + $this->addStatement($statements, "addAspect", array("aspect" => $aspect) + $this->getWhereArray()); + } + } + + // Add the removeAspect + if ($this->removedAspects != null) + { + foreach($this->removedAspects as $aspect) + { + $this->addStatement($statements, "removeAspect", array("aspect" => $aspect) + $this->getWhereArray()); + } + } + + // Add non primary children + foreach($this->addedChildren as $childAssociation) + { + if ($childAssociation->isPrimary == false) + { + + $assocDetails = array("associationType" => $childAssociation->type, "childName" => $childAssociation->name); + + $temp = array(); + if ($childAssociation->child->_isNewNode == true) + { + $temp["to_id"] = $childAssociation->child->_id; + $temp = $temp + $assocDetails; + } + else + { + $temp["to"] = array( + "store" => $this->_store->__toArray(), + "uuid" => $childAssociation->child->_id) + + $assocDetails; + } + $temp = $temp + $this->getWhereArray(); + $this->addStatement($statements, "addChild", $temp); + } + } + + // Add associations + foreach($this->addedAssociations as $association) + { + $temp = array("association" => $association->type); + $temp = $temp + $this->getPredicateArray("from", $this) + $this->getPredicateArray("to", $association->to); + $this->addStatement($statements, "createAssociation", $temp); + } + } + + private function addStatement(&$statements, $statement, $body) + { + $result = array(); + if (array_key_exists($statement, $statements) == true) + { + $result = $statements[$statement]; + } + $result[] = $body; + $statements[$statement] = $result; + } + + private function getWhereArray() + { + return $this->getPredicateArray("where", $this); + } + + private function getPredicateArray($label, $node) + { + if ($node->_isNewNode == true) + { + return array($label."_id" => $node->_id); + } + else + { + return array( + $label => array( + "nodes" => $node->__toArray() + )); + } + } + + private function getPropertyArray($properties) + { + $result = array(); + foreach ($properties as $name=>$value) + { + // Ignore content properties + if (($value instanceof ContentData) == false) + { + // TODO need to support multi values + $result[] = array( + "name" => $name, + "isMultiValue" => false, + "value" => $value); + } + } + return $result; + } + + private function getModifiedProperties() + { + $modified = $this->_properties; + $origional = $this->origionalProperties; + $result = array(); + if ($modified != null) + { + foreach ($modified as $key=>$value) + { + // Ignore content properties + if (($value instanceof ContentData) == false) + { + if (array_key_exists($key, $origional) == true) + { + // Check to see if the value have been modified + if ($value != $origional[$key]) + { + $result[$key] = $value; + } + } + else + { + $result[$key] = $value; + } + } + } + } + return $result; + } + + public function onAfterSave($idMap) + { + if (array_key_exists($this->_id, $idMap ) == true) + { + $uuid = $idMap[$this->_id]; + if ($uuid != null) + { + $this->_id = $uuid; + } + } + + if ($this->_isNewNode == true) + { + $this->_isNewNode = false; + + // Clear the properties and aspect + $this->_properties = null; + $this->_aspects = null; + } + + // Update any modified content properties + if ($this->_properties != null) + { + foreach($this->_properties as $name=>$value) + { + if (($value instanceof ContentData) && $value->isDirty == true) + { + $value->onAfterSave(); + } + } + } + + $this->origionalProperties = $this->_properties; + + if ($this->_aspects != null) + { + // Calculate the updated aspect list + if ($this->addedAspects != null) + { + $this->_aspects = $this->_aspects + $this->addedAspects; + } + if ($this->removedAspects != null) + { + foreach ($this->_aspects as $aspect) + { + if (in_array($aspect, $this->removedAspects) == true) + { + $this->remove_array_value($aspect, $this->_aspects); + } + } + } + } + $this->addedAspects = array(); + $this->removedAspects = array(); + + if ($this->_parents != null) + { + $this->_parents = $this->_parents + $this->addedParents; + } + $this->addedParents = array(); + + if ($this->_children != null) + { + $this->_children = $this->_children + $this->addedChildren; + } + $this->addedChildren = array(); + + if ($this->_associations != null) + { + $this->_associations = $this->_associations + $this->addedAssociations; + } + $this->addedAssociations = array(); + } +} ?> \ No newline at end of file diff --git a/lib/alfresco/Service/Repository.php b/lib/alfresco/Service/Repository.php index 6d1796728bd..79f9c10fa88 100644 --- a/lib/alfresco/Service/Repository.php +++ b/lib/alfresco/Service/Repository.php @@ -1,139 +1,131 @@ -libdir.'/alfresco/Service/WebService/WebServiceFactory.php'; -require_once $CFG->libdir.'/alfresco/Service/BaseObject.php'; - -if (isset($_SESSION) == false) -{ - // Start the session - session_start(); -} - -// change by moodle -class Alfresco_Repository extends BaseObject -{ - private $_connectionUrl; - private $_host; - private $_port; - - public function __construct($connectionUrl="http://localhost:8080/alfresco/api") - { - $this->_connectionUrl = $connectionUrl; - $parts = parse_url($connectionUrl); - $this->_host = $parts["host"]; - if (empty($parts["port"])) { - $this->_port = 80; - } else { - $this->_port = $parts["port"]; - } - } - - public function getConnectionUrl() - { - return $this->_connectionUrl; - } - - public function getHost() - { - return $this->_host; - } - - public function getPort() - { - return $this->_port; - } - - public function authenticate($userName, $password) - { - // TODO need to handle exceptions! - - $authenticationService = WebServiceFactory::getAuthenticationService($this->_connectionUrl); - $result = $authenticationService->startSession(array ( - "username" => $userName, - "password" => $password - )); - - // Get the ticket and sessionId - $ticket = $result->startSessionReturn->ticket; - $sessionId = $result->startSessionReturn->sessionid; - - // Store the session id for later use - if ($sessionId != null) - { - $sessionIds = null; - if (isset($_SESSION["sessionIds"]) == false) - { - $sessionIds = array(); - } - else - { - $sessionIds = $_SESSION["sessionIds"]; - } - $sessionIds[$ticket] = $sessionId; - $_SESSION["sessionIds"] = $sessionIds; - } - - return $ticket; - } - - public function createSession($ticket=null) - { - $session = null; - - if ($ticket == null) - { - // TODO get ticket from some well known location ie: the $_SESSION - } - else - { - // TODO would be nice to be able to check that the ticket is still valid! - - // Create new session - $session = new Session($this, $ticket); - } - - return $session; - } - - /** - * For a given ticket, returns the realated session id, null if one can not be found. - */ - public static function getSessionId($ticket) - { - $result = null; - if (isset($_SESSION["sessionIds"]) == true) - { - $result = $_SESSION["sessionIds"][$ticket]; - } - return $result; - - } - -} - - ?> +. + */ + +require_once $CFG->libdir.'/alfresco/Service/WebService/WebServiceFactory.php'; +require_once $CFG->libdir.'/alfresco/Service/BaseObject.php'; + +if (isset($_SESSION) == false) +{ + // Start the session + session_start(); +} + +class Alfresco_Repository extends BaseObject +{ + private $_connectionUrl; + private $_host; + private $_port; + + public function __construct($connectionUrl="http://localhost:8080/alfresco/api") + { + $this->_connectionUrl = $connectionUrl; + $parts = parse_url($connectionUrl); + $this->_host = $parts["host"]; + if (empty($parts["port"])) { + $this->_port = 80; + } else { + $this->_port = $parts["port"]; + } + } + + public function getConnectionUrl() + { + return $this->_connectionUrl; + } + + public function getHost() + { + return $this->_host; + } + + public function getPort() + { + return $this->_port; + } + + public function authenticate($userName, $password) + { + // TODO need to handle exceptions! + + $authenticationService = WebServiceFactory::getAuthenticationService($this->_connectionUrl); + $result = $authenticationService->startSession(array ( + "username" => $userName, + "password" => $password + )); + + // Get the ticket and sessionId + $ticket = $result->startSessionReturn->ticket; + $sessionId = $result->startSessionReturn->sessionid; + + // Store the session id for later use + if ($sessionId != null) + { + $sessionIds = null; + if (isset($_SESSION["sessionIds"]) == false) + { + $sessionIds = array(); + } + else + { + $sessionIds = $_SESSION["sessionIds"]; + } + $sessionIds[$ticket] = $sessionId; + $_SESSION["sessionIds"] = $sessionIds; + } + + return $ticket; + } + + public function createSession($ticket=null) + { + $session = null; + + if ($ticket == null) + { + // TODO get ticket from some well known location ie: the $_SESSION + } + else + { + // TODO would be nice to be able to check that the ticket is still valid! + + // Create new session + $session = new Session($this, $ticket); + } + + return $session; + } + + /** + * For a given ticket, returns the realated session id, null if one can not be found. + */ + public static function getSessionId($ticket) + { + $result = null; + if (isset($_SESSION["sessionIds"]) == true) + { + $result = $_SESSION["sessionIds"][$ticket]; + } + return $result; + + } + +} + + ?> \ No newline at end of file diff --git a/lib/alfresco/Service/Session.php b/lib/alfresco/Service/Session.php index 880eaa5324e..9204d7da574 100644 --- a/lib/alfresco/Service/Session.php +++ b/lib/alfresco/Service/Session.php @@ -1,277 +1,271 @@ -nodeCache = array(); - - $this->_repository = $repository; - $this->_ticket = $ticket; - - $this->repositoryService = WebServiceFactory::getRepositoryService($this->_repository->connectionUrl, $this->_ticket); - $this->contentService = WebServiceFactory::getContentService($this->_repository->connectionUrl, $this->_ticket); - } - - /** - * Creates a new store in the current respository - * - * @param $address the address of the new store - * @param $scheme the scheme of the new store, default value of 'workspace' - * @return Store the new store - */ - public function createStore($address, $scheme="workspace") - { - // Create the store - $result = $this->repositoryService->createStore(array( - "scheme" => $scheme, - "address" => $address)); - $store = new Store($this, $result->createStoreReturn->address, $result->createStoreReturn->scheme); - - // Add to the cached list if its been populated - if (isset($this->_stores) == true) - { - $this->_stores[] = $store; - } - - // Return the newly created store - return $store; - } - - /** - * Get the store - * - * @param $address the address of the store - * @param $scheme the scheme of the store. The default it 'workspace' - * @return Store the store - */ - public function getStore($address, $scheme="workspace") - { - return new Store($this, $address, $scheme); - } - - /** - * Get the store from it string representation (eg: workspace://SpacesStore) - * - * @param $value the stores string representation - * @return Store the store - */ - public function getStoreFromString($value) - { - list($scheme, $address) = explode("://", $value); - return new Store($this, $address, $scheme); - } - - public function getNode($store, $id) - { - $node = $this->getNodeImpl($store, $id); - if ($node == null) - { - $node = new Node($this, $store, $id); - $this->addNode($node); - } - return $node; - } - - public function getNodeFromString($value) - { - // TODO - throw new Exception("getNode($value) not yet implemented"); - } - - /** - * Adds a new node to the session. - */ - public function addNode($node) - { - $this->nodeCache[$node->__toString()] = $node; - } - - private function getNodeImpl($store, $id) - { - $result = null; - $nodeRef = $store->scheme . "://" . $store->address . "/" . $id; - if (array_key_exists($nodeRef, $this->nodeCache) == true) - { - $result = $this->nodeCache[$nodeRef]; - } - return $result; - } - - /** - * Commits all unsaved changes to the repository - */ - public function save($debug=false) - { - // Build the update statements from the node cache - $statements = array(); - foreach ($this->nodeCache as $node) - { - $node->onBeforeSave($statements); - } - - if ($debug == true) - { - var_dump($statements); - echo ("

    "); - } - - if (count($statements) > 0) - { - // Make the web service call - $result = $this->repositoryService->update(array("statements" => $statements)); - //var_dump($result); - - // Update the state of the updated nodes - foreach ($this->nodeCache as $node) - { - $node->onAfterSave($this->getIdMap($result)); - } - } - } - - /** - * Clears the current session by emptying the node cache. - * - * WARNING: all unsaved changes will be lost when clearing the session. - */ - public function clear() - { - // Clear the node cache - $this->nodeCache = array(); - } - - private function getIdMap($result) - { - $return = array(); - $statements = $result->updateReturn; - if (is_array($statements) == true) - { - foreach ($statements as $statement) - { - if ($statement->statement == "create") - { - $id = $statement->sourceId; - $uuid = $statement->destination->uuid; - $return[$id] = $uuid; - } - } - } - else - { - if ($statements->statement == "create") - { - $id = $statements->sourceId; - $uuid = $statements->destination->uuid; - $return[$id] = $uuid; - } - } - return $return; - } - - public function query($store, $query, $language='lucene') - { - // TODO need to support paged queries - $result = $this->repositoryService->query(array( - "store" => $store->__toArray(), - "query" => array( - "language" => $language, - "statement" => $query), - "includeMetaData" => false)); - - // TODO for now do nothing with the score and the returned data - $resultSet = $result->queryReturn->resultSet; - return $this->resultSetToNodes($this, $store, $resultSet); - } - - public function getTicket() - { - return $this->_ticket; - } - - public function getRepository() - { - return $this->_repository; - } - - public function getNamespaceMap() - { - if ($this->_namespaceMap == null) - { - $this->_namespaceMap = new NamespaceMap(); - } - return $this->_namespaceMap; - } - - public function getStores() - { - if (isset ($this->_stores) == false) - { - $this->_stores = array (); - $results = $this->repositoryService->getStores(); - - foreach ($results->getStoresReturn as $result) - { - $this->_stores[] = new Store($this, $result->address, $result->scheme); - } - } - - return $this->_stores; - } - - /** Want these methods to be package scope some how! **/ - - public function nextSessionId() - { - $sessionId = "session".$this->_ticket.$this->idCount; - $this->idCount ++; - return $sessionId; - } -} -?> +. + */ + +require_once $CFG->libdir.'/alfresco/Service/Store.php'; +require_once $CFG->libdir.'/alfresco/Service/Node.php'; +require_once $CFG->libdir.'/alfresco/Service/WebService/WebServiceFactory.php'; + +class Session extends BaseObject +{ + public $authenticationService; + public $repositoryService; + public $contentService; + + private $_repository; + private $_ticket; + private $_stores; + private $_namespaceMap; + + private $nodeCache; + private $idCount = 0; + + /** + * Constructor + * + * @param userName the user name + * @param ticket the currenlty authenticated users ticket + */ + public function __construct($repository, $ticket) + { + $this->nodeCache = array(); + + $this->_repository = $repository; + $this->_ticket = $ticket; + + $this->repositoryService = WebServiceFactory::getRepositoryService($this->_repository->connectionUrl, $this->_ticket); + $this->contentService = WebServiceFactory::getContentService($this->_repository->connectionUrl, $this->_ticket); + } + + /** + * Creates a new store in the current respository + * + * @param $address the address of the new store + * @param $scheme the scheme of the new store, default value of 'workspace' + * @return Store the new store + */ + public function createStore($address, $scheme="workspace") + { + // Create the store + $result = $this->repositoryService->createStore(array( + "scheme" => $scheme, + "address" => $address)); + $store = new Store($this, $result->createStoreReturn->address, $result->createStoreReturn->scheme); + + // Add to the cached list if its been populated + if (isset($this->_stores) == true) + { + $this->_stores[] = $store; + } + + // Return the newly created store + return $store; + } + + /** + * Get the store + * + * @param $address the address of the store + * @param $scheme the scheme of the store. The default it 'workspace' + * @return Store the store + */ + public function getStore($address, $scheme="workspace") + { + return new Store($this, $address, $scheme); + } + + /** + * Get the store from it string representation (eg: workspace://SpacesStore) + * + * @param $value the stores string representation + * @return Store the store + */ + public function getStoreFromString($value) + { + list($scheme, $address) = explode("://", $value); + return new Store($this, $address, $scheme); + } + + public function getNode($store, $id) + { + $node = $this->getNodeImpl($store, $id); + if ($node == null) + { + $node = new Node($this, $store, $id); + $this->addNode($node); + } + return $node; + } + + public function getNodeFromString($value) + { + // TODO + throw new Exception("getNode($value) not yet implemented"); + } + + /** + * Adds a new node to the session. + */ + public function addNode($node) + { + $this->nodeCache[$node->__toString()] = $node; + } + + private function getNodeImpl($store, $id) + { + $result = null; + $nodeRef = $store->scheme . "://" . $store->address . "/" . $id; + if (array_key_exists($nodeRef, $this->nodeCache) == true) + { + $result = $this->nodeCache[$nodeRef]; + } + return $result; + } + + /** + * Commits all unsaved changes to the repository + */ + public function save($debug=false) + { + // Build the update statements from the node cache + $statements = array(); + foreach ($this->nodeCache as $node) + { + $node->onBeforeSave($statements); + } + + if ($debug == true) + { + var_dump($statements); + echo ("

    "); + } + + if (count($statements) > 0) + { + // Make the web service call + $result = $this->repositoryService->update(array("statements" => $statements)); + //var_dump($result); + + // Update the state of the updated nodes + foreach ($this->nodeCache as $node) + { + $node->onAfterSave($this->getIdMap($result)); + } + } + } + + /** + * Clears the current session by emptying the node cache. + * + * WARNING: all unsaved changes will be lost when clearing the session. + */ + public function clear() + { + // Clear the node cache + $this->nodeCache = array(); + } + + private function getIdMap($result) + { + $return = array(); + $statements = $result->updateReturn; + if (is_array($statements) == true) + { + foreach ($statements as $statement) + { + if ($statement->statement == "create") + { + $id = $statement->sourceId; + $uuid = $statement->destination->uuid; + $return[$id] = $uuid; + } + } + } + else + { + if ($statements->statement == "create") + { + $id = $statements->sourceId; + $uuid = $statements->destination->uuid; + $return[$id] = $uuid; + } + } + return $return; + } + + public function query($store, $query, $language='lucene') + { + // TODO need to support paged queries + $result = $this->repositoryService->query(array( + "store" => $store->__toArray(), + "query" => array( + "language" => $language, + "statement" => $query), + "includeMetaData" => false)); + + // TODO for now do nothing with the score and the returned data + $resultSet = $result->queryReturn->resultSet; + return $this->resultSetToNodes($this, $store, $resultSet); + } + + public function getTicket() + { + return $this->_ticket; + } + + public function getRepository() + { + return $this->_repository; + } + + public function getNamespaceMap() + { + if ($this->_namespaceMap == null) + { + $this->_namespaceMap = new NamespaceMap(); + } + return $this->_namespaceMap; + } + + public function getStores() + { + if (isset ($this->_stores) == false) + { + $this->_stores = array (); + $results = $this->repositoryService->getStores(); + + foreach ($results->getStoresReturn as $result) + { + $this->_stores[] = new Store($this, $result->address, $result->scheme); + } + } + + return $this->_stores; + } + + /** Want these methods to be package scope some how! **/ + + public function nextSessionId() + { + $sessionId = "session".$this->_ticket.$this->idCount; + $this->idCount ++; + return $sessionId; + } +} +?> \ No newline at end of file diff --git a/lib/alfresco/Service/SpacesStore.php b/lib/alfresco/Service/SpacesStore.php index 91082c44765..b595432e935 100644 --- a/lib/alfresco/Service/SpacesStore.php +++ b/lib/alfresco/Service/SpacesStore.php @@ -1,54 +1,48 @@ -scheme . "://" . $this->address; - } - - public function getCompanyHome() - { - if ($this->_companyHome == null) - { - $nodes = $this->_session->query($this, 'PATH:"app:company_home"'); - $this->_companyHome = $nodes[0]; - } - return $this->_companyHome; - } -} +. + */ + +require_once $CFG->libdir.'/alfresco/Service/Store.php'; +require_once $CFG->libdir.'/alfresco/Service/Node.php'; + +class SpacesStore extends Store +{ + private $_companyHome; + + public function __construct($session) + { + parent::__construct($session, "SpacesStore"); + } + + public function __toString() + { + return $this->scheme . "://" . $this->address; + } + + public function getCompanyHome() + { + if ($this->_companyHome == null) + { + $nodes = $this->_session->query($this, 'PATH:"app:company_home"'); + $this->_companyHome = $nodes[0]; + } + return $this->_companyHome; + } +} ?> \ No newline at end of file diff --git a/lib/alfresco/Service/Store.php b/lib/alfresco/Service/Store.php index 723ca9ccc05..dca6545f912 100644 --- a/lib/alfresco/Service/Store.php +++ b/lib/alfresco/Service/Store.php @@ -1,81 +1,75 @@ -_session = $session; - $this->_address = $address; - $this->_scheme = $scheme; - } - - public function __toString() - { - return $this->scheme . "://" . $this->address; - } - - public function __toArray() - { - return array( - "scheme" => $this->_scheme, - "address" => $this->_address); - } - - public function getAddress() - { - return $this->_address; - } - - public function getScheme() - { - return $this->_scheme; - } - - public function getRootNode() - { - if (isset ($this->_rootNode) == false) - { - $result = $this->_session->repositoryService->get( - array( - "where" => array( - "store" => $this->__toArray()))); - - $this->_rootNode = Node::createFromWebServiceData($this->_session, $result->getReturn); - } - - return $this->_rootNode; - } -} +. + */ + +require_once $CFG->libdir.'/alfresco/Service/BaseObject.php'; +require_once $CFG->libdir.'/alfresco/Service/Node.php'; + +class Store extends BaseObject +{ + protected $_session; + protected $_address; + protected $_scheme; + protected $_rootNode; + + public function __construct($session, $address, $scheme = "workspace") + { + $this->_session = $session; + $this->_address = $address; + $this->_scheme = $scheme; + } + + public function __toString() + { + return $this->scheme . "://" . $this->address; + } + + public function __toArray() + { + return array( + "scheme" => $this->_scheme, + "address" => $this->_address); + } + + public function getAddress() + { + return $this->_address; + } + + public function getScheme() + { + return $this->_scheme; + } + + public function getRootNode() + { + if (isset ($this->_rootNode) == false) + { + $result = $this->_session->repositoryService->get( + array( + "where" => array( + "store" => $this->__toArray()))); + + $this->_rootNode = Node::createFromWebServiceData($this->_session, $result->getReturn); + } + + return $this->_rootNode; + } +} ?> \ No newline at end of file diff --git a/lib/alfresco/Service/Version.php b/lib/alfresco/Service/Version.php index 6087b665595..74f7213700d 100644 --- a/lib/alfresco/Service/Version.php +++ b/lib/alfresco/Service/Version.php @@ -1,200 +1,194 @@ -_session = $session; - $this->_store = $store; - $this->_id = $id; - $this->_description = $description; - $this->_major = $major; - $this->_properties = null; - $this->_aspects = null; - $this->_type = null; - } - - /** - * __get override. - * - * If called with a valid property short name, the frozen value of that property is returned. - * - * @return String the appropriate property value, null if none found - */ - public function __get($name) - { - $fullName = $this->_session->namespaceMap->getFullName($name); - if ($fullName != $name) - { - $this->populateProperties(); - if (array_key_exists($fullName, $this->_properties) == true) - { - return $this->_properties[$fullName]; - } - else - { - return null; - } - } - else - { - return parent::__get($name); - } - } - - /** - * Gets session - * - * @return Session the session - */ - public function getSession() - { - return $this->_session; - } - - /** - * Get the frozen nodes store - * - * @return Store the store - */ - public function getStore() - { - return $this->_store; - } - - public function getId() - { - return $this->_id; - } - - public function getDescription() - { - return $this->_description; - } - - public function getMajor() - { - return $this->_major; - } - - public function getType() - { - return $this->_type; - } - - public function getProperties() - { - return $this->_properties; - } - - public function getAspects() - { - return $this->_aspects; - } - - private function populateProperties() - { - if ($this->_properties == null) - { - $result = $this->_session->repositoryService->get(array ( - "where" => array ( - "nodes" => array( - "store" => $this->_store->__toArray(), - "uuid" => $this->_id)))); - - $this->populateFromWebServiceNode($result->getReturn); - } - } - - private function populateFromWebServiceNode($webServiceNode) - { - $this->_type = $webServiceNode->type; - - // Get the aspects - $this->_aspects = array(); - $aspects = $webServiceNode->aspects; - if (is_array($aspects) == true) - { - foreach ($aspects as $aspect) - { - $this->_aspects[] = $aspect; - } - } - else - { - $this->_aspects[] = $aspects; - } - - // Set the property values - $this->_properties = array(); - foreach ($webServiceNode->properties as $propertyDetails) - { - $name = $propertyDetails->name; - $isMultiValue = $propertyDetails->isMultiValue; - $value = null; - if ($isMultiValue == false) - { - $value = $propertyDetails->value; - if ($this->isContentData($value) == true) - { - $value = new ContentData($this, $name); - } - } - else - { - $value = $propertyDetails->values; - } - - $this->_properties[$name] = $value; - } - } - } -?> +. + */ + + + /** + * Version class + * + * @author Roy Wetherall + */ + class Version extends BaseObject + { + private $_session; + private $_store; + private $_id; + private $_description; + private $_major; + private $_properties; + private $_type; + private $_aspects; + + /** + * Constructor + * + * @param $session the session that the version is tied to + * @param @store the store that the forzen node is stored in + * @prarm @id the id of the frozen node + * @param @description the description of the version + * @param @major indicates whether this is a major or minor revision + */ + public function __construct($session, $store, $id, $description=null, $major=false) + { + $this->_session = $session; + $this->_store = $store; + $this->_id = $id; + $this->_description = $description; + $this->_major = $major; + $this->_properties = null; + $this->_aspects = null; + $this->_type = null; + } + + /** + * __get override. + * + * If called with a valid property short name, the frozen value of that property is returned. + * + * @return String the appropriate property value, null if none found + */ + public function __get($name) + { + $fullName = $this->_session->namespaceMap->getFullName($name); + if ($fullName != $name) + { + $this->populateProperties(); + if (array_key_exists($fullName, $this->_properties) == true) + { + return $this->_properties[$fullName]; + } + else + { + return null; + } + } + else + { + return parent::__get($name); + } + } + + /** + * Gets session + * + * @return Session the session + */ + public function getSession() + { + return $this->_session; + } + + /** + * Get the frozen nodes store + * + * @return Store the store + */ + public function getStore() + { + return $this->_store; + } + + public function getId() + { + return $this->_id; + } + + public function getDescription() + { + return $this->_description; + } + + public function getMajor() + { + return $this->_major; + } + + public function getType() + { + return $this->_type; + } + + public function getProperties() + { + return $this->_properties; + } + + public function getAspects() + { + return $this->_aspects; + } + + private function populateProperties() + { + if ($this->_properties == null) + { + $result = $this->_session->repositoryService->get(array ( + "where" => array ( + "nodes" => array( + "store" => $this->_store->__toArray(), + "uuid" => $this->_id)))); + + $this->populateFromWebServiceNode($result->getReturn); + } + } + + private function populateFromWebServiceNode($webServiceNode) + { + $this->_type = $webServiceNode->type; + + // Get the aspects + $this->_aspects = array(); + $aspects = $webServiceNode->aspects; + if (is_array($aspects) == true) + { + foreach ($aspects as $aspect) + { + $this->_aspects[] = $aspect; + } + } + else + { + $this->_aspects[] = $aspects; + } + + // Set the property values + $this->_properties = array(); + foreach ($webServiceNode->properties as $propertyDetails) + { + $name = $propertyDetails->name; + $isMultiValue = $propertyDetails->isMultiValue; + $value = null; + if ($isMultiValue == false) + { + $value = $propertyDetails->value; + if ($this->isContentData($value) == true) + { + $value = new ContentData($this, $name); + } + } + else + { + $value = $propertyDetails->values; + } + + $this->_properties[$name] = $value; + } + } + } +?> diff --git a/lib/alfresco/Service/VersionHistory.php b/lib/alfresco/Service/VersionHistory.php index 57c2ea7f8e7..baabab4044b 100644 --- a/lib/alfresco/Service/VersionHistory.php +++ b/lib/alfresco/Service/VersionHistory.php @@ -1,80 +1,74 @@ -_node = $node; - $this->populateVersionHistory(); - } - - /** - * Get the node that this version history relates to - */ - public function getNode() - { - return $this->_node; - } - - /** - * Get a list of the versions in the version history - */ - public function getVersions() - { - return $this->_versions; - } - - /** - * Populate the version history - */ - private function populateVersionHistory() - { - // Use the web service API to get the version history for this node - $client = WebServiceFactory::getAuthoringService($this->_node->session->repository->connectionUrl, $this->_node->session->ticket); - $result = $client->getVersionHistory(array("node" => $this->_node->__toArray())); - //var_dump($result); - - // TODO populate the version history from the result of the web service call - } - } -?> +. + */ + + /** + * Version history class. + * + * @author Roy Wetherall + */ + class VersionHistory extends BaseObject + { + /** Node to which this version history relates */ + private $_node; + + /** Array of versions */ + private $_versions; + + /** + * Constructor + * + * @param $node the node that this version history apples to + */ + public function __construct($node) + { + $this->_node = $node; + $this->populateVersionHistory(); + } + + /** + * Get the node that this version history relates to + */ + public function getNode() + { + return $this->_node; + } + + /** + * Get a list of the versions in the version history + */ + public function getVersions() + { + return $this->_versions; + } + + /** + * Populate the version history + */ + private function populateVersionHistory() + { + // Use the web service API to get the version history for this node + $client = WebServiceFactory::getAuthoringService($this->_node->session->repository->connectionUrl, $this->_node->session->ticket); + $result = $client->getVersionHistory(array("node" => $this->_node->__toArray())); + //var_dump($result); + + // TODO populate the version history from the result of the web service call + } + } +?> diff --git a/lib/alfresco/Service/WebService/AlfrescoWebService.php b/lib/alfresco/Service/WebService/AlfrescoWebService.php index 8f2edf5d2e6..b549755b467 100644 --- a/lib/alfresco/Service/WebService/AlfrescoWebService.php +++ b/lib/alfresco/Service/WebService/AlfrescoWebService.php @@ -1,118 +1,111 @@ - true, 'exceptions' => true), $ticket = null) - { - // Store the current ticket - $this->ticket = $ticket; - - // Call the base class - parent::__construct($wsdl, $options); - } - - public function __call($function_name, $arguments=array()) - { - return $this->__soapCall($function_name, $arguments); - } - - public function __soapCall($function_name, $arguments=array(), $options=array(), $input_headers=array(), $output_headers=array()) - { - if (isset($this->ticket)) - { - // Automatically add a security header - $input_headers[] = new SoapHeader($this->securityExtNS, "Security", null, 1); - - // Set the JSESSION cookie value - // change by moodle - $sessionId = Alfresco_Repository::getSessionId($this->ticket); - if ($sessionId != null) - { - $this->__setCookie("JSESSIONID", $sessionId); - } - } - - return parent::__soapCall($function_name, $arguments, $options, $input_headers, $output_headers); - } - - public function __doRequest($request, $location, $action, $version) - { - // If this request requires authentication we have to manually construct the - // security headers. - if (isset($this->ticket)) - { - $dom = new DOMDocument("1.0"); - $dom->loadXML($request); - - $securityHeader = $dom->getElementsByTagName("Security"); - - if ($securityHeader->length != 1) - { - throw new Exception("Expected length: 1, Received: " . $securityHeader->length . ". No Security Header, or more than one element called Security!"); - } - - $securityHeader = $securityHeader->item(0); - - // Construct Timestamp Header - $timeStamp = $dom->createElementNS($this->wsUtilityNS, "Timestamp"); - $createdDate = date("Y-m-d\TH:i:s\Z", mktime(date("H")+24, date("i"), date("s"), date("m"), date("d"), date("Y"))); - $expiresDate = date("Y-m-d\TH:i:s\Z", mktime(date("H")+25, date("i"), date("s"), date("m"), date("d"), date("Y"))); - $created = new DOMElement("Created", $createdDate, $this->wsUtilityNS); - $expires = new DOMElement("Expires", $expiresDate, $this->wsUtilityNS); - $timeStamp->appendChild($created); - $timeStamp->appendChild($expires); - - // Construct UsernameToken Header - $userNameToken = $dom->createElementNS($this->securityExtNS, "UsernameToken"); - $userName = new DOMElement("Username", "username", $this->securityExtNS); - $passWord = $dom->createElementNS($this->securityExtNS, "Password"); - $typeAttr = new DOMAttr("Type", $this->passwordType); - $passWord->appendChild($typeAttr); - $passWord->appendChild($dom->createTextNode($this->ticket)); - $userNameToken->appendChild($userName); - $userNameToken->appendChild($passWord); - - // Construct Security Header - $securityHeader->appendChild($timeStamp); - $securityHeader->appendChild($userNameToken); - - // Save the XML Request - $request = $dom->saveXML(); - } - - return parent::__doRequest($request, $location, $action, $version); - } -} - -?> +. + */ + +class AlfrescoWebService extends SoapClient +{ + private $securityExtNS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; + private $wsUtilityNS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"; + private $passwordType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"; + + private $ticket; + + public function __construct($wsdl, $options = array('trace' => true, 'exceptions' => true), $ticket = null) + { + // Store the current ticket + $this->ticket = $ticket; + + // Call the base class + parent::__construct($wsdl, $options); + } + + public function __call($function_name, $arguments=array()) + { + return $this->__soapCall($function_name, $arguments); + } + + public function __soapCall($function_name, $arguments=array(), $options=array(), $input_headers=array(), &$output_headers=array()) + { + if (isset($this->ticket)) + { + // Automatically add a security header + $input_headers[] = new SoapHeader($this->securityExtNS, "Security", null, 1); + + // Set the JSESSION cookie value + $sessionId = Alfresco_Repository::getSessionId($this->ticket); + if ($sessionId != null) + { + $this->__setCookie("JSESSIONID", $sessionId); + } + } + + return parent::__soapCall($function_name, $arguments, $options, $input_headers, $output_headers); + } + + public function __doRequest($request, $location, $action, $version, $one_way = 0) + { + // If this request requires authentication we have to manually construct the + // security headers. + if (isset($this->ticket)) + { + $dom = new DOMDocument("1.0"); + $dom->loadXML($request); + + $securityHeader = $dom->getElementsByTagName("Security"); + + if ($securityHeader->length != 1) + { + throw new Exception("Expected length: 1, Received: " . $securityHeader->length . ". No Security Header, or more than one element called Security!"); + } + + $securityHeader = $securityHeader->item(0); + + // Construct Timestamp Header + $timeStamp = $dom->createElementNS($this->wsUtilityNS, "Timestamp"); + $createdDate = date("Y-m-d\TH:i:s\Z", mktime(date("H")+24, date("i"), date("s"), date("m"), date("d"), date("Y"))); + $expiresDate = date("Y-m-d\TH:i:s\Z", mktime(date("H")+25, date("i"), date("s"), date("m"), date("d"), date("Y"))); + $created = new DOMElement("Created", $createdDate, $this->wsUtilityNS); + $expires = new DOMElement("Expires", $expiresDate, $this->wsUtilityNS); + $timeStamp->appendChild($created); + $timeStamp->appendChild($expires); + + // Construct UsernameToken Header + $userNameToken = $dom->createElementNS($this->securityExtNS, "UsernameToken"); + $userName = new DOMElement("Username", "username", $this->securityExtNS); + $passWord = $dom->createElementNS($this->securityExtNS, "Password"); + $typeAttr = new DOMAttr("Type", $this->passwordType); + $passWord->appendChild($typeAttr); + $passWord->appendChild($dom->createTextNode($this->ticket)); + $userNameToken->appendChild($userName); + $userNameToken->appendChild($passWord); + + // Construct Security Header + $securityHeader->appendChild($timeStamp); + $securityHeader->appendChild($userNameToken); + + // Save the XML Request + $request = $dom->saveXML(); + } + + return parent::__doRequest($request, $location, $action, $version); + } +} + +?> diff --git a/lib/alfresco/Service/WebService/WebServiceFactory.php b/lib/alfresco/Service/WebService/WebServiceFactory.php index b312b6a1cc6..b9683719591 100644 --- a/lib/alfresco/Service/WebService/WebServiceFactory.php +++ b/lib/alfresco/Service/WebService/WebServiceFactory.php @@ -1,64 +1,57 @@ -libdir.'/alfresco/Service/WebService/AlfrescoWebService.php'); - -class WebServiceFactory -{ - public static function getAuthenticationService($path) - { - $path .= '/AuthenticationService?wsdl'; - return new AlfrescoWebService($path, array('location'=>$path)); - } - - public static function getRepositoryService($path, $ticket) - { - $path .= '/RepositoryService?wsdl'; - return new AlfrescoWebService($path, array('location'=>$path), $ticket); - } - - public static function getContentService($path, $ticket) - { - $path .= '/ContentService?wsdl'; - return new AlfrescoWebService($path, array('location'=>$path), $ticket); - } - - public static function getAdministrationService($path, $ticket) - { - $path .= '/AdministrationService?wsdl'; - return new AlfrescoWebService($path, array('location'=>$path), $ticket); - } - - public static function getAuthoringService($path, $ticket) - { - $path .= '/AuthoringService?wsdl'; - return new AlfrescoWebService($path, array('location'=>$path), $ticket); - } -} - -?> +. + */ + +require_once $CFG->libdir.'/alfresco/Service/WebService/AlfrescoWebService.php'; + +class WebServiceFactory +{ + public static function getAuthenticationService($path) + { + $path .= '/AuthenticationService?wsdl'; + return new AlfrescoWebService($path, array()); + } + + public static function getRepositoryService($path, $ticket) + { + $path .= '/RepositoryService?wsdl'; + return new AlfrescoWebService($path, array(), $ticket); + } + + public static function getContentService($path, $ticket) + { + $path .= '/ContentService?wsdl'; + return new AlfrescoWebService($path, array(), $ticket); + } + + public static function getAdministrationService($path, $ticket) + { + $path .= '/AdministrationService?wsdl'; + return new AlfrescoWebService($path, array(), $ticket); + } + + public static function getAuthoringService($path, $ticket) + { + $path .= '/AuthoringService?wsdl'; + return new AlfrescoWebService($path, array(), $ticket); + } +} + +?> \ No newline at end of file diff --git a/lib/blocklib.php b/lib/blocklib.php index 1c7097e9246..3aabe710a76 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -1108,7 +1108,7 @@ class block_manager { * @return boolean true if anything was done. False if not. */ public function process_url_delete() { - $blockid = optional_param('bui_deleteid', null, PARAM_INTEGER); + $blockid = optional_param('bui_deleteid', null, PARAM_INT); if (!$blockid) { return false; } @@ -1134,9 +1134,9 @@ class block_manager { * @return boolean true if anything was done. False if not. */ public function process_url_show_hide() { - if ($blockid = optional_param('bui_hideid', null, PARAM_INTEGER)) { + if ($blockid = optional_param('bui_hideid', null, PARAM_INT)) { $newvisibility = 0; - } else if ($blockid = optional_param('bui_showid', null, PARAM_INTEGER)) { + } else if ($blockid = optional_param('bui_showid', null, PARAM_INT)) { $newvisibility = 1; } else { return false; @@ -1169,7 +1169,7 @@ class block_manager { public function process_url_edit() { global $CFG, $DB, $PAGE, $OUTPUT; - $blockid = optional_param('bui_editid', null, PARAM_INTEGER); + $blockid = optional_param('bui_editid', null, PARAM_INT); if (!$blockid) { return false; } @@ -1367,7 +1367,7 @@ class block_manager { public function process_url_move() { global $CFG, $DB, $PAGE; - $blockid = optional_param('bui_moveid', null, PARAM_INTEGER); + $blockid = optional_param('bui_moveid', null, PARAM_INT); if (!$blockid) { return false; } @@ -1960,35 +1960,6 @@ function blocks_delete_all_on_page($pagetype, $pageid) { return false; } -/** - * Dispite what this function is called, it seems to be mostly used to populate - * the default blocks when a new course (or whatever) is created. - * - * @deprecated since 2.0 - * - * @param object $page the page to add default blocks to. - * @return boolean success or failure. - */ -function blocks_repopulate_page($page) { - global $CFG; - - debugging('Call to deprecated function blocks_repopulate_page. ' . - 'Use a more specific method like blocks_add_default_course_blocks, ' . - 'or just call $PAGE->blocks->add_blocks()', DEBUG_DEVELOPER); - - /// If the site override has been defined, it is the only valid one. - if (!empty($CFG->defaultblocks_override)) { - $blocknames = $CFG->defaultblocks_override; - } else { - $blocknames = $page->blocks_get_default(); - } - - $blocks = blocks_parse_default_blocks_list($blocknames); - $page->blocks->add_blocks($blocks); - - return true; -} - /** * Get the block record for a particular blockid - that is, a particular type os block. * diff --git a/lib/completionlib.php b/lib/completionlib.php index 4df3bc0cc8c..f30b4f0399e 100644 --- a/lib/completionlib.php +++ b/lib/completionlib.php @@ -31,10 +31,10 @@ defined('MOODLE_INTERNAL') || die(); /** * Include the required completion libraries */ -require_once $CFG->libdir.'/completion/completion_aggregation.php'; -require_once $CFG->libdir.'/completion/completion_criteria.php'; -require_once $CFG->libdir.'/completion/completion_completion.php'; -require_once $CFG->libdir.'/completion/completion_criteria_completion.php'; +require_once $CFG->dirroot.'/completion/completion_aggregation.php'; +require_once $CFG->dirroot.'/completion/criteria/completion_criteria.php'; +require_once $CFG->dirroot.'/completion/completion_completion.php'; +require_once $CFG->dirroot.'/completion/completion_criteria_completion.php'; /** @@ -616,8 +616,8 @@ class completion_info { * @return void */ public function set_module_viewed($cm, $userid=0) { - global $PAGE, $UNITTEST; - if ($PAGE->headerprinted && empty($UNITTEST->running)) { + global $PAGE; + if ($PAGE->headerprinted) { debugging('set_module_viewed must be called before header is printed', DEBUG_DEVELOPER); } diff --git a/lib/conditionlib.php b/lib/conditionlib.php index 650006a0288..7557190f189 100644 --- a/lib/conditionlib.php +++ b/lib/conditionlib.php @@ -79,6 +79,10 @@ define('OP_ENDS_WITH', 'endswith'); * OP_IS_EMPTY - comparison operator that determines whether a specified user field is empty */ define('OP_IS_EMPTY', 'isempty'); +/** + * OP_IS_NOT_EMPTY - comparison operator that determines whether a specified user field is not empty + */ +define('OP_IS_NOT_EMPTY', 'isnotempty'); require_once($CFG->libdir.'/completionlib.php'); @@ -374,7 +378,8 @@ abstract class condition_info_base { protected $idfieldname; /** @var array */ protected $usergroupings; - + /** @var array An array of custom profile field ids => to their shortname */ + protected $customprofilefields = null; /** * Constructs with item details. * @@ -583,12 +588,13 @@ abstract class condition_info_base { */ public static function get_condition_user_field_operators() { return array( - OP_CONTAINS => get_string('contains', 'filters'), - OP_DOES_NOT_CONTAIN => get_string('doesnotcontain', 'filters'), - OP_IS_EQUAL_TO => get_string('isequalto', 'filters'), - OP_STARTS_WITH => get_string('startswith', 'filters'), - OP_ENDS_WITH => get_string('endswith', 'filters'), - OP_IS_EMPTY => get_string('isempty', 'filters') + OP_CONTAINS => get_string('contains', 'condition'), + OP_DOES_NOT_CONTAIN => get_string('doesnotcontain', 'condition'), + OP_IS_EQUAL_TO => get_string('isequalto', 'condition'), + OP_STARTS_WITH => get_string('startswith', 'condition'), + OP_ENDS_WITH => get_string('endswith', 'condition'), + OP_IS_EMPTY => get_string('isempty', 'condition'), + OP_IS_NOT_EMPTY => get_string('isnotempty', 'condition'), ); } @@ -801,9 +807,8 @@ abstract class condition_info_base { foreach ($this->item->conditionsfield as $field => $details) { $a = new stdclass; $a->field = $details->fieldname; - $a->operator = get_string($details->operator, 'filters'); $a->value = $details->value; - $information .= get_string('requires_user_field_restriction', 'condition', $a) . ' '; + $information .= get_string('requires_user_field_'.$details->operator, 'condition', $a) . ' '; } } @@ -935,8 +940,8 @@ abstract class condition_info_base { $modinfo = get_fast_modinfo($course); } if (empty($modinfo->cms[$cmid])) { - global $PAGE, $UNITTEST; - if (!empty($UNITTEST) || (isset($PAGE) && strpos($PAGE->pagetype, 'course-view-')===0)) { + global $PAGE; + if (isset($PAGE) && strpos($PAGE->pagetype, 'course-view-')===0) { debugging("Warning: activity {$this->cm->id} '{$this->cm->name}' has condition " . "on deleted activity $cmid (to get rid of this message, edit the named activity)"); } @@ -1002,15 +1007,14 @@ abstract class condition_info_base { // Check if user field condition if (count($this->item->conditionsfield) > 0) { foreach ($this->item->conditionsfield as $field => $details) { - $uservalue = $this->get_cached_user_profile_field($userid, $field, $grabthelot); - if (!$fieldconditionmet = $this->is_field_condition_met($details->operator, $uservalue, $details->value)) { + $uservalue = $this->get_cached_user_profile_field($userid, $field); + if (!$this->is_field_condition_met($details->operator, $uservalue, $details->value)) { // Set available to false $available = false; $a = new stdClass(); $a->field = $details->fieldname; - $a->operator = get_string($details->operator, 'filters'); $a->value = $details->value; - $information .= get_string('requires_user_field_restriction', 'condition', $a) . ' '; + $information .= get_string('requires_user_field_'.$details->operator, 'condition', $a) . ' '; } } } @@ -1185,7 +1189,15 @@ abstract class condition_info_base { * @return boolean */ private function is_field_condition_met($operator, $uservalue, $value) { + if ($uservalue === false) { + // If the user value is false this is an instant fail. + // All user values come from the database as either data or the default. + // They will always be a string. + return false; + } $fieldconditionmet = true; + // Just to be doubly sure it is a string. + $uservalue = (string)$uservalue; switch($operator) { case OP_CONTAINS: // contains $pos = strpos($uservalue, $value); @@ -1224,6 +1236,11 @@ abstract class condition_info_base { $fieldconditionmet = false; } break; + case OP_IS_NOT_EMPTY: // is not empty + if (empty($uservalue)) { + $fieldconditionmet = false; + } + break; } return $fieldconditionmet; } @@ -1233,71 +1250,94 @@ abstract class condition_info_base { * * @param int $userid set if requesting grade for a different user (does not use cache) * @param int $fieldid the user profile field id - * @param bool $grabthelot If true, grabs all the user profile fields for current user on this course, so that later ones come from cache * @return string the user value, or false if user does not have a user field value yet */ - private function get_cached_user_profile_field($userid, $fieldid, $grabthelot) { - global $USER, $DB, $SESSION; - // Check if the field is a custom profile field - $iscustomprofilefield = is_numeric($fieldid) ? true : false; - if ($userid == 0 || $userid == $USER->id) { - if ($iscustomprofilefield) { - // For current user, go via cache in session - if (empty($SESSION->userfieldcache) || $SESSION->userfieldcacheuserid != $USER->id) { - $SESSION->userfieldcache = array(); - $SESSION->userfieldcacheuserid = $USER->id; - } - if (!array_key_exists($fieldid, $SESSION->userfieldcache)) { - if ($grabthelot) { - // Get all custom profile field values for user - $sql = "SELECT uf.id, ud.data - FROM {user_info_field} uf - LEFT JOIN {user_info_data} ud ON uf.id = ud.fieldid - WHERE ud.userid = :userid"; - if ($records = $DB->get_records_sql($sql, array('userid' => $USER->id))) { - foreach ($records as $r) { - $SESSION->userfieldcache[$r->id] = $r->data; - } - } - } else { - // Just get specified user field - $sql = "SELECT ud.data - FROM {user_info_data} ud - INNER JOIN {user_info_field} uf ON ud.fieldid = uf.id - WHERE uf.id = :fieldid - AND ud.userid = :userid"; - if ($record = $DB->get_record_sql($sql, array('fieldid' => $fieldid, 'userid' => $USER->id))) { - $field = $record->data; - } else { - $field = false; - } - $SESSION->userfieldcache[$fieldid] = $field; - } - } - if (!empty($SESSION->userfieldcache[$fieldid])) { - return $SESSION->userfieldcache[$fieldid]; - } else { - return false; - } - } else { - return $USER->$fieldid; - } - } else { - if ($iscustomprofilefield) { - $sql = "SELECT ud.data - FROM {user_info_data} ud - INNER JOIN {user_info_field} uf ON ud.fieldid = uf.id - WHERE uf.id = :fieldid - AND ud.userid = :userid"; - if ($record = $DB->get_record_sql($sql, array('fieldid' => $fieldid, 'userid' => $userid))) { - return $record->data; - } - } else { - return $DB->get_field('user', $fieldid, array('id' => $userid), MUST_EXIST); - } - // If it reaches here, then no matches found + private function get_cached_user_profile_field($userid, $fieldid) { + global $USER, $DB, $CFG; + + if ($userid === 0) { + // Map out userid = 0 to the current user + $userid = $USER->id; + } + $iscurrentuser = $USER->id == $userid; + + if (isguestuser($userid)) { + // Must be logged in and can't be the guest. (this should never happen anyway) return false; } + + // Custom profile fields will be numeric, there are no numeric standard profile fields so this is not a problem. + $iscustomprofilefield = is_numeric($fieldid); + if ($iscustomprofilefield) { + // As its a custom profile field we need to map the id back to the actual field. + // We'll also preload all of the other custom profile fields just in case and ensure we have the + // default value available as well. + if ($this->customprofilefields === null) { + $this->customprofilefields = $DB->get_records('user_info_field', null, 'sortorder ASC, id ASC', 'id, shortname, defaultdata'); + } + if (!array_key_exists($fieldid, $this->customprofilefields)) { + // No such field exists. + // This shouldn't normally happen but occur if things go wrong when deleting a custom profile field + // or when restoring a backup of a course with user profile field conditions. + return false; + } + $field = $this->customprofilefields[$fieldid]->shortname; + } else { + $field = $fieldid; + } + + // If its the current user than most likely we will be able to get this information from $USER. + // If its a regular profile field then it should already be available, if not then we have a mega problem. + // If its a custom profile field then it should be available but may not be. If it is then we use the value + // available, otherwise we load all custom profile fields into a temp object and refer to that. + // Noting its not going be great for performance if we have to use the temp object as it involves loading the + // custom profile field API and classes. + if ($iscurrentuser) { + if (!$iscustomprofilefield) { + if (property_exists($USER, $field)) { + return $USER->{$field}; + } else { + // Unknown user field. This should not happen. + throw new coding_exception('Requested user profile field does not exist'); + } + } + // Checking if the custom profile fields are already available. + if (!isset($USER->profile)) { + // Drat! they're not. We need to use a temp object and load them. + // We don't use $USER as the profile fields are loaded into the object. + $user = new stdClass; + $user->id = $USER->id; + // This should ALWAYS be set, but just in case we check. + require_once($CFG->dirroot.'/user/profile/lib.php'); + profile_load_custom_fields($user); + if (array_key_exists($field, $user->profile)) { + return $user->profile[$field]; + } + } else if (array_key_exists($field, $USER->profile)) { + // Hurrah they're available, this is easy. + return $USER->profile[$field]; + } + // The profile field doesn't exist. + return false; + } else { + // Loading for another user. + if ($iscustomprofilefield) { + // Fetch the data for the field. Noting we keep this query simple so that Database caching takes care of performance + // for us (this will likely be hit again). + // We are able to do this because we've already pre-loaded the custom fields. + $data = $DB->get_field('user_info_data', 'data', array('userid' => $userid, 'fieldid' => $fieldid), IGNORE_MISSING); + // If we have data return that, otherwise return the default. + if ($data !== false) { + return $data; + } else { + return $this->customprofilefields[$field]->defaultdata; + } + } else { + // Its a standard field, retrieve it from the user. + return $DB->get_field('user', $field, array('id' => $userid), MUST_EXIST); + } + } + return false; } /** diff --git a/lib/cronlib.php b/lib/cronlib.php index 7155373dfa8..8535689effe 100644 --- a/lib/cronlib.php +++ b/lib/cronlib.php @@ -318,7 +318,7 @@ function cron_run() { if ($CFG->enablecompletion) { // Completion cron mtrace('Starting the completion cron...'); - require_once($CFG->libdir . '/completion/cron.php'); + require_once($CFG->dirroot.'/completion/cron.php'); completion_cron(); mtrace('done'); } diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php index 060fc002c00..24d6120482f 100644 --- a/lib/db/upgrade.php +++ b/lib/db/upgrade.php @@ -405,7 +405,7 @@ function xmldb_main_upgrade($oldversion) { } if ($oldversion < 2012042300.02) { - require_once($CFG->libdir . '/completion/completion_criteria.php'); + require_once($CFG->dirroot.'/completion/criteria/completion_criteria.php'); // Delete orphaned criteria which were left when modules were removed if ($DB->get_dbfamily() === 'mysql') { $sql = "DELETE cc FROM {course_completion_criteria} cc @@ -1045,6 +1045,29 @@ function xmldb_main_upgrade($oldversion) { upgrade_main_savepoint(true, 2012070600.11); } + if ($oldversion < 2012071900.01) { + // Cleanup after simpeltests tool + capabilities_cleanup('tool_unittest'); + unset_all_config_for_plugin('tool_unittest'); + + upgrade_main_savepoint(true, 2012071900.01); + } + + if ($oldversion < 2012072400.00) { + // Remove obsolete xhtml strict setting - use THEME->doctype in theme config if necessary, + // see theme_config->doctype in lib/outputlib.php for more details. + unset_config('xmlstrictheaders'); + upgrade_main_savepoint(true, 2012072400.00); + } + + if ($oldversion < 2012072401.00) { + + // Saves orphaned questions from the Dark Side + upgrade_save_orphaned_questions(); + + // Main savepoint reached + upgrade_main_savepoint(true, 2012072401.00); + } return true; } diff --git a/lib/deprecatedlib.php b/lib/deprecatedlib.php index 714efb884f0..5349be5ec60 100644 --- a/lib/deprecatedlib.php +++ b/lib/deprecatedlib.php @@ -925,20 +925,6 @@ function current_theme() { return $PAGE->theme->name; } -/** - * @todo Remove this deprecated function when no longer used - * @deprecated since Moodle 2.0 - use $PAGE->pagetype instead of the . - * - * @param string $getid used to return $PAGE->pagetype. - * @param string $getclass used to return $PAGE->legacyclass. - */ -function page_id_and_class(&$getid, &$getclass) { - global $PAGE; - debugging('Call to deprecated function page_id_and_class. Please use $PAGE->pagetype instead.', DEBUG_DEVELOPER); - $getid = $PAGE->pagetype; - $getclass = $PAGE->legacyclass; -} - /** * Prints some red text using echo * diff --git a/lib/dml/mysqli_native_moodle_database.php b/lib/dml/mysqli_native_moodle_database.php index b23ea275e0f..38eb523a9b3 100644 --- a/lib/dml/mysqli_native_moodle_database.php +++ b/lib/dml/mysqli_native_moodle_database.php @@ -384,6 +384,7 @@ class mysqli_native_moodle_database extends moodle_database { $errorno = @$this->mysqli->connect_errno; if ($errorno !== 0) { + $this->mysqli = null; throw new dml_connection_exception($dberr); } diff --git a/lib/dtl/database_exporter.php b/lib/dtl/database_exporter.php index bac739403e0..7051c82a4d7 100644 --- a/lib/dtl/database_exporter.php +++ b/lib/dtl/database_exporter.php @@ -1,5 +1,4 @@ . - /** * General database export class * - * @package core - * @subpackage dtl + * @package core_dtl * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -41,16 +38,17 @@ defined('MOODLE_INTERNAL') || die(); * @see export_table_data for the same table. */ abstract class database_exporter { - /** Connection to the source database (a @see moodle_database object). */ + /** @var moodle_database Connection to the source database (a @see moodle_database object). */ protected $mdb; - /** Database manager of the source database (a @see database_manager object). */ + /** @var database_manager Database manager of the source database (a @see database_manager object). */ protected $manager; - /** Source database schema in XMLDB format (a @see xmldb_structure object). */ + /** @var xmldb_structure Source database schema in XMLDB format (a @see xmldb_structure object). */ protected $schema; /** * Boolean flag - whether or not to check that XML database schema matches * the RDBMS database schema before exporting (used by * @see export_database). + * @var bool */ protected $check_schema; @@ -158,5 +156,4 @@ abstract class database_exporter { } $this->finish_database_export(); } - } diff --git a/lib/dtl/database_importer.php b/lib/dtl/database_importer.php index b7f6a2d0311..92b9ff2d221 100644 --- a/lib/dtl/database_importer.php +++ b/lib/dtl/database_importer.php @@ -1,5 +1,4 @@ . - /** * General database importer class * - * @package core - * @subpackage dtl + * @package core_dtl * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -43,23 +40,22 @@ defined('MOODLE_INTERNAL') || die(); * is respected. */ class database_importer { - /** Connection to the target database (a @see moodle_database object). */ + /** @var moodle_database Connection to the target database (a @see moodle_database object). */ protected $mdb; - /** Database manager of the target database (a @see database_manager object). */ + /** @var database_manager Database manager of the target database (a @see database_manager object). */ protected $manager; - /** Target database schema in XMLDB format (a @see xmldb_structure object). */ + /** @var xmldb_structure Target database schema in XMLDB format (a @see xmldb_structure object). */ protected $schema; /** * Boolean flag - whether or not to check that XML database schema matches * the RDBMS database schema before importing (used by * @see begin_database_import). + * @var bool */ protected $check_schema; - /** - * How to use transactions. - */ + /** @var string How to use transactions. */ protected $transactionmode = 'allinone'; - /** Transaction object */ + /** @var moodle_transaction Transaction object */ protected $transaction; /** @@ -105,7 +101,7 @@ class database_importer { global $CFG; if (!$this->mdb->get_tables()) { - // not tables yet, time to create all tables + // No tables present yet, time to create all tables. $this->manager->install_from_xmldb_structure($this->schema); } diff --git a/lib/dtl/database_mover.php b/lib/dtl/database_mover.php index d61d416a992..419080e089e 100644 --- a/lib/dtl/database_mover.php +++ b/lib/dtl/database_mover.php @@ -1,5 +1,4 @@ . - /** * General database mover class * - * @package core - * @subpackage dtl + * @package core_dtl * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -28,33 +25,35 @@ defined('MOODLE_INTERNAL') || die(); class database_mover extends database_exporter { - /** Importer object used to transfer data. */ + /** @var database_importer Importer object used to transfer data. */ protected $importer; - protected $feeback; + /** @var progress_trace Progress tracing object */ + protected $feedback; /** * Object constructor. * - * @param moodle_database $mdb Connection to the source database (a + * @param moodle_database $mdb_source Connection to the source database (a * @see moodle_database object). * @param moodle_database $mdb_target Connection to the target database (a * @see moodle_database object). * @param boolean $check_schema - whether or not to check that XML database * schema matches the RDBMS database schema before exporting (used by + * @param progress_trace $feedback Progress tracing object * @see export_database). */ public function __construct(moodle_database $mdb_source, moodle_database $mdb_target, - $check_schema = true, progress_trace $feeback = null) { - if (empty($feeback)) { - $this->feeback = new null_progress_trace(); + $check_schema = true, progress_trace $feedback = null) { + if (empty($feedback)) { + $this->feedback = new null_progress_trace(); } else { - $this->feeback = $feeback; + $this->feedback = $feedback; } if ($check_schema) { - $this->feeback->output(get_string('checkingsourcetables', 'core_dbtransfer')); + $this->feedback->output(get_string('checkingsourcetables', 'core_dbtransfer')); } parent::__construct($mdb_source, $check_schema); - $this->feeback->output(get_string('creatingtargettables', 'core_dbtransfer')); + $this->feedback->output(get_string('creatingtargettables', 'core_dbtransfer')); $this->importer = new database_importer($mdb_target, $check_schema); } @@ -70,12 +69,13 @@ class database_mover extends database_exporter { * Callback function. Calls importer's begin_database_import callback method. * * @param float $version the version of the system which generating the data + * @param string $release moodle release info * @param string $timestamp the timestamp of the data (in ISO 8601) format. * @param string $description a user description of the data. * @return void */ public function begin_database_export($version, $release, $timestamp, $description) { - $this->feeback->output(get_string('copyingtables', 'core_dbtransfer')); + $this->feedback->output(get_string('copyingtables', 'core_dbtransfer')); $this->importer->begin_database_import($version, $timestamp, $description); } @@ -86,7 +86,7 @@ class database_mover extends database_exporter { * @return void */ public function begin_table_export(xmldb_table $table) { - $this->feeback->output(get_string('copyingtable', 'core_dbtransfer', $table->getName()), 1); + $this->feedback->output(get_string('copyingtable', 'core_dbtransfer', $table->getName()), 1); $this->importer->begin_table_import($table->getName(), $table->getHash()); } @@ -108,7 +108,7 @@ class database_mover extends database_exporter { * @return void */ public function finish_table_export(xmldb_table $table) { - $this->feeback->output(get_string('done', 'core_dbtransfer', $table->getName()), 2); + $this->feedback->output(get_string('done', 'core_dbtransfer', $table->getName()), 2); $this->importer->finish_table_import($table->getName()); } diff --git a/lib/dtl/file_xml_database_exporter.php b/lib/dtl/file_xml_database_exporter.php index 9f93cb3f845..498609f3d30 100644 --- a/lib/dtl/file_xml_database_exporter.php +++ b/lib/dtl/file_xml_database_exporter.php @@ -1,5 +1,4 @@ . - /** * XML format exporter class to file storage * - * @package core - * @subpackage dtl + * @package core_dtl * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -31,9 +28,9 @@ defined('MOODLE_INTERNAL') || die(); * XML format exporter class to file storage. */ class file_xml_database_exporter extends xml_database_exporter { - /** Path to the XML data file. */ + /** @var string Path to the XML data file. */ protected $filepath; - /** File descriptor for the output file. */ + /** @var resource File descriptor for the output file. */ protected $file; /** @@ -53,6 +50,7 @@ class file_xml_database_exporter extends xml_database_exporter { /** * Specific output method for the file XML sink. + * @param string $text */ protected function output($text) { fwrite($this->file, $text); diff --git a/lib/dtl/file_xml_database_importer.php b/lib/dtl/file_xml_database_importer.php index a4362f347fe..cf34f3a0a78 100644 --- a/lib/dtl/file_xml_database_importer.php +++ b/lib/dtl/file_xml_database_importer.php @@ -1,5 +1,4 @@ . - /** * XML format importer class from file storage * - * @package core - * @subpackage dtl + * @package core_dtl * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -31,7 +28,7 @@ defined('MOODLE_INTERNAL') || die(); * XML format importer class from file storage. */ class file_xml_database_importer extends xml_database_importer { - /** Path to the XML data file. */ + /** @var string Path to the XML data file. */ protected $filepath; /** diff --git a/lib/dtl/string_xml_database_exporter.php b/lib/dtl/string_xml_database_exporter.php index 85ce03027c6..cc2dc589019 100644 --- a/lib/dtl/string_xml_database_exporter.php +++ b/lib/dtl/string_xml_database_exporter.php @@ -1,5 +1,4 @@ . - /** * XML format exporter class to memory storage * - * @package core - * @subpackage dtl + * @package core_dtl * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -31,11 +28,12 @@ defined('MOODLE_INTERNAL') || die(); * XML format exporter class to memory storage (i.e. a string). */ class string_xml_database_exporter extends xml_database_exporter { - /** String with XML data. */ + /** @var string String with XML data. */ protected $data; /** * Specific output method for the memory XML sink. + * @param string $text */ protected function output($text) { $this->data .= $text; diff --git a/lib/dtl/string_xml_database_importer.php b/lib/dtl/string_xml_database_importer.php index fc80593361e..94095e94125 100644 --- a/lib/dtl/string_xml_database_importer.php +++ b/lib/dtl/string_xml_database_importer.php @@ -1,5 +1,4 @@ . - /** * XML format importer class from memory storage * - * @package core - * @subpackage dtl + * @package core_dtl * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -31,13 +28,13 @@ defined('MOODLE_INTERNAL') || die(); * XML format importer class from memory storage (i.e. string). */ class string_xml_database_importer extends xml_database_importer { - /** String with XML data. */ + /** @var string String with XML data. */ protected $data; /** * Object constructor. * - * @param string data - string with XML data + * @param string $data - string with XML data * @param moodle_database $mdb Connection to the target database * @see xml_database_importer::__construct() * @param boolean $check_schema - whether or not to check that XML database diff --git a/lib/dtl/xml_database_exporter.php b/lib/dtl/xml_database_exporter.php index ae76a7abe7e..374a735c0b5 100644 --- a/lib/dtl/xml_database_exporter.php +++ b/lib/dtl/xml_database_exporter.php @@ -1,5 +1,4 @@ . - /** * XML format exporter class * - * @package core - * @subpackage dtl + * @package core_dtl * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -51,7 +48,7 @@ abstract class xml_database_exporter extends database_exporter { public function begin_database_export($version, $release, $timestamp, $description) { $this->output(''); //TODO add xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and schema information - $this->output(''); + $this->output(''); } /** @@ -93,7 +90,7 @@ abstract class xml_database_exporter extends database_exporter { if (is_null($value)) { $this->output(''); } else { - $this->output(''.htmlspecialchars($value, ENT_NOQUOTES).''); + $this->output(''.htmlspecialchars($value, ENT_NOQUOTES, 'UTF-8').''); } } $this->output(''); diff --git a/lib/dtl/xml_database_importer.php b/lib/dtl/xml_database_importer.php index 24ca87ab9a6..da522dd13af 100644 --- a/lib/dtl/xml_database_importer.php +++ b/lib/dtl/xml_database_importer.php @@ -1,5 +1,4 @@ . - /** * XML format importer class * - * @package core - * @subpackage dtl + * @package core_dtl * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -150,9 +147,9 @@ abstract class xml_database_importer extends database_importer { * @param string $data character data to be processed * @return void */ - protected function cdata($parser, $cdata) { + protected function cdata($parser, $data) { if (isset($this->current_field)) { - $this->current_data .= $cdata; + $this->current_data .= $data; } } } diff --git a/lib/editor/tinymce/lib.php b/lib/editor/tinymce/lib.php index 3fca21ed0a8..a7404834068 100644 --- a/lib/editor/tinymce/lib.php +++ b/lib/editor/tinymce/lib.php @@ -155,7 +155,7 @@ class tinymce_texteditor extends texteditor { 'min_height' => 30, 'theme_advanced_toolbar_location' => "top", 'theme_advanced_statusbar_location' => "bottom", - 'spellchecker_rpc_url' => $CFG->wwwroot."/lib/editor/tinymce/tiny_mce/$this->version/plugins/spellchecker/rpc.php", + 'spellchecker_rpc_url' => $CFG->httpswwwroot."/lib/editor/tinymce/tiny_mce/$this->version/plugins/spellchecker/rpc.php", 'spellchecker_languages' => $spelllanguagelist ); @@ -172,7 +172,7 @@ class tinymce_texteditor extends texteditor { $params['moodleemoticon_emoticons'] = json_encode($imgs); } - if (empty($CFG->xmlstrictheaders) and (!empty($options['legacy']) or !empty($options['noclean']) or !empty($options['trusted']))) { + if (!empty($options['legacy']) or !empty($options['noclean']) or !empty($options['trusted'])) { // now deal somehow with non-standard tags, people scream when we do not make moodle code xtml strict, // but they scream even more when we strip all tags that are not strict :-( $params['valid_elements'] = 'script[src|type],*[*]'; // for some reason the *[*] does not inlcude javascript src attribute MDL-25836 diff --git a/lib/form/advcheckbox.php b/lib/form/advcheckbox.php index f4c165bfe10..26ae788005f 100644 --- a/lib/form/advcheckbox.php +++ b/lib/form/advcheckbox.php @@ -84,19 +84,6 @@ class MoodleQuickForm_advcheckbox extends HTML_QuickForm_advcheckbox{ parent::HTML_QuickForm_advcheckbox($elementName, $elementLabel, $text, $attributes, $values); } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function (optional)function name get help html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/button.php b/lib/form/button.php index f37baf66ff3..bfa9615c142 100644 --- a/lib/form/button.php +++ b/lib/form/button.php @@ -54,19 +54,6 @@ class MoodleQuickForm_button extends HTML_QuickForm_button parent::HTML_QuickForm_button($elementName, $value, $attributes); } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/checkbox.php b/lib/form/checkbox.php index c578decd887..37397da5189 100644 --- a/lib/form/checkbox.php +++ b/lib/form/checkbox.php @@ -56,19 +56,6 @@ class MoodleQuickForm_checkbox extends HTML_QuickForm_checkbox{ parent::HTML_QuickForm_checkbox($elementName, $elementLabel, $text, $attributes); } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/dndupload.js b/lib/form/dndupload.js index 53018b9f08e..bbadd5c03f6 100644 --- a/lib/form/dndupload.js +++ b/lib/form/dndupload.js @@ -165,11 +165,22 @@ M.form_dndupload.init = function(Y, options) { this.Y.on('dragleave', this.drag_leave_page, 'body', this); }, + /** + * Check if the filemanager / filepicker is disabled + * @return bool - true if disabled + */ + is_disabled: function() { + return (this.container.ancestor('.fitem.disabled') != null); + }, + /** * Show the 'drop files here' message when file(s) are dragged * onto the page */ drag_enter_page: function(e) { + if (this.is_disabled()) { + return false; + } if (!this.has_files(e)) { return false; } @@ -210,6 +221,9 @@ M.form_dndupload.init = function(Y, options) { * @return boolean true if a valid file drag event */ check_drag: function(e) { + if (this.is_disabled()) { + return false; + } if (!this.has_files(e)) { return false; } diff --git a/lib/form/duration.php b/lib/form/duration.php index 06cd85ad329..9f1b9669dfa 100644 --- a/lib/form/duration.php +++ b/lib/form/duration.php @@ -188,7 +188,7 @@ class MoodleQuickForm_duration extends MoodleQuickForm_group { if ($arg[2]['optional']) { $caller->disabledIf($arg[0], $arg[0] . '[enabled]'); } - $caller->setType($arg[0] . '[number]', PARAM_NUMBER); + $caller->setType($arg[0] . '[number]', PARAM_FLOAT); return parent::onQuickFormEvent($event, $arg, $caller); break; diff --git a/lib/form/editor.php b/lib/form/editor.php index 0f054a52c1b..5a919fb3715 100644 --- a/lib/form/editor.php +++ b/lib/form/editor.php @@ -208,10 +208,11 @@ class MoodleQuickForm_editor extends HTML_QuickForm_element { * @param mixed $_helpbuttonargs arguments to create help button * @param string $function name of the callback function * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() + * @todo MDL-34508 this api will be removed. + * @see MoodleQuickForm::addHelpButton() */ function setHelpButton($_helpbuttonargs, $function='_helpbutton') { + debugging('setHelpButton() is deprecated, please use $mform->addHelpButton() instead'); if (!is_array($_helpbuttonargs)) { $_helpbuttonargs = array($_helpbuttonargs); } else { diff --git a/lib/form/file.php b/lib/form/file.php deleted file mode 100644 index 259881b5042..00000000000 --- a/lib/form/file.php +++ /dev/null @@ -1,109 +0,0 @@ -. - - -/** - * File type form element - * - * Contains HTML class for a file type form element - * - * @package core_form - * @copyright 2007 Jamie Pratt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -require_once('HTML/QuickForm/file.php'); - -/** - * file element - * - * HTML class for a form element to upload a file - * - * @package core_form - * @deprecated since Moodle 2.0 Please do not use this form element. - * @todo MDL-31294 remove this element - * @see MoodleQuickForm_filepicker - * @see MoodleQuickForm_filemanager - * @copyright 2007 Jamie Pratt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class MoodleQuickForm_file extends HTML_QuickForm_file{ - /** @var string html for help button, if empty then no help */ - var $_helpbutton=''; - - /** - * Constructor - * - * @param string $elementName (optional) name of the editor - * @param string $elementLabel (optional) editor label - * @param array $attributes (optional) Either a typical HTML attribute string - * or an associative array - */ - function MoodleQuickForm_file($elementName=null, $elementLabel=null, $attributes=null) { - debugging('file forms element is deprecated, please use new filepicker instead'); - parent::HTML_QuickForm_file($elementName, $elementLabel, $attributes); - } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** - * set html for help button - */ - function getHelpButton(){ - return $this->_helpbutton; - } - - /** - * Override createElement event to add max files - * - * @param string $event Name of event - * @param mixed $arg event arguments - * @param object $caller calling object - * @return bool - */ - function onQuickFormEvent($event, $arg, &$caller) - { - if ($event == 'createElement') { - $className = get_class($this); - $this->$className($arg[0], $arg[1].' ('.get_string('maxsize', '', display_size($caller->getMaxFileSize())).')', $arg[2]); - return true; - } - return parent::onQuickFormEvent($event, $arg, $caller); - } - - /** - * Slightly different container template when frozen. - * - * @return string - */ - function getElementTemplateType(){ - if ($this->_flagFrozen){ - return 'static'; - } else { - return 'default'; - } - } - -} \ No newline at end of file diff --git a/lib/form/filemanager.js b/lib/form/filemanager.js index 164c6834a4b..cbd528a71d5 100644 --- a/lib/form/filemanager.js +++ b/lib/form/filemanager.js @@ -255,6 +255,9 @@ M.form_filemanager.init = function(Y, options) { this.msg_dlg_node.one('.fp-msg-text').setContent(msg); this.msg_dlg.show(); }, + is_disabled: function() { + return this.filemanager.ancestor('.fitem.disabled') != null; + }, setup_buttons: function() { var button_download = this.filemanager.one('.fp-btn-download'); var button_create = this.filemanager.one('.fp-btn-mkdir'); @@ -272,6 +275,9 @@ M.form_filemanager.init = function(Y, options) { if (this.options.subdirs) { button_create.on('click',function(e) { e.preventDefault(); + if (this.is_disabled()) { + return; + } var scope = this; // a function used to perform an ajax request var perform_action = function(e) { @@ -325,6 +331,9 @@ M.form_filemanager.init = function(Y, options) { // setup 'download this folder' button button_download.on('click',function(e) { e.preventDefault(); + if (this.is_disabled()) { + return; + } var scope = this; // perform downloaddir ajax request this.request({ @@ -351,7 +360,7 @@ M.form_filemanager.init = function(Y, options) { on('click', function(e) { e.preventDefault(); var viewbar = this.filemanager.one('.fp-viewbar') - if (!viewbar || !viewbar.hasClass('disabled')) { + if (!this.is_disabled() && (!viewbar || !viewbar.hasClass('disabled'))) { this.filemanager.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked') if (e.currentTarget.hasClass('fp-vb-tree')) { this.viewmode = 2; @@ -369,6 +378,9 @@ M.form_filemanager.init = function(Y, options) { show_filepicker: function (e) { // if maxfiles == -1, the no limit e.preventDefault(); + if (this.is_disabled()) { + return; + } var options = this.filepicker_options; options.formcallback = this.filepicker_callback; // XXX: magic here, to let filepicker use filemanager scope @@ -400,7 +412,9 @@ M.form_filemanager.init = function(Y, options) { el.one('.fp-path-folder-name').setContent(p[i].name). on('click', function(e, path) { e.preventDefault(); - this.refresh(path); + if (!this.is_disabled()) { + this.refresh(path); + } }, this, p[i].path); } this.pathbar.removeClass('empty'); @@ -873,6 +887,9 @@ M.form_filemanager.init = function(Y, options) { return node.filepath; }, select_file: function(node) { + if (this.is_disabled()) { + return; + } var selectnode = this.selectnode; selectnode.removeClass('loading').removeClass('fp-folder'). removeClass('fp-file').removeClass('fp-zip').removeClass('fp-cansetmain'); diff --git a/lib/form/filemanager.php b/lib/form/filemanager.php index f6d968d2841..82f9090131b 100644 --- a/lib/form/filemanager.php +++ b/lib/form/filemanager.php @@ -169,19 +169,6 @@ class MoodleQuickForm_filemanager extends HTML_QuickForm_element { $this->_options['maxfiles'] = $num; } - /** - * Sets help button for filemanager - * - * @param mixed $helpbuttonargs arguments to create help button - * @param string $function name of the callback function - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * Returns html for help button. * diff --git a/lib/form/filepicker.js b/lib/form/filepicker.js index e372a23c086..b2811a25dbc 100644 --- a/lib/form/filepicker.js +++ b/lib/form/filepicker.js @@ -32,7 +32,9 @@ M.form_filepicker.init = function(Y, options) { } Y.on('click', function(e, client_id) { e.preventDefault(); - M.core_filepicker.instances[client_id].show(); + if (this.ancestor('.fitem.disabled') == null) { + M.core_filepicker.instances[client_id].show(); + } }, '#filepicker-button-'+options.client_id, null, options.client_id); var item = document.getElementById('nonjs-filepicker-'+options.client_id); diff --git a/lib/form/filepicker.php b/lib/form/filepicker.php index 58253bbe6c9..fb5e0f36036 100644 --- a/lib/form/filepicker.php +++ b/lib/form/filepicker.php @@ -84,19 +84,6 @@ class MoodleQuickForm_filepicker extends HTML_QuickForm_input { parent::HTML_QuickForm_input($elementName, $elementLabel, $attributes); } - /** - * Sets help button for filepicker - * - * @param mixed $helpbuttonargs arguments to create help button - * @param string $function name of the callback function - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton') { - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * Returns html for help button. * diff --git a/lib/form/form.js b/lib/form/form.js index 938fab6be66..b49d76a0437 100644 --- a/lib/form/form.js +++ b/lib/form/form.js @@ -207,16 +207,14 @@ M.form.initFormDependencies = function(Y, formid, dependencies) { this.removeAttribute('disabled'); } - // Extra code to disable a filepicker - if (this.getAttribute('class') == 'filepickerhidden'){ - var pickerbuttons = form.elementsByName(name + 'choose'); - pickerbuttons.each(function(){ - if (disabled){ - this.setAttribute('disabled','disabled'); - } else { - this.removeAttribute('disabled'); - } - }); + // Extra code to disable filepicker or filemanager form elements + var fitem = this.ancestor('.fitem'); + if (fitem && (fitem.hasClass('fitem_ffilemanager') || fitem.hasClass('fitem_ffilepicker'))) { + if (disabled){ + fitem.addClass('disabled'); + } else { + fitem.removeClass('disabled'); + } } }) }, diff --git a/lib/form/format.php b/lib/form/format.php deleted file mode 100644 index ef55aae33c5..00000000000 --- a/lib/form/format.php +++ /dev/null @@ -1,59 +0,0 @@ -. - - -/** - * editor format form element - * - * Contains HTML class for a editor format drop down element - * - * @package core_form - * @copyright 2007 Jamie Pratt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ - -global $CFG; -require_once "$CFG->libdir/form/select.php"; - -/** - * editor format form element - * - * HTML class for a editor format drop down element - * - * @package core_form - * @copyright 2007 Jamie Pratt - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - * @deprecated since Moodle 2.0 Please do not use this form element. - * @todo MDL-31294, remove this element - * @see MoodleQuickForm_editor - */ -class MoodleQuickForm_format extends MoodleQuickForm_select{ - - /** - * Class constructor - * - * @param string $elementName Select name attribute - * @param mixed $elementLabel Label(s) for the select - * @param mixed $attributes Either a typical HTML attribute string or an associative array - * @param mixed $useHtmlEditor Either a string returned from can_use_html_editor() or false for no html editor - * default 'detect' tells element to use html editor if it is available. - */ - function MoodleQuickForm_format($elementName=null, $elementLabel=null, $attributes=null, $useHtmlEditor=null) - { - throw new coding_exception('MFORMS: Coding error, text formats are handled only by new editor element.'); - } //end constructor - -} diff --git a/lib/form/grading.php b/lib/form/grading.php index e89460bdda6..00674218849 100644 --- a/lib/form/grading.php +++ b/lib/form/grading.php @@ -89,19 +89,6 @@ class MoodleQuickForm_grading extends HTML_QuickForm_input{ return $this->get_gradinginstance()->render_grading_element($PAGE, $this); } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - public function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/group.php b/lib/form/group.php index 7c734aca2ed..3d95d9f53db 100644 --- a/lib/form/group.php +++ b/lib/form/group.php @@ -57,19 +57,6 @@ class MoodleQuickForm_group extends HTML_QuickForm_group{ /** @var string template type, would cause problems with client side validation so will leave for now */ //var $_elementTemplateType='fieldset'; - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * set html for help button */ diff --git a/lib/form/header.php b/lib/form/header.php index c232d9941cd..36c5a08e6f3 100644 --- a/lib/form/header.php +++ b/lib/form/header.php @@ -63,19 +63,6 @@ class MoodleQuickForm_header extends HTML_QuickForm_header $renderer->renderHeader($this); } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/hidden.php b/lib/form/hidden.php index 02e88f41385..b0e78b4c857 100644 --- a/lib/form/hidden.php +++ b/lib/form/hidden.php @@ -59,11 +59,11 @@ class MoodleQuickForm_hidden extends HTML_QuickForm_hidden{ * @param array $helpbuttonargs array of arguments to make a help button * @param string $function function name to call to get html * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() + * @todo MDL-34508 this api will be removed. + * @see MoodleQuickForm::addHelpButton() */ function setHelpButton($helpbuttonargs, $function='helpbutton'){ - + debugging('setHelpButton() is deprecated, please use $mform->addHelpButton() instead'); } /** diff --git a/lib/form/htmleditor.php b/lib/form/htmleditor.php index 0a8252bb8de..2e79dcc3d97 100644 --- a/lib/form/htmleditor.php +++ b/lib/form/htmleditor.php @@ -85,19 +85,6 @@ class MoodleQuickForm_htmleditor extends MoodleQuickForm_textarea{ editors_head_setup(); } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * Returns the input field in HTML * diff --git a/lib/form/password.php b/lib/form/password.php index c443bad7c2a..4265ec6fa1b 100644 --- a/lib/form/password.php +++ b/lib/form/password.php @@ -51,36 +51,20 @@ class MoodleQuickForm_password extends HTML_QuickForm_password{ */ function MoodleQuickForm_password($elementName=null, $elementLabel=null, $attributes=null) { global $CFG; - if (empty($CFG->xmlstrictheaders)) { - // no standard mform in moodle should allow autocomplete of passwords - // this is valid attribute in html5, sorry, we have to ignore validation errors in legacy xhtml 1.0 - if (empty($attributes)) { - $attributes = array('autocomplete'=>'off'); - } else if (is_array($attributes)) { - $attributes['autocomplete'] = 'off'; - } else { - if (strpos($attributes, 'autocomplete') === false) { - $attributes .= ' autocomplete="off" '; - } + // no standard mform in moodle should allow autocomplete of passwords + if (empty($attributes)) { + $attributes = array('autocomplete'=>'off'); + } else if (is_array($attributes)) { + $attributes['autocomplete'] = 'off'; + } else { + if (strpos($attributes, 'autocomplete') === false) { + $attributes .= ' autocomplete="off" '; } } parent::HTML_QuickForm_password($elementName, $elementLabel, $attributes); } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/passwordunmask.php b/lib/form/passwordunmask.php index e14eb6cb38b..bd256fcf123 100644 --- a/lib/form/passwordunmask.php +++ b/lib/form/passwordunmask.php @@ -53,19 +53,17 @@ class MoodleQuickForm_passwordunmask extends MoodleQuickForm_password { */ function MoodleQuickForm_passwordunmask($elementName=null, $elementLabel=null, $attributes=null) { global $CFG; - if (empty($CFG->xmlstrictheaders)) { - // no standard mform in moodle should allow autocomplete of passwords - // this is valid attribute in html5, sorry, we have to ignore validation errors in legacy xhtml 1.0 - if (empty($attributes)) { - $attributes = array('autocomplete'=>'off'); - } else if (is_array($attributes)) { - $attributes['autocomplete'] = 'off'; - } else { - if (strpos($attributes, 'autocomplete') === false) { - $attributes .= ' autocomplete="off" '; - } + // no standard mform in moodle should allow autocomplete of passwords + if (empty($attributes)) { + $attributes = array('autocomplete'=>'off'); + } else if (is_array($attributes)) { + $attributes['autocomplete'] = 'off'; + } else { + if (strpos($attributes, 'autocomplete') === false) { + $attributes .= ' autocomplete="off" '; } } + parent::MoodleQuickForm_password($elementName, $elementLabel, $attributes); } diff --git a/lib/form/radio.php b/lib/form/radio.php index dd97ee9732d..6aaa7809a0b 100644 --- a/lib/form/radio.php +++ b/lib/form/radio.php @@ -55,19 +55,6 @@ class MoodleQuickForm_radio extends HTML_QuickForm_radio{ parent::HTML_QuickForm_radio($elementName, $elementLabel, $text, $value, $attributes); } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/recaptcha.php b/lib/form/recaptcha.php index 35a0c8420ff..ccbd8cced82 100644 --- a/lib/form/recaptcha.php +++ b/lib/form/recaptcha.php @@ -110,19 +110,6 @@ class MoodleQuickForm_recaptcha extends HTML_QuickForm_input { return $html . recaptcha_get_html($CFG->recaptchapublickey, $error, $this->_https); } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/select.php b/lib/form/select.php index 22c8752d1b7..6d17686b146 100644 --- a/lib/form/select.php +++ b/lib/form/select.php @@ -80,19 +80,6 @@ class MoodleQuickForm_select extends HTML_QuickForm_select{ } } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/selectgroups.php b/lib/form/selectgroups.php index 310c49294be..2d5dd635d31 100644 --- a/lib/form/selectgroups.php +++ b/lib/form/selectgroups.php @@ -474,19 +474,6 @@ class MoodleQuickForm_selectgroups extends HTML_QuickForm_element { $this->_hiddenLabel = $hiddenLabel; } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/selectwithlink.php b/lib/form/selectwithlink.php index dc683396556..4377b316464 100644 --- a/lib/form/selectwithlink.php +++ b/lib/form/selectwithlink.php @@ -119,19 +119,6 @@ class MoodleQuickForm_selectwithlink extends HTML_QuickForm_select{ return $retval; } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/static.php b/lib/form/static.php index 825b3e1a56f..716b0268849 100644 --- a/lib/form/static.php +++ b/lib/form/static.php @@ -55,19 +55,6 @@ class MoodleQuickForm_static extends HTML_QuickForm_static{ parent::HTML_QuickForm_static($elementName, $elementLabel, $text); } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/text.php b/lib/form/text.php index 40b1e9658c1..307c4f6c311 100644 --- a/lib/form/text.php +++ b/lib/form/text.php @@ -79,19 +79,6 @@ class MoodleQuickForm_text extends HTML_QuickForm_text{ } } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/textarea.php b/lib/form/textarea.php index d3719b1aa65..f03b610726e 100644 --- a/lib/form/textarea.php +++ b/lib/form/textarea.php @@ -58,19 +58,6 @@ class MoodleQuickForm_textarea extends HTML_QuickForm_textarea{ parent::HTML_QuickForm_textarea($elementName, $elementLabel, $attributes); } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/url.php b/lib/form/url.php index 743a796468e..18c74650ea3 100644 --- a/lib/form/url.php +++ b/lib/form/url.php @@ -127,19 +127,6 @@ EOD; return $str; } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * get html for help button * diff --git a/lib/form/warning.php b/lib/form/warning.php index f67dfc554f0..90865ea1cc2 100644 --- a/lib/form/warning.php +++ b/lib/form/warning.php @@ -62,19 +62,6 @@ class MoodleQuickForm_warning extends HTML_QuickForm_static{ $this->_class = $elementClass; } - /** - * set html for help button - * - * @param array $helpbuttonargs array of arguments to make a help button - * @param string $function function name to call to get html - * @deprecated since Moodle 2.0. Please do not call this function any more. - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::setHelpButton() - */ - function setHelpButton($helpbuttonargs, $function='helpbutton'){ - debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead'); - } - /** * Returns HTML for this form element. * diff --git a/lib/form/yui/passwordunmask/passwordunmask.js b/lib/form/yui/passwordunmask/passwordunmask.js index 2b98922d47c..dfe4de4b472 100644 --- a/lib/form/yui/passwordunmask/passwordunmask.js +++ b/lib/form/yui/passwordunmask/passwordunmask.js @@ -36,4 +36,4 @@ YUI.add('moodle-form-passwordunmask', function(Y) { M.form.passwordunmask = function(params) { return new PASSWORDUNMASK(params); } -}, '@VERSION@', {requires:['base', 'node']}); \ No newline at end of file +}, '@VERSION@', {requires:['base', 'node']}); diff --git a/lib/formslib.php b/lib/formslib.php index 72003796eca..38afe826588 100644 --- a/lib/formslib.php +++ b/lib/formslib.php @@ -158,17 +158,14 @@ abstract class moodleform { */ function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) { global $CFG, $FULLME; - if (empty($CFG->xmlstrictheaders)) { - // no standard mform in moodle should allow autocomplete with the exception of user signup - // this is valid attribute in html5, sorry, we have to ignore validation errors in legacy xhtml 1.0 - if (empty($attributes)) { - $attributes = array('autocomplete'=>'off'); - } else if (is_array($attributes)) { - $attributes['autocomplete'] = 'off'; - } else { - if (strpos($attributes, 'autocomplete') === false) { - $attributes .= ' autocomplete="off" '; - } + // no standard mform in moodle should allow autocomplete with the exception of user signup + if (empty($attributes)) { + $attributes = array('autocomplete'=>'off'); + } else if (is_array($attributes)) { + $attributes['autocomplete'] = 'off'; + } else { + if (strpos($attributes, 'autocomplete') === false) { + $attributes .= ' autocomplete="off" '; } } @@ -406,6 +403,22 @@ abstract class moodleform { } } } + // Check all the filemanager elements to make sure they do not have too many + // files in them. + foreach ($mform->_elements as $element) { + if ($element->_type == 'filemanager') { + $maxfiles = $element->getMaxfiles(); + if ($maxfiles > 0) { + $draftid = (int)$element->getValue(); + $fs = get_file_storage(); + $context = context_user::instance($USER->id); + $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false); + if (count($files) > $maxfiles) { + $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles); + } + } + } + } if (empty($errors)) { return true; } else { @@ -1529,63 +1542,6 @@ class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless { $this->setDefaults(array($elementName=>$defaultValue)); } - /** - * Add an array of buttons to the form - * - * @param array $buttons An associative array representing help button to attach to - * to the form. keys of array correspond to names of elements in form. - * @param bool $suppresscheck if true then string check will be suppressed - * @param string $function callback function to dispaly help button. - * @deprecated since Moodle 2.0 use addHelpButton() call on each element manually - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::addHelpButton() - */ - function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){ - - debugging('function moodle_form::setHelpButtons() is deprecated'); - //foreach ($buttons as $elementname => $button){ - // $this->setHelpButton($elementname, $button, $suppresscheck, $function); - //} - } - - /** - * Add a help button to element - * - * @param string $elementname name of the element to add the item to - * @param array $buttonargs arguments to pass to function $function - * @param bool $suppresscheck whether to throw an error if the element - * doesn't exist. - * @param string $function - function to generate html from the arguments in $button - * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually - * @todo MDL-31047 this api will be removed. - * @see MoodleQuickForm::addHelpButton() - */ - function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){ - global $OUTPUT; - - debugging('function moodle_form::setHelpButton() is deprecated'); - if ($function !== 'helpbutton') { - //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more'); - } - - $buttonargs = (array)$buttonargs; - - if (array_key_exists($elementname, $this->_elementIndex)) { - //_elements has a numeric index, this code accesses the elements by name - $element = $this->_elements[$this->_elementIndex[$elementname]]; - - $page = isset($buttonargs[0]) ? $buttonargs[0] : null; - $text = isset($buttonargs[1]) ? $buttonargs[1] : null; - $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle'; - $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false; - - $element->_helpbutton = $OUTPUT->old_help_icon($page, $text, $module, $linktext); - - } else if (!$suppresscheck) { - print_error('nonexistentformelements', 'form', '', $elementname); - } - } - /** * Add a help button to element, only one button per element is allowed. * @@ -2562,10 +2518,8 @@ MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/datesel MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector'); MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration'); MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor'); -MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file'); MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager'); MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker'); -MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format'); MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading'); MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group'); MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header'); diff --git a/lib/grade/grade_category.php b/lib/grade/grade_category.php index ca67450c4ab..10656f95c82 100644 --- a/lib/grade/grade_category.php +++ b/lib/grade/grade_category.php @@ -878,22 +878,66 @@ class grade_category extends grade_object { asort($grade_values, SORT_NUMERIC); $dropped = 0; - foreach ($grade_values as $itemid=>$value) { + // If we have fewer grade items available to drop than $this->droplow, use this flag to escape the loop + // May occur because of "extra credit" or if droplow is higher than the number of grade items + $droppedsomething = true; - if ($dropped < $this->droplow) { + while ($dropped < $this->droplow && $droppedsomething) { + $droppedsomething = false; - if ($extraused and $items[$itemid]->aggregationcoef > 0) { - // no drop low for extra credits - - } else { - unset($grade_values[$itemid]); - $dropped++; - } - - } else { - // we have dropped enough + $grade_keys = array_keys($grade_values); + if (count($grade_keys) === 0) { + //We've dropped all grade items break; } + + $originalindex = $founditemid = $foundmax = null; + + // Find the first remaining grade item that is available to be dropped + foreach ($grade_keys as $gradekeyindex=>$gradekey) { + if (!$extraused || $items[$gradekey]->aggregationcoef <= 0) { + // Found a non-extra credit grade item that is eligible to be dropped + $originalindex = $gradekeyindex; + $founditemid = $grade_keys[$originalindex]; + $foundmax = $items[$founditemid]->grademax; + break; + } + } + + if (empty($founditemid)) { + // No grade items available to drop + break; + } + + // Now iterate over the remaining grade items + // We're looking for other grade items with the same grade value but a higher grademax + $i = 1; + while ($originalindex+$i < count($grade_keys)) { + $possibleitemid = $grade_keys[$originalindex+$i]; + if ($grade_values[$founditemid] != $grade_values[$possibleitemid]) { + // The next grade item has a different grade value. Stop looking. + break; + } + + if ($extraused && $items[$possibleitemid]->aggregationcoef > 0) { + // Don't drop extra credit grade items. Continue the search. + continue; + } + + if ($foundmax < $items[$possibleitemid]->grademax) { + // Found a grade item with the same grade value and a higher grademax + $foundmax = $items[$possibleitemid]->grademax; + $founditemid = $possibleitemid; + // Continue searching to see if there is an even higher grademax + } + + $i++; + } + + // Now drop whatever grade item we have found + unset($grade_values[$founditemid]); + $dropped++; + $droppedsomething = true; } } else if (!empty($this->keephigh)) { diff --git a/lib/grade/tests/grade_category_test.php b/lib/grade/tests/grade_category_test.php index 102ef8625c6..727e69867f0 100644 --- a/lib/grade/tests/grade_category_test.php +++ b/lib/grade/tests/grade_category_test.php @@ -406,6 +406,7 @@ class grade_category_testcase extends grade_base_testcase { $items[$this->grade_items[2]->id] = new grade_item($this->grade_items[2], false); $items[$this->grade_items[4]->id] = new grade_item($this->grade_items[4], false); + // Test excluding the lowest 2 out of 4 grades from aggregation with no 0 grades $category = new grade_category(); $category->droplow = 2; $grades = array($this->grade_items[0]->id=>5.374, @@ -417,6 +418,7 @@ class grade_category_testcase extends grade_base_testcase { $this->assertEquals($grades[$this->grade_items[1]->id], 9.4743); $this->assertEquals($grades[$this->grade_items[4]->id], 7.3754); + // Test aggregating only the highest 1 out of 4 grades $category = new grade_category(); $category->keephigh = 1; $category->droplow = 0; @@ -429,25 +431,28 @@ class grade_category_testcase extends grade_base_testcase { $grade = reset($grades); $this->assertEquals(9.4743, $grade); + // Test excluding the lowest 2 out of 4 grades from aggregation with no 0 grades + // An extra credit grade item should be kept even if droplow means it would otherwise be excluded $category = new grade_category(); $category->droplow = 2; $category->aggregation = GRADE_AGGREGATE_SUM; - $items[$this->grade_items[2]->id]->aggregationcoef = 1; + $items[$this->grade_items[2]->id]->aggregationcoef = 1; // Mark grade item 2 as "extra credit" $grades = array($this->grade_items[0]->id=>5.374, $this->grade_items[1]->id=>9.4743, $this->grade_items[2]->id=>2.5474, $this->grade_items[4]->id=>7.3754); - $category->apply_limit_rules($grades, $items); $this->assertEquals(count($grades), 2); $this->assertEquals($grades[$this->grade_items[1]->id], 9.4743); $this->assertEquals($grades[$this->grade_items[2]->id], 2.5474); + // Test only aggregating the highest 1 out of 4 grades + // An extra credit grade item is retained in addition to the highest grade $category = new grade_category(); $category->keephigh = 1; $category->droplow = 0; $category->aggregation = GRADE_AGGREGATE_SUM; - $items[$this->grade_items[2]->id]->aggregationcoef = 1; + $items[$this->grade_items[2]->id]->aggregationcoef = 1; // Mark grade item 2 as "extra credit" $grades = array($this->grade_items[0]->id=>5.374, $this->grade_items[1]->id=>9.4743, $this->grade_items[2]->id=>2.5474, @@ -456,6 +461,61 @@ class grade_category_testcase extends grade_base_testcase { $this->assertEquals(count($grades), 2); $this->assertEquals($grades[$this->grade_items[1]->id], 9.4743); $this->assertEquals($grades[$this->grade_items[2]->id], 2.5474); + + + // Test excluding the lowest 1 out of 4 grades from aggregation with two 0 grades + $items[$this->grade_items[2]->id]->aggregationcoef = 0; // Undo marking grade item 2 as "extra credit" + $category = new grade_category(); + $category->droplow = 1; + $category->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2; // simple weighted mean + $grades = array($this->grade_items[0]->id=>0, // 0 out of 110. Should be excluded from aggregation. + $this->grade_items[1]->id=>5, // 5 out of 100 + $this->grade_items[2]->id=>2, // 0 out of 6 + $this->grade_items[4]->id=>0); // 0 out of 100 + $category->apply_limit_rules($grades, $items); + $this->assertEquals(count($grades), 3); + $this->assertEquals($grades[$this->grade_items[1]->id], 5); + $this->assertEquals($grades[$this->grade_items[2]->id], 2); + $this->assertEquals($grades[$this->grade_items[4]->id], 0); + + // Test excluding the lowest 2 out of 4 grades from aggregation with three 0 grades + $category = new grade_category(); + $category->droplow = 2; + $category->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2; // simple weighted mean + $grades = array($this->grade_items[0]->id=>0, // 0 out of 110. Should be excluded from aggregation. + $this->grade_items[1]->id=>5, // 5 out of 100 + $this->grade_items[2]->id=>0, // 0 out of 6 + $this->grade_items[4]->id=>0); // 0 out of 100. Should be excluded from aggregation. + $category->apply_limit_rules($grades, $items); + $this->assertEquals(count($grades), 2); + $this->assertEquals($grades[$this->grade_items[1]->id], 5); + $this->assertEquals($grades[$this->grade_items[2]->id], 0); + + // Test excluding the lowest 5 out of 4 grades from aggregation + // Just to check we handle this sensibly + $category = new grade_category(); + $category->droplow = 5; + $category->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2; // simple weighted mean + $grades = array($this->grade_items[0]->id=>0, // 0 out of 110. Should be excluded from aggregation. + $this->grade_items[1]->id=>5, // 5 out of 100 + $this->grade_items[2]->id=>6, // 6 out of 6 + $this->grade_items[4]->id=>1);// 1 out of 100. Should be excluded from aggregation. + $category->apply_limit_rules($grades, $items); + $this->assertEquals(count($grades), 0); + + // Test excluding the lowest 4 out of 4 grades from aggregation with one marked as extra credit + $category = new grade_category(); + $category->droplow = 4; + $category->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2; // simple weighted mean + $items[$this->grade_items[2]->id]->aggregationcoef = 1; // Mark grade item 2 as "extra credit" + $grades = array($this->grade_items[0]->id=>0, // 0 out of 110. Should be excluded from aggregation. + $this->grade_items[1]->id=>5, // 5 out of 100. Should be excluded from aggregation. + $this->grade_items[2]->id=>6, // 6 out of 6. Extra credit. Should be retained. + $this->grade_items[4]->id=>1);// 1 out of 100. Should be excluded from aggregation. + $category->apply_limit_rules($grades, $items); + $this->assertEquals(count($grades), 1); + $this->assertEquals($grades[$this->grade_items[2]->id], 6); + } /** diff --git a/lib/javascript-static.js b/lib/javascript-static.js index 66af6218bd0..463f8249616 100644 --- a/lib/javascript-static.js +++ b/lib/javascript-static.js @@ -716,7 +716,13 @@ M.util.get_string = function(identifier, component, a) { // creating new instance if YUI is not optimal but it seems to be better way then // require the instance via the function API - note that it is used in rare cases // for debugging only anyway - var Y = new YUI({ debug : true }); + // To ensure we don't kill browser performance if hundreds of get_string requests + // are made we cache the instance we generate within the M.util namespace. + // We don't publicly define the variable so that it doesn't get abused. + if (typeof M.util.get_string_yui_instance === 'undefined') { + M.util.get_string_yui_instance = new YUI({ debug : true }); + } + var Y = M.util.get_string_yui_instance; } if (!M.str.hasOwnProperty(component) || !M.str[component].hasOwnProperty(identifier)) { diff --git a/lib/medialib.php b/lib/medialib.php index 57a9e902bb0..fe28a95e405 100644 --- a/lib/medialib.php +++ b/lib/medialib.php @@ -526,8 +526,6 @@ OET; */ class core_media_player_youtube extends core_media_player_external { protected function embed_external(moodle_url $url, $name, $width, $height, $options) { - global $CFG; - $site = $this->matches[1]; $videoid = $this->matches[3]; @@ -539,27 +537,10 @@ class core_media_player_youtube extends core_media_player_external { self::pick_video_size($width, $height); - if (empty($CFG->xmlstrictheaders)) { - return << OET; - } - - // NOTE: we can not use any link fallback because it breaks built-in - // player on iOS devices. - $output = << - - - - - - -OET; - - return $output; } protected function get_regex() { diff --git a/lib/messagelib.php b/lib/messagelib.php index f4674cec59f..ba05880a4c8 100644 --- a/lib/messagelib.php +++ b/lib/messagelib.php @@ -370,11 +370,12 @@ function message_set_default_message_preference($component, $messagename, $filep * * @see message_get_providers_for_user() * @deprecated since 2.1 - * @todo Remove in 2.2 (MDL-31031) + * @todo Remove in 2.5 (MDL-34454) * @return array An array of message providers */ function message_get_my_providers() { global $USER; + debugging('message_get_my_providers is deprecated please update your code', DEBUG_DEVELOPER); return message_get_providers_for_user($USER->id); } diff --git a/lib/moodlelib.php b/lib/moodlelib.php index b2c6223bb46..29f4362eb23 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -254,28 +254,33 @@ define('PARAM_CLEAN', 'clean'); /** * PARAM_INTEGER - deprecated alias for PARAM_INT + * @deprecated since 2.0 */ define('PARAM_INTEGER', 'int'); /** * PARAM_NUMBER - deprecated alias of PARAM_FLOAT + * @deprecated since 2.0 */ define('PARAM_NUMBER', 'float'); /** * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls * NOTE: originally alias for PARAM_APLHA + * @deprecated since 2.0 */ define('PARAM_ACTION', 'alphanumext'); /** * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc. * NOTE: originally alias for PARAM_APLHA + * @deprecated since 2.0 */ define('PARAM_FORMAT', 'alphanumext'); /** * PARAM_MULTILANG - deprecated alias of PARAM_TEXT. + * @deprecated since 2.0 */ define('PARAM_MULTILANG', 'text'); @@ -765,7 +770,6 @@ function clean_param($param, $type) { return (int)$param; // Convert to integer case PARAM_FLOAT: - case PARAM_NUMBER: return (float)$param; // Convert to float case PARAM_ALPHA: // Remove everything not a-z diff --git a/lib/navigationlib.php b/lib/navigationlib.php index c14929a2796..e6049b824ed 100644 --- a/lib/navigationlib.php +++ b/lib/navigationlib.php @@ -3574,7 +3574,7 @@ class settings_navigation extends navigation_node { // Add the module chooser toggle $modchoosertoggleurl = clone($baseurl); if ($this->page->user_is_editing() && course_ajax_enabled($course)) { - if ($usemodchooser = get_user_preferences('usemodchooser', 1)) { + if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) { $modchoosertogglestring = get_string('modchooserdisable', 'moodle'); $modchoosertoggleurl->param('modchooser', 'off'); } else { diff --git a/lib/outputlib.php b/lib/outputlib.php index 0cf29d8fef8..69c13934e52 100644 --- a/lib/outputlib.php +++ b/lib/outputlib.php @@ -275,6 +275,14 @@ class theme_config { */ public $enablecourseajax = true; + /** + * @var string Determines served document types + * - 'html5' the only officially supported doctype in Moodle + * - 'xhtml5' may be used in development for validation (not intended for production servers!) + * - 'xhtml' XHTML 1.0 Strict for legacy themes only + */ + public $doctype = 'html5'; + //==Following properties are not configurable from theme config.php== /** @@ -390,7 +398,7 @@ class theme_config { $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax', 'supportscssoptimisation', - 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector'); + 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector', 'doctype'); foreach ($config as $key=>$value) { if (in_array($key, $configurable)) { diff --git a/lib/outputrenderers.php b/lib/outputrenderers.php index b2d0e491005..d099429c1d6 100644 --- a/lib/outputrenderers.php +++ b/lib/outputrenderers.php @@ -304,34 +304,22 @@ class core_renderer extends renderer_base { * Get the DOCTYPE declaration that should be used with this page. Designed to * be called in theme layout.php files. * - * @return string the DOCTYPE declaration (and any XML prologue) that should be used. + * @return string the DOCTYPE declaration that should be used. */ public function doctype() { - global $CFG; + if ($this->page->theme->doctype === 'html5') { + $this->contenttype = 'text/html; charset=utf-8'; + return "\n"; - $doctype = '' . "\n"; - $this->contenttype = 'text/html; charset=utf-8'; - - if (empty($CFG->xmlstrictheaders)) { - return $doctype; - } - - // We want to serve the page with an XML content type, to force well-formedness errors to be reported. - $prolog = '' . "\n"; - if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') !== false) { - // Firefox and other browsers that can cope natively with XHTML. + } else if ($this->page->theme->doctype === 'xhtml5') { $this->contenttype = 'application/xhtml+xml; charset=utf-8'; - - } else if (preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) { - // IE can't cope with application/xhtml+xml, but it will cope if we send application/xml with an XSL stylesheet. - $this->contenttype = 'application/xml; charset=utf-8'; - $prolog .= 'httpswwwroot . '/lib/xhtml.xsl"?>' . "\n"; + return "\n"; } else { - $prolog = ''; + // legacy xhtml 1.0 + $this->contenttype = 'text/html; charset=utf-8'; + return ('' . "\n"); } - - return $prolog . $doctype; } /** @@ -341,7 +329,11 @@ class core_renderer extends renderer_base { * @return string HTML fragment. */ public function htmlattributes() { - return get_html_lang(true) . ' xmlns="http://www.w3.org/1999/xhtml"'; + $return = get_html_lang(true); + if ($this->page->theme->doctype !== 'html5') { + $return .= ' xmlns="http://www.w3.org/1999/xhtml"'; + } + return $return; } /** @@ -354,6 +346,12 @@ class core_renderer extends renderer_base { public function standard_head_html() { global $CFG, $SESSION; $output = ''; + if ($this->page->theme->doctype === 'html5' or $this->page->theme->doctype === 'xhtml5') { + // Make sure we set 'X-UA-Compatible' only if script did not request something else (such as MDL-29213). + if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) { + $output .= '' . "\n"; + } + } $output .= '' . "\n"; $output .= '' . "\n"; if (!$this->page->cacheable) { @@ -2050,7 +2048,7 @@ $icon_progress